The ramblings of web developer Beau Brownlee

Archive for the ‘ LINQ ’ Category

 
Thursday, May 27th, 2010

Reading an xml file is something that every developer has to do at some point (if not regularly). XML protocol is extremely prevalent across all technologies which makes it important to understand how to parse it. Sivlerlight exposes System.XML.Linq namespace that has all the needed classes to use Linq to query your XML to get the node/s that you need.

Always Starts with the Document

As with every XML reader you start out by creating an instance of the document and then filling it with the XML file’s data. In this case Silverlight provides ‘XDocument’ class to instantiate the document object and then the ‘Load’ method to read the data into the object. Then once we’ve loaded the object with data then we can run a traditional Linq query on the data.

Test Case

So lets run through a test case. Lets say we have a configuration file in which we want to determine what logo to display based on the url that called it. So here is our example xml:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <Logos>
    <Logo url="url1">
      <LoginWindowLogo>/namespace;path/img1.png</LoginWindowLogo>
    </Logo>
    <Logo url="url2">
      <LoginWindowLogo>/namespace;path/img2.png</LoginWindowLogo>
    </Logo>
  </Logos>
</configuration>

And here is the C# code to read it:

XDocument document = XDocument.Load("Config.xml");
 
            var images = (from e in document.Descendants("Logo")
                          where e.Attribute("url").Value == App.Current.Host.Source.Host
                          select new
                          {
                              LoginWindowLogo = e.Element("LoginWindowLogo").Value,
                          }).FirstOrDefault();
 
            if (images != null)
            {
                loginwindowlogopath = images.LoginWindowLogo;
            }

App.Current.Host.Source.Host is the property that gives you the current apps domain, the function ‘FirstOrDefault’ get the results and turn it into an object that just has the properties selected.

 
Thursday, November 12th, 2009

I have recently been using LINQ to accomplish much of my data abstraction and have found it very useful for building a robust ASP.Net application. Ultimately what LINQ to SQL does is it translates your C# code into a SQL query and returns an object or an object list instead of a dataset. This can be much easier to deal with than a dataset. I have run into a couple things that I didn’t expect so I thought I’d share. (more…)

cheap software