## JavaScript Module Pattern

Posted: September 9, 2011 in Design Patterns, JavaScriipt
Tags: , ,

I recently wrote one article on JavaScript Module pattern in Code project. Please visit this website and suggest me your thoughts on it…

Javascript Module Pattern

## How to use VLOOKUP

Posted: August 3, 2011 in Excel
Tags: ,

Today, I learned about one Excel Sheet Formula “VLOOKUP”. It is very useful formula that gives us the power to search a value in a particular column.

Problem that VLOOKUP can solve.

Let’s say you have one Excel Sheet of Employee Data. You have 2 sheets inside the Excel Book. One sheet is for Employee ID, Address and Name. And in sheet number 2 you have Employee ID and Employee Address. In Sheet number 1 you have only Employee ID and Name data present, you want the address of all the employees. Address can be found from the sheet#2. If we go manually and  do search for address for each employee ID and paste the same data in Sheet1 then it would be a long task and boring stuff to do 😦

In order to automate the search functionality VLOOKUP is there in Excel Sheet.

Let’s solve our previous problem, see below is the Sheet1 we have named it as main. It has 3 Cols EmpId, Name and Address.

Below is the image of Sheet2, lets rename it to address. It has 2 cols; EmpId and Address.

Now in order to search Address we have to take the EmpId one by one from sheet1 and check in Address sheet that if the Employee ID is found or not. If employee Id is found that we need its address.

VLOOKUP formula building

In order to build the expression for VLOOKUP, please Follow below steps.

Step1:

Click on fx in sheet1, it will open up an Insert Function Pop up Window. Then Type VLOOKUP in text box of the pop-up window and click on Go button. It will search and select the VLOOKUP function then click on ok Button.

Step2:

This step is crucial, now we are going to build the expression that will do the search. VLOOKUP has 4 arguments:

1) Lookup_value: It is the value that you want to search for. We have written A2 because we want to search for first Employee Id which value is 1 and it is in A2 column. Lookup_value: A2

2) Table_array: As its name suggests, it is an array of semicolon (;) separated key value pair data. Key value paris are separated by comma (,). For example: {1,”Brajrajnagar”; 2,”Jharsuguda”; 3,”Mumbai”}. It is the data through which the function will look up for the value we are searching for. For Table_array field, you have to write sheet name (from where you want to search address) and the column range (where the data is there) separated by Exclamatory (!) mark. Like in our case, we have to search in address sheet and our column range is from A2 to B4 (A2:B4). Therefore, we will write address!A2:B4. Now, this is perfect however, if you see in my above screen shot, I have written address!\$A\$2:\$B\$4. Each column name is separated by Dollar (\$) sign from the both side. It is because, if you want to write the formula for the next value; say for EmpId = 2 then there you don’t have to write it manually. You can select this formula and by pressing Control Key, you can drag this formula to the next below cell and it will automatically create formula for the next column. If you don’t write \$ sign with column name then above drag and drop formula will not work. So finally: Table_array: address!\$A\$2:\$B\$4.

3) Col_index_num: This is the index number of the column from which it will search the value. In our case it is the address column of sheet2 and its index number is 2: Col_index_num:2

4) Range_lookup: This is a boolean value either TRUE or FALSE. If we select TRUE then it will do like search. If any one of the value matches or looks like the value searched for then it will fetch that data. However, if you select FALSE then it will do exact match before selecting the data. Range_looup: FALSE

Step3

In this step, we will create the same formula for rest of the rows for 3rd row and 4th row. To do that just select the First cell where we wrote our formula that is in C2 and drag it to the C3 cell by pressing control key. It will automatically generate the formula for C3. Similarly you can select the C2 and drag it to up to C4 and it will generate the formula both for C3 and C4. Also you will see the correct address displayed on the selected cells.

Conclusion

This is the complete explanation how one should write the VLOOKUP formula. I hope you enjoyed it, give me your feedbacks and let me know if you know something better or you wanna suggest something. I am the fledgling guy in Excel world  🙂 Please download the Excel sheet that I discussed now from this link Example Excel Sheet VLOOKUP.

## Knockout

Posted: July 21, 2011 in JavaScript, jQuery
Tags: , , , ,

I came through an open source JavaScript named as “Knockout.js”. After learning this javascript functionality and features. I found it very powerful, when it is used combined with jquery.js. and jquery.tmpl.js. It gives us a JavaScript object named as “ko” that has powerful methods and cool utility methods. I found that knockout helps us to write JavaScript code in MVVM pattern that is very neat and clean object oriented coding practices and pattern. By using ko, you can create your own ViewModel JavaScript object and bind that object with your DOM element. Changes into the DOM element value will dynamically reflect into the ViewModel object and it is vice versa. It is kind of one/ two way data bindings with the DOM element and ViewModel object. For linking with the value of the DOM element and ViewModel object you have given “data-bind” attribute from ko object. It’s data linking functionality is very similar to datalink.js. However, it is not just data binding things that you can achieve using knockout.js. Knockout goes little bit above to that. It has few more advantages like over data linking as:

1) Automatic Dependency Tracking.

2) Declarative Binding

3) Integrated Templating

4) Re-rendering the template. Instead of rendering all element it can re-rendered the only element which is being updated. I am going to write few methods and behavior of knockout.js.

One Way Data Binding

You can use observable() method to make certain DOM element to be observable. That means, if observable DOM value gets changed then the corresponding property of ViewModel object gets changed automatically. In below example I have Name Text Box and Read only label. If you change the name then the viewModel name property will gets changed and whatever DOM element linked with Name property of ViewModel will get changed automatically. Here we have one Span element that is linked with Name property of
the View Model. Example:

```
<div>
Enter Name: <input type="text" data-bind="value:Name" /><br />
You Have Entered: <span data-bind="text: Name"></span>
</div>

```

```
<script type="text/javascript">
var viewModel = {
Name: ko.observable("Rupesh")
}
\$(function() {
ko.applyBindings(viewModel);
});
</script>

```

You can see I have used data-bind property in the DOM elements in order to link them all with the same ViewModel property. Similarly if you have array of objects on which the changes happens you want to track then you can use Ko.observableArray(). It is helpful in Result Grid while you show list of data and when you change any row. The ViewModel will get updated automatically with that row.

Combining Multiple Observable Data [ Two way Data Binding ]

You can make another DOM element that will depend on 2 or more observable DOM elements. Let’s have one example. Say you have two Text Boxes like: First Name and Last Name. And now you want to show one read-only Text say Full name that is the concatenation of First Name and Last Name. The Full Name Text should automatically get changed when the user will change First Name and Last Name. If you want to achieve this requirement then you can use “dependentObservable” method. You can write “Ko.dependentObservable(callback, object)” See the below example:

```
<div>
First Name:
<input type="text" data-bind="value:<span />
Last Name:
<input type="text" data-bind="value:<span />
<br />
Full Name: <span data-bind="text:FullName"></span>

```

```
<script type="text/javascript">
var viewModel = {
FirstName: ko.observable("Rupesh")
,LastName: ko.observable("Tiwari")
}
viewModel.FullName = ko.dependentObservable(function() {
return this.FirstName() + " " + this.LastName();
}, viewModel);

\$(function() {
ko.applyBindings(viewModel);
});

</script>

```

Updating DOM behavior

There are properties those help on expressing the behavior of DOM Elements. They are many I am listing out few: Visible, Enable, disable, checked.

```
</pre>
<div data-bind="visible:<span class=">myBooks().length>0"></div>
<pre>
<pre>
Show this div if 'myBooks' has at least one Book.

</div>

```

```
<script type="text/javascript">
var viewModel = {

myBooks: ko.observableArray([]) // Initially empty, so div is hidden
};
viewModel.myBooks.push("jQuery In Action"); // Now visible

\$(function() {
ko.applyBindings(viewModel);
});
</script>

```

Using jQuery Template with KO

We can use jquery template to show list of data like table records. However, if we update any row of the table then in jquery template while rendering the updated row it renders the entire table. In order to overcome this problem knockout came up with foreach helper method that will allow the browser to render those part out of the template modified. Please see the below example: I am adding a new book in my book list and for that I have created one template bookTemplate. On click of Add Book button it only appends the new row in the table using the jquery template. However , while appending the new row it is not rerendering the entire template that is the benefit and performance improvement part.

```<p dir="ltr"> <div>
<table>
<tr>
<th>
Author Name
</th>
<th>
Book Name
</th>
</tr>
<tbody data-bind='template: { name: "bookTemplate",foreach: books }'>
</tbody>
</table>
</div></p>
```

```
<script type="text/html" id="bookTemplate">
<tr>
<input type="text" data-bind="value: <span class=" />AuthorName"/>
<input type="text" data-bind="value: <span class=" />BookName" />
</tr>
</script>

```

```
<script type="text/javascript">
var viewModel = {
books: ko.observableArray([
{ AuthorName: "Yehuda Katz", BookName: "jQuery In Action" },
{ AuthorName: "Cody Lindley ", BookName: "jQuery Cookbook" }
]),
this.books.push({AuthorName: "Dan Wellman", BookName: "jQuery UI" });
}
};
ko.applyBindings(viewModel);
</script>

```

Updating ViewModel and DOM Element

Suppose you got some data from server layer using your Model present inside the server layer. And now you want to update the ViewModel and corresponding UI elements linked with the viewModel Properties. In order to update the ViewModel properties, you can use ViewModel properties as a method and pass the new value as an argument and get updated your ViewModel properties with new value. Suppose you want to search a person by name and display the same Name. Below is the steps for the same:

Step 1. Pass UI search Criteria to Server. You can use ko.toJSON() method to convert your viewmodel object to a JSON object. You can also use JSON.stringify() however in IE 8 and above browser. In old browser you have to use json2.js file as a reference and can use the stringify method of JSON. However, in viewmodel object we do have extra javascript code so if we use JSON’s stringify method on ViewModel
object then it does not clean them out that’s why it is suggested to us ko.toJSON() method.

Step 2. Get the JSON form server side which contains Name. You can use \$.getJSON method or \$.get or \$.ajax to get the JSON object.

Step 3. Bind the JSON with the ViewModel You can use viewModel.Name(jsonobject.Name)

Step 4. Update the HTML DOM Element. ko will automatically update the DOM element the moment viewModel will get updated.

```<em>Please Try with "Rupesh", "Ritesh", "Rakesh" names.</em>
<br />
Enter Name to Search:
<input type="text" data-bind="value:Name" />
<button id="btnSearch" data-bind="click:Search">
Get Age</button>
<br />
<div data-bind="visible:Age">
&nbsp; Age is:
</span>
</div>

```

```
<script type="text/javascript">
var viewModel = {
Name: ko.observable()
,Age:ko.observable()
,Search:function(){
\$.getJSON("json.aspx",{name: viewModel.Name()},function(data) {
viewModel.Age(data); // updating the viewModel after getting data from server.
});
}
};
\$(function() {
ko.applyBindings(viewModel);
});
</script>

```

```
public partial class json : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer sr = new JavaScriptSerializer();
string s = Request.Params["name"];
List<ViewModel> ps = new List<ViewModel>(){
new ViewModel(){ Age =23, Name ="Rupesh"}
,new ViewModel(){ Age =24, Name ="Ritesh"}
,new ViewModel(){ Age =25, Name ="Rakesh"}
};

Response.ContentEncoding = Encoding.UTF8;
Response.ContentType = "application/json";
var age = (from p in ps where p.Name == s select p.Age).ToArray();
int ageStr = (age.Count() != 0) ? age[0] : 0;
Response.Write(sr.Serialize(ageStr).ToString());
Response.End();

}
}
public class ViewModel
{
public string Name;
public int Age;
}

```

Using Mapping Plugin

We saw in our previous example that in order to update the viewModel after getting updated data from server. We have to call each property of the viewModel as a method and pass the new value. Like viewModel.property1(new value); viewModel.property2(new value)… and so on. However, if you want to update the entire viewModel in one chunk. Then you can do this by using knockout mapping. This plugin will convert the JavaScript object into an observable object. That means all of the properties of the object will become observable. If any of the property will modified then it will modify the corresponding linked DOM automatically. For downloading the ko.mapping.js  plugin.

Suppose you have below object:

```
var store  = {

item : "Shirt"

, size : [21,22,23,24]

}

```

Now if you want to convert the data into standard viewModel then you just have to write:

```
var viewModel = ko.mapping.fromJS(store);

```

Now, suppose you got new store value from server side as an JSON formate by making \$.get or \$.ajax call. And you want to update the each and every property of your viewModel then you can do it by writing one line of code only:

```
ko.mapping.updateFromJS(viewModel, store);

```

Above line of code will update the viewModel with the latest values of the store. And ko will automatically update the corresponding DOM elements if they are linked up with this viewModel.

Completing the MVVM pattern

In model MVVM design pattern, we have Model, View and ViewModel object. View is the UI layer, Model is the Server side object that saves or retrieves the data by dealing with the Data Access Layer or any other service or third party. View Model is an abstraction over view that gives the binding of data with the DOM elements. It comprises the presentation logic. So here ViewModel is in UI layer only. As you know that MVVM pattern is made for RIA applications like WPF and Silverlight application. To learn more about MVVM pattern please read Josh Smth’s article .

In RIA application, UI layer takes few responsibilities from the server layer and makes the server layer lighter. knowckout.js allows us to write the presentation logic in viewmodel and using ko object.

Reference

For more details please visit knockoutjs. They have great online tutorial to learn knockout features, please visit this also.

## Basics of jQuery

I took session on jQuery. It was nice experience to talk in front of my colleagues. First time I took session where some of my colleagues joined on phone also with live meeting request. Overall the session was good and learning. If you get chance to check out these videos:

1)

2)

I have covered:

1) Basic Actions of jQuery

2) Traversals

3) Manipulations

4) Attributes & Css

5) Animations

6) Ajax

7) Stack

8- Plugin

I have uploaded the jQuery lab source code in this link jQuery lab and explainations

Posted: July 8, 2011 in jQuery

## Restoring Scroll Position

Posted: July 3, 2011 in ASP.Net, JavaScript
Tags: ,

Suppose you are searching for a product in a shopping website and you got a big set of results. It normally comes in a grid view with a long scroll bar. Sometimes you scrolled to some end and selected a particular product and suppose because of some reason or you clicked some button and page got posted back. Normally now a days because of Ajax nobody does page post back. However, suppose it happened and now page again rendered. Now user has to again scroll the page to find out his/her product. From User Experience point of view it is not good and it is really annoying to scroll to multiple times when your page got posted.

Therefore, we should keep the record of last scrolled position before rendering the grid view. We can do this by using one hidden field to store the last scrolled positions and we have to update the hidden field whenever user will scroll the page. While rendering the page we have to read the scroll position from the hidden field and set it to the page. This way we can solve our problem. I know there are multiple ways to do it.

In my below example I have one div with id “me” and inside this div suppose I have a gridview or table with multiple rows.

```<%@ Page Language="C#" AutoEventWireup="true" CodeFile="scroll.aspx.cs" Inherits="scroll" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<title></title>
<style type="text/css">
div.demo
{
background: #CCCCCC none repeat scroll 0 0;
border: 3px solid #666666;
margin: 5px;
position: relative;
width: 200px;
height: 100px;
overflow: auto;
}
p
{
margin: 10px;
border: 2px solid #666;
width: 1000px;
height: 1000px;
}
</style>

<body>
<form id="form1" runat="server">
<input type="hidden" runat="server"  id="hdnPos"/>

//you can put your grid inside this div
<div class="demo" id="me">
<table>
//Multiple rows are there need vertical scroll bar and fixed height.
</table>
</div>
//button to do postback and check if the scroll position is maintained or not.
<asp:Button ID="Button1" runat="server" Text="Button" />

//Javascript code required for getting and setting the scroll position of the grid div.
<script type="text/javascript">
//getting hidden field and grid id.
var
hdn = document.getElementById("hdnPos"),
gridDiv = document.getElementById("me");
//storing top left scroll position on scroll
gridDiv.onscroll = function(e) {
var
x = gridDiv.scrollTop,
y = gridDiv.scrollLeft;
hdn.value = x + "," + y;
}
//restoring the top left position on each load.
var token = hdn.value.split(",");
gridDiv.scrollTop = token[0] | 0;
gridDiv.scrollLeft = token[1] | 0;
}
</script>
</form>
</body>
</html>

```

## Assembly Binding Log Viewer

Posted: June 27, 2011 in ASP.Net
Tags: ,

My Friend was looking for one error that he was continuously getting when he was trying to setup my old version 1.0 .net code. The error message was:
The given assembly name or codebase, “Microsoft.practices.EnterpriseLibrary.Common” was invalid.

Then I went in Google and searched for the issue, I did not get any satisfactory resolution. However I came to know about one good tool from Microsoft that I had never been used. That tool name is “Assembly Binding Log Viewer”. Using that tool it is very easy to get the error which runtime faced while loading the assembly. I came to know that it may be 3 reasons when we generally get above type of error.

1) assembly deployed to the wrong location
2) mismatch in version numbers
3) mismatch in cultures

Before I could ever suggested my friend how to resolve the problem he came to my desk and said that he had solved his problem. I asked him how did you achieve that he said he deleted all the old folders with all assemblies and then he recreated everything back then it started running  🙂
I was happy that at least his problem got resolved.

However, Assembly Binding Log Viewer is a good tool it starts logging the error that we get while loading assembly at runtime. It helps us to know what the exact error was because typically the .net application shows us the exception message that is very generic it’s called TypeLoadException. By looking only that exception it is very difficult diagnosis the problem.

Fusion log View

For running the tool:

You have to type fuslogvw.exe (it stands for Fusion Log Viewer) in visual studio tools, command prompt.  The moment you will type it will open up one handy-dandy widow’s application.
It will show you the entries of each failed assembly bind. It will show you below details:

1) application that initiated the bind
2) the assembly the bind is for
3) Name
4) Version
5) Culture
6) Public key
7) Date time of failure.

You can store the log files in your desired location you only have to say the directory name you cannot write the log file name this tool will take care of it. Say if you want to store it in C drive then you have to click on settings button you will get one new popup window there you can enable custom path and write c for drive.    This directory should be clean, and only contain files that the runtime generates. If it contains an executable that generates a failure to be logged, the failure will not be logged because the tool tries to create a directory with the same name as the executable. In addition, an attempt to run an executable from the log location will fail.

However, you have to take care of deletion/clearance of the entire log files generated by tool. It will not be deleted automatically. If you will not select custom path to store the log files then this tool will generate this log files in wininet cache, and therefore automatically cleans it out.

Now I started using this tool whenever I got any assembly binding related problems because it saves my hours that I wasted digging into the problem by doing hit and trial methods. You can also read Suzannes article for more details.

Posted: March 17, 2011 in ASP.Net, C#
Tags:

From last 4 days, I have been struggling on how I should load the UserControldynamically in my default page. I know in today’s world where .Net 4.0 came up, MVCis there and in future C# 5.0 is also coming and I am talking of same old UserControlsthat we used to talk in .Net 1.1 -2.0 era. Well I can’t do anything because in my project we have a lots of UserControls and they are not migrating the application from old legacy style to what we have dynamic rendering html using jQuery ajax and other stuffs.

Anyway coming back to my problem how to load user control in a page dynamically? It has simple one line answer that we can put one placeholder and load our usercontrolinside the placeholder at runtime by this way we would be able to render the usercontrol in page dynamically.

```protected void Page_Load(object sender, EventArgs e)
{
}
```

However, this is not as easy as I said now. Let’s go deeper and think on what are the problems that would arise by loading usercontrol by above fashion. There may be various issues however let me talk on 2 major issues listed below:
1) ViewState would not be saved and retrieved.
2) Any Custom Events or dynamically added control events would not fire

Now take one by one let’s take number one problem

viewstate would not maintain
What this mean exactly? Let’s understand it with a simple silly example. Say you have any label in your usercontrol and in page load if you have put your name on the label’s text property. Now, you do button click or by any way if you posted back your page then the label would no more be displaying your name after rendering the page. Think why? Isn’t it weird? 😦

Normally, what happens is when you put some value inside the text property of the label. And if postbackhappens then the page viewstateused to save the unique ID and value of the label and before rendering the usercontrolit loads the viewstatedata by identifying the same label unique id. Therefore, you normally see your value again after postback as well.

As we know the HTTP protocol is stateless. Therefore, whatever is loaded in first time pageload, when the postbackoccurs then server would not aware of the previous status of the page controls and its value. Hence .Net framework has introduced viewstatein order to store the previous state of the page controls. So that it persists after postbackas well. Thanks to ViewState. Don’t take me wrongly if I would say thanks to viewstate. As I am not supporter of the viewstateas I know it causes many problems those are separate concern and separate topic of discussion. You might be heard about the concept of Leaky Abstraction. Sometimes I feel .net ViewState is also one of the example of Leaky Abstraction. Any ways lots of digression happened lets concentrate on our basic problem.

Then why in our dynamically loaded user control viewstate stuff is not loading? Well, In order to understand this first we need to understand the page life cycle events. Are you ready to discuss them …? I am sure you might be saying ok … go ahead … am I not hearing you? 🙂

Anyway jokes apart. There are basically many events those gets fired automatically by the .net framework while loading the page however we are more concern about 12 major events.

Those are:

In the page life cycle events the tracking of viewstatechanges is turned on in between Init and InitCompleteevents. So in the initcompleteevent frameworks adds all the controls property id and value in the viewstatecollection so as to persist after postback. So in our case when we click on the button then the viewstatewould not find the usercontrolin init event because we are adding it in pageloadevent and that’s why it would fail to load the value of the label. So if we want to save our view state stuffs inside the usercontrolthen we have to add the usercontrolat oninitevent. So that we would make sure that viewstatebag is taking care of all the control properties inside the usercontrol.

So we have to make our code like below in order to make sure viewstate would work properly:

```protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
```

So above code would solve our first problem.

Let’s go to our second problem
Any Custom Events or dynamically added control events would not fire:
Let,s you have WebUserControl1 and below code inside its code behind.

```namespace DynamicUserControlLoading
{
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
myalertEvent("He catch this event and show this message in content page");
}
}
}
}
```

And in your default page lets you have below code

```protected void Page_Load(object sender, EventArgs e)
{

}
{
return msg;
}
```

Then on click of the button present in the usercontrolit won’t be delegated to the default page in order to handle it by your returnalert method present in content or default page.

This problem is again related to the viewstatestuffs only as we know the Control Events get fired after the pageloadevent occurs as we were adding our placeholder in pageloadevent. However we are not persisting with the old controls after each postbackswe are adding a new instance of the usercontrol in each trip. Therefore, framework’s viewstate is not able to bind the events on the control events.

The solution to above problem is we have to add the events each time we created the usercontrolsnew instance in the placeholder however it should be in the oninit event only.

Therefore the code should be like below:

```protected override void OnInit(EventArgs e)
{