Monday, June 27, 2011

ASP.NET MVC(Model-VIew-Controller) Overview architecture

The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.
MVC design pattern

mvc_DesignPatternMVC is a standard design pattern that many developers are familiar with. Some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern that is based on Web Forms and postbacks. Other types of Web applications will combine the two approaches; neither approach excludes the other.
The MVC framework includes the following components:
  • Models. Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.
    In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a dataset and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the dataset takes on the role of a model object.
  • Views. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Product object.
  • Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.
The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic.
The loose coupling between the three main components of an MVC application also promotes parallel development. For example, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model.
In addition to managing complexity, the MVC pattern makes it easier to test applications than it is to test a Web Forms-based ASP.NET Web application. For example, in a Web Forms-based ASP.NET Web application, a single class is used both to display output and to respond to user input. Writing automated tests for Web Forms-based ASP.NET applications can be complex, because to test an individual page, you must instantiate the page class, all its child controls, and additional dependent classes in the application. Because so many classes are instantiated to run the page, it can be hard to write tests that focus exclusively on individual parts of the application. Tests for Web Forms-based ASP.NET applications can therefore be more difficult to implement than tests in an MVC application. Moreover, tests in a Web Forms-based ASP.NET application require a Web server. The MVC framework decouples the components and makes heavy use of interfaces, which makes it possible to test individual components in isolation from the rest of the framework.
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.
The ASP.NET MVC framework provides the following features:
  • Separation of application tasks (input logic, business logic, and UI logic), testability, and test-driven development (TDD). All core contracts in the MVC framework are interface-based and can be tested by using mock objects, which are simulated objects that imitate the behavior of actual objects in the application. You can unit-test the application without having to run the controllers in an ASP.NET process, which makes unit testing fast and flexible. You can use any unit-testing framework that is compatible with the .NET Framework.
  • An extensible and pluggable framework. The components of the ASP.NET MVC framework are designed so that they can be easily replaced or customized. You can plug in your own view engine, URL routing policy, action-method parameter serialization, and other components. The ASP.NET MVC framework also supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models. DI enables you to inject objects into a class, instead of relying on the class to create the object itself. IOC specifies that if an object requires another object, the first objects should get the second object from an outside source such as a configuration file. This makes testing easier.
  • Extensive support for ASP.NET routing, which is a powerful URL-mapping component that lets you build applications that have comprehensible and searchable URLs. URLs do not have to include file-name extensions, and are designed to support URL naming patterns that work well for search engine optimization (SEO) and representational state transfer (REST) addressing.
  • Support for using the markup in existing ASP.NET page (.aspx files), user control (.ascx files), and master page (.master files) markup files as view templates. You can use existing ASP.NET features with the ASP.NET MVC framework, such as nested master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding, localization, and so on.
  • Support for existing ASP.NET features. ASP.NET MVC lets you use features such as forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture.

Wednesday, June 15, 2011

Detecting changes in web form or web pages (Dirty Form) using JQuery Plugins

Hi ,

If you want to give a alert mesage to user's while you naivagate away from one page to other page or any where. Then you need to use Dirty Form using Jquery.
If we use this plugin then we can prevent loss of any unsaved data from your web form.

This functinality invoke while 
1. Click on menu items
2. Back button,forward button
3. And any other action which will navigate away from your current page.

It will detect the changes happend in your web form and give an prompt message for user like you have some unsaved data .you want to navigate from here or not ?

Using this  task user may not loss any kind of data.


JQuery has a set of plug-ins which helps in watching the form for modifications and notifying the user when he navigates away from a webpage so that user will not lose unsaved information.

a)      LiveQuery: This plug-in helps in handling the dynamic updates scenario on the webpage. So even if DOM is manipulated using DHTML techniques, the     changes in the form values will be properly tracked.Live Query (formerly Behavior) utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.

Example :    $('a')
    .livequery('click', function(event) {
        alert('clicked');
        return false;
    });

b)      DirtyForm:
This is a project for watching containers of inputs and notifying the user of unsaved changes.This plug-in actually does the task of     tracking changes to form values.Dirty Forms is a flexible jQuery plugin to help prevent users from losing data when editing forms.

Dirty Forms will alert a user when they attempt to leave a page without submitting a form they have entered data into. It alerts them in a modal popup box, and also falls back to the browser’s default onBeforeUnload handler for events outside the scope of the document such as, but not limited to, page refreshes and browser navigation buttons.

Oh, and it’s pretty easy to use.
$('form').dirtyForms();


Sample webpage (How to use Dirty Flag)

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Index</title>

    <!-- Step1 -->

    <!-- Reference to core JQuery library -->

    <script src="../../Scripts/jquery-1.4.2.js" type="text/javascript"></script>

    <!-- Reference to dirty form JQuery plug-in -->
    <script src="../../Scripts/jquery.dirtyform.js" type="text/javascript"></script>

    <!-- Reference to live query JQuery plug-in -->
    <script src="../../Scripts/jquery.livequery.js" type="text/javascript"></script>



    <script type="text/javascript">

       

        //Step2

        //Flag variable which helps in identifying whether any modifications have been done

        on the form

        var isDirty = false;
       

        //Step3

        //Intercepts any navigation away from webpage. This event handler will display alert

        message if there are unsaved changes on form

        window.onbeforeunload = function() {

            if (isDirty) {

                return 'You have unsaved changes on this page.';

            }

        }

        //JQuery ready function executes after the complete html DOM has been loaded in the

        web-browser

        $(document).ready(function() {

       

            //Step4

            //Configures Dirty form plugin to observe for changes on the form

            $("#myForm").dirty_form().dirty(function(event, data) {

                isDirty = true;

            });

             //Step5

            //Cancel button action navigates to a different webpage

            $("#btnCancel").click(function() {

                window.location.href = "http://www.google.com"

            });



            //Step6

            //Form submit handler. In this case we want to suppress the alert message.

            //The trick is to turn off the isDirty flag and then continue with post operation.

            $("#btnSubmit").click(function() {

                isDirty = false;

                return true;

            });

        });
      

    </script>

</head>

<body>

    <form id="myForm" action="" method="post">

        Message:

        <input type="text"/>

        <input type="submit" value="Submit" id="btnSubmit" />

        <input type="button" value="Cancel" id="btnCancel" />

        <!-- Clicking this hyperlink will alert user of any unsaved data on the form -->

        <a href="http://www.google.com">Goto Google</a>

    </form>

</body>

</html>


Steps followed in above sample are:

 Step1: Add references to core jquery library, livequery and dirty form jquery plug-ins

Step2: Use a global variable isDirty to track form changes

Step3: Use onbeforeunload event to trap navigations away from current webpage and notify user of unsaved changes.

Step4: Configure Dirty form plug-in to observe for changes on the form

Step5: Configure event handler for Cancel button

Step6: Configure event handler for Submit button to suppress alert message during submit operation

Sunday, June 12, 2011

A potentially dangerous Request.Form value was detected from the client

Everytime a user posts something containing < or > in a page in webapp, you will get this exception thrown.
so for this issue you need to  Put

1. validateRequest="false" in your page directive or web.config file.

The .NET framework is throwing up an error because it detected something in the entered text which looks like an HTML statement. The text doesn't need to contain valid HTML, just anything with opening and closing angled brackets ("<...>").
The reason behind the error is as a security precaution. Developers need to be aware that users might try to inject HTML (or even a script) into a text box which may affect how the form is rendered. For further details see www.asp.net/learn/whitepapers/request-validation/.


In your web.config file

2. <httpRuntime requestValidationMode="2.0"/>
<configuration>
    <system.web>
        <pages validateRequest="false" />
    </system.web>
</configuration>
 
3.  
[Post, ValidateInput(false)]
public ActionResult Edit(string message) {
    ...
} 
4.
[AcceptVerbs(HttpVerbs.Get)]
[ValidateInput(false)]
public ActionResult List(string message)
{
}
If you are using MVC3.0 you can use [AllowHtml]
public class XMLModel
    {
        [AllowHtml]
        public string msg { get; set; }
    }
 
Thanks

Saturday, June 11, 2011

Speeding Up jQuery Javascript & CSS Download Times

Now-days, jQuery are becoming so popular in client-side of web development. jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML. jQuery itself is composed by "one" file called jquery-x.x.x.min.js. With only one Javascript there is no performance problem. But with jQuery has been appeared some "addons/plugins" that uses this library. An example could be jQueryUI http://jqueryui.com/ but more can be found at http://plugins.jquery.com/. Each of these addons contain their own Javascript file. For example jQueryUI contains apart from jQuery file, jquery-ui-x.x.x.custom.min.js and one CSS file, so in this case in a web page two Javascript and a CSS elements are defined. As more and more extensions are used, more Javascript files are required. And more scripts imply more connections to server, so for example if three Scripts and one CSS are defined, four connections from browser to server are required.

Because of these amounts of connections, downloading time is increased; content negotiation and the fact that normally there will be only two concurrent connections to the same host, produces an overhead that results in a long page loading time. For example, it is faster to serve a 8KB script file than  eight of 1KB.

Jquery Dialog events and methods - how to use those methods.

Hi All,

The jQuery UI framework offers up a functional Dialog widget that allows resizing and also the ability to display forms. The basic dialog window is an overlay positioned within the viewport and is protected from page content (like select elements) shining through with an iframe. It has a title bar and a content area, and can be moved, resized and closed with the ‘x’ icon by default.
for creating a dialog :

$("#DivID").dialog({
autoOpen: false,
height: 270,
width: 550,
modal: true,
title: 'Name of the title',
draggable: true,//You can drag any where on a page
resizable: false,//Size can be increase or decrease.
closeOnEscape: false//while press Escape button
});

This is simple dialog properties.

1. pass it as parameter in dialog is used for hiding close (x) in dialog:
open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); }
Another method for hidinh close(x)button in right corner is

$("#DivID").dialog().parent('.ui-dialog').find('.ui-dialog-titlebar-close').hide();

2.We have event Close event , while colse the dialog is there any functnality you want then you need to pass like

$('#DivID').dialog({
close: function(event, ui) {
var urlString1 = '<%=Url.Action("Action", "Controller") %>';
var urlString = urlString1;
urlString = Url.decode(urlString);
urlString = String.format(urlString);
try { location.href = urlString; } catch (e) { }
}});

3. We have event beforeclose

$("#DivID").dialog({
beforeclose: function(event, ui) {
if (cancel == false) {
if (dirtyFlag == true) {
return any URL or some thing.
}
}
}
});

If you want to some more information please refer :
jQuery UI Dialog

Thanks.

Jquery dynamic validation for Phone,ZipCode,Pager and Fax. 9/5 digit validate for Zipcode US .

Hi All,
If you want validate your Zipcode,phone or fax number as per US rule.
Because phone number has 10 digit and zipcode has total 9 digit.but 5 digit also valid zip number in US.
So we need to validate both(All)the scenario.
If you will used masked(Masking) input for this type of input that's very good for you.

================================================

jQuery.validator.addMethod("ZipCodeRule", function(zip) {
var i;
for (i = 1; i <= 9; i++) { zip = zip.replace(/([_])/, ""); } if (zip.length == 0 || (zip.length == 1 && zip.charAt(0) == "-") || zip.match(/^\d{5}([- ]?\d{4})?$/) || zip.match(/^\\d{5}$/) || zip.length == 6) { return true; } return false; }, "Enter valid Zip Code");

================================================

/*If Phone is not mandatory*/ jQuery.validator.addMethod("PhoneNumberRule", function(Phone, element) { Phone = Phone.replace(/\s+/g, ""); for (i = 1; i <= 10; i++) { Phone = Phone.replace(/([_])/, ""); } if (Phone.length == 0 || (Phone.length == 3 && Phone.charAt(1) == ")")) return true; else return this.optional(element) || Phone.length > 9 &&
Phone.match(/^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$/);
}, "Enter Valid Phone Number");

================================================

/*If FaxNumber is not mandatory*/
jQuery.validator.addMethod("FaxNumberRule", function(Fax, element) {
Fax = Fax.replace(/\s+/g, "");
for (i = 1; i <= 10; i++) { Fax = Fax.replace(/([_])/, ""); } if (Fax.length == 0 || (Fax.length == 3 && Fax.charAt(1) == ")")) return true; else return this.optional(element) || Fax.length > 9 &&

Fax.match(/^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$/);
}, "Enter Valid Fax Number");

================================================

/*If Pager is not mandatory*/
jQuery.validator.addMethod("PagerNumberRule", function(Pager, element) {
Pager = Pager.replace(/\s+/g, "");
for (i = 1; i <= 10; i++) { Pager = Pager.replace(/([_])/, ""); } if (Pager.length == 0 || (Pager.length == 3 && Pager.charAt(1) == ")")) return true; else return this.optional(element) || Pager.length > 9 &&
Pager.match(/^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$/);
}, "Enter Valid Pager Number");

================================================


Thanks

split function for more than one parameter...

Hi All,

As you know that we have split function for split based on a particular character
Like
string str="This is very good string and every | bode can use it"

//string strPhrase = child.Phrase.Split('|');
Then it will give two values.
But suppose I have string like this
string str="This is very good string and every || bode can use it"
Now in this happened we will get three string's because we can not split this string based on || this .
for multiple charcter split you need to use this type of method
string str="This is very good string and every bode can use it"

string[] strPhrase = str.Split(new string[1] { "{every}" },StringSplitOptions.None);
string str1= strPhrase[0];

if this is not working then use this one

string[] res = str.Split(new string[] { "every" }, StringSplitOptions.None);
string str1 = res[1];

Now in this time we will retrieve two string after split based on "every".

Thanks

XMl Parsing Error Resolved special character & , ', %,$ #,<>

Hi All,
this is very good idea to resolving to this type of error. you do not need to convert to all the characters into some other to HTML user friendly character.
Some time what happend if you are using <,>,%,& ' this character this given a lot of problem while parsing XML.
This is a very simple method (trick)to resolved this issue.

You need to pass your values inside ![CDATA[{ANY CHARACTER YOU WANT}]]
this should be passed between angular brackets < and >.

Thanks