.NET

.NET

Generic Factory over Object Initializers

 

Consider the following generic factory method:     public class Builder     {         public static TType Create<TType>(Action<TType> actionOnTType) where TType : new()         {             var item = new TType();             actionOnTType(item);             return item;         }     } Which allows us to do something like this:             var aRunningCar = Builder.Create<Car>(car =>             {                 car.Engine = new Engine("v8");                 car.Start();             }); What are your thoughts on the above over the standard object initializers found in C# 3.0?  Initially the difference is that this allows us to invoke methods on the instance as the instance is passed into our...

Microsoft Mocking Framework and TypeMock

 

While everyone has been wondering over the past couple years when Microsoft would ship its own version of a mocking framework, as of yesterday TypeMock announced it has been acquired by Microsoft and the product will be included in future versions of Visual Studio.  At least they didn't follow their previous pattern and create a less powerful clone of other products already on the market.  Hmm, interesting this should be me thinks.  Next to follow, possibly a DynamicProxy2 clone from Microsoft?  What day is today again?

Creating Objects - Round 3

 

Ayende has been discussing the different ways of actually creating objects in .NET and the perf cost associated to each of them.  I thought I'd add to the mix one more method, using the DLR.  I've talked to several people who have identified concerns with the speed of the DLR so I found the results rather interesting.  The context is still the same, identify the time it takes to construct one million Created instances. The delegate: delegate Created CreateInstance(int num, string name); The structure: public class Created { public int Num; public string Name; public Created(int num, string name) ...

Vibrant Ink for Visual Studio 2008

 

For those of you that enjoy the Vibrant Ink theme that was originally produced for Textmate, John Lam converted it to work under both Vim and Visual Studio 2005 a while back.  I've enjoyed that for both editors, however with Visual Studio 2008 out, we need to update.  I've updated the settings file to now work with Visual Studio 2008.  Feel free to download it here.

Code to Live Video from Tulsa TechFest

 

Jeffrey Palermo and I sat down with Chris Koenig while at Tulsa TechFest back in October to chat about the new ASP.NET MVC stack.  Josh Holmes just published an extract of our conversation out on Channel 9 here.  This was recorded back in October, right after the ASP.NET MVC stack was first made public by Scott Guthrie down at the ALT.NET conference in Austin, TX.  We discussed other things such as the open source movement and it's relationship to the Java counterpart but they didn't make the cut in the editing room.  You can watch the video directly here.  Have...

The Pitfalls of Concession

 

Ayende recently posted about a design aspect of the new MVC framework coming down from Microsoft. Ayende raised concern about the design requirement of attributing your public actions on a controller. He points out that Rob Conery has a 6 page post covering the usage of a tool to mask the pain involved in typing the excess noise. A follow-up by Phil Haack presents a solution through subclassing that allows one to avoid the attribute. What about composition instead? The real reason behind this post is not to discuss the merit of a design decision directly, but...

Castle Presentation

 

I will be presenting at the September Iowa .NET User Group meeting, if you don't have any plans September 5th come on out for some free pizza and a presentation on the Castle MicroKernel/WindsorContainer. I will be giving an introduction to the dependency inversion principal, and then we will jump into MicroKernel and the extensions that have been built on top of MicroKernel to create WindsorContainer. My final demo will include a custom facility to extend WindsorContainer that will provide integration with the memcached distributed object caching system. I hope to see you out there!

DLR Scores

 

In the constant battle for staying ahead in the software world, Microsoft appears to have a slight edge from the dynamic language perspective. The DLR is being created to support the various dynamic languages that Microsoft intends on releasing, IronPython and recently IronRuby with a dynamic version of Visual Basic in the future (this reminds me of VBScript and the VARIANT data type - sigh). Microsoft hasn't exactly been on the forefront of dynamic languages, Smalltalk has been around for over 25 years. However what does appear to be changing is the way languages and platforms...

IronRuby Emerges

 

So John Lam annouced the alpha release of IronRuby, he mentions that they did a lot of work on string and arrays, unfortunately, with the current release .NET types aren't able to execute Ruby mixins. I was hoping to do something like the following: require 'mscorlib' require 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' list = System::Collections::ArrayList.new list.Add(5) list.Add(10) list.Add(15) list.extend Enumerable list.each {|i| puts i.to_i} The following code does execute: require 'mscorlib' require 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' require 'System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' require 'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' Application = System::Windows::Forms::Application Form = System::Windows::Forms::Form Button = System::Windows::Forms::Button Point = System::Drawing::Point Size = System::Drawing::Size MessageBox = System::Windows::Forms::MessageBox window = Form.new window.text = 'Testing IronRuby'...

EventWaitHandle.Set

 

This blog has been pretty quiet lately, what's going on, has Nick fallen asleep? Nope, I've just been busy wrapping a few things up. Most importantly, I got married on June 2nd, and we took a few weeks off to head down to Hawaii and relax. If you've never been, my recommendation is to skip Maui and head right for Kauai. I will be presenting at the Cedar Rapids User Group on January 7, giving my presentation on Castle's MicroKernel/Windsor Container, so if you are interesting in hearing more about the light-weight IoC container come on...

ReSharper 3.0 Released

 

Absolutely amazing, do not pass go, do not collection $200, just go get it.

ReSharper 3.0 Beta

 

Get it here, looks like they've added quite a bit to this release including a new model for different editions of the product.

Message Propagation

 

Today I ran into an issue where multiple user controls within a scrollable container (Windows Forms) were not always scrolling properly within the container. When the outer user control (specific controls actually) within the container had focus, scrolling worked fine, however when other controls had focus, scrolling with the mouse wheel doesn't occur at all - time to start digging. I noticed this occurred with the TextBox class, and it behaves differently depending on the Multiline state of the control. This is actually a valid situation, we want the TextBox class to handle the WM_MOUSEWHEEL message when...

DLR Hosting Services

 

I was poking around within the DLR code that was release yesterday within the IronPython Alpha release and I came across the Script class which allow local hosting of a script. Given a language provider you can then execute a block of code. Internally the ScriptEnvironmentSetup loads 4 LanguageProviderSetup classes currently IronPython.Hosting.PythonLanguageProvider Microsoft.JScript.Compiler.Hosting.LanguageProvider Microsoft.VisualBasic.Scripting.Hosting.VisualBasicLanguageProvider Ruby.Hosting.RubyLanguageProvider Unfortunately it appears they are only including the IronPython.Hosting.PythonLanguageProvider with this current release. A quick example of what you can do, the Script class is a wrapper around the ScriptDomainManager: using System; using Microsoft.Scripting; namespace IronPythonScriptHost { class Program { static void Main(string[] args) { string code = "print \"Hello\"...

DLR and IronRuby

 

Today at Mix the DLR was announced along with Silverlight. IronRuby is on the list to be one of the languages that will make the initial release under the DLR. If you're interesting in poking around with the early bits of the DLR, check the 2.0 Alpha release of IronPython. Hammett, any chance MonoRail is going to take advantage of these new features/languages?

MVC in ASP.NET

 

Jeffrey Palermo recently commented about a discussion he and the CodeBetter guys had with Scott Guthrie regarding adding new support for MVC within ASP.NET. While I didn't get a chance to talk to Scott, I hope they look at other features that current MVC frameworks provide that make the development cycle more fluid. For example, the process of extracting values submitted from the form can be tedious. Within MonoRail, the MVC web framework provided from Castle, if your controller inherits from the SmartDispatchController, you can take advantage of data binding back to the action of your...

Upgrading to Subtext

 

The other day I finally decided to replace CommunityServer with Subtext. After upgrading to CommunityServer from .Text a while ago, I found the user experience less than friendly. Subtext also is offering more features right now than CommunityServer such as cocomment and akismet support out of the box. Scott mentioned recently that CommunityServer is looking to potentially add cocomment support with the next release, I'd rather not wait. Blog spam is increasingly an issue, while I was working on the import process, I deleted 9,410 spam comments. Most importantly I now have the source code...

Microsoft MVP - Visual C#

 

I am once again a Microsoft MVP for Visual C# in 2007; what a great way to start the new year!

DNUG Meeting

 

Last night Robert Hundausen presented at our Iowa DNUG meeting covering many of the new features found within SQL Server 2005. Robert has a photo posted of last nights event here. I just wanted to thank Robert for presenting, we had a great time, including the spanning topics discussed during dinner afterwards. :-)

HDC Presentation

 

Tim and I just finished out presentation on Model View Presenter in ASP.NET 2.0 this afternoon which we followed up by doing a podcast for PodcastStudio.net with Jeff Julian and Dru Sellers. Overall I was very pleased with the presentation, we had one issue with a live demo, but since when do demos work in front of 150 people? For anyone interested, the code is available on svn here.

Drawing the line

 

Ted Neward recently commented about a comment that Scott Hanselman made during the patterns & practices Summit. Scott said that his company Corillian had built an abstraction layer atop of log4net. From Ted's perspective, the Java world has been dealing with too many layers of abstraction for the last decade they are paying the price for it (agreed). Ted also brings up YAGNI, suggesting that layers are added without an existing need. In my opinion they are both right (way to take sides huh?) Java is attempting to dig itself out of a hole, an example of...

Heartland Developers Conference

 

The 3rd annual Heartland Developers Conference will be October 26th and 27th in Omaha, NE. HDC has just sold out with over 500 attendees expected! Tim Gifford and I will be presenting on the Model View Presenter pattern within ASP.NET 2.0. It appears that Kent Tegels is presenting at the same time. He is covering the new Entity Data Framework which sounds intriguing. For those that are curious, we will be using NHibernate for our data persistence tool during the presentation. :-) Let me know if you'll be out there the night before...

UIPAB Survey

 

The patterns & practices team is currently holding a survey about the direction of a new project aimed to fill the gaps and extend where the UIPAB left off. I am curious if they will be integrating Windows Workflow into the project as it seems to be a good fit. At TechEd this summer there were several presentations on Windows Workflow within ASP.NET by the ASP.NET team, hopefully Microsoft isn't creating two different projects with the same goals in mind. This wouldn't happen would it - Windows Communicator, Windows Messenger, MSN Messenger ;-) Go ahead and...

Mock Object Discussion

 

Scott Hanselman has a great discussion on mock objects on Hanselminutes. They go over the basics of how mocks fit into the development environement and how it helps in a test driven development environment. Scott mentions how the Expect API of many mock object frameworks read like an english sentence, this is a great example of a fluent interface. Scott points out one of the most apparent reasons why Rhino Mocks is a great mock library, it doesn't rely on string-based method names, you actually use the method in your expectations. This is great because it...

Model View Presenter Redux

 

The Model View Presenter (MVP) pattern seems to be all the rage within the last year; it must be the new pink. While I agree this is a great pattern to decouple various logical layers within a system, I think we are missing an important core piece to the puzzle. In my opinion, humble of course, the Model is purely a representation of my data, and I prefer to depict that in the form of a Data Transfer Object (DTO), this is the ubiquitous PONO (Plain Old .NET Object) - (Edit: Domain Model's are welcome too) . The View...

XmlMessageFormatter Woes

 

I ran into an issue with the XmlMessageFormatter yesterday where I noticed a difference between how .NET 1.1 and .NET 2.0 behave with streams and thought it would be good to share. We are pulling messages off a queue (ours happens to pull from Oracle AQ running on top of JMS). Since we don't know exactly what .NET type the XML message represents we can provide an XmlMessageFormatter with the types our application is aware of and ask it to perform the deserialization process for us. There is nothing complicated with this, internally it is just attempting...

A Good Feeling

 

Our team adopted a continuous integration server a little over a month ago and we have been very happy with the results since. We were using Visual Source Safe as our source repository and CC.NET for a continuous integration server. A special "builder" account was created in VSS for CC.NET to pull down the source for each project it had registered. Our projects are set to trigger within CC.NET every 15 minutes. Over time, as we added more projects, CC.NET would report a failed build sporadically. The build error alluded to a VSS user specific...

TeamCity

 

For anyone who has done Java development, you know the first-class tool support that IntelliJ provides for the Java developer. Luckily, JetBrains has entered the Microsoft space with the Visual Studio add-in for C# called ReSharper. This provides a multitude of productivity enhancing features for both C# and ASP.NET. JetBrains just announced a new product called TeamCity which is targeted at providing productivity enhancements to the development team as a whole. With features such as supporting continuous integration, delayed commit, build management, static code analysis and a web-based project dashboard it appears that Team System will...

Test Driven Development Discussion

 

Last night I had the opportunity to go to dinner with the Visual C# Team, C# MVP's and Regional Directors. I had an interesting discussion with Bill Wagner on the merits of having development teams following the test driven development methodology. It was a hearty discussion where I attempted to play the devil advocate in support of full compliance of the TDD approach. I also had the chance to chat with Jeffrey Palermo about some of the idiosyncrasies related to the configuration file within StructureMap and the immediate value ReSharper provides to development teams.

Dirty SOAP

 

I just came from Scott Hanselman and Patrick Cauldwell's session on dynamically endpoints without ASMX. Their session was great and I had the opportunity to talk with Scott for a little bit afterwards. Scott's company uses dynamic endpoints to allow their customers to easily integrate with their financial software by providing WS-I compliant web services to support integration with disparate client software. Using a dynamic adapter, they are well suited to evolve with the eminent release of WCF. Three days into TechEd and the only things missing are power strips in the session rooms (shouldn't this...

Rhino Mocks To The Rescue

 

A recent discussion on the Test Driven Development group brought in question the lacking ability of NMock for mocking classes. NMock will currently only mock an interface. The problem arose when the author wanted to mock a class that takes parameters in its constructor. His solution is to add an Initialize method to the interface and then every other method checks to confirm the object was initialized. While that is very mechanical and error prone - it does work, however there is another solution. Rhino Mocks allows you to create a PartialMock of a class...

Dependency Injection with StructureMap

 

I have posted previously about using Spring.NET as an IoC container and how we can implement some of this out of the box with the System.ComponentModel namespace. StructureMap is another dependency injection framework that in my opinon is much more approachable than Spring out of the box. Why? - Let's take a look at what it takes to start requesting services from the StructureMap container.   IRule rule = ObjectFactory.GetInstance<IRule>(); or for .NET 1.1   IRule rule = ObjectFactory.GetInstance(typeof(IRule)) as IRule; To begin with, StructureMap now supports generics (granted the 1.0.2 release of Spring does as well), however...

Asynchronous File I/O with NAnt

 

I recently needed to recursively iterate over a directory and change the content of files based on a search term. While there are certain NAnt tasks that have been defined to perform similar operations such as the foreach task used in conjunction with a loadfile and its associated filterchain and replacestring, I didn't see an easy way to recursively navigate the directory and perform my changes. A potential solution might have been nesting several foreach tasks and assigned the child directories to a property and subsequently call a different task to pull that directory out of the property, it didn't...

Tech Ed 2006 BoF Session

 

Eric Jacobs and I will be holding a BoF session at Tech Ed called ".NET User Group Open Forum" Tuesday night at 7:45. The purpose is to discuss ways to facilitate a .NET user group in your area, driving membership and promoting good content. We will discuss both things to do and not do when running your user group. If you are a member of an existing user group or would like to start one in your area and will be at Tech Ed, stop by our BoF session and share your thoughts. Unfortunately I won't...

XPath Debugging Visualizer

 

This morning I put together an XPath Visualizer for an XmlDocument to be used within Visual Studio 2005. This comes from waking up at 4 a.m. and not falling back asleep. Any suggestions? Here are a few screenshots: XPathVisualizer 1 XPathVisualizer 2 XPath query during debugging. Viewing the Xml document while debugging. Source is available here. Installer is available here.

Extending Enterprise Library 2.0

 

Brian Button, formerly of the Patterns and Practices team just held a webcast covering how to provide custom design time extensions to the Enterprise Library console. I missed his session, however after reviewing the slide deck which he has provided, extending Enterprise Library appears much easier than when I had to do it only a year ago. Definitely worth checking out if you would like to integrate your own custom extensions within Enterprise Library.

Service Locator with System.ComponentModel

 

Javier mentioned from my previous post that it would be nice to be able to request an object directly from .NET, without a reliance on the Spring Framework. To a certain extent, this is provided in the System.ComponentModel and System.ComponentModel.Design namespaces. You can create a ServiceContainer and register services with it, then if you expose your ServiceContainer as an IServiceProvider, your client can then request services back from the container. It looks something like this: IServiceContainer sc = new ServiceContainer(); sc.AddService(typeof(IDatabase), new Database()); // Add more services IServiceProvider provider = sc as IServiceProvider; Now, within another layer, assuming we have the IServiceProvider,...

Inversion of Control with Spring.NET

 

I have previously mentioned using the Spring Framework for the AOP support the framework provides, however Spring is deeply rooted in providing dependency injection or Inversion of Control (IoC). Spring uses a configuration file to manage type relationship mappings to objects, which can be stored in its own external XML file, an embedded resource within an assembly, or directly within your web.config or app.config file. For a simple example, we will define our own XML file (spring.xml), with the following contents:   <?xml version="1.0" encoding="utf-8" ?> <objects xmlns="http://www.springframework.net"> <object name="Database" singleton="false" type="SpringDemo.Database, SpringDemo"> <constructor-arg ref="SqlConnectionObject" /> <constructor-arg ref="SqlCommandObject" /> </object> <object name="SqlConnectionObject" singleton="false" type="System.Data.SqlClient.SqlConnection, System.Data"> <constructor-arg type="System.String" value="Data...

Ruby on Rails and .NET

 

There has been a lot of hype out in the development community over the past year regarding Ruby on Rails, even with Ruby alone. For those that are unaware, Ruby on Rails is a full stack web framework written in Ruby. While I've only read the first 100 pages of Agile Web Development with Rails, I can say that RoR is very intriguing. At a high level, RoR relies on a MVC architecture, using the ActiveRecord design pattern for data persistence. I've found radrails to be an excellent IDE for RoR if you're developing on a Windows machine. If...

KerberosToken and ASP.NET

 

Today I found myself debugging a security issue involving the WSE 2.0 SP3. A little background; we have a web service that we wanted to secure; WSE seems to be an obvious choice. We were using WSE to embed a KerberosToken in the SOAP header, this allowed us to retrieve the KerberosToken on the server, access the embedded Principal and check to see if the sender was in fact a member of a specified NT domain group. A simple Windows application proved this worked and I continued on my way. As I started to test an...

Debugging Web Services

 

Recently I have been working on a mobile application running on a Pocket PC. The application uses XML web services to synchronize itself with SQL Server. Web Service Studio allow you to point to a web service to which it will generate the proxy, compile it, generate an assembly, and then reflect over that assembly providing you a user interface to the web service. You can then select any of the methods the web service exposes and it provides a UI to interact with you web services, showing you the results. This tool is very similar...

CruiseControl.NET

 

For those of you using CruiseControl.NET, and in particular the CCTray tool, here is a great link for audio sounds for your various build results. Does anyone have any favorites?

MVP Award

 

I was just notified that I have been selected for the Microsoft MVP Award in Visual C# from Microsoft for 2006. This is a great experience; I had a great time at the MVP Global Summit this past year and am looking forward to making the trip this year. Unfortunately, Rafael Munoz (the MVP Lead) doesn't have a blog (Rafael - you need a blog <g>) , but I would like to thank him for all the support he has given throughout the past year.

AJAX Search

 

I decided to update my search by adding a little AJAX support via Michael Schwarz’s Ajax.NET library. When implementing the Ajax.NET library within a user control, I found that the suggested method of registering you class with the library in the Load event doesn’t work properly. While the library does emit the Javascript references to the HTTP handler (the purpose of registering your class with the library), invoking a call to the proxy didn’t work correctly. This only appeared to be an issue with user controls, regular .aspx pages work correctly. By directly including the two...

Casting in C#

 

Garrett Smith of ThoughtWorks discusses his thoughts on the two different ways of performing casting in C#. Garrett states that he prefers the C-style mechanism of casting as it "crashes early". Here's the distinction, when a cast is performed in C# using the C-style casting syntax such as the following: SomeObject s = (SomeObject)hashTable[i]; An InvalidCastException will be thrown if the cast fails. So, with defensive programming techniques, we are encouraged to wrap our code in a try/catch block. Garrett then mentions that using the "as" operator to perform casting is problematic due to the fact that no exception...

Scrum Plug-in for VSTS

 

Conchango has developed a Scrum plugin for Visual Studio Team System. This is definitely worth checking out and just goes to show how extensible the new Visual Studio environment is.

Difficult Code to Test

 

In preparing for the December presentation on Test Driven Development for the Iowa .NET User Group, I would like to get a little feedback relative to your current testing environment. Specifically, what type of code do you find most difficult to test? Please feel free to leave feedback and I will try to address these issues during the presentation.

Data Driven Unit Tests in .NET 2.0

 

The new unit testing namespace provided with .NET 2.0 includes support for data-driven testing which is a great help when writing unit tests that deal with data access, or at least database access as it appears. The framework provides the DataSourceAttribute to specify your data source (fairly obvious), however, this attribute is really only designed for database access. What if my data source were an XML document or a 3rd party web service? Obviously there are other ways to access an XML document or a web service, such as through the Properties property of the TestContext. I'm just surprised the...

Design by Contract with AOP Revisited

 

Last night I posted a quick example of how we could place runtime requirements on methods. This is a common need by developers. I have since updated my example to clean it up a bit and make it more useable. The cleanup should make it much more extensible. In this example, I am placing two restrictions on our parameter. In order to call our function, the parameter being passed to it must be within both the minimum and maximum range defined in our PrologAttribute. What are your thoughts?   using System; using System.Reflection; using AopAlliance.Intercept; using Spring.Aop.Framework; using Spring.Aop.Interceptor; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DeveloperNotes { public class ConstraintInterceptor : IMethodInterceptor { public object...

Design by Contract with AOP

 

Over a year ago I discussed with Joe Duffy, a program manager on the CLR team about the concept of design by contract. Recently I had a similar disucussion with Richard Hale Shaw and Cyrus Najmabadi a developer on the C# compiler team at Microsoft while I was at the MVP Global Summit. I thought I would put together a quick example of how this could be applied, spawning off of my previous post discussing AOP. This example allows the developer to place certain restrictions on a method and for those restrictions to be applied before the method is actually...

CTP's Everywhere

 

If you really enjoy trying out new Community Technology Previews (CTP's), but have found the crux to be having the correct corresponding packages installed at the same time, Channel 9 is to the rescue. Brad Abrams and Jason Sutherland have put together an XML file that will provide you with a list of all components that will play well together based on what you want to install. Channel 9 has put together a nice little interface to it. Check it out.

Aspect Oriented Programming with Spring and Generics

 

I wanted to post this example to flesh out an idea I was thinking about earlier today. Suppose you wanted to check permissions of a user before they made a method call, you might suggest an implementation of code access security. While that's a fair suggestion, I'd like to throw another option into the mix. With aspect oriented programming using the Spring framework, you can effectively check permissions before a method is called through the use of a proxy object that dispatches your calls to interceptors, that subsuquently invoke the requested call. Thus, depending on the results of your permission...

Quote Of The Day

 

We've been using Visual Studio 2005 for the last two months, including Visual Studio Team Systems for our source control repository. We have enabled the requirement that a comment is required before a check-in can take place. Because this is a beta product we have had our share of issues to work with, though I'm extremely happy with the product. This comment came in today from Javier and I thought it was worth sharing. For those days when you just have no idea what happened, comments like these arise. “File is unchanged. I needed to check...

Extension Methods in C# 3.0

 

Microsoft has made public documention describing new features of C# 3.0. At the PDC today, Microsoft announced LINQ, but there are other features of the C# language that are changing drastically. For example, extension methods are being added to the language which will allow you to do something like the following: namespace Acme.Utilities { public static class Extensions { public static int ToInt32(this string s) { return Int32.Parse(s); } public static T[] Slice(this T[] source, int index, int count) { if (index < 0 || count < 0 || source.Length – index < count) throw new ArgumentException(); T[] result = new T[count]; Array.Copy(source, index, result, 0, count); return result; } } } Assuming you import...

NT Groups in .NET 2.0

 

Yesterday, we needed to get the NT groups associated to an account. I have done this before, but now our team is working in .NET 2.0. It's worth noting that the value for each group returned from the WindowsIdentity is in the form of a SID, or a SecurityIdentifier which we can use to translate into a more human readable form, the NTAccount.   WindowsIdentity wi = WindowsIdentity.GetCurrent(); if(wi != null) { foreach(IdentityReference group in wi.Groups) { if(group != null) { NTAccount acct = group.Translate(typeof(NTAccount)) as NTAccount; if(acct != null) { Console.WriteLine(acct.Value); } } } }

MSBuild Context Menu Revisited

 

I mentioned in a previous post how to add a context menu for invoking MSBuild against any .*proj file. The only problem I had was I wasn't able to pass the file name to MSBuild, which would have typically been qualified with "%1" following the MSBuild command. When MSBuild is invoked and a file isn't passed to it, it searches the directory to find one. The problem is, if there are more than one .*proj files in the same directory, it doesn't know which file to run. To solve this, I moved the setting of the environment variables to the...

Advanced Design Time Support For Your Components

 

Have you ever noticed the blue links below the property grid of a objects such as the DataGrid or TabControl when you drag it onto a form? These links provide additional configuration functionality of their objects through various means; a UITypeEditor is used for the DataGrid for example. Implementing this functionality is rather simple, here is just an example. The follow example will allow you to edit the FullName value through a custom UITypeEditor, exposing the editor several different ways, one of which is a custom designer for the component. namespace DeveloperNotes { using System; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Drawing.Design; using System.ComponentModel; using System.ComponentModel.Design; [Designer(typeof(ManagerDesigner))] public class ManagerComponent :...

Shell Extension for MSBuild

 

I really enjoy having the shell extension for NAnt; I can quickly right-click on my build file without directly navigating to a command prompt. For the client I have been working with recently, we are using Visual Studio 2005 Beta 2, enter MSBuild. MSBuild is a great tool, but I discovered they don't already have a context menu for their .*proj files. Adding the following entries to the registry will give you a right click menu to launch MSBuild for any of the .*proj files: Navigate to HKEY\CLASSES\ROOT\* Add a new key called “shell“ if it doesn't already exist. Add...

API Design

 

Just wanted to note something that caught my eye the other day. According to Improving .NET Application Performance and Scalability, part of the Patterns and Practices series, exceptions should not be used to control regular application flow. I noticed that the comments as part of the PrincipalPermission.Demand method, the method itself returns void, however the mechanism you use to determine success or failure is whether or not it threw a SecurityException. Hmmm, why not just return a bool instead? I wonder if this will change in the future? Does this bother anyone else?

Assembly Probing

 

As some of you are aware, I have been working on a UITypeEditor for a custom designer in Enterprise Library. This designer will support Inversion of Control (IoC) Containers for Enterprise Library. Part of the UITypeEditor allows selecting of an assembly and class, be it installed in the GAC or a private assembly. I was running into an issue when I would load a private assembly and attempt to get it collection of types. I was using the static Assembly.LoadFrom method which worked well, except when I called GetTypes(), a ReflectionTypeLoadException exception was thrown. ReflectionTypeLoadException contains a property called LoaderExceptions,...

2005 MVP Global Summit

 

The 2005 MVP Global Summit will be here before we know it, I just registered today. The event is scheduled to take place in Seattle, WA from September 28 through October 1st. It should be a great chance to meet the product teams as well as fellow MVP's. I will be staying at the W Seattle while I am there. Drop me a line if you are going as well.

Composite UI Application Block

 

The group behind the Composite UI Application Block (CAB) just released a community technical preview. CAB is based on .NET 2.0 and its purpose is to allow abstract complex UI design for smart clients. If you would rather spend time working on the business specific components of your application rather than getting caught up with threading and asynchronous requests you should check this out.

XP Themes Issue

 

Yesterday I was working on an internal tool that contains several controls, one being a TreeView control. I noticed that my images for each node within my TreeView weren't showing up. As it turns out, there is an issue with calling Application.EnableVisualStyles() in 1.1 of the .NET Framework that causes TreeNode images to not display. To work around this, you can call Application.DoEvents() to process all Windows messages that are in queue before the instance of your application is invoked. Luckily, this has been fixed in 2.0.

Dev Con 2005

 

Dev Con 2005 is now over and as a whole my presentations went well. Unfortunately when we were in Minneapolis my last demo didn't work properly, specifically where I detailed the ClickOnce API in an auto update scenario. The ClickOnce team is aware of the issue, which will of course be resolved prior to RTM. The problem was a missing “.application” MIME file type under the HTTP Headers tab within the root of IIS. Thus, the subsequent request for the deployment manifest causes an error. I was able to get this fixed prior to our...

Adding Visual Studio .NET 2003 Support for NAnt

 

Ok, I spent a little time yesterday working on this so I thought I'd post it for future reference and to share. You can add support for NAnt build scripts within Visual Studio .NET 2003 with 4 steps. First, you need to create a template file that will be loaded every time you add an item through Visual Studio .NET. Something like the following will work well, remember to reference the schema. <project xmlns="http://nant.sf.net/schemas/nant.xsd" default="build"></project> Save this file to the following directory: C:\Program Files\Microsoft Visual Studio .NET 2003 \VC#\CSharpProjectItems Now we need to create a .vsdir file so Visual Studio .NET...

Automated Build

 

Do you have an automated build system in place for your development? This morning I came in, ran my NAnt script which cleaned my Build directory out, built every project within my solution, copied over the .exe's, .dll's, .config's, .xml's and .manifest files, then it subsequently invoked my WiX script that built a complete MSI installer package, including the web service deployment. Wow, all this and I haven't even had my coffee for the day.

Installing Visual Studio 2005 Beta 2

 

Earlier today I was installing Visual Studio 2005 Beta 2 when it prompted me to remove a previous install of the .NET Framework 2.0. Specifically I needed to remove the following:   Microsoft .NET Framrwork 2.0 Beta 2 Microsoft Device Emulator Beta 2 Microsoft Visual J# .NET Redistributable Package 2.0 Beta No problem, I went to Add/Remove programs and removed both the .NET Framework 2.0 Beta 2 and the Device Emulator Beta 2; however the Visual J# .NET Redistributable Package 2.0 Beta was not listed. I did a quick search and found it located in the following...

Visual Studio 2005 Beta 2

 

Beta 2 has just been released, as of yesterday they only had the links up however the content wasn't available, today everything is there so if you are an MSDN subscriber you can now download Visual Studio 2005 Beta 2.

Visual Studio 2005 Developers Conference

 

Its official, the Visual Studio 2005 Developers Conference is a go. I will be presenting in both the Minneapolis and Omaha locations covering ClickOnce deployment on June 1st and 2nd, respectively. I will be discussing the high level architecture, deployment and application manifests. I will also cover both security as well as API support to implement on-demand download and custom updating scenarios. There will be three tracks, a Smart Client Track, ASP.NET 2.0 Track, and Visual Studio Team Systems Track. You can register now for only $99, come out and learn what's new for the...

My Latest Article

 

My latest article has been published on The Code Project. Custom Data Binding Through Reflection discusses the use of both reflection and custom attributes to map data objects to UI elements. Check it out if you have a chance, let me know what you think as well.

CLR Internals

 

The May issue of MSDN magazine came in the mail today and there is a great article inside called Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects. This article is definitely not for the faint of heart, but I absolutely love this stuff. Hanu Kommalapati and Tom Christian go into great detail discussing items such as LoaderHeaps, High and Low Frequency Heaps, the SOS debugger and how the ClassLoader creates the Method Slot Table to name just a few. Oh yes, you will learn how virtual method dispatching works from the ClassLoader's...

Fun with the CodeDOM

 

I just realized tonight that it's been quite awhile since I've had a blog post. Things at work have kept me rather busy but they are finally starting to settle down now. I was talking to Tim Gifford earlier today about the use of CodeDOM. I decided to put together a little sample that shows you how to generate code on the fly. The example was just thrown together so there are obviously many modifications that can be done to clean this up, an exercise that will be left up to the reader. It's important...

Ode To My State Controller

 

Today we are working on meeting an internal deadline for a project that Javier and I are working on. I was reusing a search control that we wrote earlier, however I found it was a little confused about its state, wouldn't you agree?

Third Times A Charm…Not This Time

 

Last night I attempted for the third time to install Visual Studio 2005 beta 2 and failed for the third time in a row. I did the download this past weekend and made two attempts last Sunday which yielded negative results, last night was no better. Actually, I thought I was in the clear because it had made it through the whole list of items to install with green checkmarks next to each of them, much better than what occurred last weekend. Of course, right at the end (doesn’t it always happen like that?), the install failed....

Solidifying The Glue

 

There has been a lot of recent chatter about Indigo, especially since Eric Rudder recently gave the VSLive! Keynote in San Francisco yesterday. My previous post resulted in a "glue" feeling from Kent that the Microsoft environment provided in the past. I am starting to get this feeling again. I am not saying this is a bad thing; in this case it actually makes sense with what they've done. When .NET first came out we had .NET remoting, ASMX for web services, enterprise services for distributed transactions, WSE for all of your WS-* and MSMQ for message queuing....

Iowa .NET User Group Meeting

 

Last night we had our monthly Iowa .NET User Group Meeting, we had great attendance, 62 if I remember correctly. Jeff Brand came down from Minnesota to give a great presentation covering ASP.NET 2.0, he even talked about some of the beta 2 bits even though we will have to wait till around the end of quarter one for an official release. There were a lot of great questions asked, I'm glad everyone stopped out. Thanks again Jeff. Next month we've got Paul D. Sheriff, a Microsoft Regional Director presenting “Top 10 Tricks for a “Killer”...

Microsoft vs. Sun – Web Frameworks

 

Over the years both Microsoft and Sun have attempted to provide different programming frameworks to developers, yet as these frameworks are all vying for the same goal (i.e., higher developer productivity, easier integration, etc.), they are attacking their goal from opposite ends of the spectrum. If we look back at ASP, before .NET we see that Microsoft provided a framework centered on a COM infrastructure that allowed everyone to develop their applications in either VBScript or JScript. Mind you, there was no inherent framework for web development, at least, not in the sense that we tend to see it now....

Post-Cache Dynamic Content Generation

 

Nikhil was recently talking about this support for the upcoming release within ASP.NET 2.0. If you wanted to do this previously it required some use of JavaScript or iframes. This is definitely going to be a nice bit of functionality I will want to take advantage of.

Debugging Web Applications with Fiddler

 

I just came across a new article on MSDN detailing the release of a tool called Fiddler. Fiddler sits as a proxy between WinINET and your requests to web servers; allowing it to capture all HTTP traffic. Fiddler is then able to track results and provide performance metrics based on the HTTP traffic being processed. Something I think makes this product even more valuable is the support for debugging. Fiddler supports a type of breakpoint, which allows you pause HTTP traffic, and edit values. If you don’t have an IDE readily available this is the...

C# vs. C++

 

Ok, so this is obviously not a new topic and you are probably accustomed to seeing a comparison between C# and it's more common competitor, VB.NET. Eric Gunnerson gave a really nice, detailed list of reasons as to why C# is better than C++ followed by only 4 pluses to the usage of C++. The choice of C# seems rather clear when compared to a language that isn't managed, however when comparing multiple managed languages it becomes much more vague.

Valid RSS from .Text

 

I use RSS Bandit as my RSS aggregator, it comes with a host of nice options, one of which allow you to validate a specific RSS feed to confirm it is well formed. This morning I decided to check to see that my feed, which is being generated from .Text is properly formed. It wasn't. When I went to Feed Validator, it came back with an error stating the <managingEditor> element needed to include an email address. I quickly pulled up the .Text source code to see what was going on. I was able to...

What type of developer are you?

 

Brad Abrams wrote a post back in late 2003 discussing three types of developers. These three types of developers (i.e., Systematic, Pragmatic and Opportunistic) can map closely to the languages of C++, C# and VB, respectively. These three types were defined by Steven Clarke who works on API usability at Microsoft. I think a major flaw with this mapping is that developers can become pigeonholed specifically by the programming language they use. I don't feel that I fit into one specific category here; it's more of a melting pot for me. So I wonder, where do you fit in...

CAPTCHA Added To Site

 

Well, I woke up this morning and got to work, a short time later I've got an effective CAPTCHA control added to decrease the influx of spam posts I've been receiving. Let me know what you think.

Search Added To Site

 

I added searching to my site tonight, hopefully over the weekend I also plan on adding a CAPTCHA control to lower the amount of spam comments I receive. The search is performed via MSN Search, which can provide an RSS feed as output for your search results.

Dinner in Omaha

 

Well, last night Javier and I drove out to Omaha for dinner with Jeff Brand from Microsoft and a bunch of other Omaha developers; Joe Olsen and Phil Wolfe to name a few. It appears that Javier already beat me to the post so I won't ramble on any further but I just wanted to say thanks again, what a great night.

Revisiting Eclipse – Another IDE

 

Tonight I got out my copy of The Pragmatic Programmer; I haven’t read this book for almost two years now so I thought it would be a good chance to review it. If you haven’t read this book yet and you get paid to develop software I would highly recommend it. After reviewing a few chapters it put me in the mood to revisit an old IDE I once used. I haven’t worked with Eclipse since I was in college, since I was in a bit of a reminiscent mood I decided to download the latest bits...

 

Comega is an extension to C# in two areas; a control flow extension for asynchronous wide-area concurrency and a data type extension for XML and table manipulation (the latter seems much easier to say, don't you think?). This is a research project that has been going on at Microsoft Research; however Dare Obasanjo recently made a post mentioning an article he has recently written that should show up around the end of the month. It appears that Comega could really provide an enhanced support of Object <--> XML mapping, this would be very welcome in my book. ...

Use Ruby to Unit Test C#

 

As I mentioned earlier I would be posting an entry showing how to test your .NET code with Ruby. John Lam recently posted an example using Python.NET to test a C# class so I though I would use his C# example to show how you would do this with Ruby. First off, you will need the Ruby/.NET Bridge which is available here. Here is the C# class that we will be testing:   using System; namespace Calc { public class Calc { public int Add(int x, int y) { return x + y; } public int Divide(int x, int y) { return x / y; } } } Next, compile that...

Microsoft Visual C# MVP Award

 

I’ve been awarded the Visual C# MVP (Most Valuable Professional) award from Microsoft for 2005! I just received the email tonight with all the details regarding the program. This is a great honor, I was really delighted when I found out I had been selected. I am really looking forward to the MVP Global Summit; it will be a great chance to visit Seattle, friends and some family that live there. I know I had mentioned that my first post of the New Year would reflect using the .NET Framework from Ruby, but I am currently working on...

Linked on MSDN

 

The other day I was playing with Google and did a check to see who is linking to me (this can be done by typing link:[yoursitehere] in Google) and I noticed that MSDN is linking to my blog in their Visual C# Developer Center page! Wow, that’s was amazing, and then I noticed that a good friend and former coworker of mine noticed (okay, I told him about it) and has posted about it on his blog. I feel compelled to create a trackback. To add, for those of you that have followed my posts where I...

Unit Testing

 

John Lam has a great post about using Python (specifically due to it being a dynamically typed programming language) to perform your unit testing. IronPython is a great addition to allow you to use both the .NET Framework and python modules together. Everyone performs unit testing, right, if not, this is a perfect new year's resolution.

Heartland Developers Conference

 

The Heartland Developers Conference is only one day away now! This conference is a gathering from .NET user groups from Iowa, Minnesota, Nebraska, North Dakota and South Dakota, which is being sponsored by Microsoft, INETA and others. We have two sessions set up: .NET Today and .NET Tomorrow. This conference sold out over a month ago, if you're not able to attend this year next year we will change locations so we can hold more people.

make_pair in C#

 

Recently in the C# forum on the Code Project someone asked of a mechanism to implement a make_pair in C#. make_pair is provided in the Standard Template Library in C++ which allows you to easily maintain a pair of two specified types in one contained data element. While there are classes in place within the .NET Framework version 1.1 that allow you to perform similar operations, basically any class that implements the IDictionary interface provides this base functionality that make_pair exposes (i.e, Hashtable, HybridDictionary, ListDictionary, etc) although access to their members isn't as direct as a make_pair exposes....

Check to see if your .dll or .exe is a .NET assembly in unmanaged C++

 

Javier recently made an interesting post on how to check to see if a .dll or .exe is in fact a .NET assembly or not. This can also be done in unmanaged code so I took this as an opportunity to sit down and write a quick example of how we can check a file to see if it is a .NET Assembly. This is what I came up with. #include "cor.h" #include <stdio.h> bool IsAssembly(char file[]); int main(int argc, char* argv[]) { bool bIsAssembly = false; bIsAssembly = IsAssembly(argv[1]); if(bIsAssembly) printf("I am a .NET Assembly.\n"); else printf("I am not .NET Assembly.\n"); return 0; } bool IsAssembly(char file[]) { bool bIsAssembly =...

Enumerating GAC Assemblies with IronPython

 

I haven't been able to play with IronPython for a while now, work has been rather busy and I have also just received a copy of Programming .NET Security from the folks at O'Reilly to read and review. So far I am rather impressed with the book. This morning when I woke up I decided to sit down and play around with IronPython again. I love the fact that I can simple write a script yet have the power of the .NET Framework available to me at the same time. With the following script we can...

Singleton remarks

 

There are many different ways to skin the Singleton cat, well; at least there are slight variations of it anyway. However the following way is more efficient than using volatile because of performance implications. public sealed class Singleton { private Singleton(){} private static Singleton value; private static object syncRoot = new Object(); public static Singleton Instance { get { if(Singleton.value == null) { lock(syncRoot) { if(Singleton.value == null) { Singleton s = new Singleton(); System.Threading.Thread.MemoryBarrier(); Singleton.value = s; } } } return Singleton.value; } } }

.NET Security

 

Kieth Brown has recently released the book “The .NET Developer's Guide to Windows Security”. Keith initially had this book available online as he wrote it, I'm looking forward to having a copy in hand soon.

Comments are back up

 

Javier Lozano came through on this one, there is a problem with the WebUIValidation.js file within a .NET Framework 1.1 install. Read up on the details here: http://www.lozanotek.com/archive/2004/09/27/147.aspx

Nice use of generics

 

Eric Gunnerson recently talked about a nice use of generics that I thought I would share. To create a COM object in .NET you can do the following: Type t = Type.GetTypeFromCLSID(guid); IGraphBuilder graphBuilder = (IGraphBuilder) Activator.CreateInstance(t); so a nice helper function using generics looks like this: private T CreateComObject(Guid guid) where T: class| { Type comType = Type.GetTypeFromCLSID(guid); object o = Activator.CreateInstance(comType); if(o == null) return null; else return (T) o; } and now you can do something like this: IGraphBuilder graphBuilder = CreateComObject<IGraphBuilder>(CLSID_FilterGraph); Just wanted to document this for future use. ...