Friday, November 27, 2009

XLINQ and Lambda Expressions

I had used LINQ recently in one of the projects but I had very less knowledge while developing it. But I am sure it is one of the very good add on for the programming which makes many of our life so easy especially while working with xml and DB. Most of the places I had used the LINQ query but I just tried using the same thing using the Lambda expressions.

If you are new to XLINQ, you might want to go through xlinq first. I take an example as below and explain how to obtain the same results using XLINQ and Lambda expressions.

My xml
string xmldoc = "<customer><item id=\"1\" status=\"N\" name=\"Item 1\"><item id=\"2\" status=\"O\" name="Item 2\"><item id=\"3\" status=\"O\" name=\"an item\"></customer>";


Loading xml to Xelement
XElement objElement = XElement.Parse(xmldoc);

Ok now my xml is loaded and ready to use. Lets say if I need to take the items with Status “O” and order by Name, if we have to do it using XMLDocument(in earlier version) it would require many lines of code and debugging. The LINQ made it very easy. I would simply query as below


IEnumerable oldItem = (from c in objElement.Elements("Item")
where (string)c.Attribute("Status") == "O"
orderby c.Attribute("Name").Value
select c);


The oldItem list will have all the items with Status “O” order by “Name”. Just parse through oldItem and you will know it for sure


foreach (XElement obj in oldItem)
{
MessageBox.Show(obj.Attribute("Name").Value);
}



Now let’s do the same thing using lambda expression

IEnumerable oldItemLamda = objElement.Elements("Item").Where(d => d.Attribute("Status").Value == "O").OrderBy(d => d.Attribute("Name").Value);


It looks pretty straitght forward while the above looks like someone needs to have query skill. The expression d => d.Attribute("Status").Value == "O" is the predicate. Have you observed the new operator used here ? "=>" is called as Lambda operator which is introduced in .net 3.0. The expression on right side is called lambda expression. An expression lambda returns the result of the expression and takes the following basic form:

(input parameters) => expression

So we have the Xelement filter with “O” status and Order by name. Lets make sure we have the right elements selected


foreach (XElement obj in oldItemLamda)
{
MessageBox.Show(obj.Attribute("Name").Value);
}



The results from the above query and the lambda expression are same.

There are many methods available which expects the predicate and returns the result based on the expression.











You can get more information on Lambda expression on http://msdn.microsoft.com/en-us/library/bb397687.aspx

Thursday, November 26, 2009

Working with Object Oriented Javascript

There are many situations we use javascript on web application. Most of us use it for client side validation or to load some dynamic content on client side. There are many things we can achieve using javascript. Here I thought of explaining some basics of object oriented approach to work with javascript.

First thing you shoud keep in mind is that object oriented in javascript is not like any other progamming languages like C#, Java, C++ where we are referring to instances of classes or structs. There is nothing like creating class on javascript. We can assume that its a collection of name value pairs or dictionary with string keys. Simple way to express that as we create a function and assign that to a variable. Here is how the sample Javascript class file will look like



<script>

function Myclass(){
this.myPublicvar = '';
var method1 = function()
{
if(arguments.length > 0){

alert("parameter length" + arguments.length);
}
else
{
alert("inside the method " + this.myPublicvar);
}
}

this.mypublicMethod = method1;
}


function alertme(){
var myObj = new Myclass();
myObj.myPublicvar = 'Sample';
myObj.mypublicMethod();
}


function testoverloading()
{
var myObj = new Myclass();
myObj.mypublicMethod(1);
myObj.mypublicMethod(1,'Test parameter');

}
<script>


<input onclick="alertme()" value="Click here" type="button">
<input onclick="testoverloading()" value="Try Overloading" type="button">




In above case, we have a function created as Myclass which will act as a class. There is a method defined inside Myclass method1. The method1 is assigned to a public variable myPublicMethod.

When you create a object of Myclass, you can invoke the method by using myObj.mypublicMethod(); As you can see in the above example it has one of the public variable defined myPublicvar. Now you must have understood the use of "this" keyword inside the function Myclass.



We can also achieve function overloading. In above scenario, we have one more button “Try Overloading” which will invoke a method testoverloading(). This will show how the overloading works. One of the feature of javascript that makes it very flexible that,we can pass any number of parameters and we can get them as parameter array. You can find the same in above example. The same public method mypublicMethod is invoked with different parameter. The alert will show the number of parameter passed.


When you are working with complicated logic on client side this will help us a lot. Hope this piece of information will give some basic idea on object oriented approach on javascript programming.

You can get details on http://msdn.microsoft.com/en-us/magazine/cc163419.aspx

Wednesday, November 25, 2009

Foreign key constraints and Delete records

In many cases, while designing the database, we consider primary key and foreign key. Some of the cases, the data will be never deleted form the system and we use only soft delete which is nothing but keeping another column to indicate whether the row is active or not.

But some of the cases, we might want to delete the record but it will also have the reference in other table.


I will take an example of a table customer and items and itemlocation


create table itemlocation

(

locationid int primary key,

locationdesc varchar(100)

)

create table Items

(

ItemID int primary key,

ItemName varchar(100),

ItemPrice int,

locationid int constraint Item_location_FK references itemlocation(locationid)

)

create table customer

(

CustID int primary key,

CustomerName varchar(100),

ItemID int constraint Cust_Item_FK references Items(ItemID)

)

insert into itemlocation (locationid,locationdesc) values (1, 'Bangalore')

insert into itemlocation (locationid,locationdesc) values (2, 'Mysore')

insert into Items (ItemID, ItemName,ItemPrice,locationid ) values (1,'T shirt', 100, 1)

insert into Items (ItemID, ItemName,ItemPrice,locationid ) values (2,'Shoes', 500, 1)

insert into Items (ItemID, ItemName,ItemPrice,locationid ) values (3,'Shirt', 500, 2)

insert into customer(CustID, CustomerName, ItemID) values (1,'Subbu',null)

insert into customer(CustID, CustomerName, ItemID) values (2,'Ravi',1)

insert into customer(CustID, CustomerName, ItemID) values (3,'Raj',2)

insert into customer(CustID, CustomerName, ItemID) values (4,'Sam',3)


Now we have all the tables and data. If anyone has to delete the item, they need to delete referring customers first otherwise system will throw an error


delete from Items where ItemID=1

Msg 547, Level 16, State 0, Line 1

The DELETE statement conflicted with the REFERENCE constraint "Cust_Item_FK". The conflict occurred in database "ReportServer", table "dbo.customer", column 'ItemID'.

The statement has been terminated.



In some cases we can use delete cascade which will not throw this error and delete all referring records too. Here is what happens when we use delete cascade in our case


alter table customer drop constraint Cust_Item_FK

alter table customer add constraint Cust_Item_FK

foreign key (ItemID) references Items(ItemID)on delete cascade

go

Ok. Now you delete the same item and see what happens


Delete executed fine without any errors but you have also lost the customer record. If you look at customer table, the customer with ItemId 1 is deleted.



Now try the delete cascade on item table as below


alter table Items drop constraint Item_location_FK


alter table Items add constraint Item_location_FK

foreign key (locationid) references itemlocation(locationid)on delete cascade

go



After the table altered execute below statement

delete from itemlocation where locationid=1


Now see what happens, You have lost all the items and customers linked with location 1. We need to be very careful when we using delete cascade. All the data are lost.


To over come this problem we can use a new feature introduced in Sql 2005 and above on delete Set Null option.



Lets change our constraint something like this


alter table customer drop constraint Cust_Item_FK

alter table customer add constraint Cust_Item_FK

foreign key (ItemID) references Items(ItemID) on delete set null


Now lets try the delete statement as below


delete from Items where ItemID=1


Now the cstomer table has data as below


CustID CustomerName ItemID

----------- --------------- -----------

1 Subbu NULL

2 Ravi NULL

3 Raj 2

4 Sam 3


The Itemid which is deleted is affected on customer table but the customer is assigned with Null for the deleted item. We can also use on delete set default which will update default value while deleting referenced data.

This is one of the very good feature added on Sql which will definitely help many of us while deleting referenced data. So be careful to add this when you use delete cascade next time.