ASP.NET MVC 3 Rapid Application Development                           Mădălin     tefîrcă and Victor Chircu       Abstract...
If you run the application you will notice that you have a fully functional project in-cluding a minimal authentication sy...
erties of type string and name them Name and CompanyName and an Id. Still insidethe class, if you type in “ctor” and press...
4      Html helpersHtml Helpers are provided by visual studio as support for rendering HTML controlsin a view. It has a wi...
[WebGet(UriTemplate = "Result?q={keyword}&lat={latitude}&lng={longitude}&rad={radius}&output={outputType}")]public string ...
There are other vendors that offer 3rd party components and controls, like Telerik orDevExpress. These controls get rid of...
Upcoming SlideShare
Loading in...5
×

ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010

196

Published on

This paper’s aim is to point out the RAD ( Rapid application development) elements present in the Microsoft’s MVC 3 and WCF 4.0 using Microsoft Visual Studio 2010. It will describe why creating a new web application using MVC 3 and WCF 4.0 is a easy and fast and also present simple ways to develop such applications.

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
196
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
1
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010

  1. 1. ASP.NET MVC 3 Rapid Application Development Mădălin tefîrcă and Victor Chircu Abstract. This paper’s aim is to point out the RAD ( Rapid application devel- opment) elements present in the Microsoft’s MVC 3 and WCF 4.0 using Micro- soft Visual Studio 2010. It will describe why creating a new web application us- ing MVC 3 and WCF 4.0 is a easy and fast and also present simple ways to de- velop such applications.1 IntroductionThe paper will describe to you the simplicity of developing a web application usingMicrosoft’s ASP.NET MVC 3 and WCF 4.0. Starting with the creation of a newproject, adding new items, and quickly adding functionality including modeling, data-bases CRUD operations, UI elements, exposing and consuming REST services etc.There will be a brief presentation of the Html Helpers provided by Visual Studio, andthe use of Dynamic Templates and how they can help you and a comparison betweenMVC 3 and Web Forms, the main web oriented frameworks provided by Microsoft.2 Creating a new projectCreating a new project is easier than ever. You can create an emtpy project allowingyou to structure it the way you think is best fit, or you can choose to create a newInternet Application that will create for you a fully functioning project and fully ex-tensible. It is recommended to choose the second option, because this way you willnot have to worry about the project structure and start developing since the very firstminute. If you watch Fig.1 you can notice that Visual Studio has buit for you separatefolders for Controllers, Views, Models, Scripts, Content.If you check the packages.config file you can also see that Visula Studio also addedsome useful packages for you like jQuery, jQuery-UI, jQuery.Validation meaningjavascript libraries that will greatly improve your development and are very commonto an experienced developer. The Entity Framework nuGet package is installed alsoby default and it comes in handy when working with complex databases since most ofthe work is done by this ORM (Object Relational Mapping tool ).In the ViewsShared folder you will find two .cshtml files, _Layout, used as a masterpage in the application, and Error, used as an global error page displayed to the userwhen the server crashes. These two are also added by default when creating a newMVC3 project.
  2. 2. If you run the application you will notice that you have a fully functional project in-cluding a minimal authentication system that allows you to register users and authen-ticate them later on. Fig. 1.3 Adding new items3.1 Models Visual Studio also has provided for you an easy way for adding new items to yourprojects. You can add a new class in the Models folder that will be our new model.Right click the Models folder and select Add/Class. Name the class Employee andclick Add. Inside the class you type “prop” and click the Tab key. This will instantlycreate for you a default property. Pressing the Tab key will switch you through theproperty type and property name in order to change them. Make for a start two prop-
  3. 3. erties of type string and name them Name and CompanyName and an Id. Still insidethe class, if you type in “ctor” and press Tab key it will automatically generate a con-structor for you. Inside the constructor assign the CompanyName property a string.Now you have your first model. Your code should look like this:public class Employee { public Employee() { this.CompanyName = "Fictional Company"; } public int Id { get; set; } public string Name { get; set; } public string CompanyName { get; set; } }3.2 ContextNow we will have to add a context for Entity Framework database. Int he Modelsfolder add a new class. This should inherit the DBContext object from Sys-tem.Data.Entity. Add a property to the class that should look like this:public class EmployeeContext : DbContext { public DbSet<Employee> Employees { get; set; } }And now you have your context.3.3 ControllersTo add a new controller, you simply right click the Controllers folder and selectAdd/Controller. You type in the controller name, and then you get to choose betweenseveral scaffolding options like and empty controller, controller with empty actions orcontroller with read/write actions and views. The latter is the easiest way to develop.Choosing this option will require you to set the model class and the data context. Ourmodel is Employee and context is EmployeeeContext. After selecting those previouslymentioned click Add. This will generate you the whole mechanism required forCRUD (Create, Read, Update, Delete) operations over the Employee entity, includingdatabase operations, and UI. If you take a look in the Views/Employees folder youwill see that Visual Studio has already generated all the html you need for the actions.If you run the application in your browser and go to host/Employees you will have thefull functionality done.
  4. 4. 4 Html helpersHtml Helpers are provided by visual studio as support for rendering HTML controlsin a view. It has a wide variety of choices like generating a link, forms, or even inputsor validations for inputs based on a predefined model. Also these helpers are highlyextensible, customizing them being a great benefit for development.@Html.EditorFor(m => m.Property)@Html.DropDownListFor(m => m.Property, customSelectList)5 Dynamic templatesTemplates are used to display a predetermined portion of the page layout which alsocontains fill-in-the-blanks that can be filled at run time. Template saves a lot of timebecause it can be reused in many places. Razor view engine includes a feature calledInline Template, which allows you to define a portion of dynamic HTML that can bereused. Also using Razor template you can pass template as a parameter to a method.You can make this for display or edit mode. All you must do is to set the @model ofthe template to the desired type. This can be a struct, a class, or even a collection.You can call this templates either by setting the name of the templates exactly thesame as the type of the property of the model, or by setting an attribute to the property[UIHint(“templateName”)].6 WCF and RESTConsuming and exposing REST services has become easier with the release of Win-dows Communication Foundation (WCF) 4.0, because of the inclusion of the WebHTTP programming model.For exposing RESTful services, all you need is the WCF Rest Service Template 40,which you can get through the Extension Manager (you can find it in the Toolsmenu). In a project created with the template mentioned earlier, you can add a newclass for your service and decorate it with the [ServiceContract] attribute. Now youcan add methods to your service class and decorate them with either the [WebGet]attribute (for GET requests) or with the [WebInvoke] attribute (for other HTTP me-thods). Both attributes take a UriTemplate as a parameter, in which you can specifythe URI template to your resource. As a note, every token (string between “{}”) in theUriTemplate has to be a parameter to the method, as shown in the following example:
  5. 5. [WebGet(UriTemplate = "Result?q={keyword}&lat={latitude}&lng={longitude}&rad={radius}&output={outputType}")]public string Get(string keyword, double latitude, double longitude, int radius, string outputType)After you have defined your RESTfull method, the only think that remains is to regis-ter it in the Global.asax file, in the RegisterRoutes method:RouteTable.Routes.Add(new ServiceRoute("WhereToGoService", new WebServiceHostFactory(), typeof(WhereToGoService)))Now by accesing :<serv-er>:<port>/WhereToGoService/Result?q=Tuxy&lat=24.4&lng=24.4&rad=10&output=json, the corresponding Get method from WhereToGoService will be called.Consuming RESTful services is easy if you use the right tools and .NET classes: • UriTemplate to specify the template for the URI, and using the UriTem- plate.BindByPosition or UriTemplate.BindByName methods to replace the tokens in the template with the actual values. • WebClient to get the data from the specified URI (for example you can use the WebClient.DownloadString method which returns the String received by accessing the URI specified as the method’s parameter). • LINQ to XML for converting the string into and XML, and manipulating the XML through LINQ sintax. • Newtonsoft’s Json.net library for manipulating strings in Json format (for ex- ample if the service that you are consuming returns information in Json for- mat), and for converting XML to Json and vice-versa.These are simple use cases used as proof of concept, but you can develop far morecomplex REST services using WCF 4.0, together with other frameworks and librariesprovided by the .NET community.7 AlternativesThe main advantages of the ASP.NET MVC 3 are that it enables full control over therendered HTML, it provides clean separation of concerns, easy integration with java-script, RESTful urls that enables SEO, no ViewState and PostBacks events. The webforms provide a wide variety of RAD elements, like drag & drop, automatic eventgeneration, and it is easier for developers coming from the winform development toadapt. Another big plus for the web forms framework is the maturity - it has beenaround since 2002 and there is a big amount of information regarding solving prob-lems. Both of them are good choices, neither of the web frameworks are to be re-placed by the other, nor there are plans to have them merged.
  6. 6. There are other vendors that offer 3rd party components and controls, like Telerik orDevExpress. These controls get rid of most of the boilerplate code that you would bewriting, so they are feasible for small applications. But when it comes to buildingcomplex enterprise applications, you would notice that these 3rd party components donot cover all of the uses cases that you need, so ASP.MVC would be a safer bet.8 ConclusionAll mentioned above prove that MVC 3 is very reliable and can easily be used todevelop complex web applications in a very short time, with great elegance. It is easyto start with at a beginner level, allowing you to build basic functionality without toomuch experience, and allowing more advanced developers to build solid, complexapplications in a short time. When working on a project you have to take into consid-eration its purpose, scale, scalability and maintainability, and choose a frameworkaccordingly. Even if lately Microsoft has integrated more and more RAD componentsinto ASP.MVC, this framework is still designed for complex web application.

×