MVC (Model View Controller), is simply a framework used to design web applications, as simple its definition could be.
The three layers are interconnected and are dependant on each other. The below figure will explain better:-
As we can see above, the Data layer or the Model that deals with the data is accessed both by the View and Controller. Here, in MVC there is separation between every laye, that helps in loose coupling the items and also in application development process. Now, one might wonder what exactly Separation of Concern means! This can be framed as there should not be or there should be minimal overlapping/dependancy of functions in an application. For example, take the scenario of the View and the Controller. Can they be separately done!! That is can their be no dependancy between them!! View is the presentation layer and the Controller is the action layer. We can have in real scenario a controller without a View, but a view without a controller sounds a bit radical. This is not necessarily true always. So, we can conclude here that Separation of Concern can be minimal but still lies a grey line. NOTE: Thus always have separate UI layer, Data access layer & Logic Layer in order to achieve clean separation.
The above image displays the simple MVC folder structure. The Models having the Entities, Controllers as well as the Views for each controller, the shared folder having the master pages.
Models(in a bit more depth) : Contains all the application logic i.e.
This holds as well as manipulates the data in the database. This folder contains the classes/entities that are required and present in the application.
Views(in a bit more depth) : The View generally stores the Html files may it be .cshtml or .vbhtml (C# and VB) respectively. These may have extensions as html, asp, aspx. The interesting thing is every controller there is a view folder and for every action a view. There is always a Shared folder inside View, that is used to have the Layout or the Master pages.
Controllers(in a bit more depth) : This contains the controller classes responsible for input and responses. The name of the Controller ends with Controller to distinguish. For example, “HomeController.cs”. Every controller implements the Icontroller interface from the System.Web.Mvc namespace.
public interface Icontroller { void Execute(RequestContext requestContext); }
The single method Execute is invoked when a request is targeted at the controller class. What happens to the request that comes to the application? The request that comes to the web application first goes through the UrlRoutingModule object (System.Web.Routing.UrlRoutingModule). The request gets parsed and then the route selection is done. When the application starts up, it runs the Application_Start() method present in the Global.asax that marks the application initialization.
protected void Application_Start() { RouteConfig.RegisterRoutes(RouteTables.Routes); }
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.Ignore(“{resource}.axd/{*pathinfo}”); routes.MapRoute( name:"", url:"{controller}/{action}/{id}", defaults: new {controller = "Home",action="Index",id=UrlParameter.optional} ); } }
Then the UrlRoutingModule discussed above finds a matching route for the incoming URL from the Route Table. When it matches, it retreives the IRouteHandler instance for that route (MvcRoutehandler). Then the IRouteHandler’s GetHttpHandler() is called and finally the ProcessRequest() method is invoked. Then MvcRoutehandler instantiates and executes controller.
Here as you can see, the URL has the {controller}/{action}/{id}, the id is optional which is defined in the defaults. URL may also be only {controller}/{action}. As the routes would be specified or registered in the Route Table, so will the navigation will be.
public class TenantController : Controller //Derived from Base controller { public ActionResult Index() //Default Action method-URL: /Home/Index { return View(); } public ActionResult Index(int id) //Action Method with an Id as parameter // -URL: /Home/Index/3 { return View(); } }
This is how the routing works on incoming request from the browser. Similarly we can use custom routes also as not always we will be using Home/Index ..
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.Ignore(“{resource}.axd/{*pathinfo}”); routes.MapRoute( name:"Employee", url:"{controller}/{action}/{id}", defaults: new{controller = "Employee",action="Add",id=UrlParameter.optional}//Adds a new employee action ); } }
If the Url matches any of the routing registered in the Table, the user lands on the View else 404 errornot found page.
public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)
After getting the appropriate action, then comes the work of the model binders, default being System.Web.Mvc.DefaultModelBinder, receives the Http request, validates and does the conversions requiqred and also mapping the input values from the user.
This was the basic and foremost things to knowabout MVC. These are all done on the background. Being Developers, not bothering about the flow is now worthy enough. Thus, Just adding a Controller an action to it and oviously a View to it, does not mean we have done something great!! You would always prefer a pot full with water rather than the one that is almost empty!!
. We are done with the first part. We will be covering interesting topics for learning MVC in part-2
Hope this helps any way. Any suggestions, queries and comments are most welcome.
Dotnet Tricks
Adam Freeman Pro Asp.Net MVC4
Windows Azure provides various cloud enabled storage services and Blob storage is one of them. BLOB stands for “Binary Large Object” which means unstructured data that typically includes images, documents, audio, video or other multimedia objects. The main purpose for using BLOB cloud services is it has a many advantages over storing files in local file systems.
As the msdn suggests the advantages are :-
And many more, for the time these are of more focus.
This article mainly focuses on use of cloud services as here is Azure, checking for containers in our development storage and creating blobs dynamically into it and uploading files to it, as its being used in almost every sites.
In order to develop Azure Cloud enabled applications, we need to install SDK(Software Development Kit-A software development tool required to create application for specific software) first. The best way to develop SDK is :
It will then redirect you to download the SDK if its not installed.
Now lets start our play with MVC, Add a class to it that would create and check for the containers(I have named as BlobStorageServices.cs) and the code goes as mentioned below:-
//namespaces used using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcWebRole1 { //Container information public class BlobStorageServices { public CloudBlobContainer GetCloudBlobContainer() { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("ImageUploadSetting"));//gets settings value CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();//activates the storage account on local CloudBlobContainer blobContainer = blobClient.GetContainerReference("imagesupload"); if(blobContainer.CreateIfNotExists()) { blobContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });//Allowing public Access } return blobContainer; } } }
Now add a action method to your HomeController. I have named the action as Upload[HttpGet]/[HttpPost]. The code goes below:-
BlobStorageServices blobStorageServices = new BlobStorageServices();//Instantiate object of the class we just created for containers. /// <summary> /// Uploads this Image. /// </summary> /// <returns>Views of blobs</returns> [HttpGet] public ActionResult Upload() { CloudBlobContainer blobContainer = blobStorageServices.GetCloudBlobContainer(); List<string> blobs=new List<string>(); foreach(var blobItem in blobContainer.ListBlobs()) { blobs.Add(blobItem.Uri.ToString());//Returns all the blobs Uri in the container. } return View(blobs);//Returns to view to display all blobs. }
/// <summary> /// Uploads the specified image. /// </summary> /// <param name="image">The image.</param> /// <returns>Redirected to Upload Action</returns> [HttpPost] public ActionResult Upload(HttpPostedFileBase image) //Accept the posted file { try { if (image.ContentLength > 0) { CloudBlobContainer blobContainer = blobStorageServices.GetCloudBlobContainer(); CloudBlockBlob blob = blobContainer.GetBlockBlobReference(image.FileName); //First Blob // Upload content to the blob, which will create the blob if it does not already exist. blob.UploadFromStream(image.InputStream); } } catch(Exception ex) //Catches Null Exception here and stores it to blob { CloudBlobContainer blobContainer = blobStorageServices.GetCloudBlobContainer(); CloudBlockBlob blob2 = blobContainer.GetBlockBlobReference("myfile.txt"); //Second Blob blob2.UploadText(ex.ToString()); } return RedirectToAction("Upload"); }
Here I have gone for an exception handling and a better way is I am uploading the exception content creating another blob (myfile.txt). Here we upload image and a text file that includes exception, incase it occurs.
Now lets work on the UI part. I am coding a simple UI design and the code goes here:-I have used Razor in MVC4.
@{ ViewBag.Title = "Upload"; } <h2>Upload Image</h2> <p> @using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { <input type="file" name="image" /> <input type="submit" value="Upload" /> } </p> <ul> @foreach (var item in Model) { <li> <img src="@item" alt="Images uploaded"width="150"height="150" /> </li> } </ul>
Lets just overview about the WebRole, WorkerRole and Queue in Azure:-
Web Role in Windows Azure are special purpose services and provide a dedicated IIS used for hosting web application, we can easily add and deploy application to webrole and scale as per our compatibility as per requirement.It is basically front-end that appears to the users.
Worker Role are processes that can do some work as the name suggests. For example, compressing an uploaded image automatically or on the fly, any changes in the database, best is notifications that are recieved.
Queue contain set of messages and those messages should be queue. The main thing is that Web Role, Worker Role and Queues are Virtual Machines running on cloud.
]]>A Favicon
(“favorites icon”), is an icon associated with a particular website or webpage that is displayed in the browser address bar next to a site’s URL. Favicon
is a little icon, but plays a subtle and important role. It acts as a brand.
This Favicon
is very familiar, which can be seen next to the Title of any WordPress WebPage and some other places as described below.
It is displayed at three places.
It is very simple and easy. Follow the steps described below.
I recommend Favicon Generator.
That would become your Website’s brand image.
Add it in your root directory and remember to rename it as sometimes it does not refresh itself if Internet Template is used.
<span class="code-keyword" style="color: blue;"><</span><span class="code-leadattribute" style="color: maroon;">link</span> <span class="code-attribute" style="color: red;">rel</span><span class="code-keyword" style="color: blue;">="</span><span class="code-keyword" style="color: blue;">shortcut icon"</span> <span class="code-attribute" style="color: red;">href</span><span class="code-keyword" style="color: blue;">="</span><span class="code-keyword" style="color: blue;">https://www.codeproject.com/NAME of your FAVICON.ico"</span> <span class="code-attribute" style="color: red;">type</span><span class="code-keyword" style="color: blue;">="</span><span class="code-keyword" style="color: blue;">image/x-icon"</span><span class="code-keyword" style="color: blue;">></span>
Put the above code in the <head>.......</head>
section of your webpages if Empty Template is used, else in theLayout Page for Internet template.
While working on a demo, I saw a Favicon
in my root directory and got curious to know what is the use. I saw this when I used an Internet Template in ASP.NET MVC4
not an Empty Template. Hope beginners like me get to know about this and use this with their Websites.
Give your Website a brand with these steps and enjoy.
This is trivial and my very first Tip and Post too, wanted to start with this.
Happy Coding
]]>