Where should these classes/methods go? - c#

I have a structure like this
WebUI project - controllers, views
Framework project- repositories,service layer and domain
So now I have 3 methods/classes
Open Id/Open auth
At first I thought I would put all my logic in a service layer in my framework project(preparing the request, checking the response and etc would be in this layer).
So now I am using the dotnetopenauth library and because I need to use the AsActionResult method in my controller(I return "OutgoingWebResponse" from my service layer as I don't want anything MVC in my service layers)
It got me to thinking when I decided not to have anything MVC in my service layer. As what I read is that your service layer that contains your business logic should not have any dependencies like MVC references because if you go to a windows phone application you should not be using MVC stuff.
Your business layer should be sort of plug and play into any application.
So now I am not sure if I should move what I wrote for openId into my models folder in my mvc projectjust for the reasons above. Since if I do go to a windows phone application or forms application I won't be using dotnetopenauth since I don't think it's supported in these types of applications.
My second one is with forms authentication. Again pretty much same reasons as above. Should this go as well in my models folder as a local service/repo layer(ie in the same project file).
I am using nhibernate, fluent nhiberate and ninject. My repos are all in my framework project. So I have of course all the references in there. But since I am using ninject for ioc I have all the references in my webui project as well.
I have no clue if this one could be changed to get rid of these references from my webui. I am thinking no because they I can't have my ioc in my webui where I think it should go.

As a general rule of thumb you shouldn't write code against requirements that don't exist ( porting the app to a windows phone ) .
Normally you'd abstract this out in your service layer however OAuth or Facebook integration poses a problem because of its reliance on http and being able to visit the authenticating site.
The problem you'll run into because "all abstractions are leaky" is that your service layer will be corrupted somehow by the openauth registration process regardless of where you place it. Details about user registration and login such as what their openid url is will end up in your database. You're service/repo/db/model/mvc/viewmodel/controllers classes are all going to know what openauth is because of its nature.
The good thing is these browser based authentication strategies can live in a Windows Form, WPF or Silverlight application. You simply open a browser inside the application instead of redirecting natively with MVC.
So what I'd recommend is placing your dotnetopen auth registration code inside of your service layer and actually abstracting out how the redirection and callback process happens.
Something like:
public interface IOpenAuthRedirect
{
public void Redirect( url )
public void ParseCallback( url )
}
public class MVCOpenAuthRedirect
{
public void Redirect(url)
{
HttpContext.Current.Response.Redirect(url);
}
}
public class SilverlightOpenAuthRedirect
{
public void RedirectUrl( url )
{
SomeBrowserControl.IForgetTheCallToRedirect( url );
}
}
Now the different implementation details are flexible and you can easily transition to another platform besides MVC.

Related

A web application and Xamarin.Android app communicating to a Service/API

I'm working on an .Net application in which a user can either use a Xamarin Android app or a web application to use the system. I would like to put all the business logic at one place and both the applications shall use it.
Considering that I have "NO" experience in Web APIs or Services, how shall I design my application?
However, I'm ready to learn both (Web APIs or Services) if required for the implementation.
Considering that I have "NO" experience in Web APIs or Services, how
shall I design my application?
The question should rather be, do you need to call some external services, or can you do everything locally on the phones? If some external services are required, you need web API call from your different platforms. The business logic goes in your API.
If everything can be done locally, you can just share your client side code.
As you probably know, Xamarin app's usually follow a MVVM architecture.
It does not mean the business logic must be in the sharing ViewModels (I actually wrote a blog post about that if it you want more information).
The business logic must be in the domain models, and possibly some services.
Thus, in the end you can share the c# code of your domain models and business services between your xamarin app and your web application.
Hope it helps.

OWIN FLOW (from MVC 5) to Class Library

I've a website with 3 layers.....
MVC 5 (Presentation layer) with custom OWIN to store cookie. It checks with Service layer to validate user and then create a cookie.
Service layer (Class Library): Presentation layer has reference to this layer and any communication with database, needs to go through these.
Data layer (Class Library): Data layer with SQL statements. This layer is responsible for any communication with database. Service layer has reference to this.
All the above mentioned layers reside on same machine but within seperate projects. There is also potential that I've had to move all the layers to its own seperate servers (Presentation, Service, Data).
Now, once the user is authenticated and authorized, I want to basically pass the identity to Service and Data layers as I don't want anyone to call the service and data layers directly. But I don't know how to do it.
Could anyone please show me the light?
Cookie/Token is only usable in browser-based environment (that means it only help to secure your presentation layer.
If you want to secure the Presentation layer (which is class library as you mentioned), quick and dirty way is store a private key inside Web project, and every time you call a service, validate the private key passing in.
Standard way is use StrongNameIdentityPermission to prevent others to reference your DLL. (https://msdn.microsoft.com/en-us/library/system.security.permissions.strongnameidentitypermission.aspx)
Extra note: consider to use obfuscator tool to prevent others to decompile your DLL code.

Moving authentication to service

I'm writing simple CRUD-like MVC app at the moment, trying to learn proper N-tier architecture, and so far i had MVC which gets objects through WCF which call my Data Access layer to get those objects from Database.
However I just realized most likely huge mistake I'm making, I left all generated authentication stuff where it was - in MVC project except ApplicationUser and ApplicationDbContext which i moved to Business layer and Data Access layer accordingly and referenced them which I think defeats purpose of Service. How do I move properly authentication to service in this case? Perhaps there is a sample N-Tier project which has authentication moved to service and all?
So far my references are like this:
MVC client knows about Service(as service reference), Business layer
Service knows about Data Access, Business Layer
Data Access knows about Business layer.
this might help you! this explains asp.net identity with Design Patterns
http://timschreiber.com/2015/01/14/persistence-ignorant-asp-net-identity-with-patterns-part-1/

ASP.Net MVC Website & Web API As Single Implementation

I have a client dashboard application, written in ASP.Net MVC 4 (not bound to this version, happy to upgrade). The website is hosted in Windows Azure.
Our clients would like to programmatically access this dashboard, via an API.
Affectively they would like to be able to perform all of the same functions which they normally carry out on the dashboard website, programmatically from code using an HTTP Restful Service.
....My instant reaction was to simply build an ASP.net Web API project, and separate out the shared services/libraries/components from the existing MVC project so that both the API and the MVC website can call the same code base.
Questions
Is it possible to simply create Web API controllers within my existing MVC website project, and expose them over HTTP?
If it is not possible to do "1.", will Azure play nicely if I have an MVC solution, a separate Web API solution, and a shared library project of common services and models? How will I ensure that Azure copies the shared library components into the cloud when I deploy the MVC solution and the Web API solution separately?
Update
Based on the comments, the following implementation of two separate controllers (the original MVC controller within the MVC project, and an additional Web API controller within the same project), does in fact work. Please note that based on the following LINKED ARTICLE, the below implementation would be a "pre-MVC 6" implementation. MVC 6 itself provides the ability to implement both API calls and normally MVC View calls, into a single controller (as opposed to separate controllers that inherit from different base classes).
public class ProductsController : Controller
{
//Products/Index
public ActionResult Index()
{
return View();
}
}
public class ProductsAPIController : ApiController
{
// GET api/productsapi/getall
public IEnumerable<string> GetAll()
{
return new string[] { "value1", "value2" };
}
}
To be fair - MVC or WebAPI, as far as your consuming clients are concerned, it shouldn't matter.
Both MVC and WebAPI can create JSON or XML outputs - it's just one makes it a bit easier (WebAPI serializes the relevant response based on the client).
But you can quite easily mix the two together, as others have said, it's as simple as Add New Item
The newest version of MVC (6) has now integrated both technologies into one solution. http://www.asp.net/vnext/overview/aspnet-vnext/create-a-web-api-with-mvc-6
This would be ideally what you are looking for if you can start a new project.
Question 1: Yes it is, just take a look at the article above.
Question 2:
Azure will be fine if you have a MVC solution and also a WebApi solution, but I think you will need to run them under different websites (I'm not 100% on this).
Yes it will work fine. The only potential gotcha is you have to clearly separate your WebAPI routes from your MVC routes (like, for instance having all WebAPI routes under a /api/... prefix, this is the default).
If you do decide to do two separate projects for whatever reason and want to have a shared library, the best solution is to keep that library in a NuGet package on a private feed. TeamCity supports this out of the box, along with other nice features (continuous integration/deployment).

Web API in MVC solution in separate project

I am creating a new MVC4 project, and research has lead me to believe that communicating from javascript to the server side is better achieved now through web API framework rather than controller actions. Is my understanding correct on this?
I am presuming that I can share all my attributes etc between web API and MVC controllers so on the face it, it does not seem a massive change for me.
When I am setting up applications, I like to split components out in to projects. My plan was to have a MVC project and a web API project. But I have ran in to issues. For example I have ended up with 2 apps as such, separate routing set up etc etc.
So my question is, in a MVC application should the web API framework sit within the same project, or should the web API be separated into a project of its own and work around the issues?
Unfortunately you are wrong about that - I am presuming that I can share all my attributes etc between web api and mvc controllers so on the face it, it does not seem a massive change for me.
Many of the concepts used by Web API and MVC, even though similar at first glance, are actually not compatible. For example, Web API attributes are System.Web.Http.Filters.Filter and MVC attributes are System.Web.Mvc.Filter - and they are not interchangeable.
Same applies to many other concepts - model binding (completely different mechanisms), routes (Web API uses HTTPRoutes not Routes, even though they both operate on the same underlying RouteTable), dependency resolver (not compatible) and more - even though similar on the surface, are very different in practice. Moreover, Web API does not have a concept of areas.
Ultimately, if all you are trying to do achieve is to have a "new, trendy" way of serving up JSON content - think twice before going down that path. I certainly wouldn't recommend refactoring any existing code unless you are really looking into embracing HTTP and building your app in a RESTful way.
It all really depends on what you are building. If you are starting a new project, and all you need is to serve up some JSON to facilitate your web app - provided you willing to live with some potentially duplicate code (like the stuff I mentioned above), Web API could easily be hosted within the same project as ASP.NET MVC.
I would only separate Web API into a separate project if you are going to build a proper API for your online service - perhaps to be consumed by external customers, or by various devices - such as fueling your mobile apps.
IMO, security and deployment should drive your decision. E.g., if your MVC app uses Forms authentication but you're interested in using Basic authentication (with SSL) for your API, separate projects are going to make your life easier. If you want to host yout site at www.example.com but host your API as api.example.com (vs. www.example.com/api), separate projects will make your life easier. If you separate your projects and subdomain them accordingly and you intend to leverage your own API from your MVC app, you will have to figure out how to deal with the Same Origin Policy issue for client-side calls to your API. Common solutions to this are to leverage jsonp or CORS (preferably if you can).
Update (3/26/2013): Official CORS support is coming: http://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API
After some degree of experience (creating API for apps and for mvc). I mostly do both.
I create a separate project for api calls that come from other clients or other devices (Android/IOS apps). One of the reasons is because the authentication is different, it is token based (to keep it stateless). I do not want to mix this within my MVC application.
For my javascript/jquery api calls to my mvc application, I like to keep things simple so I include a web api inside my MVC application. I do not intend to have token based authentication with my javascript api calls, because hey, it's in the same application. I can just use [authorize] attribute on a API endpoint, when a user is not logged in, he will not get the data.
Furthermore, when dealing with shopping carts and you want to store a users shopping cart in a session (while not logged in), you need to have this in your API as well if you add/delete products via your javascript code. This will make your API stateful for sure, but will also reduce the complexity in your MVC-API.
Steven from SimpleInjector (IoC framework) advises two separate projects: What is the difference between DependencyResolver.SetResolver and HttpConfiguration.DependencyResolver in WebAPI
I have recently done almost the same thing: I started with a new MVC 4 web application project choosing the Web API template in VS2012.
This will create a Web API hosted in the same application as MVC.
I wanted to move the ApiControllers into a separate class library project. This was fairly easy but the solution was a bit hidden.
In AssemblyInfo.cs of the MVC 4 project add similar line of code
[assembly: PreApplicationStartMethod(typeof(LibraryRegistrator), "Register")]
Now you need the class LibraryRegistrator (feel free to name it whatever)
public class LibraryRegistrator
{
public static void Register()
{
BuildManager.AddReferencedAssembly(Assembly.LoadFrom(HostingEnvironment.MapPath("~/bin/yourown.dll")));
}
}
In the MVC 4 project also add reference to the Api library.
Now you can add Api controllers to your own separate class library (yourown.dll).
Even if your project is so complex as to warrant two "front ends" then I would still only consider splitting out webapi into a separate project as a last resort. You will have deployment headaches and it would be difficult for a newbie to understand the structure of your solution. Not to mention routing issues.
I would aim to keep the system.web namespace isolated in the one "presentation layer". Despite the webapi not being presentational it is still part of the interface of your application. As long as you keep the logic in your domain and not your controllers you should not run into too many problems. Also, don't forget to make use of Areas.
In addition to setup the separate DLL for the Web.Api.
Just a Suggestion:
Create the Project
Nugget WebActivatorEx
Create a a class Method to be called upon app_start
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(API.AppWebActivator),"Start")]
[assembly:WebActivatorEx.ApplicationShutdownMethod(typeof(API.AppWebActivator), "Shutdown")]
Register a web.api routes inside the Start Method
public static void Start() {
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Reference the Project to the Web Project. to activate the Start Method.
Hope this helps.
I tried to split the API controllers into a new project. All I've done is to create a new library project, moved the controllers inside folder named API.
Then added the reference of the library project to the MVC project.
The webAPI configuration is left in the MVC project itself. It works fine.

Categories