Monday, October 27, 2008

Code Snippets: Monitor class for thread-safety

Code Snippets is an interesting in-built feature of Visual Studio 2005. Code snippets are normally used in the Code Editor by first typing a shortcut (short name or alias), and then pressing TAB key. The code snippet shortcut/alias will then expand into a programming construct. This can make writing program code quicker, easier and more reliable.

To use the code snippets, use any of the follwing ways:

1. Right click in Code Editor and select the Insert Code Snippet menu command,
2. Activate the code snippet list by typing CTRL + K followed by X.


The Code Snippets Manager, found under the Tools menu, allows us to manage code snippets (add/remove) that will be available to insert into the code. It can also be accessted by CTRL K, followed by B.


The code snippets are stored as XML in .snippet files, and any user-defined snippet can be easily imported through the Code Snippets Manager and used during coding.

As a example, I will write a code snippet in order to use the Monitor.Enter and Monitor.Exit methods for thread-safe code (as we already have the 'lock' code snippet in VS2005) as shown below:

try
{
    System.Threading.Monitor.Enter(obj);
 
    // do some work here
}
finally
{
    System.Threading.Monitor.Exit(obj);
}

>>> Create the code snippet and store it as monitor.xml

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>monitor</Title>
      <Shortcut>monitor</Shortcut>
      <Description>Code snippet to use Monitor class for thread-safety</Description>
      <Author>Ashvin Gunga</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>expression</ID>
          <ToolTip>Expression to evaluate</ToolTip>
          <Default>AnObject</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
          try
          {
          System.Threading.Monitor.Enter($expression$);
          //TODO: Enter your code here
          $selected$ $end$
          }
          finally
          {
          System.Threading.Monitor.Exit($expression$);
          }]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

>>> Use the Code Snippets Manager and import the monitor.snippet file under My Code Snippets


>>> Now, in the code, type monitor and press TAB. The monitor shortcut is expanded to:

try
{
    System.Threading.Monitor.Enter(AnObject);
 
    //TODO: Enter your code here
}
finally
{
    System.Threading.Monitor.Exit(AnObject);
}

Downloads
Visual Studio 2005 Code Snippets can be downloaded here.

Saturday, October 25, 2008

Load data from XML file into Crystal Reports

In this post, I will demonstrate how we can display data found in an XML file in a Crystal Report in C# using .NET Framework. It is easier to understand the whole thing when there is no need to write code for database (such as Oracle, Access or SQL) access or adapter or connection objects.

Pre-requisite: Crystal Reports installed on the machine, along with Visual Studio 2005.

1. The first thing is to create a new Windows Application (here I've named it XmlToCrystalReports) in VS2005.

2. I will add an Employees.xml file to the project, under a DATA folder. The xml file will contain data about employees.

Right click on the Windows Application in the Solution Explorer. Select Add -> Add New Item. Choose XML File in the Add New Item form, name it Employees.xml and select Add..


3. Populate the xml file with test data.
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee>
    <Id>1</Id>
    <Name>John</Name>
    <Position>Team Leader</Position>
    <Experience>6</Experience>
  </Employee>
  <Employee>
    <Id>2</Id>
    <Name>Frank</Name>
    <Position>Analyst Programmer</Position>
    <Experience>3</Experience>
  </Employee>
  <Employee>
    <Id>3</Id>
    <Name>Michael</Name>
    <Position>Senior Analyst Programmer</Position>
    <Experience>5</Experience>
  </Employee>
  <Employee>
    <Id>4</Id>
    <Name>Thomas</Name>
    <Position>Senior Analyst Programmer</Position>
    <Experience>4</Experience>
  </Employee>
  <Employee>
    <Id>5</Id>
    <Name>Alan</Name>
    <Position>Trainee Analyst Programmer</Position>
    <Experience>0.5</Experience>
  </Employee>
</Employees>

4. Next, I will add a Crystal Report to the project.

Right click on the Windows Application in the Solution Explorer. Select Add - Add New Item.


Choose Crystal Report, name it EmployeesReport.rpt, and select Add.


The Crystal Reports Gallery pops up. I will leave the default options and select OK.


The Standard Report Creation Wizard is shown, along with a list of available data sources. Under Project Data -> .NET Objects, double click on XmlToCrystalReports.MainForm.


The ADO.NET form is shown. Browse and select the Employees.xml file created earlier and choose Finish.


And we are back in the Standard Report Creation Wizard. The Employee table is now shown under the Available Data Sources tree. Select the Employee table, move it to the right under the Selected Tables tree and choose Next.


Now, we will need to select the appropriate fields to be displayed in the crystal report. So, move all the fields under the Fields to Display tree on the right and select Finish.


The EmployeesReport.rpt is added to the project and shown in the designer, with a pre-defined layout.


5. Format the crystal report to meet your needs (example, change font size, add title in header)


6. The Solution Explorer will now be as follows:


7. Now to view the report when the application runs, we will need to add a Crystal Report Viewer to the main form. The Crystal Report Viewer component is available in the Toolbox under Crystal Reports.



We can hide the Group Tree found on the left by setting the DisplayGroupTree to false in the Properties Window.


8. The last step is during form load, we will need to (1) load the XML file into a dataset, (2) create an EmployeesReport instance and set the data source to the dataset created, and (3) set the ReportSource of the crystal viewer to the instance of the EmployeesReport.

private void Form1_Load(object sender, EventArgs e)
{
    DataSet dsEmployees = new DataSet();
    dsEmployees.ReadXml(@"DATA\Employees.xml");
 
    EmployeesReport report = new EmployeesReport();
 
    report.SetDataSource(dsEmployees);
    crystalReportViewer1.ReportSource = report;
 
}

9. Run the application, and (if everything is ok) the Crystal Reports Viewer will display the employee displays found the the xml file.

Friday, October 24, 2008

Dotfuscate

Introduction
The Microsoft .NET compiler converts the C# source code into Microsoft Intermediate Language (MSIL). However, with the use of a good decompiler tool and a few mouse clicks, any person can revert this .NET compiled code to its original C# source code. Hence, we need to protect the source code, including the 'trade secrets and logic' from attackers, especially when distributing the libraries/executables to third parties. A viable solution is the use of an Obfuscation Tool such as the .NET Dotfuscator (or simply, Dotfuscator).

The definition of 'obfuscate' is 'to confuse' or 'to make obscure or unclear', and that's exactly what an obfuscator tool will do. The Obfuscator will apply behavior preserving transformations on the code so that the functionality is preserved but the readability or understandability of the code is drastically reduced. The aim is to confuse observers while giving a consistent behavior to the Runtime Environment.

Main strategies of an obsfuscator
Compaction
The entire application is analysed and unused members are identified and removed from the obfuscated assembly. This is called the Compaction process. The unused members include unused classes, methods, instance variables and design time metadata, just to name a few. For example, a common library may offer a lot of functionalities but only a few are used in the application. So, these unused methods can be safely removed. Compacted programs also tend to load faster and run using less memory.

Overload Induction
The obfuscator renames all program identifiers to small, meaningless names. The Overload Induction mechanism works by identifying colliding set of methods across inheritance hierarchies and renaming such sets according to some enumeration (e.g. the alphabet). This method determines all opportunities for name reuse and hence, you may find more than 30% of ALL methods renamed to a single letter 'a'. Another advantage is the final program size of the obfuscated code is reduced by approximately 10% as there is heavy reuse of identify names.

String Encryption
Another interesting feature is the implementation of the runtime decrypted string encryption. An encryption algorithm is applied to all string literals and constants so as to make reverse-engineering even harder. This is very useful to hide hardcoded SQL strings, usernames and passwords that may be found in the code. Also, a decryption algorithm is inserted in the obfuscated code and later called at runtime to get back the original string literals.

Control Flow obfuscation
Control Flow obfuscation is yet another strong form of code protection. Here the flow of the program is changed so that the link between the original code and the obfuscated code breaks. It also ensures that no bug is introduced. For example, a for loop statement may be transformed into a while loop, a switch statement may be converted to a nested if statement and go to statements and labels may be introduced, just to name a few. This in turn transform the neat logic and flows in the original source code into a 'spaghetti-like' code to confuse the readers and any reverse engineering tool.

Assembly Linking
Multiple input assemblies are also combined into one or more output assemblies.



PreEmptive Solutions Dotfuscator flavors
There are currently two different version of the Dotfuscator: Professional Edition and Community Edition. The Community Edition is an entry level obfuscator and is included in Visual Studio 2005 Pro. The Professional Edition provides superior protection to foil decompilation, size reduction to conserve memory and improve load times, incremental obfuscation to release patches, watermarking to track pirates and so on and so forth.

Simple Dotfuscator Demonstration
1. Create your project in VS2005. Here, I shall use a simple application that print numbers 1 to 100.
using System;
using System.Collections.Generic;
using System.Text;
 
namespace DotfuscateDemo
{
    class Program
    {
        private double unUsedDouble;
 
        /// <summary>
        /// Gets or sets the un used double.
        /// </summary>
        /// <value>The un used double.</value>
        public double UnUsedDouble
        {
            get { return unUsedDouble; }
            set { unUsedDouble = value; }
        }
 
        /// <summary>
        /// Main method
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            Print1ToN(100);
            Console.ReadLine();
        }
 
        /// <summary>
        /// Print1s to N.
        /// </summary>
        /// <param name="nValue">The n value.</param>
        private static void Print1ToN(int nValue)
        {
            for (int i = 1; i <= nValue; i++)
            {
                Console.WriteLine(i);
            }
        }
    }
}


2. Build your project to get the assemblies that needs to be dotfuscated.

3. In Visual Studio 2005, open the Dotfuscator Community Edition found under Tools menu.


4. On the 'Select Project Type' screen, select the 'Create New Project' option.


5. Now we are ready to dotfuscate the project asssembly.

Select the Input tab on the Dotfuscator main window.

Select the option 'Browse and add assemblies to list' (this is an open folder icon) and add the project assembly.


6. There are other features available in the different tabs on the window and many of them may also be disable if you using the Community Edition. To keep this example simple, I will go directly to the dotfuscation process.

7. Now its time to save the project using Save Project under File menu. The solution is saved as an xml file.

8. The final step is to kick off the obfuscation process. This is done by selecting the Build Project option (play icon).

9. Once the build is completed, a Build Statistics is shown giving summary details of the obfuscated code changes.


10. You can now find the dotfuscated assemblies in a folder named Dotfuscated at the location where you saved the project xml file.

Before obfuscation...
After obfuscation...
Worth noting facts about Dotfuscator
A command line interface is available and thus, makes it suitable for integration into scripting environments or automated build processes.

ASP.NET code behind assemblies can be obfuscated using the Dotfuscator.

Dotfuscator will solely work on the compiled .NET assemblies and the original source code is never affected.

Dotfuscator is not a profiler (a very common misconception!!!).

Dotfuscator supports the Microsoft .NET Compact Framework.

And finally ...
Last but not least, it is important to know that obfuscation (or even encryption) is not 100% protected and secure. The only aim is to make the reverse engineering process extremely time consuming and painful so that it's not worth the effort and hence, stopping any potential attacker.

References
Microsoft .NET Support Team Blog
Preemptive Solutions
The Dotfuscator Solution

Thursday, October 23, 2008

Hide ListView border in .NET Compact Framework

To disable (or hide) the border of a ListView control in .NET Compact Framework,

1. Declare the following PInvoke methods...

#region PInvoke Declarations

const int GWL_STYLE = -16;

const int WS_BORDER = 0x00800000;

const int SWP_NOSIZE = 0x1;

const int SWP_NOMOVE = 0x2;

const int SWP_FRAMECHANGED = 0x20;

 

[DllImport("coredll.dll")]

private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

 

[DllImport("coredll.dll")]

private extern static void SetWindowLong(IntPtr hwnd, int nIndex, int dwNewLong);

 

[DllImport("coredll.dll")]

private static extern bool SetWindowPos(IntPtr hwnd, IntPtr hWndInsertAfter,

   int x, int y, int cx, int cy, int uflags);

#endregion



2. Write a ShowListViewBorder method...

/// <summary>

/// Shows the list view border.

/// </summary>

/// <param name="handle">The handle.</param>

/// <param name="showBorder">if set to <c>true</c> [show border].</param>

private void ShowListViewBorder(IntPtr handle, bool showBorder)

{

   int style = GetWindowLong(handle, GWL_STYLE);

   if (showBorder)

   {

        style |= WS_BORDER;

   }

   else

   {

        style &= ~WS_BORDER;

   }

   SetWindowLong(handle, GWL_STYLE, style);

   SetWindowPos(handle, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED);

}



3. Call the ShowListViewBorder...

ShowListViewBorder(window.lvwDetails.Handle, false);

Sunday, October 5, 2008

'Beautify' C# source code in VS2005

Many times I have been asked whether it is possible to 'beautify' the C# source code in Visual Studio 2005. The answer is yes, we can.

In VS2005, the Format Document command found in the Edit -> Advanced Menu is available. The keyboard shortcut is:

Ctrl-k, Ctrl-d

(i.e. press ctrl, k and d keys simultaneously)

Before Format Document command...
public class Divider
{
public static double Divide(int divident, int divisor)
{
try{return divident / divisor;}
catch (Exception ex){
throw ex;
}
}
 
public static void Main() { try
{Divider.Divide(30, 0);}
catch (Exception ex)
{Debug.WriteLine(ex.StackTrace);
}
}
}

After Format Document command...
public class Divider
{
    public static double Divide(int divident, int divisor)
    {
        try { return divident / divisor; }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    public static void Main()
    {
        try
        { Divider.Divide(30, 0); }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.StackTrace);
        }
    }
}


Tip: Another way to achieve the same result is to first find the last closing bracket in the source and then delete it, and finally re-type it.

You can also check out the other interesting features available on the Edit -> Advanced menu: