• Wriju's BLOG

    How to find public key token for a .NET DLL or assembly

    • 21 Comments

    Many times we need to get the Public key token for a strongly named assembly in .NET. FAQ on that “how to get the public key token?”. Answer is very simple use the .NET Framework tools sn.exe. So open the Visual Studio 2008 Command Prompt and then point to the dll’s folder you want to get the public key,

    Use the following command,

    sn –T myDLL.dll

    This will give you the public key token. Remember one thing this only works if the assembly has to be strongly signed.

    Example

    C:\WINNT\Microsoft.NET\Framework\v3.5>sn -T EdmGen.exe

    Microsoft (R) .NET Framework Strong Name Utility  Version 3.5.21022.8

    Copyright (c) Microsoft Corporation.  All rights reserved.

     

    Public key token is b77a5c561934e089

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity: Insert Update and Delete

    • 28 Comments

    For small blogs, it requires more references and explanation, which sometimes are redundant. So I thought of writing single blog which is combination of topics more or less related to one thing.

     

    I am exploring ADO.NET Entity Framework and have been trying things out there. Here I am planning to demonstrate how to do insert, update and delete.

     

    Here I will use a database created by me. In the Emp table there are two columns Id (Primary and auto-generated) and Name (simple varchar(50)).

    image

    Now I will create TestDB.edmx out of this database.

    image

    Insert

     

    using (TestDBEntities ctx = new TestDBEntities())

    {

        //Create new Emp object

        Emp e = new Emp() { Name = "Test Employee" };

     

        //Add to memory

        ctx.AddToEmp(e);

     

        //Save to database

        ctx.SaveChanges();

    }

     

     

    Update

     

    using (TestDBEntities ctx = new TestDBEntities())

    {

        //Get the specific employee from Database

        Emp e = (from e1 in ctx.Emp

                 where e1.Name == "Test Employee"

                 select e1).First();

     

        //Change the Employee Name in memory

        e.Name = "Changed Name";

     

        //Save to database

        ctx.SaveChanges();

    }

     

    Delete

     

    using (TestDBEntities ctx = new TestDBEntities())

    {

        //Get the specific employee from Database

        Emp e = (from e1 in ctx.Emp

                 where e1.Name == "Test Employee"

                 select e1).First();

     

        //Delete it from memory

        ctx.DeleteObject(e);

     

        //Save to database

        ctx.SaveChanges();

    }

     

    In my next post I will write about “how to handle CRUD with Relationship”.

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio 2008 Express ISO image download

    • 20 Comments

    As usual Express editions are free but this time you can take this and sit in a remote location and install Visual Studio with no Internet connections. Yes we can download offline .iso to avoid download & install pain.

    Please visit, http://www.microsoft.com/express/download/offline.aspx

    VSE_Menu_Header_Logo

    After downloading you can write them in DVD. This version includes all the Express Editions.

    All-In-OneDVD

    So enjoy with this light-weight Visual Studio 2008 and have the magic. You can also install .iso by creating virtual drive by using utility such as Daemon.

    Namoskar!!!

  • Wriju's BLOG

    Free EBooks at CodePlex

    • 9 Comments

    There are many more books available. Go and grab them

     

    ·         Acceptance Test Engineering Guidance

    ·         Application Architecture Guidance

    ·         Common Service Locator

    ·         Composite Application Guidance for WPF

    ·         Design for Operations

    ·         Enterprise Library

    ·         ESB Guidance

    ·         GAX Extensions Library

    ·         Guidance Explorer

    ·         Performance Testing Guidance for Web Applications

    ·         Performance Testing Guidance Project

    ·         SharePoint Development Guidance

    ·         Smart Client Guidance

    ·         Team Development with Visual Studio Team Foundation Server

    ·         Unity Application Block

    ·         VSTS Guidance Project

    ·         WCF Security Guidance

    ·         Web Client Software Factory

    ·         Web Service Software Factory

     

    More http://msdn.microsoft.com/hi-in/practices/bb190344(en-us).aspx 

    Namoskar!!!

  • Wriju's BLOG

    LINQ to SQL : Using Transaction

    • 14 Comments

    LINQ to SQL uses optimistic concurrency be default. LINQ to SQL is pure in memory operation, because you normally get the data from database and store them in .NET memory and perform some pure in memory update to those objects and finally when you are done with your modification you give those data back to the database. But what if someone changes the data in between; this is quite possible in network scenario. The default behavior in LINQ to SQL is that whoever hits the database wins the race. This is called optimistic concurrency. You can implement pessimistic concurrency with the new Transaction in .NET 3.0.

     

    Let’s check it out

     

    I have a table

     

    Emp

    Id       int     

    Name  varchar(50)

     

    Let’s have some dummy data,

    Id      Name

    1        C# 1.0

    2        C# 2.0

    3        C# 3.0

    4        Orcas

     

    Now I want to play with the Id = 4, and modify as per the condition.

     

    Need this basic,

    [Table(Name="Emp")]

    public class Emp

    {

        [Column(IsPrimaryKey=true, IsDBGenerated=true)]

        public int Id { get; set; }

     

        [Column]

        public string Name { get; set; }

    }

     

    public class TestDB : DataContext

    {

        public Table<Emp> Emps;

     

        public TestDB(string s):base(s){}       

    }

     

    Now using this code I will write an application to update data in the database.

     

    static void Main(string[] args)

    {

        Console.Title = "LINQ to SQL Demo";

     

        string sConn = @"Database connection string";

        TestDB db = new TestDB(sConn);

     

        ObjectDumper.Write(db.Emps);  

           

        //Get the element you want to modify

        var query = db.Emps.First(e => e.Id == 4);

     

        //Update the memory object

        if (query.Name == "Orcas")

            query.Name = "Visual Studio 2008 Beta 2";

        else

            query.Name = "Orcas";

     

        //Just wait for other application to make changes

        //this is intetional as we need to throw an error

        Console.WriteLine("Ready to edit. Press any key..");

        Console.Read();

     

        //Update the database

        db.SubmitChanges();

       

        //Show the changed value

        ObjectDumper.Write(db.Emps);           

     

        }

    }

     

    Now if you compile and run this app in two different command window and both of them will come and wail with the line, “Ready to Edit. Press any key to continue..”.

     

    Whichever you click first will update the data and the second one will throw you and error.

     

    Unhandled Exception: System.Data.Linq.ChangeConflictException: Row not found or changed.

     

    This is optimictic concurrency, who executes first wins the race and other fails because there is a conflict in the actual source and the in memory data which you are modifying.

     

    Now if you inplement the same code with TransactionScope class which is new in .NET Framework 2.0.

     

     

    static void Main(string[] args)

    {

        Console.Title = "LINQ to SQL Demo";

     

        string sConn = @"Database connection";

        TestDB db = new TestDB(sConn);

     

        ObjectDumper.Write(db.Emps);  

       

        //This new Transaction class in .NET Framework 3.0

        using (TransactionScope ts = new TransactionScope())

        {

            //Get the element you want to modify

            var query = db.Emps.First(e => e.Id == 4);

     

            //Update the memory object

            if (query.Name == "Orcas")

                query.Name = "Visual Studio 2008 Beta 2";

            else

                query.Name = "Orcas";

     

            //Just wait for other application to make changes

            //this is intetional as we need to throw an error

            Console.WriteLine("Ready to edit.Press any key..");

            Console.Read();

     

            //Update the database

            db.SubmitChanges();

           

            //Complete the Transaction

            ts.Complete();

        }       

      

        //Show the changed value

        ObjectDumper.Write(db.Emps);           

    }

     

    This again uses the same behavior but with managed scope. Especially when you have multiple update happening and the error is more tempting I must say,

     

    Unhandled Exception: System.Data.SqlClient.SqlException: Transaction (Process ID 52) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

     

    No one likes to be a deadlock victim.

     

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity: LINQ to Entity with Relationship

    • 4 Comments

    Relationship and getting data from Entity Framework using Northwind database

    image

    Simple Query

     

    using (NorthwindEntities ctx = new NorthwindEntities())

    {

        var query = from o in ctx.Orders

                    select o.OrderID;

     

        foreach (var k in query)

        {

            Console.WriteLine(k);

        }

    }

     

    Now if you want to filter this with the parent information,

     

    var query = from o in ctx.Orders

                where o.Customers.City == "London"

                select o.OrderID;

    This actually goes one level up and then filters the data.

     

    Include Child Information

     

    var query = from c in ctx.Customers

                where c.City == "London"

                select c;

     

    foreach (var k in query)

    {

    Console.WriteLine(k.ContactName);

    }

     

    Now if you want to get the “Orders” table, there are two ways to do it,

     

    Immediate Loading

     

    var query = from c in ctx.Customers.Include("Orders")

                where c.City == "London"

                select c;

     

    foreach (var k in query)

    {

        Console.WriteLine(k.Orders.Count);

    }

     

    On-Demand Loading

     

    var query = from c in ctx.Customers

                where c.City == "London"

                select c;

     

    foreach (var k in query)

    {

        //if not loaded then load it

        if (!k.Orders.IsLoaded)

            k.Orders.Load();

     

        Console.WriteLine(k.Orders.Count);

    }

     

     

    Namoskar!!!

     

  • Wriju's BLOG

    LINQ to SQL vs. ADO.NET – A Comparison

    • 17 Comments

    ADO.NET is our contemporary data access component and now we have written many applications. Now there has been a lot of talk on LINQ to SQL. So we are little skeptical about this component and trying to find some relation between existing ADO.NET technology.

     

    Purpose of this post is to give some quick brief on some major differences between ADO.Net and LINQ to SQL. I have not used 100% code as this is just to give an idea. The database I have used here is Northwind (SQL Server 2000 Sample database).

     

    Some comparison,

     

    Scenario 1

    +++++++

    Establishing connection between database and application,

     

    ADO.NET

    using(SqlConnection conn = new SqlConnection("Connection String"))

    {

        conn.Open();

    }

     

    LINQ to SQL

    You create a .dbml file and give a name (assume “NW.dml”). Then there will be a DataContext class created. So you need to initialize the instance of an object.

     

    NWDataContext db = new NWDataContext("Connection String");

     

    You do not need to call any Open() method. Datacontext handles well the open and close method.

     

    Scenario 2

    +++++++

    Getting data from database,

     

    ADO.NET

    using(SqlConnection conn = new SqlConnection("Connection String"))

    {

        using (SqlCommand comm = new SqlCommand("Select * from Customers"))

        {

            conn.Open();

            SqlDataReader reader = comm.ExecuteReader();

            DataTable dt = new DataTable("New Table");

            dt.Load(reader);

        }

    }

     

    LINQ to SQL

    using (NorthwindDataContext db = new NorthwindDataContext())

    {

        //You can also use "var" at "IEnumerable<Customer>"

        IEnumerable<Customer> custs = from c in db.Customers

                                      select c;

     

        foreach (Customer c in custs)

        {

            Console.WriteLine(c.CompanyName);

        }

    }

     

    WOW!!! I have received comment from our Senior Program Manager Dinesh Kulkarni from LINQ to SQL team when I requested him to visit my blog. He mentioned,

    DataTable provides you a cache that can be re-enumerated without DB roundtrip while LINQ to SQL results need to be explicitly cached with something like a ToList()/ToArray(). Identity caching in DataContext aside, the L2S code is closer to enumerating a DataReader. Although DataReader does not allow you to re-enumerate and requires another ExecuteReader, the impact of reenumerating L2S query is the same – another roundtrip to DB.

    Scenario 3

    +++++++

    Inserting into the database,

     

    ADO.NET

     

    using(SqlConnection conn = new SqlConnection())

    {

        conn.Open();  

        SqlCommand comm = new SqlCommand("INSERT INTO...", conn);

     

        comm.ExecuteNonQuery();

    }

     

    LINQ to SQL

     

    using (NorthwindDataContext db = new NorthwindDataContext())

    {

        //Create a new object

        Customer c = new Customer();

        c.CustomerID = "ABCDE";

        //.... add all the properties you need to add while inserting

     

        //Add it to the collection

        db.Customers.InsertOnSubmit(c);

     

        //Save the changes to the database

        db.SubmitChanges();   

    }

     

    Scenario 4

    +++++++

    Updating database,

    ADO.NET

     

    Same as Scenario 3

     

    LINQ to SQL

    using (NorthwindDataContext db = new NorthwindDataContext())

    {

        //Get the object from database

        Customer cust = (from c in db.Customers where c.CustomerID == "ALFKI" select c).First();

     

        //Update the exsisting value

        cust.CompanyName = "I do not know?";   

       

           

        //Save the changes to the database

        db.SubmitChanges();   

    }

     

    Scenario 5

    +++++++

    Deleting records from the database,

    ADO.NET

     

    Same as Scenario 3

     

    LINQ to SQL

    using (NorthwindDataContext db = new NorthwindDataContext())

    {

        //Get the object from database

        Customer cust = (from c in db.Customers where c.CustomerID == "ALFKI" select c).First();

     

        //Remove it from collection

        db.Customers.DeleteOnSubmit(cust);

           

        //Save the changes to the database

        db.SubmitChanges();   

    }

     

    Scenario 5

    +++++++

    Executing stored proc which returns record(s),

     

    ADO.NET

    using(SqlConnection conn = new SqlConnection())

    {

        conn.Open();

        using (SqlCommand comm = new SqlCommand("SalesByCategory", conn))

        {

            comm.CommandType = CommandType.StoredProcedure;

            comm.Parameters.AddWithValue("@param1", "value1");

            comm.Parameters.AddWithValue("@param2", "value2");

     

            SqlDataReader reader = comm.ExecuteReader();       

        }

    }

     

    LINQ to SQL

    In LINQ to SQL it becomes metod as you drag and drop it to .dbml file,

     

    using (NorthwindDataContext db = new NorthwindDataContext())

    {

     

        var outPut = db.SalesByCategory("SeaFood", "1998");        

    }

     

    Performance of LINQ to SQL and ADO.NET

     

    LINQ to SQL Performance Part 1

    LINQ to SQL Performance Part 2

    LINQ to SQL Performance Part 3

    LINQ to SQL Performance Part 4

    LINQ to SQL Performance Part 5

     

    There are a many to discuss. Hope you have enjoyed it.

     

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to SQL : Update data through Object Model

    • 14 Comments

    LINQ to SQL support updating data through object. Continuing with my previous blog on INSERT, let me discuss about the update method

     

    static void Main(string[] args)

    {

        string strConnection = @"Connection String";

     

        TestDB db = new TestDB(strConnection);

       

        //Here I am finding the employee with Id 19

        var updateQ = db.Emps.First(e => e.Id == 19);

     

        //Then I will modify that employee name and give new name

        updateQ.Name = "Updated Employee";

                               

        //Commit the changes to database

        //at this point DML gets generated

        db.SubmitChanges();        

     

        //To view the updated data

        ObjectDumper.Write(db.Emps);

    }

     

    All the methods are coming from DataContext class (responsible for SQL query generation). The above method converts the object addition to DML query.

     

    Namoskar!!!

  • Wriju's BLOG

    Using Repository Pattern in Entity Framework

    • 8 Comments

    One of the most common pattern is followed in the world of Entity Framework is “Repository Pattern”. Since this is something which is heavily used and being practiced, I am not going to talk about the core pattern. Rather, try to show how one can implement it.

    Objectives

    As mentioned in http://msdn.microsoft.com/en-us/library/ff649690.aspx

    • You want to maximize the amount of code that can be tested with automation and to isolate the data layer to support unit testing.
    • You access the data source from many locations and want to apply centrally managed, consistent access rules and logic.
    • You want to implement and centralize a caching strategy for the data source.
    • You want to improve the code's maintainability and readability by separating business logic from data or service access logic.
    • You want to use business entities that are strongly typed so that you can identify problems at compile time instead of at run time.
    • You want to associate a behavior with the related data. For example, you want to calculate fields or enforce complex relationships or business rules between the data elements within an entity.
    • You want to apply a domain model to simplify complex business logic.

    Simple approach to ADO.NET Entity Framework

    Let’s have one domain class called “Employee”

    public class Employee
    
    {
    
        public int Id { get; set; }
    
        public string FullName { get; set; }
    
    }
    Now using this we will have a simple context class
    public class HRContext : DbContext
    
    {        
    
        public DbSet<DomainClasses.Employee> Employees { get; set; }
    
    }
    After that, define the repository interface IEmployeeRepository
    public interface IEmployeeRepository : IDisposable
    
    {
    
        IQueryable<Employee> All { get; }
    
        IQueryable<Employee> AllIncluding(params Expression<Func<Employee, object>>[] includeProperties);
    
        Employee Find(int id);
    
        void InsertOrUpdate(Employee employee);
    
        void Delete(int id);
    
        void Save();
    
    }
    Then the Repository class called EmployeeRepository
    public class EmployeeRepository : IEmployeeRepository
    
    {
    
        HRContext context = new HRContext();
    
        public IQueryable<Employee> All
    
        {
    
            get { return context.Employees; }
    
        }
    
        public IQueryable<Employee> AllIncluding(params Expression<Func<Employee, object>>[] includeProperties)
    
        {
    
            IQueryable<Employee> query = context.Employees;
    
            foreach (var includeProperty in includeProperties) {
    
                query = query.Include(includeProperty);
    
            }
    
            return query;
    
        }
    
        public Employee Find(int id)
    
        {
    
            return context.Employees.Find(id);
    
        }
    
        public void InsertOrUpdate(Employee employee)
    
        {
    
            if (employee.Id == default(int)) {
    
                // New entity
    
                context.Employees.Add(employee);
    
            } else {
    
                // Existing entity
    
                context.Entry(employee).State = EntityState.Modified;
    
            }
    
        }
    
        public void Delete(int id)
    
        {
    
            var employee = context.Employees.Find(id);
    
            context.Employees.Remove(employee);
    
        }
    
        public void Save()
    
        {
    
            context.SaveChanges();
    
        }
    
        public void Dispose() 
    
        {
    
            context.Dispose();
    
        }
    
    }
    Then you should be implementing it in your apps (any type Windows or Web), like a Console Application
    namespace ConsoleApplication
    
    {
    
        class Program
    
        {
    
            static void Main(string[] args)
    
            {
    
                GetSomeEmployee();
    
            }
    
            private static void IntiateData()
    
            {
    
                using (var repo = new EmployeeRepository())
    
                {
    
                    Employee em = new Employee() { FullName = "Wriju" };
    
                    repo.InsertOrUpdate(em);
    
                    repo.Save();
    
                }
    
            }
    
            private static void GetSomeEmployee()
    
            {
    
                using (var repo = new EmployeeRepository()) 
    
                {
    
                    foreach (var emp in repo.All)
    
                    {
    
                        Console.WriteLine("{0} - {1}", emp.Id, emp.FullName);
    
                    }
    
                }            
    
            }
    
        }
    
    }
    This obviously simple approach. The recommended options are to make the Repository generic and handle the related entities. I will discuss about them later.
    Namoskar!!!
  • Wriju's BLOG

    ADO.NET Entity: Insert Update and Delete with Relationship

    • 18 Comments

    Few days back I had written an article on Insert/Update/Delete for simple standalone tables at ADO.NET Entity: Insert Update and Delete. Now after that many of you had requested me to put article on how it works with relationship.

     

    Here I will use a database created by me. There will be two tables connected with each other.

    image

    Now I will create TestDB.edmx out of this database.

     

    image 

    Insert

     

    using (TestDBEntities ctx = new TestDBEntities())

    {

        //Create new Department

        Dept d = new Dept() { DeptName = "ADO Entity" };

     

        //Create new Employee 1

        EmpDept ed1 = new EmpDept() { EmpName = "ADO Employee 1" };

     

        //Create new Employee 2

        EmpDept ed2 = new EmpDept() { EmpName = "ADO Employee 2" };

     

        //Add employee to the Dept *OBJECT*

        d.EmpDept.Add(ed1);

        d.EmpDept.Add(ed2);

     

        //Updating the context

        ctx.AddToDept(d);

     

        //Save to Database

        ctx.SaveChanges();

    }

     

    Update

     

    using (TestDBEntities ctx = new TestDBEntities())

    {

        //Get an existing Department

        Dept dep = (from d in ctx.Dept

                    where d.DeptId == 22

                    select d).First();

     

        //Set new Department name

        dep.DeptName = "ADO.NET 3.0";

     

        //Create new Employee 2

        EmpDept ed2 = new EmpDept() { EmpName = "ADO 2" };

     

        //Add *new* employee to the Dept *OBJECT*

        dep.EmpDept.Add(ed2);

     

        //Save to Database

        ctx.SaveChanges();

    }

     

    Delete

     

    using (TestDBEntities ctx = new TestDBEntities())

    {

        //Get an existing Department

        Dept dep = (from d in ctx.Dept.Include("EmpDept")

                    where d.DeptId == 22

                    select d).First();

     

        /*

         Needd to do ToList() becuase once you delete

         a record then iteration will not be possible.         

        */

        foreach (EmpDept ed in dep.EmpDept.ToList())

        {

            //This removes relationship from Context

            dep.EmpDept.Remove(ed);

     

            //Delete it from context

            ctx.DeleteObject(ed);       

        }

     

        //Delete the master table

        ctx.DeleteObject(dep);

           

        //Save to Database

        ctx.SaveChanges();

    }

     

    Note: during delete you first need to remove the relationship from entity and then delete the object from entity. So you need to keep the child data offline and then do operation. Then delete the main object.

     

    In my next post I will write about “how to select with Relationship”.

     

    Namoskar!!!

     

  • Wriju's BLOG

    LINQ to SQL Windows Form Binding Data Step by Step

    • 11 Comments

    LINQ to SQL designer in Visual Studio allows us to create mapped class using the drag and drop feature from Server Explorer. Now that is business object which ideally you could use as your datasource and from Visual Studio 2008. So let us have this step by step,

    Open your Visual Studio 2008 and create a new Windows Forms application (assume C#).

    Now add new item to the project LINQ to SQL (.dbml). Give name NW.dbml.

    Open a new Data Connection from your VS 2008’s Server Explorer window.

    Point to Northwind database. Drag and drop Customers and Orders table. Since Customer and Order table has one to many relationship the designer will get generated like below,

    Dbml_thumb4

    Now open a data source from Data menu of your VS 2008. Click on add new Datasource. Add object DataSource.

    image

    Now click on next, choose Customer.

    image

    Click next and finish.

    Now your datasource window will show both Customer and Order because they are connected through PK/FK.

    image

    Make Customer as details view

    image

    Drag Customer to your Windows Forms. Then all the navigator and grid will be created as the RAD (Rapid Application Development).

    Now you also drag and drop Orders (this will create DataGrid). Now a add the code to your form_load event.

    private void Form1_Load(object sender, EventArgs e)

    {

    NWDataContext db = new NWDataContext();

    this.customerBindingSource.DataSource = db.Customers;

    }

     

    That's all.

    Final look,

    image

    Namoskar!!!

  • Wriju's BLOG

    Immediate Window is missing in Visual Studio Menu

    • 20 Comments

     

    When you do not see “Immediate” window under Debug menu of Visual Studio you may get frustrated. But there is a quick way to get it when required,

     

    Go to View > Other Windows > Command Window or press Ctrl+W, A

     

    Then type immed. It will bring the Immediate Window.

     

    And inside the Immediate Window if you type cmd it will bring the Command Window back again.

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to SQL : Paging Data

    • 11 Comments

    When we work with relational database and especially when with larger data we generally go for custom paging. This allows us to create superfast application.

     

    The simple logic for paged query is like,

     

    Let’s suppose you have 100 rows. Now you want to get data of page size 10 for page 2.

     

    So the starting record would be

     

    StartRecord = (PageNumber – 1) * PageSize

     

    For page 2 it would be

     

    StartRecord = (2 – 1) * 10 = 10 (may be you need to +1 to skip one record)

     

    Now when this comes to LINQ to SQL scenario remains the same where the implementation is little different.

     

    NorthWindDataContext db = new NorthWindDataContext();

     

    var query = from c in db.Customers

                select c.CompanyName;

     

    //Assuming Page Number = 2, Page Size = 10

    int iPageNum = 2;

    int iPageSize = 10;

     

    var PagedData = query.Skip((iPageNum - 1) * iPageSize).Take(iPageSize);

     

    ObjectDumper.Write(PagedData);

     

    Generated T-SQL,

    For SQL Server 2000 the provider does not support Skip().

     

    For SQL Server 2005

    ===================

    SELECT [t1].[CompanyName]
    FROM (
        SELECT ROW_NUMBER() OVER (ORDER BY [t0].[CompanyName]) AS [ROW_NUMBER], [t0]
    .[CompanyName]
        FROM [dbo].[Customers] AS [t0]
        ) AS [t1]
    WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
    ORDER BY [t1].[ROW_NUMBER]
    -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [10]
    -- @p1: Input Int (Size = 0; Prec = 0; Scale = 0) [10]
    -- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30428.1

     

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ: Query vs Lambda Expression

    • 8 Comments

     

    LINQ is not just for the developers who used to write queries for databases but also for the Functional Programmers. So do not worry if you are not very comfortable with SQL kind of queries, we have a very nice option called “Lambda Expression”. Here I am going to demonstrate the scenario for both the options with a small example. This example has an array of integers and I am only retrieving the even numbers using the power of LINQ. Here we go

     

    using System;

    using System.Collections.Generic;

    using System.Text;

    using System.Query;

    using System.Xml.XLinq;

    using System.Data.DLinq;

     

    namespace LINQConsoleApplication1

    {

        class Program

        {

            static void Main(string[] args)

            {

                int[] arrInt = {1,2,3,4,5,6,7,8,9,10};

     

                #region Place to change

                //Language Integrated Query

                var aa = from s in arrInt

                         where s % 2 == 0

                         select s;

                #endregion

     

                foreach (var item in aa)

                {

                    Console.WriteLine("{0}", item);

                }

                Console.ReadKey();

            }

        }

    }

     

    If you do not want to use the different approach of query for Language then you are free to use Lambda Expression. So just replace the #region area with the following code block results will be identical.

     

                #region Place to change

               

                //Lambda Expression

                var aa = arrInt.Where(s => s % 2 == 0);

     

                #endregion

     

    Output will look like

     

    Output

    =====================

    2

    4

    6

    8

    10

     

     

    Namoskar

     

  • Wriju's BLOG

    LINQ to XML : Creating complete XML document

    • 9 Comments

    LINQ to XML API allows us to create complete XML document as expected with all the elements. So this X-DOM has everything as you expect.

     

    Simple sample looks like,

     

     

    XDocument doc = new XDocument(

        new XDeclaration("1.0", "utf-16", "true"),

        new XProcessingInstruction("test", "value"),

        new XComment("This is comment by you"),

        new XElement("Employees",

            new XElement("Employee",

                new XAttribute("id", "EMP001"),

                new XElement("name", "Wriju"),

                new XCData("~~~~~~~XML CDATA~~~~~~~~"))));

     

    By calling Save method of XDocument (actually of XContainer) you can save it to a physical file. And the file will look like,

     

    <?xml version="1.0" encoding="utf-16" ?>

    <?test value?>

      <!-- This is comment by you -->

    <Employees>

      <Employee id="EMP001">

        <name>Wriju</name>

        <![CDATA[ ~~~~~~~XML CDATA~~~~~~~~]]>

      </Employee>

    </Employees>

     

    To me this looks like more aligned to the human thinking mechanism.

     

    Namoskar!!!

     

  • Wriju's BLOG

    Generics : An easy way to bind the data in DataGridView

    • 22 Comments

    Applied to: Visual Studio 2005 [C#]

     

    Yes this is Generics. The concept which helps us to create collection easily and elegantly. Two steps to create the list is demonstrated here.

     

    Step 1:

     

    You have one object say for list of products which contains three properties Name, Quantity and Price.

     

    using System;

    using System.Collections.Generic;

    using System.Text;

     

    namespace MSDN_Generics

    {

        class Product

        {

        

            private int _Quantity;

     

            public int Quantity

            {

                get { return _Quantity; }

                set { _Quantity = value; }

            }

     

            private int _Price;

     

            public int Price

            {

                get { return _Price; }

                set { _Price = value; }

            }

     

            private string _Name;

     

            public string Name

            {

                get { return _Name; }

                set { _Name = value; }

            }

     

            /// <summary>

            /// Constructor to initialize the class

            /// </summary>

            /// <param name="sName"></param>

            /// <param name="iQty"></param>

            /// <param name="iPrice"></param>

            public Product(string sName, int iQty, int iPrice)

            {

                _Name = sName;

                _Quantity = iQty;

                _Price = iPrice;

            }

         

        }

    }

     

     

    Step 2: Create a List of this class to use it for DataGridView’s datasource.

     

                List<Product> myProds = new List<Product>();

     

                myProds.Add(new Product("Prod 1", 1, 1));

                myProds.Add(new Product("Prod 2", 2, 2));

                myProds.Add(new Product("Prod 3", 3, 3));

                myProds.Add(new Product("Prod 4", 4, 4));

                myProds.Add(new Product("Prod 5", 5, 5));

                myProds.Add(new Product("Prod 6", 6, 6));

                myProds.Add(new Product("Prod 7", 7, 7));

     

                dataGridView1.DataSource = myProds;

     

    You need a namespace reference to use this Generic listing System.Collections.Generic

     

  • Wriju's BLOG

    VB.NET 9.0: Object and Array Initializers

    • 6 Comments

    Last week I was exploring VB.NET for the ISV demo delivery. Some findings I want to share with you. First the object and Array Initializers

     

    Let’s suppose we have a class called Customer

     

    Public Class Customer

        Public Id As Integer

        Public Name As String

    End Class

     

    Now when you initialize this object in conventional VB.NET, this could be your approach,

     

    Dim cust As New Customer()

     

    With cust

        .Id = 1

        .Name = "VB.NET"

    End With

     

    Now in VB.NET 9.0 we do things in little differently,

     

    Dim cust = New Customer() With {.Id = 2, .Name = "VB.NET 9.0"}

     

    Also for array initialization in VB.NET we go for,

     

    Dim objCusts(1) As Customer

    objCusts(0) = New Customer() With {.Id = 3, .Name = "VB.NET 10.0"}

    objCusts(1) = New Customer() With {.Id = 4, .Name = "VB.NET 11.0"}

     

    In VB.NET 9.0 we write,

     

    Dim objCusts() As Customer = { _

        New Customer() With {.Id = 3, .Name = "VB.NET 10.0"}, _

        New Customer() With {.Id = 4, .Name = "VB.NET 11.0"}}

     

    It is small (to me simple), it is sweet.

     

    Namoskar!!!

  • Wriju's BLOG

    XLinq: Create XML from object using LINQ

    • 4 Comments

     

    We have seen how to create the XML content from raw data initializing elements and attributes one by one. More realistic approach in the world of application development would be to read the values either from relational database or collection. Let’s use the combined power of LINQ and XLinq to create XML content easily and smartly.

     

    Using C# 3.0 enhancement, implicitly typed array which is the combination of anonymous object initializers to create the anonymously typed data structures.

    My famous Customers object, defined 

     

    var objCust = new[]

    {

     new {CustID = 2, CustName = "Sumitra", Phone = "123-123-1236"},

     new {CustID = 3, CustName = "Wriju", Phone = "123-123-1235"},

     new {CustID = 4, CustName = "Writam", Phone = "123-123-1234"},

     new {CustID = 1, CustName = "Debajyoti", Phone = "123-123-1237"}   

    };

     

    Now we will create XML out of it with proper order (notice that the CustID is not in proper sequence). We can filter the data with the help of LINQ.

     

    XElement _customers = new XElement("customers",

                            from c in objCust

                            orderby c.CustID //descending 

                            select new XElement("customer",

                                new XElement("name", c.CustName),

                                new XAttribute("ID", c.CustID),

                                new XElement("phone", c.Phone)

                                                )

                                        );

     

    Console.WriteLine(_customers);

     

    The output will look like.

     

    <customers>

      <customer ID="1">

        <name>Debajyoti</name>

        <phone>123-123-1237</phone>

      </customer>

      <customer ID="2">

        <name>Sumitra</name>

        <phone>123-123-1236</phone>

      </customer>

      <customer ID="3">

        <name>Wriju</name>

        <phone>123-123-1235</phone>

      </customer>

      <customer ID="4">

        <name>Writam</name>

        <phone>123-123-1234</phone>

      </customer>

    </customers>

     

    Isn’t it cool!!!! Yes, yes, yes….

     

    Namoskar

     

  • Wriju's BLOG

    Installing TFS 2010 is very very Easy

    • 3 Comments

    Installing Team Foundation Server 2010 is as easy as Microsoft Office Installation. This is my second attempt to install single server TFS 2010. I am successful again.

    Few things we need to take care is

    1. Use the Team Foundation Server 2010 Installation Guide and follow it step by step at http://www.microsoft.com/downloads/en/details.aspx?FamilyID=2d531219-2c39-4c69-88ef-f5ae6ac18c9f&displaylang=en

    2. I had to ensure that it has IIS and .NET Framework installed from Server Role.

    3. I had installed Windows Server 2008 R2 and then installed SQL Server 2008 R2 Standard. I have installed it with all the component including SSRS and SSAS.

    4. Then I downloaded and installed Windows SharePoint Services 3.0 x64 with Service Pack 2 from http://go.microsoft.com/fwlink/?LinkId=148457. Follow the instruction.

    5. Finally I installed Team Foundation Server 2010

    image

    Once the TFS 2010 Installation is complete it asks for the configuration

    image

    Configure the Proxy

    image

    Then Build service

    image

    Last thing is the Sharepoint. Once over you are ready to go. What is most important is the easily approach and we do not have to think about it. Enjoy the ALM via Team Foundation Server 2010.

    Namoskar!!!

  • Wriju's BLOG

    Code First EF 4.1 : Building Many to Many Relationship

    • 8 Comments

    Since we do not have any designer question might arise how can we create Many to Many relationship in Code First 4.1. Here it is

    public class Emp
    {
        public Emp()
        {
            Projects = new HashSet<Project>();
        }
    
        public int EmpId { get; set; }
        public string EmpName { get; set; }
        public ICollection<Project> Projects { get; set; }
    }
    
    public class Project
    {
        public Project()
        {
            Emps = new HashSet<Emp>();
        }
    
        public int ProjectId { get; set; }
        public string ProjectName { get; set; }
        public ICollection<Emp> Emps { get; set; }
    }
    
    public class EmpContext : DbContext
    {
        public DbSet<Emp> Emps { get; set; }
        public DbSet<Project> Projects { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var p1 = new Project() { ProjectName = "Fun Boat" };
            var p2 = new Project() { ProjectName = "Jumbo Jet" };
            var p3 = new Project() { ProjectName = "Free Zoo" };
    
            var e1 = new Emp() { EmpName = "Wriju" };
            var e2 = new Emp() { EmpName = "Wrishika" };
            var e3 = new Emp() { EmpName = "Saswati" };
    
            p1.Emps.Add(e1);
            p1.Emps.Add(e2);
    
            p2.Emps.Add(e2);
            p2.Emps.Add(e3);
    
            p3.Emps.Add(e3);
            p3.Emps.Add(e1);
    
            using (var ctx = new EmpContext())
            {
                ctx.Projects.Add(p1);
                ctx.Projects.Add(p2);
                ctx.Projects.Add(p3);
                    
                ctx.SaveChanges();
            }
        }
    }

    Generated database would look like

    image

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 : IsolatedStorage Save and Read Data to a File

    • 4 Comments

    Windows Phone 7 apps runs in an isolated environment and often application needs store and retrieve data from files. Application can use its IsolatedStorage to store and retrieve data.

    The example shows how to read from a  file and display it in ListBox and save data to the file located in its isolated storage.

    We need the class to create a structure for UI data binding.

    //Creating the structure to display
    public class MyDataClass
    {
        public string MSG { get; set; }
    }
    

    After that define the UI look,

    <ListBox Background="White" x:Name="lstDisplay" Grid.Row="1" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock FontSize="20" Foreground="Black" Text="{Binding Path=MSG}"></TextBlock>
                    <TextBlock Foreground="Black" Text="---"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>                
    </ListBox>
    

    We now need to initialize the IsolatedStorage for our application.

    IsolatedStorageFile myFile = IsolatedStorageFile.GetUserStoreForApplication();
    string sFile = "DataTest.txt";
    

    Once done we will start reading lines form the inline text file.

    public void LoadData()
    {
        //myFile.DeleteFile(sFile);
        if (!myFile.FileExists(sFile))
        {
            IsolatedStorageFileStream dataFile = myFile.CreateFile(sFile);
            dataFile.Close();
        }
    
        //Reading and loading data
        StreamReader reader = new StreamReader(new IsolatedStorageFileStream(sFile, FileMode.Open, myFile));
        string rawData = reader.ReadToEnd();
        reader.Close();
    
        string[] sep = new string[] { "\r\n" }; //Splittng it with new line
        string[] arrData = rawData.Split(sep,StringSplitOptions.RemoveEmptyEntries);
                            
        List<MyDataClass> dataList = new List<MyDataClass>();
        foreach (var d in arrData)
        {
            dataList.Add(new MyDataClass() { MSG = d });
        }
        //Binding data to the UI for display
        lstDisplay.ItemsSource = dataList;
    }
    

    Below is how we can save the data in the file.

    private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        if (txtMSG.Text.Trim() !="")
        {
            string sMSG = txtMSG.Text;
            StreamWriter sw = new StreamWriter(new IsolatedStorageFileStream(sFile, FileMode.Append, myFile));
            sw.WriteLine(sMSG); //Wrting to the file
            sw.Close();
    
            //Refresh the display
            LoadData();
            txtMSG.Text = "";
        }
    }
    

    Namoskar!!!

  • Wriju's BLOG

    LINQ to XML : Creating complex XML through LINQ

    • 14 Comments

    We can generate hierarchical object graph in our memory though LINQ. To be more realistic we can bring data from relational database. So if we consider Northwind database and use LINQ to SQL to bring all the Customers and their Orders and Order Details the query would look like,

     

     

    //LINQ to SQL way to get data from database

    var q = from c in db.Customers

            select new

            {

                CId = c.CustomerID,

                Orders = from o in c.Orders

                         select new

                         {

                             OID = o.OrderID,

                             Qty = from od in o.Order_Details

                                   select new { Qty = od.Quantity }

                         }

            };

     

     

     

    So what I am trying to do here is that, I am trying to fetch CustomerId from Customers table and OrderId from Orders table and Quantity from Order Details table. It is bringing 3 level deep data for me and storing it to memory.

     

    By using XElement and XAttribute I will create a single XML stream. Which will look like,

     

    <?xml version="1.0" encoding="utf-8"?>

    <customers>

      <customer id="ALFKI" country="Germany" contactName="Maria Anders" contactTitle="Sales Representative">

        <Orders id="10643" date="1997-08-25T00:00:00">

          <items>

            <item price="45.6000" quantity="15" />

            <item price="18.0000" quantity="21" />

            <item price="12.0000" quantity="2" />

          </items>

        </Orders>

        <Orders id="10692" date="1997-10-03T00:00:00">

          <items>

            <item price="43.9000" quantity="20" />

          </items>

        </Orders>

     

    …….

     

    To achieve this I have to write a very simple query like syntax based on the query I have written earlier,

     

    var query = new XElement("customers",

               from c in db.Customers                       

               select

                   new XElement("customer",

                       new XAttribute("id", c.CustomerID),

                       new XAttribute("country", c.Country),

                       new XAttribute("contactName", c.ContactName),

                       new XAttribute("contactTitle", c.ContactTitle),

     

                       from o in c.Orders

                       select new XElement("Orders",

                           new XAttribute("id", o.OrderID),

                           new XAttribute("date", o.OrderDate),

                                new XElement("items",

     

                           from od in o.Order_Details

                           select new XElement("item",

                                   new XAttribute("price", od.UnitPrice),

                                   new XAttribute("quantity", od.Quantity))))));

     

     

    It looks complex because it is one liner but actually it is very simple. This will give you the exact XML output mentioned earlier.

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ : IEnumerable<T> and IQueryable<T>

    • 4 Comments

    IEnumerable<T> and IQueryable<T> are the two most used terms of any LINQ discussion. What I am trying to here is that I am trying to simplify the two interfaces depending on their behavior. In LINQ world we generally have few providers available within .NET Framework, like LINQ to Object, LINQ to SQL, LINQ to XML.

     

    It is a statement that every LINQ statement returns IEnumerable<T>. IEnumerable works in steps. Meaning, when you write,

     

    var q = from a in b

               where a > 5

               select a;

    It creates a list out “b” depending on “where” then it creates another list for “select”. This is the behavior of LINQ to Object and LINQ to XML.

     

    image

     

    When you use LINQ to SQL it uses IQueryable<T>. This interface inherits from IEnumerable<T> but typically any LINQ to SQL generates T-SQL at the backend to be able to get the data for us. This evaluate and generates the query at one shot and gives us the whole data.

     

    image  

    Namoskar!!!

     

  • Wriju's BLOG

    Code First 4.1 : Using Stored Procedure to Insert Data

    • 4 Comments

    Code First in Entity Framework does not support Stored Procedure by default. As there is no designer we cannot even map our stored procs to the entity. There are a many scenario we have seen where we are bound to use stored procedure for any database modifications (insert/update/delete). Here is how we can use stored procedure.

    image

    This would finally call the Stored Procedure.

    The stored proc used here is very simple

    ALTER PROCEDURE [dbo].[stp_InsertEmp]
    (
    	@Name as VARCHAR(50)
    ) AS
     
    	INSERT INTO Emps(Name) VALUES(@Name)

    Namoskar!!!

  • Wriju's BLOG

    Choosing between ADO.NET Entity Framework and LINQ to SQL

    • 10 Comments

    As part of my day to job I come across a very common question from the developer community that one should be using LINQ to SQL (L2S) or ADO.NET Entity Framework (EF).

     

    Earlier I have posted a blog containing the features http://blogs.msdn.com/wriju/archive/2009/01/05/choosing-between-linq-to-sql-and-entity-framework.aspx. 

     

    To me I feel very excited about EF as it has got more power and capability than L2S. L2S was important for us to understand the new era of Object Relational Model (ORM) with native programming language querying (LINQ) capabilities. But going forward EF is the technology you should be focusing on.

     

    There has been another concern comes from dev community is that is LINQ to SQL going to retire? Answer to that is no. Microsoft will continue to support L2S and enhance based on customer feedback. Tim Mallalieu clearly have mentioned in his Post that Microsoft will heavily invest into EF and the most wanted features like POCO will be with .NET 4.0.

     

    EF is the recommended data access solution while accessing data using LINQ. LINQ to SQL will also be there.

     

    So when the question arises what to choose? Go ahead and plan for Entity Framework. I would like to share some of my thoughts around it,

     

    Why I should use Entity Framework?

    Ø       It simplifies the data access and allows me to create conceptual model required for my business.

    Ø       EF allows you to handle Many to Many relationship without extra join.

    Ø       Map related tables into single entity to reduce code complexity.

    Ø       Strong inheritance supports for (Table per hierarchy, subclass and concrete type)

    Ø       Consolidation for complex object is very easy.

    Ø       It has powerful query mechanism through EntitySQL. For them who do not like LINQ you can use EntityClient provider with EntitySQL.

    Ø       You can expose your modeled data through ADO.NET Data Services (Astoria).

    Ø       Database independent and based on standard ADO.NET Providers.

    Ø       There are many third party providers currently available.

    o        Devart offers provider for Oracle, MySQL and PostgreSQL

    o        Phoenix Software Solution offers EF provider for SQLite.

    o        Npgsql offers another provider for PostgreSQL.   

    o        OpenLink Software offers a very wide range of support for Oracle (versions 7.x to 11.x), Microsoft SQL Server (6.x to 2005), IBM DB2 , Sybase (4.2 to 12.x+), IBM Informix (5.x to 11.x), Ingres (6.4 to 9.x), Progress (7.x to 10.x), MySQL, PostgreSQL, and Firebird 

    o        Sybase SQL Anywhere provides support for SQL Anywhere.

    o        IBM natively supports databases like DB2, Informix and U2.

    Ø       <TODO: will add few more as and when come across>

     

    Closing

    At the end of the story I still feel good about LINQ to SQL when it comes to smaller applications with less complexity. Entity Framework is capable of handling large enterprise applications and will have more power in v2 (in .NET 4.0). So if you are targeting your application for multiple databases the L2S is not the right choice for you.

    My vote is for ADO.NET Entity Framework. You will enjoy with the conceptual model and Astoria.  

    Namoskar!!!

Page 1 of 25 (609 items) 12345»