Create Controller and add Views to another project - asp.net

Visual Studio 2015 + all updates.
Asp .Net Web application (MVC).
I start off by adding a few class libraries and separating the Asp .Net WA into layers i.e. DataAccess, Business Logic and the web project itself.
Once separated I add relevant references and everything is working as I expect it to be (i.e. the application functions as it did before I separated it into layers).
In my BL (Controllers are found here). I don't have the option to Add a Controller, like you would when right clicking the Controllers folder in the default project, so add the below line
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
to the csproj file for my class library and the Add Controller option now appears. Create a controller but throws an error which was due to not having a web.config file - add this file and all works (although it would be nice to have this library working without a web.config file).
The problem I've hit is, when the Controller is created it also adds a View template within the class library but my Views folder is located in my web project.
Have I done this wrong? Is there a workaround so when a controller is created, it also creates the Views into the correct project? Or another approach for this?

This is just a guess, but it seems like you are try to use a UI-based architectural pattern to build your business layer.
Typically, your models, views, and controllers are all maintained in the main web-app project. Any supporting functions (like your BL and DL) are added via class libraries. The Visual Studio MVC templates are built around that concept, which is why you had to manually add support with the GUID - and why it automatically creates the view.
If I may ask, why are you trying to build controllers into your BL? If you are trying to decouple your UI from your server code, perhaps WebAPI would be a better option.
UPDATE - A few helpful links
ProDinner - ASP.NET MVC Sample App
N Layered App with Entity Framework, Autofac, ASP.NET MVC and Unit Testing
Architecture Guide: ASP.NET MVC Framework + N-tier + Entity Framework and Many More

Most of your issues boil down to using the scaffold. The scaffold is great when you're just starting out or for extremely simple projects, but it quickly falls down beyond that. Specifically, adding a controller via scaffold is designed for an MVC project, so it expects to find things you'd find in an MVC project. Additionally, it creates scaffolded views in an appropriate directory in Views because, again, that's what it's designed to do.
The simplest solution, then, is to just not use the scaffolds. A controller is just a class that inherits from Controller. Nothing special there. Then, you can create the views where you want to create them.

Related

Publish Web API controllers in separate files

I have a problem with publishing Web API in Visual Studio.
In VS, when I publish the Web API, it is published as dll's, and when we have several controllers it is going to aggregate those into one dll.
But I have project that can have different controllers, like:
Android.cs
CoWorker.cs
TelegramBot.cs
and when I publish the project, I would like to publish the controllers in separated DLL's, because I should have update the controllers continuously and when I have an error in a specific controller, I can't publish another.
Please help!
What you are looking for will not happen on its own. If you want a plug and play like architecture where you can just publish only a module without re-publishing the whole solution.
To achieve this you need to move your controller(s)/module as a separate project (separate library). One of the useful configuration feature of ASP.NET Web API is that it allows you to define about the assemblies into which it will look to discover your controller types.
This is very useful if you have external assemblies and are not part of the Web API project.
You can implement interface System.Web.Http.Dispatcher.IAssembliesResolver GetAssemblies() or even can extend the DefaultAssembliesResolver as following.
public class CustomAssembliesResolver : DefaultAssembliesResolver
{
public override ICollection<Assembly> GetAssemblies()
{
//Your implementation here
}
}
You can find more details on this on following link.
MSDN
Sample
I think what you're looking for is a MICRO-SERVICE architecture ...
https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/data-driven-crud-microservice
https://github.com/dotnet-architecture/eShopOnContainers
you can use .NET full framework
or the new .NET Core (it depends on what you have to do)

How to add a MVC Account controller to WebApi project in Visual Studio 2013?

I am trying to understand the concept of one asp.net. I did the entire exercise here.
Its easy.
Now trying to understand further, I created a new Asp.Net project and selected Web API template as follows. So we see that MVC and Web API check boxes are selected.
If I observe the project The AccountController is an ApiController and so the views folder does not have any Account and Manage folders as expected.
Now my question is how do I add an Mvc Account controller to the above project? I very well know that if I select MVC in the new project dialog as follows I can get that.
What I want is to add is an MVC account controller along with the views exactly like the following in the Web api project show earlier.
This should be very easy I guess. So could someone please describe some steps? Like for example, which model and context we need to select on add scaffold and then Add Controller dialogs?
In other words I want to understand looking at a controller say AccountController be it Api or Mvc, how do I understand what is the model class and Data context associated with it.
The plenty of scafold templates that exists are very useful to have an application running. Even you can create a new WepApplication project and add the Nuget package AspNet.Identity Sample, wich has a lot of features.
However for your project, I recommend you to start with and Empty Web Api project and then start adding only the stuff that you need. This way you will understand better how your Wep Api works with AspNet Identity (Account Management, External Login Providers like Google or Facebook, ...).
This Step by Step tutorial (and the next series) will guide you in implementing and understanding the Web Api and AspNet Identity starting from an Empty Web Api project.
Hope this helps.

Adding Web API to existing asp.net web forms Application

My team wants to upgrade from WCF to Web API. We have a working asp.net web form application, that we have imported to VS2012 from VS2010. So far so good.
But now as I try to make a separate Web API project, I see that there is no Web API template available. The closest thing that I can find is by creating an MVC 4 application and setting the Project Template as WebAPI. I followed this way and everything falls in perfectly. I have the working API with a sample controller that I can invoke by making calls from the browser.
The only downside to this is that, this particular method brings in its own baggage. The MVC 4 project I created has JQUERY and other libraries included, plus some other folders that I probably don't need. What I want is the Web API structure only - and not the extra baggage.
I tried finding a template using online search but the package I found does not work properly and as very poor rating.
I hope I have illustrated my problem properly. I am looking forward for some feedback now :) Thanks.
In Visual Studio 2013
Right-click on the ASP.NET Web Forms project.
Add -> Add Scaffolded Item... or New Scaffolded Item...
Under Installed/Common/MVC/Web API choose the scaffold type you wish
to use.
Follow the instructions for the scaffold template. For example, when you choose "Web API 2 Controller with read/write actions" or "Web API 2 Controller - Empty", you are prompted for a controller name
You will then need to move the recently created controller into the recently created Controllers folder.
Results
From what I can see, Visual Studio does the following:
"App_Start/WebApiConfig2.cs" is created.
Controllers folder is created.
Web.config is edited to add "handlers" element with content in "system.webServer".
The following references are added:
System.Net.Http
System.Net.Http.Formatting
System.Web.Extensions
System.Web.Http
System.Web.Http.WebHost
packages.config is updated to include:
"Microsoft.AspNet.WebApi"
"Microsoft.AspNet.WebApi.Client"
"Microsoft.AspNet.WebApi.Core"
"Microsoft.AspNet.WebApi.WebHost"
Notes
Subsequently, I recommend following the same steps, starting with right-clicking on the Controllers folder instead of the project. This will put the new controller in the Controllers folder instead of at the root level.
Readme from Visual Studio after following the above steps:
Visual Studio has added the full set of dependencies for ASP.NET Web API 2 to project 'RowersCode.Web'.
The Global.asax.cs file in the project may require additional changes to enable ASP.NET Web API.
Add the following namespace references:
using System.Web.Http;
using System.Web.Routing;
If the code does not already define an Application_Start method, add the following method:
protected void Application_Start()
{
}
Add the following lines to the beginning of the Application_Start method:
GlobalConfiguration.Configure(WebApiConfig2.Register);
After much research I have been able to come up with a solution to this problem. Let me illustrate my solution with respect to the Visual Studio Version.
VS 2012
As I mentioned in the question, there is no definite way to create the Web API project in VS2012. You are gonna have to do it by creating an MVC 4 application and setting the Project Template as WebAPI. Then once you have done this and you have your Web API functional, you can safely delete the extra baggage like the Jquery libraries and other stuff, because these things are absolutely of no use here in your project.
VS 2013
In VS2013 there is however a better approach followed to add and manage the Web API projects. Currently I am using VS2013 for the Web API and all things have fallen into place just as I wanted. Kindly see this link and you will get a better idea
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
I hope this information will help all those new to Web API. Especially for those who want to upgrade to Web API or add Web API to existing projects.

Reusable ASP.NET MVC components in dll like ASP.NET WebControls

I have several websites and these website share several components. It was quite easy with classic ASP.NET WebControls ascx. I created several such controls, put into one dll library and I reference these libraries from these websites via namespace.elements runat=server...
But I don't know how to do it after I have upgraded to ASP.NET MVC. I can put model and cotroller class into dll.
But how should I put and reuse Views into dll?
I suppose that Views are not compiled into dll, if I can change the View without recompiling the dll.
EDITS:
I would prefer some standard solution over third party. The last solution for me is to use StringBuilder instead of ViewEngine.
I've been using Razor Generator for several years to store reusable MVC views and helpers in separate .dll.
Razor Generator "is a Custom Tool for Visual Studio that allows processing Razor files at design time instead of runtime, allowing them to be built into an assembly for simpler reuse and distribution."
Installation instructions
It’s on the VS extension gallery, so install
it from there. It’s called “Razor Generator” (not to be confused with
“Razor Single File Generator for MVC”).
It is quite simple to use:
Usage in an MVC app
Install the 'RazorGenerator.Mvc' package, which registers a special
view engine
Go to an MVC Razor view's property and set the Custom tool to RazorGenerator
Optionally specify a value for Custom Tool Namespace to specify a namespace for the generated file. The project namespace is used by
default.
Optionally specify one of the generators in the first line of your Razor file. A generator declaration line looks like this: #*
Generator: MvcHelper *# . If you don't specify this, a generator is
picked based on convention (e.g. files under Views are treated as
MvcViews)
You'll see a generated .cs file under the .cshtml file, which will be used at runtime instead of the .cshtml file
You can also go to the nuget Package Manager Console and run 'Enable-RazorGenerator' to enable the Custom Tool on all the views.
And to cause all the views to be regenerated, go to the nuget Package Manager Console and run 'Redo-RazorGenerator'. This is
useful when you update the generator package and it needs to
generate different code.
MVC project should be chosen for class library in order to support intellisense and other useful features.
Usage in a View Library
If you need to create a separate library for your precompiled MVC
views, the best approach is to actually create an MVC project for
that library, instead of a library project. You'll never actually run
it as an Mvc app, but the fact that it comes with the right set of
config files allows intellisense and other things to work a lot
better than in a library project.
You can then add a reference to that 'MVC View project' from your real
MVC app.
And note that you need to install the 'RazorGenerator.Mvc' package
into the library, not the main MVC app.
Programming ASP.NET MVC 4 written by Jess Chadwick tells that
In the ASP.NET Web Forms world, you can achieve this by creating user
controls or custom controls that can be compiled into standalone
assemblies. These assemblies can be distributed across projects,
thereby enabling their reuse across projects.
The Web Forms view
engine offers the ViewUserControl class, which can be leveraged to
create such components for the MVC framework. The Razor view engine in
ASP.NET MVC, however, does not offer any such method out of the box.
and suggests using Razor Single File Generator visual studio extension, another one but the similar to Razor Generator approach.

Tool or Standard Procedure to add a different type of Visual Studio Project to an existing one?

I have an existing website coded in ASP.Net 4.0 Webforms, and would like to add an "ASP.Net Dynamic Data Entities Web Application" (project templates of VS2010 to my actual project):
So my question is, what are the steps to "merge" the 2 projects or integrate the "ASP.Net Dynamic Data Entities Web Application" to my actual webforms.
I think I must merge my Global.asax.cs files and web.config file + move rest of the files. Is that correct ?
I already read that post (that may be outdated?):
http://www.hanselman.com/blog/IntegratingASPNETMVC3IntoExistingUpgradedASPNET4WebFormsApplications.aspx
Thanks for your answers :)
(the original title of this post was: “ASP.Net Dynamic Data Entities Web Application” integration with an existing Webforms)
I've read Scott Hanselman's article which you've provided in your question and yes the same technique still applies today, here are a few steps/considerations which should help you along the way:
When you create the new ASP.NET Dynamic Data Entities Web Application make sure that it's the same .NET Framework version as your Web Forms project, to avoid version conflicts.
Remember to add a reference to all the required libraries that you've been using in the Web Forms project.
Now it's safe to copy all the necessary .aspx pages to the new site.
There is some automatically generated code inside the Global.asax of a Dynamic Data project which is used to configure ASP.NET routing, it may be useful later so instead of replacing it with your Global.asax use a tool like WinMerge to merge the two files.

Resources