Wednesday, December 15, 2010

VB + C# Adventures (Final Part)

Now that I’ve been using C# continuously for my current project, I can honestly say that I can switch between VB.NET and C# easily.  As I’ve said before, I learned .NET in C# a long time ago and personal projects are done in C#, but most of my production experience has been using VB.NET

Do I regret having to use VB.NET?  Not at all, because it’s all about the framework, not the syntax.  I like being able to use both languages and achieve the same outcome.  Of course I can’t say that I know C# inside and out, but I can’t say the same about VB.NET either.  I also feel a sense of pride being able to do more than one language and not complain about it.  I still find it funny when my developer friends say something like “Oh I hate VB.NET.” or “I can program in C# about 3x faster than VB.NET.”

So which language do I prefer?  I have always preferred C# over VB.NET, but I’ve never complained and never will, if I have to use VB.NET for a project.  Sometimes there’s no choice in what language you have to use and knowing both is a useful skill to have.  Maybe one day if we need to develop some kind of math intensive library, F# will be thrown my way :)

Friday, December 10, 2010

Closing a WPF Window Through Your ViewModel

I ran into the issue of properly closing a Window (View) from my ViewModel a while ago.  How does one do this without breaking MVVM or adding too much complexity?  Since I’m developing my current project using Prism and my IUnityContainers are injected into my ViewModels, why not just inject this.Close() also?

/**** Window (View) ****/
public Window(IUnityContainer unityContainer)
   this.DataContext = new ViewModel(unityContainer, this.Close);
/**** End Window (View) ****/
/**** ViewModel ****/
public class ViewModel
   public ViewModel(IUnityContainer unityContainwer, Action closeAction)    
      CloseCommand = new DelegateCommand(closeAction);    
   public DelegateCommand CloseCommand    
      private set;    
/**** End ViewModel ****/

Does this break MVVM at all?  Is testability decreased because I injected the this.Close() method into my ViewModel?  I would argue not since I’ve used the Action delegate.  This seems to be the easiest/simplest way to do what I (and many others) want.  Now there may be some purists out there that don’t want any user entered code in the code-behind, but as you might have guessed, I’m no purist.

Wednesday, December 8, 2010

WPF, MVVM and TextBoxes

Overall, I like WPF and MVVM.  That’s not to say that I think MVVM is a perfect design pattern.  I find myself breaking the purity of MVVM sometimes because I think there’s a lot of compromise needed to do what I want to without adding complexity.

Anyway, one of the biggest gripes about MVVM and TextBoxes is that the data for bound TextBoxes is updated when the TextBox control loses focus.  But that makes sense, right?  Well, what if you’ve updated a TextBox and hit a MenuItem to save your data.  Guess what?  The TextBox doesn’t lose focus and your save takes the stale TextBox data.  Needless to say this is VERY frustrating…

One solution would be to move the focus off of the TextBox like so:

((System.Windows.UIElement)System.Windows.Input.Keyboard.FocusedElement).MoveFocus(new System.Windows.Input.TraversalRequest(System.Windows.Input.FocusNavigationDirection.Next));

You can call that before you actually execute your save command, but even that seems like a bit too much effort to do what should logically be done anyway… I’ve done the above in some of my projects, but there has to be some other way to do what I want…

Instead of using the vanilla Menu control, I turned to Infragistics’ xamMenu.  I was hoping that their menu would take into account something like the issue I was having with my TextBox data.  I was right… sort of.  It turns out that if I use their xamMenu like so:

<ig:xamMenuItem Header="Save">
<MouseBinding MouseAction="LeftClick" Command="{Binding SaveCommand}"/>

The above doesn’t do what I want either… After some experimenting, I found that if I use the vanilla MenuItem elements instead of Infragistics’ XamMenuItem elements, my TextBox data updates and saves.  It seems weird to me that using a combination of the Infragistics xamMenu and the vanilla MenuItem causes the data to update correctly, yet using all Infragistics’ elements doesn’t.

<shrug> In the end I ended up using vanilla Button elements in the xamMenu because using the vanilla MenuItem elements caused spacing issues:

<Button Command="{Binding SaveCommand}" Background="Transparent" BorderBrush="Transparent">
<StackPanel Orientation="Horizontal">
<Image Stretch="None" Source="{StaticResource Image}"/>
<TextBlock Background="Transparent" Margin="4,0,0,0" Text="Save"/>

Wednesday, October 20, 2010

VS2010 IDE vs Stand Alone Execution Weirdness (Mouse Wheel)

So I’m doing some ActiveX Interop with my WPF application.  As most people know, it’s more of a two step process with WPF since you have to host the ActiveX control inside of a WindowsFormsHost object before you can introduce it into a WPF Control or Window.

Anyway, I was testing my component in the IDE and it seemed to be working fine.  Next, I ran the application by itself because it’s faster than through the IDE and I found that my mouse wheel was not working.  What gives? Why would it work properly in the IDE, but not by itself?

I got frustrated and posted a question on the MSDN forums about it.  Since my ActiveX component has license restrictions, I couldn’t provide a proper sample application.  I then got the suggestion to host the Interop component in a Winforms application as a test.  My Winforms sample project works as it should inside and outside of the IDE.

I then tried to just start a simple WPF application with the Interop control and the same behavior occurs as in my main project: Mouse Wheel works in the IDE, but not stand alone.  At this point it seems like it’s a WPF/ActiveX Interop issue.

Another suggestion I got was to use Spy++ to see my component was responding to the Mouse Wheel messages.  I opened up Spy++, but before I did anything I noticed that my application was now handling the Mouse Wheel messages.  Now here’s what’s confusing me, as soon as I closed Spy++, my application stopped handling Mouse Wheel messages again.  Why does the simple fact of having Spy++ open make my ActiveX component work correctly???  I didn’t event start logging the component!

According to Spy++, my component was indeed handling Mouse Wheel messages as indicated by the log and also because the component was scrolling as it should… I’m waiting for a response to my forum post, hopefully someone can tell me what’s going on.

Monday, October 4, 2010

VB + C# Adventures (Part 5)

I Miss This

VB definitely makes certain things easier than C#.  This may go back to the whole VB making me lazy thing, but I miss being able to do this and not having to worry about a null reference exception:


Dim i As Integer = Len(Trim(SomeString))


Note that if the code above were to changed to SomeString.Trim.Length, a null reference exception could occur in either language.

Conversion methods are available in the System.Convert namespace, but in VB you can do the old CBool(SomeObject), CInt(SomeObject), etc.  I’m not saying that using the System.Convert methods are bad or anything, just that I need to get used to certain things. 



I’ll be blunt, I hate sloppy code.  I try to be consistent in my style and cleanliness regardless of the language I’m programming in.  I think that C# definitely has more possibilities as far as clean styles go.  For example:

if (someCondition)
if (someCondition){
if (someCondition)

I find all three of the above styles readable.  However, given the syntactic flexibility of C#, messiness is just as easy:

if (someCondition) DoThis(); if(someOtherCondition) {DoThis();AlsoDoThis();}
int i = 0;

I’ve always hated code that sat on one line, even way back in college when I was learning C/C++.  Sure it can be more succinct, but I find it harder to read.

Thursday, September 30, 2010

My Prism Journey (Part 3)

It’s Me, Not You

WPF’s bare controls are decent, but not always as robust as people need or want.  I initially setup my Shell using the basic Grid component on a Window.  Of course I was and still am in the learning phase, but as my project becomes more “real”, I realize that I should probably start using the components that’ll actually be needed once my project hits our production environment.

Since I’ll be using floating panes, I turned to Infragistics.  We use their controls in many of our WinForms applications so it seemed logical to use them for my Prism project.  I figured this would be easy since Prism can inject views into any control that hosts an ItemControl or ContentControl

There was a bit of a learning curve to get Infragistics’ Dock Manager to work the way I wanted.  Although I was easily able to place ConentControls in the various dock regions, for some reason I couldn’t get the Dock Manager to fill its parent container.  This behavior wasn’t expected because the WinForms equivalent did fill in the area as expected.  I also followed the Getting Started sample from scratch in a new project and the control didn’t fill…

I did some searching and it looked like others were having the same issue.  The post I found was dated 2009 with no answer so I figured that this issue wasn’t resolved.  I was pretty irate that the expected behavior wasn’t implemented over a year later.  I even went so far as to gripe to the boss about it and asked if I could look at other companies’ components.

After my grumbling session, I took a step back.  Infragistics has been in the controls game a long time (remember Sheridan and VB pre .NET?), they couldn’t have let something like this slip.  I did some more searching and I found that all I needed was a single property: LayoutMode=”FillContainer”

Open hand facing upwards and forcefully place forehead into hand…


Views, ViewModels, And Events

Not all applications have simple UIs.  I have a registered library that handles some of my Region management based on certain requirements.  This manager will inject a View+ViewModel into a Region, nothing complicated here.  In my ViewModel I subscribe to certain events, which again is nothing complicated. 

I noticed something odd when I retrieved data through my application.  Every time I retrieved data, the time it took to display multiplied.  At first, I thought it was because my View wasn’t being properly removed from my Region. Nope, the ActiveView count is 0 as it should be.  I then placed break points in my data layer and found the culprit. 

The expected behavior is that if I request data, a new data layer is instantiated, and my data is returned.  However, every time I requested data, a data layer was instantiated, and the data was returned, but the previously instantiated data layer never got destroyed and was also retrieving data! 

This immediately made me look at the fact that I subscribed to a retrieval event, but never unsubscribed from it.  Prism’s event system must have still had a reference to the CallBack and was still calling it.  This explained the multiplicative time increase.  I ended up having to make sure that my Region manager library unsubscribes from any events when removing Views from my Regions

Thursday, September 23, 2010

VB + C# Adventures (Part 4)

Event Handlers

Adding and removing event handlers in VB is pretty straightforward.  I think the syntax, although wordy, lends itself to readability better than its C# counterpart.  In VB for example:

AddHandler o.SomeEvent, AddressOf Handler
RemoveHandler o.SomeEvent, AddressOf Handler

In C#, you’d have to do the following:

o.SomeEvent += new EventHandler(Handler);
o.SomeEvent -= new EventHandler(Handler);

Now the thing that struck me as “funny” was the need to create a new EventHandler delegate (or whatever event handler delegate you created) to remove it in the C# syntax…


Method Parameters Passed By Reference

Since I’m using methods that pass parameters as reference, you have to use the ref identifier before those parameters in C#.  At first this bugged me because I was so used to not having to do it in VB.  But is it necessarily better not having to identify a reference parameter?  I got to thinking about this and I now think it’s good to have to denote it. 

Why do I think so now?  The intent of a parameter passed by reference is to change the parameter itself (of course this has different implications for value types versus reference types).  This can lead to confusion if you don’t know that the variable that you’re passing in can change.  Requiring the ref identifier alleviates this confusion in my opinion.

Tuesday, September 21, 2010

My Prism Journey (Part 2)

Have you registered some types in your bootstrapper like I have?  Through Prism’s Dependency Injection, I’ve been passing the EventAggregator around to my objects as a parameter.  I’ve also passed in some other registered types, but then I got to thinking…why not just resolve it through the UnityContainer?  Instead of injecting all the registered types I need, I can just pass in a single IUnityContainer and resolve all of the types I need.  Pretty slick!

Monday, September 20, 2010

VB + C# Adventures (Part 3)

I ran into a little hiccup today, which I found amusing.  Parentheses use is very important in C#, whereas in VB you can be lazy about them (think method calls).  In my C# project, I was trying to do an object.ToString.ToUpper, but for some reason Intellisense couldn’t didn’t find ToUpper.  Well, given that ToString is a method call, you need to call it as such: object.ToString().ToUpper().  Has VB made me a lazy developer? :)

Optional parameters… I personally never liked them, but they’re pretty ubiquitous in VB land.  It wasn’t until .NET 4 that C# got this language feature.  VB will let you have optional value and reference parameters, whereas C# won’t let you have optional reference/out parameters.  I’m currently using a data access layer written in VB that has a few methods with optional parameters for my C# project and I saw this first hand through Intellisense.  No brackets were present around the optional reference parameters through C#

Friday, September 17, 2010

My Prism Journey (Part 1)

I’m not going to describe what Prism is because you can just do a search :)  I’m going to post my experiences in trying to leverage the Prism libraries to create a modular application.  The tutorials that come with the library are very helpful so people should definitely read the chm file for help.  I’m also trying to be as MVVM as possible so hopefully I don’t completely mangle my application.

One of the components that I’m adding to my application requires COM Interop… yay.  I did the obligatory aximp call on my ActiveX component, but for some reason I got a file not found exception whenever I tried to access the component at runtime.  Adding the references created by aximp didn’t seem to work.

I had to actually create a new WinForms control library, add the component to my toolbox, drag the component to the control, and then I was able to access the component at runtime.  No worries, I just copied the interop dlls and placed them in a folder so that those can be used instead of the aximp generated ones.

To include interop ActiveX components in your WPF application, you need to host the ActiveX component in a WinForms control.  No problem, add WindowsFormsIntegration so you can use the WindowsFormHost control in your WPF app/control.  You can then add the component to the WindowsFormHost.Child and it will display.  Pretty straight forward…

After getting the above sorted out, I got my interop control to display in the specified region in my shell.  However, it was displaying incorrectly… I set the ActiveX.Dock = Fill, but it wasn’t filling the region.  I sat there for a good hour or so trying to figure this one out… No matter what I did, it just wouldn’t fill the damn region

I then decided to create a little test program to see where the issue could possibly be.  I added a WindowsFormHost and a reference to the ActiveX component.  It filled fine!  Ok, maybe it’s because the region in my application is wrapped with a Tabcontrol.  I wrapped the WindowsFormHost with the TabControl and it still filled correctly.  Wait, to add a region to your shell, you need to specify what the region is hosted in, which is either an ItemsControl or ContentControl

It turns out that I used ItemsControls to host my regions (because the tutorial used those as well).  I then tried switching my region hosts to ContentControls and now my ActiveX component fills as it should… Sheesh.

Thursday, September 16, 2010

VB + C# Adventures (Part 2)

We’re using Visual Studio 2010 so all of my gripes, comparisons, etc will be based on that. 

The biggest thing I noticed right off the bat is in the IDE.  C# Intellisense is kind of clunky compared to its VB counterpart.  I found this kind of weird…

C# Syntax

I’m finding myself using parentheses where I should be using brackets, but it’s rare. 

I miss the With construct that’s in VB.

I sometimes declare my variable name before the type.

Semi-colons…don’t forget those!

Curly-braces galore!

I find the syntax to be a bit more cryptic.


VB Syntax

More verbose, but I find it easier to read (this is just personal preference I guess).

Gotta love direct access to My.Settings and My.Resources.

No need to break after every case in Select (Switch) statements.

Delegate parameters need an AddressOf identifier when passing into a method, whereas C# you just pass in the method.

VB + C# Adventures (Part 1)

I’ll be starting a new series documenting my experiences with using VB and C# simultaneously.  This isn’t meant to be a comparison between the languages, but rather just a non-technical (as can be anyway) dump of the things that are going through my head as I use both languages.  I’m sure this has been done before, but this ought to be fun anyway.

Some personal background…

Back when I was in college, I learned C++ as my first language.  Of course there was some minor SPARC assembly (like I really remember any of that…) and later Java as required by whichever classes I was taking.  I had extremely light exposure to VB6 in my senior year in one of my design classes.  We did UML diagrams and we tied it into a VB skeleton with absolutely no requirement to write any code.  I literally wrote zero lines of VB code in that class.

My first professional job was at a mortgage company and the environment was VB6.  It didn’t take long for me to get adjusted, but I found VB6 a little odd as it went against most of the guiding principles I learned in college as to how to write a program.  Anyway, I’m not going to jump onto the “bash VB” train because that train is full…

Since VB6 was on my resume, my proceeding jobs were also related to me using VB6.  I didn’t mind it, but at the same time I wasn’t really learning anything new… I guess you can say that I started getting bored. 

Fast forward to my current job.  When I first started here, I had zero professional experience with .NET.  I’ve always wanted to get into it, but opportunities seemed slim for me given that I had no professional experience in .NET (catch 22…, but it’s worse for game developers).  I did do some studying on my own in C#, but I wasn’t about to lie and say that I had real-world .NET experience.  I was very fortunate to come across a job listing for my current position and also for the fact that Greg gave me a shot.

Jumping from VB6 to VB.NET wasn’t difficult.  I guess it was because I had retained some of the objected-oriented knowledge from college and the syntax between the two wasn’t too different.  I was (and still am) excited to learn something new for a change.  So far, doing things in C# isn’t too difficult for me.  I had some prior experience with C-style syntax already and I know the .NET framework from doing things in VB.NET already.

I feel that a good carpenter can build a great house with any brand of tools you give them.  The same holds true in the case of a good .NET developer (or any developer for that matter).  A good or bad developer will be a good or bad developer regardless of what language they are using.  This is why I really don’t understand the C# snobbery I see a lot of.  Both languages have their pros and cons, but in the end it’s the result that matters.

Tuesday, August 17, 2010

Visual Studio 2010, When “Save All” Doesn’t Mean “Save All”

I found a minor bug related to the Save All functionality while updating our build definitions.  A new project was added to our TFS and this needed to be cloaked for all of our existing build definitions.  No problem, just add the path, set it to cloaked, and copy the line so you can easily paste it in your next build definition without having to pick the path. 

I did this for five of our definitions and I decided to go back to the first one for some reason to double check.  Why didn’t the path get saved?  I hit Save All and didn’t get a prompt when I closed the build definitions, so what gives?  Okay, maybe it was a glitch or something so I did it again, this time I tried using the regular Save instead of Save All.  This time my build definitions were updated. 

It seems like there’s a bug with Save All and updating build definitions.  I submitted the issue to Microsoft, but they want a video… I’m always wary about submitting anything work related to the public domain so I had to decline.  Hopefully the issue gets resolved, but in the meantime if anybody else is having the same issue, just hit Save instead.

Monday, August 9, 2010

The Reappearing Breakpoint (VS2010)

Today I somehow made VS2010 crash in the middle of debugging.  After I reopened my project, I noticed that a breakpoint that I had deleted previously kept on showing up.  Needless to say this was quite confusing since I removed it.  No problem, I’ll just remove it again…

Whenever I ran my application in debug mode, the breakpoint would magically reappear! I thought maybe it was a glitch, so I just closed and reopened my project.  F5 and why is it reappearing when I just deleted it?  Okay, I’ll just shut down VS and reopen it… F5, OMG why won’t you go away?! 

Debug->Delete All Breakpoints fixed it… life’s a glitch.

Wednesday, June 9, 2010

VS2008 to VS2010 Upgrade Notes

UPDATE 6/23/2010:

The issue with one of our setup project builds has been successfully resolved with a workaround that I thought didn’t work at first.  It turns out our Microsoft contact couldn’t reproduce the issue.  It was the end of the day so I decided to shelve this issue until this morning.  I tried running the setup project from my XP machine with the workaround and it worked.  More importantly, I ran it on our build machine and it worked!  The thing that threw me off was that it failed on my Windows 7 development machine, which is where I initially tested the issue.  I suspect it might have to do with the fact that the interop assemblies were actually built on my old XP development environment and that something isn’t jiving now when I use the same assemblies to build on my Windows 7 machine.  In any case, copying the interop dlls to the same path as the vdproj file works like a charm.



Using the latest and greatest development environment is always fun.  However, upgrading from a previous version isn’t always easy.  When we converted our dev environment from VS2005 to VS2008, there were a number of headaches to get everything working properly.  So far, upgrading to VS2010 from VS2008 is proving no different.  Since we’re still on TFS2008, we used this workaround to build VS2010 solutions on our Build machines. 

So after our build machines had VS2010 installed and the above MSBuildPath workaround was applied, I ran my first build.  It was a ClickOnce build and it actually ran without any issues.  The application compiled and everything got copied over to our drop location…Cool!  So then I tried running our MSI build for the same project.  I was expecting it to build fine since the ClickOnce build is a little bit more complex, but the MSI build failed.  After thoroughly checking all settings in the Setup project, I couldn’t figure out why it was failing.  The only reason in the BuildLog.txt was EXEC : error : Unable to update the dependencies of the project.  Could the message be a bit more vague, please?

After searching the web, it seemed others were having the same problem.  The workarounds suggested on that page didn’t work for us.  So instead of waiting around, we decided to open up a support ticket, which our contact at Microsoft is currently looking into.  I had a feeling that Interop assemblies in our project might be causing the problem, but it wasn’t until today that my suspicion was gaining ground.  We have a few projects that have MSI builds, so I went ahead and converted and built those out.  What do you know?  The MSI builds that don’t have Interop assemblies build fine on our build machine.  We’re still waiting for a real solution to this problem, until then, we’re building the MSI package locally for that one project.

Another one of our builds has unit tests.  I ran this project’s build without the unit tests first and it completed.  I then ran the build with the unit tests and 99.9% of the unit tests failed, but not all of them, which was weird to me.  These unit tests passed completely when we were using VS2008, so maybe the MSTest reference needed to be updated or something.  I searched MSDN and found this post about the same exact issue we were having.  I tried the solutions suggested, but they didn’t work.  There were some other odd issues with the build with the unit tests, so I just decided to delete the workspace associated with that build.  After I did this, the unit tests passed and everything looked good.

I hope when we upgrade our TFS2008 to TFS2010, that there aren’t going to be more issues.  I have my fingers crossed…

Monday, April 5, 2010

Running an Interactive Application Through a Windows Service

Have a need to run an interactive application through a Windows Service?  I do and I did a LOT of searching on the Internet and the answer I found was that it can’t be done anymore ever since Windows Vista was released.

A lot of people on MSDN asked this question, but couldn’t seem to get it to work either.  I just assumed that it couldn’t be done since nobody else couldn’t get it to work either. 

Luckily, I asked this question myself on one of the MSDN forums and a MSFT moderator was able to point me to this blog:

Thankfully, Stephen Martin was able to get the problem solved and even has some sample code to show you that it does work as it should.  It’s in C#, but you can always translate it to VB if you need to.  I personally used a converter found here:  The converter isn’t perfect, but it only had a few things that needed to be fixed.

One issue I had though was with running a .cmd file (I imagine the same issue would happen for .com/.bat files also).  For some reason, running the CreateProcessAsUser would show the command window then disappear.  My .cmd file was a long file name with spaces so I thought maybe that had something to do with it.  I included double quotes around my command string like this:  cmd.exe /c “C:\This Is a Long Path\command.cmd”  The .cmd file would not run. 

Scratching my head, I put the above string in the Windows Run and tried to run it.  It wouldn’t run here either… I then tried putting the .cmd file in the root of my C:\ and tried running it like this: cmd.exe /c “C:\command.cmd”  This ran fine.  I figured that since both CreateProcessAsUser and Windows Run were having the same issue, it was a good thing. 

After much playing around with the string and a lot of frustration, I tried the following: cmd.exe /c “”C:\This Is a Long Path\command.cmd”  This worked… I’m not too sure why the double quotes are needed twice before the long file name though…  This also works with the .cmd file that was in the root of my C:\ like this: cmd.exe /c “”C:\command.cmd”

Thursday, March 11, 2010

WinForms/WPF Interop ElementHost Not Drawing The WPF Control!


It turns out it wasn’t externalizing the WPF control that solved the issue, but rather changing my build configuration to Release instead of Debug.  When I added the externalized assembly, I set the configuration to Release.  I’m not sure exactly why a debug build would cause this behavior…


<Edit 2>

It seems to work properly on Windows XP regardless of the build configuration.  Might be a Windows 7 thing…

</Edit 2>

I’ve been doing a lot of WPF work lately and a lot of it has been with WinForms interoperating with WPF.  Today I noticed some odd behavior when I tried to add a WPF control to a WinForms ElementHost object…

Usually I put the WPF control in a separate assembly, but today I thought I didn’t need to since it was just a very simple control.  Immediately I saw that the WPF control wouldn’t draw itself properly for some reason.  It would only draw itself sometimes, but if i clicked on the WPF control and somehow hit a Button or ComboBox, the control would show up.

I then decided to try and put the simple control in its own assembly and that solved the problem… It looks like there’s some issues with including a WPF control in a WinForms project directly, in my case anyway.  I’m using Visual Studio 2008 on Win7 x86 and if anybody else has this type of issue, try doing what I did to resolve the issue.