MVC – Model, View, Controller – Part1

•Models encapsulate objects and data

•Views generate the user interface

•Controllers interact with user actions

 

MVC based application development is bundle of ASP.NET shared features ( Configuration , Authentication , Membership and Roles , State Management , Caching ) with Javascript,  jQuery and some of classic ASP features.

 

Image

When user send an request from browser in the view, it triggers the corresponding action in the controller that performs actions using underlying model and model interact database sends back required info to controller, which in return data(after performing various business rules and actions) through view  to the user.

In MVC, processing of user requests is not file based as in asp.net, the processing happens based on actions. Like when user submit data in a login form, mvc triggers “Login” action(method) in a controller rather than “Loginpage.aspx” as in asp.net. Action in a controller is nothing but a method. Controller is a class to handle user actions and map to corresponding action methods.

 The ASP.NET MVC framework maps URLs to classes that are referred to as controllers. Controllers process incoming requests, handle user input and interactions, and execute appropriate application logic. A controller class typically calls a separate view component to generate the HTML markup for the request.

The base class for all controllers is the ControllerBase class, which provides general MVC handling. The Controller class inherits from ControllerBase and is the default implement of a controller.

All controller classes must be named by using the “Controller” suffix

When a user enters a URL into the browser, the MVC application uses routing rules that are defined in the Global.asax file to parse the URL and to determine the path of the controller. The controller then determines the appropriate action method to handle the request. By default, the URL of a request is treated as a sub-path that includes the controller name followed by the action name.

Controllers can include as many action methods as needed.

Action methods typically have a one-to-one mapping with user interactions. Examples of user interactions include entering a URL into the browser, clicking a link, and submitting a form. Each of these user interactions causes a request to be sent to the server. In each case, the URL of the request includes information that the MVC framework uses to invoke an action method.

ActionResult Return Type

Most action methods return an instance of a class that derives from ActionResult. The ActionResult class is the base for all action results. However, there are different action result types, depending on the task that the action method is performing. For example, the most common action is to call the View method. The View method returns an instance of the ViewResult class, which is derived from ActionResult.

You can create action methods that return an object of any type, such as a string, an integer, or a Boolean value. These return types are wrapped in an appropriate ActionResult type before they are rendered to the response stream.

Various ActionResule types are:

  • ViewResul
  • PartialViewResult
  • RedirectResulteResul
  • ContentResult
  • JsonResult
  • JavascriptResult
  • FileResult
  • EmptyResult

 

Differences between ASP.NET Webforms engine and Razor View Engine

=> Razor Engine is an advanced view engine that was introduced with MVC3. This is not a new language but it is a new markup syntax. Web Form Engine is the default view engine for the Asp.net MVC that is included with Asp.net MVC from the beginning.

=> The namespace for Razor Engine is System.Web.Razor.The namespace for Webform Engine is System.Web.Mvc.WebFormViewEngine.

=> The file extensions used with Razor Engine are different from Web Form Engine. It has .cshtml (Razor with C#) or .vbhtml (Razor with VB) extension for views, partial views, editor templates and for layout pages.The file extensions used with Web Form Engine are also like Asp.net Web Forms. It has .aspx extension for views, .ascx extension for partial views & editor templates and .master extension for layout/master pages.

=> Razor has new and advance syntax that are compact, expressive and reduces typing.Web Form Engine has the same syntax like Asp.net Web Forms uses for .aspx pages.

=> Razor syntax are easy to learn and much clean than Web Form syntax. Razor uses @ symbol to make the code like as:

        @Html.ActionLink(“SignUp”, “SignUp”)

Web Form syntax are borrowed from Asp.net Web Forms syntax that are mixed with html and sometimes make a view messy. Webform uses <% and %> delimiters to make the code like as:

        <%: Html.ActionLink(“SignUp”, “SignUp”) %>

=> By default, Razor Engine prevents XSS attacks(Cross-Site Scripting Attacks) means it encodes the script or html tags like <,> before rendering to view. Web Form Engine does not prevent XSS attacks means any script saved in the database will be fired while rendering the page

=>  Razor Engine is little bit slow as compared to Webform Engine.. Web Form Engine is faster than Razor Engine.

=> Razor Engine, doesn’t support design mode in visual studio means you cannot see your page look and feel.Web Form engine support design mode in visual studio means you can see your page look and feel without running the application.

=>  Razor Engine support TDD (Test Driven Development) since it is not depend on System.Web.UI.Page class. Web Form Engine doesn’t support TDD (Test Driven Development) since it depend on System.Web.UI.Page class which makes the testing complex.

 

When to use MVC

sorce: http://msdn.microsoft.com/en-us/library/dd381412%28v=vs.108%29.aspx

You must consider carefully whether to implement a Web application by using either the ASP.NET MVC framework or the ASP.NET Web Forms model. The MVC framework does not replace the Web Forms model; you can use either framework for Web applications. (If you have existing Web Forms-based applications, these continue to work exactly as they always have.)

Before you decide to use the MVC framework or the Web Forms model for a specific Web site, weigh the advantages of each approach.

Advantages of an MVC-Based Web Application

The ASP.NET MVC framework offers the following advantages:

  • It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.

  • It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.

  • It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure. For more information, see Front Controller.

  • It provides better support for test-driven development (TDD).

  • It works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.

Advantages of a Web Forms-Based Web Application

The Web Forms-based framework offers the following advantages:

  • It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.

  • It uses a Page Controller pattern that adds functionality to individual pages. For more information, see Page Controller.

  • It uses view state on server-based forms, which can make managing state information easier.

  • It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development.

  • In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.

MVC Pros and cons

Tags

, ,

hi friends,

Here am listing few MVC pros and cons (info got from other sources)

 

PRO – No ViewState or “surprise crap”

In traditional ASP.NET WebForms, the luxury of pretending to behave like a Windows Form comes at a price. The ViewState is a reliable way of storing all of the state information for the form. Unfortunately, due to the limitations of the web, this data needs to be a giant string inside of a hidden form field. This ends up adding a substantial number of bytes to the page, making it slower and requiring extra bandwidth. Of course the ViewState is controllable, much like the dinosaurs in Jurassic Park.

Not only is the ViewState gone, but “mystery” generated HTML is also gone. You have strict control over the HTML. This gives you great power, but with great power comes great responsibility. Use it wisely, and you will have elegant XHTML output with no surprises. You need to really know your HTML, which in today’s web world is a prerequisite anyway.

PRO – Faster server-side

It’s hard to get any real performance data about MVC, but it’s been suggested that it’s potentially 8000 times faster. Supposedly it’s due to less processing since it simply processes a “template” instead of having to build a complicated control tree. Even if it’s twice as fast, or even marginally faster, that would be significant for popular sites, or give at least a slight boost to smaller sites.

PRO – Simplified model for multiple related views

Easier to do with MVC was to have multiple versions of a page that displayed the same data, but in a slightly different format. For example, on my RSS package tracking website, you can look at your tracking information in a full-featured desktop browser, a mobile browser, or an RSS reader. The data being displayed is always the same, but the actual rendered output was different. If I later want to make an iPhone specific version for example, I would simply make a new view, and use an existing controller action.

PRO – Unit testable

One of the biggest challenges with WebForms was that testing was difficult. Not only was the actual output not easy to test, but the code-behind would tend to be a place that would contain important code that would never get unit tested. With both MVC and WebForms, it’s best to keep your logic away from the page, but it’s not always easy or ideal. MVC makes it simple to unit test the logic that is specific to a page. To do so, you simply test the actions in your controllers, which are regular, easy to test classes.

CON – Difficult to convert an existing site

MVC is not only a framework in this case, but a style. It is possible to convert specific pages as needed, but the cost is high. The problem is that MVC is radically different, so the benefit of converting probably isn’t worth it for most of your existing pages.

If you decide to convert your site to MVC, you may also run into issues trying to maintain existing page addresses. The specific issue I’ve ran into is that routes cannot have a trailing slash. If you want to maintain existing URL’s that have trailing slashes, there is no way to have the built-in routing generate URL’s with a trailing slash. You may end up losing one of the big advantages that MVC has to offer.

CON – Not best for SEO out of the box

The routing engine likes to allow multiple addresses to render the same page, instead of enforcing a single address for each page. You can use a URL rewrite engine to bend it to your will. I highly recommend spending some time writing intelligent rules that perform the necessary 301 redirects, because you don’t want to take chances with SEO (Search Engine Optimization).

CON – Challenges if you’re not running IIS7

It’s clear that the last couple of versions of IIS have been major improvements over their predecessors. IIS7 takes .NET integration to an entirely new level. There is already a good page that covers the challenges you’ll face if you’re not running IIS6. I’ll just list them here for brevity:

  • .NET needs to handle all page requests to ensure that the MVC pages will be processed. This leads to bad performance of static files.
  • HTTP Compression through IIS6 doesn’t work, because the MVC pages are dynamic.
  • The homepage gives a 404 when hosted on the root of a domain.

MVC History

Tags

,

Asp.Net MVC1

  1. Released on Mar 13, 2009
  2. Runs on .Net 3.5 and with Visual Studio 2008 & Visual Studio 2008 SP1
  3. MVC Pattern architecture with WebForm Engine
  4. Html Helpers
  5. Ajax helpers
  6. Routing
  7. Unit Testing

Asp.Net MVC2

  1. Released on Mar 10, 2010
  2. Runs on .Net 3.5, 4.0 and with Visual Studio 2008 & 2010
  3. Strongly typed HTML helpers means lambda expression based Html Helpers
  4. Templated Helpers
  5. Support for Data Annotations Attribute
  6. Client-side validation
  7. UI helpers with automatic scaffolding & customizable templates
  8. Attribute-based model validation on both client and server
  9. Overriding the HTTP Method Verb including GET, PUT, POST, and DELETE
  10. Areas for partitioning a large applications into modules
  11. Asynchronous controllers

Asp.Net MVC3

  1. Released on Jan 13, 2011
  2. Runs on .Net 4.0 and with Visual Studio 2010
  3. The Razor view engine
  4. Improved Support for Data Annotations
  5. Remote Validation
  6. Compare Attribute
  7. Sessionless Controller
  8. Child Action Output Caching
  9. Dependency Resolver
  10. Entity Framework Code First support
  11. Partial-page output caching
  12. ViewBag dynamic property for passing data from controller to view
  13. Global Action Filters
  14. Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
  15. Use of NuGet to deliver software and manage dependencies throughout the platform
  16. Good Intellisense support for Razor into Visual Studio

Asp.Net MVC4

  1. Released on Aug 15, 2012
  2. Runs on .Net 4.0, 4.5 and with Visual Studio 2010SP1 & Visual Studio 2012
  3. ASP.NET Web API
  4. Enhancements to default project templates
  5. Mobile project template using jQuery Mobile
  6. Display Modes
  7. Task support for Asynchronous Controllers
  8. Bundling and minification
  9. Support for the Windows Azure SDK

Asp.Net MVC5

  1. Released on 17 October 2013
  2. Runs on .Net 4.5, 4.5.1 and with Visual Studio 2013
  3. One Asp.Net
  4. Asp.Net Identity
  5. ASP.NET Scaffolding
  6. Authentication filters – run prior to authorization filters in the ASP.NET MVC pipeline
  7. Bootstrap in the MVC template
  8. ASP.NET Web API2

VS 2008 Solution Explorer Autohide

Tags

, , , , , , ,

In Visual Studio 2008,

I lost AutoHide feature on that window. when I right click on Solution explorer I see that AutoHide is disabled.

How can I enable it.

 2) Also I like all my autohide windows on left hand. how can I move right hand windows to left hand like resource view.

Solution:

Two things you can try:

1. Window->ResetWindow Layout

2. Tools->Import and Export Settings… Reset All Settings (Whether you save the current settings or not is your choice).

Memory Leak in CLR

Tags

, , , , , , , , ,

Definition of memory leak

A memory leak occurs when memory is allocated in a program and is never returned to the operating system, even though the program does not use the memory any longer. The following are the four basic types of memory leaks:

  • In a manually managed memory environment: Memory is dynamically allocated and referenced by a pointer. The pointer is erased before the memory is freed. After the pointer is erased, the memory can no longer be accessed and therefore cannot be freed.
  • In a dynamically managed memory environment: Memory is disposed of but never collected, because a reference to the object is still active. Because a reference to the object is still active, the garbage collector never collects that memory. This can occur with a reference that is set by the system or the program.
  • In a dynamically managed memory environment: The garbage collector can collect and free the memory but never returns it to the operating system. This occurs when the garbage collector cannot move the objects that are still in use to one portion of the memory and free the rest.
  • In any memory environment: Poor memory management can result when many large objects are declared and never permitted to leave scope. As a result, memory is used and never freed.

When it occurs?

Because of the garbage collection package that is implemented in the Microsoft .NET Framework, it is not possible to have a memory leak in managed code. This suggests two questions: How then can a memory leak occur? Why does it appear that you have a memory leak?

A memory leak can occur in a .NET Framework application when you use unmanaged code as part of the application. This unmanaged code can leak memory, and the .NET Framework runtime cannot address that problem.

Additionally, a project may only appear to have a memory leak. This condition can occur if many large objects (such as DataTable objects) are declared and then added to a collection (such as a DataSet). The resources that these objects own may never be released, and the resources are left alive for the whole run of the program. This appears to be a leak, but actually it is just a symptom of the way that memory is being allocated in the program.

If a collection is declared at the global level of the program, and objects are declared throughout the program and added to that collection, this means that even though the objects are no longer in scope, the objects remain alive because they are still being referenced.

Each time that this occurs, the amount of memory that the program is using increases. The memory does not decrease until the end of the program or the release of the objects from the collection. When you watch the program on a performance monitor, this appears to be a memory leak, but it is not. The program still has control over the memory but has chosen not to release it. The fact that the program still has control prevents this from being a memory leak, but the fact that the program keeps increasing the amount of memory used can make it appear to be a memory leak.

ISNULL vs. COALESCE

Tags

, ,

ISNULL()

ISNULL is a TSQL Function which is built into SQL Server. It is NOT a function defined by ANSI-92 – rather it is a feature which Microsoft has elected to include in TSQL in addition to the ANSI SQL standard.

ISNULL() accepts two parameters. The first is evaluated, and if the value is null, the second value is returned (regardless of whether or not it is null). The following queries will return the second parameter in both cases:

SELECT ISNULL(NULL, 1)
--Returns 1
SELECT ISNULL(NULL, NULL)
--Returns NULL

COALESCE()

COALESCE() is a TSQL function which, like ISNULL, is built into SQL Server. Unlike ISNULL, COALESCE is also a part of the ANSI-92 SQL Standard. Coalesce returns the first non-null expression in a list of expressions. The list can contain two or more items, and each item can be of a different data type. The following are valid examples of COALESCE:

SELECT COALESCE(NULL, 1)
--Returns 1

SELECT COALESCE(NULL, 3, NULL, 1)
--Returns 3
ISNULL vs. COALESCE

Whenever multiple methods exist for addressing a single problem, the inevitable question is: which method is better? There are a few differences between the two functions which make COALESCE come out on top more often than not:
– COALESCE is ANSI-92 compliant. In the event that you need to port your code to another RDBMS, COALESCE will not require rework.
– COALESCE accepts greater than two expressions, whereas ISNULL accepts only two. In order to compare three expressions with ISNULL, you would have to nest expressions:
SELECT ISNULL(ISNULL(Col1, Col2), Col3)
– ISNULL constrains the result of a comparison of parameterrs to the datatype of the first value. For example, the following query will produce some often undesirable results using ISNULL, however it will behave as expected with COALESCE:

DECLARE @Field1 char(3), @Field2 char(50)
SET @Field2 = 'Some Long String'

SELECT ISNULL(@Field1, @Field2)
--Returns 'Som'
SELECT COALESCE(@Field1, @Field2)
--Returns 'Some Long String'

Note: In other situations, COALESCE will produce unexpected results. COALESCE by nature promotes it’s arguments to the highest datatype among compatable arguments (arguments which are not explicitly case, and which aren’t compatable, will of course throw an error). When using COALESCE on an integer and a datetime, in that order, COALESCE will cast the integer as a datetime.

For example:
SELECT COALESCE(5, GETDATE())
Will not return 5, it will return 1900-01-06 00:00:00.000 (5 as a datetime). 

ISNULL vs. COALESCE

Whenever multiple methods exist for addressing a single problem, the inevitable question is: which method is better? There are a few differences between the two functions which make COALESCE come out on top more often than not:
– COALESCE is ANSI-92 compliant. In the event that you need to port your code to another RDBMS, COALESCE will not require rework.
– COALESCE accepts greater than two expressions, whereas ISNULL accepts only two. In order to compare three expressions with ISNULL, you would have to nest expressions:
SELECT ISNULL(ISNULL(Col1, Col2), Col3)
– ISNULL constrains the result of a comparison of parameterrs to the datatype of the first value. For example, the following query will produce some often undesirable results using ISNULL, however it will behave as expected with COALESCE:

DECLARE @Field1 char(3), @Field2 char(50)
SET @Field2 = 'Some Long String'

SELECT ISNULL(@Field1, @Field2)
--Returns 'Som'
SELECT COALESCE(@Field1, @Field2)
--Returns 'Some Long String'

Note: In other situations, COALESCE will produce unexpected results. COALESCE by nature promotes it’s arguments to the highest datatype among compatable arguments (arguments which are not explicitly case, and which aren’t compatable, will of course throw an error). When using COALESCE on an integer and a datetime, in that order, COALESCE will cast the integer as a datetime.

 For example:
SELECT COALESCE(5, GETDATE())
Will not return 5, it will return 1900-01-06 00:00:00.000 (5 as a datetime).

 
source:
 http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ISNULL_COALESCE&referringTitle=Homeb

Finding Duplicates in a Table

Tags

, , , , ,

Here’s a handy query for finding duplicates in a table. Suppose you want to find all email addresses in a table that exist more than once:

SELECT email,
 COUNT(email) AS NumOccurrences
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )

You could also use this technique to find rows that occur exactly once:

SELECT email
FROM users
GROUP BY email
HAVING ( COUNT(email) = 1 )
For further reading:
http://support.microsoft.com/default.aspx?scid=kb;en-us;139444
http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DuplicateRows&referringTitle=Home