Sunday, December 9, 2012

Check if Checkbox is checked using jQuery

to find out if checkbox is checked or not using jQuery. I was knowing one way to find out but there are couple of other ways as well to find out if checkbox is checked using jQuery. In this post, you will find all different possible ways.

1. First Way:

Below single line of code will provide the status of checkbox using jQuery. It checks whether the checked is checked or not using jQuery and will return 1 or 0.

1var isChecked = $('#chkSelect').attr('checked')?true:false;
I have noticed that on many website it is written that 'checked' attribute will return true or false, but this is not correct. If the checked box is checked then it return status as "checked", otherwise "undefined".

2. Second Way
1var isChecked = $('#chkSelect:checked').val()?true:false;

3. Third Way
1var isChecked = $('#chkSelect').is(':checked');
The above method uses "is" selector and it returns true and false based on checkbox status.

4. Fourth Way

The below code is to find out all the checkbox checked through out the page.
2    function() {
3       // Your code goes here...
4    }
Feel free to contact me for any help related to jQuery, I will gladly help you.

Find Current Location of Data and Log File of All the Database and get size of databases

Some time for carring data from one machine to another machine we need to copy database file

for that we need to copy database ldf and mdf file becaues this is eassiest way yo carring database. for this  we must be know the these db files are where is located on server so we can copy this.

First way to write this query on our Query window

SELECT name, physical_name AS current_file_location
FROM sys.master_files

Second way to find the location with Appropriate database file size 

SELECT DB_NAME(mf.database_id) AS databaseName
FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS divfs
JOIN sys.master_files AS mf ON mf.database_id = divfs.database_id
AND mf.file_id = divfs.file_id

Third way to find database details with size in shortest form that you wanted to find

DB_NAME(mf.database_id) AS databaseName,
name as File_LogicalName,
when type_desc = 'LOG' then 'Log File'
when type_desc = 'ROWS' then 'Data File'
Else type_desc
end as File_type_desc
,size_on_disk_bytes/ 1024 as size_on_disk_KB
,size_on_disk_bytes/ 1024 / 1024 as size_on_disk_MB
,size_on_disk_bytes/ 1024 / 1024 / 1024 as size_on_disk_GB

FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS divfs
JOIN sys.master_files AS mf ON mf.database_id = divfs.database_id
AND mf.file_id = divfs.file_id
ORDER BY num_of_Reads DESC

Thursday, November 29, 2012

JavaScript function to get random number between a range

Getting random number in JavaScript

Code:  alert(Math.random())
Getting random number is very easy you can use JavaScript function random() of Math object to get the random number between 0 and 1. For example, above JavaScript statement returns a random number between 0 and 1.

JavaScript function to get random number between 1 and N

//function to get random number from 1 to n
function randomToN(maxVal, floatVal) {
    var randVal = Math.random() * maxVal;
    return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal);

As, you can see in the above JavaScript function, there are two parameters. One for the maximum value(N) up to which random number have to be generated. The second parameter is optional which specifies number of digits after decimal point.If not provided, this function returns integer.

JavaScript function to get random number between a range

    function GenerateRandom(min, max, floatVal) {
        var randVal = min + (Math.random() * (max - min));
        return typeof floatVal == "undifined" ? Math.round(randVal) : randVal.toFixed(floatVal);
The above JavaScript funciton accepts three parameters.The first and second parameter is mandatory while the third is optional. The first and second parameter specifies the range between which the random number has to be generated. The thir parameter is optional which specifies number of floating point digits, if not provided, the above JavaScript function returns integer random number.

Thursday, November 8, 2012

Xml data type is not supported in distributed queries. Remote object

I found one issue while coping records from latest version of sql to old version of 
sql where xml datatype is not supported using linked server while fetching records 
i found following error occurred
"Xml data type is not supported in distributed queries. Remote object 
   'Server1.dbMurli.dbo.TB_Murli' has xml column(s).
Root Cause :
- XML column can not be accessed directly from the remote server....
- Following is the table structure in Remote server and Local server
Column1  VARCHAR(10),
[Address] XML
Solution :
So, we can solve this issue as given below...
  [Addres] FROM dbMurli.dbo.TB_Murli')
)AS XUsign the "OPENQUERY" 
we can solve the issue...  
In Short :-  
XML is not supported in distributed queries. You could write a passthrough query with OPENQUERY, and cast the XML column to nvarchar(MAX). For instance:
SELECT cast(xmlcol as xml) FROM OPENQUERY(REMOTESVR, 'SELECT cast(xmlcol AS nvarchar(MAX)) FROM db.dbo.tbl')

Insert Records from one table to another table

Before records insertion from one table to another table we must need to aware of these steps

1. New table need to be create with data.
2. Table is exists but we need to copy all records.
3. Table is exists and we wanted to copy particular records on existing table.

How to copy records for all the above steps.

Note : - Consider we have tblSource with all records Ex:-
Create table tblSource(Id int Primary Key,Name varchar(50), Address varchar(100),Created datetime default getdate())
Insert into tblSource(Id,Name,Address) values (1,'Murli','Mumbai-Sanpada')
Insert into tblSource(Id,Name,Address) values (2,'Deepak','Mumbai-Vasai')
Insert into tblSource(Id,Name,Address) values (3,'Ajit','Mumbai-Thane')

1. New table need to be create with data when target table is not exists.
       Select * Into tblIntoSource from tblSource

2. Target table exists and i wanted to copy all the records from source table.
       Insert tblSourceCopy Select * from tblSource

3. Target table exists and i wanted to copy particular records on it... i have two option to do this.
  A. Using Into Command
       Insert into tblDest(Id,Name) Select Id,Name from tblSource

  B. Using Direct Insert Command
       Insert tblSourceCopy1(Id,Name) Select Id,Name from tblSource


Tuesday, October 30, 2012

Create Resource/Multilingual Files on your page.

To Add/Create multilingual site we need to do following changes on files

Steps :

1. Create Resource file with required keys and value that you wanted to change accordingly
2. Add Resource file name on your page property
3. Set the page UICulture and Culture info on page property
4. Add Meta Resource code where you wanted to populate on pages.

Example :

I have used here App_GlobalResource depend on my requirement.
1. Create resource file App_GlobalResources\baseres.resx on my root directory.
2. Added following changes on my page directory Culture="auto" meta:resourcekey="baseres" UICulture="auto"
3. and added lines of code on the page following ways
     <asp:Label ID="lblLanguage" runat="server" Text="<%$ Resources:baseres, Language %>" />  :
     <asp:Label ID="lblWord" runat="server" Text="<%$ Resources:baseres, Word %>" />

Note : Here Language and Word are my two keys that i mentioned on the my resource file i.e. baseres.resx file.

For Custom Google Convertor Download link . this project is i copied from one of good website. for more details of the linked project visit Click Me

Creating multilingual website (English / Hindi / Punjabi) using

This post will be some fun. We will learn how to create a multilingual website using A website so built that it will work in any language you choose. By any i mean any ! It works like magic. A click of a button and the whole experience of the visitor changes, as he is now being served content in the language he understands. This helps your website reach more potential customers, not only people who understand English.

What is the logic behind this ?

There are two ways to convert content written in one language into another. Translation and Transliteration. During translation we keep the meaning of the sentence intact. We convert a sentence in some other language which has the same meaning in that language. For example if i translate “I need to drink water” in some other language, then i would speak this sentence in that language by keeping the meaning intact. Transliteration is the practice of converting a text from one writing system into another in a systematic way. For example when you write a message in your local language by using English, you are doing transliteration.
When we change the language of the website from one language to another, we are neither doing translation nor doing transliteration ! We are simple reading content from different files and just displaying what ever is written in those files. The website or the browser has no information as to which language is being displayed. The website just reads the content from the file and displays it. Its your responsibility to write content in different languages and keep them in proper files. If you make a mistake in writing or arranging the content, the website will not be able to detect it. It would just display the content as it is, whether its right or wrong.

Lets create our multilingual site step by step

Fire up visual studio and create a new website. Once you have your website in the solution explorer, right click on the website and select Add folder option and create App_LocalResources folder. See the screen shot below:

Please notice that you need to select App_LocalResources folder, not App_GlobalResources folder. We created this folder because we will be storing our resource files in this folder. Resource files are the files in which we will add our data in the different languages.

Add a new web page to your website

Right click on your website and add a new web page. Lets name this page as MultiLingualPage.aspx. See the screen capture below:

Add a resource file to your project

What is a resource file and why is it needed ? Any project that you create have some resources associated with it. Your images, audio files, video files, text files etc that you use in your project are all known as resources for your project. In this particular case we need different files in which we will store our strings. I have created this multilingual website in English and Hindi. So i will create 2 resource files, one for English and the second one for Hindi. Microsoft has created .net to be culture sensitive. Many cultures in this world are supported by .net. When i say cultures i mean spoken languages. The default culture for .net is en-US, which is United State’s English. If we want to change the culture to Indian Hindi, we will write hi-IN. Similarly Indian Punjabi is supported, we will write pa-IN. All resource files are culture specific. If I add hi-IN to the name of the resource file, it will automatically be read by website when you change the website’s culture to Indian Hindi. I will demonstrate later how to change the culture of your website.
For now lets just add 2 resource files to our App_LocalResources folder. To add a resource file, right click on the App_LocalResources folder and select Add New Item. Select the Resource File option and click Add. Earlier when we created App_LocalResources folder i specifically said that do not create App_GlobalResources folder. There was a reason behind this. Local resources are page specific where as Global resources are website specific. This means that every aspx page in your web application will have its own Local Resource file. The name of the Local Resource file for every web page will be the same as that of the page. We created a web page by the name MultiLingualPage.aspx, so the Resource files for this page will also have the same name. See the screen shot below:

By default this resource file will be considered for en-US culture. Next lets add a new resource file for Indian Hindi culture. See the screen shot below:

Thus we have 2 resource files in the App_LocalResources folder, one for en-US culture and the second one for hi-IN culture.

But how will the website change its language ?

We display text using labels. This is how you add a label to your page.
Text=”Hello World”
> For this label you have fixed the text to “Hello World”, and that too in English. Now what ever you do you can not change the language for this label. Every time you run your website this label will display Hello World and that too in English. Now the trick to change the language for you website is not to provide text to your label directly. We will keep the actual text in our resource files and provide the key for that text to our label so that the label reads the text from the resource file and displays the text. Look at the highlighted code below :
Text=”<%$Resources:HelloWorld Text%>”
> The above line directs the label to refer to the local resource file for the page in which it is kept and read the string whose key is HelloWorldText. Any thing that will be written for this key in the resource file will be read and displayed as text for this label. Add the following to your English resource file:

Similarly for your Hindi resource file add the Hello World ! string in Hindi. See the screen shot below.

But my keyboard is in English. How can i write other languages ?

Well, Google is the answer. Google provides both translation and transliteration services. The demo site i have created contains text written in English and Hindi. I wrote the content in English and the used Google translation and transliteration both to get appropriate conversions. Below are the links for both these services.
Google Translation Service : Click here
Google Transliteration Service : Click here

Last step, how to change the culture for the website ?

Put an DropDownList on your web page and provide it the following markup:

This drop down list has two options, one for English and the second for Hindi. The value for English selection is en-US and that for Hindi selection is hi-IN. The user can choose the language of his choice from here and we will set the culture of the website accordingly. The code for changing the culture for the website will be added to the Global.asax file, in the Application_BeginRequest event. See below:
void Application_BeginRequest(Object sender, EventArgs e)
string culture = string.Empty;
foreach (string key in Request.Form.Keys)
if (key.Contains(“ddlChangeLanguage”))
culture = Request.Form[key];
System.Threading.Thread.CurrentThread.CurrentCulture =
System.Threading.Thread.CurrentThread.CurrentUICulture =
new System.Globalization.CultureInfo(culture);
In the above code we are checking the Request.Form collection for the value of the dropdownllist that the user selected. Request.Form collection stores data in key value pairs. The key is the Id of the control for which the data is brought back and the value if the value the user selected. Here we are searching for the value of ddlChangeLanguage control, as the name of our DropDownlList was ddlChangeLanguage. Don’t worry about the above code, i have provided all the code for this along with the demo of this post.

We are done !

Now finally when you will run your site the user will be displayed the label in English by default. Then when he selects Hindi language from the drop down, we change the culture of the website in the Application_BeginRequest event. We set the culture to hi-IN and the web page automatically reads the Hindi resource file and displays the text in Hindi. Below are the screen shots of the demo application for this post, both in English and in Hindi.

This is how it looks when Hindi language is selected.

And this is how it looks when Punjabi language is selected.

Simple and smooth. You can download the code for this multilingual website and run it on your system to understand it even better. I have tried to explain quite in detail, but you might not get the real feel unless you download and run the code by yourself. Please post your queries as comments to this post in case you could not understand the concept even after running the website on your local machine. I will reply to your queries and help you understand the concept. Check the following link to see this multilingual site in action and also for downloading the source code.
Hope the information provided in this post was useful. Please provide us your comments / suggestions / appreciations which would help us in providing even more useful posts on this blog. You can help us in sharing this information by clicking the facebook share button, facebook like button or the twitter tweet button below. Also you can share this information on social bookmarking sites by clicking the links under “Share this knowledge” section.
Thanks for reading.

Monday, October 29, 2012

MVC 3 with Razor client-side validation

To Validation client Side on MVC you need to follow these steps

1. My web.config file has the following entries.
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />

2.The _Layout.cshtml has the following scripts or Required pages where you wanted to validate fields

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

3. My partial class has the following
public partial class Address
        public class AddressMetaData
            [DisplayName("Address Line 1")]
            [Required(ErrorMessage = "Address Line 1 is required")]
            [StringLength(100, ErrorMessage="Maximum of 100 characters")]
            public object AddressLine1 { get; set; }

            [DisplayName("Address Line 2")]
            [Required(ErrorMessage = "Address Line 2 is required")]
            [StringLength(100, ErrorMessage = "Maximum of 100 characters")]
            public object AddressLine2 { get; set; }

            [DisplayName("Address Line 3")]
            [Required(ErrorMessage = "Address Line 3 is required")]
            [StringLength(100, ErrorMessage = "Maximum of 100 characters")]
            public object AddressLine3 { get; set; }
4. And my Edit.cshtml view is so 
@model Grid.PolicyLocation
ViewBag.Title = "Edit";
  Edit Location
@using (Html.BeginForm())
@Html.ValidationSummary("Please correct Errors")
<table class="noborder">
    <td class="noborder">
      @Html.LabelFor(model => Model.Address.AddressLine1)
    <td class="noborder">
      @Html.EditorFor(model => model.Address.AddressLine1)
      @Html.ValidationMessageFor(model => model.Address.AddressLine1)
    <td class="noborder">
      @Html.LabelFor(model => Model.Address.AddressLine2)
    <td class="noborder">
      @Html.EditorFor(model => model.Address.AddressLine2)
      @Html.ValidationMessageFor(model => model.Address.AddressLine2)
    <td class="noborder">
      @Html.LabelFor(model => Model.Address.AddressLine3)
    <td class="noborder">
      @Html.EditorFor(model => model.Address.AddressLine3)
      @Html.ValidationMessageFor(model => model.Address.AddressLine3)

5. If on blur validation not work then only add this code
$(document).ready(function () {
            $('input[type=text]').blur(function () {

Friday, October 26, 2012

MVC Interview Questions

What are the 3 main components of an ASP.NET MVC application?
1. M - Model
2. V - View
3. C - Controller

In which assembly is the MVC framework defined?

Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?
Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

What does Model, View and Controller represent in an MVC application?
Model: Model represents the application data domain. In short the applications business logic is contained with in the model.

View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.

Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.

What is the greatest advantage of using mvc over webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET Webforms?

What are the advantages of ASP.NET MVC?
1. Extensive support for TDD. With MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
4. ASP.NET MVC views are light weight, as they donot use viewstate.

Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?
Yes, all the features in an MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.

Is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.

What is the role of a controller in an MVC application?
The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.

Where are the routing rules defined in an MVC application?
In Application_Start event in Global.asax

Name a few different return types of a controller action method?
The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult

What is the significance of NonActionAttribute?
In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.

What is the significance of ASP.NET routing?
ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.

What are the 3 segments of the default route, that is present in an ASP.NET MVC application?
1st Segment - Controller Name
2nd Segment - Action Method Name
3rd Segment - Parameter that is passed to the action method

Controller Name = Customer
Action Method Name = Details
Parameter Id = 5

ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?
1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.

What is the adavantage of using ASP.NET routing?
In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users.

What are the 3 things that are needed to specify a route?
1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.
2. Handler - The handler can be a physical file such as an .aspx file or a controller class.
3. Name for the Route - Name is optional.

Is the following route definition a valid route definition?
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.

What is the use of the following default route?
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.

What is the difference between adding routes, to a webforms application and to an mvc application?
To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method.

How do you handle variable number of segments in a route definition?
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.

What are the 2 ways of adding constraints to a route?
1. Use regular expressions
2. Use an object that implements IRouteConstraint interface

Give 2 examples for scenarios when routing is not applied?
1. A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.

What is the use of action filters in an MVC application?
Action Filters allow us to add pre-action and post-action behavior to controller action methods.

If I have multiple filters impleted, what is the order in which these filters get executed?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters

What are the different types of filters, in an mvc application?
1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters

Give an example for Authorization filters in an mvc application?
1. RequireHttpsAttribute
2. AuthorizeAttribute

Which filter executes first in an mvc application?
Authorization filter

What are the levels at which filters can be applied in an mvc application?

1. Action Method
2. Controller
3. Application
[b]Is it possible to create a custom filter?[/b]

What filters are executed in the end?
Exception Filters

Is it possible to cancel filter execution?

What type of filter does OutputCacheAttribute class represents?
Result Filter

What are the 2 popular mvc view engines?
1. Razor
2. .aspx

What symbol would you use to denote, the start of a code block in razor views?

What symbol would you use to denote, the start of a code block in aspx views?
<%= %>

In razor syntax, what is the escape sequence character for @ symbol?
The escape sequence character for @ symbol, is another @ symbol

When using razor views, do you have to take any special steps to proctect your mvc application from cross site scripting (XSS) attacks?
No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks.

When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of master pages. What is master pages equivalent, when using razor views?
To have a consistent look and feel when using razor views, we can make use of layout pages. Layout pages, reside in the shared folder, and are named as _Layout.cshtml

What are sections?
Layout pages, can define sections, which can then be overriden by specific views making use of the layout. Defining and overriding sections is optional.

What are the file extensions for razor views?
1. .cshtml - If the programming lanugaue is C#
2. .vbhtml - If the programming lanugaue is VB

How do you specify comments using razor syntax?
Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end. An example is shown below.
@* This is a Comment *@

JQuery getJSON call to MVC Controller

This can happen if the data return by the controller method is violating JSON format. You can try the following-
  • Change ActionResult to JsonResult.
  • Add [AcceptVerbs(HttpVerbs.Get)] to Filter method.
  • Add {} as second paramenter of getJSON as it takes three parameter.
Its working fine with the following code-
    public JsonResult Filter()
       var myData = new[] { new { first = "Murli", last = "D" }, new { first = "Deepak", last = "Tripathi" } };
       return Json(myData, JsonRequestBehavior.AllowGet);
<script type="text/javascript">
    function () {
        "/Account/Filter", {}, 
        function (myData) {

Monday, October 22, 2012

Call PageMethod From JavaScript in ASP.NET Ajax

Most of time we need to call page method(server side code) by client side script(JavaScript) without post back. I will accomplish this using the Page Methods feature. To do this we are using ASP.Net Ajax. Using page method a JavaScript knowledge will help.

Create a script manager control on your form, to use PageMethods,we will need to set the EnablePageMethods property to true of ScriptManager.
Enable Page Methods on your ScriptManager
<asp:ScriptManager ID="ScriptManager1" runat="server"  EnablePageMethods="True"> 

Create static method and set WebMethod attribute
Now we create a static method on our code behind file. It must marked with the WebMethod attribute, if we are not using WebMethod attribute we can't able to call this page method via javascript.To use WebMethod attribute we need to add System.Web.Services namespace.
using System.Web.Services;
public static bool WelcomeMessage(string name)
    if (name == "ASP" || name == "C#" || name == "Ajax" || name ==     "JQuery")
        return true;
        return false;
Call from JavaScript
Call this method from JavaScript as follows:
<script type="text/javascript">
var divWelcomeMessage =document.getElementById('divWelcomeMessage'); function CallMethod(username) {     //initiate the Ajax page method call     //alert(username);     PageMethods.WelcomeMessage(username,OnSucceeded);     } // Callback function invoked on successful completion of the page method. function OnSucceeded(result, userContext, methodName) {     if (methodName == "WelcomeMessage")     {         if(result==true)             divWelcomeMessage.innerHTML = "Welcome Dear";         else             divWelcomeMessage.innerHTML = "Go from here";     } }
We call this JavaScript on the textbox keyup event as follows.

<input type="text" id="txtusername" runat="server"onkeyup="CallMethod(this.value);"/
><div id="divWelcomeMessage" /gt;

Sunday, October 21, 2012

How is ASP.NET MVC different from ASP.NET WebForms

ASP.NET WebForms
Uses the ‘Page Controller’ pattern. Each page has a code-behind class that acts as a controller and is responsible for rendering the layout.
Uses the ‘Front Controller’ pattern. There is a single central controller for all pages to process web application requests and facilitates a rich routing architecture
Uses an architecture that combines the Controller (code behind) and the View (.aspx). Thus the Controller has a dependency on the View. Due to this, testing and maintainability becomes an issue.
ASP.NET MVC enforces a "separation of concerns". The Model does not know anything about the View. The View does not know there’s a Controller. This makes MVC applications easier to test and maintain.
The View is called before the Controller.
Controller renders View based on actions as a result of the User Interactions on the UI.
At its core, you ‘cannot’ test your controller without instantiating a View. There are ways to get around it using tools.
At its core, ASP.NET MVC was designed to make test-driven development easier. You ‘can’ test your Controller without instantiating a View and carry out unit-tests without having to run the controllers in an ASP.NET process.
WebForms manage state by using view state and server-based controls.
ASP.NET MVC does not maintain state information by using view state.
WebForms supports an event-driven programming style that is like Windows applications and is abstracted from the user. The State management is made transparent by using sessions, viewstate etc. In the process, the HTML output is not clean making it difficult to manage later. The ViewState also increases your page size.
In ASP.NET MVC, the output is clean and you have full control over the rendered HTML. The orientation is towards building standard compliant pages and provides full control over the behavior of an application.
Deep understanding of HTML, CSS and JavaScript is not required to a large extent since the WebForm model abstracts a lot of these details and provides automatic plumbing. While abstracting details to provide ease of use, sometimes a solution is overcomplicated, than it needs to be.
A thorough understanding of how HTML, CSS and JavaScript work together is required. The advantage is you can do a lot of jQuery and AJAX stuff in an efficient and simple manner than you would do in an ASP.NET application.
WebForms can drastically reduce time while building up intranet and internet applications that use a lot of controls (drag and drop model). Although this is true for development, a lot of time is spent later to code around limitations.
You lose the 'drag and drop' quick model of building your web applications. The focus is on control over the application behavior and test-driven development. The model is extensible and you do not have to spend time working around limitations.
Relatively simple to learn and pickup. Works very well for developers who initially have trouble with the HTTP/HTML model and are coming from a similar WinForms oriented event model.
There is a learning curve to understand the why, when and how of ASP.NET MVC.
Lesser amount of code is required to build webapps since a lot of components are integrated and provided out of the box. You can also use a lot of data controls provided out of the box that rely on ViewState.
Since the application tasks are separated into different components, amount of code required is more. Since ASP.NET MVC does not use ViewState, you cannot use Data controls like GridView, Repeater.
Works very well for small teams where focus is on rapid application development
Works well for large projects where focus in on testability and maintainability.

Wednesday, October 3, 2012

Anonymous Methods

Delegates are defined as "a reference type that can be used to encapsulate a method with a specific signature"

The use of delegates is involved in event handlers, callbacks, asynchronous calls and multithreading, among other uses.


Before C# 2.0, the only way to use delegates was to use named methods. In some cases, this results in forced creation of classes only for using with delegates. In some cases, these classes and methods are never even invoked directly.


C# 2.0 offers an elegant solution for these methods described above. Anonymous methods allow declaration of inline methods without having to define a named method.

This is very useful, especially in cases where the delegated function requires short and simple code. Anonymous methods can be used anywhere where a delegate type is expected.


Anonymous Method declarations consist of the keyword delegate, an optional parameter list and a statement list enclosed in parenthesis.


Code Snippet: Event Handler (without using anonymous methods)


btnSave.Click += new EventHandler (btnSave_Click);



void AddClick(object sender, EventArgs e)



lblStatus.Text = "Your changes have been saved";


Code Snippet: Event Handler (using anonymous methods)

btnSave.Click += delegate { SaveChanges(); lblStatus.Text = "Your changes have been saved"; };

Code Snippet:  Event Handler using Anonymous Methods, with a parameter list 

btnSave.Click += delegate(object sender, EventArgs e)




MessageBox.Show("Your changes have been saved");


Anonymous methods can be specified with parameters enclosed in parenthesis, or without parameters, with empty parenthesis. When parameters are specified, the signature of the anonymous method must match the signature of the delegate. When the delegate has no parameters, empty parenthesis are specified in the anonymous method declaration. When an anonymous method is declared without parenthesis, it can be assigned to a delegate with any signature. 

Note that method attributes cannot be applied to Anonymous methods. Also, anonymous methods can be added to the invocation list for delegates but can be deleted from the invocation list only if they have been saved to delegates.


An advantage offered with the use of anonymous methods is that they allow access to the local state of the containing function member.




Anonymous methods offer a simple and elegant solution in many situations. In the next version of C#, (C# 3.0), anonymous methods are evolved into Lambda Expressions used in Language Integrated Query (Linq).



This article is for purely educational purposes and is a compilation of notes, material and my understanding on this subject. Any resemblance to other material is an un-intentional coincidence and should not be misconstrued as malicious, slanderous, or any anything else hereof 

Thursday, September 20, 2012

3 ways to define a JavaScript class


JavaScript is a very flexible object-oriented language when it comes to syntax. In this article you can find three ways of defining and instantiating an object. Even if you have already picked your favorite way of doing it, it helps to know some alternatives in order to read other people's code.
It's important to note that there are no classes in JavaScript. Functions can be used to somewhat simulate classes, but in general JavaScript is a class-less language. Everything is an object. And when it comes to inheritance, objects inherit from objects, not classes from classes as in the "class"-ical languages.

1. Using a function

This is probably one of the most common ways. You define a normal JavaScript function and then create an object by using the new keyword. To define properties and methods for an object created using function(), you use the this keyword, as seen in the following example.
function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = getAppleInfo;

// anti-pattern! keep reading...
function getAppleInfo() {
    return this.color + ' ' + this.type + ' apple';
To instantiate an object using the Apple constructor function, set some properties and call methods you can do the following:
var apple = new Apple('macintosh');
apple.color = "reddish";

1.1. Methods defined internally

In the example above you see that the method getInfo() of the Apple "class" was defined in a separate function getAppleInfo(). While this works fine, it has one drawback – you may end up defining a lot of these functions and they are all in the "global namespece". This means you may have naming conflicts if you (or another library you are using) decide to create another function with the same name. The way to prevent pollution of the global namespace, you can define your methods within the constructor function, like this:
function Apple (type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
Using this syntax changes nothing in the way you instantiate the object and use its properties and methods.

1.2. Methods added to the prototype

A drawback of 1.1. is that the method getInfo() is recreated every time you create a new object. Sometimes that may be what you want, but it's rare. A more inexpensive way is to add getInfo() to the prototype of the constructor function.
function Apple (type) {
    this.type = type;
    this.color = "red";

Apple.prototype.getInfo = function() {
    return this.color + ' ' + this.type + ' apple';
Again, you can use the new objects exactly the same way as in 1. and 1.1.

2. Using object literals

Literals are shorter way to define objects and arrays in JavaScript. To create an empty object using you can do:
var o = {};
instead of the "normal" way:
var o = new Object();
For arrays you can do:
var a = [];
instead of:
var a = new Array();
So you can skip the class-like stuff and create an instance (object) immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:
var apple = {
    type: "macintosh",
    color: "red",
    getInfo: function () {
        return this.color + ' ' + this.type + ' apple';
In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.
apple.color = "reddish";
Such an object is also sometimes called singleton. It "classical" languages such as Java, singleton means that you can have only one single instance of this class at any time, you cannot create more objects of the same class. In JavaScript (no classes, remember?) this concept makes no sense anymore since all objects are singletons to begin with.

3. Singleton using a function

Again with the singleton, eh? :)
The third way presented in this article is a combination of the other two you already saw. You can use a function to define a singleton object. Here's the syntax:
var apple = new function() {
    this.type = "macintosh";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
So you see that this is very similar to 1.1. discussed above, but the way to use the object is exactly like in 2.
apple.color = "reddish";
new function(){...} does two things at the same time: define a function (an anonymous constructor function) and invoke it with new. It might look a bit confusing if you're not used to it and it's not too common, but hey, it's an option, when you really want a constructor function that you'll use only once and there's no sense of giving it a name.


You saw three (plus one) ways of creating objects in JavaScript. Remember that (despite the article's title) there's no such thing as a class in JavaScript. Looking forward to start coding using the new knowledge? Happy JavaScript-ing!