Windows – Desktopography 2009 Win7 theme

The most interesting feature in Windows 7 is changing the desktop wallpaper after given time. With this feature we don’t have a boring wallpaper all time and I like it very much. I can create myself a theme and add many wallpapers that I like and let themselves changed after 15 minutes. And every time when I minimize all of working windows and I’ll see an other wallpaper, that’s just a … small change but anyway it makes my computer more exciting than before. Microsoft offers a lot of themes too. You can find them at following link http://windows.microsoft.com/en-US/windows/downloads/personalize but none of them pleases me.
I have tried a lot of theme (my own one and the others) but what I like at most is theme with Desktopography wallpapers which I choose from the gallery of Desktopography. They are really amazing wallpapers and even can be the best wallpapers of 2009. Therefore I would like to share my theme pack, it is pretty large, about 50 MB but I think it’s worth to download and install as your win7 theme. My own pack is larger but I delete some of wallpapers before sharing because the size is so large. It’s about 80 MB at original size.

Desktopography 2009

You can download it at following link
Mirror 1: http://www.megaupload.com/?d=K033U3E0
Mirror 2: http://ugotfile.com/file/791246/Desktopography2009.themepack
I really respect what the authors of this wallpapers have done. Not only how they design and use color but also their imagination. How can they draw such scenes in their brains? My grandfather always tell me that I should read more fictional novel to improve my imagination. He says that science is good but without imagination human can make any inventive step. I think my grandfather is right because a lot of scientific projects are trying to make some imaginative things to be real.

C# – Catch USB plug and unplug event

When I am making review about session 0 and windows service, I would like to write a small example to detect the plug and unplug event of USB stick and attach it to windows service. I used ManangementEventWatcher class to subscribe to temporary event notifications based on a specified event query. This query is type of WqlEventQuery class which represents a WMI event query in WQL format.

WqlEventQuery weqQuery = new WqlEventQuery();
weqQuery.EventClassName = "__InstanceOperationEvent";
weqQuery.WithinInterval = new TimeSpan(0, 0, 3);
weqQuery.Condition = @"TargetInstance ISA 'Win32_DiskDrive'";

The WMI Query Language (WQL) is a subset of the American National Standards Institute Structured Query Language (ANSI SQL)—with minor semantic changes. This initialization above is equivalent to the WQL below where as __InstanceOperationEvent serves as a base class for all intrinsic events that relate to an instance.

string strQueryString =
@"SELECT *
FROM __InstanceOperationEvent
WITHIN 3
WHERE
TargetInstance ISA 'Win32_DiskDrive'";

__InstaceOperationEvent is a type of WMI System Classes. The WMI system classes are a collection of predefined classes based on the Common Information Model (CIM). Unlike classes supplied by providers, the system classes are not declared in a Managed Object Format (MOF) file.
Objects from the system classes are used to support WMI activities, such as: event and provider registration, security, and event notification. Some objects are temporary, and some are stored in the repository as instances of the system classes
. For more information about WMI System Classes you can read at following link http://msdn.microsoft.com/en-us/library/aa394583%28VS.85%29.aspx

After declaration of query event we can now bind it with a listener

 m_mewWatcher = new ManagementEventWatcher(msScope, weqQuery);
m_mewWatcher.EventArrived += new EventArrivedEventHandler(m_mewWatcher_EventArrived);
m_mewWatcher.Start();

In the code handling EventArrive, we’ll check out if the event relates to USB.

static void m_mewWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
	
	bool bUSBEvent = false;
   
	foreach (PropertyData pdData in e.NewEvent.Properties)
	{
		ManagementBaseObject mbo = (ManagementBaseObject) pdData.Value;
		if (mbo != null)
		{                    
			foreach (PropertyData pdDataSub in mbo.Properties)
			{
				if (pdDataSub.Name == "InterfaceType" && pdDataSub.Value.ToString() == "USB")
				{
					bUSBEvent = true;
					break;
				}
			}

			if (bUSBEvent)
			{
				if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
				{
					Console.WriteLine("USB was plugged in");
				}
				else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent")
				{
					Console.WriteLine("USB was plugged out");
				}
			}
		}
	}
}

The complete of working source code you can download at “USB plug and unplug event“. You can expand the application by attach it to a windows service.

UPDATE 12.04.2012

Get disk name of USB Device after being plugged in.

...
if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
{
	Console.WriteLine("USB was plugged in");

	//Get disk letter
	foreach (ManagementObject partition in new ManagementObjectSearcher(
"ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + mbo.Properties["DeviceID"].Value
+ "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
	{
		foreach (ManagementObject disk in new ManagementObjectSearcher(
					"ASSOCIATORS OF {Win32_DiskPartition.DeviceID='"
						+ partition["DeviceID"]
						+ "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
		{
			Console.WriteLine("Disk=" + disk["Name"]);
		}
	}
}
...

C# – Catch Exception of a thread

During our development we must handle with a lot of errors. Working with multitasking, handling exceptions turn to be a little complex. In multi-threading the exceptions can not be cross-thread accessed, they can only be caught from the thread which code is running on.

public static void Main() 
{
	try 
	{
		new Thread (Go).Start();
	}
	catch (Exception ex) 
	{
		// We'll never get here!
		Console.WriteLine ("Exception!");
	}
}

static void Go() 
{ 
	throw null; 
}

In the code above, we never land to the code where we catch exception in main function. The try/catch statement in example above is effectively useless, and the newly created thread will be encumbered with an unhandled NullReferenceException. This behavior makes sense when you consider a thread has an independent execution path. The remedy is for thread entry methods to have their own exception handlers. So what should we do if we want to catch exception? I would like to enumerate some cases which I deal with exceptions of thread.
1. BackgroundWorker
The BackgroundWorker provides us a simple way to handle with exceptions. It’s pretty easy to catch them. If the operation raises an exception that your code does not handle, the BackgroundWorker catches the exception and passes it into the RunWorkerCompleted event handler, where it is exposed as the Error property of RunWorkerCompletedEventArgs.We just need to handle as example below

void m_bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
	if (e.Error != null)
	{
		lblException.Text = e.Error.Message;
	}
	else if (e.Cancelled)
	{
		lblMessage.Text = "Canceled";
	}
	else
	{
		lblMessage.Text = e.Result.ToString();
		btnStart.Text = "Start";
	}
}

2. Normal Thread
This solution only works in case of windows form because we must call the Control.Invoke to call back to main thread and handle exceptions at main thread. To implement this solution, we just declare a delegate and its correlative method.

public partial class frmMain : Form
{
	public delegate void CatchExceptionDelegate(Exception ex);
	public delegate void UpdateResultDelegate(double dResult);

	public frmMain()
	{
		InitializeComponent();
	}

	private void CatchException(Exception ex)
	{
		lblException.Text = "Catch exception from main thread :" + ex.Message;
	}

	private void UpdateResult(double dResult)
	{
		lblException.Text = dResult.ToString();
	}
	private void btnSqrt_Click(object sender, EventArgs e)
	{   
		Thread thCalculateSqrt = new Thread(new ParameterizedThreadStart(SqrtCalculate));
		thCalculateSqrt.Start(txtNumber.Text);         
	}

	public void SqrtCalculate(object nNumber)
	{
		try
		{
			double dArg = Convert.ToDouble(nNumber);
			double dResult = Math.Sqrt(dArg);
			Math.Sign(dResult);
			this.Invoke(new UpdateResultDelegate(this.UpdateResult), dResult);
		}
		catch (ArithmeticException ex)
		{
			this.Invoke(new CatchExceptionDelegate(this.CatchException), ex);
		}
	}
} 

As you can see, it’s pretty simple. The complete source code you can download “Catch thread exception

3. Global exceptions
From .NET 2.0 onwards, an unhandled exception on any thread shuts down the whole application, meaning ignoring the exception is generally not an option. Hence a try/catch block is required in every thread entry method – at least in production applications – in order to avoid unwanted application shutdown in case of an unhandled exception. This can be somewhat cumbersome – particularly for Windows Forms programmers, who commonly use the “global” exception handler, as follows

static void Main()
{
	Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
	Application.EnableVisualStyles();
	Application.SetCompatibleTextRenderingDefault(false);
	Application.Run(new frmMain());
}

static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
	throw new NotImplementedException();
}

The Application.ThreadException event fires when an exception is thrown from code that was ultimately called as a result of a Windows message (for example, a keyboard, mouse or “paint” message) – in short, nearly all code in a typical Windows Forms application. While this works perfectly, it lulls one into a false sense of security – that all exceptions will be caught by the central exception handler. Exceptions thrown on worker threads are a good example of exceptions not caught by Application.ThreadException (the code inside the Main method is another – including the main form’s constructor, which executes before the Windows message loop begins).
The .NET framework provides a lower-level event for global exception handling: AppDomain.UnhandledException. This event fires when there’s an unhandled exception in any thread, and in any type of application (with or without a user interface). However, while it offers a good last-resort mechanism for logging untrapped exceptions, it provides no means of preventing the application from shutting down – and no means to suppress the .NET unhandled exception dialog.

How to install Add-on for Firefox without caring version compatibility?

Yersterday Firefox has released his beta 5 for version 3. I’m using FF 3 beta 4 which I write a review before and this update was automatically made, so I am forced to use the newest version. And as consequence my Adblock Plus add-on doesn’t work anymore in this new version. But I would like to use it anytime when I surf net so that I do not have to see the bad advertisements on web. So I try to find a way to handle with this problem…

First I go to the development site of Adblock Plus to download the latest version of this add-on, try to install it on FF 3 beta 5 but… naturally I doesn’t work. A message was popped up telling that an incompatible version was happened

Error Message

So I click right on the link and download it to my machine to research later. The extension of file is a .xpi extension, I rename it to .zip so that I can see what kind of files are in this package. After renaming I extract all files to a directory.

Directory

You see there are 2 files relating with the install process of Adblock Plus. Because of the incompatible version I believe that there must be a constant variable containing the version of Firefox so that Adblock Plus can check its compatibility. So I opened up the javascript file install.js and search with the keyword “3” for the version of FF. I found some but they are not related to version of FF.

Then I opened the install.rdf file with Notepad. Notepad is really a strongest tool which I see. For file with unknown extension I usually use it to open and it can read 80% of the cases. I search again with the keyword “3” and found an interesting XML tag 3.0b5pre .

Max Version

I just change it to 3.0b6, save file and zip all files again, rename it to .xpi extension. Try to install and at last I have my Adblock Plus add-on again with my newest Firefox.

Although this method works in some cases but in most of cases it doesn’t work because of the invalid signing of the add-on. You will receive an error “Signing could not be verified”. To handle this problem we need to add some new options into configuration of Firefox.

In address bar of Firefox, type about:config and enter.

* Click button “I’ll be careful, I promise” otherwise we can not access the configuration of Firefox.
* Right-click anywhere. Choose New>Boolean.

Boolean

* Make the name of your new config value extensions.checkCompatibility and set it to false.

Set Name

* Make another new boolean pair called extensions.checkUpdateSecurity and set the value to false.
* Restart Firefox.

After adding these values you can install any add-on which you like without caring of version compatibility. However when you access Firefox add-on website, you can not install them because Firefox checks the version to allow which add-ons can be installed.

Deactivate

To activate this install we go to configuration site again through about:config. Filter to find this key “general.useragent.extra.firefox”, modify its value to 2.0.0.13. Restart Firefox and now go to add-on site again; you can install the add-ons without any problem.

Remember to change the general.useragent.extra.firefox to the real version of Firefox after installing add-on so that you can be updated with new patches from Mozilla.You can try yourself with your add-on. Maybe you will find some problems when doing like I do. Then post a comment here we can discuss about them.