• 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

    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

    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

    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

    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

    Visual Studio 2008 Automatic Property is the default snippet

    • 18 Comments

    Now if you type prop and hit "tab" twice, this will bring the Automatic property not the conventional property declaration.

    This is my new finding.

    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 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

    Changing the SiteMapDataSource’s XML filename at runtime

    • 15 Comments

     

    Applies to: ASP.NET 2.0

     

    ASP.NET 2.0 comes with set of very rich navigation controls like TreeView, Menu, SiteMapPath. Ideally these controls should load the values at runtime from any structured data sources, be it SQL or XML or TXT. The default and most commonly used provider is XmlSiteMapProvider which accepts the data from XML file. But if you have to load different XML files at runtime, then … Here we go

     

    Create two web.sitemap files

     

    File 1 [web.sitemap]

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

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

    <siteMap>

          <siteMapNode title="MyMenu 1" url="Default.aspx">          

          </siteMapNode>

    </siteMap>

     

    File 1 [web2.sitemap]

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

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

    <siteMap>

      <siteMapNode title="MyMenu 2" url="Default.aspx">

      </siteMapNode>

    </siteMap>

     

     

    Then put any navigation control in your aspx page with the SiteMapDataSource as data source.

     

    The main trick is with the web.config settings. There you have to mention all the files as the provider collection like

    <?xml version="1.0"?>

    <configuration>  

          <system.web>

                ………

                <siteMap defaultProvider="1SiteMap" enabled="true">

                      <providers>

                            <add name="1SiteMap" type="System.Web.XmlSiteMapProvider" siteMapFile="Web.sitemap"/>

                            <add name="2SiteMap" type="System.Web.XmlSiteMapProvider" siteMapFile="Web2.sitemap"/>

                      </providers>

                </siteMap>

          </system.web>

     

    Then in the page load event of your page (where the SiteMapDataSource and navigation controls are) change the property SiteMapProvider like

         

    protected void Page_Load(object sender, EventArgs e)

        {

            //The provider name mentioned in the web.config

            SiteMapDataSource1.SiteMapProvider = "2SiteMap";

        }

     

    Hope this will help in simpler way, but it is recommended that you should use SqlSiteMapProvider for all dynamic scenarios.

     

    Ref: http://weblogs.asp.net/scottgu/archive/2005/11/20/431019.aspx

     

    Namoskar

     

  • Wriju's BLOG

    C# 3.0 Features: Automatic Property

    • 15 Comments

    I am super excited with the Orcas March 2007 CTP release. I was doing the hands on with the C# and LINQ and as you know C# 3.0 comes with a lot of new things which increases the level of abstraction for the developer. We now write less and do more. As I often have mentioned in my previous entries and presentations with Microsoft Partner that now have think more on why not on how. I remember the day when I first learned the Property. I used to scratch my head on what to do with get or set. I probably started it now as we have snippet for property. Anyways in conventional way we declare property in a class like

     

    public class Customer

    {

        public Customer() { }

     

        private int _CustID;

     

        public int CustID

        {

            get { return _CustID; }

            set { _CustID = value; }

        }    

               

    }

     

    Now C# 3.0 suggests us not to invest so much. Rather than using property like

     

    private int _CustID;

     

    public int CustID

    {

        get { return _CustID; }

        set { _CustID = value; }

    }   

     

    We can declare property like

     

    public int CustID

    {

        get;

        set;

    }

     

    No more private variable or = or value etc required. This is Automatic property in C# 3.0.

     

     

    Namoskar!!!

  • Wriju's BLOG

    Orcas March 2007 CTP Error: Unable to find the requested .Net Framework Data Provider. It may not be installed.

    • 14 Comments

     

    If you have installed Orcas March 2007 CTP and trying to play with SQL Server 2005 Express database using the IDE feature. You might meet with an error mentioning “Unable to find the requested .Net Framework Data Provider.  It may not be installed.” while trying the below mentioned steps

     

    In Server Explorer, Add New Connection - > Choose SQL Server 2 - > Provide the local database server information -> (drop down will not be refreshed or if you forcefully type the database name in the text box) and hit OK button. The above mentioned error will block you to go ahead.

     

    I did install Orcas in fresh machine and then installed VS 2005 there. I think that was the issue. But the workaround is little tricky here,

     

    Steps to follow:

     

    Go to the folder C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG

    Select the Machine.config and then find the tag <DbProviderFactories> under <system.data>.Then next step is to hide all the provider entries which has either Version=3.5.0.0 or Version=9.0.242.0.

     

    Following are the entries in my machine

    <DbProviderFactories>

          <add name="Odbc Data Provider" invariant="System.Data.Odbc" description=".Net Framework Data Provider for Odbc" type="System.Data.Odbc.OdbcFactory, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

     

          <add name="OleDb Data Provider" invariant="System.Data.OleDb" description=".Net Framework Data Provider for OleDb" type="System.Data.OleDb.OleDbFactory, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

     

          <add name="OracleClient Data Provider" invariant="System.Data.OracleClient" description=".Net Framework Data Provider for Oracle" type="System.Data.OracleClient.OracleClientFactory, System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

     

          <add name="SqlClient Data Provider" invariant="System.Data.SqlClient" description=".Net Framework Data Provider for SqlServer" type="System.Data.SqlClient.SqlClientFactory, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

     

          <!--<add name="SQL Server Compact Edition Data Provider" invariant="System.Data.SqlServerCe" description=".NET Framework Data Provider for Microsoft SQL Server Compact Edition" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=3.5.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />

     

          <add name="SQL Server Compact Edition Client Data Provider" invariant="Microsoft.SqlServerCe.Client" description=".NET Framework Data Provider for Microsoft SQL Server Compact Edition Client" type="Microsoft.SqlServerCe.Client.SqlCeClientFactory, Microsoft.SqlServerCe.Client, Version=3.5.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />

          <add name="SQL Server CE Data Provider" invariant="Microsoft.SqlServerCe.Client" description=".NET Framework Data Provider for Microsoft SQL Server 2005 Mobile Edition" type="Microsoft.SqlServerCe.Client.SqlCeClientFactory, Microsoft.SqlServerCe.Client, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />-->

     

        </DbProviderFactories>

     

    Then you are ready to work. Everything else will work fine.

     

    Thanks to the entry from where I got the clue to the solution. You could find the bug entry at connect.

     

    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

    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

    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 to XML : Join Xml Data

    • 13 Comments

    Let’s say I have created two Xml files using LINQ to XML from Northwind database. I have taken two tables Category and Products and tried to join between two different files.

     

    Category XML

     

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

    <categories>

      <category id="1">

        <CategoryName>Beverages</CategoryName>

      </category>

      <category id="2">

        <CategoryName>Condiments</CategoryName>

      </category>

      <category id="3">

    ……

     

    Products XML

     

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

    <products>

      <product ProductID="1" CategoryID="1">

        <ProductName>Chai</ProductName>

      </product>

      <product ProductID="2" CategoryID="1">

        <ProductName>Chang</ProductName>

      </product>

    ……

     

    LINQ rocks here,

    XElement prods =  XElement.Load(@"..\..\XmlData\Product.xml");

    XElement cats = XElement.Load(@"..\..\XmlData\Category.xml");

     

    var root =

        from p in prods.Descendants("product")

        join c in cats.Descendants("category")

        on

            (string)p.Attribute("CategoryID")

        equals

            (string)c.Attribute("id")

        select new

        {

            ProductId = (string)p.Attribute("ProductID"),

            ProductName = (string)p.Element("ProductName"),

            CategoryName = (string)c.Element("CategoryName")

        };

     

    //Console.WriteLine(root.Count());

     

    foreach (var k in root)

    {

        Console.WriteLine(k);

    }

     

    Output will look like,

    { ProductId = 1, ProductName = Chai, CategoryName = Beverages }

    { ProductId = 2, ProductName = Chang, CategoryName = Beverages }

    { ProductId = 3, ProductName = Aniseed Syrup, CategoryName = Condiments }

     

    If you want to create Xml file

     

    var root = new XElement("ProdList",

        from p in prods.Descendants("product")

        join c in cats.Descendants("category")

        on

            (string)p.Attribute("CategoryID")

        equals

            (string)c.Attribute("id")

        select new XElement("ProductCategory",

    new XAttribute("ProductID", (string)p.Attribute("ProductID")),

    new XElement("ProductName", (string)p.Element("ProductName")),

    new XElement("CategoryName", (string)c.Element("CategoryName"))));

     

    Console.WriteLine(root);

     

     

    Output will look like,

    <CategoryName>Produce</CategoryName>

    </ProductCategory>

    <ProductCategory ProductID="8">

      <ProductName>Northwoods Cranberry Sauce</ProductName>

      <CategoryName>Condiments</CategoryName>

    </ProductCategory>

    <ProductCategory ProductID="9">

      <ProductName>Mishi Kobe Niku</ProductName>

      <CategoryName>Meat/Poultry</CategoryName>

    </ProductCategory>

    …..

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to XML : Changing connectionString in app.config

    • 12 Comments

    When you create data bind application using wizard in Windows Forms application and connection string gets added to you settings file. Now you may be interested in changing that connection string but problems,

    1)     The connection string in settings has an Application Scope so it is ReadOnly property. You modify and remove “ReadOnly” from .vb file but it gets refreshed whenever you try to add new or modify anything.

    2)     Things in Settings gets stored into <applicationName>.exe.config file.

     

    I took the challenge to alter the app.config file and save it again. During my try I found that LINQ to XML is the easiest way to alter with its powerful API. So the sample I have created does looks for the first <connectionString> in the <connectionStrings> section and then alters the connectionString attribute of <add element.

     

    Actually in app.config the section looks like,

    <connectionStrings>

        <add name="AppConfigChange.My.MySettings.Connstr"

            connectionString=

    "Data Source=wghosh2k3\sqlexpress;Initial Catalog=Northwind;Integrated Security=True"

            providerName="System.Data.SqlClient" />

     

    I am changing the highlighted part and saving it back to the same file.

     

    And the code looks like,

     

    Dim sNewConnStr As String = ""

     

    'Get the file info

    Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

     

    'Load the file info

    Dim xml = XElement.Load(config.FilePath)

     

    'Get the first config section (first connection string info)

    Dim connStrXML = xml.Descendants("connectionStrings").Elements().First()

     

    'Get the connection string value

    Dim connStr = connStrXML.Attribute("connectionString").Value

     

    'Create an array with ';'

    Dim arrConn() As String = connStr.Split(";")

     

    For i As Int16 = 0 To arrConn.Length - 1

        'Get the attribute and value splitted by "="

        Dim arrSubConn() As String = arrConn(i).Split("=")

        If (arrSubConn.Length = 2) Then

            Dim sConnAttr As String = ""

            Dim sConnValue As String = ""

            sConnAttr = arrSubConn(0)

            sConnValue = arrSubConn(1)

     

            'Change Database name

            If (sConnAttr = "Initial Catalog") Then

                'This is the place where you will be changing the database name

                sConnValue = "NewDBName"       

       End If

     

            'Generate newly altered connection string

            sNewConnStr += sConnAttr + "=" + sConnValue + ";"

        End If

    Next

     

    After doing everything you need to save it back to the same file,

     

    'Modify the existing connection string information

    connStrXML.SetAttributeValue("connectionString", sNewConnStr)

     

    'Saving config at the same place

    xml.Save(config.FilePath)

     

     

    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 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

    C# 3.0 : Exploring Lambda Expression

    • 10 Comments

    I started playing with Lambda expression after the TechEd demo by Anders Hejlsberg. Couple of nice things I would like to share with you.

     

    As there might be many definitions for Lambda expression but to me Lambda Expression is the concise way to write functional implementation for Anonymous Method. This is been used by compiler to translate LINQ to method calls. This also allows us to maintain 100% backward compatibility with any managed version of C#.

     

    Lambda function can be created using the Generic delegate Func. Func<A,R> (represents a function taking an argument of type A and returning a value of type R) is the predefined .NET call to a delegate for n number of parameters with any type. Life is easy for us. Func is defined inside System.Linq namespace. So being developer we do not have to bother about the number of variable and there types. We can simply go ahead and create any function using Func.

     

    Now if you have an anonymous method for a List of Integers which finds the even numbers from the list.

     

    //Generic List of Integers

    List<int> arrInt = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

     

    //Using delegate (anonymous method) get the even numbers

    List<int> even1 = arrInt.FindAll(delegate(int i2) { return i2 % 2 == 0; });

     

    //dump them in the console

    foreach (int j in even1)

    {

        Console.WriteLine(j);

    }

     

    Now, if I want to implement Lambda Expression there the code will look like,

     

    //Generic List of Integers

    List<int> arrInt = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

     

    //Using Lambda Expression get the even numbers

    List<int> even1 = arrInt.FindAll(i => i % 2 ==0);

     

    //dump them in the console

    foreach (int j in even1)

    {

        Console.WriteLine(j);

    }

     

    Now, if you want to create the same list by using Lambda Expression and Func

    //This means I am creating a function which

    //takes an argument integer and returns bool.

    Func<int, bool> EvenGetter = x => x % 2 == 0;

     

    //Generic List of Integers

    List<int> arrInt = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

     

    //Using Lambda Expression get the even numbers

    IEnumerable<int> even1 = arrInt.Where(EvenGetter);

     

    //dump them in the console

    foreach (int j in even1)

    {

        Console.WriteLine(j);

    }

     

    So here we are reusing a Function with the name EvenGetter and this is like any other function not in embedded.

     

    Func is very powerful, we can create List of Lambda Expression Functions and iterate through the list and check one input through multiple functions,

     

    Let us assume that I need to pass one integer and get some four out puts. I will create Generic List of Func’s which takes one argument as double and returns double.

     

    List<Func<double, double>> funcs = new List<Func<double,double>>();

     

    //Add function to the list

    funcs.Add(x => x * x); //Get the square

    funcs.Add(x => 1 / x);

    funcs.Add(x => Math.Sqrt(x)); //Sqr root of x

     

    //iterate through the list

    foreach (var f in funcs)

    {

        //Execute the functions one by one with the value 100

        Console.WriteLine(f(100));   

    }

     

     

    Output

    ---------

    10000

    0.01

    10

    Press any key to continue . . .

     This is pure functional programming.


    Namoskar!!!

  • Wriju's BLOG

    LINQ: Query to SQL, XML and Object and JOIN them

    • 10 Comments

    Getting data from SQL, XML and Object and joining them using Language Integrated Query is something you might be looking for. I have created a small application which brings data from SQL Server (table name is Employee), XML (file name is Department.xml) and Object (Generic list containing list of Managers).

     

    My SQL Table Looks like

     

    EmpId           int     

    EmpName      varchar(50)

    DeptId          int

    ManagerId     int

     

    Now the DeptID is linked to an XML file (where the department name is assigned against DeptId is that file)

     

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

    <Departments>

      <Department id="1" name="Software"></Department>

      <Department id="2" name="Service"></Department>

      <Department id="3" name="Support"></Department>

    </Departments>

     

    And to get the XML data from the file located at C:\XMLData you need

     

    public static List<Departments> GetDepartments()

    {

        //Loading the XML file and storing it in List of type Departments

    var query = from e in XElement.Load(@"C:\XMLData\Department.xml").Elements("Department")

                    select new Departments

                   {

                       DeptID = (int)e.Attribute("id"),

                       DeptName = (string)e.Attribute("name")

                   };

     

        return query.ToList();

    }

     

     

     

    Manager id is also like that and it has details in Generic List.

     

    List<Managers> mgrs = new List<Managers>

    {

        new Managers{ManagerId = 1, ManagerName = "Manager 1"},

        new Managers{ManagerId = 2, ManagerName = "Manager 2"}               

    };

     

    Now for each of the three entities I have object representation in my code,

     

    /*

    Class for the XML data coming from physical file

    Using the Automatic feature

    */

    public class Departments

    {

        public int DeptID{get;set;}

        public string DeptName{get;set;}

    }

     

    /*

    Class for the Linq to Sql

    Table is in SQL Express 2005 Database "Northwind"

    Attributes are coming from the namespace "System.Data.Linq.Mapping"

    */

    [Table(Name="Employee")]

    public class Employees

    {

        [Column]

        public int EmpId { get; set; }

        [Column]

        public string EmpName { get; set; }

        [Column]

        public int DeptId { get; set; }

        [Column]

        public int ManagerId { get; set; }

    }

     

    /*

    This class is for the pure C# List<Managers>   

    */

    public class Managers

    {

        public int ManagerId { get; set; }

        public string ManagerName { get; set; }

    }

     

    Now you have to join them to get the linked data. Linq comes into the picture to help you out in this scenario.

     

    static void Main(string[] args)

    {

        //Connection string for the Linq to Sql

        string sConn =

           @"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;

                                                 Integrated Security=True";

     

        //Initializing the connection

        DataContext db = new DataContext(sConn);

       

        var query =

            from emp in db.GetTable<Employees>().ToList()

            join dep in GetDepartments() on emp.DeptId equals dep.DeptID

            join mgr in GetManagers() on emp.ManagerId equals mgr.ManagerId

                    select new

                           {

                               EmpName = emp.EmpName,

                               DeptName = dep.DeptName,

                               ManagerName = mgr.ManagerName

                           };

     

        foreach (var res in query)

        {

            Console.WriteLine("Name={0}, Dept={1}, Manager={2}"

                               ,res.EmpName, res.DeptName, res.ManagerName);

        }

    }

     

    I have attached full source code as attached.

     

    Namoskar!!!

     

  • Wriju's BLOG

    IE 7 Shortcut keys tips

    • 10 Comments

    We have started enjoying the IE7 and IE 7 always tries to help us by providing the possible shortcut keys (as being impatient we miss it). Here are those for you and me

     

    Keyboard shortcuts

    Open links in a new tab in the background

    CTRL+click

    Open links in a new tab in the foreground

    CTRL+SHIFT+click

    Open a new tab in the foreground

    CTRL+T

    Open a new tab from the Address bar

    ALT+ENTER

    Open a new tab from the search box

    ALT+ENTER

    Open Quick Tabs (thumbnail view)

    CTRL+Q

    Switch between tabs

    CTRL+TAB/CTRL+SHIFT+TAB

    Switch to a specific tab number

    CTRL+n (n can be 1-8)

    Switch to the last tab

    CTRL+9

    Close current tab

    CTRL+W

    Close all tabs

    ALT+F4

    Close other tabs

    CTRL+ALT+F4

    Mouse shortcuts

    Open a link in a background tab

    Click the middle mouse button on a link

    Open a new tab

    Double-click the empty space to the right of the last tab

    Close a tab

    Click the middle mouse button on the tab

     

    Namoskar!!!

  • Wriju's BLOG

    Windows Forms – Enable Shortcut Key all over the Form

    • 10 Comments

    Windows Application and shortcut key are synonyms. People prefer to use shortcut keys for faster activity. Assume you are in a text box and you want to hit F5 to reload the form. You do not want to move your mouse cursor. So what you will be doing is that you will be adding “Key Down” event to the text box. But if you are in a different text box or in a button that will not work. So you will add “Key Down” event to your form.

     

    But you need to enable a property to work it properly and that’s the trick.

     

    private void Form1_KeyDown(object sender, KeyEventArgs e)

    {

        if (e.KeyCode == Keys.F5)

        {

            btnRefresh_Click(null, null);

        }

    }

     

    But golden trick is, in the property window of the Form make the following changes

     

    KeyPreview = True 

    Enjoy programming. 

    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!!!

  • Wriju's BLOG

    LINQ to SQL : Returning Scalar Value from Stored Procedure

    • 10 Comments

    In LINQ to SQL it is not that easy thing to achieve as compared to other features. Let us assume you have a Stored Procedure like,

    Case 1: With Output Parameter

    CREATE PROCEDURE [dbo].[GetEmployeeCount]

          @OutVal DateTime OUTPUT

    AS

    BEGIN

          SELECT @OutVal = GetDate()

    END

    You need to write code which will look like,

    using (TestDBDataContext db = new TestDBDataContext())

    {

        //Need a Nullable type here

        //and you need to have some value to it

        DateTime? dt = null;

        var q = db.GetEmployeeCount(ref dt);

     

        Console.WriteLine(dt);               

    }

    Case 2: With Return (only for Integers)

    CREATE PROCEDURE [dbo].[GetEmployeeCountRet]         

    AS

    BEGIN

          DECLARE @Ret INT

          SELECT @Ret = COUNT(*) FROM Emp

          RETURN @Ret

    END

    Your code may look like,

    using (TestDBDataContext db = new TestDBDataContext())

    {

        //For Stored Procedure with Return value (for Integer)

        //returns Int

        var q = db.GetEmployeeCountRet();

     

        Console.WriteLine(q);               

    }

    You cannot simply say

    SELECT COUNT(*) FROM Emp and capture the value in a variable. Because in LINQ to SQL a Stored Procedure either returns ISingleResult<T> or IMultipleResults<T>, so capturing single value becomes very tricky.

    So when you have to do it go for Scalar-Valued function

    Case 3: Using Scalar-Values Functions

    ALTER FUNCTION [dbo].[fn_GetEmployeeCount]()

    RETURNS int

    AS

    BEGIN

          DECLARE @ResultVar int

         

          SELECT @ResultVar = Count(*) FROM Emp

         

          RETURN @ResultVar

    END

    You code,

    using (TestDBDataContext db = new TestDBDataContext())

    {

        var q = db.fn_GetEmployeeCount();

     

        Console.WriteLine(q);               

    }

    Namoskar!!!

  • Wriju's BLOG

    Windows Phone 7 - Binding Data to ListBox through Code

    • 10 Comments

    In Windows Phone 7 we need to display data programmatically. Below one demonstrates the simply way of binding data through code.

    Suppose you have Emp class as below.

    public class Emp
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    Let’s create List<Emp>

    List<Emp> myData = new List<Emp>()
    {
        new Emp(){Id = 1, Name = "Wriju"},
        new Emp(){Id = 2, Name = "Writam"},
        new Emp(){Id = 3, Name = "Saswati"},
        new Emp(){Id = 4, Name = "Wrishika"},
        new Emp(){Id = 5, Name = "Baba"},
        new Emp(){Id = 6, Name = "Ma"}
    };
    

    After that format the ListBox to display it properly.

    <Grid>
        <ListBox Name="listBoxEmployee">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=Id}"></TextBlock>
                        <TextBlock Text=" - "></TextBlock>
                        <TextBlock Text="{Binding Path=Name}"></TextBlock>
                    </StackPanel>
                </DataTemplate>               
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
    

    Now, you need to simply code to bind the data

    lstData.ItemsSource = myData;
    

    This is a very simple example but useful in many scenario and applied to most of the data-bound application.

    Namoskar!!!

Page 1 of 25 (609 items) 12345»