Rob Kraft's Software Development Blog

Software Development Insights

Archive for the ‘Visual Studio 2010’ Category

The Correct Way to Re-Throw An Exception – .Net Tip

Posted by robkraft on March 6, 2013

When catching and re-throwing an exception, you should include the original exception as a 2nd parameter.  Including the original exception may provide a deeper stack trace that will assist you with solving the exception.

This syntax may not include the full stack trace.

This syntax may not include the full stack trace.

In the code above, if an error occurs in methodWithoutCatch(), the call stack returned will show “methodWithTryCatch” as the deepest method in the stack.

System.Exception: Additional Error Info: blah blahObject reference not set to an instance of an object.
at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 34 at WindowsFormsApplication6.Form1.button1_Click
This example will include the full call stack.

This example will include the full call stack.

However, if you include the original exception in the throw as shown in the second throw example, then the call stack returned will show “methodWithoutCatch” as the deepest method in the stack.

System.Exception: Additional Error Info: blah blahObject reference not set to an instance of an object.
---> System.NullReferenceException: Object reference not set to an instance of an object.
at WindowsFormsApplication6.Form1.methodWithoutCatch(String z) in ...\Form1.cs:line 40
at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 29
--- End of inner exception stack trace ---
at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 35
at WindowsFormsApplication6.Form1.button1_Click

Including the original exception as the second parameter of your new exception provides you with a better call stack.  In this example, it allows you to determine that the error occurred in the methodWithoutCatch method.  In the first case, you are left wondering if the methodWithTryCatch really caused the error, or if one of the three methods it called (method1, methodWithoutCatch, or method3) caused the error.

Posted in Code Design, Visual Studio 2005, Visual Studio 2008, Visual Studio 2010 | 1 Comment »

Binary Serialization Notes in .Net 4.0

Posted by robkraft on December 5, 2011

I ran into a problem using binary serialization recently.  Some of the objects that I was serializing were really large.  By really large I mean that they were 2,000,000 bytes long instead of the expected 2,000 bytes long.  I could not find a good source of information about binary serialization other than this fine article:  http://www.diranieh.com/NETSerialization/BinarySerialization.htm
But even that article left we with questions.  I ended up writing tests to find my answers.  Here are my notes:

  • In Binary Serialization, fields are serialized (in XML serialization they are not).
  • Properties are serialized in both Binary and XML.
  • In Binary Serialization, if you add a property for the field, the field and property are not both serialized (at least for simple properties).
  • Static fields and properties are not serialized.
  • Private fields ARE serialized in Binary Serialization.
  • Properties without setters (ReadOnly properties) are not serialized.
  • Make sure that you do not serialize events.  That is what caused my objects to grow 1,000 times larger.

Make sure to apply this attribute to any events you define:
[field: NonSerialized]
public new event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

We also wrote unit tests to make sure our objects did not experience unintended excessive growth in the future:

   1:  [Test]
   2:  public void TheSizeOfOneModuleShouldNotExceed25000bytes()
   3:  {
   4:  var module = ModuleList.GetByModuleID(3);
   5:  long lBuffer = 0;
   6:  using (MemoryStream buffer = new MemoryStream())
   7:  {
   8:   BinaryFormatter formatter = new BinaryFormatter();
   9:   formatter.Serialize(buffer, module);
  10:   lBuffer += buffer.Length;
  11:  }
  12:  Assert.That(lBuffer, Is.LessThan(25000));
  13:  }

				

Posted in Coding, Visual Studio 2010 | Leave a Comment »

How to tell Visual Studio 2010 to open files in the correct window when you double-click

Posted by robkraft on April 28, 2011

I tend to tolerate minor annoyances in order to focus on more important tasks I want to accomplish. Recently though I finally got tired of my documents opening in the wrong window in Visual Studio when I double-clicked on them. Generally this occurs when I do a find across all files, and the find results pane is docked in a shorter window at the bottom of Visual Studio 2010. When I double-click on one of the lines in the Find Results pane, it opens the intended document in the same lower window, not the larger window on top where I generally view the source code I am interested in. It took me a little while to resolve this and to tell Visual Studio to open the windows in the top pane instead of the bottom pane. The fix is simply to select ‘Reset Window Layout’ from the Windows menu in Visual Studio 2010. I guess that menu option could also be called “Make Visual Studio open documents correctly again.”. I don’t know why my window layout began misbehaving in the first place.

Posted in Visual Studio 2010 | 17 Comments »

How to programmatically switch to a new pivot item in Windows Phone 7

Posted by robkraft on April 3, 2011

I hope the title of my article does not mislead you, but I just learned today that you cannot programmatically change which pivot item is displayed in the pivot control from your C# code. Apparently this is a known bug:
http://stackoverflow.com/questions/4541020/pivotcontrol-item-changing-behavior-in-silverlight-windows-phone-7.

Unfortunately for me this is a fairly devasting problem because my whole user interface (UI) is based on the Pivot Control and I needed my search function in the application to send me to a specific PivotItem. But code like this does not work:

PivotControl.SelectedIndex = 3;

I spent an hour or two before I started writing my application trying to decide if a Pivot Control or non Pivot based UI would work best. Had I known that the pivotcontrol was not working as expected, I certainly would have not used it. Fortunately I have also been writing unit tests and using MVVM on this project which is going to make putting an entirely different UI on the application relatively simple. I estimate 2 to 8 hours. Of course since I only work on this on the evenings and weekends the calendar time is going to cost me a week.

I am using the latest Microsoft Phone Developer SDK (release in February 2011). Hopefully the next SDK will fix this bug.

Posted in Code Design, Silverlight, Visual Studio 2010 | 3 Comments »

Clean up all the old versions of DLLs on your development PC

Posted by robkraft on December 24, 2010

Sometimes I desire to clean up all the old copies of my DLLs from my computer in order to insure that I am testing the correct and current version.
Using the great tool “Search Everything” from VoidTools.com, I have found that I often have a lot of detritus in the following folders:
1) The Global Assembly Cache (GAC)
1a) In .Net 2.0, I could find the GAC at c:\windows\assembly and delete my files
1b) In .Net 4.0, the GAC is at C:\WINDOWS\Microsoft.NET\assembly in multiple sub-folders
2) The temporary ASP.Net file cache
2a) This is located at a folder with a name like C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
3) If you develop with Silverlight, then you may find a history of every version of Silverlight DLL file you created at:
C:\Documents and Settings\%loggedInUser%\Local Settings\Application Data\assembly\dl3
4) Clear your browser cache
5) Look for DLLs in all of your bin and obj folders.  “Search Everything” is great for this purpose.

I clean up much of this with a batch file like this now:

cd “C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files”
rd /S /Q root
rd /S /Q vs

c:
cd “C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files”
rd /S /Q root
rd /S /Q vs

c:
cd “C:\Users\rkraft\AppData\Local”
rd /S /Q temp

c:
cd “C:\Users\rkraft\AppData\LocalLow”
rd /S /Q temp

c:
cd “C:\Users\rkraft\AppData\Local\Microsoft\VisualStudio\12.0\Designer”
rd /S /Q ShadowCache

c:
cd “C:\Users\rkraft\AppData\Local\Microsoft\VisualStudio Services\5.0\”
rd /S /Q Cache

Posted in Coding, Free tools, Visual Studio 2010 | Leave a Comment »

Using the same Strong Name Key (.snk) file for multiple projects.

Posted by robkraft on December 21, 2010

Yesterday I tried to re-use an existing Strong Name Key file (.snk) on other projects by navigating to it in the Signing tab of the project properties. When I did this, Visual Studio copied the .snk file to the local project folder and referenced it. This is not what I wanted.  I wanted all of my projects to reference the same .snk file from the same folder to make it easy to change it for all projects at once.

In order to use the same .snk file for many projects, first add the .snk as a relative Link file reference to each project. You do this by right clicking on the project, select Add Existing Item, navigate to the snk file, select the item and choose the “Add as Link” option from the Add dropdown on the right side of the Add button. Then go to the Signing tab in the project properties and select “Sign the assembly” and choose the .snk file (which you should not need to browse to).

Visual Studio 2010

Posted in Visual Studio 2010 | 1 Comment »

Running Nunit post Visual Studio 2010 and .Net 4

Posted by robkraft on July 1, 2010

Prior to our upgrade to Visual Studio 2010 and .Net 4 (which also forced us to upgrade Nunit), we were able to easily launch nunit.exe from a visual studio project by setting the “Start external program” property on the debug tab to the nunit.exe.  From there, we could set break points and step through our nunit  tests.  But after all of our upgrades, we find that setting break points and doing step through debugging is not so convenient, though certainly still possible.

For starters, we need to specify that our projects launch nunit-x86.exe instead of nunit.exe in the “Start external program” of our projects.  Then you can run the project which will launch nunit-x86.exe.  Before running a test, go to Visual Studio and select “Attach to Process” from the debug menu.  Select the process named nunit-agent-x86.exe.  Then you should be able to set your breakpoints and hit them for step through debugging.

If you find the above does not work, check the following:

1) Use task manager to kill any instances of nunit-agent-x86.exe.  This can easily be left hanging in memory if you stop a test by ending the debugging session in Visual Studio rather than closing the nunit-x86.exe through its normal program close method.  If nunit-agent-x86.exe is already running you are likely to see a message “System.ApplicationException” “Unable to find test  in assembly”.  “Assembly Not Loaded”.

2) If you are still unable to hit breakpoints, then open nunit-x86.exe and go to the Tools – Settings and select the Assembly Reload section under the Test Loader section.  Make sure that only the “Reload when test assembly changes” option is checked.

Happy debugging!

Posted in Visual Studio 2010 | Tagged: , | Leave a Comment »

Reading from the registry with Silverlight.

Posted by robkraft on May 20, 2010

Yes, you can read from the registry of the local machine using a Silverlight application.  This is subject to these qualifications:

1)     The Silverlight App must be running out-of-browser.  This is necessary so that you can run the Silverlight App with elevated permissions.

2)     The Silverlight App must be running with Elevated Permissions.  This is necessary so that you can access the COM Interop.

3)     The COM Interop Automation Factory must be available.  Honestly, if you are running out of browser with elevated permission I don’t know why it would not be available.

4)     You must be running Silverlight 4.

To do this for yourself:

1)     Create a new Silverlight Application in Visual Studio 2010

2)     Open the Project Properties, select the Silverlight tab, and check the box for “Enable running application out of the browser”.

3)     Click on the “Out-of-Browser Settings” button and check the box for “Require elevated trust when running outside the browser”.

4)     Place a simple button in the Grid your MainPage.xaml.  Use the default name button1.

5)     Paste this code:

          private void button1_Click(object sender, RoutedEventArgs e)

          {

              if (App.Current.IsRunningOutOfBrowser)

                   MessageBox.Show(“Running Out of Browser!”);

              if (App.Current.HasElevatedPermissions)

                   MessageBox.Show(“Has elevated Perms!”);

              if (AutomationFactory.IsAvailable)

                   MessageBox.Show(“Automation Factory is Available!”);

              dynamic WshShell = AutomationFactory.CreateObject(“WScript.Shell”);

               MessageBox.Show(WshShell.RegRead(@”HKLM\SOFTWARE\Microsoft\Silverlight\Version”));

          }

6)     Run the app, right-click on the form and choose “Install ..appname… onto this computer…”

7)     Click the button on the “out-of-browser” version of the app.  Hopefully you receive all the expected values.

Posted in Visual Studio 2010 | Tagged: , | Leave a Comment »

Our upgrade to Visual Studio 2010 encountered more problems than we expected

Posted by robkraft on May 18, 2010

Our upgrade to Visual Studio 2010 encountered more problems than we expected. We are developing Silverlight applications for resale using Visual Studio 2008, Silverlight 3 and Blend 3. After doing a little research we devised an upgrade plan to migrate to Visual Studio 2010, .Net 4, and Silverlight 4. Our basic upgrade sequence was correct, but we neglected to include steps for upgrading Nant, Nunit, and Microsoft Patterns and Practices. Also, as of this post, we have not succeeded to get our applications to work on Silverlight 4. I’ve included the upgrade plan we now recommend at the end of this article. In between here and there are the issues we faced with each task and our resolutions.

Visual Studio 2010

I don’t recall any problems with the installation of Visual Studio 2010 or opening our projects and running them there.

.Net 4
We encountered more problems than expected, particularly with the conversion to .Net 4.
Tip 1) When converting projects to .Net 4, start with the projects in the solution that have the most dependencies, such as an .exe. Work your way down toward the dll that has the most dependencies, doing several builds along the way. Check in the changes made so far after each successful build.
Tip 2) Keep an eye on the projects you have changed, particularly if you try to have multiple instances of Visual Studio open. I frequently found that some projects I had converted to .Net 4 lost their changes. This may be because I had two solutions opened at the same time, but each had some of the same dependency projects.
Tip 3) Be careful if you open a Visual Studio command prompt. Make sure you choose a VS 2010 command prompt instead of a VS 2008 command prompt.
Tip 4) In a few cases, the update to .Net 4 did not update some of the referenced system files to their .Net 4 equivalent. Of course, the project won’t compile, and you will need to manually change the reference. This happened to me a few times with the System.Data and System.Data.Extensions DLLs.

Our project files (.csproj) have post-build events in them. Some of the changes we had to make were:
1) To put a file in the GAC, change it from:
  C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\gacutil
  to
  C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\gacutil
2) To register an assembly in the post build event, change it from:
  C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\regasm.exe
  to
  C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\regasm.exe
3) and possibly also:
  C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\tlbexp.exe
  to
  C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\tlbexp.exe

Some of our projects could not compile because they used System.Data.OracleClient which is deprecated in .Net 4. We were able to convert those projects to using the DLLs from Oracle with a few hours of work.

Some of our Visual Basic projects would not compile due to this error:
The error is warning BC42353 or BC42025
“Function ‘IsExcludeField’ doesn’t return a value on all code paths…

Some attributes are deprecated and won’t compile like RegistryPermissionAttribute.

Nant:
Nant’s gac-install was not working for .Net 4, so we converted all of our gac-install tasks to run the gacutil.exe using “exec program” instead. In hindsight, this was not necessary. The real problem was that our modifications to the nant.exe.config file were incorrect. We are now using the nant.exe.config we found at http://pastebin.com/KxqFA8T6

Nunit:
We were running on Nunit 2.4. We realized after the fact that we needed to upgrade to Nunit 2.5.5.10112. I encourage you to upgrade to Nunit 2.5 prior to your upgrade to VS2010. We had a few tests begin failing simply due to differences between Nunit 2.5.5 and 2.4.

We used to run Nunit tests from within Visual Studio by having our nunit test projects launch the Nunit.exe. This option is more complicated now that our application is on .Net 4 because Nunit is a .Net 2 app. It is still possible for Nunit to run tests built in .Net 4, but now, after we launch our application from Visual Studio we need to go back into Visual Studio to the Debug menu, select Attach To Process, and attach to the nunit-agent process in order to debug/step through our nunit tests.

We had to change our nant build process to reference the reference the new directory we installed nunit to and also to specify the correct framework version:

1) <property value=”c:\program files\NUnit 2.4\bin” />
to <property value=”c:\program files\NUnit\bin\net-2.0″ />

2)<property value=”v2.0.50727″ unless=”${property::exists(‘framework.version’)}” />
to <property value=”v4.0.30319″ unless=”${property::exists(‘framework.version’)}” />

 3) on commandline for nunit-console:

… /output=mytests.txt /labels

to

… /output=mytests.txt /labels /framework=net-4.0

Managing the GAC
The GAC has changed in .Net 4 and Microsoft has not documented it well (IMHO).

The most (perhaps only) reliable way to manage the GAC on your PC for .Net 4 is the command line tool gacutil. If you open the assembly folder (c:\windows\assembly), you will not see any .Net 4 assemblies, nor is there a .Net 4 Assembly Configuration tool (yet).

I do see that you can open c:\windows\assembly\Download to see your .Net 4 assemblies. But on my machine several of my assemblies are in there multiple times with the same version numbers. And some are marked private and some are marked shared. I don’t know what to make of all of that.

I have gotten good at running this command to dump the GAC contents to a text file which I then open with notepad:
Gacutil /l > c:\gac.txt
Notepad c:\gac.txt
To add a file to the gac I use:
Gacutil /if MyFileName.dll
To remove a file from the gac I use (no .dll extenstion):
Gacutil /u MyFileName

Microsoft Patterns & Practices Logging Framework:
We run one of the programs built on our framework from a network drive. But after our upgrade to .Net 4 this program failed to run from the network drive. We tracked the error down to an inability to load the Microsoft Patterns and Practices (P&P) Logging Framework DLLs. The problem occurred because all the DLLs in our framework use strong name keys, but the P&P DLLs do not. This was not a problem prior to .Net 4; but it is now. Instead of obtaining the P&P source code, adding SNKs, and compiling them ourselves, we obtained the recently released 5.0 version of the P&P DLLs. We had to make a minor code change, and we had to change all of our config files from version 3.1.0.0 to version 5.0.414.0. We also now deploy five P&P DLLs instead of the three we needed in the previous version of P&P.
Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
to
Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

Silverlight 4
I recommend that developers avoid installing the Silverlight 4 runtime until after they are on VS2010. I upgraded one machine to the Silverlight 4 runtime and then was no longer able to debug my Silverlight 3 application in VS2008.
At this time, we have not successfully converted to Silverlight 4.
When you convert to Silverlight 4, it is best to convert all the projects in the solution to Silverlight 4 at the same time. In a few cases, Visual Studio did not correctly upgrade the System Dlls and we had to unreferenced them, then re-reference them. Our application uses the Csla.net framework. We experienced a problem when running our app and the problem only occurs in release mode. Apparently Silverlight 4 release mode optimizes the data sent down to the client such that our serialized values don’t all make it to the client. We tried upgrading from Csla 3.8 to Csla 3.8.3; and we also tried converting all of our private static propertyinfo methods in our business objects to be public. This latter action did cause our application to get past several errors, but the application still fails to return all the data to the client in release mode most of the time. We are still working on resolving this.

If we were to do our upgrade again, this would be our conversion plan:

1) Upgrade to Nant 2.5 and upgrade your config files for Nant to support .Net 4 (http://pastebin.com/KxqFA8T6). Test build processes.
2) Upgrade to the most current version of the Microsoft Patterns & Practices Logging Framework. For us, version 5.0.414.0 (http://entlib.codeplex.com). Test build processes and deployed application from build.
3) Upgrade to the most current version of Nunit (http://nunit.org). Run all tests.
4) Upgrade one developer to Visual Studio 2010.
5) That developer should convert all projects and solutions to VS 2010 and test them.
6) Upgrade all other developers to Visual Studio 2010.
7) Upgrade the build server to Visual Studio 2010, convert all the projects and solutions on the build server to VS 2010, and test the build process. Check in all changes to the subversion repository. Developers update from subversion.
8 ) Have one developer upgrade all projects to .Net 4 and test.
9) Make changes to build processes for .Net 4, build, deploy, and test.
10) All developers update from subversion to get .Net 4 versions of projects.
11) Have one developer upgrade to Silverlight 4 and test. Make sure to test with Release mode compiles!
12) Make changes to build processes for Silverlight 4. I don’t think we had any.
13) All developers update to Silverlight 4.

Posted in Dev Environment, Visual Studio 2010 | Leave a Comment »

How to group files in partial classes under one file

Posted by robkraft on May 9, 2010

I’ve always liked that the separate files (designer and cs) comprising my aspx pages were grouped together under one aspx. Did you know that you can group any files together under one specific file? You can modify the project file and add the DependentUpon element to any include file and specify the name of the file it is dependent upon.

In Visual Studio 2010, you can do this more easily with an Extension. Go to Tools/Extension Manager, Online Gallery, and find VSCommands 2010 and install it.
This should open a web page with a quick description of the features this add-in provides. (Grouping files, open in blend, copy as link, etc.).

Posted in Free tools, Visual Studio 2010 | 1 Comment »