What Was I Thinking?

Follies & Foils of .NET Development
posts - 86 , comments - 254 , trackbacks - 0

Visual Studio

Issues related to Visual Studio and the .NET Framework
Resharper: Add “Locate in Solution Explorer” to the Code Window Tab Context Menu
I Love Resharper’s Find In Solution Explorer command. It locates the currently active code file in the solution explorer. Using my keyboard layout I can activate it using Shift+Alt+L, but most times I prefer to select it from the context menu of my code window tab, you know, this thing: Here’s how I added it: From the Tools menu select Customize On the Customize dialog click the Commands tab Select the Context Menu Radio button In the Context Menu drop down, scroll to the bottom and locate Other ......

Posted On Thursday, February 6, 2014 1:52 AM | Comments (0) | Filed Under [ Visual Studio ]

How can I include my derived class type name in the serialized JSON?
Sometimes working with the js Serializer is easy, sometimes its not. When I attempt to serialize an object that is derived from a base, the serializer decided whether or not to include the type name. When its present, the type name is represented by a ___type attribute in the serialized json like this: {"d":{"__type":"Commerce.In... The missing type name is a problem if I intend to ship the object back into a web method that needs to deserialize the ......

Posted On Thursday, June 30, 2011 8:35 PM | Comments (2) | Filed Under [ Visual Studio ]

QuickTip: Determine if Type implements IEnumerable<T>
I was working on a project that required a determination if the type was an IEnumerable collection of some type. Using a bit of reflection and the handy-dandy GetGenericTypeDefinition method, I arrive at this: Code Snippet public static bool IsIEnumerableOfT(Type type) { return type.GetInterfaces().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof (IEnumerable<>)) ; } Happy Coding ......

Posted On Thursday, April 28, 2011 8:26 AM | Comments (10) | Filed Under [ Visual Studio ]

QuickTip: Selecting Children from a Parent Item in Linq
I’m posting this here because I keep forgetting the syntax, and thought others might benefit as well. Given : public class ParentItem { IEnumerable<ChildItem> Children } Selecting all the childitem instances from an IEnumerable<ParentItem>: var allChildren = ParentItems.SelectMany(pare... Selecting matching childItem instances from an IEnumerable<ParentItem>: var selectedChildren = ParentItems.SelectMany(pare... ......

Posted On Tuesday, March 29, 2011 3:47 PM | Comments (1) | Filed Under [ Visual Studio ]

Fixing LINQ Error: Sequence contains no elements
I’ve read some posts regarding this error when using the First() or Single() command. They suggest using FirstOrDefault() or SingleorDefault() instead. But I recently encountered it when using a Sum() command in conjunction with a Where(): Code Snippet var effectiveFloor = policies.Where(p => p.PricingStrategy == PricingStrategy.EstablishFl... => p.Amount); When the Where() function eliminated all the items in the policies collection, the Sum() command threw the “Sequence contains no ......

Posted On Tuesday, February 15, 2011 8:59 AM | Comments (8) | Filed Under [ Visual Studio ]

Making Cross-Domain / Cross-Protocol Ajax calls with flXHR, jQuery & ASP.NET
If you attempt to make an ajax call that cross domain or protocol boundaries, the default XHR (XmlHttpRequest) processor will fail. The out-of-the-box implementation forbids crossing boundaries. Enter flXHR. A flash-based proxy that implements (and extends) the XHR API. That’s good news for JQuery developers. It means you can use flXHR just like the native Jquery XHR. There’s also a Jquery proxy plugin that makes it SIMPLE. You can download the sample here. In my example, I’m hosting the website ......

Posted On Tuesday, January 18, 2011 2:10 PM | Comments (0) | Filed Under [ Visual Studio ]

Fixing “ResGen.exe" exited with code–1073741701” in Visual Studio 2010
I found this fix online which appears to have resolve this issue, so I wanted to share it here. I take no credit/responsibility for it, except to say that it has resolved the issue for me. Set the 32-bit flag on resgen.exe a. Open a Visual Studio command-prompt as an administrator b. Navigate to the Microsoft SDKs\Windows\v7.0A\bin directory. c. ***SAVE A COPY*** of your original resgen.exe file. This is very important if you want to be able to replace our tweak with the original file without having ......

Posted On Tuesday, November 23, 2010 11:59 AM | Comments (2) | Filed Under [ Visual Studio ]

QuickTip: Don’t rely on HTTPPostedFile.FileName
Supposedly, HTTPPostedFile.FileName is supposed to contain just the name of the uploaded file. It should exclude the original filename path. This doesn’t always appear to be the case, and seems to vary by the browser doing an upload. To avoid the browser issue entirely, use a FileInfo(HttpPostedFile.Fil... to return just the file name (and extension) portion of the file. Change this: Code Snippet var saveFileName = Path.Combine(UploadedFileSe... FilePackage.PostedFile.File... to this: ......

Posted On Friday, November 5, 2010 8:57 PM | Comments (1) | Filed Under [ Visual Studio ]

ASP.NET Data Binding from a Latebound IEnumerable<T>
Many of the examples of databinding use datasource or objectsource controls. I prefer to databind from the code-behind. I feel I have finer control over how to data is prepared before I load it. The downside to doing this “late binding” of the data, and I can’t use the strongly typed names in my declarative markup. The following code fails because the compiler can’t resolve the “Products” reference. Code Snippet <asp:DataList ID="DataList1" runat="server" RepeatColumns="1" DataSource='<%#Products%... ......

Posted On Friday, October 8, 2010 10:17 AM | Comments (3) | Filed Under [ Visual Studio ]

Using ThreadPoolHelper Syntax
Code Snippet ThreadPoolHelper.QueueUserW... arg2, arg3, (localArg1, localArg2, localArg3) => { /* code block */ }); ......

Posted On Tuesday, September 28, 2010 11:06 AM | Comments (1) | Filed Under [ Visual Studio ]

QuickTip: Specifying user credentials when installing a service.
I recently attempted to install a windows service I had created. I created an installer and deployed the msi to the target machine. When I ran the setup I was prompted for the username and password credentials for the identity to run the service. I had a local account created. The account was permissioned correctly and had been granted the rights to logon as a service. After supply the credentials, the I received the following error: Error 1001. The account name is invalid or does not exist, or the ......

Posted On Saturday, September 25, 2010 6:43 PM | Comments (0) | Filed Under [ Visual Studio ]

Solved: “The name 'GridView1' does not exist in the current context” after renaming the page / namespace
After I renamed the page and namespace for my aspx page, I started getting a compilation error: “The name 'GridView1' does not exist in the current context”. This was odd since the aspx codebehind and inherits attributes were in sync with the aspx.cs and aspx.designer.cs files. So what was wrong? During my rename operation, Visual Studio (or possibly ReSharper) excluded the designer file from my project. I hadn’t noticed because I usually work with the “Show All Files” option enabled in my solution ......

Posted On Sunday, September 19, 2010 6:17 PM | Comments (2) | Filed Under [ Visual Studio ]

Solved: Unit/Integration Testing of a WCF Service
I've got a solution to running and debugging unit tests for WCF hosted services that utilize the CMServiceHost. Whether your generate your serivce proxy via WSDL (Add Service Reference) or Shared Contract (ClientFactory), the solution is similar. This email will detail how to invoke a WCF Service Host for testing in both scenarios. Testing a service client generated via "Add Service Reference" I'll illustrate the solution using the following sample unit test. Let's assume you've created a service ......

Posted On Thursday, September 16, 2010 8:06 AM | Comments (0) | Filed Under [ Visual Studio ]

HOW TO: Add Copied Projects Back Into TFS
Here’s a recent post I made to the MSDN Forums and the reply which quickly fixed my problem. I’m posting it here, because I didn’t find it anywhere else on the web. I'm in the process of migrating projects from one solution to another. I've created the new solution, and copied the project files from their current disk location (a subdir of the old solution's folder) to their new disk location (a subdir under the new solution's folder). I then tried to add the application to TFS. The application was ......

Posted On Thursday, September 16, 2010 7:51 AM | Comments (1) | Filed Under [ Visual Studio ]

QuickTip: Turn off CSS Validation Errors
I'm working on a prototype of a Single Sign On (SSO) solution for a web portal using Windows Cardspace as the authentication mechanism. This means I've spent my weekend developing web sites which may explain my foul mood. I was applying some color attributes to some of my UI controls which rendered fine, but generated compiler errors because they were failing CSS Validation. Since it renders without issue (even between browsers), I'm not sure why its an error at all. In any event these errors were ......

Posted On Monday, March 17, 2008 5:03 PM | Comments (4) | Filed Under [ Visual Studio ]

QuickTip: Clean up Visual Studio's Recent Project List
We recently revised the organizational structure of some source code, and as a result projects now resided in new locations on disk. I've a big fan of the MRU list, and make use of it often in visual studio (both via the File->Recent Project/Solution menu option and the quick links available on the VS start page). The reorganization of my code base orphaned this links. I was unable to locate a UI for managing this list within visual studio, but did locate the source of these lists in my window's ......

Posted On Sunday, February 17, 2008 10:47 PM | Comments (7) | Filed Under [ Visual Studio ]

Supporting Request Timeout with a WebClient
I recently needed to adjust the timeout value of the HTTP Request being generated by WebClient. My attempt to perform a POST of a large file over HTTP was causing the WebClient to timeout. I thought adjusting the timeout value for the web client would fix this problem. One problem, the WebClient doesn’t support a Timeout value. I did some snooping via Reflector and discovered 2 important facts about the WebClient. Fact #1, The WebClient isn’t sealed. This means we can inherit from it. Fact #2: The ......

Posted On Tuesday, September 14, 2010 12:52 PM | Comments (6) | Filed Under [ Visual Studio ]

Launching ASP.NET WCF Service Hosts for WCF Unit Tests
My solution contains a number of projects; including a contract, service, host, and unit test assemblies. I host my services in ASP.NET web sites, which I run via my dev web server (cassini), and then IIS when I deploy to my production and test environments. My start up project is the Host project, so when I press F5, my service host starts and my services become available. When I want to unit tests my WCF Services however, the service host doesn’t start. I’ve specified the Host Project to Always ......

Posted On Tuesday, August 10, 2010 10:29 PM | Comments (5) | Filed Under [ Visual Studio ]

.NET 3.5 Certification Exam Beta is Still Available
Microsoft has extended the deadline for the .NET 3.5 technologies certification exam betas. There are certification tests available for WCF, WPF and Windows Workflow. You can take the exams for free, if you pass they will count towards your overall MS certification. Interested? Read more about it here ......

Posted On Friday, January 25, 2008 1:57 PM | Comments (6) | Filed Under [ Visual Studio ]

FIX: Visual Studio Post Build Event Returns –1 when it should not.
I had written a Console Application that I run as part of my post build for other projects.. The Console application logs a series of messages to the console as it executes. I use the Environment.ExitCode value to specify an error or success condition. When the application executes without issue, the ExitCode is 0, when there is a problem its –1. As part of my logging, I log the value of the exit code right before the application terminates. When I run this executable from the command line, it behaves ......

Posted On Thursday, May 27, 2010 12:00 PM | Comments (0) | Filed Under [ Visual Studio ]

Solving “XmlSchemaException: The global element '<elementName>' has already been declared.”
I recently encountered this error when I attempted to consume a new hosted WCF service. The service used the Request/Response model and had been properly decorated. The response and request objects were marked as DataContracts and had a specified namespace. My WCF service interface was marked as a ServiceContract and shared the namespace attribute value. Everything should have been fine, right? [ServiceContract(Namespace = "http://schemas.myclient.co... public interface IProductActivationService ......

Posted On Wednesday, April 14, 2010 10:01 AM | Comments (6) | Filed Under [ Visual Studio ]

CoolCommands for Visual Studio 2010
Gaston Milano has just informed me that he has a new version of CoolCommands for Visual Studio 2010. In addition to all the existing commands, the new release, now called CoolX, supports Context Explorer shell commands, support for multiple monitors and new features to help tame the Project Reference beast. Check out all the info including a download, available here –>http://visualstudiogal... I’m also hosting a version for download ......

Posted On Wednesday, March 24, 2010 8:27 AM | Comments (0) | Filed Under [ Visual Studio ]

My Website (ports) Have Been Hijacked!
This is one of the scary problems that turns out to have a pretty easy solution. I tried to view one of my websites hosted by IIS on my primary workstation and the site wouldn’t render. I checked IIS Admin and the site was there, but I couldn’t access it on either port 443 or port 80. In reviewing the event log I found the following entry: The World Wide Web Publishing Service (WWW Service) did not register the URL prefix http://x.x.x.x:80/ for site 1. The site has been disabled. The data field contains ......

Posted On Monday, March 15, 2010 9:09 AM | Comments (0) | Filed Under [ Visual Studio ]

How to get Pre-Build Event support for Web Site Projects
In Visual Studio (2008) Web Site Projects do not support pre/post build events. Web applications do, but web sites do not. This doesn’t mean you can’t have pre/post build events however. You just have to be a little creative. In my scenario, I needed a pre-build event to fire. 1. I added a new class library project to my solution and configured its post build event to execute the pre-build event I wanted. 2. I added a project dependency on the Web Site of the new class library. Right click the solution ......

Posted On Saturday, January 30, 2010 4:01 PM | Comments (1) | Filed Under [ Visual Studio ]

Running Batch Files from the Solution Explorer in Visual Studio
If you want to run a batch (.bat) file from within Visual Studio, you need to add an external tool. From the Tools menu select External Tools, and then click Add. Fill out the values as illustrated below: Click OK to close the dialog. Now you can select the bat file to run in solution explorer, and select the Run Batch File command from the Tools menu. The output of the batch file will be echoed to the output window inside visual studio. <Revised 6/2/10> You can also run .bat files from the ......

Posted On Thursday, January 28, 2010 12:29 PM | Comments (2) | Filed Under [ Visual Studio ]

Deploying Sub folders for VS Unit Tests
My unit test project uses a app.config file that has external source references to other config files located in my “configuration” folder. My configuration folder is a sub folder of the unit test project. When the unit test runs, I need to deploy this folder to the TestResults/Out folder so the app.config can be properly loaded during test execution. Here’s the easiest way to accomplish deploying folders to the TestResults folder: Right click on the .testrunconfig file in your solution explorer. ......

Posted On Thursday, January 28, 2010 12:10 PM | Comments (0) | Filed Under [ Visual Studio ]

QuickTip: Did You Know??? Auto-Adding Dictionary entries
When adding an item to a dictionary, I always thought you had to use the Add() method, like this: string key = "MyKey";int value = 20;var myDictionary = new Dictionary<string, int>();myDictionary.Add(... value); Apparently, you can directly reference it in the collection, and if the key doesn’t exist, its auto-added to the collection string key = "MyKey";int value = 20;var myDictionary = new Dictionary<string, int>();myDictionary[key] = value; most likely you already knew this. I did ......

Posted On Monday, October 19, 2009 4:21 AM | Comments (2) | Filed Under [ Visual Studio ]

Exception & Fault Handling in WCF
I am considering writing a policy based error handler for WCF. The Error handler would be registered with the service host, and would automatically log all exceptions. WCF Services would “opt-in”/register for this error handler by a custom attribute. Deciding how to handle the unhandled exceptions is the policy part. The policy could state which exception types to convert to handled WCF faults, which exception types to map to different fault/exception types, which exceptions to obfuscate and which ......

Posted On Thursday, July 9, 2009 3:12 AM | Comments (0) | Filed Under [ Visual Studio ]

QuickTip: Attach the VS Debugger to IIS’s Worker Process in a single keystroke
I’ve been spending a lot of time lately debugging through some web-hosted applications. Some of these applications are hosted by Visual Studio’s own internal web server (Cassini), and others are hosted by my local instance of IIS. Web projects hosted locally get automatic attached to the VS debugger when you press F5. Projects hosted under IIS do not. In order to debug IIS hosted projects, you must attach the Visual Studio debugger to the IIS worker process (aspnet_wp.exe or w3wp.exe) manually. Traditionally, ......

Posted On Friday, October 30, 2009 8:45 AM | Comments (3) | Filed Under [ Visual Studio ]

QuickTip - Flatten strings to a comma delimited list
Ever need to convert a List of strings in a comma delimited list? In the past I'd write a foreach loop. Something like: public static string FlattenStringList(List<s... items) { StringBuilder str = new StringBuilder(); bool firstOne = false; foreach (string item in items) { if (!firstOne) str.Append(","); else firstOne = false; str.Append(item); } return str.ToString(); } Now, thanks to String.Join and Linq, I can compress it to a single expression: string.Join(",", items.ToArray()); Also ......

Posted On Tuesday, December 23, 2008 1:03 AM | Comments (0) | Filed Under [ Visual Studio ]

Iterating Static Fields / Properties
Often during development I end up with "Constants" classes, classes of constant or static values that I want design time Visual Studio intellisense support for, and run-time domain checking. Consider the following class: public static classConstants { public static classClaimTypes { internal static stringClaimTypeNameSpace = "http://schemas.wtfsolution... public static stringFirstName = ClaimTypeNameSpace + "firstname"; public static stringLastName = ClaimTypeNameSpace ......

Posted On Wednesday, July 9, 2008 10:27 PM | Comments (0) | Filed Under [ Visual Studio ]

Clean Up WCF Clients : The Right Way
As I've done more and more WCF work recently, I've noticed an intermittent problem running my unit tests. The host seemingly hangs for no obvious reason. Eventually the connection times out and produces the following in the service log: System.ServiceModel.Communi... System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934... Stopping the host and client and re-running the test allows it to pass without issue. The problem is related to the way ......

Posted On Friday, May 23, 2008 5:12 PM | Comments (12) | Filed Under [ Visual Studio ]

Developing Windows Services
I've been developing and debugging a windows service for my current project. Working with a Windows service is very much like working with a console app, with the startup and shutdown logic separated into the servicebase's start and stop methods. Debugging a Windows Service Unlike a console app, however Visual studio can't run a windows service and automatically attach the debugger (no Run-with-Debugger (F5) support). Not to fear, its easily enough to attach the debugger to the windows service. In ......

Posted On Saturday, May 10, 2008 11:48 AM | Comments (0) | Filed Under [ Visual Studio ]

QuickTip: Case Insensitive Dictionaries
I've often thought about making my own implementation of a Dictionary<K,V> where the key values are case insensitive. Its been one of those things on my ever-growing to-do list. I usually end up casting the key values to all uppercase and try to encapsulate all my calls the the dictionary with my own logic that performs the case conversion. A case insensitive dictionary would avoid all that nastiness. Sometimes it's helpful to read the tooltip overloads. As I coded a new dictionary instance ......

Posted On Wednesday, April 30, 2008 3:28 PM | Comments (2) | Filed Under [ Visual Studio ]

QuickTip: Debugging VBS Files with CScript.exe and Visual Studio
This is another one of those "Posted here for MY convenience" tips. You can use the Visual Studio Debugger to debug a .vbs (vbscript) file executed with cScript.exe by using the //X flag at the command line. To debug MyTest.vbs cscript.exe MyTest.vbs //X The //X will set a breakpoint and invoke the "select a debugger" dialog where you can choose Visual Studio and step into your vbs code. I haven't found a way to directly edit from the debugger however, so I end up having to debug, break execution, ......

Posted On Monday, April 14, 2008 11:26 AM | Comments (10) | Filed Under [ Visual Studio ]

QuickTip: Performing work on a new thread using anonymous delegates
I know this is available other places on the web, but I'm posting it here because I often have to search for it. This tip is more for my benefit than others :) class Program { public static void Main() { Thread t = new Thread(delegate() { SayName("Lou","Costello"); }); t.Start(); } protected static void SayName(string firstName, string lastName) { Console.WriteLine(firstName + " " + lastName); } } ......

Posted On Monday, April 7, 2008 8:39 PM | Comments (1) | Filed Under [ Visual Studio ]

HowTo: Set up your project for Window's Workflow (C# style)
Any C# project can contain Workflow definitions. They're just code file and/or XAML files. The trick is getting Visual Studio to recognize the project as supporting worfklows for design-time support and compilation. To enable a project for Windows Workflow,: Open the project in visual studio. If you're using source control check out the project file so it becomes writable In the Solution Explorer, right click and select Unload Project . The project tree will disappear from the solution explorer and ......

Posted On Saturday, January 19, 2008 11:31 AM | Comments (3) | Filed Under [ Visual Studio ]

XMLSerialization - Solving the "Type Not Statically Known" exception
.NET's XMLSerializer can be pretty stupid. It refuses to serialize an object if its properties are of a derived type. Consider the following example: [Serializable]public classPerson{ public stringFirstName { get; set; } public stringLastName { get; set; }}[Serializable]public classSalesReceipt{ publicPersonCustomer { get; set; }}[Serializable]public classEmployee:Person{ publicDateTime DateOfHire { get; set; }}public classtrythis{ public voidmain() { Employee employee = newEmployee{ DateOfHire = ......

Posted On Thursday, January 17, 2008 1:07 AM | Comments (4) | Filed Under [ Visual Studio ]

QuickTip: How to determine if a type implements an interface
This is the functional equivalent of a "type is anothertype" but for interfaces: public static bool TypeImplementsInterface(Type type, Type interfaceType) { string interfaceFullName = interfaceType.FullName; return type.GetInterface(interface... != null; } ......

Posted On Wednesday, January 16, 2008 3:37 PM | Comments (3) | Filed Under [ Visual Studio ]

Workflow Validation Exception: Condition Not Found
Recently I migrated one of my solutions from .net 3.0 to .net 3.5. For the most part the migration went smoothly, except for an issue with the type provider, and XAML activated workflows that included accompanying .rules files. I was able to load and work with the workflows in the Visual Studio designer, but they would fail execution at runtime: line 402 error 1342: Activity 'PersistWasSucessful' validation failed: Can not find the condition "ParticipationSaved". ---> System.Workflow.ComponentMo... ......

Posted On Wednesday, December 12, 2007 8:29 AM | Comments (10) | Filed Under [ Visual Studio ]

How to Serialize an Interface using the XMLSerializer
The short answer is you can't. At least not without some trickery and giving the serializer some help, and even then it's not pretty. Here's the plain-jane implementation. Note: The following snippet WILL NOT WORK public interface IWorker { string WorkerName { get; set; } } [Serializable] public class ImplementedWorker:IWorker { #region IWorker Members public string WorkerName { get; set; } #endregion } [Serializable] public class WorkToDo { public IWorker Worker; } public void Tryme() { WorkToDo ......

Posted On Wednesday, January 16, 2008 10:17 AM | Comments (9) | Filed Under [ Visual Studio ]

Working with Thread.Abort()
This is an adaptation of the code from the MSDN help file. I prefer it to calling Thread.Abort() as a first chance approach for terminating a thread. A word of caution: It looks as though the ThreadAbortException skips over any finalization code that might occur inside of the executing thread. For example, the background threaded code was using an IDisposable resource (like a reader/writer), I don't believe the finalizer gets called on the resource, leaving it open. In my example, I've added a flag ......

Posted On Tuesday, January 15, 2008 5:37 PM | Comments (0) | Filed Under [ Visual Studio ]

QuickTip: Resize All Your ListView Columns with a single Keystroke.

Just when you think you know all you can know about something..  Ctrl+Plus (on the number pad) will auto resize your ListView columns.  Go ahead, try it!  You know you want to.

Posted On Tuesday, January 15, 2008 5:14 PM | Comments (0) | Filed Under [ Visual Studio ]

Resource String Editing Made Easy
I'm working on a project that involves building a library of string resources. Some of these resource values are small, consisting of a sentence or two, other resources are actually embedded XSL's, and can be quite lengthy. Visual Studio's built-in resource editor might suffice for other resource types, but is painfully inadequate for a large resource strings. My experience with the Visual Studio editor involves waiting 45-70 seconds for the initial data grid of strings to load, and another 30 seconds ......

Posted On Sunday, January 13, 2008 9:42 PM | Comments (5) | Filed Under [ Visual Studio ]

CoolCommands in Visual Studio 2008
After installing VS2008, I quickly noticed the absence of some of my favorite IDE helpers. How do I copy project references between projects? How do I locate the current document in the solution explorer, without turning on that annoying "track active" option No problem.. I'll just reinstall CoolCommands, or as I like to call it "Commands That Microsoft Should Have included, but didn't" For the uninitiated, learn about coolcommands here -->http://weblogs.asp.ne... ......

Posted On Wednesday, December 12, 2007 9:13 AM | Comments (24) | Filed Under [ Visual Studio ]

Powered by: