• Wriju's BLOG

    Internet Explorer 8: Start of a new era

    • 3 Comments

    Being web developer I am super excited about the release of Internet Explorer 8. There are lots of talks and already we have Beta 1. Now there are some thousands features with this version and many are planned for the new version. Excitements anxiousness and many more..

    The two major goals for this release are

    Ø  Developer productivity

    Ø  User productivity

    This version of IE allows us (anyone regardless he is pro/dev) to be able to customize. There were bugs in IE7 that are addressed here apart from the new features.

    The WebSlice and Activity are the most amazing things here. If you install it you will enjoy them.

    Some start up resources,

    Find more on,

    http://www.microsoft.com/windows/products/winfamily/ie/ie8/default.mspx

    https://blogs.msdn.com/ie/

    Namoskar!!!

  • Wriju's BLOG

    Visual Studio 2008 Product Comparison

    • 1 Comments

    One of the mostly asked questions in the Visual Studio adopters group is “what am I not getting with my version?”. This probably sometimes leads to a business decision towards buying.

    cover image: Visual Studio 2008 Product Comparison
    Download the data sheet (from MSDN)

    One place for all your queries, at http://msdn.microsoft.com/en-us/vstudio/products/cc149003.aspx

    Namoskar!!!

  • Wriju's BLOG

    LINQ : IEnumerable<T> and IQueryable<T>

    • 4 Comments

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

     

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

     

    var q = from a in b

               where a > 5

               select a;

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

     

    image

     

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

     

    image  

    Namoskar!!!

     

  • Wriju's BLOG

    LINQ to SQL : FAQ Answer By Matt Warren

    • 3 Comments

    Wonderful composition of FAQ is available at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2769747&SiteID=1 by Matt Warren.

     

    Q: How do I get default values from the database when inserting new entities?

    A: LINQ to SQL does not support using default values from the database.  The values in the entity at the time SubmitChanges is called are used instead.  You can override how LINQ to SQL inserts entities by implementing an insert method on the DataContext.  For an entity type called ‘Entity’ implement a function with the signature of ‘InsertEntity(Entity instance)’. 

    Q:  How do I attach and update entities?  When I attach and call SubmitChanges nothing happens.

    A:  Attaching entities to a DataContext may not work as you intend.  An attached entity is merely the equivalent of an entity that has just been queried from the database and not yet modified.  In order to instruct the DataContext that you intend to have the entity updated you must provide it with information describing how the entity has changed.  You can do this in a variety of ways.  1) You can call Attach to add the entity to the DataContext and then modify individual properties.  This assumes the entity is not already in a modified state.  2) You can call the form of Attach that takes both a current and original instance of the entity.  The DataContext will recognize that individual properties values differ.  3) You can call the form of Attach that takes an additional Boolean parameter set to true to indicate that the DataContext should treat the entity as all properties modified.  The option requires that the object have a version property.

     Q: How do I serialize entities using .Net Remoting?

    A: LINQ to SQL does not support serialization using .Net Remoting.  Key data types such as EntityRef and EntitySet are not serializable. 

    Q: How do I serialize entities using WCF (Windows Communication Foundation)?

    A: LINQ to SQL supports serialization as XML via WCF by generating WCF serialization attributes and special serialization specific logic during code-generation.  You can turn on this feature in the designer by setting serialization mode to ‘Unidirectional’.  Note this is not a general solution for serialization as unidirectional mode may be insufficient for many use cases.

    Q: How do I move entities between tiers in my multi-tier application?

    A:  While it is possible to use WCF serialization to move entities between tiers it may be insufficient for your application as it will not allow for round-tripping of changes.  Defining a custom data exchange contract as part of your web service API is a better all around solution.

     Q: Should I create a new DataContext in every business logic method?

    A: The DataContext conforms to the Unit of Work design pattern.  Unless you are moving data between physical tiers between each operation you should keep your DataContext alive for the duration of work.

    Q: Should I keep my DataContext in a static/global/shared variable?

    A: The DataContext is not thread safe and is not meant to be shared.  A DataContext is meant to be used for a single unit or work or at most  for multiple consecutive units of work.

    Q: Where should I put my business logic?  The system I’m currently developing uses static methods on the entities themselves for loading, saving and other operations.

    A: The DataContext conforms to the Unit of Work design pattern.  A work context must exist and be maintained separate from the entities themselves.  You should either place all your business logic as methods on the DataContext or devise a separate business context that encapsulates a DataContext instance.  You should not be using static methods.

    Q: Are LINQ to SQL entities Business Entities or Data Transfer Objects?  How do I build a business layer on top of LINQ to SQL?

    A: LINQ to SQL entities are both business entities and data transfer objects.  LINQ to SQL takes the place of your Data Access Layer and is the basis for your Business Layer.  You can add business logic directly to the DataContext or encapsulate the DataContext in your own business context.  The purpose for making a separate business context would be to restrict access to other DataContext methods.  If this is not an issue for you, putting all business logic methods on the DataContext is the best choice.

     Q: How can I keep entities cached beyond the lifetime of a single DataContext?  I want to keep a collection of entities in a cache so that all subsequent requests can read from this cache instead of going back to the database each time.

    A: It is possible to cache entities beyond the lifetime of a single DataContext.  However, it is dangerous to do this for entities with defer loaded properties as you are likely to get accesses back to the originating DataContext if these properties are ever navigated.  You are also likely to unintentionally retain all entities materialized via that same DataContext causing what may appear to be a memory leak.  To alleviate these problems you can either turn deferred loading off when first retrieving these entities or you can dispose the DataContext after the entities are fully loaded using an operation such as ToList or ToArray.

     Q: How can I re-attach an entity to a new DataContext?  When I try to do this I get an exception thrown.

    A: LINQ to SQL does not support re-attaching entities.  Entities are never actually detached from their originating DataContexts. The Attach methods are intended to be used with entity instances that are newly created after round-tripping data from another physical tier.  LINQ to SQL detects that an entity belongs to another DataContext if any deferred properties are still unloaded.  It is possible to trick the DataContext into accepting entities from another DataContext by either not having deferred properties, pre-loading all of them or turning deferred loading off on the originating DataContext.

     Q: How can I use globally cached entities to initialize the association properties of a new entity instance or to change an association property in order make an update?  When I try this I get strange behaviors like inserts I did not intend or exceptions thrown during SubmitChanges.

    A: LINQ to SQL does not support mixing and matching entities loaded from different DataContext instances together in the same object graph.  Trying to do so is generally a bad idea.  Most association properties are bi-directional, so assigning one to a property of another or adding one to a collection property changes state and references in both entities.  This means that globally cached entities are being modified potentially on multiple threads at the same time (when running as a service).  As a general rule of thumb, a single connected entity graph should only be associated to a single unit of work at a time.  Instead of using globally cached entities to assign association properties, use entities retrieved from the DataContext you are using to perform the insert or update, or assign values to the foreign key fields directly to avoid extra round-trips to the database server.

     

    Namoskar!!!

  • Wriju's BLOG

    MSDN Magazine Topics Online

    • 1 Comments

    • C# (566)

  • Wriju's BLOG

    LINQ to XML : Modifying XML document

    • 8 Comments

    You have XML document now you want to modify that XML file using LINQ to XML. It is as easy as you generally modify any database column value.

     

    Let us create a dummy XML stream,

     

    //Create dummy XML to work

    var root = new XElement("parent",

        from i in new int[] { 1, 2, 3, 4, 5, 6 }

        select new XElement("child",

            new XAttribute("number", i)));

     

    This will create XML like,

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

    <parent>

      <child number="1" />

      <child number="2" />

      <child number="3" />

      <child number="4" />

      <child number="5" />

      <child number="6" />

    </parent>

     

    Let us play with this XML file,

     

    //Get the element (child3)

    XElement child3 = root.Descendants("child").First(

        el => (int)el.Attribute("number") == 3);

     

    //Add element before the child3

    child3.AddBeforeSelf(new XElement("child25"));

     

    //Add sub-element to the child3

    child3.Add(new XElement("grandchild"));

     

    //Add element after the child3

    child3.AddAfterSelf(new XElement("child35"));

     

    //Add attribute to the child3

    child3.Add(new XAttribute("attr", "something"));

     

    //Change the existing attribute

    child3.SetAttributeValue("number", 100);

     

    After all these activities you will get the following output,

     

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

    <parent>

      <child number="1" />

      <child number="2" />

      <child25 />

      <child number="100" attr="something">

        <grandchild />

      </child>

      <child35 />

      <child number="4" />

      <child number="5" />

      <child number="6" />

    </parent>

     

    Highlighted part is the modified portion of your XML. You can also remove an element,

     

    child3.Remove();

     

    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

    The Developer Highway Code Free E Book

    • 1 Comments

    The Developer Highway Code, written by Paul Maher of DPE, is a concise handbook that captures and summarizes the key security engineering activities that should be an integral part of the software development process. This companion guide should be a must for any Developer, Architect, Tester etc. undertaking software development...The book is presented in easy to read checklist form, covering essential guidance on writing and releasing secure code. And it is available for free!

    “Developers are a most critical component to a more safe computing experience for all computer users in the UK and around the world. Code written for a program or operating system, or process must be able to withstand the most aggressive attempts to ‘break it’.  From games to mission-critical operations, secure code will form the base for success or disaster.  The Developer Highway Code should be a required reading." Edward P Gibson, Chief Security Advisor, Microsoft Ltd

    Where can you get The Developer Highway Code?

    Download full book only as a pdf or Download full book only as an xps

    I got the information from here.

    Namoskar!!!

  • Wriju's BLOG

    LINQ to XML : Adding Namespace quickly

    • 6 Comments

    I have written a post earlier on how to attach Namespaces. After reading my article someone complained about the redundancy of the code. I also realized the pain. I was reading the book C# 3.0 In a Nutshell. There I got a very elegant solution. Let me explain the scenario,

     

    If you create a XML like,

     

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

    - <numbers xmlns="urn:myns-com">

      <number value="1" square="1" xmlns="" />

      <number value="2" square="4" xmlns="" />

      <number value="3" square="9" xmlns="" />

      <number value="4" square="16" xmlns="" />

      <number value="5" square="25" xmlns="" />

      <number value="6" square="36" xmlns="" />

      <number value="7" square="49" xmlns="" />

      <number value="8" square="64" xmlns="" />

      <number value="9" square="81" xmlns="" />

      <number value="10" square="100" xmlns="" />

    </numbers>

     

    By writing

     

    XNamespace ns = XNamespace.Get("urn:myns-com");

     

    XElement root = new XElement(ns+ "numbers",

        from i in Enumerable.Range(1, 10)

        select new XElement("number",

            new XAttribute("value", i),

            new XAttribute("square", i*i)));

     

    Now since we have not added ns in all the blocks it adds xmlns=”” in all the areas. We can avoid this by writing,

     

    XNamespace ns = XNamespace.Get("urn:myns-com");

     

    XElement root = new XElement(ns+ "numbers",

        from i in Enumerable.Range(1, 10)

        select new XElement(ns + "number",

            new XAttribute("value", i),

            new XAttribute("square", i*i)));

     

    Sometimes this could be painful if the structure is more complicated.

     

    So writers have given us a tip,

    foreach (XElement e in root.DescendantsAndSelf())

    {

        if (e.Name.Namespace == "")

        {

            e.Name = ns + e.Name.LocalName;

        }

    }

     

    This will modify the existing Xml to

     

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

    - <numbers xmlns="urn:myns-com">

      <number value="1" square="1" />

      <number value="2" square="4" />

      <number value="3" square="9" />

      <number value="4" square="16" />

      <number value="5" square="25" />

      <number value="6" square="36" />

      <number value="7" square="49" />

      <number value="8" square="64" />

      <number value="9" square="81" />

      <number value="10" square="100" />

    </numbers>

     

     

    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 : Working with Prefixes

    • 5 Comments

    Based on my previous post on LINQ to XML : Working with Namespaces, if you want to add prefixes to your Xml things becomes little crazy. The trick is that you have to use XAttribute() to attach prefixes. So the Xml as below need the following code,  

     

    <pfx:root xmlns:pfx="urn:mynamespace-com">

      <pfx:child />

    </pfx:root>

     

    XNamespace ns = XNamespace.Get("urn:mynamespace-com");

     

    XElement root = new XElement(ns+"root",

        new XAttribute(XNamespace.Xmlns + "pfx", ns),

        new XElement(ns+"child"));

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to XML : Working with Namespaces

    • 7 Comments

    If you are working with complex real world XML then you have to deal with namespaces to disambiguate. There are several ways to implement namespaces in LINQ to XML. One is you can use pure string to add your namespace with each element declaration, like

     

    <root>

      <child />

    </root>

     

    To create the above Xml you will be writing

    XElement root = new XElement("root",

        new XElement("child"));

     

    To add namespace here, it is very simple

     

    XElement root = new XElement("{urn:mynamespace-com}root",

        new XElement("child"));

     

    Console.WriteLine(root);

     

    The output will look like,

    <root xmlns="urn:mynamespace-com">

      <child xmlns="" />

    </root>

     

    But this does not add namespace to child. So if you have to add namespace to child also,

     

    XElement root = new XElement("{urn:mynamespace-com}root",

        new XElement("{urn:mynamespace-com}child"));

     

    Then the output will look like,

    <root xmlns="urn:munamespace-com">

      <child />

    </root>

     

    But this approach is redundant as you have to type {urn:mynamespace-com} everywhere to make that the part of the same namespace.

     

    So to avoid this you can write some elegant code.

     

    XNamespace ns = XNamespace.Get("urn:mynamespace-com");

     

    XElement root = new XElement(ns+"root",

        new XElement(ns+"child"));

     

    This looks more elegant code.

     

    Another Mike Taulty magic.

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to SQL Overview Video

    • 0 Comments

    Luca, the Microsoft Lead Program Manager, he is one of my favorite presenters. The way he demonstrate uninteresting thing and make fun of himself is one everyone should learn. Please enjoy the through presentation of LINQ to SQL at http://blogs.msdn.com/lucabol/archive/2008/03/03/linq-to-sql-overview-video.aspx

     

    Namoskar!!!

  • Wriju's BLOG

    Amazing BlueScreen Screen Saver

    • 0 Comments

    I am not a screen saver crazy person. But I do keep on adding screen saver as and when I get good one. My friend Amit found out such one which is the most feared one i.e., BlueScreen. It also simulates the startup screen. This was created by one of Microsoft’s Technical Fellows (the most respected technical position at Microsoft) Dr. Mark Russinovich. I always feel good to share @microsoft.com in my email address with them. Join Microsoft and enjoy the fun.

     

    If you install it you can easily make your colleague fool. Good one for the month of April.

     

    Find more at http://technet.microsoft.com/en-us/sysinternals/bb897558.aspx  

     

    Namoskar!!!

  • Wriju's BLOG

    Parallel Extensions to the .NET Framework

    • 0 Comments

    Daniel Moth posted a nice blog on Parallel Extension. Enjoy http://www.vsj.co.uk/articles/display.asp?id=704

    Namoskar!!!

  • Wriju's BLOG

    MSDN Magazine March 2008 is now online

    • 1 Comments

    March2008

    http://msdn2.microsoft.com/en-us/magazine/cc301916.aspx

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 Query Expressions by Bruce Eckel and Jamie King

    • 2 Comments

    Bruce, a renowned author of the famous book “Thinking in Java” is now exploring C# 3.0. He wrote many other books on

    Ø       The Hands-On Java Seminar CD ROM (available on the Web site)

    Ø       Thinking in C++ (PH 1995; 2nd edition 2000, Volume 2 with Chuck Allison, 2003)

    Ø       C++ Inside & Out (Osborne/McGraw-Hill 1993

     

    In his preface he wrote, “The dollar amount you pay for any education is the cheapest part. It’s the work, dedication, and sweat you put forth to acquire your education that increases your value as a programmer (and your salary).”

     

    The preview of this book is available for free download,

    http://www.mindviewinc.com/Books/CSharp/Index.php

     

    Respect authors,

    Note: This book is only available from this web site. Please do not mirror or otherwise distribute this book from any other location.

     

    Namoskar!!!

  • Wriju's BLOG

    MIX8 is now online

    • 0 Comments

    http://sessions.visitmix.com/

    Namoskar!!!

  • Wriju's BLOG

    LINQ to XML : Creating complete XML document

    • 9 Comments

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

     

    Simple sample looks like,

     

     

    XDocument doc = new XDocument(

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

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

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

        new XElement("Employees",

            new XElement("Employee",

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

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

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

     

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

     

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

    <?test value?>

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

    <Employees>

      <Employee id="EMP001">

        <name>Wriju</name>

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

      </Employee>

    </Employees>

     

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

     

    Namoskar!!!

     

  • Wriju's BLOG

    Bill Gates at Stanford

    • 1 Comments


    The Bill Gates Stanford Speech

    Namoskar!!!

     

  • Wriju's BLOG

    Students Get the Free Microsoft Software

    • 8 Comments

    Are you a student? Want to develop using Microsoft product? We are giving it for free. Know more

     


    Bill Gates talks about Free Software, Students, and Technology
     

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to XML : Creating XML from another XML

    • 5 Comments

    Based on my previous post if I have to filter the list of customers only in the country “US” and create another XML which may look like,

     

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

    <usaCustomers>

      <usaCustomer>

        <title>Marketing Manager</title>

        <name>Howard Snyder</name>

      </usaCustomer>

      <usaCustomer>

        <title>Sales Representative</title>

        <name>Yoshi Latimer</name>

      </usaCustomer>

      <usaCustomer>

        <title>Marketing Manager</title>

        <name>John Steel</name>

      </usaCustomer>

    ….

     

     

    To get this if I have to use the System.Xml namespace then code will become something like,

     

    //Conventional XML way to generate another XML out of this XML          

    XmlDocument customers = new XmlDocument();

    customers.Load(@"C:\XMLData.xml");

     

    XmlDocument usaCustomers = new XmlDocument();

    XmlElement usaRoot = usaCustomers.CreateElement("usaCustomers");

    usaCustomers.AppendChild(usaRoot);

     

    foreach (XmlNode n in customers.SelectNodes(

        "/customers/customer[@country='USA']"))

    {

        XmlElement usaCustomer = usaCustomers.CreateElement("usaCustomer");

     

        XmlElement usaTitle = usaCustomers.CreateElement("title");

        usaTitle.InnerText = n.Attributes["contactTitle"].Value;

        usaCustomer.AppendChild(usaTitle);

     

        XmlElement usaContact = usaCustomers.CreateElement("name");

        usaContact.InnerText = n.Attributes["contactName"].Value;

        usaCustomer.AppendChild(usaContact);

     

        usaRoot.AppendChild(usaCustomer);

    }

     

    This approach works perfectly fine but for this you also need to learn XPath and XQuery on top of conventional System.Xml.

     

    To achieve this in simple “what you think what you write” scenario you can go for LINQ to XML.

     

    //LINQ to XML way

    XElement root = new XElement("usaCustomers",

                    from c in XElement.Load(@"C:\XMLData.xml").Descendants("customer")

                    where (string)c.Attribute("country") == "USA"

                    select new XElement("usaCustomer",

                        new XElement("title", (string)c.Attribute("contactTitle")),

                        new XElement("name", (string)c.Attribute("contactName"))));

     

    Its simple its magic. Thanks to Mike Taulty for my learning.

     

    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 : Two important classes XElement and XAttribute

    • 5 Comments

    XElement and XAttribute are the two  very important classes available in System.Xml.Linq.dll assembly. Using these two classes you can do lot of things in the LINQ to XML world. I will show you step by step how,

     

    For just an element

     

    XElement _root = new XElement("root");

     

    _root.Save(fileName);

     

    And the output will look like,

     

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

          <root />

     

    Now if you want to add child to the root,

     

    XElement _root = new XElement("root");

    XElement _child = new XElement("child");

     

    _root.Add(_child);

     

    The generated XML would look like,

     

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

    <root>

          <child />

    </root>

     

    This work like DOM.

     

    Now the .Add() method allows you pass values in form of object. So we can pass anything there,

     

    XElement _root = new XElement("root");

    XElement _child = new XElement("child");

     

    XAttribute attr = new XAttribute("attrbt", 2008);

     

    _root.Add(_child);

    _root.Add(attr);

     

    The XML view will be like,

     

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

    <root attrbt="2008">

      <child />

      </root>

     

    Now another interesting part is that the Add() method not only takes an object it also accepts array of objects. So you ideally do not have to call .Add() multiple times.

     

    With the same output as before you can create you code,

     

    XElement _root = new XElement("root");

    XElement _child = new XElement("child");

     

    XAttribute attr = new XAttribute("attrbt", 2008);

     

    _root.Add(_child, attr);

     

    For more child you can simply keep on adding elements to the Add() method separated by comma.

     

    XElement _root = new XElement("root");

    XElement _child1 = new XElement("child1");

    XElement _child2 = new XElement("child2");

    XElement _child3 = new XElement("child3");

     

    XAttribute attr = new XAttribute("attrbt", 2008);

     

    _root.Add(_child1, _child2, _child3, attr);

     

    Now the output goes,

     

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

    <root attrbt="2008">

                   <child1 />

    <child2 />

    <child3 />

      </root>

     

    By using List<T> you can elegantly add elements to the root. Same output for this code,

     

    XElement _root = new XElement("root");

     

    List<XElement> childs = new List<XElement>

        {

            new XElement("child1"),

            new XElement("child2"),

            new XElement("child3")

        };

     

    XAttribute attr = new XAttribute("attrbt", 2008);

     

    _root.Add(childs, attr);

     

    Now with all these options you can go ahead and use the constructor to add elements and attribute to your root.

     

    So if I want to generate previous XML in one liner way, I could do this,

     

    XElement _root = new XElement("root",

       

        new List<XElement>

        {

            new XElement("child1"),

            new XElement("child2"),

            new XElement("child3")

        },

     

        new XAttribute("attrbt", 2008));

     

    //_root.Add(childs, attr);

     

    Now I do not require Add() method at all.

     

    Hope this gives you the idea about the basics of XElement and XAttribute. Thanks to Mike Taulty , I have learnt this from one of his finest demos.

     

    Namoskar!!!

  • Wriju's BLOG

    VB.NET 9.0: XML Hole

    • 2 Comments

    I have discussed about the native XML support in VB.NET code editor in one of my BLOG posts. Now to generate a XML dynamically with values you can play with LINQ and project it to a XML.

     

    Let us get the list of process running into my local machine with their thread count,

     

    Original LINQ

     

    Dim query = From p In System.Diagnostics.Process.GetProcesses() _

                Select New With _

                    { _

                        .ProcessName = p.ProcessName, _

                        .ThreadCount = p.Threads.Count _

                    }

     

    Structure of XML I want to create

     

    <Processes>

        <Process ThreadCount="2">Some Name</Process>

    </Processes>

     

    To generate XML you may have this code,

     

    Dim _xml3 = _

    <Processes>

        <%= From p In System.Diagnostics.Process.GetProcesses() _

        Select <Process ThreadCount=<%= p.Threads.Count %>><%= p.ProcessName %></Process> %>   

    </Processes>

     

    Console.WriteLine(_xml)

     

    Dim fileName As String = "C:\MyProcesses.xml"

    _xml3.Save(fileName)

     

    Shell("notepad " + fileName, AppWinStyle.NormalFocus)

     

    This will also save the XML in a file and you will find the XML header.

     

    Namoskar!!!

Page 18 of 25 (609 items) «1617181920»