Thursday, December 17, 2009

ASP.NET MVC Pattern – VAR Controllers(View-Ajax-Redirect)

In this blog, I am going to introduce one controller pattern, VAR Pattern, for the ASP.NET MVC framework.


For last few days, I have started to learn the ASP.NET MVC framework. I have downloaded and studied various sample/demo applications with help of search engine.

I have also noticed that different operations,like CRUD (Create, Retrieve, Update, Delete), are divided in different views (actually pages). But it may be required that an application needs a single page has all CRUD plus others.

Before going to explain the VAR pattern, we can still develop very good ASP.NET MVC applications using different tools/libraries like Spark view engine, AutoMapper etc and different patterns.

Generally we can categorized 3 types of actions"

1. View - Submit (Postback) – submit the view.
2. Ajax called by client side to update a view through javascript or jquery.
3. Redirect redirects the view.

For each type of action, there is one controller is defined which are listed;

1.ViewController:


It should return View or PartialView.

There are 2 kind of usage,

a). To Submit the view and do the needful operations

e.g. Insert or Delete a record and display other view.


View → Insert is button pressed → “Insert” action is executed from “ViewController” → form data are saved → redirect to Home view


b). To update the view.

e.g. Search operation changes the view data

View → Search is button pressed → “Search” action is executed from “ViewController” → data are fetched based on search criteria → update the view

2.AjaxController:

It should return .NET primitive datatype (converted in Content by ASP.NET MVC framework), ContentResult, JSON result. i.e return type which can be processed/manipulated through javascript.

There is one kind of usage,

a). To fetch data from server and use it at client side.

e.g. In “Registration” view to check that Username is exist or not
“Update” the view data.

View → Modify the form data → Update is button pressed → “Update” action is executed, through jquery ajax, from “AjaxController” → data are updated → notifies the client.

Generally I like to post updated data on server asynchronously if update is not too much complex.
The reason is whatever updated values are known and persist in the view. So It is not required to update the view forcefully through post back.

3.RedirectController:

There are 2 kind of usage.

a). To redirect from one view to another

e.g. Home view to Admin view

Home view → Admin button is pressed → ”RedirectCMS” action is executed from “RedirectController”→ validate the admin token → redirect to Admin view

b). To submit the current view and redirect that view with default values.

e.g. Delete record with current form data and update the view with default values
View → Delete button is pressed → “Delete” action is executed from “RedirectController” → data are deleted → redirects the view with default data.

We can create the VAR controllers for each entity.

I have created the demo (another demo in ASP.NET MVC framework ;)) at http://cid-c91ae1db65f80fc6.skydrive.live.com/self.aspx/.Public/Blog/MVCPattern%5E_VAR.zip



Tuesday, July 14, 2009

Delete items from List

We should able to do CURD (Create, Update, Read, and Delete) operations in the List. Create, Read, and Update operation are very easy to maintain the List but Delete is difficult because List is automatically rearrange the elements after deleting item[s].

A month ago, we have faced problem while deleting items from List in one of the projects.

Below are steps what we have implemented.
1.Fetch data from SQL.

2.Convert them in to List collection and bind it to GridView having checkbox and paging enabled.
3.From the current page, we need to delete the item
s from List whose rows are checked.

Scenarios while deleting item[s] from List:


A list has object type “Item” having fields “ID” and “ItemName”.

Initial Data:

List Elements – [1,”Item1”], [2,”Item2”], [3,”Item3”], [4,”Item4”], [5,”Item3”], [6,”Item6”]


1. Delete item[s] from list using index.
Deleted List Index – 0, 2
Expected resultant List elements - [2,”Item2”], [4,”Item4”], [5,”Item3”], [6,”Item6”]


1. Data after deleting first item:
List Elements – [2,”Item2”], [3,”Item3”], [4,”Item4”], [5,”Item3”], [6,”Item6”]
2. Data after deleting second item:
List Elements – [2,”Item2”], [3,”Item3”], [5,”Item3”], [6,”Item6”]

Problems:
a. Produces wrong resulting list. b. Some time throws exception - “out of index”.

2. Delete item[s] from list by finding the index of the object and remove the item from the list using searched index.

Delete items having “ItemName”– “Item1”, “Item3”

1. Data after deleting item having ItemName as “Item1”:
  • Search “Item” object using foreach/for/LINQ to find the object having “ItemName” as “Item1”. Either it will give object[s].
  • Find the index of the object using “List.FindIndex” for each founded object.
OR
  • Use method “List.FindAll” which returns array of matching records and then use “List.FindIndex” for matched objects.
  • Delete the object from list using founded index.
In our case, single item found [1,”Item1”] and its index is “0”.

List elements – [2,”Item2”], [3,”Item3”], [4,”Item4”], [5,”Item3”], [6,”Item6”]
2. Data after deleting item having ItemName as “Item3”:
  • Repeat the same process for “Item3”.
In our case, 2 items found [3,”Item3”] and [5,”Item3”] with index is “1” and “3” respectively.

List elements – [2,”Item2”], [3,”Item3”], [4,”Item4”], [5,”Item3”], [6,”Item6”]
Resultant List items – [2,”Item2”], [4,”Item4”], [6,”Item6”]




Problems:
Page 1 elements – [1,”Item1”], [2,”Item2”], [3,”Item3”], Page 2 elements – [4,”Item4”], [5,”Item3”], [6,”Item6”] Because of this method, [3,”Item3”], [5,”Item3”] items are deleted even though you want to delete [3,”Item3”] from Page 1.

This problem gives unexpected results if you have more records having same “ItemName”.


We can also write the logic for preventing the unexpected result.


So, I have written the logic to delete the items in any scenario and achieved the expected result.


Solutions while deleting item[s] from List:

1. Delete item[s] by maintaining the removed items counter.

a. Take variable which stores the number removed items from that list.
int itemsRemoved = 0
b. Calculate the index using that counter and GridView.PageSize and Grid.PageIndex.
int removedIndex = i - itemsRemoved + (gridObject.PageIndex * gridObject.PageSize);
c. Delete the items using above calculated index.
listObject.RemoveAt(removedIndex);
d. Increment that counter by 1 after removing items from that list.
itemsRemoved++;
e. Complete Source:
int itemsRemoved = 0;
List listObject = GetItems();
for (int i = 0; i <>
{
GridViewRow row = gridObject.Rows[i];
CheckBox chkItem = (CheckBox)(row.Cells[0].Controls[1]);
if (chkItem.Checked)
{
int removedIndex = i - itemsRemoved + (gridObject.PageIndex * gridObject.PageSize);
itemsRemoved ++;
listObject.RemoveAt(removedIndex);
}
}
//RefreshGrid again so changes are reflected;

2. Prepare the Deleted Index List.
a. Prepare the index list by checking the checkbox value.
List removeIndexList = new List();
int startIndex = gridObject.PageIndex * gridObject.PageSize;
for (int i = 0; i <>
{
GridViewRow row = gridObject.Rows[i];
CheckBox chkItem = (CheckBox)(row.Cells[0].Controls[1]);
if (chkItem.Checked)
{
removeIndexList.Add(i + startIndex);
}
}
b. Now reverse the list.
removeIndexList.Reverse();
c. Now, using for/foreach delete the item from the list using “List.RemoveAt (index)”.
foreach (int k in indexList)
{
listObject.RemoveAt(k);
}
3. Prepare the Deleted Object List.
a. Prepare the object list by checking the checkbox value.
List deletedItemList = new List();
int startIndex = gridObject.PageIndex * gridObject.PageSize;
for (int i = 0; i <>
{
GridViewRow row = gridObject.Rows[i];
CheckBox chkItem = (CheckBox)(row.Cells[0].Controls[1]);
if (chkItem.Checked)
{
deletedItemList.Add(listObject.ElementAt(startIndex + i));
}
}
b. Now, for each item find the index and delete it from the list using “List.RemoveAt (index)”.

for (int i = 0; i <>
{
int k = listObject.IndexOf(deletedItemList [i]);
if (k > -1)
listObject.RemoveAt(k);
}
4. By nullifying the object.
a. Nullify the object for the selected index
int startIndex = gridObject.PageIndex * gridObject.PageSize;
for (int i = 0; i <>
{
GridViewRow row = gridObject.Rows[i];
CheckBox chkItem = (CheckBox)(row.Cells[0].Controls[1]);
if (chkItem.Checked)
{
listObject[startIndex + i] = null;
}
}
b. Delete all objects whose values are “null”.
listObject.RemoveAll(delegate(Item i) { return i == null; });
5. By modifying the property
a. Select any property whose type is string and insert any special character at first position that has been never occurred in the property. Let’s say ”>“
int startIndex = gridObject.PageIndex * gridObject.PageSize;
for (int i = 0; i <>
{
GridViewRow row = gridObject.Rows[i];
CheckBox chkItem = (CheckBox)(row.Cells[0].Controls[1]);
if (chkItem.Checked)
{
listObject[startIndex + i].Name = ">" + listObject [startIndex + i].Name;
}
}
b. Delete all objects whose property has first character ">".
listObject.RemoveAll(delegate(Item i){return i.Name[0]=='>';});

NOTE:
1. First method gives good performance than others.
2. If you want to display deleted items before removing it then use the Third method.

Thursday, May 21, 2009

OOP Concepts

I know every programmers know the OOP concept but still I have decided to write small and sweet article related to OOP used to refresh our OOP concepts.

Definition:

OOP is the programming model where related information (data/fields-properties and processes/method) are integrated to form an object.

Advantages:

- Code redundancy and maintenance is lower.
- Code readability (Abstraction), reusability (Inheritance), reliability, security (Encapsulation) is higher.
- Less coding
- In OOP, everything (data and process) is related to object and object is closely related to real life.

Disadvantages:

- Performance/efficiency is lower then Structured Programming

Reason:
1. Object is reference type and referenced through pointer. So little bit of space overhead to store pointers and little bit of speed overhead to find the space in the memory (heap) to store the objects runtime.
2. For dynamic methods there is little bit of time overhead to call the right method while OOP features used like inheritance, polymorphism.

Features:
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Abstraction:

A concept without thinking/showing of a specific example/actual implementation. It is the process to hide/omit unwanted detail and showing just representation of the actual implementation/detail.

Abstraction refers to the act of representing essential features without including the background details or explanations.

e.g. Real time examples are,
- Stopping the car engine, starting the car engine, switch on/off to any electrical devices.

Abstraction is achieved by classes and objects.

Encapsulation:

It is the process of integrating the data and functions into a single unit called class.
The objective of encapsulation is to provide a).Protection and b).Information Hiding.

a).Protection is the limiting and use of class’ data and functions. In short, data and/or functions can not be used with out object. Protection is about adding methods and data to a class. When you add methods or data to a class, then you are protecting the methods or data from use without first having an object of the class.

b).Information hiding is the removing the data and functions from public space of class. It can be achieved using access modifiers like private, public, protected.

Abstraction tells us what external face we should present to the world where as Encapsulation ensures that the implementation of the interface doesn’t leak out to the outside world.

Inheritance:

It is the process to inherit/derive commonly used data (state) and functions (behavior) from other classes, called parent/base class and inherited/derived class called child or derived class. It is intended to reuse existing code with little or no modification.

a).Generalization and b). specialization are the associated with the concept of inheritance.

a). Generalization is the defining the classes, called base/parent/super class, having common characteristics of its subclasses.
e.g. “Vehicle” is the generalization of “car”, ”bike”, ”plane”, ”boat”, ”bicycle” and many more.

b).Specialization is to refine the derived/child class behavior using overriding.
e.g. Start and Stop behaviors of vehicle are different. Car has different mechanism to start then bike.

Polymorphism:

Poly – multi and Morph =”forms” -> having multiple forms
Polymorphism is the process of using an operator or function in different ways for different set of inputs given.

Redefining the inherited the members differently using overloading and overriding is called polymorphism

There are 3 concepts to achieve polymorphism;

1. Function overloading – functions having same name but different signatures/prototype does not include return type
e.g. Add(int a, int b) - Adds two integer numbers
Add(string a, string b) - concatenates the string a & b
2. Operator overloading – redefining existing operator for the objects of the classes.
e.g. + used to add numbers
+ used to
concatenates two string
3. Function overriding - redefining the derived method into the derived class.
e.g. Work() - defined in Parent class - Parent do business
Work() - defined in Child class - Child does the job

Tuesday, May 19, 2009

Facebook - Linq to Fql

Step 1: Requirements

1. Download the Facebook LINQ to FQL binaries(DLLs) from http://facebooklinq.codeplex.com/
2. Create a website or application in VS 2008
3. Add references of DLL (downloaded in step1) in to the project.

Step 2: Facebook Application Setting

4. Login in http://www.Facebook.com with valid user name and password.
5. Paste the URL http://www.facebook.com/developers/ to support custom application in your account.
6. Click “Allow” button to allow for custom Facebook application
7. Click “Setup New Application” button to validate your custom application
8. Give the application name – let’s say “My Application” and select “Agree” radio button then click “Save Changes” button.
8. Go to "Canvas" tab and enter the "Canvas Callback URL". Let's say "http://localhost:1111/FBDemo/Default.aspx
9. On the same tab, select Render Method as IFrame from "Canvas Setting" section.
10. Facebook generates some credentials for the created application like “API Key”, “Application Secret”,” Application ID” with respective values. See below fig


Step 3: Setting the Facebook application credentials in Web.Config

11. Add below values in “appSettings” section

12.Add below value in “httpHandlers” section

Step 4: Accessing Facebook Data

13. Open the webpage (in our case Default.aspx)
14. Add reference of Facebook dlls using below lines
using facebook;
15. Authenticate current Facebook Logged in user with below line
bool isAuthenticated = facebook.Web.FacebookContext.Current.TryAuthenticating(true);
16. After authentication, create the object of FacebookDataContext with below line
var db = new FacebookDataContext();
17. Now access the properties of db whose type of facebook.Linq.FqlTable indicates the facebook
data like;
a. db.user – user information
b. db.group – groups information
c. db.friend_info – friends list etc.
18. Filter data as per requirements through executing LINQ on the above lists

Step 5: Source code listing
a. ASPX Page
Put the DataList and add item templates in to the datalist as per requirements

b. Source Listing (C# Code):
Write the below code to display the logged in user information like name, birthday and photo of the user.
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (facebook.Web.FacebookContext.Current.TryAuthenticating(true))
{
var db = new FacebookDataContext();
var myUser = from user in db.user where user.uid == db.uid select user;
var myUser2 = db.user.Where(t => t.uid == db.uid);
Example1DataList.DataSource = myUser.Take(10);
DataBind();
}
}
catch (Exception ex)
{
throw ex;
}
}