Sai Stuff to Developers

December 4, 2012

Unobtrusive Validation in Framework 4.5 Data Validations

Filed under: DotNet — tosaik @ 7:41 am
Tags: , , , , ,

Today I was working on ASP.NET web application on framework 4.5; I came across a strange error which I never experienced in my past working on earlier environments of dot net framework and that is error titled

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for ‘jquery’. Please add a ScriptResourceMapping named jquery(case-sensitive).

When I dig in to this issue and found the root cause of this issue and here my case study about this issue…

Unobtrusive Validation is a new concept in Framework 4.5, and this is by default enables when we create a new ASP.NET web application by adding one of the key in a Web.Config->appsettings section as below

 <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />

What exactly this validation does for us

Forms with complex data including validators tend to generate too much JavaScript code in the page, which can represent about 60% of the code. With unobtrusive validation enabled, your HTML code will look cleaner and tidier.

For example we will compare the HTML code generated by both configurations.

Case-1:

Steps to create the sample application without unobtrusive validation enabled (default for all earlier versions)

1)      Open Visual studio 2012 IDE and create a new Web Application as shown below

UV1

 

 

 

 

 

 

 

 

2)      Now Press F5 to start the web application.

3)      Right-click on the browser page, and select View Source option to open the HTML code generated by the application.

4)      Scroll through the page source code and notice that ASP.NET has injected JavaScript code in the page to perform the validations and show the error list.

UV2

5)      Select the Script tab and expand the “{your current page}.aspx” combo to see all the referenced scripts. Notice that there are no references to the jQuery library. The validations are performed using the Microsoft Ajax Libraries together with JavaScript code injected within the page.

Case-2:

Steps to create the sample application with unobtrusive validation enabled (default for all new version(s))

1)      Now you will enable unobtrusive validation. Open Web.Config and locate ValidationSettings:UnobtrusiveValidationMode key in the AppSettings section. Set the key value to WebForms.

<appSettings>
    <add key="aspnet:uselegacysynchronizationcontext" value="false" />
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms"/>
</appSettings>

2) Open the Global.asax.cs file and add the following using statement

using System.Web.SessionState;
using WebFormsLab.Model;
using System.Web.ModelBinding;

3)      Within the Application_Start method of the Global.asax.cs file, add the following code

ScriptResourceDefinition myScriptResDef = new ScriptResourceDefinition();
myScriptResDef.Path = "~/Assets/Scripts/jquery-1.7.1.min.js";
myScriptResDef.DebugPath = "~/Assets/Scripts/jquery-1.7.1.js";
myScriptResDef.CdnPath = "http://code.jquery.com/jquery-1.7.1.min.js";
myScriptResDef.CdnDebugPath = "http://code.jquery.com/jquery-1.7.1.js";
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", null, myScriptResDef);

4)      Open Site.Master. Add the code below to include a ScriptManager on the page to include a script reference to the jQuery client library.

<form runat="server">
<asp:ScriptManager ID="uxScriptManagerMasterPage" runat="server" EnableCdn="False">
<Scripts>
    <asp:ScriptReference Name="jquery" />
</Scripts>
</asp:ScriptManager>


5)      Now Press F5 to start the web application.

6)      Right-click on the browser page, and select View Source option to open the HTML code generated by the application. Notice that by enabling the unobtrusive validation ASP.NET has replaced the injected JavaScript code with data- *attributes.

UV3

Don’t want this feature enabled?

Simply add the following setting in your AppSettings section in your web.config if it doesn’t exist. If already exist make value as “none” as shown below

 <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

Conclusion:

With Unobtrusive validation we reduce the unnecessary JavaScript code generation for all validation controls by asp.net runtime. As if we enable this validation the asp.net runtime by default get and use the jquery environment to perform these validations through this we can have least overhead of unwanted JavaScript code in our HTML page and it also effect the improvement in the performance and take less time in rendering and loading your pages.

I Hope you got advantage of this article…

Please drop a comment if you like it…

Thanks Happy Coding  🙂

Advertisements

October 22, 2012

Download: Visual Studio Express 2012

Filed under: DotNet — tosaik @ 11:02 am
Tags: , , , ,

Visual Studio Express 2012(Free)

Microsoft Visual Studio Express 2012 for Web is a free and robust development environment for building, testing, and deploying web applications across the Microsoft Web Platform. After installation, you can try this product for up to 30 days. You must register to obtain a free product key for ongoing use after 30 days.

Download Here

Visual Studio 2012 Express for Windows Desktop(Free)

You can use Visual Studio Express 2012 for Windows Desktop to build powerful desktop apps in C#, Visual Basic, and C++. You can target client technologies such as Windows Presentation Foundation (WPF), Windows Forms, and Win32. After installation, you can try this product for up to 30 days. You must register to obtain a free product key for ongoing use after 30 days.

Download Here

Happy Coding 🙂

September 20, 2012

Using jQuery allowing Only Alphanumeric Characters in a Textbox

Filed under: jQuery — tosaik @ 7:41 am
Tags: , , , ,

Requirement

Need to restrict the users by entering other than Alphanumeric Characters, if any user enters Non- Alphanumeric Characters then need to trim those Characters and display a message beside the respective textbox saying only Alphanumeric Characters are allowed…

 

Solution:

We have many solutions but using jQuery is the best way to achieve, with this we can use more flexible and reliable Regular expression technology with jQuery to achieve the above requirement.

 

Script Code:

 
 $(function () {

            $("#span_txtFirstName").hide();

            $("[id*='txtFirstName']").keyup(function () {

                $("#span_txtFirstName").hide();

                if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
                    this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
                    $("#span_txtFirstName").toggle(500);
                }
            });

HTML Code:

 
<asp:TextBox ID="txtFirstName" runat="server" Width="200px" CssClass="styled_input"></asp:TextBox>
<span id="span_txtFirstName" class="RegistrationNumericDiv">oops! Only AlphaNumberic Charecters are Accepted.</span>

Explanation:

In the above HTML Code is the normal code as I used asp.Net TextBox control to present this demo, but we can use any technology here as our browser parser can understand only HTML tags so every technology has their own parser to parse their respective language code to HTML code. Next line we have a SPAN tag which is used to hold the message to the user whenever user types a non-alphanumeric character in the respective textbox and this SPAN tag hide/show will be handled in the given jQuery code itself.

As we can see we use the regular expression to validate each character enter by the user and if anything wrong we replace those character(s) with empty string (‘’) and we show the message by toggling the  SPAN tag..

That’s it we are done with our requirement J

Thank you

Happy Coding J

July 31, 2012

Microsoft delivering Windows Phone Mango toolkit for Silverlight developers

Filed under: Mobile Apps — tosaik @ 6:23 am
Tags: ,

Great News !!!

Microsoft delivers Windows Phone Mango toolkit for Silverlight developers

Microsoft is continuing to inch toward the roll-out of Mango, the next version of its Windows Phone operating system. The company just made available to developers a new Silverlight toolkit for the Mango release.

With just a few days left before Windows Phone developers can submit their “Mango” applications for inclusion in the Windows Phone Marketplace, Microsoft is making a new toolkit for Silverlight coders available.

Microsoft made available for download the Silverlight for Windows Phone Toolkit add-on for the Windows Phone 7.1 SDK (software development kit) on August 17. The Mango 7.1 SDK is currently in beta, with a Release Candidate due in “late August,” according to the Softies.

In a new post on the Windows Phone developer blog, Microsoft officials said the toolkit will include user interface controls with components like toggle switches, page transitions, picker controls and more. Microsoft also has localized the toolkit into all the languages which will be supported by Mango.

Microsoft officials said recently that the Windows Phone Marketplace will be open for Mango application submissions on August 22. Earlier this week, Microsoft officials provided more guidance about how developers should think about transitioning their Windows Phone apps for Mango.

Microsoft and its OEM partners are expected to begin rolling out new Windows Phone 7.5 handsets preloaded with Mango (Windows Phone OS 7.1) this fall.

Mango adds a number of new features to the Windows Phone operating system, including third-party multitasking, Twitter integration, new Bing audio and visual search capabilities and more.

Source: http://dot-net-developers.blogspot.in

May 3, 2012

Converting DataTable to a List of Entity Object

Filed under: DotNet,LINQ — tosaik @ 12:30 pm
Tags: , , , , ,

Recently some one asked me how should i need to convert a DataTable to an List of Entity Object. Let me Explain in detail below…

Let say we have following Entity Class called Testimonial with two properties i.e.., Comment and Commentedby here Comment is the property where we have the actual comment by the User and Commentedby is the property to store the name of the User who commented it.

 public class Testimonial
    {
        public string Comment { get; set; }
        public string Commentedby { get; set; }
    }

Now we need to get these Testimonial data from data source it may be from Database / XML file / CSV File etc.., we use XML file for this example . Now using linq we Enumerate the collection of dataRows in the datatable and create a list of Testimonials as shown below

List<Testimonial> lstTestimonial = new List<Testimonial>();

 string strpath = System.IO.Path.Combine(AppDomain.CurrentDomain.GetData(“DataDirectory”).ToString(), “Testimonials.xml”);
            DataSet ds = new DataSet();
            ds.ReadXml(strpath);

            if (ds != null && ds.Tables.Count > 0)
            {
                lstTestimonial = (from r in ds.Tables[0].AsEnumerable()
                                  select new Testimonial
                                  {
                                      Comment = r.Field<string>(“Comment”),
                                      Commentedby = r.Field<string>(“Commentedby”)
                                  }).ToList<Testimonial>();
            }

Note this is the best way to convert because due to strong data-type using Field Method, we can rectify any type conversion issues at Compile time.

Hope this short explanation (due to insufficient time) Helps you… Please comment me in any case…

Happy Coding 🙂

 

 

Blog at WordPress.com.

%d bloggers like this: