• Wriju's BLOG

    LINQ to SQL : Enabling .dbml file for WCF

    • 7 Comments

    LINQ to SQL is object relational model and .dbml file generates the class file for all kind of Create, read, update and delete (CRUD) through the mapping mechanism. Ideally this should allow us to enable it for WCF Service. But for that we have to manually add DataContract and DataMember attributes. We can use .dbml’s designer feature to add those to our code.

     

    Simply right click on the dbml designer and press F4 to get the property window, you will get a property “Serialization Mode”. Set it to “Unidirectional”. That’s all. This is simple but very helpful.

     

    DBMLWCF

     

    Now your DataContext and Properties will have the following attributes,

    [DataContract()]

    [DataMember(Order=n)]

    Wherever required. *n indicates the sequence.

     

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio 2008 Training Kit Videos on LINQ

    • 3 Comments

    Visual Studio 2008 Training Kit videos are now available on web. Get some real exciting presentations

     

    VS2008 Training Kit: What's new in C# 3.0?

    VS2008 Training Kit: What's new in Visual Basic 9.0?

    VS2008 Training Kit: .NET Language Integrated Query (LINQ)

    VS2008 Training Kit: Using LINQ with Relational Data

     

    For more detailed list please visit http://channel9.msdn.com/Showforum.aspx?forumid=38&tagid=267

     

    Enjoy learning.

     

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio 2008 and LINQ Case Studies

    • 1 Comments

    Some of the early adopters case studies are now available,

     

    Xcalia

    OpenNETCF Consulting

    Sogeti Group

    K2

     

    Get some of the quotes from there,

     

     

    LINQ is an object-oriented language and so fits perfectly with the philosophy of our product, which aims to make technical details of data access transparent to the developer.

     

    LINQ helped us simplify how we targeted code objects and dictionaries inside our product. Experiencing it firsthand has made us quite enthusiastic about the technology.

     

    We believe that LINQ is more than just a query language for retrieving data from data sources. In fact, it should also be considered as another way to implement your algorithm in your application.

     

    We were looking everywhere for something to help us test our AJAX code, and the features in Visual Studio Team System are some of the best around.

     

    We’ll ship better quality code earlier. Development and support costs will drop dramatically because we can find bugs earlier through better testing.

     

    We now spend less time doing product support and more time producing new code because the applications are more reliable.

     

    I opened up the code in Visual Studio 2008 Professional, and in three to four minutes, I recompiled some 100,000-plus lines of code

     

    The kind of agility we got from Visual Studio Team System 2008 Architecture Edition at both the micro and system level saved lots of time by making modeling easier.

     

    These are from real world implementation.

     

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio 2008 and .NET 3.5 Namespaces Posters

    • 3 Comments

    Get it printed and paste in your cubicle,

    clip_image001

    Visual C# 2008 Poster

    clip_image001[6]

    .NET Framework 3.5 Common Namespaces and Types Poster

    Other posters are available also at Microsoft Downloads.

    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

    C# 3.0 : Evaluation of Lambda Expression to Language INtegrated Query (LINQ)

    • 8 Comments

    From code name “cool” to C# 3.0, it’s been a long journey for this amazing language with .NET Runtime. Here I am going to show you the evaluation step by step.

     

    Let us assume we have generic list of integers and I need to find the even numbers from that list,

     

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

     

    C# Way: Beginners

    +++++++++++++

    List<int> even1 = new List<int>();

     

    foreach (int i in arrInt)

    {

        if (i % 2 == 0)

            even1.Add(i);               

    }

     

    foreach (int item in even1)

    {

        Console.WriteLine(item);

    }

     

     

    C# 1.1 Way: Using Delegate

    +++++++++++++++++++

    Using Predicate<T> we can call delegate and then with some existing method’s help I can get the data as I require.

     

    So the method I need here will look like,

     

    public static bool EvenGetter(int i2)

    {

        return i2 % 2 == 0;

    }

     

    Now the predicate implementation seems something like,

     

    List<int> even1 = arrInt.FindAll(new Predicate<int>(EvenGetter));

     

    foreach (int item in even1)

    {

        Console.WriteLine(item);

    }

     

    C# 2.0 Way: Using Anonymous Method

    ++++++++++++++++++++++++++

     

    Anonymous Methods helps us to implement delegate without having any method.

     

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

     

    foreach (int item in even1)

    {

        Console.WriteLine(item);

    }

     

    C# 3.0 Way: Using Lambda Expression

    ++++++++++++++++++++++++++

    Hmm, this is magic. Please refer C# 3.0 Specification for more information.

     

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

     

    foreach (int item in even1)

    {

        Console.WriteLine(item);

    }

     

    C# 3.0 Way: Implementing LINQ

    ++++++++++++++++++++++

    Write SQL like query as native statement, LINQ Rocks!!!

     

    IEnumerable<int> even1 = from i in arrInt

                             where i % 2 == 0

                             select i;

     

    foreach (int item in even1)

    {

        Console.WriteLine(item);

    }

     

    This is the actual conversion happens when you compile the above code.

    IEnumerable<int> even1 = arrInt.Where(i => i % 2 == 0);

     

    Actual IL (disassembled) generated code looks like,

    IEnumerable<int> even1 = <>g__initLocal0.Where<int>(delegate (int i) {

            return (i % 2) == 0;

        });

     

    Pure code.

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to SQL: Working with hierarchical data

    • 7 Comments

    LINQ to SQL supports hierarchical data and you can easily create a query and get output from there. Let us take an example of Northwind database. Northwind has Category -> Products -> Order_Details tables. -> indicates one to many relationships here. So ideally for a Category can have multiple products and a product can have multiple Orders (in Order_Details). Now to get the number of Orders given for each Products under a category of id with their total price we have to write sub queries and SQL will become complex.

     

    But if we use LINQ to SQL and drag and drop all the three tables there. The designer will look like,

     

    clip_image001

     

    Now to get the required output we can write a simple LINQ statement,

     

    NorthwindDataContext db = new NorthwindDataContext();

    var query =

     

    from p in db.Products

    where p.CategoryID == 1

    select new

    {

    p.ProductID,

    p.ProductName, 

    p.Category.CategoryName,

         NumOrders = p.OrderDetails.Count,

         Revenue = p.OrderDetails.Sum(o=>o.UnitPrice * o.Quantity)

    };

     

    TextBox1.Text = db.GetCommand(query).CommandText;

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to SQL : New method DataContext.GetCommand()

    • 5 Comments

    LINQ to SQL we can read the generated T_SQL query using DataContext.Log or SQLQueryVisualizer. But If you are working with WebProject the Log property not very much convenient as you have to use TextWriter to dump the generated T-SQL query.

     

    In Orcas Beta 1 we had DataContext.GetQueryText which used to give us the generated T-SQL now we do not have this from Visual Studio 2008 Beta 2. I have mentioned about this change in one of my earlier Blog post. The implementation is here,

     

    TextBox1.Text = db.GetCommand(query).CommandText;

     

    Now this will give you the DataContext generated T-SQL query.

     

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio 2008 and .NET Framework 3.5 Release Date

    • 1 Comments

    Visual Studio 2008 and the .NET Framework 3.5 will be available by the end of November 2007. For more please refer http://www.microsoft.com/presspass/press/2007/nov07/11-05TechEdDevelopersPR.mspx

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET 2.0 : Fine tune your DataSet Performance

    • 2 Comments

    ADO.NET 2.0 offers us a unique feature through which we can make a real lightweight DataSet. This is very important and much neglected development practice to overlook the performance part. So when you have huge data and you are getting multiple hit this small tune may help you a lot.

     

    Assume I am working with Orders table and creating a DataSet out of it. Now this DataSet can be shared through network. When we pass the data the bigger stream size can create problem. Let us create a text file to check the size,

     

    DataSet dsOrders = new DataSet();

     

    using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Orders", CONN_STR))

    {

        da.Fill(dsOrders);

        gridOrders.DataSource = dsOrders;

        gridOrders.DataMember = dsOrders.Tables[0].TableName;

    }

     

    //Setting the Property to make it lightweight

    dsOrders.RemotingFormat = SerializationFormat.Binary;

     

    BinaryFormatter bf = new BinaryFormatter();

    using (FileStream fs = new FileStream(@"C:\DataSet_2.txt", FileMode.OpenOrCreate))

    {

        bf.Serialize(fs, dsOrders);

    }

     

    If you do not set the SerializationFormat.Binary then the default setting is SerializationFormat.Xml. This is huge compared to Binary.

     

    Size of the generated file, is

     

    Xml     :  434 KB

    Binary :  139 KB

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0: Vote for the keyword “var”

    • 4 Comments

    You all probably know what is “var”. You might have a question why this new keyword is required in programming language like C#. One of the few strong reasons is to have an Anonymous Type stored in a variable. Whenever you have to initialize a type you have to mention the type before you give a name for a variable. But can you do something like this,

     

    AnonymousType~1 obj = new {Id = 1, Name="Wriju"};

     

    The anonymous type will be decided during compile time and it is random. You simple cannot assume anything here.  The proper way of declaration would be,

     

    var obj = new {Id = 1, Name="Wriju"};

     

    Another area in LINQ where to get multi column output we often use anonymous type and get the IEnumerable of that type. So when you have no type in place can you declare IEnumerable of that type?

     

    var q = from c in db.Customers

            select new { c.CompanyName, c.ContactName };


    If you want to have IEnumerable<T> then you have to have type T defined in your apps somewhere. But it is very inconvenient to have a type defined every time you want to get a different combination.

     

    Things to remember,

    Ø       var cannot be used as public property/field

    Ø       var cannot be a return type of any method

     

    Otherwise var rocks and it is Reflection enabled. Performance is equal.

     

    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

    LINQ to SQL : Some of the best BLOGs

    • 2 Comments

    Some of the best blogs on LINQ to SQL I found are available for great learning,

    Scott Guthrie

    The Famous LINQ TO SQL Series

    There are several good new blogs from members of the Microsoft C# team. Nevertheless, the most important items in this edition of Community Convergence are Rico Mariani's series of articles on LINQ to SQL performance.

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio 2008 Videos

    • 2 Comments

    No better place to learn VS 2008 than http://msdn2.microsoft.com/en-us/vstudio/bb655906.aspx 

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 : Anonymous Type and .NET Reflection Hand-in-Hand

    • 2 Comments

    Anonymous Type is nothing but the type which gets defined by CLR (not you). So that type is as rich as any other normal type. Probably the conventional way to find the components of an Anonymous Type through reflection would be clearer to us,

     

    static void Main()

    {

        //Anonymous Type

        var anyType = new

        {

            IntID = 1,

            StringName = "Wriju"

        };

     

        Type t = anyType.GetType();

     

        PropertyInfo[] pi = t.GetProperties();

     

        foreach (PropertyInfo p in pi)

        {

            //Get the name of the prperty

            Console.WriteLine(p.Name);

        }

     

        //Using LINQ get all the details of Property

        var query = from p in t.GetProperties()

                    select p;

     

        ObjectDumper.Write(query);

    }

      

     

    Namoskar!!!

     

  • Wriju's BLOG

    Pattern’s and Practices Guidance Explorer

    • 2 Comments

    This is one tool which will help you to find anything and everything for what you might scratch your head.

     

    This tool is amazing. Please go ahead and install from

    Download

    Download GuidanceExplorer build 20060926 http://www.codeplex.com/guidanceExplorer/Project/FileDownload.aspx?DownloadId=2716

     

    This is the best Guidance you can get in your day to day programming.

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 : Anonymous Types

    • 6 Comments

    C# 3.0’s Anonymous Type is a cool feature and it allows us to create object and collection of no type. Actually the type does not exist but on the fly you can create object out of that type. Let’s say you need to create some object which will have two properties Id of type int and Name of type string. In normal scenario, you have to write a class and then create the object of that class. But C# 3.0 allows us to declare an object of that type and assign value to it.

     

    Suppose you need this Class

     

    public class Cust

    {

        public int CustId { get; set; }

     

        private string _CustName;

        public string CustName

        {

            get { return _CustName; }

            set { _CustName = value; }

        }

    }

     

    But you are too lazy to create the class. This C# 3.0 will create this class for you. So if you write something like

     

    var obj = new { CustId = 1, CustName = "C#" };

     

    OneTypes

     

    Notice here after the keyword “new” I have no type name. This gives instruction to the compiler to create a dummy type for me. Now Visual Studio is so exciting that this does not require me to compile to be able to provide me the IntelliSense support. Without compiling I can get the IntelliSense and auto complete.

     

    Whenever I will use obj and after the “.” Visual Studio 2008 IntelliSense will show me the two properties,

     

    Img1

     

    One of the drawbacks is that you cannot reset the property value. So if you try to write, obj.CustId = 1; will through you an error.

     

    Property or indexer 'AnonymousType#1.CustId' cannot be assigned to

    -- it is read only  

     

    This is because it creates get-only property and can only be initialized through the Object Initializers feature of C# 3.0.

     

    Another observed behavior is that if you create object with the keyword “new”, like,

     

    var obj = new { CustId = 1, CustName = "C#" };

     

    var obj2 = new { Id = 1, Name = "C#" };

     

    TwoTypes

     

     

    Now the compiler will create two anonymous types as the property name differs.

     

    But….

     

    If you use objects like,

     

    var obj = new { CustId = 1, CustName = "C#" };

     

    var obj1 = new { CustId = 1, CustName = "C#" };

     

    Compiler will not create multiple types as the name is same.

     

    But!!!

     

    Interestingly if you have declarations like,

     

    var obj = new { CustId = 1, CustName = "C#" };

     

    var obj1 = new { CustId = "A", CustName = "C#" };

     

    var obj2 = new { CustId = 2.2, CustName = "C#" };

     

     

    The CLR will create only one Type, but the compiler will give you three different date type options for the three objects.

     

    Img2

    For obj the CustId will be inferred as type “int”.

     

    Img3

    For obj1 the CustId will be inferred as type “string”.

     

     

    Img4   

    For obj2 the CustId will be inferred as type “double”.

     

    This is because the generated IL creates the type as Generic type. With the

     

    .field private initonly !'<CustId>j__TPar' '<CustId>i__Field'

     

    "initonly" is readonly and "!" indicates that the type is generic.

     

    Namoskar!!!

  • Wriju's BLOG

    Get 1 GB Storage at Skydrive Windows Live

    • 1 Comments

    Get 1 GB storage online at http://skydrive.live.com. Microsoft launched it today.

    For more details please visit http://skydriveteam.spaces.live.com/default.aspx.

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio 2008 : How to add Visualizer for LINQ

    • 6 Comments

    There are two very important visualizers for LINQ which are not part of default installation.

     

    The visualizers are

    Ø       ExpressionTree Visualizer

    Ø       SqlServerQuery Visualizer  

     

    Both the visualizers are available from

     

    Visual Basic

    Samples for Visual Studio 2008 Beta 2

     

    Visual C#

    LINQ and language samples for Visual Studio 2008 Beta 2

     

    Once you install them you will find the ExpressionTree Visualizer and SqlServerQuery Visualizer under

     

    ..My Documents\Visual Studio Samples\LinqSamples\

    ExpressionTreeVisualizer\ExpressionTreeVisualizer

     

    ..My Documents\Visual Studio Samples\LinqSamples

    \QueryVisualizer\SqlServerQueryVisualizer

     

    If you open the *.proj from these two folders and compile them you will get two dlls

    Ø       ExpressionTreeVisualizer.dll

    Ø       LinqToSqlQueryVisualizer.dll

     

    Under bin\debug or bin\release folder depending on the type of build you select. Now copy both the dlls and drop them to the folder located under My Documents

     

    ..My Documents\Visual Studio 2008\Visualizers

     

    Once it is there, and you are in the debug mode inside your visual studio 2008 these two options will come respectively.

     

    View of LinqToSqlQuery Viauslizer

     

    ExpressionTree

     

    Now click on the "Linq to SQL Debugger Visualizer" button,

     

    Sql

     

     

     

     

    View of ExpressionTree Viauslizer

     

    Sql

     

    Now click on the "Expression Tree Visualizer" button,

     

    Sql

     

     

     

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to SQL : Change in DataContext from Beta 1 to Beta 2

    • 2 Comments

    During the demonstration I have noticed that two major methods of DataContext has changed from Beta 1 to Beta 2.

     

    First one, is the new name for the class DataShape(). Now there is no class called DataShape() but we have DataLoadOptions().

     

     

    var loadOption = new DataLoadOptions();           

    loadOption.LoadWith<Customer>(c => c.Orders);

     

    db.LoadOptions = loadOption;

     

    Secondly,

     

    DataContext does not have any method called GetQueryText() it got changed to GetCommand().

     

    Please let me know if you find something else. I will update this entry.

     

    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

    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

    Have you tried LINQPad (Beta)?

    • 1 Comments

    Experiment and learn new concept of LINQ. This is just an exe which requires no extra installation.

    Pre-requisites

    Download

    http://www.albahari.com/LINQPad.exe

    For more information please visit,

    http://www.albahari.com/linqpad.html

    Aha this is from my screen,

     LINQPad

    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

    S. Somasegar (Soma) and Scott Guthrie on Orcas Beta 2

    • 1 Comments

    Channel 9 video at http://channel9.msdn.com/showpost.aspx?postid=329443

    Namoskar!!!

Page 20 of 25 (609 items) «1819202122»