Thursday, July 03, 2008

Continuing in my never-ending (at least until day 4) review of Tech Ed, this post will talk about how the second day of the conference went.

At breakfast, I got to sit down at the same table as Sara Ford, a PM at Microsoft on the CodePlex team and a well known for her Visual Studio Tip of the Day series. That experience sort of reinforced the fact that you really do get to interact with the people who are working on the tools that we use every day.

The first session from that day was entitled “Nine Essential Tools for Every Developer.” I left early because I didn’t notice the subtitle that told me the session was actually about Office Power Tools. I don’t currently develop any Office interop applications, primarily because we’re still supporting Office 2000 (if not 97). It wasn’t exactly the most accurate session title.

I attended a session by Drew Robbins on hosting WCF in IIS7. I am seriously excited about IIS7 and it really makes me want to move my development machine from XP to either Vista or Server 2008. It won’t really make a difference because we’re still targeting Server 2003 (and thus IIS6), but it is still awesome. I got a lot more out of this session on IIS7 than I did on WCF hosting. The best part of the session for me was the demo of the IIS7 PowerShell provider.

At lunch, I got to hang out with the TwitterTribe.

TwitterTribe lunch (includes Colin Neller, Scott C. Reynolds, Alan Stevens, and others)

I didn’t catch everyone’s name, but the picture above has (from left) Colin Neller (http://twitter.com/cneller), Scott C. Reynolds (http://twitter.com/scottcreynolds), and Alan Stevens (http://twitter.com/alanstevens) (after the guy in the blue shirt). The guy on the right just out of the picture is Dan Hibbets (http://twitter.com/MobilityMatters). Keith Elder (http://twitter.com/keithelder) swung by later as did Cory Smith (http://twitter.com/DualBrain). I apologize to those that I missed (leave a comment and I’ll add you in, too). We had a lot of fun geeking out and thanks to Alan for organizing it. Alan even put together a poster with the “Twitter is having problems” image so we would know where to meet up. :-)

After lunch, I attended a session by Scott Hanselman on Dynamic Data in ASP.NET. Scott is a great presenter, but you already knew that if you’ve watched any of his sessions or screencasts. This session served as a part 1 to a two part session, but I skipped out on part 2, because I had to catch the session on the Managed AddIn Framework.

The session on MAF with Jesse Kaplan was very exciting to me. Some of the readers will know that the primarily application that I work on dynamically hosts other application in it. I deal with things like Assembly Binding, Assembly Loading, versioning, etc. every single day. I am really excited about System.AddIn. Having the ability to load up addins in separate AppDomains to have isolation from your host to your addin is a great feature. Honestly, I know this could be done before, but the real benefit for us is the ability to host our addins (that have a UI) in a separate AppDomain. Through some very nasty hacking, I was able to get WinForms UI to run in a separate AppDomain from the host WinForms UI, but it was not ideal by any means. If you want to do this sort of thing, look at System.AddIn. I’d like to present on MAF at the user groups in the area at some point, so if you’re at all interested in this, let me know and I’ll see about putting some information together.

That pretty much finishes up my second day of Tech Ed. Just two more days of review left!

posted on Thursday, July 03, 2008 9:26:06 AM (Central Standard Time, UTC-06:00)  #    Comments [0]
 Wednesday, July 02, 2008

I’m continuing my review of Tech Ed from yesterday. Yes I still realize that I’m a month behind. :-)

So, after breakfast, I imagine what everyone will be interested in is the keynote by Bill Gates. Here’s the view I had after sitting down:

Getting ready for Bill Gates' keynote

Woohoo! Below is my great picture of Bill Gates, too. I tweaked the image slightly so that you can spot him.

Tech Ed 2008 2008-06-02 004

Anyway, keynote… yeah. Sort of boring. They started off with the Bill Gates Retirement Video. I think there might have been a little bit more content than the first time it was released, but still, nothing new. There was talk about Oslo, but I wasn’t really interested. I don’t really want modeling tools to improve architecture, when the drag/drop designer tools are leading me away from good architecture anyway. If you’re interested in any more regarding the keynote, check out Herding Code’s overview of the keynote announcements.

The first real session I attended was by Grigori Melnik and he covered Enterprise Library 4. Honestly, my feeling regarding EntLib is way too much XML configuration. I’m also not a fan of the config editor for the configuration. I’d really rather configure it in code or using some DSL support or something. I’m interested in Unity (the one release from Microsoft that got to keep its cool name!) somewhat, though. Unity is Microsoft’s offering in the IoC/DI space. It has gotten some flak, but it really isn’t all that bad from what little I’ve used it. I do like that it is very lightweight and the fluent interface it provides for component registration is pretty good. The session itself was mainly demos, though, so not much content.

I walked into a session by Sara Ford on CodePlex, but I didn’t stay too long because it seemed to be a walkthrough on how to use the CodePlex site itself.

Another session I attended that day was by Jimmy Schementi entitled “Dynamic Languages and the Web.” You can probably guess that this one was primarily on IronRuby. As you might guess, a lot of the talk revolved around how dynamic languages will work with Silverlight. Jimmy pointed out the Silverlight Dynamic Languages SDK which provides tooling for running dynamic languages under Silverlight, including IronRuby, IronPython, and other DLR based languages. It was pretty cool seeing a Rails app running on IronRuby. Jimmy also showed us an IronRuby version of Try Ruby, which runs in the browser with Silverlight instead of having to ship the Ruby commands back to the server to be executed. (note – if you haven’t tried out Ruby, go use the Try Ruby site. It is an excellent introduction into an awesome language)

I spent the rest of that day in Hands on Labs (see my Virtual Labs post to get an idea of the what the HOLs were like) and talking to the Microsoft guys. I spent time talking to a couple of developers on the .NET Framework team (whose names I unfortunately missed) and asked them a little bit about the MAF (Managed AddIn Framework). Their advice on that was to check with Jesse Kaplan (does Jesse have a blog I can link to?) so I did exactly that later in the week. I also spent time talking to them about versioning headaches and how we attempt to deal with breaking changes. It was interesting.

Afterwards, they told me that the MSDN documentation guys were looking for feedback, so I swung by there. I didn’t get much information from them, but I tried to give them a lot of personal feedback on my feelings towards MSDN documentation. I currently still use Google to get to most of the MSDN help. I told them I used the local MSDN help up until Visual Studio 2005, at which point the help application because too slow to use. They seemed very welcome to hear feedback and I really think they’re trying to improve.

All in all, it was a pretty good first day. That night was the vendor party where you basically sold yourself and your contact information for t-shirts and other swag. :-)

posted on Wednesday, July 02, 2008 8:16:40 AM (Central Standard Time, UTC-06:00)  #    Comments [0]
 Tuesday, July 01, 2008

I’m guessing it has been so long since Tech Ed that no one will be interested in hearing how it went, but you know – I’m going to post about it anyway.

I’m planning on doing a blog post per each day of Tech Ed so that I can (hopefully) give each session its due. The first day was the preconference session. The session I attended was entitled “Building Great Web Applications with Silverlight” with Jeff Prosise. The session covered both versions 1 and 2 (only beta 1 though). It was unfortunate that beta 2 wasn’t announced until later that week, so Jeff just got to hint at differences that would be coming out with the next release… which came out a week later. The hints were actually sort of funny, because Jeff was officially under NDA, so he would say things like, “this might change soon… hint, hint.”

The first half of the session was almost entirely getting most people up-to-date with WPF, so it turned into a review session for me. The bulk of what was new for me was better coverage of the network and I/O stack that Silverlight provides, which filled the rest of the session. Silverlight 2 brings a portion of the CLR to the browser (called the CoreCLR) so you have access to WCF and System.Net functionality as well as file I/O access via isolated storage. Threading is also provided so that’s nice. Something interesting to note is that Silverlight won’t provide any synchronous versions of methods that also have asynchronous methods. For example, the System.Net.HttpWebRequest will only provide the BeginGet* methods, not the synchronous Get* methods. The reason for this is because they’re trying to trim everything out that isn’t needed to cut the size of the CoreCLR down. Makes sense to me.

Well, that’s about it for the preconference. Like I said, more of a review than a lot of new information. I did get to have lunch that day with Colin Neller and Robertjan Tuit. Rob was telling us about the hair styling convention that was going on at the same time as Tech Ed. What a combination of conferences – geeks and hair stylists.

That night I attended Party With Palermo. While there, Jay Smith and I talked about a potential ALT.NET Open Spaces event that Raymond Lewallen is planning. I’m not so sure it will be happening in mid-July seeing as it is already July, but who knows? If it does, I’m in! I also got to see Scott Hanselman from across the room. I was telling Colin that I wanted to go up and say hi, but I didn’t really know how to approach Scott without, as Colin put it, “feeling like a groupie.” I mean, seriously, “hey Scott, I read your blog and listen to Hanselminutes and watch your videos and… man, you are awesome!” Missed opportunity I guess.

That does remind me of a funny occurrence that happened that night that I heard about secondhand. The three other guys I went to Tech Ed with were all sitting around at the party and Scott came over to sit by them. As you might imagine, everyone had name tags on. One of the guys sees “Hanselman” on Scott’s name tag and asks Scott if he is any relation to Scott Hanselman. “Uhh, yeah, I’m Scott.” “The Scott Hanselman?!?” Sure am glad I didn’t look like a groupie. At least I recognized him. :-) I told this unnamed individual that he later should have asked Scott to sign one of his books as “the Scott Hanselman.” Yet another missed opportunity! :-)

I’ll see about getting my overview of the rest of Tech Ed up later.

posted on Tuesday, July 01, 2008 7:35:32 AM (Central Standard Time, UTC-06:00)  #    Comments [0]
 Wednesday, June 18, 2008

A couple of weeks ago, I was fortunate enough to attend the Tech Ed 2008 Developer conference. It was my first Tech Ed conference and I had a great time. (Yes, I still need to blog about my experiences there overall and I’m still planning on doing that.) One thing I wanted to bring up if you’ve never been to Tech Ed before is the great experience that the Hands on Labs (HOLs) provided. Basically, you walked up to the HOL computer and, in a few short steps, you had a full development virtual machine ready to go. It was a really nice experience and ensured that you could try out new features without having to set up your own VM or worse, download and install a lot of betas on your own development machine.

Apparently, Microsoft is using the same setup over the web. Maybe I’ve been in the dark for a long time, but I’ve never used a VM in a browser window before. Check the screenshot out:

image

Seriously, look at the browser title – this is in IE. On the right side of the screen, you’ve got the lab walkthrough, too. If you’ve been unable to look at new technology like .NET 3.5, LINQ, WPF, WCF, etc, you should check out Microsoft’s Virtual Labs. The MSDN Virtual Labs are at http://msdn.microsoft.com/en-us/virtuallabs/default.aspx, but TechNet also has labs for things like Windows Server 2008.

image

posted on Wednesday, June 18, 2008 7:01:36 AM (Central Standard Time, UTC-06:00)  #    Comments [2]
 Friday, May 23, 2008

Most of the work I currently do (during the day) is with WinForms applications and most of the time, debugging their problems really isn't all that hard. Application hangs or crashes that only occur on one machine at a remote location are not easy though. We ran into one of those situations a few weeks back. I told our support group that if they saw the hang again to let me know and I would swing by so that we could get a memory dump of the application and start debugging it. Here's everything I did to figure out what went wrong.

First thing, install Debugging Tools for Windows. This will get you things like adplus and windbg. Make sure you pick the right version for your platform (i.e. x86 or x64) because the debugger has to match the platform you're debugging on. I already had it installed on my machine, but I shared the directory so that I could access the tools on the remote machine that was having the hang.

Next, I remoted into the machine with the problem and ran adplus to get a memory dump. To do this, I first copied over the debugging directory to the remote machine from my share. Luckily, the Debugging Tools can be copied and therefore don't need an MSI or setup executable. To get the dump, I pulled up a command prompt, moved to the debugging directory, and ran 'adplus -hang -p 3423' where 3423 was the process ID for the application that was hanging. If you're dealing with an application that is crashing, you would need to pass different arguments in. By the way, note that adplus is just a VBScript - this means that you can open it and see what they're doing if you're so inclined. You can get the PID from either task manager or process explorer.

image

Let this script run to completion and it should create the memory dump (in this case, a minidump) in a directory that looks something like this:

image

I then zipped up this directory and copied it back over to my machine so that the user could get back to work :-) Get back to your desk because you'll be able to do everything else there.

This is where it gets fun, because we get to use WinDbg. Before doing any real work with WinDbg, I would strongly recommend getting your colors customized because it is very hard to spot errors or warnings when all the text is black on white. Check out Tess's post on setting up a custom workspace for WinDbg. I set up WinDbg exactly as she did in the post and it works quite well.

Next, you can open your minidump. Under the File menu, there is an "Open Crash Dump" command that you can use (Ctrl+D for you keyboard guys) so pull that up and open your minidump file. It should look something like this:

image

You can think of WinDbg sort of like a command prompt, even though it has windows and buttons. It is just as user friendly as the command prompt is when you're sitting at the C: prompt. In other words, it isn't friendly at all. In this case, instead of a C: prompt, you have the prompt at the bottom of the screen.

WinDbg starts out as an unmanaged/native debugger, which means you could debug your managed application, but it will be fairly difficult with just native commands. What you need to use is a tool called SOS. John Robbin's, master debugging guru guy, has an excellent MSDN Magazine article on SOS that you should read for more information. My next step was to load up the SOS extension in WinDbg by typing '.loadby sos mscorwks' which tells WinDbg to load the SOS extension from the same directory as the mscorwks assembly was loaded from. (check out this comment for cases when the loadby might not work, such as when mscorwks hasn't been loaded yet)

image

When I typed it in, I unfortunately got an error, though (pasted below for Googlibility, if that's a word).

PDB symbol for mscorwks.dll not loaded
Failed to load data access DLL, 0x80004005
Verify that 1) you have a recent build of the debugger (6.2.14 or newer)
            2) the file mscordacwks.dll that matches your version of mscorwks.dll is
                in the version directory
            3) or, if you are debugging a dump file, verify that the file
                mscordacwks_<arch>_<arch>_<version>.dll is on your symbol path.
            4) you are debugging on the same architecture as the dump file.
                For example, an IA64 dump file must be debugged on an IA64
                machine.

You can also run the debugger command .cordll to control the debugger's
load of mscordacwks.dll.  .cordll -ve -u -l will do a verbose reload.
If that succeeds, the SOS command should work on retry.

If you are debugging a minidump, you need to make sure that your executable
path is pointing to mscorwks.dll as well.

This got me digging for a while to figure out why I couldn't load up SOS. Quite a few other people were curious, too. The gist of it can be summed up in this Microsoft Connect post, which details that you have to have the exact same version of the .NET Framework as the machine where the minidump was taken. In short, I had installed .NET 3.5 on my machine which included patches to .NET 2.0 while the user who was having the problem was a few versions back.

To confirm this, you can use the loaded modules command (lm) to see all of the modules that were loaded at the time of the minidump. I specifically used 'lmv m mscorwks'. The 'v' apparently means details or something and the 'm mscorwks' tells the command to match on modules named 'mscorwks'. Here is the result, with the file version info from my local mscorwks file as well (found in c:\windows\microsoft.net\framework\v2.0.50727).

image

Don't despair if you're in this situation, because I have a solution. Virtual machines! It takes a bit of work, but you can get a VM set up with the same framework version. I started out with blank Windows XP SP2 VM and installed the .NET Framework 2.0 RTM on it. Turns out, I was still off. The below screenshot is from the VM.

image

I was starting to get frustrated at this point, but Doug Stewart saved the day with a couple of posts on .NET 2.0 versions, one on .NET 2.0 revisions and one on the version history of the CLR 2.0. I was able to determine that the problem computer was running a patch from KB928365. I installed the patch on the VM and... SUCCESS! SOS loaded up!

With SOS loaded, you run a lot more interesting and powerful commands from WinDbg, like !threads, !CLRStack, !analyze and more. Here are the basic steps I took to attempt to narrow down what was going on.

I ran !threads, which displayed all of the threads that were running at the time the minidump was taken.

image

You can see that, though it looks like a lot was going on, there really was the main STA thread (the thread that contains the WndProc which pumps the Windows messages) and a lot of system threads like the Finalizer threads and Completion Port threads.

You can switch between threads, by using the ~[THREAD]s command, like ~11s, which switches to the thread with the ID of 11. Once switched to a thread, you can run !clrstack and get the call stack for that thread.

image

It looks like thread 11 was an animation timer. Back on the main thread (STA), it really just looks like normal WndProc activity - nothing too strange.

image

It was looking like I wasn't getting anywhere, so I decided to try something else. I ran the DumpStackObjects (!dso) command, which gives me all of the object instances on the stack.

image

Looks like the application in question was using an Infragistics library, but the thing I was really interested in was the bottom one, the WinFormsAppContext, which was an instance of an ApplicationContext. From that instance, I could run the !do (dump object) command to see details about it.

image

From there, I wanted to find which mainForm it was using. I ran !do on the Value column of the mainForm instance.

image

Nice! Now I know the name of the instance that was loaded! At this point, I've got a much better idea about what is going on and can now start digging through some code to try to determine what it is doing.

The rest of the story is fairly boring because, after opening the offending code, I spotted the problem fairly quickly. The hang, if you even want to call it that, had nothing to do with threading. It just looked like the application was hanging because, in the Form's Closing event, the application in question was cancelling the close and hiding itself. I have no idea why, but I guess that's debugging for you.

To finish off, I'd like to share some excellent debugging resources, particularly with WinDbg.

Hope this helps!

posted on Friday, May 23, 2008 8:57:15 AM (Central Standard Time, UTC-06:00)  #    Comments [3]
 Wednesday, May 21, 2008

I've been meaning to get a local version of my blog running so that I could test changes and tweaks to my theme and I finally found some time yesterday to do that. Can you tell the difference? Basically, I added the social networking links on the right as well as the Tech Ed 2008 badge.

Tech Ed 2008 - Meet Me There

This will be my first time to go to Tech Ed, so I'm excited. I've only been to one other conference and that was devLink last year (which was awesome - I still need to register for this year!). There will be 3 other guys from my company going and I know that Randy Walker and I think Jay Smith will be as well. Anyone else out there going? Let me know in the comments! Also, anyone planning to attend Party with Palermo? I haven't registered yet, but I'm thinking about it.

Speaking of conferences, the Northwest Arkansas area is planning a technology summit. I've missed out on the discussions about it so far but I'm hoping to make the next meeting to talk about it. We'll make sure information gets out regarding the specifics so that everyone can participate.

posted on Wednesday, May 21, 2008 7:18:48 AM (Central Standard Time, UTC-06:00)  #    Comments [0]
 Wednesday, May 07, 2008

A coworker swung by a few days ago to ask some questions about using Reflection. I learn really well by example so I decided to use Powershell to show using Reflection. Below is the session I used and later emailed to him. You can see a few spots at the bottom of the example where I was unsure of the syntax on passing an empty parameter array, but I figured it out.

This is a good example of why I like Powershell :-)

  1 [1] » "haha".gettype()
  2
  3 IsPublic IsSerial Name                                     BaseType
  4 -------- -------- ----                                     --------
  5 True     True     String                                   System.Object
  6
  7
  8 [2] » $temp = "haha".gettype()
  9 [3] » $temp.GetProperties()
10
11
12 MemberType    : Property
13 Name          : Chars
14 DeclaringType : System.String
15 ReflectedType : System.String
16 MetadataToken : 385875994
17 Module        : CommonLanguageRuntimeLibrary
18 PropertyType  : System.Char
19 Attributes    : None
20 CanRead       : True
21 CanWrite      : False
22 IsSpecialName : False
23
24 MemberType    : Property
25 Name          : Length
26 DeclaringType : System.String
27 ReflectedType : System.String
28 MetadataToken : 385875995
29 Module        : CommonLanguageRuntimeLibrary
30 PropertyType  : System.Int32
31 Attributes    : None
32 CanRead       : True
33 CanWrite      : False
34 IsSpecialName : False
35
36
37
38 [4] » $temp.GetProperties()[0]
39
40
41 MemberType    : Property
42 Name          : Chars
43 DeclaringType : System.String
44 ReflectedType : System.String
45 MetadataToken : 385875994
46 Module        : CommonLanguageRuntimeLibrary
47 PropertyType  : System.Char
48 Attributes    : None
49 CanRead       : True
50 CanWrite      : False
51 IsSpecialName : False
52
53
54
55 [5] » $temp.GetProperties()[0].name
56 Chars
57 [6] » $temp.GetProperties()[1].name
58 Length
59 [7] » $temp.GetProperties()[1].GetGetMethod()
60
61
62 Name                       : get_Length
63 DeclaringType              : System.String
64 ReflectedType              : System.String
65 MemberType                 : Method
66 MetadataToken              : 100663629
67 Module                     : CommonLanguageRuntimeLibrary
68 MethodHandle               : System.RuntimeMethodHandle
69 Attributes                 : PrivateScope, Public, HideBySig, SpecialName
70 CallingConvention          : Standard, HasThis
71 ReturnType                 : System.Int32
72 ReturnTypeCustomAttributes : Int32
73 ReturnParameter            : Int32
74 IsGenericMethod            : False
75 IsGenericMethodDefinition  : False
76 ContainsGenericParameters  : False
77 IsPublic                   : True
78 IsPrivate                  : False
79 IsFamily                   : False
80 IsAssembly                 : False
81 IsFamilyAndAssembly        : False
82 IsFamilyOrAssembly         : False
83 IsStatic                   : False
84 IsFinal                    : False
85 IsVirtual                  : False
86 IsHideBySig                : True
87 IsAbstract                 : False
88 IsSpecialName              : True
89 IsConstructor              : False
90
91
92
93 [8] » $temp.GetProperties()[1].GetGetMethod().Invoke
94
95
96 MemberType          : Method
97 OverloadDefinitions : {System.Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo cu
98                       lture), System.Object Invoke(Object obj, Object[] parameters)}
99 TypeNameOfValue     : System.Management.Automation.PSMethod
100 Value               : System.Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo cul
101                       ture), System.Object Invoke(Object obj, Object[] parameters)
102 Name                : Invoke
103 IsInstance          : True
104
105
106
107 [9] » $temp.GetProperties()[1].GetGetMethod().Invoke("hello world", [])
108 Unable to find type []: make sure that the assembly containing this type is loaded.
109 At line:1 char:65
110 + $temp.GetProperties()[1].GetGetMethod().Invoke("hello world", []) <<<<
111 [10] » $temp.GetProperties()[1].GetGetMethod().Invoke("hello world")
112 Cannot find an overload for "Invoke" and the argument count: "1".
113 At line:1 char:47
114 + $temp.GetProperties()[1].GetGetMethod().Invoke( <<<< "hello world")
115 [11] » $temp.GetProperties()[1].GetGetMethod().Invoke("hello world", {})
116 Exception calling "Invoke" with "2" argument(s): "Parameter count mismatch."
117 At line:1 char:47
118 + $temp.GetProperties()[1].GetGetMethod().Invoke( <<<< "hello world", {})
119 [12] » $temp.GetProperties()[1].GetGetMethod().Invoke("hello world", $Null)
120 11
121 [13] »
122

Note - I used the :toHTML command from Vim along with Peter Provost's Powershell syntax file to get the color. Powershell doesn't support color at the console like this yet without explicitly passing color arguments to Write-Host.

posted on Wednesday, May 07, 2008 7:51:00 AM (Central Standard Time, UTC-06:00)  #    Comments [0]
 Thursday, April 24, 2008

(Warning - this post is both a rant against the Mutex as well as a guide for its usage. Also, don't blindly copy code, only the bottom code snippet works. :-) )

I'm a big fan of an API that is so easy to use that I don't have to look at the documentation.

I had to look up the documentation for System.Threading.Mutex... multiple times.

Taking a look at Mutex, I see that it implements IDisposable. Great, that means I can wrap it in a using block.

My first try:

bool createdNew;
using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))
{
    MessageBox.Show("Press OK to release the mutex.");
}

Looks good, right? Nope, that is a big negative. Nowhere does this actually acquire the mutex. When you run this application twice, they both show the message box just fine. Maybe I should actually check the createdNew value?

Let's change the code to look like this:

bool createdNew;
using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))
{
    if (!createdNew)
        mtx.WaitOne();
    MessageBox.Show("Press OK to release the mutex.");
}

However, that didn't work, either. It turns out that the createdNew parameter just tells you if you're the one who created the mutex, not if you currently own the mutex. That is what the purpose for the WaitOne method is for. Of course, the documentation just says that it "blocks the current thread until the current WaitHandle receives a signal." Okay. Well, I'm glad that I now know that it also waits for my thread to acquire a lock on the mutex. (note, if you pass in 'true' as the first parameter, you'll request to be the owner, but you'll only be the owner if the createdNew out parameter comes back with true)

Third try. Third time's the charm, right?

bool createdNew;
using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))
{
    mtx.WaitOne();
    MessageBox.Show("Press OK to release the mutex.");
}

Great, now when I run my app twice, the second one is blocking on the WaitOne call. Cool. You can even tell in the below screenshot, because the button's paint event is blocked and is whiting out (like Solitaire does when you win!).

image

Let's click okay and see if the second form gets the mutex, thus displaying the message. That's weird - the form still isn't responding. Let's close the first form.

image

Ouch! That was unexpected. What? Abandoned mutex? This sounds like I never even released the mutex. Hmmm... ReleaseMutex? Shouldn't that be called from the Dispose (end of the Using block)? Might as well try it.

bool createdNew;
using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))
{
    try
    {
        mtx.WaitOne();

        MessageBox.Show("Click OK to release the mutex.");
    }
    finally
    {
        mtx.ReleaseMutex();
    }
}

Finally! Now, it works like I'm wanting. I'm keeping the using block in place, because that disposes the WaitHandle that Mutex uses (Mutex in face inherits from WaitHandle).

Anyway, I'm hoping there is a reason for the API to be designed in this way, but man, it doesn't seem very intuitive to me.

While learning this, I unfortunately tried putting the Mutex in some of my code without trying it small scale first. After struggling for quite a while, I went to the small application and discovered everything that I've posted here. I hope this helps you with the Mutex when you have to deal with it.

posted on Thursday, April 24, 2008 2:48:19 PM (Central Standard Time, UTC-06:00)  #    Comments [0]

Here is a simple script I wrote which was inspired by this post on terminal color highlighting and by ColorDiff that does essentially the same thing.

# Out-ColorDiff.ps1
Process {
    if ($_) {
        foreach ($line in $_) {
            if ($line -match '^[<|-]') {
                Write-Host -ForegroundColor red $line
            }
            elseif ($line -match '^[>|+]') {
                Write-Host -ForegroundColor green $line
            }
            else {
                Write-Host $line
            }
        }
    }
}

Here is a screenshot of sample output from the script:

image

You can use it by piping the diff output to the script, like 'svn diff somefile | out-colordiff' or if you're stuck using something like MKS, you can use 'si diff somefile | out-colordiff'.

Possible (and easy) additions would be to add direct parsing of a file instead of taking an argument off of the pipeline. This is all I need currently, but if you wish to add more features, feel free to leave them in the comments.

posted on Thursday, April 24, 2008 9:55:44 AM (Central Standard Time, UTC-06:00)  #    Comments [0]

image

(Sorry for the lack of substance with this blog post - I'm hoping that just posting anything will spur me on to post something with substance. Wish me luck.)

posted on Thursday, April 24, 2008 8:06:17 AM (Central Standard Time, UTC-06:00)  #    Comments [0]