Random Post : LINQ to XML

14 07 2008

Thought of refreshing my LINQ to XML skills and here is the outcome – another blog post today! 8)

Here is our sample XML file (never mind where it came from or why it is complex)

<?xml version="1.0" encoding="utf-8" ?>
<Output_Message>
    <Dataset>
        <Row>
            <Persons_Current_Name>
                <Name>
                    <Surname>John</Surname>
                    <GivenName>Samuels</GivenName>
                </Name>
            </Persons_Current_Name>
            <Persons_Name_At_Birth>
                <Name>
                    <Surname></Surname>
                    <GivenName>John</GivenName>
                </Name>
            </Persons_Name_At_Birth>
            <DateOfBirth>1865-07-31</DateOfBirth>
        </Row>
    </Dataset>
    <StatusInformation>
        <Status>OK</Status>
        <Alive>YES</Alive>
    </StatusInformation>
</Output_Message>

I am going to query each element (as listed below) and display their values

  • Persons_Current_Name
  • Persons_Name_At_Birth, and
  • DateOfBirth

Our first step would be to load this XML file. We can make use of XDocument to load the whole XML file.

XDocument mainXMLDoc
         = XDocument.Load("Input.xml");

To start with, let us traverse all the nodes and display their values

//Traversing the whole XML
Console.WriteLine("XML Traverse");
Console.WriteLine();
foreach (XElement xelement in
                   mainXMLDoc.Descendants())
{
    Console.WriteLine("{0} : {0}",
              xelement.Name, xelement.Value);
}

Looks simple, isn’t it :)

Next, let us get the value of Persons_Current_Name. I already have a class called Name, which is shown below:

public class Name
{
    public String Surname { get; set; }
    public String GivenName { get; set; }
}

How do we directly query Persons_Current_Name element? Below is the very straight forward (ugly) code :D

//Persons Current Name
// The Ugly Way
XElement current_name =
    mainXMLDoc.Root
        .Element("Dataset")
        .Element("Row")
        .Element("Persons_Current_Name")
        .Element("Name");
Name persons_current_name = new Name
    {
             Surname =
                  current_name.Element("Surname").Value,
             GivenName =
                   current_name.Element("GivenName").Value
    };

Well, I really don’t like to code this way. Do we have any another option? Yes, we do! 8)

//Persons Current Name
// The Neat Way
Name persons_current_name =
    (from c in mainXMLDoc.Descendants()
     where c.Name == "Persons_Current_Name"
     select new Name
           {
                 Surname =
                      c.Element("Name").Element("Surname").Value,
                 GivenName =
                      c.Element("Name").Element("GivenName").Value
            }).FirstOrDefault();

The above code certainly looks better than our previous code :)

Similarly for DateOfBirth,

//Date of Birth
String[] strDob =
    (from c in mainXMLDoc.Descendants()
     where c.Name == "DateOfBirth"
     select c.Value).FirstOrDefault().Split('-');
DateTime dob = new DateTime(Convert.ToInt32(strDob[0]),
    Convert.ToInt32(strDob[1]),
    Convert.ToInt32(strDob[2]));

All looks good, but wait! What to do if I have my XML in string format ? How do I load it? Dont panic, you can use the same XDocument to load the XML in the string format :)

XDocument mainXMLDoc =
         XDocument.Parse(strXML);




Interested to work for Intergen?

14 07 2008

To all of my friends who want to work or looking to work @ Intergen, below is a list of additional perks along with the exciting job that Intergen Offers 8)

  • $400 + GST towards the purchasing of a new mobile phone and a discounted phone plan of which Intergen will pay up to $110 per month towards
  • Free monthly massages
  • Drinks and nibbles every Friday afternoon
  • Free Life Insurance cover of 3 times annual salary
  • Free Income protection Insurance for 75% of salary for up to 5 years
  • Free Travel insurance (for you and your family)
  • Additional Maternity Package to Government Assistance (after one year of employment)
  • Banking benefits from ASB Bank
  • Employee Assistance Programme
  • Option to join a discounted Health Insurance Scheme
  • Technology purchases at dealer rates – computers, TVs, stereos, electronics
  • Option to join the Superannuation Scheme with admin fees paid by Intergen
  • Free soft drinks including Coke, V, Just Juice

So, if you are looking for an exciting job, you can look here at our Careers Section





Team System Unit Test and Output Directories

14 07 2008

I always use NUnit to write my unit tests but now at Intergen I also use Microsoft Visual Studio Team System Unit Tests. Today I was stuck by a very basic problem and here it is.

I have a XML file in my project which is added to the output directory when compiled.

When I was running my unit tests against this, Visual Studio threw me this error saying that it couldn’t find the file!

(click to enlarge)

I was really surprised as my XML file is said to copy to output directory and the test fails saying that there is no such file. Checked my Test Solution’s output directory and found that there is indeed the Templates folder and the XML file.

So, whats the problem? Why is my test failing?

Well, the VSTE has a separate directory where it stores all its test results. The directory can be found in your root directory of your solution under the name TestResults. The TestResults also have various folders for each test run you do. If you refer back to the error image that is attached above, you could get the exact directory name. So, the VSTE did not copy the Templates directory to this ‘dynamic’ (for each test run there will be a directory created : correct me if am wrong here) directory. How do we do this then?

The answer is with the Local Test Run Config’s Deployment settings. You can find the local test run config in your solution browser.

Double click the file to open the properties dialog and go to the Deployment section.

Specifying a file or directory here would be included along with the test results :)

My test doesnt fail now 8)

Another way to do this (if its a single file : if you know how to add for a directory, please do leave your comment :) ) is to specify along with your test method,

[TestMethod, DeploymentItem(@"Templates\BirthInputTemplate.xml")]

public void Test_BuildInputXML()
{
}





How I Got Started in Software Development

13 07 2008

babyandcomputer_thumb1

I have been memed! Thanks James :)

How old were you when you started programming?

19

How did you get started in programming?

I got introduced to programming and computer languages in my high school. It got into me from then and when I joined my University, I was fully ready to rock myself in programming :)

What was your first language?

C/C++

What was the first real program you wrote?

A DirectX game in Visual Basic 6.0

What languages have you used since you started programming?

C/C++, Visual C++ 6.0, Visual Basic 6.0, HTML, Javascript, ASP 2.0, Python, PyGTK, PyQt, Qt (C++), ASP 3.0, C#

What was your first professional programming gig?

A tool for Telecommunication and Telemedicine for one of the projects at ISRO

If you knew then what you know now, would you have started programming?

YES!

If there is one thing you learned along the way that you would tell new developers, what would it be?

1) Blog, Communicate

1) Analyse whatever you are doing

2) Dont hurry – Relax, Think and Code

3) Test whatever you code (Unit Testing)

What’s the most fun you’ve ever had… programming?

Testing what I write. Its always a challenge to break up your mind to test what you write and find mistakes/problems ;)

I Choose

1) Daniel Moth

2) Nigel Parker

3) Kirupa

4) Jeremy Boyd





NDepend

13 07 2008

Its really hard to summarize what is NDepend in few words as this tool does a lot and its really useful when you have a big project and had to do code analysis, code usage, code metrics etc., etc., So, to make things simpler, lets take what their website says :)

NDepend is a tool that simplifies managing a complex .NET code base. Architects and developers can analyze code structure, specify design rules, plan massive refactoring, do effective code reviews and master evolution by comparing different versions of the code.

With NDepend you can analyse a set of .NET assemblies and that was the first step for me in using NDepend. Another highlight of NDepend is that you can use Code Queries to query to analyse and get results. More on Code Query Language here.

Here is a small screencast on NDepend introduction from me. Its in .swf format and just open it in your browser :)





Silverlight and WCF

31 05 2008

With the release of Silverlight 2 beta 1, now developers can use .Net to create Silverlight applications To be more precise, developers can use XAML and VB.NET or C# as the back-end code language. To know more about Silverlight and what tools you need to start developing Silverlight applications, visit my post here.

This post focuses on how to make your Silverlight applications interact with Windows Communication Foundation(WCF) services. Visual Studio 2008 introduced several new WCF features. We will create a small calculator service which is going to add two numbers and return the result to the user.

First, let us create a Silverlight Web Application project.

silverlight-project

Visual Studio creates the necessary files needed for your solution. Let us straight away start with adding our WCF service. Visual Studio creates two projects, one being the actual Silverlight control project and the other being the web application project where the Silverlight control is hosted. So, we would be able to add a WCF service to our web application project and then reference the service in our Silverlight control project. Right click the web application project and add a WCF service to the project.

add-new-item

Name the service as CalculatorService. Visual Studio adds the necessary files such as the SVC and code-behind files and also the service configuration to the web.config file.

wcf-service-added

I have modified the service to hold only function as shown below:

[ServiceContract]
public interface ICalculatorService
{
    [OperationContract]
    int AddTwoNumbers(int num1,int num2);
}

And here is the implementation:

#region ICalculatorService Members

public int AddTwoNumbers(int num1, int num2)
{
    return (num1 + num2);
}

#endregion

Nothing complex, just simple addition and return the result ;)

Now comes the most important thing, at least for this beta 1 release – Silverlight supports only basicHttpBinding and thus our WCF service can only use basicHttpBinding if we are to interact with a Silverlight client. Let us check our CalcultorService’s binding in the web.config file under the system.servicemodel section.

default-binding

Yes, you are right. WCF by default uses wsHttpBinding and thus we need to change the binding to basicHttpBinding. Below is the modified version:

modified-binding

How do we use this service in our Silverlight application? Below is a screenshot of our Silverlight application.

screenshot-control

The interface is pretty simple accepting two numbers from the user and when Add is clicked, our service’s AddTwoNumbers is invoked to get the result.

How do we reference our WCF service now? We do the same way as we do in normal WPF or WinForms applications :D

Right click on the Reference and select Add Service Reference

silverlight-add-service-reference

We will be presented with a dialog box to add a service reference.

service-discover

We can use the Discover option to discover any WCF services in our solution. As our CalculatorService is hosted in the same solution, the Discover would be able to find our service.

calculator-service-discovered

Let us give a name to our service reference – CalculatorServiceProxy :)

Once we add our service, we can see that the Silverlight project now has the necessary files to interact with our WCF service.

silverlight-added-wcf-reference-files

Now we are ready to add our code to the button Click event handler. Below is the code snippet.

private void Button_Click(object sender, RoutedEventArgs e)
{
    int num1 = Convert.ToInt32(TxtNum1.Text);
    int num2 = Convert.ToInt32(TxtNum2.Text);

    CalculatorServiceClient calculator_proxy =
        new CalculatorServiceClient();

    calculator_proxy.AddTwoNumbersCompleted +=
        new EventHandler<AddTwoNumbersCompletedEventArgs>
            (calculator_proxy_AddTwoNumbersCompleted);

    calculator_proxy.AddTwoNumbersAsync(num1, num2);

}

void calculator_proxy_AddTwoNumbersCompleted(object sender,
    AddTwoNumbersCompletedEventArgs e)
{
    HtmlPage.Window.Alert(Convert.ToString(e.Result));
}

You guessed it right – WCF reference adds the asynchronous operations to our Silverlight project and it does makes more sense to use asynchronous operations in a Silverlight environment as we cant block the browser and make the user wait.

Let us build and execute our project :)

And here is the screenshot:

output

That’s it! Now we have a Silverlight application interacting with a WCF service ;)

Wasn’t it easy 8)

The sample can be downloaded here:





Resharper 4.0 – Lambda Support

26 05 2008

Resharper 4.0 beta was out few days back. I found an excellent feature which I think should be blogged :)

Here is small test code snippet which uses RhinoMocks unit testing framework

You can see that Resharper has issued a warning against

Call(delegate { mockSubject.Remove(subject); });

And the warning message is as follows,

You can see that it is intelligent enough to deduce that lambda expressions can be used in the place of anonymous delegates! 8)

And once you allow Resharper to convert to lambda, you get this:

How cool is that 8)








Follow

Get every new post delivered to your Inbox.