Friday, April 29, 2011

Software Quotes


If someone shows off a very complicated software design to you, consider to quote the following:

"There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult."
C.A.R. Hoare

Let's say everything in a huge project is clear - theoretically. Why should implementing it be difficult? Because...

"In theory, theory and practice are the same. In practice, they're not."
Yogi Berra


"The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time."
Tom Cargill

Cutting the development time by throwing more developers into a project? Reply this:

"Nine people can't make a baby in a month."
Fred Brooks


"Whereas Europeans generally pronounce my name the right way ('Nick-louse Veert'), Americans invariably mangle it into 'Nickel's Worth.' This is to say that Europeans call me by name, but Americans call me by value."
Niklaus Wirth

Something every programmer of a large project at least said once in his life:

"It works on my machine."
Anonymous Programmer


"Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away."
Antoine de Saint Exupéry


You do deliberate practice to improve your ability to perform a task. It’s about skill and technique. Deliberate practice means repetition. It means performing the task with the aim of increasing your mastery of one or more aspects of the task. It means repeating the repetition. Slowly, over and over again, until you achieve your desired level of mastery. You do deliberate practice to master the task, not to complete the task.

Jon Jagger



1.If a program is incorrect, it matters little what the documentation says.
2.If documentation does not agree with the code, it is not worth much.
3.Consequently, code must largely document itself. If it cannot, rewrite the code rather than increase the supplementary documentation. Good code needs fewer comments than bad code does.
4.Comments should provide additional information that is not readily obtainable from the code itself. They should never parrot the code.
5.Mnemonic variable names and labels, and a layout that emphasizes logical structure, help make a program self-documenting

Kernighan and Plauger The Elements of Programming Style


Try and leave this world a little better than you found it.
Robert Stephenson Smyth Baden-Powell

Duplication Is Waste
Repetition in Process Calls for Automation
Repetition in Logic Calls for Abstraction
Steve Smith

Aspect-Oriented Programming

The inherent limitations of the OO paradigm were identified quite a few years ago, not many years after the introduction of OOP. However, today AOP still is not widely implemented even though everybody agrees on the benefits it produces. The main reason for such a limited adoption is essentially the lack of proper tools. We are pretty sure the day that AOP is (even only partially) supported by the .NET platform will represent a watershed in the history of AOP.
Wikipedia: Gregor Kiczales started and led the Xerox PARC team that eventually developed AspectJ

Cross-Cutting Concerns

AOP is about separating the implementation of cross-cutting concerns from the implementation of core concerns. For example, AOP is about separating a logger class from a task class so that multiple task classes can use the same logger and in different ways.
We have seen that dependency injection techniques allow you to inject—and quite easily, indeed—external dependencies in a class. A cross-cutting concern (for example, logging) can certainly be seen as an external dependency. So where's the problem?
Dependency injection requires up-front design or refactoring, which is not always entirely possible in a large project or during the update of a legacy system.
In AOP, you wrap up a cross-cutting concern in a new component called an aspect. An aspect is a reusable component that encapsulates the behavior that multiple classes in your project require.

Processing Aspects

In a classic OOP scenario, your project is made of a number of source files, each implementing one or more classes, including those representing a cross-cutting concern such as logging.
In an AOP scenario, on the other hand, aspects are not directly processed by the compiler. Aspects are in some way merged into the regular source code up to the point of producing code that can be processed by the compiler. If you are inclined to employ AspectJ, you use the Java programming language to write your classes and the AspectJ language to write aspects. AspectJ supports a custom syntax through which you indicate the expected behavior for the aspect. For example, a logging aspect might specify that it will log before and after a certain method is invoked and will validate input data, throwing an exception in case of invalid data.

In other words, an aspect describes a piece of standard and reusable code that you might want to inject in existing classes without touching the source code of these classes.

In the AspectJ jargon, the weaver is a sort of preprocessor that takes aspects and weaves their content with classes. It produces output that the compiler can render to an executable.

In other AOP-like frameworks, you might not find an explicit weaver tool. However, in any case, the content of an aspect is always processed by the framework and results in some form of code injection. This is radically different from dependency injection. We mean that the code declared in an aspect will be invoked at some specific points in the body of classes that require that aspect.

Before we discuss an example in .NET, we need to introduce a few specific terms and clarify their intended meaning. These concepts and terms come from the original definition of AOP. We suggest that you do not try to map them literally to a specific AOP framework. We suggest, instead, that you try to understand the concepts—the pillars of AOP—and then use this knowledge to better and more quickly understand the details of a particular framework.

Inside AOP Aspects


As mentioned, an aspect is the implementation of a cross-cutting concern. In the definition of an aspect, you need to specify advice to apply at specific join points.

A join point represents a point in the class that requires the aspect. It can be the invocation of a method, the body of a method or the getter/setter of a property, or an exception handler. In general, a join point indicates the point where you want to inject the aspect's code.

A pointcut represents a collection of join points. In AspectJ, pointcuts are defined by criteria using method names and wildcards. A sample pointcut might indicate that you group all calls to methods whose name begins with Get.

An advice refers to the code to inject in the target class. The code can be injected before, after, and around the join point. An advice is associated with a pointcut.
Here's a quick example of an aspect defined using AspectJ:
public aspect MyAspect
{
// Define a pointcut matched by all methods in the application whose name begins with
// Get and accepting no arguments. (There are many other ways to define criteria.)
public pointcut allGetMethods ():
call (* Get*() );

// Define an advice to run before any join points that matches the specified pointcut.
before(): allGetMethods()
{
// Do your cross-cutting concern stuff here
// for example, log about the method being executed
.
.
.
}
}
The weaver processes the aspect along with the source code (regular class-based source code) and generates raw material for the compiler. The code actually compiled ensures that an advice is invoked automatically by the AOP runtime whenever the execution flow reaches a join point in the matching pointcut.


AOP can be implemented in dot net using the Microsoft's Policy Injection Application Block in Enterprise Library 3.0 and higher. You can check it on MSDN Magazine or at Programming Help


Hoping that this topic has brought to you a wider vision about AOP, stay tuned for some examples of implementing AOP in Dot Net 4.0

Thursday, April 28, 2011

Using Returned XML with C#

Once you have retrieved data from a web service you will need to do something with it. This HOWTO describes the various built-in methods .NET provides to use XML returned by a web service.
  • Overview
  • Returned Data to a String
  • Using XmlReader
  • Using XmlDocument
  • Using XPathNavigator/XPathDocument
  • Using a DataSet
  • Further Reading

Overview

The .NET Framework provides excellent support for XML. Combined with the databinding support of WinForms and ASP.NET applications you have an easy and powerful set of tools. ASP.NET 2.0 takes databinding another step further by providing the DataSource control which lets you declaratively provide data access to data-bound UI controls.

Returned Data to a String

The simplest way to view the returned data is to get the response stream and put it into a string. This is especially handy for debugging. The following code gets a web page and returns the contents as a string.

C# String Sample


  1. public class StringGet   
  2. {   
  3.     public static string GetPageAsString(Uri address)   
  4.     {   
  5.         string result = "";   
  6.   
  7.         // Create the web request   
  8.         HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;   
  9.   
  10.         // Get response   
  11.         using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)   
  12.         {   
  13.             // Get the response stream   
  14.             StreamReader reader = new StreamReader(response.GetResponseStream());   
  15.   
  16.             // Read the whole contents and return as a string   
  17.             result = reader.ReadToEnd();   
  18.         }   
  19.   
  20.         return result;   
  21.     }   
  22. }   

Using XmlReader

XmlReader provides fast forward-only access to XML data. It also allows you to read data as simple-typed values rather than strings. XmlReader can load an XML document without having to use HttpRequest, though you won't have the same amount of control over the request. If you use HttpRequest, you can just pass the stream returned by the GetResponseStream() method to XmlReader. Fast write-only functions are provided by XmlTextWriter.
With .NET 2.0 you should create XmlReader instances using the System.Xml.XmlReader.Create method. For the sake of compatibility and clarity the next sample uses the .NET 1.1 creation method.

C# XmlReader Sample


  1. using System.Xml;   
  2.   
  3. // Retrieve XML document   
  4. XmlTextReader reader = new XmlTextReader("http://xml.weather.yahoo.com/forecastrss?p=94704");   
  5.   
  6. // Skip non-significant whitespace   
  7. reader.WhitespaceHandling = WhitespaceHandling.Significant;   
  8.   
  9. // Read nodes one at a time   
  10. while (reader.Read())   
  11. {   
  12.     // Print out info on node   
  13.     Console.WriteLine("{0}: {1}", reader.NodeType.ToString(), reader.Name);   
  14. }   

Using XmlDocument

XmlDocument gives more flexibility and is a good choice if you need to navigate or modify the data via the DOM. It also works as a source for the XslTransform class allowing you to perform XSL transformations.

C# XmlDocument Sample


  1. // Create a new XmlDocument   
  2. XmlDocument doc = new XmlDocument();   
  3.   
  4. // Load data   
  5. doc.Load("http://xml.weather.yahoo.com/forecastrss?p=94704");   
  6.   
  7. // Set up namespace manager for XPath   
  8. XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);   
  9. ns.AddNamespace("yweather""http://xml.weather.yahoo.com/ns/rss/1.0");   
  10.   
  11. // Get forecast with XPath   
  12. XmlNodeList nodes = doc.SelectNodes("/rss/channel/item/yweather:forecast", ns);   
  13.   
  14. // You can also get elements based on their tag name and namespace,   
  15. // though this isn't recommended   
  16. //XmlNodeList nodes = doc.GetElementsByTagName("forecast",    
  17. //                          "http://xml.weather.yahoo.com/ns/rss/1.0");   
  18.   
  19. foreach(XmlNode node in nodes)   
  20. {   
  21.     Console.WriteLine("{0}: {1}, {2}F - {3}F",   
  22.                         node.Attributes["day"].InnerText,   
  23.                         node.Attributes["text"].InnerText,   
  24.                         node.Attributes["low"].InnerText,   
  25.                         node.Attributes["high"].InnerText);   
  26. }   

Using XPathNavigator/XPathDocument

XPathDocument provides fast, read-only access to the contents of an XML document using XPath. Its usage is similar to using XPath with XmlDocument.

C# XPathDocument Sample


  1. using System.Xml.XPath;   
  2.   
  3. // Create a new XmlDocument   
  4. XPathDocument doc = new XPathDocument("http://xml.weather.yahoo.com/forecastrss?p=94704");   
  5.   
  6. // Create navigator   
  7. XPathNavigator navigator = doc.CreateNavigator();   
  8.   
  9. // Set up namespace manager for XPath   
  10. XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);   
  11. ns.AddNamespace("yweather""http://xml.weather.yahoo.com/ns/rss/1.0");   
  12.   
  13. // Get forecast with XPath   
  14. XPathNodeIterator nodes = navigator.Select("/rss/channel/item/yweather:forecast", ns);   
  15.   
  16. while(nodes.MoveNext())   
  17. {   
  18.     XPathNavigator node = nodes.Current;   
  19.   
  20.     Console.WriteLine("{0}: {1}, {2}F - {3}F",   
  21.                         node.GetAttribute("day", ns.DefaultNamespace),   
  22.                         node.GetAttribute("text", ns.DefaultNamespace),   
  23.                         node.GetAttribute("low", ns.DefaultNamespace),   
  24.                         node.GetAttribute("high", ns.DefaultNamespace));   
  25. }   

Using a DataSet

Using a DataSet from the System.Data namespace lets you bind the returned data to controls and also access hierarchical data easily. A dataset can infer the structure automatically from XML, create corresponding tables and relationships between them and populate the tables just by calling ReadXml().

C# DataSet Sample


  1. using System.Data;   
  2.   
  3. public void RunSample()   
  4. {   
  5.     // Create the web request   
  6.     HttpWebRequest request    
  7.         = WebRequest.Create("http://xml.weather.yahoo.com/forecastrss?p=94704"as HttpWebRequest;   
  8.   
  9.     // Get response   
  10.     using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)   
  11.     {   
  12.         // Load data into a dataset   
  13.         DataSet dsWeather = new DataSet();   
  14.         dsWeather.ReadXml(response.GetResponseStream());   
  15.   
  16.         // Print dataset information   
  17.         PrintDataSet(dsWeather);   
  18.     }   
  19. }   
  20.   
  21. public static void PrintDataSet(DataSet ds)   
  22. {   
  23.     // Print out all tables and their columns   
  24.     foreach (DataTable table in ds.Tables)   
  25.     {   
  26.         Console.WriteLine("TABLE '{0}'", table.TableName);   
  27.         Console.WriteLine("Total # of rows: {0}", table.Rows.Count);   
  28.         Console.WriteLine("---------------------------------------------------------------");   
  29.   
  30.         foreach (DataColumn column in table.Columns)   
  31.         {   
  32.             Console.WriteLine("- {0} ({1})", column.ColumnName, column.DataType.ToString());   
  33.         }  // foreach column   
  34.   
  35.         Console.WriteLine(System.Environment.NewLine);   
  36.     }  // foreach table   
  37.   
  38.     // Print out table relations   
  39.     foreach (DataRelation relation in ds.Relations)   
  40.     {   
  41.         Console.WriteLine("RELATION: {0}", relation.RelationName);   
  42.         Console.WriteLine("---------------------------------------------------------------");   
  43.         Console.WriteLine("Parent: {0}", relation.ParentTable.TableName);   
  44.         Console.WriteLine("Child: {0}", relation.ChildTable.TableName);   
  45.         Console.WriteLine(System.Environment.NewLine);   
  46.     }  // foreach relation   
  47. }   

Creating a Simple Class in C# (2)

Instantiating the Class

Although we have not explicitly added any functionality to the class, it can now be instantiated to create objects. These objects will have the standard behaviour of all classes. To demonstrated this, return to the program code file containing the Main method. In this method we will create a new vehicle object and run its ToString method to see the results. As we have not yet defined how ToString should work, this will simply show the fully qualified name.
static void Main(string[] args)
{
    Vehicle car = new Vehicle();
    Console.WriteLine(car.ToString());  // Outputs "ClassTest.Vehicle"
}
NB: The prefix of ClassTest is simply the name of the namespace of the Vehicle class.

Adding Methods

Public Methods

Public methods are part of the class' public interface, ie. these are the methods that can be called by other objects.
  • C# Methods
  • C# Functional Methods
  • C# Method Parameters
The syntax for creating methods described in the above articles must be modified slightly to make the methods visible to external objects. To achieve this, the public keyword is used as a prefix. The following code added to the vehicle class provides a new method for pressing a vehicle's horn. Make sure that you add the code within the class' code block.
public void PressHorn()
{
    Console.WriteLine("Toot toot!");
}
To use the new method, change the code within the Main method as follows:
static void Main(string[] args)
{
    Vehicle car = new Vehicle();
    car.PressHorn();                    // Outputs "Toot toot!"
}

Private Methods

To provide for encapsulation, where the internal functionality of the class is hidden, some methods will be defined as private. Methods with a private protection level are completely invisible to external classes. This makes it safe for the code to be modified to change functionality, improve performance, etc. without the need to update classes that use the public interface. To define a method as private, the private keyword can be used as a prefix to the method. Alternatively, using no prefix at all implies that the method is private by default.
The following method of the car class is a part of the internal implementation not the public interface so is defined as being private.
private void MonitorOilTemperature()
{
    // Internal oil temperature monitoring code...;
}
To demonstrate that this method is unavailable to external classes, try the following code in the Main method of the program. When you attempt to compile or execute the program, an error occurs indicating that the MonitorOilTemperature method cannot be called due to its protection level.
static void Main(string[] args)
{
    Vehicle car = new Vehicle();
    car.MonitorOilTemperature();
}

Limitations

This article has described the creation of a basic class with public and private methods. However, every object that is generated from this class is identical, as it currently has no state. In the next article in the series, we will add properties to the class to resolve this.

Creating a Simple Class in C#

What is a Class?

The class is the fundamental building block of code when creating object-oriented software. A class describes in abstract all of the characteristics and behaviour of a type of object. Once instantiated, an object is generated that has all of the methods, properties and other behaviour defined within the class.
A class should not be confused with an object. The class is the abstract concept for an object that is created at design-time by the programmer. The objects based upon the class are the concrete instances of the class that occur at run-time. For example, the Car class will define that all cars have a make, model and colour. Only at run-time will an object be instantiated as a Red Ferrari Dino.

Creating a Class

The basic syntax for the creation of a new class is very simple. The keyword 'class' followed by the name of the new class is simply added to the program. This is then followed by a code block surrounded by brace characters {} to which the class' code will be added.
class class-name {}
To demonstrate this, we will create a new class in a new console application.

Create a Console Application

I will assume that you are using either Microsoft Visual Studio or Microsoft C# 2005 Express Edition to develop this program. Launch either of these development environments and elect to create a new project of type, "Console Application". Name the application, "ClassTest".
If you are using another development environment, follow the processes required to create a new console application.
Once the new application has been created, you should have a single code file named 'Program.cs' or similar within the new project. This should contain a class definition and a single method named 'Main'. This method is the first piece of code executed when the software runs. The class definition will be within the code block of a namespace called 'ClassTest'. We will return to this class later.

Add a New Class to the Application

Any number of classes may be added to a namespace within a single code file. However, as this would quickly lead to very large files, it is more readable to separate classes into their own files. We will now add a new class file to the project for a class that will describe vehicles.
Choose 'Add Class...' from the Project menu of Visual Studio or Microsoft C# Express Edition. You will be asked for a name for the new class. Type 'Vehicle' and click the Add button. A new class file is generated with the definition of the class already added. Note that the namespace is the same as the namespace in the original file. You can switch between files using the Solution Explorer to compare the namespaces.
Your new class definition should be similar to that below:
namespace ClassTest
{
    class Vehicle
    {
    }
}
NB: If you are not using Visual Studio, the process for adding a class file may differ slightly.