Saturday, December 19, 2009

Drag’n Drop files in WinForms

Recently I have been playing a little bit with drag and drop functionality and this short article shows how to implement drag and drop for files in WinForms.

The first thing is to set the AllowDrop property to true for the control we are going to drop files, without it drag'n drop events are not fired. I have used ListView control listView1 to display some basic file information about the dragged file e.g. file name, path and size. To make it more fun lets allow dropping multiple files at the same time, which is a standard Windows behavior.

Next thing is create DragEnter event handler in which dragged data is being checked and Effect property is set. You might want to add some conditions e.g. allowing files with certain extension.

It may look something like this:

private void listView1_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effect = DragDropEffects.Copy;
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }
}


Now is the time for the DragDrop event handler, in which the file names are retreived from the dragged files and passed to the method which does the rest of job i.e. adds data to the listView1 control.

private void listView1_DragDrop(object sender, DragEventArgs e)
{
    try
    {
        if (e.Effect == DragDropEffects.Copy)
        {
            string[] fileNames = e.Data.GetData(DataFormats.FileDrop) as string[];
            if (fileNames != null)
            {
                foreach (string s in fileNames)
                {
                    Console.WriteLine(s);
                    AddFileInfoToTheListBox(s);
                }
            }
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine("Exception in listBox1_DragDrop: " + exception.Message);
    }
}

Here is the AddFileInfoToTheListView method definition. It might be not the most elegant way of handling data but for the purpose of this example it is fine. To get information from the dragged file the FileInfo class is used.

private void AddFileInfoToTheListView(string fileName)
{
    try
    {
        FileInfo fi = new FileInfo(fileName);
        string [] fileData = { fi.Name, fi.ToString(),fi.Length.ToString() };
        ListViewItem lvi = new ListViewItem(fileData);
        this.listView1.Items.Add(lvi);

    }
    catch (Exception exception)
    {
        Console.WriteLine("Exception in AddFileInfoToTheListView: " + exception.Message);

    }

}

And here is the final result

Friday, October 23, 2009

SyntaxHighlighter

SyntaxHighlighter is an excellent tool for highlighting code syntax in blog posts. It works with many different languages, here is the full list.

If you'd like to see how your code is going to look, take a look at this post about Trace statements , I updated it to use the SyntaxHighlighter.

The tool is completely free of charge. You don't even have to download anything, just use hosted version and voila.

Its creator definitively deserves a couple of beers!

Wednesday, September 30, 2009

Strong name assembly and unit test project (InternalsVisibleTo attribute)

I tried to create a test project for a strong name assembly and I've encountered following error

Friend assembly reference 'TestProject1' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.

In order to fix it, the test project assembly has to be strong signed as well. The thing is that the test assembly needs to get access to the private members in the tested assembly, so it has to be decorated with the InternalsVisibleTo
attribute and should look like this:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("TestProject1, PublicKey=PUBLIC_KEY")]

Where TestProject1 is the name of the test assembly which need access to private members, and PUBLIC_KEY is,as the name suggests, the public key value of tested assembly. But how to get the PUBLIC_KEY value?

> sn –Tp AssemblyFileName

And this information is displayed; we need the public key

Public key is

0024000004800000940000000602000000240000525341310004000001000100537d27966b492e
6e4402d93b86848897b04781de2bf54fbef46671e3163d817d43bed3a786eeaa0e5beda76cda89
ec6845deef5d2852165bac0a4df08a22bb8fccec93c4c24ed7803886178b6d4279488b7800eac0
bbfa6357e3c52d6bb19bb278056955fba5f4c85fa18164088ca18377f15d74d9b75e0fd58cd053
97cdc7de

Public key token is fd41b11fd220edb5

So the attribute at the end has this form:

[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("TestProject1, PublicKey="+
"0024000004800000940000000602000000240000525341310004000001000100537d27966b492e"+
"6e4402d93b86848897b04781de2bf54fbef46671e3163d817d43bed3a786eeaa0e5beda76cda89"+
"ec6845deef5d2852165bac0a4df08a22bb8fccec93c4c24ed7803886178b6d4279488b7800eac0"+
"bbfa6357e3c52d6bb19bb278056955fba5f4c85fa18164088ca18377f15d74d9b75e0fd58cd053"+
"97cdc7de")]

After adding above attribute I could build without the unit test project any issues. Problem solved.

Wednesday, September 23, 2009

FxCop

FxCop is a great free tool for static code analysis, which checks managed code assemblies for compliance with .NET Framework Design Guidelines. FxCop is available both as GUI and a command line tool, so it can be easily used in build process. Certain messages can be excluded from future reports if you can intentionally avoid rules. New custom rules can be created using FxCop SDK.

If you recently updated Windows SDK to version 7, the FxCop installation file can be found in the Windows SDK v7.0/Tools/ directory.

To use GUI version of FxCop just start the application, add targets i.e. assembly or assemblies which you want to check and click Analyze button. After a while, depending on the assembly size, you will get the report.


Every message should be reviewed and one of the following actions should be taken

  • If there is a code defect - fix the code
  • If rule broken intentionally – exclude message
  • If message generated is false– exclude message

After you fix the code for all other messages rebuild the assembly and analyze the code again.

FxCop is great tool for all .NET developers, especially for these who are not familiar with .NET Framework Design Guidelines. FxCop can help you write robust and easily maintainable .NET Framework code.

Monday, September 21, 2009

Extension methods – great new feature of C# 3.0

C# 3.0 has a new great feature which is extension methods. It basically allows you adding methods to already existing types without recompiling, creating derived types, and yes it can be used with sealed types!

Let's take a look how to create an extended method for string type which checks if string is empty or null.


Ok we have a method defined, let's see how to use it – it couldn't be simpler, just type method name after string object. As you can see Visual Studio IntelliSense shows it as an extension with arrow shape icon.


I think extension methods are great feature making developer life easier and what's important code just looks cleaner and simpler, doesn't it?

Tuesday, September 15, 2009

Single instance application for each user

Sometimes there is a need of creating a single instance application. It can be achieved in several ways and below you can find how it may be done using named Mutex. Named mutexes are visible throughout the operating system and can be used for synchronization purposes. Additional requirement is that there has to be single instance application for each user. To achieve this we are going to create a unique mutex name for every user. Please notice that if you use the same name for every user there it will be possible to run only one instance for the whole system. If another instance of the application is running, the main window will be displayed with SetForegroundWindow
method from user32.dll library.

Because an external library will be used add namespace declaration

using System.Runtime.InteropServices

Now the SetForegroundWindow metod declaration

[DllImport("user32.dll")]


static extern bool SetForegroundWindow(IntPtr hWindow);

And here is the code that does the job

Friday, August 28, 2009

A few Software Development Podcasts worth checking

HanselMinutes is a weekly audio talk show with noted web developer and technologist Scott Hanselman and hosted by Carl Franklin. Scott discusses utilities and tools, gives practical how-to advice, and discusses ASP.NET or Windows issues and workarounds.

.NET Rocks!
is a weekly talk show for anyone interested in programming on the Microsoft .NET platform. The shows range from introductory information to hardcore geekiness.

Herding Code is a weekly podcast with K. Scott Allen, Kevin Dente, Scott Koon, and Jon Galloway on .NET development topics

Software Engineering Radio is a podcast targeted at the professional software developer. A new episode published every ten days. Episodes are either tutorials on a specific topic, or an interview with a well-known character from the software engineering world.

Thursday, April 23, 2009

Structured debugging process

Debugging should never be done chaotically. Below you can find instructions how to debug in a structured way.

  1. Duplicate the Bug
    The most important, no repro no fix
  2. Describe the Bug
    Keep it in database – easier to track changes
  3. Always assume that the Bug is yours
    If bug is in your code you can fix it, if not = trouble; eliminate any possibility before looking elsewhere
  4. Divide and conquer
    Hypothesis and elimination, look into code, like a binary search.
  5. Think creatively
    Version mismatches, operating system differences, problems with program binaries or installations, external factors
  6. Leverage Tools
    Helps to investigate e.g. Error detection tools (invalid memory accesses, parameters to system APIs and COM interfaces)
  7. Start Heavy Debugging
    Much time on exploring program's operations
  8. Verify that the Bug is fixed
    Easy when isolated module, harder in critical code – verify for all data conditions, good and bad & regression. Changes to critical code => inform the team!
  9. Learn and Share
    Summarize what you have learned and share with colleagues – helps eliminate the bug faster.

Of course there is no need to follow all the steps. If the bug is found and fixed just go directly to the step no.8

The steps are taken from an excellent book "Debugging Applications for .Net and Microsoft Windows" by John Robbins.

Wednesday, April 1, 2009

Windows Developer .Net 3.5

I have upgraded MCPD Windows Developer .Net 2.0 to .Net 3.5 by passing following exam 70-566: Upgrade: Transition your MCPD Windows Developer Skills to MCPD Windows Developer 3.5

The exam has two parts, the Technology Specialist part, with 20 questions and the second one, the Pro, with 25 questions. From 'upgrade' exam I expected more questions strictly about .NET 3.5 features but actually there were plenty of general Windows Development questions, many similar to those from both TS and Pro .Net 2.0 exams. The main benefit is that in order to get .Net 3.5 certification you have to, instead of passing two exams with about 45 questions each, pass one two parts exam with 45 questions.

I have been thinking about next step and decided not to extend skills with other technologies (e.g. ASP.NET), but rather specialize and improve skills in my current domain, which is .Net Windows Development.

Saturday, March 14, 2009

Posting to blog from Word 2007

If you are blogging the Word 2007 has a very nice feature for you - you can post to your blog from Word 2007!

How to do this:

  1. Click the Office button in the top left corner
  2. Click Publish\Blog - it will open new window
  3. Register a blog account 
  4. Choose blog provider
  5. Provide user name and password
  6. Optionally click picture options - you can provide details for picture provider
  7. Now create your post and when it is ready click the Publish button

Except of posting directly to your blog, you can publish a post as a draft or open an existing post for editing!



Unfortunately it seems that there is one flaw - security. If you try to set blog provider to the blogger (I have not checked other providers) in Word 2007, it says that a user name and a password will be visible to other people... It is for sure not the way it should work. Revealing user/pass details to the whole world is just not good idea.

I was searching for a solution. But have not found anything yet. It is impossible that no one thought about the security.

If anyone knows how to use it a secure manner please leave a comment and let me know.

Thursday, March 12, 2009

What's new in .NET 3.5

Here are some of the new features and enhancements in .NET Framework 3.5. These are not all differences but I think the most interesting ones. Let's take a look.

Common Language Runtime:

new specialized collection HashSet<T>, EventSchemaTraceListener, Pipes support (anonymous and named) allows for interprocess communication for processes from local computer as well within network, improvements in Garbage Collector, new ReaderWriterLockSlim with performace comparable to lock statement in the Threading namespace and Time Zone enhancements

Networking

Peer-to-peer network support, Socket Performance enhancements

Windows Forms

WPF controls and content support in Windows Forms; ClickOnce improvements (deployment from multiple locations is now possible); Client Application Services – Web and Win-based applications can use these services to authenticate users and retrieve user roles and application settings from a shared server ;Vista support –existing Windows Forms applications have the same appearance as written especially for Vista.

LINQ

Linq to Objects, Linq to XML, Linq to SQL, Linq to DataSets (support for any generic database)

ASP.NET

client-centric and server centric AJAX controls; Visual Web Developer IntelliSense support for Java Script and MS Ajax Library

Saturday, March 7, 2009

Logging information - Trace Class


What are Trace statements
Trace statements are essentially printf style debugging. It allows to debug without a debugger. This kind of debugging was used before interactive debuggers were used.

How to use Trace class
Trace objects are active only if TRACE is defined-by default TRACE is defined in debug and release build projects in Visual Studio.

Similarly as Debug object, the Trace object uses TraceListeners to handle output.
If log data need to be stored in some particular way a custom trace listener can be implemented e.g. if data should be stored in database.
By default all logging information goes to the Output window. Let's see how to use a non-default listener, in this example we will use TextWriterTraceListener class.

FileStream objStream = new FileStream("C:\\AppLog.txt", FileMode.OpenOrCreate);
TextWriterTraceListener objTraceListener = new TextWriterTraceListener(objStream);
Trace.Listeners.Add(objTraceListener);
Trace.WriteLine("This is first trace message");
Trace.WriteLine("This is second trace message");
Trace.Flush();
objStream.Close();

In first line a FileStream object is created with file mode set to open or create.
Next the TextWriterTraceListener object is initialized with FileStream object.
To make it work the listener has to be added to Listeners collection of Trace class. Next the WriteLine method is used to log two text messages and finally the buffer is flushed to the output and FileStream is closed.
Notice that the default trace listener was not removed from the collection so whatever will be written using Trace class methods will go to all listeners from the collection, in this case will go to the Output window and will be logged to the AppLog.txt file.

How to control Trace from outside of application
Trace class can be controlled from outside of an application. Furthermore the configuration can be modified without rebuilding the application.
In order to configure trace we have to add the App.config file to the project which is basically XML file. After building a project the App.config file will change name to ApplicationName.exe.config where ApplicationName is actual application's Assembly name.

Let's take a look at following example.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <trace autoflush="true" indentsize="2">
            <listeners>
                <remove name="Default"/>
                <add name="EventLogListener" type="System.Diagnostics.EventLogTraceListener" initializeData="MyEventLog"/>
            </listeners>
        </trace>
    </system.diagnostics>
</configuration>
All trace configuration should be placed under node. In above example we set two trace properties, the flush and the indent size. Next the default listener is removed, so the Trace will not write anything to the Output window. Next line we add a new listener of the type of EventLogTraceListener with a name of EventLogListener and we set an event source name to MyEventLog. Without writing a single line of code we added a a non-default trace listener. Isn't that great?

If above configuration is used you can find trace logs in the Event Viewer under Windows Logs/Application (click picture to enlarge).


How to use switches
Switches allow enabling or disabling tracing. In general there are two classes of switches BooleanSwitch (as name suggests has two possible states) and more interesting TraceSwitch class, which is basically multilevel switch with following possible levels
  • Off
  • Error
  • Warnings
  • Info
  • Verbose

There are two things which need to be done in order to use switches
  1. Define TraceSwitch object

    TraceSwitch theSwitch = new TraceSwitch("theSwitchName", "description");

    The first parameter is very important and enables to control the switch from outside of application. Second parameter is a description.
  2. Set the switch level.
    it can be done in the code e.g.

    theSwitch.Level = TraceLevel.Info;

    Or it can be configured from outside of application in already known config file, which is very useful since changes in configuration do not require rebuilding application!
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>
        <switches>
            <add name="theSwitchName" value="3" />
        </switches>
    </system.diagnostics>
</configuration>
Possible values of trace level
Trace Level Value
  • Off 0
  • Error 1
  • Warnings(& errors) 2
  • Info(warnings & errors) 3
  • Verbose (everything) 4
If the value of theSwitch is set to 2 only two first messages are logged ( for error and for warning ).
Trace.WriteLineIf(theSwitch.TraceError, "Error tracing is on!");
Trace.WriteLineIf(theSwitch.TraceWarning, "Warning tracing is on!");
Trace.WriteLineIf(theSwitch.TraceInfo, "Info tracing is on!");
Trace.WriteLineIf(theSwitch.TraceVerbose, "VerboseSwitching is on!");


To remove some some overhead we can use switch in a following way:
if ( theSwitch.TraceWarning )
{
    Trace.WriteLine( "Warning tracing is on!");
}

To use Trace statements in efficient manner we have to analyze how much information is needed to solve a problem on a machine without development environment. Too large log files will make process slow and on the other hand with too little information the problem cannot be solved.

Tuesday, March 3, 2009

Defensive programming – Assertions


What are Asserts?
Assertions are key component for proactive programming. If they are used in a correct way they tell where and why error happened.
Assertion declares that some condition must be true, if it is not, the assert fails, bringing up message on failed condition (screen shot below).


Asserts are used only on Debug builds ( the DEBUG must be defined - it is enabled by default in debug builds in Visual Studio )
If you will take a look in a retail build assembly using the .Net Reflector tool the Debug.Assert(...) code will not be in the assembly.


How to Assert?
There are two basic rules:
  1. Assert must not change values or state of program (treat as read only)
  2. Rule: Check a single item at a time.

What to Assert?
Generally you should use Asserts for:
  1. Parameters coming into method. Sometimes better approach is to throw InvalidArgumentException
  2. Values returned by methods; on wrong returned program may die after 20 minutes (Asserts help! )
  3. Use asserts when you need to check for assumption (e.g. Available memory )

How to use Asserts in .Net Framework

The Debug class is defined in System.Diagnostics namespace. The Debug class methods allows to print debugging information and check application logic with assertions, making more robust without impacting the performance and code size of retail assemblies.

The Debug class except of Assert method, in which we are the most interested, provides following write methods: Write, WriteIf, WriteLine and WriteLineIf.

Lets take a look at the Debug.Assert method, There are three overloaded versions of the method.
  • Debug.Assert(i > 10);
  • Debug.Assert(i > 10, "i > 10");
  • Debug.Assert(i > 10, "i > 10", " i should be greater than 10, if you see this it means that it was not ;)");
The first parameter is a boolean condition, second is a string message and the third parameter is a string detailed message.
  • If assert is used in a similar way as below it does not tell us which parameter was bad
// wrong way to write assertion. Which param was bad?
public static void DoStuffWithObject1(int i, object o, int iLen)
{
    Debug.Assert((i > 0) && (null != o) && (iLen < MAXVAL ));
}
  • And here is the right way of doing this
// right way to write assertion - every param individually
public static void DoStuffWithObject2(int i, object o, int iLen)
{
    Debug.Assert(i > 0);
    Debug.Assert(null != o);
    Debug.Assert(iLen < MAXVAL ));
    ...
}
  • Asserts should check a value completely, in following example we expect that a parameter will be a valid customer name, what happens if an empty string is passed?
// incomplete checking 
public static bool GetCustomerName(string CustName)
{
    Debug.Assert(null != CustName, "null != CustName");

    return true;
}
  • And here example of complete checking
// complete checking
public static bool GetCustomerNameBetterChecking(string CustName)
{
    Debug.Assert(null != CustName, "null != CustName");
    Debug.Assert(0 != CustName.Length, "CustName is EmptyString");

    return true;
}
  • Be careful because improper using of Asserts can crash application!
    if the null is passed as a parameter the NullReferenceException is thrown
// Assert that crashes application if CustName is null
public static bool NullReferenceExceptionCrash(string CustName)
{
    Debug.Assert(CustName.Length > 0);

    return true;
}

Friday, February 6, 2009

Some subjects to write about

This blog was meant to bring some value by describing some solutions for programming problems. I've promised myself to reserve some time and publish some articles on regular basis.

Here are some ideas:
-defensive programming with assertions
-structured debugging process
-improving performance of SQL operations
-Unit tests with NUnit
-XML serialization

All MCPD exams passed

Another goal achieved - the Microsoft Certified Professional Developer: Windows Developer :)
This is great. I have to find some new challenges soon :)

Tuesday, January 13, 2009

Second certification exam passed

Wooohooo I passed my second certification exam today!

The 70–526: TS: Microsoft .NET Framework 2.0 – Windows-Based Client Development. According to following MS page http://www.microsoft.com/learning/mcp/mcts/winapps/default.mspx by passing both exams I have earned MCTS: .NET Framework 2.0 Windows Applications.

The exam itself was hard. There were many questions about creating installers and I do not have (almost) any experience with creating installers and the VS Express Edition does not support the Installer project template.

I spend about 4 weeks to prepare for exam and last days were really hard and now after the exam is passed instead of taking a rest I am thinking about the next step :)