Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts
Saturday, June 19, 2010

Sum and Concat Operator operators in Linq.

Linq contains lots useful operators and i have found more two operators that can be help full in our day to day programming life. Here are explanation.

Concat Operator: Concat operator concats two entities into single entities its very use full when we are doing some string operator where need to do string operations like concatenation. Here in example i have taken two arrays and concat into single entity.

Sum Operator: When we are developing application like shopping cart and other stuff this operator can be use full where we need to calculate the total or order price and other stuff you can apply this operator array, list and anything that implemented IEnumerable interface. Here i have taken a integer array for the example.

Here is the code for both operators.

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] a = { "a", "b", "c", "d" };
string[] b = { "d","e","f","g"};


Console.WriteLine("Concat Example");
var CtResult = a.Concat<string>(b);
foreach (string s in CtResult)
{
Console.WriteLine(s);
}

int[] num = { 1, 2, 3, 4, 5 };
Console.WriteLine("\n\n\nSum Example");
var SumResult = num.Sum();
Console.WriteLine(SumResult);
Console.ReadKey();
}

}
}
And here is the output of console application as expected.LinqOperators

Hope this will help you..

Technorati Tags: ,,,
Shout it
kick it on DotNetKicks.com
Share:
Friday, June 18, 2010

Take,Skip and Reverse Operator in Linq

I have found three more new operators in Linq which is use full in day to day programming stuff. Take,Skip and Reverse. Here are explanation of operators how it works.

Take Operator: Take operator will return first N number of element from entities.

Skip Operator: Skip operator will skip N number of element from entities and then return remaining elements as a result.

Reverse Operator: As name suggest it will reverse order of elements of entities.

Here is the examples of operators where i have taken simple string array to demonstrate that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] a = { "a", "b", "c", "d" };


Console.WriteLine("Take Example");
var TkResult = a.Take(2);
foreach (string s in TkResult)
{
Console.WriteLine(s);
}

Console.WriteLine("Skip Example");
var SkResult = a.Skip(2);
foreach (string s in SkResult)
{
Console.WriteLine(s);
}

Console.WriteLine("Reverse Example");
var RvResult = a.Reverse();
foreach (string s in RvResult)
{
Console.WriteLine(s);
}

}
}
}
Here is the output as expected.LinqOperators

hope this will help you..

Technorati Tags: ,,,
Shout it
kick it on DotNetKicks.com
Share:

Union,Except and Intersect operator in Linq

While developing a windows service using Linq-To-SQL i was in need of something that will intersect the two list and return a list with the result. After searching on net i have found three great use full operators in Linq Union,Except and Intersect. Here are explanation of each operator.

Union Operator: Union operator will combine elements of both entity and return result as third new entities.

Except Operator: Except operator will remove elements of first entities which elements are there in second entities and will return as third new entities.

Intersect Operator: As name suggest it will return common elements of both entities and return result as new entities.

Let’s take a simple console application as a example where i have used two string array and applied the three operator one by one and print the result using Console.Writeline. Here is the code for that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
 class Program
 {
     static void Main(string[] args)
     {
         string[] a = { "a", "b", "c", "d" };
         string[] b = { "d","e","f","g"};

         var UnResult = a.Union(b);
         Console.WriteLine("Union Result");
         foreach (string s in UnResult)
         {
             Console.WriteLine(s);           
         }

         var ExResult = a.Except(b);
         Console.WriteLine("Except Result");
         foreach (string s in ExResult)
         {
             Console.WriteLine(s);
         }

         var InResult = a.Intersect(b);
         Console.WriteLine("Intersect Result");
         foreach (string s in InResult)
         {
             Console.WriteLine(s);
         }
         Console.ReadLine();
        
     }

 }
}

Here is the output of console application as Expected.

LinqOperators

Hope this will help you.. Stay tuned for more!!


Share:
Thursday, May 20, 2010

Using transactions with LINQ-to-SQL

Today one of my colleague asked that how we can use transactions with the LINQ-to-SQL Classes when we use more then one entities updated at same time. It was a good question. Here is my answer for that.For ASP.NET 2.0 or higher version have a new class called TransactionScope which can be used to manage transaction with the LINQ.

Let’s take a simple scenario we are having a shopping cart application in which we are storing details or particular order placed into the database using LINQ-to-SQL. There are two tables Order and OrderDetails which will have all the information related to order. Order will store particular information about orders while OrderDetails table will have product and quantity of product for particular order.We need to insert data in both tables as same time and if any errors comes then it should rollback the transaction.

To use TransactionScope in above scenario first we have add a reference to System.Transactions like below.

TransactionScope,System.Transactions

After adding the transaction we need to drag and drop the Order and Order Details tables into Linq-To-SQL Classes it will create entities for that. Below is the code for transaction scope to use mange transaction with Linq Context.

 MyContextDataContext objContext = new MyContextDataContext();
using (System.Transactions.TransactionScope tScope
= new System.Transactions.TransactionScope(TransactionScopeOption.Required))
{
objContext.Order.InsertOnSubmit(Order);
objContext.OrderDetails.InsertOnSumbit(OrderDetails);
objContext.SubmitChanges();
tScope.Complete();
}
Here it will commit transaction only if using blocks will run successfully. Hope this will help you.

Shout it
kick it on DotNetKicks.com
Share:
Sunday, March 21, 2010

Singleton Class in C#

Singleton pattern is very popular pattern used by programmer. The idea behind the singleton pattern is to have only one instance of a class at any time. This kind of pattern is very useful for for heavy resources like Linq Data Context etc. It is also useful in multithreaded application where different thread of application try to crate instance of one class but it should be thread safe. It can be also useful for global resources and state objects. In singleton class there are two things required. One static variable which hold the instance of class and other is a static method which will return the instance of singleton class. Here is the example of singleton class

 public class MySingleTon
{
private static MySingleTon mySingleTonInstance = new MySingleTon();

private MySingleTon()
{
//private constructor
}
public static MySingleTon GetInstace()
{
return mySingleTonInstance;
}

}
Now we are done with calling single ton class like following.
 MySingleTon objSingleTon = MySingleTon.GetInstace(); 
The above example is not thread safe so it may be possible that different thread can create different instance of classes. To make above singleton class thread safe we need to change code like following.
   public class MySingleTon
{
private static MySingleTon mySingleTonInstance = new MySingleTon();

private MySingleTon()
{
//private constructor
}
public static MySingleTon GetInstace()
{
lock (typeof(MySingleTon))
{
if (mySingleTonInstance == null)
{
mySingleTonInstance = new MySingleTon();
}
return mySingleTonInstance;
}

}
}
Hope this will help you…

Shout it
kick it on DotNetKicks.com
Share:
Sunday, November 29, 2009

Simple Insert,Update,View and Delete with LINQ-To-SQL

Today one of my friend asked me about simple insert,update and delete example with LINQ-To-SQL but at that time i was not having any simple example which will show the power of LINQ-To-SQL Example. So i have decided to create one simple example with LINQ-To-SQL and also decide to blog about it. Let's create a simple example which is very simple and also show basic step to use LINQ-To-SQL. First i have created a simple table called which have 4 fields like ProductId,Name,Description and Price. Like following.

Table-for-which-LINQ-To-SQL-Classes-Generated

Here is the description for each fields
  1. ProductId- A id which uniquely identify each product.
  2. Name- Name of Product
  3. Description- A short description about product
  4. Price- Price of Product.
Now, Lets create a Linq-To-SQL and rename it as MyDataContent.dbml as following. For that Go to your project ->Right Click->Add New Item->Go to Data Template-> LINQ to SQL Classes like following.

How-to-add-LINQ-To-SQL-Classes-to-your-application

Then open Database Explorer and drag and drop Product table on the newly generated LINQ-to-SQL Class like following.

How-Drag-and-Drop-Database-Tables-to-Linq-To-SQL-Classes

Now our LINQ-SQL-Class is Ready. Now we will insert some data to our table and then first we will write code to get all product information from the database. I have created a function called GetProduct which will print all the product information on page with the help of Response.Write . Following is code for that.
public void GetProducts()
{
using (MyDataContentDataContext context = new MyDataContentDataContext())
{
var Products = from product in context.Products
orderby product.Name
select product;
foreach(Product p in Products)
{
Response.Write(string.Format("<B>Id</B>:{0}", p.ProductId.ToString()));
Response.Write(string.Format("<B>Name</B>:{0}", p.Name));
Response.Write(string.Format("<B>Description</B>:{0}", p.Description));
Response.Write(string.Format("<B>Price</B>:{0}", p.Price.ToString()));
Response.Write("===========================================");
}
}
}
Now Let's Create a function to Add Product. Following is code for function to add product.
public void AddProduct(Product product)
{
using (MyDataContentDataContext context = new MyDataContentDataContext())
{
context.Products.InsertOnSubmit(product);
context.SubmitChanges();
}
}
In the above function i am passing a new object of product and passing that object to above function following is a code for that which create a new product via calling above function.
//Add New Product
Product product = new Product();
product.Name = "Product3";
product.Description="This is product 3 Description";
product.Price=10;
AddProduct(product);
Now we have added the code to add product now lets create a function to update the current product information. Following is a code for that.
public void UpdateProduct(int productId, string name, string description, double price)
{
using (MyDataContentDataContext context = new MyDataContentDataContext())
{
Product currentProduct = context.Products.FirstOrDefault(p => p.ProductId == productId);
currentProduct.Name = name;
currentProduct.Description = description;
currentProduct.Price = price;
context.SubmitChanges();
}
}
With the help of above function you can update current product like following.
////Update Product
UpdateProduct(2,"New Product2","New Description for product",20);
Now we added the code for update product so now let's create a sample code to delete a specific product. Following is a code for that.
public void DeleteProduct(int productId)
{
using (MyDataContentDataContext context = new MyDataContentDataContext())
{
Product currentProduct = context.Products.FirstOrDefault(p => p.ProductId == productId);
context.Products.DeleteOnSubmit(currentProduct);
context.SubmitChanges();
}
}
You can delete the product via passing product id as following.
//Delete product
DeleteProduct(3);
So that's it. you can create insert,update,delete operation with the help of LINQ-To-SQL within some minutes without writing so much code for .net and queries for databases.

Happy Programming...

Technorati Tags: ,,,
Shout it

kick it on DotNetKicks.com
Share:
Saturday, July 18, 2009

Partial Types, Class and Method in C#.NET 3.0/2.0

With C# 2.0 Microsoft has added partial keyword in C#. So what is partial keyword used for. Lets go through the partial keyword in greater detail.

First and foremost use of the partial keyword is the you can declare one class or method with more then one declaration and at the compilation time it will have one complete class.So now you can declare a class more then one file at the compile time it will be treated as one class.

For example this is one class

//first file Patial Class
public class partial PartialClass
{
   public void First()
   {
     //First function
   }
}
 Here is the another class
public class partial PartialClass
{
   public void Second()
   {
      // Logic...
   }
}
Now at the compile time it will be treat as single class like following.
public class PartialClass
{
   public void First()
   {
      // Logic...
   }
   public void Second()
   {
      // Logic...
   }
}
Same way you can use partial method it will treated as one method as compile time. Partial method will only available with C# 3.0. It will not be available to C# 2.0.

Practical Usage Of Partial Class:

There are lots of way where partial class is useful like many developer can work on same class via creating different files. There are lost of code generators available in market so you can extend the class functionality via marking them partial. Partial class can also be used for the manage code in separate files instead of creating large files. With C# 3.5 linq to sql designer uses this concept to split custom behaviors outside mapping class.

Share:
Friday, July 17, 2009

Subsonic 3.0 is out now- Next Generation Object Relational Mapper

There lots of ORM(Object Relational Mapper) is available now like entity framework,nhibernate, linq, dlinq but i choose subsonic 3.0 for my next application which will be a question answer site for the following reason

  1. Now subsonic 3.0 is with linq support so you can write your lambda expression and linq queries along with the subsonic
  2. It comes with simple repository.
  3. Built in T4 Templates for 4.0
  4. Linq to subsonic.
  5. Subsonic 3.0 templates.
  6. Can handle thousand of queries at a times.
  7. Full support with asp.net 3.5 features.
  8. Ease of Use.
  9. Great support with asp.net mvc

And another great news is that Rob Conery is hired by the Microsoft and subsonic will official ORM for ASP.net Applications.

You can download subsonic 3.0 from here.

http://www.subsonicproject.com/Download

Happy Coding..

Share:
Tuesday, May 26, 2009

Implementing repository pattern with the ado.net entity model

There are lots of ways to implement repository pattern but with ado.net entity model you can create repository pattern within 10 to 15 minutes.

If you are creating asp.net mvc application then just right click->Model folder->Add->Net Item->select ado.net entity data model.



From database explorer right click and drag your tables to your database explorer. It will create a entity class. For example i have created a notes table for my sample and it will create a notes entity class in my ado.net entity data model.



After creating the entity class not its time to create a interface for repository pattern which will contain my all the operations related to notes entity.

Following is the interface which we will implement use for repository.

namespace DotNetJapsMVC.Models.Respository.Interface
{
interface INotesRepository
{
void CreateNotes(Notes notesToCreate);
void EditNotes(Notes notesToEdit);
void DeleteNotes(Notes notesToDelete);
Notes GetNotes(Guid noteId);
IEnumerable ListNotes();
}
}

Now we will create a class that will implement this repository interface. Here is the coding for that.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DotNetJapsMVC.Models.Respository.Class
{
public class NotesRepository:Interface.INotesRepository
{
private DotNetJapsEntities _myEntities = new DotNetJapsEntities();

public void CreateNotes(Notes notesToCreate)
{
_myEntities.AddToNotes(notesToCreate);
_myEntities.SaveChanges();
}

public void EditNotes(Notes notesToEdit)
{
var originalNotes = (from n in _myEntities.Notes
where n.NoteId == notesToEdit.NoteId
select n).FirstOrDefault();

_myEntities.ApplyPropertyChanges(originalNotes.EntityKey.EntitySetName, notesToEdit);
_myEntities.SaveChanges();

}

public void DeleteNotes(Notes notesToDelete)
{
var originalNotes = GetNotes(notesToDelete.NoteId);
_myEntities.DeleteObject(originalNotes );
_myEntities.SaveChanges();
}

public Notes GetNotes(Guid noteId)
{
return (from n in _myEntities.Notes
where n.NoteId == noteId
select n ).FirstOrDefault();
}

public IEnumerable ListNotes()
{
return _myEntities.Notes.ToList();
}

}
}

That's it we have created the repository classes and repository interface. You can use as following in your class or pages.

private  INotesRepository _repository;

public List LoadNotes()
{
 return _repository.ListNotes();
}

Advantage Of Repository Pattern:
  1. Make application loosely coupled so if you want to change the something then you don't need to change everything from scratch.
  2. With the repository pattern we can have nice abstraction which will separate our business logic as well as database logic.
  3. You can prevent dependency injection through the repository pattern.
Happy Programming
Share:
Thursday, July 31, 2008

What is LINQ? LINQ Developer Resources

LINQ is Language Integrated query. It is a integral part of visual studio 2008 and Microsoft .NET Framework 3.5. It is object to database mapping technology thorough which you can query any type of collections of object,XML of database.

 

Recently I am goggling about the LINQ and I have found following great resources for developers:

LINQ Resources:

Linq for Oracle:
----------------
http://broersa.wordpress.com/2008/05/22/linq-for-oracle-sample/

 

.NET 2.0 Or higher transaction model to use it with linq:
----------------------------------------------------------
http://www.simple-talk.com/dotnet/.net-framework/.net-2.0-transaction-model/

 

How to use transaction with linq:
--------------------------------
http://chiragrdarji.wordpress.com/2007/08/25/how-to-use-transaction-in-linq-using-c/

 

Inside the linq datacontext site to better understanding of linq:
-----------------------------------------------------------------
http://dotnetslackers.com/articles/csharp/InsideTheLINQToSQLDataContextClass.aspx

 

Linq to SQL(part 1 to 7 -Total Understanding of linq):
------------------------------------------------------
http://aspalliance.com/1430_LINQ_to_SQL_Part_6__Retrieving_Data_Using_Stored_Procedures_.1

 

A good article about-LINQ to SQL : Using Transaction:
-----------------------------------------------------
http://blogs.msdn.com/wriju/archive/2007/08/06/linq-to-sql-using-transaction.aspx

 

Using LINQ in ASP.NET (Part 1)- A Four part series from bipin joshi:
--------------------------------------------------------------------
http://www.dotnetbips.com/articles/56f8f29d-2617-4f99-a8b4-977703ebf780.aspx

 

The Linq Project:
----------------
http://msdn.microsoft.com/en-us/vbasic/aa904594.aspx

 

What is linq:
------------
http://en.csharp-online.net/Introducing_LINQ%E2%80%94What_Is_LINQ
http://www.dotnetspider.com/resources/19939-What-LINQ.aspx.aspx

 

Scott gu's Multipart Series about linq:
--------------------------------------
http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx

 

Linq to xml:
-------------
http://sandeep-aparajit.blogspot.com/2007/12/what-is-linq.html

Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews