Posts Tagged: Tips ‘n’ Tricks


24
May 09

Creating a single instance application in C#, WPF

Some time you might want the user to run only one instance of the application. Its pretty easy to do so in C#. This is acheived using a Mutex. A mutex is used to restrict the usage of common resources in concurrent proragmming. C# provides a class called System.Threading.Mutex with which we can control the number of instances of an application that should be running. Just add the following snippet to the App.xaml.cs file (code behind file of App.xaml)

class App : Application
{
private Mutex myMutex;
...
protected override void OnStartup(StartupEventArgs theArgs)
{
bool aIsNewInstance = false;
myMutex = new Mutex(true, "Foo.SingletonApp", out aIsNewInstance);  //Creates a mutex for the application
if(!aIsNewInstance)
{
App.Current.Shutdow();  //Shutdown when a new mutex with the same name is created
}
}
}

How this works

The creation of a mutex in here takes three parameters. First one is to give the ownership of this mutex to the calling thread. Second one is the unique name given for this mutex (remember this is a unique name). Third one is an out parameter that returns
true — if there are no mutex with this name and if the new mutex is successfully created
fase — if there is already a mutex with this name.
That why we check for !aIsNewInstance in the snippet. Here we override the Startup event of the Application class (refer to my previous post on Application Events) so that we can validate the mutex during the start of the application.


15
May 09

UI designing, guidelines

Browsing about UI guideline, I got a superb link. Its a must read for UI designers. Also take up the quiz when you are done with the link.


9
Apr 09

FxCop — Code reviewer

If you are a lone wolf while writing an appliction, how do you review your code ?? Whome do you call for the code review ??? Never mind ! Use FxCop. Its an app from MS that will take in assemblies and use some rules for reviewing those assemblies. Although there are loads of softwares that does this operation, I use FxCop as it is simple, easy to use and free of cost. Unlike most other code analyser, this tool will analyse the compiled code and not the source code. This code analyser will work on any .NET assemblies and check for violations based on the rules specified. The advantage is that you can specify your own set of rules and the analyser will consider that while doing the code review. When you run the application over a set of assemblies, the violation results are generated in an xml form and FxCop itself provides sufficient information on solving those violations. Sweet, isn’t it ?? So next time, don’t worry on whome to call for code review. Try using FxCop.

If you used any other code analyser, comment on it. We shall give it a try too.


17
Mar 09

DoUNo: SelectedItem or SelectedIndex properties will not be filled unless the control is painted in screen

Recently, I was trying to write UnitTest for a panel. The panel had a ComboBox and the target method (method that needs to be tested) was populating the ComboBox with some DataSource, which is a collection of string. In my unit test driver (written in NUnit with NMock), I tried to check the item’s collection. It was always returning me null despite me adding some items to it. Even the SelectedItem and SelectedIndex were all returning me null. When I had a look in to the WinForms dll using reflector, I came to know about itemscollection .

It seems that this member will not be populated unless the ComboBox is painted in a layout.

 

So next time, when you are writing a unit test for controls, make sure that you create testcases that are testable (unlike me). Thanks to my colleague who pointed out a SO link that clearly talks about this.


14
Mar 09

GDI+ to WPF

Long since I blogged. Reason being the title. I am trying to learn WPF (Windows Presentation Foundation) programming. From now, most of the posts will be WPF related. Meanwhile, if you want to know more about WPF and why WPF, check this out. Although the article is kind of old, its worth giving a look at it.


13
Mar 09

DoUNo: DisplayMember getting reset on DataSource=null

I have a ComboBox whose items are set using the DataSource property. The DataSource is a collection of a custom object (that has a string property ‘Value’ and int property ‘Id’). In the initialise controls, I set the DisplayMember as Value and ValueMember as Id. Now I tried to clear the DataSource by calling,

myComboBox.DataSource = null;

When I did that, my ComboBox’s DisplayMember is reset to “” automatically. This was not I expected, but this is how it behaves as a .Net control. Thought it would be helful sharing it.

More @ http://stackoverflow.com/questions/641809/displaymember-getting-reset-on-datasourcenull


17
Feb 09

DoUNo: Reading Console’s text in C#

Its really simple to read a console’s text (contents) in C#. This can be done using the Console.In.ReadLine() method. The Console and the Console.In classes exposes a loads of methods that are really handy. Here is a small snippet that tries to print the directories in blue color and the others in default color in console when you type dir.

string aConsoleReadLine = null;
ConsoleColor aDefaultConsoleColor = Console.ForegroundColor;
while ((aConsoleReadLine = Console.In.ReadLine()) != null)  //Reading the text from the console and storing it in a local variable
{
  if (aConsoleReadLine.Contains("<DIR>"))  //Check if it is a directory
  {
    Console.ForegroundColor = ConsoleColor.Blue;
  }
  else
  {
    Console.ForegroundColor = aDefaultConsoleColor;
  }
  Console.WriteLine(string.Format("{0}", aConsoleReadLine));
}

To run the above mentioned snippet, create a console app and put this snippet in your main method. Then, open up command prompt. In the command prompt type dir | <your_built_exe>.exe. We use | so that we can get the output to our program.


12
Feb 09

Creating objects of private classes in C#

You can create objects of private classes of one assembly in another assembly using Reflections. Creation of object involves calling that class’s constructor. This is how you do it,

Suppose, Foo.Bar is an assembly and Foo.Bar.ClassA is a private class in Foo.Bar, then to create an object of ClassA in Bar.Baz assembly, you need to do the following,

Load the assembly  and get  the type of ClassA

Type aClassAType = Assembly.LoadFile("Foo.Bar.dll").GetType("Foo.Bar.ClassA", true, true);  //Loading a dll from the specified path and from the loaded assembly we are tyring to get a class names ClassA

First true in the parameter specifies that it can throw errors if the class is not found and the next true specifies that the class name is not case sensitive.

Invoke the constructor of ClassA

object aClassAObject = aClassAType.GetConstructor(new Type[0]).Invoke(new object[0]);  //Getting the constructor and invoking it

Here we are passing new Type[0], as an argument to  the GetConstructor method. This will get a constructor from ClassA that has zero arguments. Following this line is the Invoke call. Again, over here, we are trying to call the parameterless constructor (that is just got) with zero parameters. Thats why we pass new object [0].

To call a parameterised constructor, use

aClassAType.GetConstructor(new Type[] { typeof(string) }).Invoke(new object[] { “FooBarBaz” } );  //Here the parameter of the constructor is of type string and we are trying to call it passing “FooBarBaz”

Using the object

The above statement returns the object that has got created. From now aClassAObject is of type ClassA

Ok. Now that we have created a private class object. Whats the big use of it ??

Well, it all depends on you. I do this when I write my UnitTest for assemblies. That is one frequent area where you can use this technique. If you find any other scenarios where you can use this let us know about it.

For more information on reflections in C#.


4
Feb 09

DoUNo: Is operator overloading possible in structs ??

Yeah. One can overload operators in a structure (C#). Syntaxes are similar to that of class operator overloading, except for that fact that we need to operate on struct variables and not on class objects (obvious isn’t it ??).

For newbies — struct is of value type (stored in stacks) and classes are of reference types (stored in heaps)


4
Feb 09

DoUNo: Operator overloading in Size and Point

You can add two Size or Point members directly using the + key. Did you know that ?? You can even do -, == and != on these memebers. You cannot do * or / on them thou’. If  you find anyother class / struct in C# that enables operator overloading, you can add it to the above it. Hope you find this useful.