Monday, September 12, 2011

C# Keywords Table

Table of C# keywords and Descriptions. C# was a language developed by the Microsoft Corporation in the late 1990’s. It is an object oriented language that resembles both C and Java. The C# keywords reflect it’s origins as an off shoot of the C language. The following C# keywords are the building blocks of the programming language. A C# program is constructed by creating a syntactically and procedurally correct program file that can be compiled by a C# compiler.




Code

Description
abstract The abstract modifier can be used with classes,
methods, properties, indexers, and events.
as The as operator is used to perform conversions between
compatible types.
base The base keyword is used to access members of the base
class from within a derived class
bool

The bool keyword is an alias of System.Boolean. It is used to
declare variables to store the Boolean values, true and false.
break The break statement terminates the closest enclosing
loop or switch statement in which it appears.
byte The byte keyword denotes an integral type that stores
values as indicated in the following table.
case The switch statement is a control statement that
handles multiple selections by passing control to one of the case statements
within its body.
catch The try-catch statement consists of a try block
followed by one or more catch clauses, which specify handlers for
different exceptions.
char The char keyword is used to
declare a Unicode character in the range indicated in the following table.
checked The checked keyword is used to control the
overflow-checking context for integral-type arithmetic operations and
conversions.
class Classes are declared using the keyword class.
const The const keyword is used to modify a declaration of a
field or local variable.
continue The continue statement passes control to the next
iteration of the enclosing iteration statement in which it appears.
decimal The decimal keyword denotes a 128-bit data type.
default The switch statement is a control statement that
handles multiple selections by passing control to one of the case statements
within its body.
delegate A delegate declaration defines a reference type that
can be used to encapsulate a method with a specific signature.
do The do statement executes a statement or a block of
statements repeatedly until a specified expression evaluates to false.
double The double keyword denotes a simple type that stores
64-bit floating-point values.
else The if-else statement selects a
statement for execution based on the value of a Boolean expression.
enum The enum keyword is used to declare an enumeration, a
distinct type consisting of a set of named constants called the enumerator
list.
event

Specifies an event.

explicit The explicit keyword is used to
declare an explicit user-defined type conversion operator
extern Use the extern modifier in a method declaration to
indicate that the method is implemented externally.
false In C#, the false keyword can be used as an overloaded
operator or as a literal
finally The finally block is useful for cleaning up any
resources allocated in the try block.
fixed Prevents relocation of a variable by the garbage collector.
float The float keyword denotes a simple type that stores
32-bit floating-point values.
for The for loop executes a statement or a block of
statements repeatedly until a specified expression evaluates to false.
foreach The foreach statement repeats a group of embedded
statements for each element in an array or an object collection.
goto The goto statement transfers the program control
directly to a labeled statement.
if The if statement selects a statement for execution
based on the value of a Boolean expression.
implicit The implicit keyword is used to declare an implicit
user-defined type conversion operator.
in The foreach,in statement repeats a group of embedded
statements for each element in an array or an object collection.
int The int keyword denotes an integral type that stores
values according to the size and range shown in the following table.
interface An interface defines a contract. A class or struct that
implements an interface must adhere to its contract.
internal The internal keyword is an access modifier for types
and type members.
is The is operator is used to check whether the run-time
type of an object is compatible with a given type.
lock The lock keyword marks a statement block as a critical
section by obtaining the mutual-exclusion lock for a given object, executing a
statement, and then releasing the lock.
long The long keyword denotes an integral type that stores
values according to the size and range shown in the following table.
namespace The namespace keyword is used to declare a scope. This
namespace scope lets you organize code and gives you a way to create
globally-unique types.
new

In C#, the new keyword can be used as an operator or as a modifier.

null The null keyword is a literal that represents a null
reference, one that does not refer to any object.
object The object type is an alias for System.Object in
the .NET Framework.
operator The operator keyword is used to declare an operator in
a class or struct declaration.
out The out method parameter keyword on a method parameter
causes a method to refer to the same variable that was passed into the method
override Use the override modifier to modify a method, a
property, an indexer, or an event.
params

The params keyword lets you specify a method parameter that takes an
argument where the number of arguments is variable.

private The private keyword is a member access modifier.
protected The protected keyword is a member access modifier.
public The public keyword is an access modifier for types and
type members.
readonly The readonly keyword is a modifier that you can use on
fields.
ref The ref method parameter keyword on a method parameter
causes a method to refer to the same variable that was passed into the method.
return The return statement terminates execution of the
method in which it appears and returns control to the calling method.
sbyte

The sbyte keyword denotes an integral type that stores values according
to the size and range shown in the following table.

sealed A sealed class cannot be inherited.
short

The short keyword denotes an integral data type that stores values
according to the size and range shown in the following table.

sizeof The sizeof operator is used to obtain the size in
bytes for a value type.
stackalloc

Allocates a block of memory on the stack.


static Use the static modifier to declare a static member,
which belongs to the type itself rather than to a specific object.
string The string type represents a string of Unicode
characters.
struct A struct type is a value type that can contain
constructors, constants, fields, methods, properties, indexers, operators,
events, and nested types.
switch The switch statement is a control statement that
handles multiple selections by passing control to one of the case statements
within its body.
this The this keyword refers to the current instance of the
class. Static member functions do not have a this pointer.
throw The throw statement is used to signal the occurrence
of an anomalous situation (exception) during the program execution.
true

In C#, the true keyword can be used as an overloaded operator or as a
literal.

try The try-catch statement consists of a try block
followed by one or more catch clauses, which specify handlers for
different exceptions.
typeof The typeof operator is used to obtain the System.Type

object for a type.
uint

The uint keyword denotes an integral type that stores values according to
the size and range shown in the following table.


ulong

The ulong keyword denotes an integral type that stores values according
to the size and range shown in the following table.


unchecked The unchecked keyword is used to control the
overflow-checking context for integral-type arithmetic operations and
conversions.
unsafe

The unsafe keyword denotes an unsafe context, which is required for any
operation involving pointers.

ushort

The ushort keyword denotes an integral data type that stores values
according to the size and range shown in the following table.

using The using keyword has two major uses.
virtual The virtual keyword is used to modify a method or
property declaration, in which case the method or the property is called a
virtual member.
volatile

The volatile keyword indicates that a field can be modified in the
program by something such as the operating system, the hardware, or a
concurrently executing thread.


void

When used as the return type for a method, void specifies that the method
does not return a value.


while The while statement executes a statement or a block of
statements until a specified expression evaluates to false.

ASCII Table




ASCII stands for American
Standard Code for Information Interchange. The ASCII character set was
first published as a standard in 1967 and was last updated in 1986. The
ASCII character set was mostly used by small to mid-range computers
systems. The ASCII character set is the human readable representation
of binary numbers. The below ASCII table shows the 33 non-printable and
95 printable characters.







Dec

Hex

Oct

Char

0 0 000   null
1 1 001   start of heading
2 2 002   start of text
3 3 003   end of text
4 4 004   end of transmission
5 5 005   enquiry
6 6 006   acknowledge
7 7 007   bell
8 8 010   backspace
9 9 011   horizontal tab
10 A 012   new line
11 B 013   vertical tab
12 C 014   new page
13 D 015   carriage return
14 E 016   shift out
15 F 017   shift in
16 10 020   data link escape
17 11 021   device control 1
18 12 022   device control 2
19 13 023   device control 3
20 14 024   device control 4
21 15 025   negative acknowledge
22 16 026   synchronous idle
23 17 027   end of trans. block
24 18 030   cancel
25 19 031   end of medium
26 1A 032   substitute
27 1B 033   escape
28 1C 034   file separator
29 1D 035   group separator
30 1E 036   record separator
31 1F 037   unit separator
32 20 040   space
33 21 041 !  
34 22 042 "  
35 23 043 #  
36 24 044 $  
37 25 045 %  
38 26 046 &  
39 27 047 '  
40 28 050 (  
41 29 051 )  
42 2A 052 *  
43 2B 053 +  
44 2C 054 ,  
45 2D 055 -  
46 2E 056 .  
47 2F 057 /  
48 30 060 0  
49 31 061 1  
50 32 062 2  
51 33 063 3  
52 34 064 4  
53 35 065 5  
54 36 066 6  
55 37 067 7  
56 38 070 8  
57 39 071 9  
58 3A 072 :  
59 3B 073 ;  
60 3C 074 <  
61 3D 075 =  
62 3E 076 >  
63 3F 077 ?  


Dec

Hex

Oct

Char

Description
64 40 100 @  
65 41 101 A  
66 42 102 B  
67 43 103 C  
68 44 104 D  
69 45 105 E  
70 46 106 F  
71 47 107 G  
72 48 110 H  
73 49 111 I  
74 4A 112 J  
75 4B 113 K  
76 4C 114 L  
77 4D 115 M  
78 4E 116 N  
79 4F 117 O  
80 50 120 P  
81 51 121 Q  
82 52 122 R  
83 53 123 S  
84 54 124 T  
85 55 125 U  
86 56 126 V  
87 57 127 W  
88 58 130 X  
89 59 131 Y  
90 5A 132 Z  
91 5B 133 [  
92 5C 134 \  
93 5D 135 ]  
94 5E 136 ^  
95 5F 137 _  
96 60 140 `  
97 61 141 a  
98 62 142 b  
99 63 143 c  
100 64 144 d  
101 65 145 e  
102 66 146 f  
103 67 147 g  
104 68 150 h  
105 69 151 i  
106 6A 152 j  
107 6B 153 k  
108 6C 154 l  
109 6D 155 m  
110 6E 156 n  
111 6F 157 o  
112 70 160 p  
113 71 161 q  
114 72 162 r  
115 73 163 s  
116 74 164 t  
117 75 165 u  
118 76 166 v  
119 77 167 w  
120 78 170 x  
121 79 171 y  
122 7A 172 z  
123 7B 173 {  
124 7C 174 |  
125 7D 175 }  
126 7E 176 ~  
127 7F 177 DEL  

Reflection Examples [C#]

This example shows how to dynamically load assembly, how to create object instance, how to invoke method or how to get and set property value.
Create instance from assembly that is in your project References

The following examples create instances of DateTime class from the System assembly.
[C#]

// create instance of class DateTime
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));


[C#]

// create instance of DateTime, use constructor with parameters (year, month, day)
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime),
new object[] { 2008, 7, 4 });


Create instance from dynamically loaded assembly

All the following examples try to access to sample class Calculator from Test.dll assembly. The calculator class can be defined like this.
[C#]

namespace Test
{
public class Calculator
{
public Calculator() { ... }
private double _number;
public double Number { get { ... } set { ... } }
public void Clear() { ... }
private void DoClear() { ... }
public double Add(double number) { ... }
public static double Pi { ... }
public static double GetPi() { ... }
}
}


Examples of using reflection to load the Test.dll assembly, to create instance of the Calculator class and to access its members (public/private, instance/static).
[C#]

// dynamically load assembly from file Test.dll
Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");


[C#]

// get type of class Calculator from just loaded assembly
Type calcType = testAssembly.GetType("Test.Calculator");


[C#]

// create instance of class Calculator
object calcInstance = Activator.CreateInstance(calcType);


[C#]

// get info about property: public double Number
PropertyInfo numberPropertyInfo = calcType.GetProperty("Number");


[C#]

// get value of property: public double Number
double value = (double)numberPropertyInfo.GetValue(calcInstance, null);


[C#]

// set value of property: public double Number
numberPropertyInfo.SetValue(calcInstance, 10.0, null);


[C#]

// get info about static property: public static double Pi
PropertyInfo piPropertyInfo = calcType.GetProperty("Pi");


[C#]

// get value of static property: public static double Pi
double piValue = (double)piPropertyInfo.GetValue(null, null);


[C#]

// invoke public instance method: public void Clear()
calcType.InvokeMember("Clear",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, calcInstance, null);


[C#]

// invoke private instance method: private void DoClear()
calcType.InvokeMember("DoClear",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
null, calcInstance, null);


[C#]

// invoke public instance method: public double Add(double number)
double value = (double)calcType.InvokeMember("Add",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, calcInstance, new object[] { 20.0 });


[C#]

// invoke public static method: public static double GetPi()
double piValue = (double)calcType.InvokeMember("GetPi",
BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public,
null, null, null);


[C#]

// get value of private field: private double _number
double value = (double)calcType.InvokeMember("_number",
BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic,
null, calcInstance, null);

Tuesday, May 10, 2011

What is a Static Class?

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 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.

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;
    }
}
When calling the SendMessage method without named parameters, the following code could be used:
var sender = new MessageSender();
sender.SendMessage("Hello", false, true);
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:
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;
}
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:

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.

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

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. }