.NET Explored

Archive for November, 2009

.NET Reactive(Rx) Framework

17 November 2009 | 1 Comment » | admin

Reactive Programming is a new buzz word in the Microsoft world when late this summer they release a Framework name “Reactive Framework” in the latest version of Silver Light toolkit (System.Reactive.dll) from Microsoft. A complete version is expected to be part of Visual Studio 2010 and will be supported by .NET Framework 4.

But before dwelling deep into the reactive programming lets see what does reactive programming means. It basically means how the producer be able to publish data both static and dynamic and how the consumer be able to view the data seamlessly and automatically.

For example, in an imperative programming setting, a: = b + c would mean that a is being assigned the result of b + c in the instant the expression is evaluated.

Later, the values of b and c can be changed with no effect on the value of a. In reactive programming, the value of a would be automatically updated based on the new values.

A modern spreadsheet program is an example of reactive programming. Spreadsheet cells can contain literal values, or formulas such as “=B1+C1″ that are evaluated based on other cells. Whenever the value of the other cells change, the value of the formula is automatically updated.

Similarly another easy concept in microsoft programming world is the event handler or constantly running services which publishes the data constantly and we write a program to handle that event to show data.

Coming back to the “Reactive Framework” or “Rx Framework” it is based on the same principal discussed above. With the advance of the asynchronous programming reactive framework definitely comes to help.

 

This team has been able to implement the dual mode of communication channel of push – pull or publisher-subscriber model using the following interfaces.

  • The Iterator pattern of IEnumerable/IEnumerator to pull\subscribe to the data used by the listner
  • Iterator pattern of IObservable/IObserver for push\publish the data used by the source

 

To dwell deep into the Reactive framework have a look at the video from Eric Meijer explaining this concept.

 

Lets take a quickly look at how we can use Rx to simplify our code, we will write an extension method that will call a web client’s DownloadWeatherData method and return a String.

public static class WebClientExtender
{

public static IObservable<string> GetSite(this WebClient client, string url)
{
var downloaded = Observable.FromEvent<DownloadWeatherDataCompletedEventArgs>
                 (client, ” DownloadWeatherData”);
client.DownloadWeatherDataAsync(new Uri(url));
return downloaded.Select(x=>((DownloadWeatherDataCompletedEventArgs)x.EventArgs).Result);
}

}

To call this we can now simple add the following line of code to our Silverlight application.

new WebClient().GetSite(“http://localhost/”).Subscribe(x => MessageBox.Show(x));

This way we can very easily clean up the code and structure how the Asynchronous events are handled.

 

To have a look at some of the programming concepts of it have a look at the blog introducing reactive (Rx) Linq to Events

  • Share/Bookmark

OAuth and .NET

13 November 2009 | 2 Comments » | admin

OAuth is a new wave in the website security protocol or to be precise an API access delegation protocol’. OAuth allows a client application to obtain user consent (as access tokens) for executing operations over private resources on his behalf.

 OAuth allows you to share your private resources (photos, videos, contact list, bank accounts) stored on one site with another site without having to hand out your username and password. There are many reasons why one should not share their private credentials. Giving your email account password to a social network  site so they can look up your friends is the same thing as going to dinner and giving your ATM card and PIN code to the waiter when it’s time to pay. Any restaurant asking for your PIN code will go out of business, but when it comes to the web, users put themselves at risk sharing the same private information. OAuth here comes to the rescue.

If you want to know more about how OAuth works, you should read the following posts

Now, if we analyze the specification in more detail, we will see that the real purpose behind OAuth is to create a network of collaboration between applications. It will not be necessary anymore to keep all our stuff just in a single place, we can have for instance our pictures in a website, our contacts in another place and a third application making use of them, all these applications collaborating together.

Currently we hear OAuth being mostly associated with the social networking sites like Twitter, yahoo, google etc. However this is going to change in future, I see it being implemented in the cloud computing environment to provide more seamless access. Google has released its OpenID/OAuth implementation. This is a major step forward in the Interoperability field. The work that Google has released is very important and it will allow, for instance, that a user from Zoho Writer can use data from a Google Docs Spreadsheet and then make the result available in his Linkedin profile.

 Similarly I think with Microsoft releasing its new cloud computing platform Azure. The OAuth definitely comes into play more so important than ever before.

 Some of the OAuth .NET Faremwork Library available are :

  Here is some OAuth Implementation examples in .NET

  • Share/Bookmark

ORM in .NET

13 November 2009 | No Comments » | admin

 

Introduction

ORM, or object-relational mapping, is one of the tougher things to accomplish in modern, object-oriented programming languages. It involves moving away from the traditional data store paradigm: there is no (or very little) dedicated, pre-compiled code involved in reading/writing an object to/from the database or other backing store. Instead, the logic involved in accessing the backing store is determined at runtime using a combination of reflection and attributes that decorate the business objects in question. Many projects and frameworks have been created to try to address this concept, with varying degrees of success. What this article covers is a general introduction to ORM concepts, the approach that .NET 3.5 takes.

In the beginning…

Prior to .NET 3.5, you had several choices when it came to getting your business objects to and from the database:

  1. Roll your own – This means you don’t use any frameworks and don’t auto-generate any code. The database schema and the .NET classes are created by hand, as is the data access layer. While this will provide the ultimate level of customizability and performance, it’s tedious (involves copying a lot of boilerplate code), error prone, and difficult to maintain when the objects or the database schemas change.
  2. Auto-generate the classes and the data access layer – This is where code generation tools like CodeSmith or MyGeneration come in: you point them at your database and it will generate the .NET classes and the data access layer. Like option 1, this isn’t true ORM: you still have pre-compiled code responsible for accessing the database to read or write an object’s data. However, its automatic generation of the code is a step in the right direction, removing the error-prone human factor when creating the classes and the data access layer.
  3. Use a true ORM framework – There are several well-known ORM packages available for previous versions of the .NET framework, including NHibernate and Gentle.NET. As mentioned previously, ORM removes the dedicated data store code and inspects an object at runtime to determine what it needs to do to read/write it to/from the database. Attributes are used to decorate the class and its properties to give the framework pointers about where things go in the database. The actual SQL for an operation is generated dynamically based on these attributes. There is often a code-generation component in these packages that generates the .NET business object classes from the database schema, but no dedicated data access code is generated

Some Problems with ORM

So all this dynamic, runtime SQL generation stuff sounds great, right? Not so fast: ORM has several serious drawbacks. The first of these is performance, as you’re going to encounter a slowdown any time you bring reflection into the equation and start dynamically generating SQL. ORM will never be as fast as rolling your own: there’s no substitute to being able to hand-tweak your stored procedures and pre-compile all of the data access logic. Another drawback is that ORM doesn’t deal well with extremely complex databases. When designing complex databases with a lot of constraints and relationships spanning several tables, it’s often necessary to include intermediary tables to link various entities together that is great from a RDBMS standpoint, but doesn’t translate all that well to an object-oriented environment. This can lead to obtuse and difficult to understand auto-generated classes. Keep in mind that RDBMS and object-oriented environments are fundamentally different, and each includes its own set of design and performance considerations. What works in one environment is not necessarily optimal for the other environment. That being said, the upside to ORM in terms of maintainable, clean, and easy to understand code can be quite compelling, provided that it’s used correctly.

ADO.NET Entity Framework in .NET 3.5

So, now that you have a good idea of what ORM is all about and its potential pitfalls, let’s delve into how Microsoft approached this concept in .NET 3.5. It takes a different approach to the challenge of ORM by not focusing on slaving the object model to a relational model, but by instead giving us an entirely new way to access and query our data that’s not limited only to relational data. With this approach, the ORM capabilities of .NET 3.5 evolve almost as a side-effect instead of being the prime focus of this new data access scheme. 
 

The ADO.NET Entity Framework is designed to enable developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. The goal is to decrease the amount of code and maintenance required for data-oriented applications. Entity Framework applications provide the following benefits:

  • Applications can work in terms of a more application-centric conceptual model, including types with inheritance, complex members, and relationships.
  • Applications are freed from hard-coded dependencies on a particular data engine or storage schema.
  • Mappings between the conceptual model and the storage-specific schema can change without changing the application code.
  • Developers can work with a consistent application object model that can be mapped to various storage schemas, possibly implemented in different database management systems.
  • Multiple conceptual models can be mapped to a single storage schema.
  • Language-integrated query (LINQ) support provides compile-time syntax validation for queries against a conceptual model

LINQ in .NET 3.5

How do they do it? LINQ. It stands for Language INtegrated Query and Microsoft wants it to be THE way that you sift through data in the .NET framework. Its structure will be immediately familiar to anyone with experience writing SQL statements and it marries the simple yet powerful query syntax of SQL to the strong typing of an object-oriented language. The real kicker, however, is that it’s not limited to relational data: anything that implements the IEnumerable and IQueryable interfaces can be used with LINQ. Here’s a quick example so that you can get an idea of what it’s capable of:

C# Code
01.List<string> elements = new List<string>() 
02.
03.  "Iridium"
04.  "Einsteinium"
05.  "Polonium" 
06.};
07.IEnumerable<string> results = from element in elements
08.                  where element.Contains("n")
09.                  select element;

It’s just a simple search of a generic string list instance for elements that contain the letter “n”. Whereas before you would have had to accomplish this imperatively, that is, you would have had to write code to iterate over the collection and drive the search, you can now accomplish the same thing declaratively. Basically, you’re stating what you want to do instead of how to do it. While the syntax takes some getting used to, this approach is inherently less error-prone. It also bears mentioning that Intellisense is in full effect in the above sample, so you lose none of the “ease of use” features of Visual Studio when you employ LINQ.

  • Share/Bookmark

.NET goes open source and cross platform with Mono

10 November 2009 | No Comments » | admin

In the last blog i talked about MonoDevelop an open source cross platform IDE for .NET development. This cross platform .NET development was only possible due to the Mono Framework.

Mono is a software platform designed to allow developers to easily create cross platform applications. It is an open source implementation of Microsoft’s .Net Framework based on the ECMA standards for C# and the Common Language Runtime. We feel that by embracing a successful, standardized software platform, we can lower the barriers to producing great applications for Linux.

The Components

There are several components that make up Mono:

C# Compiler – The C# compiler is feature complete for compiling C# 1.0 and 2.0 (ECMA), and also contains many of the C# 3.0 features.

Mono Runtime – The runtime implements the ECMA Common Language Infrastructure (CLI). The runtime provides a Just-in-Time (JIT) compiler, an Ahead-of-Time compiler (AOT), a library loader, the garbage collector, a threading system and interoperability functionality.

Base Class Library – The Mono platform provides a comprehensive set of classes that provide a solid foundation to build applications on. These classes are compatible with Microsoft’s .Net Framework classes.

Mono Class Library – Mono also provides many classes that go above and beyond the Base Class Library provided by Microsoft. These provide additional functionality that are useful, especially in building Linux applications. Some examples are classes for Gtk+, Zip files, LDAP, OpenGL, Cairo, POSIX, etc.

The Benefits

There are many benefits to choosing Mono for application development:

Popularity – Built on the success of .Net, there are millions of developers that have experience building applications in C#. There are also tens of thousands of books, websites, tutorials, and example source code to help with any imaginable problem.

Higher-Level Programming – All Mono languages benefit from many features of the runtime, like automatic memory management, reflection, generics, and threading. These features allow you to concentrate on writing your application instead of writing system infrastructure code.

Base Class Library – Having a comprehensive class library provides thousands of built in classes to increase productivity. Need socket code or a hashtable? There’s no need to write your own as it’s built into the platform.

Cross Platform – Mono is built to be cross platform. Mono runs on Linux, Microsoft Windows, Mac OS X, BSD, and Sun Solaris, Nintendo Wii, Sony PlayStation 3, Apple iPhone. It also runs on x86, x86-64, IA64, PowerPC, SPARC (32), ARM, Alpha, s390, s390x (32 and 64 bits) and more. Developing your application with Mono allows you to run on nearly any computer in existance (details).

Common Language Runtime (CLR) – The CLR allows you to choose the programming language you like best to work with, and it can interoperate with code written in any other CLR language. For example, you can write a class in C#, inherit from it in VB.Net, and use it in Eiffel. You can choose to write code in Mono in a variety of programming languages.

–courtesy mono project

  • Share/Bookmark

MonoDevelop opens up Mac for .NET development

7 November 2009 | 1 Comment » | admin

As I said that I am a technology evangelist. I like new technology in .NET as well as open source. Other thing which I liked was Mac. But before MonoDevelop both were two different worlds. You could not develop a .NET application on a Mac OS X. MonoDevelop has solved most of my problem or you can say it is the new bridge between different platforms.

MonoDevelop is an opensource Integrated development environment for Linux platform, Mac OSX and Windows(to be supported in future). It allows you to develop software targeted to Mono and .NET framework. This IDE has feature like intellisense, source control integration and an integrated GUI and Web designer

MonoDevelop has recently launched the latest version of the IDE. To read more about it http://monodevelop.com/Download/MonoDevelop_2.0_Released.

If you’ve worked with Microsoft Visual Studio, you will see many similarities in MonoDevelop and will feel quite comfortable in the Mono environment. If you’re new to MonoDevelop and haven’t worked in Visual Studio, you’ll find that the learning curve is not very steep.

A new competitor for Visual Studio IDE…. eeh…lets see!!

  • Share/Bookmark

XMLDocument Vs LINQ to XML

6 November 2009 | No Comments » | admin

.NET as it had evolved has come up with different API to read and write XML data. If you are using .NET 3.0 and lower version you will have to use XMLDocument aka the classic DOM API. With .NET 3.0 Microsoft had launched Language Integrated Query(LINQ) and with this came one of the feature name the LINQ to XML.

LINQ to XML has a simple model for building XML documents by hand. Whether it be XML sources from a stream or file, or XML created on-the-fly in code there are only a few important types to know and understand. The main ones used in everyday activities are XDocument, XElement and XAttribute.

In this article we will talk about XDocument and XMLDocument.

Lets consider the following test data for our article

<root>

<child id=’123′/>

<child id=’234′/>

</root>

Reading the XML

XmlDocument.Load

XmlDocument.Load was the cleanest and easiest to understand. It is necessary that you must know XPath, although the fact is I like XPath. XmlDocument does have some security concerns with XPath injection. Here is how we code to load a document

private static void XmlDocumentReader(string fileName) {

XmlDocument doc = new XmlDocument();

doc.Load(fileName);

XmlNodeList nodes = doc.SelectNodes(“//child”);

if (nodes == null) {

throw new ApplicationException(“invalid data”);

}

foreach (XmlNode node in nodes) {

string id = node.Attributes["id"].Value;

ProcessId(id);

}

}

Another way to query a single node is given below

XmlDocument doc = XmlDocument.Load(fileName);

XmlNode node = doc.SelectSingleNodes(“/root/child[@id=’123’")

LINQ to XML

LINQ to XML was also very easy to read and understand code. XDocument.Load does read the whole document into memory before returning. Due to feature of Lambda expression it has become very easy to traverse the xml document. The query syntax is easier than XPath or XQuery for developers who do not use XPath or XQuery on a daily basis. Here is the code I used to load and search the document:

private static void XDocumentReader(string fileName) {

XDocument doc = XDocument.Load(fileName);

if (doc == null | doc.Root == null) {

throw new ApplicationException("invalid data");

}

foreach (XElement child in doc.Root.Elements("child")) {

XAttribute attr = child.Attribute("id");

if (attr == null) {

throw new ApplicationException("invalid data");

}

string id = attr.Value;

ProcessId(id);

}

}

Another way to query a single node is given below

var xd = XDocument.Load(fileName);

var domQuery =

from c in xd.Descendants("child ")

where (string)c.Attribute("id") == "123"

Writing a new XML

Both the method almost looks similar.

XmlDocument

XmlDocument xmlDoc = new XmlDocument();

// Write down the XML declaration

XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null);

// Create the root element

XmlElement rootNode  = xmlDoc.CreateElement("root");

xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);

xmlDoc.AppendChild(rootNode);

// Create a new <child> element and add it to the root node

XmlElement parentNode  = xmlDoc.CreateElement("child");

// Set attribute name and value!

parentNode.SetAttribute("ID", "01");

xmlDoc.DocumentElement.PrependChild(parentNode);

LINQ  to XML

XDocument doc = new XDocument(

new XDeclaration("1.0", "utf-8", "yes"),

new XElement("root",

new XElement ("child", new XAttribute("id", "01")

)

);

Manipulating XML Data

XmlDocument

Here we have to struggle with manipulating the xml data. First take help of XPath to select the node and then use replace node to update it. Or use the feature of delete node and insert new node. Code is given below

XmlDocument doc = new XmlDocument.Load(fileName);

//Select the cd node with the matching title

XmlNode oldCd;

XmlElement root = doc.DocumentElement;

oldCd = root.SelectSingleNode("/root/child[id='1']“);

XmlElement newCd = doc.CreateElement(“child”);

newCd.SetAttribute(“id”,2);

root.ReplaceChild(newCd, oldCd);

//save the output to a file

doc.Save(fileName);

LINQ  to XML

Here the code is very simple to write and understand. The coding time is also very less.

var xd = XDocument.Load(fileName);

var domQuery =

from c in xd.Descendants(“child “)

where (string)c.Attribute(“id”) == “123″

domQuery.Attribute(“id”).Value = 1

xd.save(filename)

Conclusion

Overall speaking both the API’s are equally powerful. However LINQ has made it little bit easier for developer to work with XML Data. I would say if you are using .NET 3.5 and higher you should rather go with LINQ To XML.

  • Share/Bookmark