• Wriju's BLOG

    LINQ to SQL : What is DataContext.Translate Method

    • 4 Comments

    DataContext’s Translate method converts existing IDataReader to an IEnumerable<T>. This is very useful when you may need to run raw SQL Query though System.Data.Linq. I am getting few similarities with DataContext’s ExecuteQuery.

     

    How Translate works

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

    Assuming I am using Northwind database.

     

     

    using (NWDataContext db = new NWDataContext())

    {

        DbConnection conn = db.Connection;

        conn.Open();

     

        DbCommand comm = conn.CreateCommand();

        comm.CommandText = "SELECT * FROM Customers";

     

        DbDataReader reader = comm.ExecuteReader();

     

        var q = db.Translate<Customer>(reader);

     

        ObjectDumper.Write(q);

    }       

     

    Now since my dbml has Customer class defined and I am running SELECT * query this can map with existing Customer class. But if I want to retrieve only the selected columns from the result set then one of the drawbacks is that I cannot project the output using Anonymous Type, rather I need to define a class in my app to project it to IEnumerable<T>. One of the reasons is that the Anonymous Type does not create any default public constructor. It would have been nice to have this anonymous type projection with the Translate.

     

    So if you want to map it to your type then your approach would be little different.

     

    using (NWDataContext db = new NWDataContext())

    {

        DbConnection conn = db.Connection;

        conn.Open();

     

        DbCommand comm = conn.CreateCommand();

        comm.CommandText = "SELECT CustomerId, CompanyName FROM Customers";

     

        DbDataReader reader = comm.ExecuteReader();

     

        var q = db.Translate<CustomerSelect>(reader);

     

        ObjectDumper.Write(q);

    }   

     

    Extra things you need is that,

     

    class CustomerSelect

    {

        public int CustID { get; set; }

        public string CompanyName { get; set; }

    }

     

    Whereas in ExecuteQuery method you do things little differently,

     

    using (NWDataContext db = new NWDataContext())

    {

        var q = db.ExecuteQuery<Customer>("SELECT * FROM Customers", "");

     

        ObjectDumper.Write(q);

    }

     

     

    Namoskar!!!

  • Wriju's BLOG

    ASP.NET 3.5 Extension Preview

    • 1 Comments

    What is that? Know more on http://quickstarts.asp.net/3-5-extensions/

     

    Other related resources,

     

    ASP.NET 3.5 Extensions Preview Download

    ASP.NET 3.5 Extensions Preview Forums

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 : Useful keyword “var”

    • 6 Comments

    People complain about the keyword “var”. Especially, when we use it with the strict programming language like C# in .NET. Developers also complain about the readability part of it. I totally agree with them, but the scenarios where there will be no options but the “var” when it comes to on the fly projection of Language INtegrated Query (LINQ). Can you initialize Anonymous Type without “var”? There are so many no-nos. Let’s appreciate it and start use. I already have explained in one of my previous blogs,

     

    Scenario 1 (Anonymous Type)

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

    When you have no type defined but want to create that, we need “var”.

     

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

     

    You cannot assume the name created by compiler for this Anonymous Type. Please feel free to add comment to my blog if you have choice to add type in the above example while declaring the variable.

     

    Scenario 2 (Projecting it to IEnumerable<AnonymousType>)

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

    Suppose if you want to get the output containing only the selected column you have to project it to a type.

     

    IEnumerable<CustomerSelect> query =

        from c in db.Customers

        where c.City == "London"

        select new CustomerSelect

        {

            CustID = c.CustomerID,

            CompanyName = c.CompanyName

        };

     

    As you cannot have “,” as you are used to for any T-SQL query. Here you need everything as strongly typed. So you need to create a class, here I have created one,

     

    class CustomerSelect

    {

        public int CustID { get; set; }

        public string CompanyName { get; set; }

    }

     

    So here boldly you can retrieve the result like, IEnumerable<CustomerSelect>

    in case if you do not want to use var here. But if you are lazy developer like me then you might not be interested in creating class for every need. Rather you will use anonymous type and get the IEnumerable<AnounymousType> as query output. But how will be defining IEnumerable of some anonymous type (in fact no type). No wander you must appreciate the real power of “var” here.

     

    var query =

        from c in db.Customers

        where c.City == "London"

        select new

        {

            CustID = c.CustomerID,

            CompanyName = c.CompanyName

        };

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 : Joining two in-memory collection through LINQ

    • 4 Comments

    LINQ allows us to join different collection source provided we are mapping with two properties with the same type. It is easy, it is quick and it is concise.

     

     

    //Create Employee Class

    class Employee

    {

        public int ID { get; set; }

        public string Name { get; set; }

        public string ManagerId { get; set; }

    }

     

    //Create Manager Class

    class Manager

    {

        public string Id { get; set; }

        public string Name { get; set; }

    }

     

    class Program

    {

        //Create the List<Manager>

        static List<Manager> GetManagers()

        {

            return new List<Manager>

            {

                new Manager(){Id = "M1", Name = "Manager 1"},

                new Manager(){Id = "M2", Name = "Manager 2"}

            };

        }

     

        //Create the List<Employee>

        static List<Employee> GetEmployees()

        {

            return new List<Employee>

            {

                new Employee(){ID = 1, Name = "A", ManagerId = "M1"},

                new Employee(){ID = 2, Name = "B", ManagerId = "M1"},

                new Employee(){ID = 3, Name = "C", ManagerId = "M1"},

                new Employee(){ID = 4, Name = "D", ManagerId = "M1"},

                new Employee(){ID = 5, Name = "E", ManagerId = "M2"},

                new Employee(){ID = 6, Name = "F", ManagerId = "M2"},

                new Employee(){ID = 7, Name = "G", ManagerId = "M2"},

                new Employee(){ID = 9, Name = "H", ManagerId = "M5"}

            };

        }

     

        static void Main(string[] args)

        {

            /*Doing join between two sources

             *The record will be retieved only the mathched data

                 * Output will give values from both the collection

                 */

                var query = from e in GetEmployees()

                            join m in GetManagers() on e.ManagerId equals m.Id

                            select new

                            {

                                EmployeeId = e.ID,

                                EmployeeName = e.Name,

                                Manager = m.Name

                            };

     

                foreach (var o in query)

                {

                    Console.WriteLine("{0}-{1} [{2}]",

                        o.EmployeeId,

                        o.EmployeeName,

                        o.Manager);

                }           

            }       

        }

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 Feature Articles

    • 0 Comments

    With this exciting release of .NET Framework 3.5 I have been exploring its magic and sharing the finding with you. Here I am compiling all of them together for indexing,

     

    C# 3.0: Vote for the keyword “var”

     

    C# 3.0 Features: Automatic Property

    C# 3.0 Features: Automatic Property (Part 2)

    C# 3.0 Features: Automatic Property (Part 3)

     

    C# 3.0 Enhancements: Lambda Expression

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

    C# 3.0 : Exploring Lambda Expression

     

    C# 3.0 Enhancements: Expression Trees

     

    C# 3.0 Enhancements: Object Initializers

    C# 3.0 Enhancements: Collection Initializers

     

    C# 3.0 Enhancements: Extension Methods

     

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

    C# 3.0 : Anonymous Types

     

    C# 3.0 : Partial Methods

     

    C# 3.0 is 100% backward compatible with C# 2.0

     

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 : Partial Methods

    • 1 Comments

    C# 2.0 and Partial class, in one of the amazing features to work with one class separated in multiple physical files. Not only that, it also helps us to extend designer generated code such as Typed DataSet, Designer generated code etc.

     

    With this C# 3.0, we can now have partial method. Partial methods are the code block which reside inside a partial type and gets executed only when it has definition. This gives us the extensibility and if user wants to implement the rule, they can go ahead and define the body but if they do not want it will not. This improves the performance as you are not loading/creating unwanted methods.

     

    Here I am going to explain what is that? People already have documented about this feature in so many places, here I am,

     

    Let us consider this piece of code,

     

    public partial class MyClass

    {

        //Public Constructor

        public MyClass(int iInput)

        {

            //Calling Partial Method

            GetMessage(iInput);

        }

     

        //Public Property

        public string Messgae { get; set; }

     

        //Partial Method

        partial void GetMessage(int iVal);

    }

     

    In the partial method declaration I cannot have any body. So, where we need to define the body of our method?

     

    Should be in another partial class (I will explain that later). But since there is no body, the method actually will have no existence in IL.

     

    clip_image001

    Notice no existence for the method GetMessage(int iVal)

     

    Calling block,

    static void Main(string[] args)

    {

        MyClass obj = new MyClass(10);

     

        Console.WriteLine(obj.Messgae);

    }

     

    Now if you define the body of the function in a partial class the IL will look different as well as the Console.WriteLine()will print the value.

     

    PartialMethod2

     

    Notice this IL, this has got the definition for GetMessage in it.

     

    How the definition would look like,

     

    public partial class MyClass

    {

        partial void GetMessage(int iVal)

        {

            this.Messgae =

    "The value entered by you is : " + iVal.ToString();

        }

    }

     

    Some golden rules on Partial Methods, (these are the typical errors you will get from Visual Studio if anything is missing)

     

    You must visit wesdyer’s blog for more detailed specification.

     

    Ø       A partial method must be declared within a partial class or partial struct

    Ø       A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers

    Ø       Partial methods must have a void return type

    Ø       A partial method cannot have out parameters

    Ø       Definition has to end with “;” No {} is allowed in this scope.

     

     

    Some good resources,

     

    http://community.bartdesmet.net/blogs/bart/archive/2007/07/28/c-3-0-partial-methods-what-why-and-how.aspx

     

    Namoskar!!!

  • Wriju's BLOG

    Architecture Journal Reader (Beta) is available for download

    • 2 Comments

    Another Windows Presentation Foundation implementation for the popular Architecture Journal is now available for download. So know about Ray Ozzie the Chief Software Architect of Microsoft – the most prestigious position in Microsoft which was captured by Bill Gates.

     

    Project Astoria, S+S and many more. All the 13 published journals are available in nice readable format.

     

    So go ahead and download Just Released: Architecture Journal Reader (Beta)

     

    Let’s check what I am reading,

     

    image

     

    Namoskar!!!

  • Wriju's BLOG

    MSDN Virtual Labs : C# 3.0, Visual Basic 9.0, ASP.NET 3.5

    • 1 Comments

    Learn and for installation-free mode and get started with Visual Studio 2008.

     

    MSDN Virtual Lab: Building Web Applications with Visual Studio 2008

    MSDN Virtual Lab: What's new in C# 3.0

    MSDN Virtual Lab: What's new in Visual Basic 9

     

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity Framework 3.5 Beta 3 Released today

    • 3 Comments

    Beta 3 of the ADO.NET Entity Framework, and a preview of ASP.NET 3.5 Extensions. Designed to make it even easier for developers to build data-centric applications and services regardless of the underlying data source, the ADO.NET Entity Framework is already gaining significant support from multiple database vendors and third-party providers, including Core Lab, Data Direct Technologies, Firebird, IBM, MySQL AB, Npgsql, OpenLink Software, Phoenix Software, Sybase and VistaDB.

     

    Microsoft also announced today a preview of ASP.NET 3.5 Extensions, which leverages the Entity Framework to make it easier for developers to build rich, interactive data-centric applications on the Web. The ASP.NET 3.5 Extensions Preview includes:

    • ADO.NET Entity Framework
    • ASP.NET MVC
    • ADO.NET Data Services
    • ASP.NET Dynamic Data
    • New additions to ASP.NET AJAX
    • Silverlight controls for ASP.NET

     

    Downloads

    +++++++

    ·         Entity Framework Beta 3 runtime

     

    ·         Entity Framework Tools CTP 2

     

    ·         ASP.NET 3.5 Extensions preview

     

    Enjoy.

     

    Namoskar!!!

     

  • Wriju's BLOG

    LINQ to SQL and C# 3.0 Hands on Labs

    • 1 Comments

    Hands on labs are available online and this is the best HOL till date for LINQ and C# 3.0.

     

    LINQ Hands On Labs

    LINQ to SQL Hands on Lab

    C# 3.0 Language Enhancements Hands On Lab

     

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

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

Page 20 of 25 (620 items) «1819202122»