Sometimes you will want to create a class that contains only static members and that cannot be instantiated. This is often the case when creating utility classes, or as an alternative to using the singleton design pattern. When using the .NET framework version 1.1, this is achieved by decorating every member declaration in the class with the "static" modifier and by including only private constructors.
In C# version 2.0, Microsoft introduced static classes to provide this behaviour using simpler code. A static class is simply a class whose definition is decorated with the "static" modifier. Once declared in this manner, the class may only contain static members. If any of the class' members is not declared as static, the compiler will report an error.
Static classes provide some benefits over standard classes. Firstly, the compiler ensures that no instance members are added accidentally. Secondly, the program can have improved performance because the overhead of creating objects is removed. However, static classes should be used with care, as they can be more difficult to mock for automated testing purposes.
A good example of the use of static classes is the Math class in the System namespace. In .NET 1.1, this was a sealed class with no public constructor. In .NET 2.0, this has been modified and is now a static class.
Creating a Static Class
To create a static class, the definition is prefixed with the "static" keyword. In the following example, the class holds a single system setting for an application. This setting holds the maximum number of files that can be used by the program and is controlled by a static property. The property is initialised in the static constructor.
public static class SystemSettings
{
static int _maximumFiles;
public static int MaximumFiles
{
get { return _maximumFiles; }
set { _maximumFiles = value; }
}
static SystemSettings()
{
_maximumFiles = 20;
}
}The members of the static class can be called without first creating an object. Instead, the name of the member is prefixed with the class name and a full stop (period), as can be demonstrated using the following code:
int maxFiles = SystemSettings.MaximumFiles;
Console.WriteLine("File limit = {0}", maxFiles); // Outputs "File limit = 20"
Tuesday, May 10, 2011
Tuesday, May 3, 2011
C# Named Parameters
With the introduction of C# 4.0, named parameters have been included in the language. Named parameters can be used to enhance the readability of source code and simplify some calls by specifying which parameters the argument values refer to.
When using a named argument, you provide the name of the parameter that you wish to pass a value to within the method call. For calls that pass literal values, this can improve the readability of your source code. Instead of viewing the method signature or displaying Intellisense for the call, the parameter names can make the literals instantly understood.
We can demonstrate this with an example. The MessageSender class below includes a single method that simulates sending a message by outputting to the console. The parameters allow some text to be provided, along with two formatting options.
When calling the SendMessage method without named parameters, the following code could be used:
At first glance, the "message" parameter is reasonably simple to understand. The effect of the two Boolean values is less easy to determine without viewing the method's signature. However, we can use named parameters for all three arguments to make their purposes obvious. This is achieved by adding the parameter name followed by a colon (:) prior to the value for each argument, as shown below:
Calls to the above method that do not use named parameters must provide the arguments in the correct order. This would prevent you from supplying a value for the capitalise parameter whilst using the default value for useQuotes. With named parameters, this restriction is removed:
What are Named Parameters?
In C# 3.0 and earlier versions, the arguments provided when calling a method would be evaluated in the order in which they appeared in the method's signature. By default, this is also the means by which argument lists are supplied in C# 4.0. However, it is now possible to associate individual arguments with specific parameters when calling a method, constructor, indexer or delegate by using named parameters.When using a named argument, you provide the name of the parameter that you wish to pass a value to within the method call. For calls that pass literal values, this can improve the readability of your source code. Instead of viewing the method signature or displaying Intellisense for the call, the parameter names can make the literals instantly understood.
We can demonstrate this with an example. The MessageSender class below includes a single method that simulates sending a message by outputting to the console. The parameters allow some text to be provided, along with two formatting options.
class MessageSender
{
public bool SendMessage(string message, bool useQuotes, bool capitalise)
{
message = capitalise ? message.ToUpper() : message;
message = useQuotes ? string.Format("\"{0}\"", message) : message;
Console.WriteLine(message);
return true;
}
}var sender = new MessageSender();
sender.SendMessage("Hello", false, true);sender.SendMessage(message: "Hello", useQuotes: false, capitalise: true);
When you are using named parameters, the arguments for a call no longer need to be passed in the order in which they appear in the member's signature. You are free to provide them in any order, allowing you to make the purpose of a call even more obvious in some situations. The following example might not improve readability but does show that the order of named arguments is unimportant to the compiler.sender.SendMessage(capitalise: true, useQuotes: false, message: "Hello");
You can mix named and unnamed arguments in a call as long as all of the unnamed arguments appear before any named ones. The unnamed arguments will be applied in the order that they appear in the method's signature. This allows code such as the following, where the first argument's purpose is obvious but where the readability of the two Booleans is improved by the naming:sender.SendMessage("Hello", useQuotes: false, capitalise: true);
Named Arguments with Optional Parameters
Named parameters provide more flexibility when used with optional parameters. When you make calls to members that include several optional parameters, you can omit any parameter whilst supplying values to any others. To demonstrate, adjust the test method as follows to make the two Boolean properties optional:public bool SendMessage(string message, bool useQuotes = false, bool capitalise = false)
{
message = capitalise ? message.ToUpper() : message;
message = useQuotes ? string.Format("\"{0}\"", message) : message;
Console.WriteLine(message);
return true;
}sender.SendMessage("Hello", capitalise: true);
3 essential skills for IT professionals
Whether you are preparing for a career in information technology (IT) or you are a seasoned professional, it's important to know what skill needs are emerging in the marketplace. As I review the technology and business landscape, I've made some observations about what I believe will be increasingly valuable proficiencies to bring to the table.
Demand for certain skills or an increased focus in specific areas is being motivated by drivers such as the commoditization of IT, which is moving many countries to more right-brained jobs economies; by the data deluge, which is presenting considerable opportunity to understand business in completely new ways; and by rigorous competition in the marketplace, which is forcing greater velocity in the generation of new service and product ideas.
Many roles within IT will continue to be valuable but may be more sensitive in the long run to the business landscape shifts we are experiencing. Rather than a decreasing need overall, I predict we'll continue to see a greater role for IT in the future as well as IT skills being an important part of almost every information worker's inventory of capabilities.
It's also fair to point out that we'll see new skills emerge that we can't even imagine right now. For example, in the mid-1990s it would have been near impossible to predict skills in search engine optimization (SEO) or the whole range of IT careers that have spawned from social media.
The following three skill areas will find high demand in the marketplace either as standalone careers or in combination with other skills.
In the context of IT, coordination is a skill set that provides guidance and oversight for the smooth interaction of multiple activities and their positive outcomes. It certainly includes project management, but it's not limited to it. People who can bridge relationships between disparate participants, such as developers in an offshore location and testers at a local facility; accommodating cultural differences, advocating for collective success, and expediting answers to questions and concerns, offer significant value.
The IT coordination skills can equally live in the business, the IT organization, or in a third-party provider. In a world where achieving results can often require the participation of a multitude a loosely related resources, effective coordination skills are paramount.
Acquiring great coordination proficiency certainly comes with experience, but preparation should include focusing on negotiation skills and communications in general; problem solving techniques; understanding the fundamentals of project management; and acquiring time management and prioritization methods.
Our digital world is creating mountains of new data. In fact, we are experiencing exponential growth in its volume. As an example, every two days now, we create as much information as we did from the dawn of civilization up until 2003. It's both a challenge and an opportunity. The challenge is clearly making sense of it. The opportunity is using findings in the data for competitive advantage.
It's becoming clear that large volumes of data can reveal new insights that were previously unknown. As examples, analysis performed on unstructured data scattered across the web can reveal sentiment on people and products. Examining the patterns within social network connections can tell us a lot about where authority resides.
It's within this new context that we see demand for people with skills to identify and extract valuable data; perform extensive analysis on it; discover patterns and hidden secrets contained within; and make sense of it for decision-making purposes.
To acquire these skills includes training in critical thinking, analysis tools, presenting quality communications through writing and visualization, and statistics.
We've seen large parts of IT turn into commoditized products and services. As an example, email is not a competitive advantage and it's largely dominated by one vendor. Whether you keep that capability and its attendant skills in-house is largely a cost and risk decision. Many organizations are reviewing their internal IT capabilities and concluding, that unless they are creating new value and a distinctive advantage, they simply remain a necessary cost center.
IT leaders are being tasked to reduce the cost center component to a minimum while ramping up the competitive elements of technology. The c-suite is requiring the IT organization to commit the biggest percentage of their available capacity to partnership activities with the business in creating new opportunities. It's this driver that is increasing the demand for innovation skills.
Innovation is the most abstract of the three skill areas in this blog as it is often the hardest to quantify. But it does include a wide range of skills that contribute to the conversion of ideas into net new business value. These include research, applied research, product evaluation and recommendations, problem solving, championing a new idea, and building a business case for investment that includes cost-benefit analysis.
As you consider your IT career, you might conclude that none of these skills are central to your interest. That's okay, too. My view is that, should you choose another IT path, it's still worth considering whether any of these three areas can complement your core interest. Whether you want to be or continue to be a programmer, business analyst, system administrator, or quality assurance analyst, adding one or more of the skills above can only add to your advantage.
We're guaranteed that the needs of the IT jobs marketplace will continue to change, but if each of us is ready to acquire new skills, a career in IT will remain one of the most lucrative and exciting of the professions.
Demand for certain skills or an increased focus in specific areas is being motivated by drivers such as the commoditization of IT, which is moving many countries to more right-brained jobs economies; by the data deluge, which is presenting considerable opportunity to understand business in completely new ways; and by rigorous competition in the marketplace, which is forcing greater velocity in the generation of new service and product ideas.
Many roles within IT will continue to be valuable but may be more sensitive in the long run to the business landscape shifts we are experiencing. Rather than a decreasing need overall, I predict we'll continue to see a greater role for IT in the future as well as IT skills being an important part of almost every information worker's inventory of capabilities.
It's also fair to point out that we'll see new skills emerge that we can't even imagine right now. For example, in the mid-1990s it would have been near impossible to predict skills in search engine optimization (SEO) or the whole range of IT careers that have spawned from social media.
The following three skill areas will find high demand in the marketplace either as standalone careers or in combination with other skills.
1. Coordination
In the context of IT, coordination is a skill set that provides guidance and oversight for the smooth interaction of multiple activities and their positive outcomes. It certainly includes project management, but it's not limited to it. People who can bridge relationships between disparate participants, such as developers in an offshore location and testers at a local facility; accommodating cultural differences, advocating for collective success, and expediting answers to questions and concerns, offer significant value.
The IT coordination skills can equally live in the business, the IT organization, or in a third-party provider. In a world where achieving results can often require the participation of a multitude a loosely related resources, effective coordination skills are paramount.
Acquiring great coordination proficiency certainly comes with experience, but preparation should include focusing on negotiation skills and communications in general; problem solving techniques; understanding the fundamentals of project management; and acquiring time management and prioritization methods.
2. Analysis
Our digital world is creating mountains of new data. In fact, we are experiencing exponential growth in its volume. As an example, every two days now, we create as much information as we did from the dawn of civilization up until 2003. It's both a challenge and an opportunity. The challenge is clearly making sense of it. The opportunity is using findings in the data for competitive advantage.
It's becoming clear that large volumes of data can reveal new insights that were previously unknown. As examples, analysis performed on unstructured data scattered across the web can reveal sentiment on people and products. Examining the patterns within social network connections can tell us a lot about where authority resides.
It's within this new context that we see demand for people with skills to identify and extract valuable data; perform extensive analysis on it; discover patterns and hidden secrets contained within; and make sense of it for decision-making purposes.
To acquire these skills includes training in critical thinking, analysis tools, presenting quality communications through writing and visualization, and statistics.
3. Innovation
We've seen large parts of IT turn into commoditized products and services. As an example, email is not a competitive advantage and it's largely dominated by one vendor. Whether you keep that capability and its attendant skills in-house is largely a cost and risk decision. Many organizations are reviewing their internal IT capabilities and concluding, that unless they are creating new value and a distinctive advantage, they simply remain a necessary cost center.
IT leaders are being tasked to reduce the cost center component to a minimum while ramping up the competitive elements of technology. The c-suite is requiring the IT organization to commit the biggest percentage of their available capacity to partnership activities with the business in creating new opportunities. It's this driver that is increasing the demand for innovation skills.
Innovation is the most abstract of the three skill areas in this blog as it is often the hardest to quantify. But it does include a wide range of skills that contribute to the conversion of ideas into net new business value. These include research, applied research, product evaluation and recommendations, problem solving, championing a new idea, and building a business case for investment that includes cost-benefit analysis.
As you consider your IT career, you might conclude that none of these skills are central to your interest. That's okay, too. My view is that, should you choose another IT path, it's still worth considering whether any of these three areas can complement your core interest. Whether you want to be or continue to be a programmer, business analyst, system administrator, or quality assurance analyst, adding one or more of the skills above can only add to your advantage.
We're guaranteed that the needs of the IT jobs marketplace will continue to change, but if each of us is ready to acquire new skills, a career in IT will remain one of the most lucrative and exciting of the professions.
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
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.
With .NET 2.0 you should create
- 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 theDataSource 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
- public class StringGet
- {
- public static string GetPageAsString(Uri address)
- {
- string result = "";
- // Create the web request
- HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
- // Get response
- using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
- {
- // Get the response stream
- StreamReader reader = new StreamReader(response.GetResponseStream());
- // Read the whole contents and return as a string
- result = reader.ReadToEnd();
- }
- return result;
- }
- }
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
- using System.Xml;
- // Retrieve XML document
- XmlTextReader reader = new XmlTextReader("http://xml.weather.yahoo.com/forecastrss?p=94704");
- // Skip non-significant whitespace
- reader.WhitespaceHandling = WhitespaceHandling.Significant;
- // Read nodes one at a time
- while (reader.Read())
- {
- // Print out info on node
- Console.WriteLine("{0}: {1}", reader.NodeType.ToString(), reader.Name);
- }
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
- // Create a new XmlDocument
- XmlDocument doc = new XmlDocument();
- // Load data
- doc.Load("http://xml.weather.yahoo.com/forecastrss?p=94704");
- // Set up namespace manager for XPath
- XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
- ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
- // Get forecast with XPath
- XmlNodeList nodes = doc.SelectNodes("/rss/channel/item/yweather:forecast", ns);
- // You can also get elements based on their tag name and namespace,
- // though this isn't recommended
- //XmlNodeList nodes = doc.GetElementsByTagName("forecast",
- // "http://xml.weather.yahoo.com/ns/rss/1.0");
- foreach(XmlNode node in nodes)
- {
- Console.WriteLine("{0}: {1}, {2}F - {3}F",
- node.Attributes["day"].InnerText,
- node.Attributes["text"].InnerText,
- node.Attributes["low"].InnerText,
- node.Attributes["high"].InnerText);
- }
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
- using System.Xml.XPath;
- // Create a new XmlDocument
- XPathDocument doc = new XPathDocument("http://xml.weather.yahoo.com/forecastrss?p=94704");
- // Create navigator
- XPathNavigator navigator = doc.CreateNavigator();
- // Set up namespace manager for XPath
- XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);
- ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
- // Get forecast with XPath
- XPathNodeIterator nodes = navigator.Select("/rss/channel/item/yweather:forecast", ns);
- while(nodes.MoveNext())
- {
- XPathNavigator node = nodes.Current;
- Console.WriteLine("{0}: {1}, {2}F - {3}F",
- node.GetAttribute("day", ns.DefaultNamespace),
- node.GetAttribute("text", ns.DefaultNamespace),
- node.GetAttribute("low", ns.DefaultNamespace),
- node.GetAttribute("high", ns.DefaultNamespace));
- }
Using a DataSet
Using aDataSet 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
- using System.Data;
- public void RunSample()
- {
- // Create the web request
- HttpWebRequest request
- = WebRequest.Create("http://xml.weather.yahoo.com/forecastrss?p=94704") as HttpWebRequest;
- // Get response
- using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
- {
- // Load data into a dataset
- DataSet dsWeather = new DataSet();
- dsWeather.ReadXml(response.GetResponseStream());
- // Print dataset information
- PrintDataSet(dsWeather);
- }
- }
- public static void PrintDataSet(DataSet ds)
- {
- // Print out all tables and their columns
- foreach (DataTable table in ds.Tables)
- {
- Console.WriteLine("TABLE '{0}'", table.TableName);
- Console.WriteLine("Total # of rows: {0}", table.Rows.Count);
- Console.WriteLine("---------------------------------------------------------------");
- foreach (DataColumn column in table.Columns)
- {
- Console.WriteLine("- {0} ({1})", column.ColumnName, column.DataType.ToString());
- } // foreach column
- Console.WriteLine(System.Environment.NewLine);
- } // foreach table
- // Print out table relations
- foreach (DataRelation relation in ds.Relations)
- {
- Console.WriteLine("RELATION: {0}", relation.RelationName);
- Console.WriteLine("---------------------------------------------------------------");
- Console.WriteLine("Parent: {0}", relation.ParentTable.TableName);
- Console.WriteLine("Child: {0}", relation.ChildTable.TableName);
- Console.WriteLine(System.Environment.NewLine);
- } // foreach relation
- }
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"
}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
public void PressHorn()
{
Console.WriteLine("Toot toot!");
}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...;
}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.
Subscribe to:
Posts (Atom)