Linq to XML – Adding,Updating and Deleting data

Software Development October 13th, 2007

The previous post about Linq to XML introduced how to query XML data using LINQ. LINQ allows us to not only query XML in a truly unique way, but also create XML documents in a very expressive manner. This post will talk about other operations on the XML: adding, updating and deleting data.

First, lets create a sample XML document:

   1:  XElement book = new XElement("Books", new XElement("Book",
   2:      new XAttribute("publisher", "O'Reilly Media, Inc."),
   3:          new XAttribute("price", "40$"),
   4:          new XElement("title", "Learning WCF: A Hands-on Guide"),
   5:          new XElement("authors", new XElement("author", "Michele Bustamante"))));
   6:   
   7:  book.Save("Books.xml");

Adding data to the XML document

Adding XML to the existing XML document is very simple, we need only construct our XML using a mixture of XElement and XAttribute types (there are other ways also…) and then add them to the document.

The following adds a new book:

   1:  XElement doc = XElement.Load("Books.xml");
   2:  XElement newBook = new XElement("Book",
   3:      new XAttribute("publisher", "Microsoft Press"),
   4:      new XAttribute("price", "45$"),
   5:      new XElement("title", "Introducing Microsoft LINQ"),
   6:      new XElement("authors", new XElement("author", "Paolo Pialorsi"), 
   7:          new XElement("author", "Marco Russo")));
   8:   
   9:  doc.Add(newBook);
  10:  doc.Save("Books.xml");

We must save the xml with the save method, because in LINQ to XML, no changes are made to the loaded XML document until that document is saved.

The XML document now is:

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <Books>
   3:    <Book publisher="O'Reilly Media, Inc." price="40$">
   4:      <title>Learning WCF: A Hands-on Guide</title>
   5:      <authors>
   6:        <author>Michele Bustamante</author>
   7:      </authors>
   8:    </Book>
   9:    <Book publisher="Microsoft Press" price="45$">
  10:      <title>Introducing Microsoft LINQ</title>
  11:      <authors>
  12:        <author>Paolo Pialorsi</author>
  13:        <author>Marco Russo</author>
  14:      </authors>
  15:    </Book>
  16:  </Books>

Updating data

Updating XML data is also very simple; Just pick the element/attribute you wish to update and then set its new value.

   1:  XElement doc = XElement.Load("Books.xml");
   2:   
   3:  //obtain a single book
   4:  IEnumerable<XElement> singleBook = (from b in doc.Elements(
   5:                                        "Book")
   6:                                      where ((string)b.Element(
   7:                                      "title")).Equals("Introducing Microsoft LINQ")
   8:                                      select b);
   9:   
  10:  //update book, should only be 1
  11:  foreach (XElement xe in singleBook)
  12:  {
  13:      xe.SetAttributeValue("price", "39$");
  14:      
  15:      //use the ReplaceContent method to do the replacement for all attribures
  16:      //this will remove all other attributes and save only the price attribute
  17:      xe.ReplaceAttributes(new XAttribute("price", "32$"));
  18:  }
  19:   
  20:  doc.Save("Books.xml");

Deleting data

We simply have to get the object we want to delete and then delete it using the Remove() method.

   1:  XElement doc = XElement.Load("Books.xml");
   2:   
   3:  //obtain the first Book
   4:  IEnumerable<XElement> firstBook = (from b in doc.Elements(
   5:                                        "Book")
   6:                                        select b).Take(1);
   7:   
   8:  //delete book price
   9:  foreach (XElement xe in firstBook)
  10:  {
  11:      xe.Attribute("price").Remove();
  12:  }
  13:   
  14:  doc.Save("Books.xml");

Other way: we pass a lambda expression in as an argument to the Where extension method.

As you can see, Xlinq is really simple and great way to work with XML.

Enjoy!

Tags: , ,

Create custom task for MSBuild – Step by Step

Software Development October 10th, 2007

This is the 2nd post in the msbuild posts series. The first post was an introduction to MSBuild and give you tasting of the basics.

In order to extend Team Foundation Build by plugging in your own logic and tasks, you must write a custom task and use it in your build script (the .proj file).

Custom MSBuild task must be implemented as a .NET class that implements the ITask interface, which is defined in the Microsoft.Build.Framework.dll assembly. You can implement your task in the following two ways:

  1. Derive your class directly from ITask and implement the methods on this interface. or
  2. Derive your class from the helper class, Task (an abstract base class that is a default implementation for BuildEngine and HostObject properties) which is defined in the Microsoft.Build.Utilities.dll assembly. Choosing this option makes it easier to log events from your task.

In both cases you must implement (ITask) or override (Task) it’s Execute method. I override this mwthod with a very simple logic to just log a string value to the Build log as you see below.

Step 1 – Creating project

Create Class Library project with a class and a reference to Microsoft.Build.Utilities assembly. I’ll derive the class from the Task abstract class and override the Execute method.

Step 2 – Writing the task

Execute function must return true if task has executed successfully otherwise it must return false. Now I will add my code to the Execute method – this is my logic which I want to be executed during the build process. I also add a property to the class (Message) and set an attribute to it [Required] (line 29) – this indicates that msbuild must pass a parameter to the task. The Log ( line 17,24) object I use is the LoggingHelper of the Build Utilities (defined at Microsoft.Build.Utilities.dll )

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:  using Microsoft.Build.Utilities;
   5:  using Microsoft.Build.Framework;
   6:   
   7:  namespace MSBuildTasks
   8:  {
   9:      public class MyTask:Task
  10:      {
  11:          private string message;
  12:   
  13:          public override bool Execute()
  14:          {
  15:              try
  16:              {
  17:                  Log.LogMessage(
  18:                      String.Format("This is the message from my task: {0}",
  19:                      message));
  20:                  return true;
  21:              }
  22:              catch
  23:              {
  24:                  Log.LogError("Error occured in my task!");
  25:                  return false;
  26:              }
  27:          }
  28:   
  29:          [Required]
  30:          public string Message
  31:          {
  32:              get { return message; }
  33:              set { message = value; }
  34:          } 
  35:   
  36:      }
  37:  }

Now compile the project.

Step 3 – Registering the task in MSBuild file

Now we need to import and register this custom task to the MSBuild file we want to extend (This is because MSBuild must know how to locate the assembly that contains the task class.) . We’ll do it by editing the .proj file of the build and add a <UsingTask> element which is a direct child of root <Project> element.  This element has a TaskName attribute to get the name of the task class and an AssemblyFile attribute to get the name or address of the assembly where this class is implemented in.

<UsingTask TaskName="MSBuildTasks.MyTask" AssemblyFile="C:\Work\Projects\Samples\MSBuild\MSBuildTasks\bin\Debug\MSBuildTasks.dll"/>

Step 4 – Calling the task from MSBuild

Calling the task depends on the point in the build process where we want to call. We should choose the point in the process that we want to call the task and add the following under it:

   1:  <Target Name="MyTaskTarget">
   2:      <MyTask Message="Hi MSBuild" />
   3:    </Target>

Line 2 calls the task. The message here is the required parameter to pass to the task.

Step 5 – Running the MSBuild file

After all of that you should run the msbuild file.

This is my MSBuild file (.proj extension)

<?xml version="1.0" encoding="utf-8"?><Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">  <UsingTask TaskName="MSBuildTasks.MyTask"            AssemblyFile="C:\MSBuildTasks\MSBuildTasks.dll" />  <Target Name="MyTaskTarget">    <MyTask Message = "Hi MsBuild"/>  </Target></Project>

This is the output of the example.

msbuild

Enjoy!!

See you in the next post of the MSBuild series.

Technorati Tags:

Tags:

I Search with Google’s experimental

Internet October 7th, 2007

Google recently added “Experiemental Search” to their list of Google labs options. Yesterday I started to search with it, and I found it quite interesting.

There are currently four different experimental search options. You just have to go to Google Experimental and select one of the four features that are currently tested.

  1. New ways to view search results: using specialized snippets, on a timeline or on a map. You can also access this feature without joining the experiment, using the view operator: just add view:info, view:timeline or view:map to your query.
  2. keyboard shortcuts: select a search result or move to the next result without using your mouse. You’ll like it if you use shortcuts in Gmail or Google Reader.
  3. Two similar experiments: put the search navigation at the left/right of the page.

 

Timeline and maps view
Timeline view is a great way to sort results, especially for research queries. The results are grouped by years (or decades) and ordered from oldest down to the most recent. At the top of the screen is a linkable timeline that allows you to filter the results by selected time periods.

For example, I would like to know Microsoft’s history.

I query: microsoft view:timeline and I got:

01

Keyboard shortcuts
The keyboard shortcut interface is just as it sounds, it provides a quick and easy way to navigate the search results using only our keyboard.

Key Action
J Selects the next result.
K Selects the previous result.
O Opens the selected result.
<Enter> Opens the selected result.
/ Puts the cursor in the search box.
<Esc> Removes the cursor from the search box.

02

left/Right hand search navigation

03

 

You can only choose one experiment at a time, it’s easy to switch between them or deactivate them and there’s an option to send your feedback.

Enjoy!!

Tags:

Microsoft Israel link to my post

Community October 7th, 2007

I am really excited. I notified that the opening page of Microsoft Israel mention my post about query XML using XLinq.

ms

It’s great!

Tags: ,

Query XML using XLINQ

Software Development October 7th, 2007

LINQ to XML is a built-in LINQ data provider that is implemented within the System.Xml.Linq namespace in .NET 3.5.
It enables us do the following to XML data:

  • Read.
  • Construct.
  • Write.

We can perform LINQ queries over XML from the file-system, from a remote HTTP URL or web-service, or from any in-memory XML content.
LINQ to XML provides much richer (and easier) querying and data shaping support than the low-level XmlReader/XmlWriter API in .NET 2 and also much more efficient with usage of much less memory than the DOM API that XmlDocument provides. That’s because it does not require you to always have a document object to be able to work with XML. Therefore, you can work directly with nodes and modify them as content of the document without having to start from a root XmlDocument object. This is a very powerful and flexible feature that you can use to compose larger trees and XML documents from tree fragments. Now that you have an overview of the XLinq’s capabilities, the next few sections will examine the reading and writing features of XLinq before discussing the query capabilities.

01 (Figure and classes explanations are taken from XLINQ overview.doc)

Of the classes shown in this figure, the XNode and XContainer classes are abstract. The XNode class is the base for element nodes, and provides a Parent method and methods such as AddBeforeThis, AddAfterThis, and Remove for updates in the imperative style. For IO, it provides methods for reading (ReadFrom) and writing (WriteTo).
Although the XElement class is bottom-most in the class hierarchy, it is the fundamental class. As the name suggests, it represents an XML element and allows you to perform the following operations:

  • Create elements with a specified element name
  • Change the element’s contents
  • Add, change, or delete child elements
  • Add attributes to the element
  • Save the element as an XML fragment
  • Extract the contents in text form

This post will introduce hoe to query xml and it is the first of series of posts regards to XLINQ.

Lets get a sense of how LINQ to XML works!

Query xml from URL

   1:  public static void GetRssFeedFromURL()
   2:  {
   3:      string url = "http://feeds.feedburner.com/MaorDavid?format=xml";
   4:   
   5:      // load the rss feeds into the XElement
   6:      XElement feeds = XElement.Load(url);
   7:   
   8:   
   9:      if (feeds.Element("channel") != null)
  10:      {
  11:          var query = from f in feeds.Element("channel").Elements("item").Take(10)
  12:                      select new { Title = f.Element("title").Value, Link = f.Element("link").Value };
  13:   
  14:          foreach (var feed in query)
  15:          {
  16:              Console.WriteLine(String.Format("Feed title: {0}",feed.Title));
  17:              Console.WriteLine(String.Format("Link: {0}",feed.Link));
  18:          }
  19:      }
  20:  }

XLinq is an XML query language that inherits from the LINQ query foundation. You can use it to query XLinq objects such as XElement, XDocument, etc using LINQ query facilities.

We start by loading the XML into memory using the Load() method of the XElement class. (Line 6).

After loading the XML , the next step is to retrieve all items (Line 11) and now you can query and iterate the results as described in my previous posts.(Var keyword, Getting started with Linq).

Very simple! This example load an XML from URL. What if you want to query XML from the file system? Nothing changed beside the uri parameter to load into the XElement. (Line 6)

   1:  public static void GetRssFeedFromFile()
   2:  {
   3:      string path = @"C:\Work\Projects\Samples\VS2008Samples\LinqToXML\Maor Davids Blog.xml";
   4:   
   5:      // load the rss feeds into the XElement
   6:      XElement feeds = XElement.Load(path);
   7:   
   8:   
   9:      if (feeds.Element("channel") != null)
  10:      {
  11:          var query = from f in feeds.Element("channel").Elements("item").Take(10)
  12:                      select new { Title = f.Element("title").Value, Link = f.Element("link").Value };
  13:   
  14:          foreach (var feed in query)
  15:          {
  16:              Console.WriteLine(String.Format("Feed title: {0}", feed.Title));
  17:              Console.WriteLine(String.Format("Link: {0}", feed.Link));
  18:          }
  19:      }
  20:  }

 

As you can see, all the code snippets presented above are fairly simple. Once the XML loaded into the LINQ to XML API, you can write queries over that tree. The query syntax is easier than XPath or XQuery.

Enjoy!!

Tags: , ,

Getting started with Astoria

Software Development October 4th, 2007

Few weeks ago, the CTP refresh for VS 2008 Beta 2 of Astoria was released. Astoria is a really cool project based on .NET 3.0 (WFC), Entity Framework to provide pure HTTP access to SQL Server data.In order to play with it, first of all you need to install the following:

After installing all we need, we can create out first project – this post will describe the steps you need in order to do that.

Create new Web Application Project:

1

After I did it, I need to add new ADO.NET Entity model. On the Project menu, click ‘Add new item’ and select the ADO.NET Entity Data Model.

2

Now, the wizard will start. Select: Generate model from database.

3

Next we’ll save the connection info

4

I checked the option to add connection string to web.config and that’s what I got there:

<add name="NorthwindEntities" connectionString="metadata=~/bin/NorthWind.csdl|~/bin/NorthWind.ssdl|~/bin/NorthWind.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\sqlexpress;Initial Catalog=Northwind;Integrated Security=True&quot;" providerName="System.Data.EntityClient" />

The next step we select the objects we want. I choose Tables only.

5

What we got so far? .edmx file was added to our project, which is the schema.

6

Next step we should add and setup Astoria service. We’ll do it from the Project menu –> Add new item.

7

New class was generated, it’s not full cause we should select the type of the service.

8

I added the NorthwindModel.NorthwindEntities type. (NorthwindModel is the model I generated)

9

Now everything ready to compile…

After compilation, I can browse to the service I created. Look what I got:

10

The service describes the schema with the object I selected (Tables only).

How can I query the service? For example, if I want all the categories, I’ll change in the address in my browser to: http://localhost:58889/NorthwindWebDataService.svc/Categories and I got all the categories:

(localhost:58889 is on my computer off course, change your host:port to match yours)

11

Amazing….

What about query it from asp.net app? There is a class that comes with the Astoria samples that provides a class and series of methods to create a more encapsulated approach to calling an Astoria web data service. You can find it at the installation folder.

What if I want to query the service to get the customers order by contact name:

http://localhost:58889/NorthwindWebDataService.svc/Customers?$orderby=ContactName

and what if I want the top 10 records:

http://localhost:58889/NorthwindWebDataService.svc/Customers?$orderby=ContactName&$top=10

Conclusion

Astoria is set to provide the developers a richer way of interacting with data on the server. The syntax is easy and there is a more structure API on the way for ASP.NET AJAX.

 

Technorati Tags: ,

Tags:

Microsoft to release .NET Framework Library Source Code

Software Development October 4th, 2007

Scott Guthrie just made an exciting post, starting with .NET 3.5 and VS 2008 the .NET libraries will have source available! 

One of the things my team has been working to enable has been the ability for .NET developers to download and browse the source code of the .NET Framework libraries, and to easily enable debugging support in them.

Today I’m excited to announce that we’ll be providing this with the .NET 3.5 and VS 2008 release later this year.

Anyone who accepts the Microsoft Reference License will be able to browse and view the source code. The initial publication will include the BCL (System, System.IO, System.Collections, System.Configuration, System.Threading, System.Net, System.Security, System.Runtime, System.Text, etc), ASP.NET (System.Web), Windows Forms (System.Windows.Forms), ADO.NET (System.Data), XML (System.Xml), and WPF (System.Windows).

Read all about it here:

http://weblogs.asp.net/scottgu/archive/2007/10/03/releasing-the-source-code-for-the-net-framework-libraries.aspx

Here’s a little more by Shawn Burke:

http://blogs.msdn.com/sburke/archive/2007/10/03/making-net-framework-source-available-to-developers.aspx

Technorati Tags: ,

Tags: ,

EntLib Contrib September 2007 Release

Software Development October 2nd, 2007

entlib EntLib Contrib is a community-developed library of extensions to the patterns & practices Enterprise Library.

The latest release of EntLib Contrib is Enterprise Library Contrib September 2007.

What’s new? Per Tom Hollander:

  • Data Access Application Block extensions:
    • MySql, SqLite and SqlEx providers.
  • Exception Handling Application Block extensions:
    • SqlException Wrap Handler.
  • Logging Application Block extensions:
    • LogParser.
  • Policy Injection Application Block extensions:
    • PostSharp4EntLib.
    • New matching rules: And, Or and Not.
    • New call handlers: CursorCallHandler, OneWayCallHandler, SynchronizedCallHandler, ThreadSafeCallHandler, TransactionScopeCallHandler.
  • Validation Application Block extensions:
    • New validators: CollectionCountValidator, TypeValidator<T>, ObjectValidator<T>, EnumDefinedValidator.
    • Designtime enhancements: Lightweight type picker, Test command.
    • Other extensions: Default validators, Argument Validation, ExternallyConfigurableObjectValidator.

Tags: ,

Query types using LINQ

Software Development October 1st, 2007

It’s great. It’s so beautiful. I really like it.

Reflecting types using LINQ.

How can we do it?

We can use Reflection of course, but with LINQ it shortest and simplest.

Declare “Type” object , assign the class you want to query and query with LINQ.

Example 1:

To get all methods of a class:

   1:  Type tPerson = typeof(Person);
   2:  var methods = from method in tPerson.GetMethods()
   3:                select method;
   4:   
   5:  Console.WriteLine("All methods:");
   6:  foreach (var m in methods)
   7:  {
   8:      Console.WriteLine(m.Name);
   9:  }

 

Example 2:

To get all methods that returns “int”, use the “where’ clause:

   1:  var ints = from method in tPerson.GetMethods()
   2:                where method.ReturnType == typeof(int)
   3:                select method;
   4:   
   5:  Console.WriteLine("All methods that returns int:");
   6:  foreach (var intType in ints)
   7:  {
   8:      Console.WriteLine(intType.Name);
   9:  }

Tags: , ,