Google
 

Friday, May 25, 2007

patterns & practices Team Development with TFS Guide

REF:http://www.codeplex.com/TFSGuide

Welcome to the patterns & practices Team Development with Visual Studio Team Foundation Server project site! This guide shows you how to make the most of Team Foundation Server. It starts with the end in mind, but shows you how to incrementally adopt TFS for your organization. It's a collaborative effort between patterns & practices, Team System team members, and industry experts. This guide is related to our Visual Studio Team System Guidance Project. - J.D. Meier, Jason Taylor, Alex Mackman, Prashant Bansode, Kevin Jones

TeamDevGuide.gif

Download the Guide

Beta 1 Release is Available! Start using the guide today, while we continue to make improvements.

Parts

Part I, Fundamentals
Part II, Source Control
Part III, Builds
Part IV, Large Project Considerations
Part V, Project Management
Part VI, Process Guidance
Part VII, Reporting
Part VIII, Setting Up and Maintaining the Team Environment

Chapters

  • Introduction
  • Ch 01 - Introducing the Team Environment
  • Ch 02 - Team Foundation Server Architecture
  • Ch 03 - Structuring Projects and Solutions
  • Ch 04 - Structuring Projects and Solutions in Team Foundation Server
  • Ch 05 - Defining Your Branching and Merging Strategy
  • Ch 06 - Managing Source Control Dependencies in Visual Studio Team System
  • Ch 07 - Team Build Explained
  • Ch 08 - Setting Up Continuous Integration with Team Build
  • Ch 09 - Setting Up Scheduled Builds with Team Build
  • Ch 10 - Large Project Considerations
  • Ch 11 - Project Management Explained
  • Ch 12 - Work Items Explained
  • Ch 13 – MSF Agile Projects
  • Ch 14 - Process Templates Explained
  • Ch 15 - Reporting Explained
  • Ch 16 - Team Foundation Server Deployment
  • Ch 17 - Providing Internet Access to Team Foundation Server

Guidelines
  • Guidelines: Visual Studio 2005 Team Foundation Server Source Control

Practices
  • Practices at a Glance: Team Foundation Server Source Control

Questions and Answers
  • Questions and Answers: Team Foundation Server Source Control and Versioning

How Tos
  • How To: Add a New Developer To Your Project in Visual Studio 2005 Team Foundation Server
  • How To: Automate Running Unit Test and Code Analysis with Team Build
  • How To: Create Build Notifications
  • How To: Create a Custom Report with Visual Studio 2005 Team Foundation Server
  • How To: Create a Risk Over Time Report with Visual Studio 2005 Team Foundation Server
  • How To: Customize a Report with Visual Studio 2005 Team Foundation Server
  • How To: Manage Projects with Visual Studio 2005 Team Foundation Server
  • How To: Migrate Source code to Team Foundation Server from Visual Source Safe
  • How To: Perform a Baseless Merge
  • How To: Setup a Continuous Integration Build
  • How To: Setup a Scheduled Build
  • How To: Step Through Creating Your Source Tree in Team Foundation Server
  • How To: Step Through Creating Custom checkin Policies for Team Foundation Server
  • How To: Structure ASP.NET Applications for Team Foundation Server
  • How To: Structure Windows Applications for Team Foundation Server
  • How To: Structure Your Source Control Folders in Team Foundation Server

Resources

Team


Feedback


Related Sites


--
Happy day, happy life!

Best Practices for Accelerating Problem Resolution in .NET Applications and Web Services

The Basics of Microsoft .NET


• Microsoft .NET is Microsoft's platform for building N-tier
applications. Microsoft .NET encompasses a family of products built
on industry and Internet standards that provide for each aspect of
developing (Visual Studio .NET), managing (.NET Servers) and
using Web services.
• Web services is a software technology that is used to connect
applications and users over standard Internet protocols. Web services
can be implemented through Microsoft Windows DNA, Microsoft
.NET, and J2EE applications.
• XML (Extensible Markup Language) is the universal format for
Web services. XML is a set of rules for designing text formats for
data, in a way that produces files that are easy to generate
and read (by a computer), and that are unambiguous and
platform-independent.
• SOAP (Simple Object Access Protocol) is a protocol built on XML.
Using SOAP, applications call each other in a standard, loosely
coupled way, making it possible to build applications that are
distributed across the Internet. If you think of the interactions
between XML Web services as a phone call, XML describes the
things that applications say to each other in their conversations
and SOAP describes how they call each other on the phone.
• CLR (Common Language Runtime) is a core component of the
Microsoft .NET Framework. Similar to a Java Virtual Machine, the
CLR is a native Windows program that provides various services,
such as memory management, security management and error
handling, to .NET managed applications. Programs can be written
for the CLR in any .NET language, including C# and VB.NET.
ASP.NET, the new version of Microsoft's ASP, is a programming
framework built on the CLR that can be used on a server to build
.NET Web applications.
ADO.NET, the new version of Microsoft's ADO, provides .NET
applications with optimized access to data sources such as
Microsoft SQL Server, as well as data sources exposed through
OLE DB and XML.
• Remoting is a .NET technology for calling procedures over the
network using XML, SOAP, and HTTP just as if they were hosted on
the same computer (you can think of Remoting as the .NET version
of DCOM).
• Interop is the process of getting managed and unmanaged
objects (e.g. COM objects) to work together.
• Assembly is the .NET logical equivalent of a DLL, a reusable
application component.
• GC (Garbage Collection) is the .NET mechanism for managing
memory, designed to absolve developers from tracking memory
usage and knowing when to free memory.

Common Problems with .NET Applications

Common Problems with .NET Applications
While Microsoft .NET addresses many of the issues historically
associated with building and deploying distributed applications, it
presents many new challenges related to deployment and support.
This is due to the following reasons:
• .NET applications are typically highly distributed; hence problem
triage is complex and time-consuming.
• .NET is a gigantic new set of technologies and concepts. As with
any new software platform, problems are common and inevitable.
• Web services often translate to significantly higher levels of
dependency between applications and a growing number of endusers,
thus increasing the direct and indirect costs of problems and
inefficiencies in the support process.
The following are some of the common problems associated with
.NET applications:

Performance Problems

As with any software environment, performance problems are
common and often difficult to pinpoint. The possible causes for
these problems include:
• Inefficient code ( e.g. frequent exceptions, many large objects,inefficient database calls – using ad hoc queries rather than
compiled stored procedures).
• Memory consumption (e.g. not freeing objects when they are no
longer used, allocating too much memory per request, inadequate
definition of maximum number of Worker and IO threads).
• Improper application settings (e.g. inadequate session-state
provider, buffering disabled on a Web Forms page).
• Interoperability with legacy Windows code ( e.g. marshaling a lot
of data from COM/COM+ to managed .NET objects).
• Infrastructure problems (e.g. bad network response times that
cause degradation in application performance).

Functional Problems

The Microsoft .NET Framework has been designed to free the
developer from dealing with various programming tasks, such
as memory allocations and security. However, just like in any
development platform, coding errors are still in abundance.
Some of the most common coding errors are:
• Incorrect business logic (e.g. incorrect calculation of interest rate).
• Thread deadlock situations.
• A severe error which leads to an application crash.


Configuration Problems

While .NET promises to resolve "DLL-hell" issues, configuration
problems are far from gone. The following detail some of the
common configuration issues with .NET applications:
• Insufficient permissions to access a resource (e.g. no permission
to write to an application directory).
• Incompatible components (e.g. incorrect versions of assemblies or
COM/COM+ objects).
• Incorrect application settings in .NET configuration files
• Conflicts with other applications (e.g. an anti-virus tool that causes a
Web application to restart intermittently).

User Errors

.NET applications are built to serve end-users. As with any software
application, users make mistakes. Some of these mistakes are resolved
quickly, while some take days to figure out.


--
Happy day, happy life!

C♯ Coding Style Guide

C♯ Coding Style Guide

  1. Keep your classes/files short, don't exceed 2000 LOC, divide your code up, make structures clearer.
  2. Create a directory for every namespace.
  3. When an expression will not fit on a single line, break it up according to these general principles:
     Break after a comma.
     Break after an operator.
     Prefer higher-level breaks to lower-level breaks.
     Align the new line with the beginning of the expression at the same level on the previous line
  4. Don't use spaces for indentation - use tabs!
  5. Block comments should usually be avoided. For descriptions use of the /// comments to give C ♯ standard
    descriptions is recommended. When you wish to use block comments you should use the following style :
    /* Line 1
    * Line 2
    * Line 3
    */
    As this will set off the block visually from code for the (human) reader.
  6. You should use the // comment style to "comment out" code (SharpDevelop has a key for it, Alt+/) . It may
    be used for commenting sections of code too. A rule of thumb says that generally, the length of a comment should not exceed the length of the code explained by too much, as this is an indication of too complicated, potentially buggy, code.
  7. These comments are formally single line C♯ comments containing XML tags. They follow this
    pattern for single line comments:
    /// <summary>
    /// This class...
    /// </summary>
    Multiline XML comments follow this pattern:
    /// <exception cref="BogusException">
    /// This exception gets thrown as soon as a
    /// Bogus flag gets set.
    /// </exception>
    All lines must be preceded by three slashes to be accepted as XML comment lines.
    Tags fall into two categories:
    • Documentation items
    • Formatting/Referencing
  8. One declaration per line is recommended since it encourages commenting
  9. Try to initialize local variables as soon as they are declared.Note: If you initialize a dialog try to use the using statement:
    using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
    ...
    }
  10. When coding C♯ classes and interfaces, the following formatting rules should be followed:
    • No space between a method name and the parenthesis "(" starting its parameter list.
    • The opening brace "{" appears in the next line after the declaration statement.
    • The closing brace " }" starts a line by itself indented to match its corresponding opening
    brace.
  11. Each line should contain only one statement.
  12. A return statement should not use outer most parentheses.
    Don't use : return (n * (n + 1) / 2);
    use : return n * (n + 1) / 2;
  13. if, if-else and if else-if else statements should look like this:
    if (condition) {
    DoSomething();
    ...
    }
    if (condition) {
    DoSomething();
    ...
    } else {
    DoSomethingOther();
    ...
    }
    if (condition) {
    DoSomething();
    ...
    } else if (condition) {
    DoSomethingOther();
    ...
    } else {
    DoSomethingOtherAgain();
    ...
    }
  14. A for statement shoud have following form :
    for (int i = 0; i < 5; ++i) {
    ...
    }
    or single lined (consider using a while statement instead) :
    for (initialization; condition; update) ;
    A foreach should look like :
    foreach (int i in IntList) {
    ...
    }
    Note: Generally use brackets even if there is only one statement in the loop.
  15. A while statement should be written as follows:
    while (condition) {
    ...
    }
    An empty while should have the following form:
    while (condition) ;
    A do-while statement should have the following form:
    do {
    ...
    } while (condition);
  16. A switch statement should be of following form:
    switch (condition) {
    case A:
    ...
    break;
    case B:
    ...
    break;
    default:
    ...
    break;
    }
  17. A try-catch statement should follow this form:
    try {
    ...
    } catch (Exception) {}
    or
    try {
    ...
    } catch (Exception e) {
    ...
    }
    or
    try {
    ...
    } catch (Exception e) {
    ...
    } finally {
    ...
    }
  18. Blank lines improve readability. They set off blocks of code which are in themselves logically related.
    Two blank lines should always be used between:
     Logical sections of a source file
     Class and interface definitions (try one class/interface per file to prevent this case)
    One blank line should always be used between:
     Methods
     Properties
     Local variables in a method and its first statement
     Logical sections inside a method to improve readability
    Note that blank lines must be indented as they would contain a statement this makes insertion in these lines
    much easier.
  19. There should be a single space after a comma or a semicolon, for example:
    TestMethod(a, b, c); don't use : TestMethod(a,b,c)
    or
    TestMethod( a, b, c );
  20. Single spaces surround operators (except unary operators like increment or logical not), example:
    a = b; // don't use a=b;
    for (int i = 0; i < 10; ++i) // don't use for (int i=0; i<10; ++i)
    // or
    // for(int i=0;i<10;++i)
  21. A logical block of lines should be formatted as a table:
    string name = "Mr. Ed";
    int myValue = 5;
    Test aTest = Test.TestYou;
    Use spaces for the table like formatting and not tabs because the table formatting may look strange in
    special tab intent levels.
  22. Pascal Casing
    This convention capitalizes the first character of each word (as in TestCounter).
  23. Camel Casing
    This convention capitalizes the first character of each word except the first one. E.g. testCounter.
  24. Only use all upper case for identifiers if it consists of an abbreviation which is one or two characters long,
    identifiers of three or more characters should use Pascal Casing instead. For Example:
    public class Math
    {
    public const PI = ...
    public const E = ...
    public const feigenBaumNumber = ...
    }
  25. Naming Guidelines
    Generally the use of underscore characters inside names and naming according to the guidelines for
    Hungarian notation are considered bad practice.
    Hungarian notation is a defined set of pre and postfixes which are applied to names to reflect the type of the
    variable. This style of naming was widely used in early Windows programming, but now is obsolete or at
    least should be considered deprecated. Using Hungarian notation is not allowed if you follow this guide.
    And remember: a good variable name describes the semantic not the type.
    An exception to this rule is GUI code. All fields and variable names that contain GUI elements like button
    should be postfixed with their type name without abbreviations. For example:
    System.Windows.Forms.Button cancelButton;
    System.Windows.Forms.TextBox nameTextBox;
  26. Class Naming Guidelines
     Class names must be nouns or noun phrases.
     UsePascal Casing see 8.1.1
     Do not use any class prefix
  27. Interface Naming Guidelines
     Name interfaces with nouns or noun phrases or adjectives describing behavior. (Example IComponent
    or IEnumberable)
     Use Pascal Casing (see 8.1.1)
     Use I as prefix for the name, it is followed by a capital letter (first char of the interface name)
  28. Enum Naming Guidelines
     Use Pascal Casing for enum value names and enum type names
     Don't prefix (or suffix) a enum type or enum values
     Use singular names for enums
     Use plural name for bit fields.
  29. ReadOnly and Const Field Names
     Name static fields with nouns, noun phrases or abbreviations for nouns
     Use Pascal Casing (see 8.1.1)
  30. Parameter/non const field Names
     Do use descriptive names, which should be enough to determine the variable meaning and it's type. But
    prefer a name that's based on the parameter's meaning.
     Use Camel Casing (see 8.1.2)
  31. Variable Names
     Counting variables are preferably called i, j, k, l, m, n when used in 'trivial' counting loops.
    (see 10.2 for an example on more intelligent naming for global counters etc.)
     Use Camel Casing (see 8.1.2)
  32. Method Names
     Name methods with verbs or verb phrases.
     Use Pascal Casing (see 8.1.2)
  33. Property Names
     Name properties using nouns or noun phrases
     Use Pascal Casing (see 8.1.2)
     Consider naming a property with the same name as it's type
  34. Event Names
     Name event handlers with the EventHandler suffix.
     Use two parameters named sender and e
     Use Pascal Casing (see 8.1.1 )
     Name event argument classes with the EventArgs suffix.
     Name event names that have a concept of pre and post using the present and past tense.
     Consider naming events using a verb.
  35. Capitalization summary
    Type Case Notes
    Class / Struct Pascal Casing
    Interface Pascal Casing Starts with I
    Enum values Pascal Casing
    Enum type Pascal Casing
    Events Pascal Casing
    Exception class Pascal Casing End with Exception
    public Fields Pascal Casing
    Methods Pascal Casing
    Namespace Pascal Casing
    Property Pascal Casing
    Protected/private Fields Camel Casing
    Parameters Camel Casing
  36. Visibility
    Do not make any instance or class variable public, make them private. For private members prefer not
    using "private" as modifier just do write nothing. Private is the default case and every C ♯ programmer
    should be aware of it.
    Use properties instead. You may use public static fields (or const) as an exception to this rule, but
    it should not be the rule.
  37. No 'magic' Numbers
    Don't use magic numbers, i.e. place constant numerical values directly into the source code. Replacing these
    later on in case of changes (say, your application can now handle 3540 users instead of the 427 hardcoded
    into your code in 50 lines scattered troughout your 25000 LOC) is error-prone and unproductive. Instead
    declare a const variable which contains the number :
    public class MyMath
    {
    public const double PI = 3.14159.. .
    }
  38. Brace placement example
    namespace ShowMeTheBracket
    {
    public enum Test {
    TestMe,
    TestYou
    }
    public class TestMeClass
    {
    Test test;
    public Test Test {
    get {
    return test;
    }
    set {
    test = value;
    }
    }
    void DoSomething()
    {
    if (test == Test.TestMe) {
    //...stuff gets done
    } else {
    //...other stuff gets done
    }
    }
    }
    }
    Brackets should begin on a new line only after:
    • Namespace declarations (note that this is new in version 0.3 and was different in 0.2)
    • Class/Interface/Struct declarations
    • Method declarations
  39. Variable naming example
    instead of :
    for (int i = 1; i < num; ++i) {
    meetsCriteria[i] = true;
    }
    for (int i = 2; i < num / 2; ++i) {
    int j = i + i;
    while (j <= num) {
    meetsCriteria[j] = false;
    j += i;
    }
    }
    for (int i = 0; i < num; ++i) {
    if (meetsCriteria[i]) {
    Console.WriteLine(i + " meets criteria");
    }
    }
    try intelligent naming :
    for (int primeCandidate = 1; primeCandidate < num; ++primeCandidate)
    {
    isPrime[primeCandidate] = true;
    }
    for (int factor = 2; factor < num / 2; ++factor) {
    int factorableNumber = factor + factor;
    while (factorableNumber <= num) {
    isPrime[factorableNumber] = false;
    factorableNumber += factor;
    }
    }
    for (int primeCandidate = 0; primeCandidate < num; ++primeCandidate)
    {
    if (isPrime[primeCandidate]) {
    Console.WriteLine(primeCandidate + " is prime.");
    }
    }
    Note: Indexer variables generally should be called i, j, k etc. But in cases like this, it
    may make sense to reconsider this rule. In general, when the same counters or indexers are
    reused, give them meaningful names.
  40. A


--
Happy day, happy life!

A conversion of the popular DotNetNuke web application to C#


REF: http://www.codeproject.com/aspnet/ASPNETnuke.asp

http://code.google.com/p/cs-dotnetnuke/
--
Happy day, happy life!

What's up with BeginInvoke?

REF :http://www.codeproject.com/csharp/begininvoke.asp

What does BeginInvoke do?

According to MSDN, Control.BeginInvoke "Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on". It basically takes a delegate and runs it on the thread that created the control on which you called BeginInvoke.

Message queue and Message pumping

  1. Every Windows application you create is provided with a thread on startup. It's this thread that calls the Main method of your application.
  2. For a console application, you can write Main to accept user input and process them.
  3. For a GUI application, things are radically different. GUI applications are event based, which means that there needs to be some entity to process and fire events. Windows manages this by creating a message queue for your application. All UI related actions get translated to messages that get posted to this message queue 1. Now, you need someone to read the messages from the queue and call appropriate event handlers. That's what a message pump is for. It basically is a loop that waits for someone to post a message to the queue. Once someone does, it dequeues it and calls the associated event handler.
  4. In .NET GUI applications, the Application.Run method takes care of message pumping.
  5. As an aside, modal dialogs (shown using Form.ShowDialog) have their own message pump whereas modeless dialogs (shown using Form.Show) don't. Which means that you can call Form.ShowDialog from any thread but Form.Show requires the calling thread to be running a message pump. Note that if you call Form.Show from a UI event handler, both the new form and the current form will be sharing the same message pump, which means that if one form is stuck executing one of the event handlers, the other one won't be usable too.

The One Rule

  1. One of the cardinal rules of Windows GUI programming is that only the thread that created a control can access and/or modify its contents (except for a few documented exceptions). Try doing it from any other thread and you'll get unpredictable behavior ranging from deadlock, to exceptions to a half updated UI. The right way then to update a control from another thread is to post an appropriate message to the application message queue. When the message pump gets around to executing that message, the control will get updated, on the same thread that created it (remember, the message pump runs on the main thread).
  2. There are two fundamental Win32 API calls to access and/or modify a control, SendMessage and PostMessage. There is a big difference in the way the two execute.
    1. The major difference is that SendMessage blocks the caller till the message gets processed by the message pump whereas PostMessage returns immediately.
    2. The subtle but important difference is that messages sent using SendMessage aren't queued in the message queue whereas PostMessage messages are.
  3. SendMessage messages are directly "sent" to the message pump. The message pump retrieves and processes messages sent using SendMessage before looking into those in the message queue.
  4. Effectively, there are then two queues, one for SendMessage messages and one for PostMessage messages (which is what we call the message queue). The message pump processes all messages in the first queue before starting with the second.
  5. An interesting observation is that if code does a SendMessage from within the message pumping thread, the window procedure gets called directly, that is, it doesn't go through the message pump.

Why The One Rule Exists

  1. In .NET, property/method calls on a Control object translate to SendMessage calls, so you can easily see how it can turn nasty. PostMessage posts a message to the queue and returns immediately, so there is no chance of deadlock.
  2. There is one other issue with using SendMessage that is not obvious at all. SendMessage, while blocking the current thread, continues to process messages that are sent to the message pump using SendMessage or one of the functions that send nonqueued[ ^] messages. This means that your code must be prepared to handle incoming messages when blocked on a SendMessage call.
  3. To avoid such problems, Windows provides the SendMessageTimeout API function, which when called with the right parameters, will prevent pumping of nonqueued messages when blocked on sending a message.
  4. However, all .NET UI controls use SendMessage, so you can't avoid the problem, unless you are planning on doing P/Invoke.

Why and when to call BeginInvoke

  1. BeginInvoke essentially does a PostMessage.
  2. Whenever you want to update a control from a thread that didn't create it, instead of directly calling the method/property to update it, you need to wrap it in a BeginInvoke call.
  3. According to MSDN: "There are four methods on a control that are safe to call from any thread: Invoke, BeginInvoke, EndInvoke, and CreateGraphics. For all other method calls, you should use one of the invoke methods to marshal the call to the control's thread".
  4. the Control class provides one property and two methods:
    • InvokeRequired: This bool property returns true if the thread on which this property is called is not the thread that created this control. Basically, if InvokeRequired returns true, you need to call one of the two Invoke methods.
    • BeginInvoke: This is a functionally similar to the PostMessage API function. It posts a message to the queue and returns immediately without waiting for the message to be processed. BeginInvoke returns an IAsyncResult, just like the BeginInvoke method on any delegate. And you can use IAsyncResult to wait for the message to be processed, just as usual. And you can call EndInvoke to get return values or out parameter values, as usual.
    • Invoke: This is like the SendMessage API function in that it waits till the message gets processed, but it does not do a SendMessage internally, it also does a PostMessage . The difference is that it waits till the delegate is executed on the UI thread before returning. So while there is a chance for the deadlock problem to occur, you can be sure that the other problems associated with SendMessage won't happen. Invoke returns the value that the function wrapped by the delegate returned.
  5.  The BCL provides a MethodInvoker delegate, which you can use if your wrapped function takes no parameters and returns void. You can also reuse the EventHandler delegate in case your wrapped function's signature matches it. The MSDN documentation says using these delegates instead of our own custom delegates will result in faster execution.
  6. Both BeginInvoke and Invoke check if they are called on the correct thread (the thread that created the control) and if so, directly update the control instead of doing the PostMessage thing. Apart from performance benefits, it also prevents deadlock if you call Invoke from within a method already running on the UI thread.

Invoke and BeginInvoke

  1. There are a few gotcha's with BeginInvoke though.
    • If the function you are calling via BeginInvoke accesses shared state (state shared between the UI thread and other threads), you are in trouble. The state might change between the time you called BeginInvoke and when the wrapped function actually executes, leading to hard to find timing problems.
    • If you are passing reference parameters to the function called via BeginInvoke, then you must make sure that no one else modifies the passed object before the function completes. Usually, people clone the object before passing it to BeginInvoke, which avoids the problem altogether.
  2. Note that the above points are valid for any function that you run as a thread. They're not so obvious when using BeginInvoke, because BeginInvoke doesn't actually create a thread and instead runs the wrapped function on an already existing thread (the UI thread). It still means that there are two threads, so you want to take the same care protecting your shared variables.

A warning

  1. Control.BeginInvoke, which is what we have been discussing so far, works slightly differently from Delegate.BeginInvoke.
  2. Delegate.BeginInvoke grabs a threadpool thread and executes the passed delegate on that thread.
  3. Control.BeginInvoke does not use a threadpool thread, it does a PostMessage to the target window handle and returns.
  4. This is crucial because if it uses threads, then there is no guarantee to the order in which messages are posted and processed by the application.
  5. Also, unlike Delegate.BeginInvoke, Control.BeginInvoke doesn't require every call to BeginInvoke to be matched by an EndInvoke. Of course, if you are using the return value of the method and/or out or ref values, then you need to call it anyway.




--
Happy day, happy life!

Thursday, May 24, 2007

Projects List

Cow Project( deleted)
http://code.google.com/p/cow-hybridization-information-management/

Cow management.
http://code.google.com/p/cow-management/
--
Happy day, happy life!

VS.NET addin for the Subversion version control system.

REF: http://ankhsvn.tigris.org/



AnkhSVN: A Subversion addin for Microsoft Visual Studio .NET

AnkhSVN is a Visual Studio .NET addin for the Subversion version control system. It allows you to perform the most common version control operations directly from inside the VS.NET IDE. Not all the functionality provided by SVN is (yet) supported, but the majority of operations that support the daily workflow are implemented.

Take a look at some screenshots here.

Progress on the AnkhSVN project is tracked by the CIA.

If you run into problems with Ankh, try either the Users mailing list or join us in the #ankhsvn channel on the irc.freenode.net IRC network.



--
Happy day, happy life!

Subversion link page

REF: http://subversion.tigris.org/links.html#clients

Books

Clients and plugins

Subversion Language bindings

Repository converters

  • cvs2svn - CVS to Subversion conversion
    cvs2svn has become its own project now, look at:
    http://cvs2svn.tigris.org/

  • p42svn - Perforce to Subversion conversion
    A Perl script which converts a Perforce depot to a Subversion repository
    http://p42svn.tigris.org/

  • rcs2svn - RCS to Subversion conversion
    A Perl script which converts RCS repositories to a Subversion repository
    http://www.coelho.net/rcs2svn.html

  • sccs2svn.py - SCCS to Subversion conversion
    A Python script which converts SCCS repositories to a Subversion repository
    http://sccs2svn.berlios.de/

  • svn-dump2dir and svn-dir2dump - Convert back and forth between a subversion dump file and a subversion dump directory.
    A "dump directory" is isomorphic to a dump file but all of the fields have been exploded out into their own files so that the field length counts are implicit. It is straightforward to hack on or patch the history a subversion repository when in this dump directory form. Also includes a reimplementation of patch that is more helpful when files are missing, as occurs in the incremental dump form. A precise grammar for the subversion dump file format is also provided.
    http://www.cubewano.org/blacktackle

  • SVN Importer - Migrate to SVN from MKS, VSS, ClearCase, Star Team, PVCS, CVS
    http://www.polarion.org/index.php?page=overview&project=svnimporter

  • Tailor - a tool to migrate changesets between ArX, Bazaar, Bazaar-NG, CVS, Codeville, Darcs, Git, Mercurial, Monotone, Subversion and Tla repositories. Supports incremental conversion.
    http://www.darcs.net/DarcsWiki/Tailor

  • vss2svn - Microsoft Visual Source Safe (VSS) to Subversion
    http://www.pumacode.org/projects/vss2svn

Community sites

  • Subversionary - A SubWiki-based site for the promotion of Subversion and for collecting information on how to configure and use Subversion.
    http://www.subversionary.org/

  • SVNForum - A Subversion community help and discussion forum for exchanging information and tips with other Subversion users.
    http://svnforum.org/

  • Subversion Wiki - A Mediawiki-based Wiki for best-practices, configuration and usage of Subversion and related tools.
    http://www.orcaware.com/svn/wiki/

  • openCollabNet - Contains downloads (such as Subversion compiled and tested by CollabNet), technical content, training and ways to interact with CollabNet's Subversion engineers (via forums or the Submerged blog). Become a member and get more, such as a free online Subversion training class.
    http://open.collab.net/

Sites that Offer Subversion Hosting

  • berlios.de: free hosting for open-source projects
    http://www.berlios.de/

    "The goal of BerliOS is to provide support for different interest groups in the area of Open Source Software (OSS). Our aim is to fulfil a neutral mediator function. The target groups of BerliOS are on one hand the developers and users of Open Source Software and on the other hand commercial manufacturers of OSS operating systems and applications as well as support companies."

  • ObjectWeb: open source middleware
    http://www.objectweb.org/

    "ObjectWeb is an international consortium fostering the development of open-source middleware for cutting-edge applications: EAI, e-business, clustering, grid computing, managed services and more." Their hosting software is GForge, with integrated Subversion support. See http://www.objectweb.org/phorum/read.php?f=49&i=37&t=37 for details.

  • CollabNet: commercial software development collaboration platform, with Subversion integration
    http://www.collab.net/subversion/

    "CollabNet Enterprise Edition (CEE) delivers a complete software development and collaboration platform, offered as a managed service, with full Subversion integration. CollabNet also offers Subversion On Demand, a hosted Subversion development environment, and Subversion support and training."

  • CVSDude: free and commercial Subversion hosting
    http://cvsdude.com/

    "CVSDude is a free CVS server and Subversion server. We provide cvs hosting and Subversion hosting for software developers, software teams, graphic artists, project managers and the like. You can use your favourite software client to access our CVS and Subversion servers. Our basic or 'free' service is limited but we do offer commercial upgrades..."

  • SourceHosting.net: commercial Subversion hosting
    http://www.sourcehosting.net/

    "SourceHosting.net provides fully-managed Subversion hosting, as well as Bugzilla and CVS hosting packages. Hourly, secure offsite backups are included in all of our hosting plans, and add-on tools such as WebSVN and CVSweb are available as well."

  • wush.net: commercial Subversion hosting
    http://www.wush.net/

    "We provide professional quality Subversion hosting for individuals and small businesses. Our plans include a suite of integrated software designed to complement Subversion."

  • hosted-projects.com: commercial Subversion hosting
    http://www.hosted-projects.com/

    "svn-hosting.com provides professional Subversion hosting. We offer everything from small repositories to dedicated Subversion servers to provide you a stable backend for your critical work."

  • ProjectLocker: commercial Subversion hosting
    http://www.projectlocker.com/

    "ProjectLocker offers professional Subversion hosting, as well as additional development process, project management, and collaboration tools."

  • Gna!: free hosting for Projects under a GPL-compatible license
    https://gna.org/index.php

    "Gna! project [is] a central point for development, distribution and maintenance of Libre Software (Free Software) projects."

  • OpenSVN.csie.org: appears to be a free Subversion hosting site, with Trac service available too.
    https://opensvn.csie.org

    [We couldn't find a good description on the site. If you find one, let us know.]

  • http://www.projxpert.com/: professional software project hosting site
    http://www.projxpert.com/

  • DevGuard.com: commercial Subversion hosting
    http://www.devguard.com/

    "DevGuard.com offers commercial Subversion hosting for individuals and small businesses. Secure, encrypted data transfer, fast network access, easy to use web admin interface."

  • AVLUX Solutions: commercial Subversion hosting
    http://www.avlux.net/

    "full-service" web hosting, including (among other things) Subversion repositories and WebSVN.

  • GeekISP: commercial Subversion hosting
    http://www.geekisp.com/

    "GeekISP includes CVS and SVN repositories with all accounts."

  • TextDrive: commercial Subversion hosting
    http://textdrive.com/

    Repository hosting services, from shared hosting to fully managed dedicated server clusters.

  • Labyrinth Data Services: commercial Subversion hosting
    http://www.labyrinthdata.net.au/

    Australian-based Linux shell accounts and web hosting; unlimited Subversion repositories with all accounts.

  • SourceForge.net: no-charge hosting for open-source projects
    http://sourceforge.net/

    Probably the largest open source project hosting site on the Net.

  • hosted-projects.com: commercial Subversion hosting
    http://www.hosted-projects.com

    hosted-projects.com is a company specialized in web hosting services for software project teams offering the Subversion revision control system coupled with project and issue management software like Trac and Bugzilla.

  • google.com: free Subversion hosting for open source projects
    http://code.google.com/hosting/

    "Our new hosting service offers a collaborative development environment that includes: project workspaces with simple membership controls; version control via Subversion; issue tracking; mailing lists at groups.google.com."

  • myVersionControl.com: Subversion Hosting and Project Management
    http://www.myversioncontrol.com/

    Commercial Subversion hosting, integrated with other project management services.

  • Versionshelf.com: commercial Subversion hosting with free service for students and teachers
    http://www.versionshelf.com/

    Versionshelf has a streamlined webinterface to configure and access repositories, users, ACLs, rss feeds, external commit triggers, backups... easily. Access is always secured through 128-bit SSL data encryption.

  • Assembla: "... free workspaces with unlimited team size and integrated tools like wiki, discussion, alerts, Subversion and Trac."
    http://www.assembla.com/

Higher-level tools that use Subversion

Repository browsing tools

Miscellaneous Utilities

Miscellaneous Resources

Articles and Reviews



--
Happy day, happy life!

Wednesday, May 23, 2007

How to convert between string and byte array in c#?

 internal class EncryptionController
    {
        public static string Encrypt(string data)
        {
            try
            {
                byte[] bytes = Encoding.Unicode.GetBytes(data);
                return Convert.ToBase64String(bytes);
            }
            catch (Exception ex)
            {
                Exceptions.LogException( new Exception(string.Format("To encrpt the '{0}' data is failed!",data)));
                return null;
            }
        }
      
        public static string Decrypt(string encryptedData)
        {
            try
            {
                byte[] bytes = Convert.FromBase64String (encryptedData);
                return Encoding.Unicode.GetString(bytes);               
            }
            catch (Exception ex)
            {
                Exceptions.LogException(new Exception( string.Format("To dencrpt the '{0}' data is failed!", encryptedData)));
                return null;
            }
           
        }

    }

--
Happy day, happy life!

REF:Keep Your Data Secure with the New Advanced Encryption Standard

REF: http://msdn.microsoft.com/msdnmag/issues/03/11/AES/

Keep Your Data Secure with the New Advanced Encryption Standard


This article assumes you're familiar with C# and bit manipulation
Level of Difficulty 1 2 3
Download Image Get the sample code for this article.

SUMMARY

The Advanced Encryption Standard (AES) is a National Institute of Standards and Technology specification for the encryption of electronic data. It is expected to become the accepted means of encrypting digital information, including financial, telecommunications, and government data. This article presents an overview of AES and explains the algorithms it uses. Included is a complete C# implementation and examples of encrypting .NET data. After reading this article you will be able to encrypt data using AES, test AES-based software, and use AES encryption in your systems.


Contents


T
he National Institute of Standards and Technology (NIST) established the new Advanced Encryption Standard (AES) specification on May 26, 2002. In this article I will provide a working implementation of AES written in C#, and a complete explanation of exactly what AES is and how the code works. I'll show you how to encrypt data using AES and extend the code given here to develop a commercial-quality AES class. I'll also explain how and why to incorporate AES encryption into your software systems, and how to test AES-based software.

Note that the code presented in this article and any other implementation based on this article is subject to applicable Federal cryptographic module export controls (see Commercial Encryption Export Controls for the exact regulations).

AES is a new cryptographic algorithm that can be used to protect electronic data. Specifically, AES is an iterative, symmetric-key block cipher that can use keys of 128, 192, and 256 bits, and encrypts and decrypts data in blocks of 128 bits (16 bytes). Unlike public-key ciphers, which use a pair of keys, symmetric-key ciphers use the same key to encrypt and decrypt data. Encrypted data returned by block ciphers have the same number of bits that the input data had. Iterative ciphers use a loop structure that repeatedly performs permutations and substitutions of the input data. Figure 1 shows AES in action encrypting and then decrypting a 16-byte block of data using a 192-bit key.

Figure 1 Some Data
Figure 1 Some Data

AES is the successor to the older Data Encryption Standard (DES). DES was approved as a Federal standard in 1977 and remained viable until 1998 when a combination of advances in hardware, software, and cryptanalysis theory allowed a DES-encrypted message to be decrypted in 56 hours. Since that time numerous other successful attacks on DES-encrypted data have been made and DES is now considered past its useful lifetime.

In late 1999, the Rijndael (pronounced "rain doll") algorithm, created by researchers Joan Daemen and Vincent Rijmen, was selected by the NIST as the proposal that best met the design criteria of security, implementation efficiency, versatility, and simplicity. Although the terms AES and Rijndael are sometimes used interchangeably, they are distinct. AES is widely expected to become the de facto standard for encrypting all forms of electronic data including data used in commercial applications such as banking and financial transactions, telecommunications, and private and Federal information.


Overview of the AES Algorithm

The AES algorithm is based on permutations and substitutions. Permutations are rearrangements of data, and substitutions replace one unit of data with another. AES performs permutations and substitutions using several different techniques. To illustrate these techniques, let's walk through a concrete example of AES encryption using the data shown in Figure 1.

The following is the 128-bit value that you will encrypt with the indexes array:

00 11 22 33 44 55 66  77 88 99 aa bb cc dd ee ff
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
The 192-bit key value is:
00 01 02 03 04 05 06  07 08 09 0a 0b 0c 0d 0e 0f  10 11 12 13 14 15 16 17
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Figure 2 Sbox
Figure 2 Sbox

When the AES constructor is called, two tables that will be used by the encryption method are initialized. The first table is a substitution box named Sbox. It is a 16 × 16 matrix. The first five rows and columns of Sbox are shown in Figure 2. Behind the scenes, the encryption routine takes the key array and uses it to generate a "key schedule" table named w[], shown in Figure 3.

Figure 3 Key Sched.
Figure 3 Key Sched.

The first Nk (6) rows of w[] are seeded with the original key value (0x00 through 0x17) and the remaining rows are generated from the seed key. The variable Nk represents the size of the seed key in 32-bit words. You'll see exactly how w[] is generated later when I examine the AES implementation. The point is that there are now many keys to use instead of just one. These new keys are called the round keys to distinguish them from the original seed key.

Figure 4 State
Figure 4 State

The AES encryption routine begins by copying the 16-byte input array into a 4×4 byte matrix named State (see Figure 4 ). The AES encryption algorithm is named Cipher and operates on State[] and can be described in pseudocode (see Figure 5).

The encryption algorithm performs a preliminary processing step that's called AddRoundKey in the specification. AddRoundKey performs a byte-by-byte XOR operation on the State matrix using the first four rows of the key schedule, and XORs input State[r,c] with round keys table w[c,r].

For example, if the first row of the State matrix holds the bytes { 00, 44, 88, cc }, and the first column of the key schedule is { 00, 04, 08, 0c }, then the new value of State[0,2] is the result of XORing State[0,2] (0x88) with w[2,0] (0x08), or 0x80:

1 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0 XOR

1 0 0 0 0 0 0 0

The main loop of the AES encryption algorithm performs four different operations on the State matrix, called SubBytes, ShiftRows, MixColumns, and AddRoundKey in the specification. The AddRoundKey operation is the same as the preliminary AddRoundKey except that each time AddRoundKey is called, the next four rows of the key schedule are used. The SubBytes routine is a substitution operation that takes each byte in the State matrix and substitutes a new byte determined by the Sbox table. For example, if the value of State[0,1] is 0x40 and you want to find its substitute, you take the value at State[0,1] (0x40) and let x equal the left digit (4) and y equal the right digit (0). Then you use x and y as indexes into the Sbox table to find the substitution value, as shown in Figure 2.

ShiftRows is a permutation operation that rotates bytes in the State matrix to the left. Figure 6 shows how ShiftRows works on State[]. Row 0 of State is rotated 0 positions to the left, row 1 is rotated 1 position left, row 2 is rotated 2 positions left, and row 3 is rotated 3 positions left.

Figure 6 Running ShiftRows on State
Figure 6 Running ShiftRows on State

The MixColumns operation is a substitution operation that is the trickiest part of the AES algorithm to understand. It replaces each byte with the result of mathematical field additions and multiplications of values in the byte's column. I will explain the details of special field addition and multiplication in the next section.

Suppose the value at State[0,1] is 0x09, and the other values in column 1 are 0x60, 0xe1, and 0x04; then the new value for State[0,1] is shown in the following:

State[0,1] = (State[0,1] * 0x01) + 
(State[1,1] * 0x02) +
(State[2,1] * 0x03) +
(State[3,1] * 0x01)

= (0x09 * 0x01) + (0x60 * 0x02) + (0xe1 * 0x03) +
(0x04 * 0x01)

= 0x57
The addition and multiplication are special mathematical field operations, not the usual addition and multiplication on integers.

The four operations SubBytes, ShiftRows, MixColumns, and AddRoundKey are called inside a loop that executes Nr times—the number of rounds for a given key size, less 1. The number of rounds that the encryption algorithm uses is either 10, 12, or 14 and depends on whether the seed key size is 128, 192, or 256 bits. In this example, because Nr equals 12, the four operations are called 11 times. After this iteration completes, the encryption algorithm finishes by calling SubBytes, ShiftRows, and AddRoundKey before copying the State matrix to the output parameter.

In summary, there are four operations that are at the heart of the AES encryption algorithm. AddRoundKey substitutes groups of 4 bytes using round keys generated from the seed key value. SubBytes substitutes individual bytes using a substitution table. ShiftRows permutes groups of 4 bytes by rotating 4-byte rows. MixColumns substitutes bytes using a combination of both field addition and multiplication.


Field Addition and Multiplication in GF(28)

As you've seen, the AES encryption algorithm uses fairly straightforward techniques for substitution and permutation, except for the MixColumns routine. The MixColumns routine uses special addition and multiplication. The addition and multiplication used by AES are based on mathematical field theory. In particular, AES is based on a field called GF(28).

The GF(28) field consists of a set of 256 values from 0x00 to 0xff, plus addition and multiplication, hence the (28 ). GF stands for Galois Field, named after the mathematician who founded field theory. One of the characteristics of GF(28) is that the result of an addition or multiplication operation must be in the set {0x00 ... 0xff}. Although the theory of fields is rather deep, the net result for GF(28) addition is simple: GF(28) addition is just the XOR operation.

Multiplication in GF(28) is trickier, however. As you'll see later in the C# implementation, the AES encryption and decryption routines need to know how to multiply by only the seven constants 0x01, 0x02, 0x03, 0x09, 0x0b, 0x0d, and 0x0e. So instead of explaining GF(28) multiplication theory in general, I will explain it just for these seven specific cases.

Multiplication by 0x01 in GF(28) is special; it corresponds to multiplication by 1 in normal arithmetic and works the same way—any value times 0x01 equals itself.

Now let's look at multiplication by 0x02. As in the case of addition, the theory is deep, but the net result is fairly simple. If the value being multiplied is less than 0x80, then the result of multiplication is just the value left-shifted 1 bit position. If the value being multiplied is greater than or equal to 0x80, then the result of multiplication is the value left-shifted 1 bit position XORed with the value 0x1b. This prevents "field overflow" and keeps the product of the multiplication in range.

Once you've established addition and multiplication by 0x02 in GF(28), you can use them to define multiplication by any constant. To multiply by 0x03 in GF(2 8), you can decompose 0x03 as powers of 2 and additions. To multiply an arbitrary byte b by 0x03, observe that 0x03 = 0x02 + 0x01. Thus:

b * 0x03 = b * (0x02 + 0x01)
= (b * 0x02) + (b * 0x01)
This can be done because you know how to multiply by 0x02 and 0x01 and how to perform addition. Similarly, to multiply an arbitrary byte b by 0x0d, you do this:
b * 0x0d = b * (0x08 + 0x04 + 0x01)
= (b * 0x08) + (b * 0x04) + (b * 0x01)
= (b * 0x02 * 0x02 * 0x02) + (b * 0x02 * 0x02) + (b * 0x01)

The other multiplications needed for the AES MixColumns routine in the encryption and decryption algorithm follow the same general pattern, as shown here:

b * 0x09 = b * (0x08 + 0x01)
= (b * 0x02 * 0x02 * 0x02) + (b * 0x01)

b * 0x0b = b * (0x08 + 0x02 + 0x01)
= (b * 0x02 * 0x02 * 0x02) + (b * 0x02) + (b * 0x01)

b * 0x0e = b * (0x08 + 0x04 + 0x02)
= (b * 0x02 * 0x02 * 0x02) + (b * 0x02 * 0x02) + (b * 0x02)

To summarize, addition in GF(28) is the XOR operation. Multiplication in GF(2 8) reduces to additions and multiplications by 0x02, where multiplication by 0x02 is a conditional 1-bit left shift. The AES specification contains a lot of additional information about operations in GF(28).


Key Expansion

The AES encryption and decryption algorithms use a key schedule generated from the seed key array of bytes. The AES specification refers to this as the KeyExpansion routine. Generating, in essence, multiple keys from an initial key instead of using a single key greatly increases the diffusion of bits. Although not overwhelmingly difficult, understanding KeyExpansion is one of the trickier parts of the AES algorithm. In high-level pseudocode, the KeyExpansion routine looks like the following:

KeyExpansion(byte[] key, byte[][4] w)
{
copy the seed key into the first rows of w

for each remaining row of w
{
use two of the previous rows to create a new row
}
}

The "use two of the previous rows to create a new row" routine makes use of two subroutines, RotWord and SubWord, and a table of constants named Rcon (for "round constants"). Let's look at each of these three items and then come back to the KeyExpansion routine as a whole.

The RotWord routine is simple. It accepts an array of 4 bytes and rotates them 1 position left. Because the round schedule table w[] has four columns, RotWord rotates a row of w[] to the left. Notice that the RotWord function used by KeyExpansion is very similar to the ShiftRows routine used by the encryption algorithm except that it works on a single row of the key schedule w[] instead of the entire encryption state table State[].

The SubWord routine performs a byte-by-byte substitution on a given row of the key schedule table w[] using the substitution table Sbox. The substitutions in KeyExpansion operate exactly like those in the encryption algorithm. The input byte to be substituted is separated into an (x,y) pair which are used as indexes into the substitution table Sbox. For example, substitution for 0x27 results in x = 2 and y = 7, and Sbox[2,7] returns 0xcc.

The KeyExpansion routine uses an array Rcon[], called the round constant table. These constants are 4 bytes each to match with a row of the key schedule table. The AES KeyExpansion routine requires 11 round constants. You can see these constants listed in Figure 7.

The leftmost byte of each round constant is a power of 2 in the GF(28) field. Another way of looking at it is to observe that each value is the previous value times 0x02, as described in the previous section discussing multiplication in GF(28). Notice that 0x80 × 0x02 = 0x1b is 0x80 left-shifted 1 bit followed by an XOR with 0x1b, as described earlier.

Now let's take a closer look at the loop inside KeyExpansion. In more detailed pseudocode than before, the loop is:

for (row = Nk; row < (4 * Nr+1); ++row)
{
temp = w[row-1]

if (row % Nk == 0)
temp = SubWord(RotWord(temp)) xor Rcon[row/Nk]
else if (Nk == 8 and row % Nk == 4)
temp = SubWord(temp)

w[row] = w[row-Nk] xor temp
}

Ignoring the if clause for a moment, you'll see that each row of the key schedule table w[] is the result of XORing the previous row with the row Nk (4, 6, or 8 depending on the key size) rows before. The first part of the if conditional modifies every fourth, sixth, or eighth row of the key schedule with SubWord, RotWord, and XORing with a round constant, depending on whether the key size is 128, 192, or 256 bits. The second part of the conditional will modify rows 12, 20, 28 and so on—every eighth row—for a 256-bit key to add additional variability to the key schedule.

Let's see how KeyExpansion gets started with the example presented at the beginning of this article. The seed key is the 192-bit / 6-word value:

00 01 02 03 04 05 06  07 08 09 0a 0b 0c 0d 0e 0f  10 11 12 13 14 15 16 17

The key schedule byte table w[] has the dimensions 4 columns and Nb × (Nr + 1) equals 4 × (12 + 1), or 52 rows. The KeyExpansion routine copies the values in the seed key into the first rows of the key schedule byte table w[]. Because my seed key is 192 bits (24 bytes), and the w[] table always has 4 columns, in this case KeyExapansion copies the seed key into the first 6 rows of w[]. Now let's see how the KeyExpansion routine fills the rest of the key schedule table. In my example, the first calculated row is row 6 because rows 0 to 5 were filled with the seed key values:

temp = w[row-1] = 14 15 16 17 
The condition (row % Nk == 0) is true, so first the RotWord subroutine is applied:
temp = 15 16 17 14 
Then SubWord is applied:
temp = 59 47 f0 fa
Then XORed with Rcon[row / Nk] = Rcon[6 / 6] = 01 00 00 00 :
temp = 58 47 f0 fa
This is then XORed with w[row-Nk] = w[6-6] = 00 01 02 03 , yielding the following result:
w[6] = 58 46 f2 f9
The process repeats itself for all of the remaining rows in key schedule table w[].

To summarize, an important part of AES encryption and decryption is the generation of multiple round keys from the initial seed key. This KeyExpansion algorithm generates a key schedule and uses substitution and permutation in a way that is similar in most respects to the encryption and decryption algorithms.


The AES Class Constructor in C#

Now that I've examined all the components of the AES encryption algorithm, I'll implement it in C#. The official specification of the AES algorithm is contained in Federal Information Processing Standards Publication 197. I decided to base my implementation on it as closely as possible, but I quickly discovered that the specification was more of a theory document than an implementation guide. To exploit the official specification as a resource, I have used the same variable names as those used in the standards publication (even when they are rather cryptic like "Nr" and "w").

My design uses the nine data members and one enumeration type as shown here:

public enum KeySize { Bits128, Bits192, 
Bits256 };

private int Nb;
private int Nk;
private int Nr;

private byte[] key;
private byte[,] Sbox;
private byte[,] iSbox;
private byte[,] w;
private byte[,] Rcon;
private byte[,] State;
Because the key size can only be 128, 192, or 256 bits, it is a great candidate for an enumerated type:
public enum KeySize { Bits128, Bits192, Bits256 };

The specification document generally uses bytes as its basic storage unit but uses 4-byte words as the size for two important data members. The two members Nb and Nk represent the block size in words and key size in words, respectively. Nr represents the number of rounds. The block size is always 16 bytes (or 128 bits, which is 4 words for AES), so it could have been declared as a constant. The key size is assigned a value of 4, 6, or 8 according to the value of the enumeration parameter KeySize. The AES algorithm iterates through a number of rounds to increase the complexity of the encrypted data. The number of rounds is either 10, 12, or 14 and is based on cryptanalysis theory. It depends directly on the key size.

When designing a class interface, I like to work backwards. I imagine calling the constructor and methods from an application. Using this approach, I decided that I wanted to instantiate an AES object like the following:

Aes a = new Aes(the key size, the seed key)
I called the encryption and decryption routines as follows:
a.Cipher(plainText, cipherText);
a.InvCipher(cipherText, decipheredText);

I chose the slightly awkward method names Cipher and InvCipher because they are used in the AES specification document. Here is the code for the AES class constructor:

public Aes(KeySize keySize, byte[] keyBytes)
{
SetNbNkNr(keySize);

this.key = new byte[this.Nk * 4];
keyBytes.CopyTo(this.key, 0);

BuildSbox();
BuildInvSbox();
BuildRcon();
KeyExpansion();

}

The constructor first set the values of Nb, Nk, and Nr by calling a helper method SetNbNkNr, which is shown in Figure 8. If efficiency is a concern, you could put this code directly in the constructor to avoid the overhead of a method call.

Next, you have to copy the bytes that are passed into the constructor into the class field variable. The key is declared with the other class fields and it gets its value by doing this:

this.key = new byte[this.Nk * 4];  
keyBytes.CopyTo(this.key, 0);
I decided to call the initialization of the substitution tables Sbox[] and iSbox[] using the private helper methods BuildSbox and BuildInvSbox in the constructor. Now Sbox[] and iSbox[] are required by the key expansion routine and the Cipher and InvCipher methods, respectively, so I could have put initialization of Sbox[] and invocation of the KeyExpansion method in both the Cipher and the InvCipher methods, but putting them in the constructor results in a cleaner code structure. sBox[] gets populated in Figure 9. The code that populates iSbox[] is similar. The code is structured for readability. As you'll see later, there is a surprising alternative to this way of supplying values for the Sbox and iSbox tables.

Declaring the key schedule table w[], the round constants table Rcon[] and the state matrix State[] in the constructor, and assigning values to Rcon[] and w[] with private helper methods seems to me to be the best way to organize them, but that is mostly a matter of style. The code that populates the round constant table Rcon is shown in Figure 7.

Recall that the left byte of each row of Rcon[] is a power of 2 in GF(28) so this table could be built computationally using something like the following:

newVal = prevVal * 0x02;
The AES constructor finishes by building the key schedule table w[] which is done in the KeyExpansion method (see Figure 10). The code is fairly straightforward. The specification document uses a hypothetical 4-byte word data type. Since C# has no such type, it is simulated with an array of 4 bytes. After the key schedule w[] is allocated space using the operator new, the first Nk (4, 6, or 8) rows of w[] get values from the seed key[] array that was passed into the constructor:
this.w[row,0] = this.key[4*row];
this.w[row,1] = this.key[4*row+1];
this.w[row,2] = this.key[4*row+2];
this.w[row,3] = this.key[4*row+3];

The operation of XORing 2 bytes together happens a lot in this code. It requires some casting from byte to int and back to byte because the XOR operator ^ is not defined on the C# byte type. For example

temp[0] = (byte)( (int)temp[0] ^ (int)this.Rcon[row/Nk,0] );
is used instead of:
temp[0] = temp[0] ^ this.Rcon[row/Nk,0];

The KeyExpansion method conditionally calls the private methods SubWord and RotWord to maintain naming consistency with the specification. Again, because there is no word type in C#, I implemented one using an array of 4 bytes. The code for SubWord and RotWord is fairly simple and you should be able to understand it easily by examining it in the AesLib source code that accompanies this article.

The slightly tricky part is looking up the substitution values in SubWord. Recall that to find the substitute value, you separate the input byte into its leftmost 4 bits and its rightmost 4 bits. For a given byte, right-shifting 4 bits with the >> operator will yield the x index, and logical ANDing with 0000 1111 will yield the y value. In slightly longer, but more readable form than the actual code, I could have done something like the following

int x = word[0] >> 4;
int y = word[0] & 0x0f;
byte substitute = this.Sbox[x,y];
result[0] = substitute;
instead of the code I used:
result[0] = this.Sbox[ word[0] >> 4, word[0] & 0x0f ];

To summarize, the AES constructor accepts a key size of 128, 192, or 256 bits and a byte array seed key value. The constructor assigns values for the input block size, the seed key size, and the number of rounds for the encryption algorithm and copies the seed key to a data member named key. The constructor also builds four tables: two substitution tables used by the encryption and decryption methods, a table of round constants, and a key schedule of round keys.


The AES Cipher Method in C#

The code for the Cipher method is shown in Figure 11. It is really very simple because it mostly farms out the work to the private methods AddRoundKey, SubBytes, ShiftRows, and MixColumns.

The Cipher method starts by copying the plaintext input array to the state matrix State[]. After an initial call to AddRoundKey, the Cipher method iterates one time fewer than the total number of rounds. On the last round, the call to MixColumns is omitted as described in the specification.

The code for the AddRoundKey and SubBytes private methods is shown in Figure 12. The AddRoundKey method needs to know what round it is at so that it can reference the correct four rows of the key schedule array w[]. Notice that State[r,c] is XORed with w[c,r] and not w[r,c]. The SubBytes method extracts indexes from the input byte using the same right-shift-4-bits and mask-with-0x0f technique used in the KeyExpansion method.

The code for the ShiftRows method is shown in Figure 13. Recall that ShiftRows (which might have been better named RotateRows) rotates row[0] 0 positions to the left, row[1] 1 position to the left, and so forth.

After copying State[] into a temp[] matrix, the shifts are then performed with:

this.State[r, (c + r) % Nb ] = temp[r,c];
This takes advantage of the % operator to wrap around a row.

The MixColumns method (see Figure 14) takes every byte and substitutes it with a linear combination of all the other values in the byte's column using GF(28) addition and multiplication. The constant coefficients used for multiplication are based on field theory and are either 0x01, 0x02, or 0x03. The substitution for a given column c is:

State[0,c] = 0x02 * State[0,c] + 0x03 * State[1,c] + 0x01 * State[2,c] +
0x01 * State[3,c]
State[1,c] = 0x01 * State[0,c] + 0x02 * State[1,c] + 0x03 * State[2,c] +
0x01 * State[3,c]
State[2,c] = 0x01 * State[0,c] + 0x01 * State[1,c] + 0x02 * State[2,c] +
0x03 * State[3,c]
State[3,c] = 0x03 * State[0,c] + 0x01 * State[1,c] + 0x01 * State[2,c] +
0x02 * State[3,c]

These expressions are a bit long already so I decided to write private helper functions that return the product of GF(2 8) multiplication by 0x01, 0x02, and 0x03. The helper functions are very short. For example, the code that's used to field-multiply a byte b by 0x03 is as follows:

return (byte) ( (int)gfmultby02(b) ^ (int)b ); 

As I discussed earlier, multiplication by 0x02 is the essential operation for all GF(28) multiplication. I called my gfmultby02 method, bending my convention of using the same method names that have been used in the specification; the specification calls this routine xtime.

The Cipher method iteratively applies four operations on its input to produce encrypted output. AddRoundKey substitutes bytes using multiple round keys derived from the single original seed key. SubBytes substitutes bytes using values in a substitution table. ShiftRows permutes bytes by shifting rows of bytes, and MixColumns substitutes bytes using field addition and multiplication of values in a column.


The AES InvCipher Method in C#

The basic premise behind the AES decipher algorithm is simple: to decrypt an encrypted block, just undo every operation in the reverse order. Although this is the basic concept, there are a few details to handle.

The AES specification names the decipher routine InvCipher rather than alternatives Decipher or Decrypt. This is a reflection of the mathematics behind AES, which are based in terms of inverse mathematical operations.

If you compare this code with the Cipher code, you will see that it is pretty much what you might expect, but with two exceptions. First, the order of the inverse method calls (like InvSubBytes) in the InvCipher method is not exactly the reverse of the corresponding calls (like SubBytes) in the Cipher method, and second, InvCipher calls the AddRoundKey method instead of an InvAddRoundKey method. Notice that the InvCipher algorithm uses the key schedule table but starts at the higher-numbered indexes and works its way down to row 0.

The code for the InvSubBytes, InvShiftRows, and InvMixColumns methods closely mirrors the code for the related SubBytes, ShiftRows, and MixColumns methods. The InvSubBytes method is just like the SubBytes method except that it uses the inverse substitution table iSbox[] instead of the Sbox[] table.

As you might guess, iSbox[] just undoes any mapping performed by Sbox[]. For example, if you have byte b that equals 0x20 and find its substitution value in Sbox[], you get 0xb7. If you look up the substitution value for 0xb7 in iSbox[], you get 0x20.

Similarly the InvShiftRows method undoes the ShiftRows method—row[0] is shifted 0 positions to the right, row[1] is shifted 1 position right, row[2] is shifted 2 positions right, and row[3] is shifted 3 positions right.

The InvMixColumns method undoes the work of MixColumns, but not in an obvious way. Recall that MixColumns replaces each byte in the state matrix with a linear combination of bytes in the original byte's column and that the coefficients were 0x01, 0x02, and 0x03. Once again, field theory comes into play. It turns out that the inverse operation is similar but uses multiplication by 0x09, 0x0b, 0x0d, and 0x0e like this:

State[0,c] = 0x0e * State[0,c] + 0x0b * State[1,c] + 0x0d * State[2,c] +
0x09 * State[3,c]
State[1,c] = 0x09 * State[0,c] + 0x0e * State[1,c] + 0x0b * State[2,c] +
0x0d * State[3,c]
State[2,c] = 0x0d * State[0,c] + 0x09 * State[1,c] + 0x0e * State[2,c] +
0x0b * State[3,c]
State[3,c] = 0x0b * State[0,c] + 0x0d * State[1,c] + 0x09 * State[2,c] +
0x0e * State[3,c]

As with the MixColumns method, I decided to write dedicated helper functions rather than expand the already long expressions inline or write a general multiplication helper function. Let me show you how I wrote the function that multiplies any byte, b, by the constant 0x0e (14 in base 10). The number 14, like any number, can be expressed as the sum of powers of 2. In this case, 14 equals 2 + 4 + 8. And since 4 equals 2 squared and 8 equals 2 cubed, you can express 14 as 2 + 22 + 23. Remember that addition is just XOR (^) in GF(28) and since I already have the gfmultby02 function, I can use it to get my result:

return (byte)( (int)gfmultby02(gfmultby02(gfmultby02(b))) ^  /* 23 + */
(int)gfmultby02(gfmultby02(b)) ^ /* 22 + */
(int)gfmultby02(b) ); /* 2 */

All of the operations used by the AES encryption algorithm are invertible, so the decryption algorithm essentially reverses all the operations performed by encryption.


Using the AES Class

One of the features of AES as implemented in C# is its simplicity. Consider the code in Figure 15 that I used to generate the output shown in Figure 1. After declaring hardcoded values for the 16-byte plaintext input and the 24-byte (192-bit) seed key, an AES object is initialized, the encrypting Cipher method encrypts the plaintext to cipher text, and then the cipher text is decrypted back using InvCipher. Very clean and simple.

Because an AES object works on byte arrays, you can easily adapt it to work on other .NET data types. I constructed a little Windows®-based demo app that accepts a single 8-character (16-byte) string and then encrypts and decrypts it. A sample run is shown in Figure 16.

Figure 16 Encryption Demo
Figure 16 Encryption Demo

Because both the encryption and decryption routines need to know what key size the user has specified, I declared it as a class-scope variable, like this:

private Aes.KeySize keysize;  
Notice that the seed key is not specified by the user. The demo uses a "null key" which consists of all zero bytes by supplying a dummy new byte[16] to the constructor. The size of the dummy argument is irrelevant because the seed key will also be initialized to all zeros. Null key encryption and decryption is an easy and effective way to deter casual external examination of your data. The Encoding.Unicode.GetBytes and Encoding.Unicode.GetString methods in System.Text make it very easy to convert a .NET string to a byte array, and vice versa.
Implementation Alternatives

Now let's look at some important variations of the AES implementation presented in this article, possible extensions of the code presented here, and cryptanalysis attacks against AES.

As much as any code that I've ever worked on, the AES algorithm has significant alternative approaches to implementation. Why is this important? AES is intended to be applicable to a wide range of systems, from smart cards with tiny memory capacities to large multiprocessor mainframe systems. In many scenarios, performance is critical and sometimes memory or processing resources are limited. Virtually every routine in AES can be modified to optimize performance at the expense of memory, or vice versa. For example, assigning the 256 values to the substitution table Sbox[] seems straightforward enough. However, these values are based on GF(28) theory and it turns out that these values can be generated programmatically. The same is true for the inverse substitution table and the round constants table.

Another interesting possibility for alternate implementation is the GF(28) multiplication used by the Cipher and InvCipher methods. My implementation codes a basic function that multiplies by 0x02 and then six additional functions which call gfmultby02. Another possibility would be to write a general multiplication function and use it instead of implementing seven separate functions like I did. At another extreme you could use a complete table of the product of all 256 possible byte values multiplied by 0x01, 0x02, 0x03, 0x09, 0x0b, 0x0d, and 0x0e. Yet another way to approach GF(28) multiplication is to implement it as a lookup into two 256-byte arrays, usually called alog[] and log[] because they are based on certain logarithm-like properties of GF(28).

Although the AES class presented here is fully capable of encrypting any form of .NET data, you might want to consider extending it in a number of ways. First, because the emphasis of this article is on presenting a clear explanation of AES, all error checking was stripped away. In my experience, adding a reasonable amount of error checking to a class similar to this AES class would triple the size of the source code. Because AES uses so many arrays, there is a lot of index bounds checking that should be done. For example, the constructor presented does not even check the size of the seed key parameter.

You might also consider extending this AES class by adding more features. The most obvious place to start would be to add methods that encrypt and decrypt fundamental .NET data types such as System.String and System.Int32. A more ambitious extension would be to implement an encrypted stream class.

How secure is AES? This is a hard question to answer, but the general consensus is that it is the most secure encryption algorithm available. AES has been subjected to more scrutiny than any other encryption algorithm to date. On both a theoretical and practical basis, AES is considered "secure" in the sense that the only effective way to crack it is through a brute-force generation of all possible keys. With a key size of 256 bits, no known brute-force attack can break AES in a reasonable amount of time (it would take years even on the fastest systems available).

Note that the most likely successful attack on an AES cipher results from a weak implementation that allows what is called a timing attack. The attacker uses different keys and precisely measures the time the encryption routine requires. If the encryption routine is carelessly coded so that execution time depends on the key value, it is possible to deduce information about the key. In AES, this is most likely to occur in the MixColumns routine because of field multiplication. Two safeguards against this attack are to insert dummy instructions so that all multiplications require the same number of instructions, or to implement field multiplication as a lookup table, as I've described.

There are many possible implementations of AES, especially using lookup tables rather than computation. The basic AES class presented in this article can be used to encrypt and decrypt any form of .NET data or can be extended into a class with added functionality.


Conclusion

The new AES will certainly become the de facto standard for encrypting all forms of electronic information, replacing DES. AES-encrypted data is unbreakable in the sense that no known cryptanalysis attack can decrypt the AES cipher text without using a brute-force search through all possible 256-bit keys.

The major obstacle I found when implementing an AES class in the Microsoft® .NET Framework was that the official specification document was written from a mathematician's point of view rather than from a software developer's point of view. In particular, the specification assumes that the reader is fairly familiar with the GF(28) field and it leaves out a few key facts regarding GF(28) multiplication that are necessary to correctly implement AES. I've tried here to remove the mystery from AES, especially surrounding GF(28) field multiplication.

It is only a question of time before AES encryption becomes widely available from Microsoft and third-party vendors in the form of .NET Framework libraries. However, having this code in your skill set will remain valuable for a number of reasons. This implementation is particularly simple and will have low resource overhead. In addition, access to and an understanding of the source code will enable you to customize the AES class and use any implementation of it more effectively.

Security is no longer an afterthought in anyone's software design and development process. AES is an important advance and using and understanding it will greatly increase the reliability and safety of your software systems.


Download ImageCode download available at: AES.exe (143KB)

For related articles see:
Security: Protect Private Data with the Cryptography Namespaces of the .NET Framework
Exploring Kerberos, the Protocol for Distributed Security in Windows 2000
For background information see:
The Design of Rijndael: AES - The Advanced Encryption Standard by Joan Daemen and Vincent Rijmen. (Springer-Verlag, 2002)
Announcing the Advanced Encryption Standard (AES): Federal Information Processing Standards Pub 197

James McCaffrey works for Volt Information Sciences Inc. where he manages technical training for software engineers at Microsoft. He has worked as a contractor on several Microsoft products including Internet Explorer and MSN Search. Reach him at jmccaffrey@volt.com or v-jammc@microsoft.com.

Subscribe  From the November 2003 issue of MSDN Magazine.
Back to top Back to top QJ: 031102

© 2007 Microsoft Corporation and CMP Media, LLC. All rights reserved; reproduction in part or in whole without permission is prohibited.


--
Happy day, happy life!