Archive for the ‘C#’ Category
DoUNo: XAML gets compiled in to a BAML
What does a xaml file gets compiled in to ? It gets compiled in to a baml (binary xaml). More @ wikipedia.
You can find the .baml file in the \obj\Debug folder.
DoUNo: MDI in WPF
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.
DoUNo: Popup animation in wpf
Every time I try adding a default animation (Slide, Fade, …) to a pop up in WPF, I find it not to be working. Today, I went thru’ MSDN (breaking my laziness
) and found that the popup animation shall work only if the AllowsTransparency of the popup is set to true. Really weird !!
DoUNo: Setting expectations on nullable type, NMock2
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
)
Settings expectations in NMock2
One of our previous articles would have given an introduction to NMocks. In here, we will try out various methods of setting expectations when we do a unit test.
note — this article considers that you know the basics of unit testing. check out our previous article if you would like to know the basics of nmock2
In NMock2, you have a wide variety of setting expectations on mocked objects.
Stubs
Stubs are expectations whose occurrences are unknown. We use stubs when we are not sure the number of times it might be called. So generally Stubs are used when expectations needs to be set 0 or more times
Stub.On(myMockedObject).Method("GetName"); //Use this only when you are unaware of the occurrences, //otherwise you end up writing a bad UT
Expect
We use the Expect class when the number of calls to the method or property of the mock objects are known.
For example,
If number of occurrences are 7 on the method called, “GetName“, then use,
Expect.Exactly(7).On(myMockObject).Method("GetName")...
If the number of occurrence is 1 on the method called, “GetName“, then use,
Expect.Once.On(myMockObject).Method("GetName")...
or
Expect.Exactly(1).On(myMockObject).Method("GetName")...
You can even set negative expectations. For example,
If you are pretty sure that the method “GetName“, will not/should not be called in your unit test, then use,
Expect.Never.On(myMockObject).Method("GetName")...
Expectation With Parameters
If you are unit testing a method that makes a call to an interface which inturn takes two params and if you know the values of those params, you could set expectation on the mock object for the method with the known params.
For example,
If “GetName” method takes two params and if the param values are “foo” and “bar” according to the unit test case, then we can write an expectation as,
Expect.Once.On(myMockObject).Method("GetName").With("foo", "bar")...
Expectation On Events
You can add expectation on events of the mock object with the EventAdd method.
For example,
public class Foo { public event EventHandler ObjectChanged; ... }
public class FooBarBaz { private Foo myFoo; ... private void SomeMethod() { myFoo.ObjectChanged += new EventHandler(Foo__ObjectChanged); ... } }
If you are writing a unit test for the method SomeMethod, then you shall add an expectation of the following form,
Expect.Once.On(myMockObject).EventAdd("ObjectChanged", Is.Anything);
Expecting Exceptions
You could also expect exceprions by adding the attribute, ExpectedException on top of your unit test.
For example,
[Test(Description="Test case method that will test whether the ArgumentNullException is raised")] [ExpectedException(typeof(ArgumentNullException))] public void TestExceptionalScenario() { ... //call the method that is supposed to throw the ArgumentNullException }
These are the commonly used expectations. If you have used something really weird, I expect you share it with us
Accessing Command Prompt from C#
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.
Using NMock2 in C#
As many would know, mocking is a useful and inevitable part of unit testing. The intention behind mocking of objects is to isolate the functionality of one method from its dependencies, For e.g. a method call from within the target test method being handled in an external interface.
This approach will help us focus on the unit being tested, rather than arranging for dependency invocation (which might be really complex at times).
I would like to share a basic tutorial here on mocking .net objects using NMock2 (available at http://nmock.org)
Steps to be followed are as follows.
1) Download the NMock2 package from http://nmock.org/download.html
2) Create a console application and add NMock2.dll from the downloaded package, as a reference.
3) Consider that you have a simple interface defined as follows.
public interface IPerson { string GetName(); }
4) A class Hello has the following definition
class Hello { IPerson person;
//--This method invokes the interface method.
public String Greet()
{
return "Hello " + person.GetName();
//If you were to write a ut for this method (without nmocks), you should have created an
//actual object of person and your inputs should be capable of navigating
//thru' GetName() of Person class
}
}
5) Our intention is to unit test the method Hello.Greet(). This is not straight forward as definition of IPerson.GetName() is not known. Moreover, it should not be of our concern when we are testing Greet() method’s functionality.
6) This is where we mock the Interface IPerson and hardcode a return value for the method GetName() so as to concentrate on the functionality of the method Greet() alone while testing. Let us see how we can do that.
7) We create a test case class, say HelloTestCases and write a method to test Greet()
i) Make use of a class named Mockery (supplied by NMock2) to create a mock object.
ii) Create a mocked interface object for IPerson using the NewMock() method.
iii) Set up a mocked result for any method/property by hardcoding of your choice.
iv) Mock the result for one execution of the mocked method.
v) Create an object of the target test class.
vi) Invoke the target test method using the object instance created in (v) and check the results with Assert statements of NUnit.
public void Test_GreetPositive() { //--i. Creating a mockery object. Mockery personMock = new Mockery(); //--ii. Mocking the IPerson interface using Mockery object. IPerson p = personMock.NewMock<IPerson>(); //--iii. Setting the mocked return value. string returnValue = "Pradeep"; //--iv. Mocking the result for method call IPerson.GetName() method. Expect.Once.On(p).Method("GetName").WithNoArguments().Will(Return.Value(returnValue)); //--v. Creating the target class object. Hello h = new Hello(p); //--vi. Invoking the target test method. Assert.AreEqual("Hello Pradeep",h.Greet()); }
So simple, isn’t it? This was a simple example. There is much more to add as feathers to NMock2.
NMock2 also provides a wide variety of Expectatons, like,
Expect.Once, Expect.Excatly(<number of times a method is called>), Stub (0 or many times), Expect.Never and so on. You could also expect exceptions by adding an attribute called [ExpectedException(typeof(<exception class>)] before the unit test method for the target method that throws an exception. In other words, NMocks2 is really an awesome lib to do a perfect unit test for your libraries. Try it out and share your experiences.
Thanks! See you all soon.
Praseo
DoUNo: When to use StringFormatFlags.DirectionRightToLeft and StringAlignment.Far
Recently I had a trouble displaying some values in a custom painted ListViewControl. I had to display some numbers right aligned. But I mistook this alignment with direction of the string, leading me to write the code as,
theArgs.Graphics.DrawString("100", FONT_ISOVALUE_VALUE, Brushes.Black, new Point(theArgs.Bounds.X + LOCATION_X_OFFSET, theArgs.Bounds.Y + LOCATION_Y_OFFSET), new StringFormat(StringFormatFlags.DirectionRightToLeft));
This was working properly for positive values, but for negative values, the - sign comes after the number. i.e., instead of -100, it was displayed as 100-, thats when I understood the difference between RightToLeft text and right aligned texts. So replacing the above snippet with the following snippet does the work.
StringFormat aStringFormat = new StringFormat(); aStringFormat.Alignment = StringAlignment.Far; theArgs.Graphics.DrawString("-100", FONT_ISOVALUE_VALUE, Brushes.Black, new Point(theArgs.Bounds.X + LOCATION_X_OFFSET, theArgs.Bounds.Y + LOCATION_Y_OFFSET), aStringFormat );
So alignment is different and direction of text is different. Use StringFormat.Alignment for alignment and StringFormatFlags for direction
WMI (Windows Management Instrumentation) in C#
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,
- Create a WqlObjectQuery object with the query statement, SELECT * FROM Win32_CDROMDrive
WqlObjectQuery aWMIQuery = new WqlObjectQuery("SELECT * FROM WIN32_CDROMDrive"); - Create an object of ManagementObjectSearcher and assign the created query to this object
ManagementObjectSearcher aManagementObjectSearcher = new ManagementObjectSearcher(); aManagementObjectSearcher.Query = aWMIQuery;
- Run the query by calling the Get method in the ManagementObjectSearcher
aManagementObjectSearcher.Get();
- 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(); } - 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
ManagementEventWatcher and WqlEventQuery in c#
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.

