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 |
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 |
sealed | A sealed class cannot be inherited. |
short | The short keyword denotes an integral data type that stores values |
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 |
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 |
ulong | The ulong keyword denotes an integral type that stores values according |
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 |
ushort | The ushort keyword denotes an integral data type that stores values |
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 |
void | When used as the return type for a method, void specifies that the method |
while | The while statement executes a statement or a block of statements until a specified expression evaluates to false. |
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.
ASCII Table
ASCII stands for American |
|
|
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);
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"
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.
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
- }
Subscribe to:
Posts (Atom)