I'm in the process of trying out a few things with MVC whilst designing a system and wanted to try and see if I could use the concept of Controllers outside of the MVC framework. When I say outside, I mean within my own C# service as opposed to a web-site.
I started a simple console application to test the theory and it was simple enough to change the profile to a non-client profile, add in System.Web.Mvc, create a controller and have it return a JsonResult. The ease of which this got set up pleased me as that is half the work done if I want a service to respond with JSON.
The next step is to set up a Http Server class, and I would love it if I could leverage the other part of the framework which will map incoming requests to my controllers. Unfortunately, this is the part where I am lost and I have no idea what code goes on behind to arrive at a particular controller's function with the parameters all in place.
Has anyone got an idea on how to accomplish this, or a resource to look at?
In short: I'd like to leverage the use of Controllers in my own service, running it's own HTTP Server.
You can use the design pattern without using the framework - what I mean is, you can apply the model view controller pattern wherever you believe it solves the problem - if you think that you can replace "view" with "service", you could apply some of the concepts...
http://msdn.microsoft.com/en-us/library/ff649643.aspx
However, there are other patterns that may lend themselves better to services, although if we are talking specifically about a JSON service, then just using the ASP.NET MVC framework as it is would work well (rather than trying to re-write it).
Are you not trying to reinvent the wheel?
If returning JSON is one of your main purpose then WCF fulfills your need. Having WCF with you you are free to host it in IIS. This serves your second purpose having its own HTTP server.
You are trying to achieve some kind of routing where based on URL your different actions will be called. Isn't it similar to having a WCF service with different methods and client is calling each of them with different URL?
Trying controller concept in a non web application seems to be innovative, however in your case it looks like over-engineering.
The basic MVC pattern isn't all the difficult to replicate. I would seriously consider writing your own, rather than trying to shoehorn the MVC classes into your app.
Simon
If it helps you, the entire ASP.Net MVC Framework is open source, you can download it all from http://aspnet.codeplex.com/ . You can use the libraries here to view how the Framework is doing things behind the scenes and adapt things for your own use as appropriate.
Related
I've been researching ways to build a Web Client using C# that is Single Page and is generated from XML files.
Essentially, I want to have a service that generates XML files that describe the UI of e.g. forms (not the problem). Those XML files are sent to the client, which in term reads the XML and dynamically creates the layout with all the controls. I had hoped to accomplish this in Blazor WebAssembly (I have also looked at ASP.NET WebForms, MVC and CORE (using DevExpress), but none of those are actually meant for SPA clients).
By comparison: We have an Android app that basically does this, similar to what is described right here: https://developer.ibm.com/tutorials/x-andddyntut/
But this time I am not developing an Android app in Java, this is supposed to be a WebClient. And as most coders in the company have a VB.NET background, my head of department would like for it to use C#. But I have tried finding ways to do something like this and have met lots of dead ends, as usually Blazor appears to be used with static pages from design time. I haven't managed to get it to run with RenderFragments, for example.
Any pointers with this would be very much appreciated!
Sincerely,
MR
You can generate the UI dynamycally using RenderTreeBuilder but most of its behavior is intended for internal use (take RenderTreeFrame for example) and therefore I don't think it is a good idea.
In short, I don't believe what you want to achieve is possible.
If these XMLs don't change often, I would think to create a transpiler that converts these XMLs to Blazor code and then recompile the app.
Not a direct answer to creating Forms dynamically, but a suggested alternative method.
For my application I have a number of services which have different properties but are based on underlying common base class. The services defined in several .NET Standard library for each type. The services are things like VoIP, Broadband, FTTC, Ethernet, Router Orders etc. etc. - not much in common, and very different types of data and behaviours.
The base service class has an abstract method called GetView which returns a C# type which is a Razor Component type. Remember in Blazor all those components are just C# classes. The type returned is a Razor Component in the same library (so we have UI as well as business and entity logic encapsulation).
The parent site loads a specific type of service, calls GetView and binds the service to the resulting Component.
That's pretty complicated to describe but I did a proof-of-concept application for this approach in the early days of Blazor as I realised it was going to be capable of this approach: https://github.com/conficient/BlazorDynamicList
There is also a demo site at https://blazordynamiclist.azurewebsites.net/
I won't explain it all in detail here but it follows a similar approach. There is an abstract base class ProductBase that has an abstract method GetViewComponent. Each product can return its preferred Razor Component to display itself.
The 'magic' is the DynamicComponent.cs which is a Razor Component with a BuildRenderTree method that creates a bound instance of the product's component view.
I have a WebAPI web service, which acts as a business logic layer for client applications (WinForms and Mobile).
Now I want to create an MVC application which will act as presentation layer only, and I am having doubts weather this architecture makes sense or does it break MVC concepts.
If it makes sence, what is the right/correct way of interaction between MVC application (as a presentation layer) and WebAPI service (as a business logic layer)?
Will appreciate if anyone can give me some code examples.
It's fine if you use mvc this way, your controllers can access the webapi and serve the data to the templates.
You might also consider angularjs as views/templates and the controllers there can call the webapi for data.
While I think other answers are accurate, here is some other concerns you may think of.
First, your WebAPI is probably where your business are implemented. Indeed, you may already deal with:
Business related exception
Validation
Operations available
etc.
Your Api is what should not change, unless the business rule behind a certain functionnality changes too.
What I want to point out here is one thing:
Keep your user interface completely independant from your API
The risk of using an MVC app with a WebApi
All the code together = mutiple reasons to change the same thing
By using an MVC app, you could be tempted to package the WebApi and the MVC app in the same solution. You would also be able to deploy all your stuff together. But doing it this way, you may end up with a big bunch of code where parts are not evolving at the same speed (i.e: user interface will change oftently, but do the Api will change every time a UI fix is need. NO. And do every changes to the API will impact the UI. No.)
All code together enables shortcuts
What I mean by that, is that if everything is package together, a developer could be tempted to call some method directly instead of calling the API that should be the only valid facade. Any shortcut taken can lead will lead to code duplication, bugs, validation error, etc.
Again: do not package your MVC app with your API.
Solutions
Use a Javascript framework
The other suggestions are good. AngularJS, ReactJS, EmberJS are good frameworks. (There are other, pick the one that fits your needs) But again, it will be a good choice for your architecture because you will create a clear separation between your UI app and your API app which are separated concerns. Your business logic will be well protected, and you will be sure that your code is only call via HTTP calls, the only valid facade of your API. In other words, you make sure nobody will take shortcuts.
Use .NET MVC app in its own project
If you still want to use .NET MVC, I would suggest that you call your API via HTTP: no shortcuts. I would create a different solution and with a separated MVC project where calls to the API would be made using the HttpClient or something like RestSharp. What you want here is to avoid to bind your UI to your API code. You want to bind your UI to the contract define by the API facade (api controllers) not their implementation.
I think better, of course if it possible in your situation, to use one of the JavaScript MVC frameworks.
I think AngularJS, ReactJS or EmberJS will be the most coolest variants for your purpose. I don't think that calling ASP.MVC actions and then do another call to WEB API from there it's good idea, imho.
I would like to ask a question.
Recently, I've learned how to make jQuery use C# methods via consuming from an ASP.NET Web service. I am thinking of exposing some database access methods such as retrieving a list of records from the database for rendering using a jQuery library.
I have on top of my head is that I create a separate project in my solution, which is a Web service project to be able to expose the said data access methods (located on a separate project also in the solution). The web service will act as interaction between my jQuery and my data access methods.
I am visualizing my idea like this:
My question is that, is my idea a good thing to do, and if not, how do you properly expose C# data access objects for use with jQuery?
Thanks!
EDIT: The Web UI is an ASP.NET Web Forms, specifically version 2.0. I'm doing this in preparation to my next job.
Yes, this is the correct approach. Typically, the Web Service is a REST API (http://en.wikipedia.org/wiki/Representational_state_transfer) that returns JSON/JSONP. This allows the client (JQuery) to use AJAX, async calls to the server.
Web API 2 (http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api) is an easy way to expose an REST API in c#.
As Richard has already explain
i will extend it and suggest you to use AngularJs instead of simple of calling jquery ajax.
Why AngularJS?
HTML is great for declaring static documents, but it falters when we
try to use it for declaring dynamic views in web-applications.
AngularJS lets you extend HTML vocabulary for your application. The
resulting environment is extraordinarily expressive, readable, and
quick to develop.
Case Studies for example
I've been searching on the net for possible answer to my question, but no luck at all.
I just wonder if I could use WCF as my Controller in ASP.NET MVC.
So if I call
(WCF)
http://localhost:1621/WCF/LogOut.svc?id=10001
It will work like
(MVC)
http://localhost:1621/WCF/LogOut?id=10001
Or I'm just having wrong thought about it?
Can you give some source for deeper knowledge in MVC and WCF.. Thanks!
The MVC states that the controller picks up requests and it is responsible for preparing the model and passing it to a view which is ultimately rendered.
Although from the perspective of web requests, WCF could possibly look like MVC, there is no easy way to make WCF render the HTML to the browser. This means that if WCF can implement "controllers" which produce "models" but is not designed to create "views".
However, if your web application can pick up XML/JSON data produced by WCF calls (i.e. you have your views implemented purely at the client side) then yes, WCF does a good job as a provider of the "controller/model" part of the MVC.
The objective is to build a service that I will then consume via jQuery and a standards based web front-end, mobile device "fat-clients," and very likely a WPF desktop application.
It seems like WCF would be a good option, but I've never built a RESTful service with WCF, so I'm not sure where to even begin on that approach.
The other option I'm thinking about is using ASP.NET MVC, adding some custom routes, add a few controller actions and using different views to push out JSON, xml, and other return types.
This project is mostly a learning exercise for myself, and I'd like to spend some extra time and do it "right" so I have a better undertanding of how the pieces fit together.
So my question is this, which approach should I use to build this RESTful service, and what are some advantages of doing it that way?
Normally, I would say WCF for any kind of hosted serice, but in the specific case for RESTful services using JSON as a serialization mechanism, I prefer ASP.NET MVC (which I will refer to as ASP.NET for the remainder of this answer).
One of the first reasons is because of the routing mechanism. In WCF, you have to define it on the contract, which is all well and good, but if you have to make quick changes to your routing, from my point of view, it's much easier to do them using the routing mechanism in ASP.NET.
Also, to the point above, if you have multiple services exposed over multiple interfaces in WCF, it's hard to get a complete image of your URL structure (which is important), whereas in ASP.NET you (typically) have all of the route assignments in one place.
The second thing about ASP.NET is that you are going to have access to all of the intrinsic objects that ASP.NET is known for (Request, Response, Server, etc, etc), which is essential when exposing an HTTP-specific endpoint (which is what you are creating). Granted, you can use many of these same things in WCF, but you have to specifically tell WCF that you are doing so, and then design your services with that in mind.
Finally, through personal experience, I've found that the DataContractJsonSerializer doesn't handle DateTimeOffset values too well, and it is the type that you should use over DateTime when working with a service (over any endpoint) which can be called by people over multiple timezones. In ASP.NET, there is a different serializer that you can use, or if you want, you can create your own ActionResult which uses a custom serializer for you. I personally prefer the JSON.Net serializer.
One of the nice things about the JSON.Net serializer and ASP.NET that I like is that you can use anonymous types with it, if you are smart. If you create a static generic method on a non-generic type which then delegates to an internal generic type, you can use type inference to easily utilize anonymous types for your serialized return values (assuming they are one-offs, of course, if you have a structure that is returned consistently, you should define it and use that).
It should also be mentioned that you don't have to completely discount WCF if developing a RESTful service. If you are pushing an ATOM or RSS feed out from your service then the classes in the System.ServiceModel.Syndication namespace of massive help in the construction and serialization of those feeds. Creating a simple subclass of the ActionResult class to take an instance of SyndicationFeed and then serialize it to the output stream when the ActionResult is executed is quite simple.
Here is a a thought that may help you make the decision between ASP.NET MVC and WCF. In the scenarios you describe, do you expect to need to use a protocol other than HTTP?
WCF is designed to be transport protocol agnostic and so it is very different than ASP.NET. It has channels and bindings, messages, service contracts, data contracts and behaviours. It provides very little in the way of guidance when it comes to building distributed applications. What it gives you is a clean slate to build on.
ASP.Net MVC is naturally a Http based framework. It deals with HTTP verbs, media types, URLs, response headers and request headers.
The question is which model is closer to what you are trying to build?
Now you mentioned ReST. If you really do want to build your distributed applications following the ReST constraints then you would be better to start with OpenRasta. It will guide you down that path.
You can do Rest in ASP.Net MVC and you can do it in WCF, but with those solutions, you will not fall into the pit of success ;-)
Personally, I am not crazy about implementing REST services in WCF. I find the asp.net mvc framework a more natural programming model for this.
The implementor of http://atomsite.net/ originally implemented the atompub specification in WCF and then rewrote the entire service using asp.net mvc. His experience echoed my comment above that for a pure REST service asp.net mvc is the way to go.
The only exception would be if I wanted to potentially expose a service in a restful and non restful way. Or if I was exposing an existing WCF service via REST.