Codelog

foreach(Snippet aSnippet in CodeLog){ aSnippet.GetSolution(); }

Archive for the ‘General Programming’ tag

DoUNo: MDI in WPF

without comments

WPF, out of the box doesn’t have provision for MDI windows. The reason is quite simple, MDI windows are outdated and most of the applications have been using tabbed documents, proving they are really easy to use. Although the framework is flexible enough for you to make such a feature, its better to move to tab based interface.

Written by sudarsanyes

January 13th, 2010 at 9:07 am

DoUNo: Setting expectations on nullable type, NMock2

without comments

Ever had a problem of setting an expectation for nullable objects?

If you wanna return false when .HasValue of a nullable object is called, then you cannot do it with the normal expect statement. Rather, try not returning any values, because NMock2 returns default value of HasValue (False) if nothing is set as return values in expect statements.

Here is a sample,

public interface IProduct  //Interface that has a nullable member
{
  int? ProductNo  //Member that I wanna test and I wish to test the scenario in which this will be null
  {
    get;
  }
}
IProduct aProduct= myMockery.NewMock<IProduct>();
//Stub.On(aProduct).GetProperty("ProductNo").Will(Return.Value(default(int?));  //this statement produces a runtime exception, so we have to use the following instead
Stub.On(aProduct).GetProperty("ProductNo");  //no return value is set, nmock2 returns false when .HasValue is queries

Hope this helped you.

Sudarsan Srinivasan
- on behalf of my friends (they found this hack :P )

Written by sudarsanyes

November 6th, 2009 at 9:08 am

Accessing Command Prompt from C#

without comments

Recently, I wanted to write a program in c# that should start the command prompt in the background (it should not show the cmd window), give inputs from my C# program and get the results redirected back to my C# application. I was googling around a bit and then came up with a solution.

Its damn simple. Usually to start any process from C# applications, we use the Process object. The process object has two properties called StandardInput and StandardOutput. These properties will allow the C# application to get the input stream of the process that needs to be started. So to mock inputs and outputs, we need to do the following,

Process aProcess = new Process();
ProcessStartInfo aStartInfo = new ProcessStartInfo();
aStartInfo.FileName = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\cmd.exe";
aProcess.StartInfo = aStartInfo;
aProcess.StandardInput.WriteLine("dir");  //will open a cmd process and feed the command "dir" to it

By this way you could give inputs to a process that you start from C#. What if you wanna see output of the cmd prompt in your own prompt ?? For this we use the StandardOutput property. But there is yet another simple way to get the output from the command prompt. This is done by subscribing for the event, OutputDataReceived.

aProcess.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
  textBox1.AppendText(e.Data);
  textBox1.AppendText(Environment.NewLine);
}

Note: These ways are possible only if,

aProcess.RedirectStandardOutput = true;
aProcess.UseShellExecute = false;
aProcess.BeginOutputReadLine();

are set to the mentioned values. BeginOutputReadLine method will start async read operations from the C# application stream instead of the standard input devices. So next time you wanna clone a command prompt, start the cmd process and give your own look and feel to it.

Written by sudarsanyes

August 31st, 2009 at 5:44 pm

WMI (Windows Management Instrumentation) in C#

without comments

In my previous post, I had written about ManagementEventWatcher with some WMI querries. In this post we will try to figure out what this WMI is.

WMI stands for Windows Management Instrumentation. Its a set of functionalities provided by the OS (Windows) for the applications to control / manage the administrative tasks (check this out for a formal definition).

For example, if you wanna retrieve information about the CDROM drive on a machine, you can write some simple queries in c# and get that job done.

Using WMI in C#

Its fairly simple  in C# to use WMI infrastructure services. C# comes with a class called, ManagementObjectSearcher with which we can query for any information. Lets take the fore mentioned example, the CDROM example. To get information about the CDROM,

  1. Create a WqlObjectQuery object with the query statement, SELECT * FROM Win32_CDROMDrive

    WqlObjectQuery aWMIQuery = new WqlObjectQuery("SELECT * FROM WIN32_CDROMDrive");
  2. Create an object of ManagementObjectSearcher and assign the created query to this object
    ManagementObjectSearcher aManagementObjectSearcher = new ManagementObjectSearcher();
    aManagementObjectSearcher.Query = aWMIQuery;
  3. Run the query by calling the Get method in the ManagementObjectSearcher
    aManagementObjectSearcher.Get();
  4. The Get() method returns a ManagementObjectCollection. Iterate thru’ it to get the reults of the query. Each ManagementObject’s Properties field (ManagementObject.Properties) will contain a PropertiesDataCollection. Iterate thru’ this for additional results on the query
    foreach (ManagementObject aObject in aObjectSearcher.Get())
    {
      Console.WriteLine(aObject.Properties.ToString());
      foreach (PropertyData aProperty in aObject.Properties)
      {
        Console.Write("\t");
        Console.WriteLine(aProperty.Name + "----->" + aProperty.Value);
      }
      Console.WriteLine();
    }
  5. Change the query according to your need. You can query USB Drive information, Hard Disks, Processes and so on. Check out the MSDN for the list of WMI classes

Written by sudarsanyes

June 25th, 2009 at 2:26 pm

ManagementEventWatcher and WqlEventQuery in c#

with one comment

Yesterday, I was searching for some kind of snippet that will throw some notification when the system starts / stops some processes, thats when I came to know about the ManagementEventWatcher in c#.

ManagementEventWatcher allows us to subscribe for specific events and notifies us when those events occur.

For example, in the fore mentioned example, we need to create a ManagementEventWatcher for the events related to the spawning of processes. This is done using the WqlEventQuery class.

So first we start off writing the WqlEventQuery. This class helps us in constructing WMI event queries. For getting a notification when a process is started or stopped, we shall write a query as follows,

WqlEventQuery aProcessCreationQuery = new WqlEventQuery("SELECT * FROM
Win32_ProcessStartTrace");

or

WqlEventQuery aProcessCreationQuery = new WqlEventQuery("__InstanceCreationEvent",
new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");

The above query shall be used to subscribe for WMI events for Win32 process creation.

Now that we have created a query, we need to use the ManagementEventWatcher to assign this query so that we can start listening for the subscribed events. So we create an object of the ManagementEventWatcher for the query that we formed earlier.

ManagementEventWatcher aWatcher = new ManagementEventWatcher(aProcessCreationQuery);

After creating an object of the ManagementEventWatcher, we need to subscribe for the events that willbe raised by the watcher. So we go for,

aWatcher.EventArrived += new EventArrivedEventHandler(ProcessStarted);

Thats it. All we have to do now is just trigger the watcher. We do this by calling,

aWatcher.Start();

This is an asynchronous call and the reply comes thru’ the event, EventArrived. So whenever the OS spawns a process, the event will be raised.

WqlEventQuery might have solved the fore mentioned problem, but I really don’t know how effective it is. If I get to know about them more, I will post it in here.

Written by sudarsanyes

June 25th, 2009 at 7:55 am

Creating a single instance application in C#, WPF

with 2 comments

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.

Written by sudarsanyes

May 24th, 2009 at 3:46 pm

WPF Application creation, an insight — part2

with one comment

Before I can start with part2, a small highlights from part1.

  • All the WPF applications are an object of System.Windows.Application running as a process
  • Visual Studio allows the users to relax from the creation and running of the System.Windows.Application object if you specify the BuildAction as Application Definition
  • Specifying the StartupUri attribute in the App.xaml with a window class allows the developer not to write snippets that will show the top level window

Accessing Application object from window classes

As soon as the Application object is created, it would be set to the Current property of itself. As this property is a static property, any window classes can access the instance of app that is running. Also the application object, as mentioned earlier, shall hold the instances of all the top level windows. So we can even access these top level window object from any class thru’ the Current.Windows property.

class Window1
{
public Window1()  //constructor
{
foreach(Window aTopLevelWindow in App.Current.Windows as Window)
{
MessageBox.Show(aTopLevelWindow.Title);
}
}
}

Shutting down the Application object

While running an Application object is done thru’ Run(), we can shut down the app thru’ Shutdown(). For example, if you want to provider a custom close button in your window, you can close the application (terminate the entire process) using the following snippet,

class Window1
{
...
public void ExplicitShutDown()  //Some method which will explicity shutdown the Application object
{
App.Current.Shutdown();  //Where App is the name of the Application class
}
}

This is called as an explicit shutdown.

Application Events

Here are some of the events of the Application object that can be of great use when you program.

  • Startup — Invoked after the Application object is created and run. You can show your top level windows in here
  • Activated and Deactivated — Invoked when one of the top level windows of the Application object is activated and deactivated will be called when another Application object’s top level window gets activated
  • Session Ending — Invoked when windows session ends either by a shutdown call or a restart call
  • Exit — Invoked when the Application.Shutdown() is called

Hope these two posts helped you in understanding how a WPF application gets instantiated. From my next post I will start writing about controls.

Written by sudarsanyes

May 24th, 2009 at 2:05 pm

Posted in C#, General Programming, WPF

Tagged with , ,

WPF Application creation, an insight — part 1

with 3 comments

Creating a WPF application is really a piece of cake if you have Visual Studio with out. All you have to do is,

  • Start Visual Studio ( >= 2008)
  • Create New Project (project type, WPF Application)
  • Hurrah, we have a WPF application now. Go on, edit your Window1.xaml and press F5 to see your WPF application in action

WHERE ?

Simple isn’t it ?? But there are a series of where questions to be asked in here.

  1. Where is the main function (entry point for the WPF application) ?
  2. How did Visual Studio found out that Window1 is my top level window (parent window) ?
  3. From where did it create the instance of Window1 to show it on the screen ?
  4. *

Lets try to figure out the answers now.

1. Where is the main method ? Answer is fairly simple. Visual Studio has created the main function for the application during the run time. If you notice the solution explorer, there will be two xaml files. App.xaml and Window1.xaml (by default). If you open the properties of App.xaml, one of the settings would be Build Action. This would be set to Application Definition, meaning the WPF application’s start point is this class.

2 and 3. Where is the instance of Window1 ? For this, we need to explore the App.xaml file. As mentioned in the previous inference, App.xaml has been made as the start point thru’ properties, so we need to explore the this file for the startup windows. If you see the code (xaml code),

<Application x:Class="Foo.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
<Application.Resources>


</Application.Resources>
</Application>

the application tag has an attribute called StartupUri whose value is Window1. This means that when the class App is getting instantiated and when the it is run, it should automatically create an instance of Window1.xaml class (as mentioned in the StartupUri attribute) and show it.

But WHY ?

So now that we have found answers for where, we still have a set of why questions to be answered

  1. Why do we need an App.xaml file, can I run my application without it ?
  2. Why did Visual Studio create the main method ? Why can’t I do it ?
  3. Can I show my Window1 myself ? I don’t want Visual Studio to do that
  4. *

Lets figure out the answers now,

1. Can I run my application without App.xaml file ? No. Its not possible.

2. Why did Visual Studio create the main method ? For this we need to understand how the WPF application works. Every WPF application is nothing but an instance of the System.Windows.Application class. To run a WPF application, first we need to create an instance of this class manually. This should be done inside the main method. As the App.xaml has the entry point, it should create an object of the System.Windows.Application and it needs to call Run in that code behind file (App.xaml.cs).

System.Windows.Application myApp = new System.Windows.Application();
myApp.Run(); //Will run the application

Doing so will run the applicaiton. But still we will not be able to see any windows on the screen.

If you notice, the App.xaml class will be of type Application and not Window unlike the Window1.xaml file. Check out the root tag of App.xaml file.

3. Can I show my Window1 myself ? After creating an instance of System.Windows.Application class, we can create an object of the window class (top level window) in the main method and then call Show on it.

Window1 myWindow = new Window1();
myWindow.Show(); //Will show the window on the screen

Atlast, your main method should look something like this,

class Program
[STAThread] //.net norms for com
static void Main()
{
System.Windows.Application myApp = new System.Windows.Application();
Window1 myWindow = new Window1();
myWindow.Show(); //Will show the window on the screen
myApp.Run(); //Will run the application
}

Visual Studio didn’t want its users to mess with all these things. So most of these are done automatically leaving the users just to bother about their application and its user interfaces. Anyways its nice to know about these when you write a WPF application.

In the next post, I will write about System.Windows.Application class

Written by sudarsanyes

May 23rd, 2009 at 10:43 am

Posted in C#, General Programming, WPF

Tagged with , ,

UI designing, guidelines

without comments

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.

Written by sudarsanyes

May 15th, 2009 at 8:58 am

DataContracts and WCF

without comments

Since its very long since I blogged, thought I would write about DataContracts in C#. DataContracts is a part of WCF (A.K.A Windows Communication Foundation). If you are writing an application in C# (.NET) that needs to communicate with a server, how do you do it ?? Thats where WCF and DataContracts comes in to picture.

DataContracts are a common agreement between the client and the server there by allowing them to share the data without sharing the actual type represented by the data. In other words, if the client and server needs to communicate, they needn’t share the same type, rather they need to share the DataContracts.

Soon I will get a sample that explains this concept clearly. Meanwhile, peek in to MSDN’s definition of DataContracts.

Written by sudarsanyes

April 24th, 2009 at 9:37 am

Posted in C#, General Programming

Tagged with ,