MVC Console app in VS 2017 - unable to serve razor views - visual-studio

I have created basic MVC application in asp.net core with Visual Studio 2017.
I got an error when trying to render index.cshtml
An error occurred during the compilation of a resource required to process this request. Please review the following specific error details and modify your source code appropriately.
Generated Code
One or more compilation references are missing. Possible causes
include a missing 'preserveCompilationContext' property under
'buildOptions' in the application's project.json.
The type or namespace name 'System' could not be found (are you
missing a using directive or an assembly reference?)
+
using System;
...
My whole console application is as short as it can be:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var host = new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseKestrel()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseMvc();
}
}
public class HomeController : Controller
{
[HttpGet("/")]
public ActionResult Index()
{
ViewBag.Message = "Hello world!";
ViewBag.Time = DateTime.Now;
return View();
}
}
}
Structure of my "project"
View
It's funny because the error tells me that I have to change something in project.json, but since Visual Studio 2017 there is no project.json anymore.
My view is in fact simple static html file and does not require any references to models or anything. But errors are complaining about missing types:
I tried to compare my project to web application template but I havent found what's causing razor views not to build in console application.
What am I missing here?

Try adding
<PropertyGroup>
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
to your csproj. And to avoid such mistakes next time, please use the ASP.NET Core templates you can find when you create a new project. They have the necessary stuff and commonly used packages added to it's csproj.

There is a different SDK to use.
Console Apps use: Microsoft.NET.Sdk
Web Apps use: Microsoft.NET.Sdk.Web
This can be updated in your *.csproj

Related

How to use SignalR with aspnetcore 2.0.0 preview

I am trying to use SignalR with aspnetcore 2.0.0 preview. The preview version is supposed to have support for signalR as per the release notes and I can add references to the "Microsoft.aspnetcoreSignalR" package.
However, I am unable to find the MapSignalR extension method or something like useSignalR() on the IApplicationBuilder.
Googling around for this gives lots of examples of the UseAppBuilder extension method. However, I still get stuck at MapSignalR with the below code:
using Microsoft.AspNetCore.Builder;
using Microsoft.Owin.Mapping;
using Microsoft.Owin.Helpers;
using Microsoft.Owin.Extensions;
using Microsoft.Owin.Builder;
using Owin;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyNamespace
{
using AppFunc = Func<IDictionary<string, object>, Task>;
public static class SignalRExtensions
{
public static IApplicationBuilder UseAppBuilder(this IApplicationBuilder app, Action<IAppBuilder> configure)
{
app.UseOwin(addToPipeline =>
{
addToPipeline(next =>
{
var appBuilder = new AppBuilder();
appBuilder.Properties["builder.DefaultApp"] = next;
configure(appBuilder);
return appBuilder.Build<AppFunc>();
});
});
return app;
}
public static void UseSignalR2(this IApplicationBuilder app)
{
app.UseAppBuilder(appBuilder => appBuilder.MapSignalR());
}
}
}
This is unable to find the MapSignalR extension method. Any thoughts on if I can find this some nuget package that will work with aspnetcore? Or is there a different mechanism to initialize signalR with aspnetcore 2.0.0 preview?
I am using visual studio 2017 preview 15.3 with .Net core 2.0 preview installed.
I basically hada the wrong set of nugget references. If I only have aspnetcore 2.0.0 preview 1 and the corresponding Microsoft.aspnetcore.signalR 1.0.0 preview package, there is already a UseSignalR() method available as an extension method for IApplicationBuilder and we don't need any of the above code.

Referencing PetaPoco from App_Code class (Umbraco 7)

Trying to create a web service to use Petapoco, I have created the following in a cs file in App_code
using System;
using Umbraco.Core;
using Umbraco.Core.Persistence;
namespace utData{
public class MyDB{
public string demo(){
var dataContext = new PetaPoco.Database("umbracoDbDSN");
return "demo - OK";
}
}
}
However, using this from a web service call results in
CS0246: The type or namespace name 'PetaPoco' could not be found (are you missing a using directive or an assembly reference?)
var dataContext = new PetaPoco.Database("umbracoDbDSN");
Any way to fix this?
Umbraco wraps its use of PetaPoco, so if you want "clean" and separate use of PetaPoco, you will need to reference it in your project or in your case (when not compiling) place PetaPoco DLL(s?) in the bin folder.
Or you could google PetaPoco Umbraco and see how PetaPoco is used in Umbraco context. According to http://www.wiliam.com.au/wiliam-blog/using-petapoco-with-umbraco-is-pretty-sweet it goes something like this (for your example):
var db = applicationContext.DatabaseContext.Database;
// or ApplicationContext.Current.DatabaseContext.Database
if (!db.TableExist("blahblah"))
{
db.CreateTable(false);
}

how to use Elmah.Contrib.WebApi 1.0.9?

I am working on WEB API project. I want to implement global error handling and i choose ELMAH for that.
On googling i found i can implement ELMAH in WEB API with Elmah.Contrib.WebApi package.
So i installed the package Elmah.Contrib.WebApi and as written in author's github site i registered it.
so my global.asax looks like following.
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());
GlobalConfiguration.Configuration.MessageHandlers.Add(new MessageLoggingHandler());
}
but it does not seem to work. i also tried to find documentation on how to implement this package in project but could not find it.
can someone help me so i can get work that pacakge?
If you are using Web API 2, you should use the new exception logger:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());
...
}
}
Also shown in this post:
http://blog.elmah.io/logging-to-elmah-io-from-web-api/
(without the elmah.io package if you are using another log store)

Http.EnumRouteContraint must implement System.Web.Routing.IRouteConstraint

I'm using AttributeRouting in my Web API project. I've installed the AttributeRouting for Web API. I want to define an Enum route constraint so I setup my AttributeRoutingHttpConfig config as follows:
using System.Reflection;
using System.Web.Http;
using AttributeRouting.Web.Http.Constraints;
using AttributeRouting.Web.Http.WebHost;
using MyProject.Data.Models;
[assembly: WebActivator.PreApplicationStartMethod(typeof(PhantasyTour.AttributeRoutingHttpConfig), "Start")]
namespace MyProject
{
public static class AttributeRoutingHttpConfig
{
public static void RegisterRoutes(HttpRouteCollection routes)
{
routes.MapHttpAttributeRoutes(
config =>
{
config.AddRoutesFromAssembly(Assembly.GetExecutingAssembly());
config.InlineRouteConstraints.Add("ListType", typeof(EnumRouteConstraint<ListType>));
});
}
public static void Start()
{
RegisterRoutes(GlobalConfiguration.Configuration.Routes);
}
}
}
When I fire up my application I immediately receive the following error:
The constraint "AttributeRouting.Web.Http.Constraints.EnumRouteConstraint`1[[MyProject.Data.Models.ListType, MyProject.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]" must implement System.Web.Routing.IRouteConstraint
I've looked at the source code for the AttributeRouting.Web.Http.Constraints.EnumRouteConstraint and confirmed that it implements IHttpRouteConstraint which presumably is the WebAPI equivalent of IRouteConstraint in the MVC namespace.
Does anyone know what I'm doing wrong and how I can get this working?
UPDATE:
I attempted to create a completely blank Web Application and add only WebAPI and AttributeRouting for WebAPI references. Despite having absolutely no references to MVC assemblies, I still receive the same error message. I did discover however that there is another EnumRouteConstraint found in the AttributeRouting.Web.Constraints namespace which works perfectly. It doesn't appear to be MVC specific since it is located in the Core AttributeRouting assembly. I would love to know why there are two different EnumRouteConstraint classes when only one of them works. But that is a question for another time.
It is interesting that the exception you get refers to the MVC interface from the namespace System.Web.Routing.
I would take it as a clue and look at all the references in your project, any place in the config where MVC Routes and Http Routes could have been mixed up.
If possible and if you have any at all, try removing all references to MVC (or System.Web.Routing for a start), and MVC flavour of attribute routing (if it's a separate dll).

Linq intellisense Missing on EF Object

I'm facing a strange type of issue.
In my VS Solution I have 3 projects.
ASP.Net App
C# Class Library (Used as my DAL and contains a EF .edmx file.
Windows Service App
The ASP.Net App can succesffully access the the EF Model and I can use either classic Linq or Lambda .First() etc. Everything works fine.
On my Windows Service App, I've added a reference to the DAL DLL , but for some reason, the Intellisense does not show up when I type in any code files in the windows service library. Example of my code below :
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace alertservice
{
class AlertPolling
{
dal.applicationEntities ent;
public AlertPolling()
{
ent = new dal.applicationEntities();
ent.Queries. // <--- ZERO INTELLISENSE HAPPENING HERE.
}
public void StartPolling()
{
}
}
}
Thanks guys. I managed to fix the problem by following the comments from flipchart.
I added a reference to System.Data.Entity which fixed it. Intellisense now coming up.

Resources