Archive for the ‘Tips ‘n’ Tricks’ tag
Transparent background with opaque controls on top of it in wpf
Ever felt like having a transparent window background and still opaque controls inside the window? It can be easily done in wpf.
- Set the window’s AllowsTransparency to True
- Set the window’s Background to Transparent
- Add a Rectangle to the parent panel of the window
- Set the opacity of the rectangle to some value < 1 (0.7, …)
- Add your controls to the parent panel
- You are one step away form seeing a transparent background with opaque controls on top of it. Go ahead, run the application now
Sample window,
<Window x:Class=”BackgroundWindow.Transparent.Samples.WPF.Window1″
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Title=”Window1″ Height=”300″ Width=”300″ AllowsTransparency=”True” Background=”Transparent” WindowStyle=”None”>
<Grid>
<Rectangle Fill=”Gray” Opacity=”0.7″ />
<Button Width=”100″ Height=”100″>Click this on</Button>
</Grid>
</Window>
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
)
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.
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.
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.
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.
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.

