Thoughts from Dan Miser RSS 2.0
 Tuesday, April 15, 2008

If you want to add Membership Provider features to your WebHost4Life application, I've found that you can't use the aspnet_regsql wizard UI. Instead, use the following code at the command prompt:


aspnet_regsql -C "Data Source=sqlNNN.mysite4now.com;Initial Catalog=yourdb;User Id=yourUserName;Password=yourPwd" -A mr

Replace NNN with your assigned address, and obviously replace the other elements of the above connection string, too. :-)

Tuesday, April 15, 2008 3:12:01 PM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET | ASP.NET
 Tuesday, March 25, 2008

Problem: I have written my own membership provider to store and validate user information. Further, I have a web page that allows a user to come and sign up with a username, password, and a whole host of other client-related data. When the user submits that data, I would like to have them logged in.

Solution: Since I'm using Forms authentication for the ASP.NET website, it appears that the following code-snippet does what I want:

if (Membership.ValidateUser(u.UserName, u.Password))
    FormsAuthentication.SetAuthCookie(u.UserName, false); 
Tuesday, March 25, 2008 2:24:17 PM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET | ASP.NET
 Monday, March 17, 2008

Nikhil Kothari wrote a brilliant blog post titled Ajax with the ASP.NET MVC Framework. In that post, he built a demonstration TaskList application that used Ajax and the ASP.NET MVC framework that Microsoft is working on. Microsoft is doing a good job in releasing more frequent updates to this framework, but that means that there will be pain when moving from one release to the next. The ASP.NET MVC Preview 2 release was no exception to this rule. There were a list of documented, tedious and manual steps that one needed to follow to get their old code running with preview 2: update web.config, change the route description, update assembly dependencies, etc.. There were also other items that were not so well-documented:  add ProjectTypeGuids to the csproj file, methods that fell out of the preview 2 release (e.g. ViewFactory.CreateView), etc.

I updated Nikhil's code, and some basic testing shows me that it's working with the preview 2 bits. Download the updated code here. Please leave a comment or send me an email if you see any errors that need to be corrected.

Monday, March 17, 2008 12:21:14 PM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET | ALT.NET
 Friday, March 07, 2008

ASP.NET MVC Preview 2 was released yesterday. I've had a chance to install and play with it, and I hate to report that I am underwhelmed. My thinking leads me to believe that MS rushed this release out the door just to be able to say they shipped something at MIX. While there has been good progress made on several issues (e.g. medium-trust support, public methods are callable by default, and route setup is improved). However, I find several other things lacking, referenced from ScottGu:

  1. Source code is not released. Sure, it might be coming "soon", but why not have everything coordinated and ready to go? Hitting an arbitrary deadline of "ship while at MIX" is less important to me than having answers to questions like these.
  2. Dynamic Data (scaffolding) will not work with Preview 2. It is almost always inexcusable to take functionality and features away. The ability to scaffold is one of the coolest things in Rails. Having something similar in ASP.NET was a welcome treat. Now it's gone. Again, I'm sure there is something that will be released "soon", but why not have everything ready to go? I hate not only playing catch up years later, but having a taste of it, only to have it yanked a few weeks later.
  3. The "choose your unit testing framework" feature that was hyped up ships with only MSTest enabled. I understand that MS is working to enlist support from the various unit testing groups to add their tool to the list, but it seems disingenuous to post mocked up screen shots with test frameworks in a combo box that were never developed.
  4. Others have pointed out some more detailed issues that need solving to help with testability (e.g. see here and here).

I look forward to seeing these issues addressed ASAP because I absolutely LOVE the promise that the MVC bits hold.

Friday, March 07, 2008 1:30:33 PM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET | ALT.NET | ASP.NET
 Thursday, March 06, 2008

All in all, I was very pleased with the inaugural meeting of the Milwaukee ALT.NET group. We had a turnout of 10 people, which exceeded my expectation in quantity, and the quality was quite good, too. We talked about general architecture topics for about 45 minutes, and then Todd Penland led the group in discussion on persistence and the Unit of Work pattern. We talked about various alternatives to building this yourself (e.g. NHibernate), and talked about the pros and cons of this approach (i.e. requiring a topological sort to deal with database changes properly (something near and dear to my heart from when I was writing code for MIDAS/DataSnap and BDP), handling object graphs, requiring a MarkDirty() call in the property setters, etc.). It was a very engaging discussion. Thanks to everyone who showed up, and to SpiderLogic for providing the refreshments.

Here are the details for next month:

When: Wednesday, April 9, 2008 @ 7pm
Where: 10000 Innovation Drive, Suite 260 (SpiderLogic office)
What: Dan Piessens (who is on the advisory panel for Unity and EntLib 4.0) will cover Unity and EntLib 4.0

I'm looking forward to it, and hope you are, too. If you're planning on being there, please send me an email to dmiser@distribucon.com, or leave a comment here. That way I can plan the food and refreshments accordingly. Feel free to drop me a line on topics you'd like to see covered, too.

Updated to change the date to April 9th. This date change will allow us to hopefully get more exposure thanks to Scott Isaacs and the WI .NET User Group. Thanks, Scott!

Thursday, March 06, 2008 10:35:55 AM (Central Standard Time, UTC-06:00)  #    Comments [1] -
.NET | ALT.NET
 Monday, February 25, 2008

A co-worker of mine, Brian Kapellusch, is working on a web framework to give us a garden path for ASP.NET applications. The code that he's writing (and the code to use it) is trés elegant. One of the underpinnings of this framework is his use of the ObjectDataSource class (ODS). I am making heavy use of NHibernate and Spring.NET in this application as well. My understanding of the ODS told me that if I wanted to control how the source object was created, that I simply needed to handle the ObejctCreating event and assign the desired object instance in that event to e.ObjectInstance (see here for some more usage examples).

However, it turns out that is not enough to fully control when an object gets created. If you set the TypeName property to a concrete class, ODS will also create a new object behind the scenes - even if you have handled the ObjectCreating event. This becomes very problematic when using an IoC container to automatically build up and inject properties into your class.

The bottom line is this: If you see one version of your object that has things built up properly (because the IoC container was used properly), and one version that has null properties (because, in essence, ODS called "new MyClass()" for you, which doesn't let the IoC container do it's job), you should change the TypeName to point to the interface type instead of the concrete class type. Much thanks to Brian for this one.

Monday, February 25, 2008 6:36:54 PM (Central Standard Time, UTC-06:00)  #    Comments [1] -
.NET | ALT.NET
 Tuesday, February 05, 2008
I'm using NHibernate a lot more lately, and it's been working great. One of the downsides, though, is the fact that you need to build up the mapping files by hand. Well, no more. I stumbled upon the open source project, active-record-gen, on Google Code. One of the templates that it provides is one that will generate NHibernate mapping files for tables in an MSSQL database. I tried this on a couple of databases and it works rather well.

A few small suggestions:

  • Implement a better pluralization/singularization strategy by using Inflector.NET.
  • Work with more databases than just MSSQL.
  • Allow for the connection string to be built up with more options. Right now, it requires SSPI integration, and attached databases don't work as well as they should. See here for more details.
Tuesday, February 05, 2008 7:57:18 AM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET | ALT.NET
 Monday, February 04, 2008

This link explains the unit testing tools available in VS.NET 2008 Professional. My take after reading that section is that Microsoft doesn't get it. Here is my list of observations about this section. Feel free to leave a comment to tell me where I'm wrong.

  • I feel like this is nothing more than an upsell to get me to go and buy VS.NET TeamSystem. Sorry, that's not going to happen. TeamSystem is way too expensive (both initially and in setup/maintenance time for a TFS server). Besides, we have an existing development infrastructure setup since we use multiple (non-MS) languages/platforms here.
  • It looks like MS wants to ignore the thriving and long-standing community of open source unit testing tools. I'm willing to bet that NUnit (and MbUnit, etc.) has more code using it than Microsoft.VisualStudio.TestTools.UnitTesting. Yet, if I want to use the integrated Test menu in VS.NET, I need to rewrite my unit test code to use near-identical attributes for my unit tests (e.g. [TestMethod()] vs. [Test]).
  • Code coverage is not available in VS.NET Pro. I guess code coverage isn't something that developers should be doing - well, unless they shell out tons of money to get it done. Thankfully, there are free alternatives, with cheap upgrades to the latest version.
  • I want to easily run and debug my unit tests. I know Resharper can do this, but I haven't installed that in VS.NET 2008 due to the number of issues I had with it. (Yes, I know an EAP is coming out soon, but I also have CodeRush and Refactor, which work fine with 2008.) I like TestDriven.net,  but I'd like to be sure that it doesn't go away.
  • The documentation is too cluttered. If you're going to give me a list of what's included and what's not included in the Pro version, then why not just separate the documentation to make it easier for me to see what capabilities I have (and what I don't).

In short, it's disappointing that MS has chosen to force people to one specific way of writing unit tests that is against industry norms. ASP.NET has shown me that they do understand the provider model, so why not use it here to allow me to run and debug my unit tests using whatever tools I want.

Monday, February 04, 2008 11:01:31 AM (Central Standard Time, UTC-06:00)  #    Comments [5] -
.NET
 Friday, February 01, 2008

I would like to take it upon myself to announce the formation of the Milwaukee chapter of the ALT.NET UserGroup. It will meet the first Wednesday of every month, with the first meeting to take place on 3/5/08 @ 7pm at 10000 Innovation Drive, Milwaukee, WI. Pizza and drinks will be served, and the event will be free to attend. Thanks to SpiderLogic for sponsoring the first meeting.

This group will cover agile development tools and techniques with .NET, best practices for architecture and coding, emerging technologies, and anything else the group decides to cover. For more backstory on ALT.NET, read this post. The use group will be a very participant-driven group. I will not look to lead this group in any significant way, other than to call this group to order, and get people involved in sustaining it. I've learned from other user groups that if a group is too dependent upon one person, it is a matter of time before it fails.

For the first meeting's agenda, I propose we get some volunteers to take on some minimum responsibilities and then break into an OpenSpaces format, where technical topics will be presented by anyone who wants to present. I don't want this to be yet another 1-way presentation medium for 1-2 hour topics, so be prepared to be engaged, discuss, and share (bring your laptop to showcase code and/or slides). I'll take a swipe at talking about ASP.NET MVC this first meeting. If you have something you want to see covered, or especially if you want to cover something, post a comment, and we'll get it on the agenda.

Please pass this notice around to anyone you think will be interested! If you plan on attending, I would appreciate either a comment on this blog or email to dmiser@distribucon.com, just so we can gauge how much food and drink to have on hand. I am really excited about this, and look forward to seeing everyone there!!

Friday, February 01, 2008 3:46:14 PM (Central Standard Time, UTC-06:00)  #    Comments [4] -
.NET | ALT.NET
 Tuesday, January 29, 2008

I have a .NET application that generates an XML file via serialization (through XmlTextWriter) and submits the data via https. Recently, they changed something on their end to only accept an upper cased UTF-8 encoding, like this:


<?xml version="1.0" encoding="UTF-8"?>

Unfortunately, using the .NET classes mentioned above, it generates the encoding string in lower case. I could find one mention of this on google, and they said to have the other company change (not an option here), or override XmlTextWriter. I went with that approach, making heavy use of Reflector along the way. I started by looking at the WriteStartDocument method, but realized that the private StartDocument is the thing that generates the output. It also gets called by the overloaded WriteStartDocument, so I'd need to override that method, too. However, in the private StartDocument method, it uses a bunch of private variables and generates output via another private method, InternalWriteProcessingInstructions. Ugly. At this point I realize that XmlTextWriter is not a class made for inheriting.

Back to Reflector, and I notice that the Encoding.WebName is the property used to write out the encoding string. I now create a descendant class of UTF8Encoding. The class is listed below. Now I just call XmlTextWriter, passing in UpperCaseUTF8Encoding.UpperCaseUTF8 for the Encoding type, and everything works perfectly.

    public class UpperCaseUTF8Encoding : UTF8Encoding
    {
        public override string WebName
        {
            get { return base.WebName.ToUpper(); }
        }

        public static UpperCaseUTF8Encoding UpperCaseUTF8
        {
            get
            {
                if (upperCaseUtf8Encoding == null)
                    upperCaseUtf8Encoding = new UpperCaseUTF8Encoding();
                return upperCaseUtf8Encoding;
            }
        }

        private static UpperCaseUTF8Encoding upperCaseUtf8Encoding = null;
    }
 Thursday, January 24, 2008

I had a need to move some VB.NET code to C# today. We're still not at the point where we can just mix and match languages within an assembly, and in this case, it would be more work than I wanted to separate things out. I looked around the net, and the best code converter that I found (read: it successfully converted everything I threw at it, where others failed) was this one.

Thursday, January 24, 2008 9:36:42 AM (Central Standard Time, UTC-06:00)  #    Comments [3] -
.NET
 Friday, January 11, 2008

To be sure, this is an incomplete list, but it is a good start. Here's what I don't like about LINQ to SQL:

  • It only works with MSSQL. Yes, this point has been beaten to death, but it is entirely justified. Third party solutions don't cut it. LINQ to SQL intentionally seeks to exclude a sizeable population because of this hair-brained decision.
  • No way to easily specify adhoc LINQ queries. This doesn't count. I know the benefits of design-time queries, but I should also be allowed to shoot myself to get the added flexibility if I so choose. Building up expression trees is not a viable option for every day development.
  • The constant labeling of LINQ to SQL as an OR/M. That label considerably overstates what this technology does. One to one mapping between a table and a class is not really OR/M. It seems like they want to force you to change your database by writing stored procs and views to make your object model better.
  • There is no automated way to easily pick up changes to the database schema.
  • There is no easy way to preserve changes to the generated code. e.g. I change the name of the automatically generated class from collection_details to CollectionDetails, but I evolve the schema of the table. When I re-add the table, I need to set all of the custom properties again. I know I shouldn't change generated code, but see the next point.
  • Speaking of collection_details, it would be much better if the underlying class generator had some options to clean up legacy table names (e.g. remove underscores, camel case resulting table and column names).
  • No many-to-many support. In short, when you have an junction table (aka associative table or cross-reference table), you will need to write code like this: User.UserPermissions[0].Permission vs. User.Permissions[0]. Until we see LINQ to Entity (if ever), we do have this, but you can't use the new entity in a LINQ query.
  • There is no built-in solution to using LINQ across tiers. I don't want to expose my LINQ classes (see the point above about the tight coupling between database and objects) as I may want to change my database, and I don't want that cascading to all of the places that use it. There is also no diffgram, so even if I did it, I would have to write my own change tracking and resolving support. I went to an OpenSpaces meeting on this very topic during CodeMash, and the consensus was not flattering.

In short, it seems like this part of LINQ was released way before it was ready. But it does demo well...

Feel free to add your own grievance to the comments.

Friday, January 11, 2008 12:23:26 PM (Central Standard Time, UTC-06:00)  #    Comments [5] -
.NET | LINQ
 Sunday, December 30, 2007

I have been reading Dustin Campbell's series, The 12 Days of Refactor! X-mas, with interest. He's a very good writer, and has broken down a bunch of Developer Express features into easy to digest chunks of information.

The episode I linked to above touched on the XML Literal support that shipped with VB in Visual Studio 2008. The one sentence summary of this technology is that it lets the VB compiler translate raw XML in the source code into strongly-typed code using XML classes under the hood. It's a very nice idea, and I encourage you to look at the links to learn a little more about it.

While the VB team thought this was a good idea and added the feature, Anders and the C# team believed that it was superfluous to add such a thing to the C# side. I haven't really made up my mind which group I side with yet. However, Anders is benevolent :-), so he gave us the little-documented PasteXmlAsLinq addin that will take XML on the clipboard and paste it into a file in C# syntax building the XML up using classes like XElement.

In a default install of VS2008, open C:\Program Files\Microsoft Visual Studio 9.0\Samples\1033\CSharpSamples.zip and extract the LinqSamples\PasteXmlAsLinq files. There is a Readme.html file in there that tells you how to build, install and use the addin.

While this isn't the same as VB's support for XML Literals, it does make things easier to work with.

Sunday, December 30, 2007 5:02:25 PM (Central Standard Time, UTC-06:00)  #    Comments [1] -
.NET | LINQ | XML
 Monday, December 10, 2007

At the risk of another "Me, too!" post, I thought I'd highlight several links that I have found to be helpful, and for a value-added bonus, talk about why this release matters to me. Back in the day (oh boy, does that make me sound old!), I learned how to program for the Internet by using straight HTML and Delphi to create CGI and ISAPI extensions. In order to do this, you needed to be quite aware of how the actual protocols worked, and what to do to make things behave as you'd expect. I stayed with web development up until I was using COM objects (again, written in Delphi) from an ASP page. After that, I wasn't into the web development scene much on a full-time basis.

ASP.NET 1.0 and 2.0 came along, and I found them to be quite daunting. It seemed as if it was framework built upon framework, layered with add-ins to do what I thought used to be simple things.

It appears to me that there has been a resurgence to move away from the barrage of constant abstractions, and to instead embrace the simplicity of the web (see the popularity of REST, Rails, and the buzz around ASP.NET MVC for some examples of this).

So for me, the reason I am excited is that not only can I once again utilize my knowledge about how the web works, but I can use it in new ways that will make my applications even better (e.g. TDD, scaffolding, etc.). At any rate, here's the set of links that I think matter for ASP.NET MVC:

Monday, December 10, 2007 2:40:56 PM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET | ASP.NET
 Friday, December 07, 2007

I wanted to attend CodeMash last year, but waiting until the last minute worked against me. This year I made sure to commit to the event early, so I just signed up and got my hotel reservations sorted out. The sessions look to be pretty deep for a smaller conference, and I'm excited about going there to talk shop.

If you'll be going, drop me a line via comment here, and we'll be sure to sit down and have a beverage or 2. If you're in the Milwaukee/Madison area, and want to chat ALT.NET, it might be a good place to formally plan and launch the Milwaukee meetup.

Hope to see you there!

CodeMash – I&apos;ll be there!

 Monday, November 26, 2007

If you see an error like the following:

MSB6006: "NCover.Console.exe" exited with code 1. in build.proj(93, 3)

be sure to check that you are using the correct version of CoverLib.dll. In older versions of NCover (e.g. 1.5.8), by default, this dll should be registered every time the NCover task is run. I haven't found that to be true, though. I had an older version of NCover installed somewhere else on the build machine, and I kept on having my build fail because version 1.5.8 of NCover.Console.exe was loading version 1.5.5 of CoverLib.dll.

By manually registering the correct version of CoverLib.dll, I got the build working again.

Monday, November 26, 2007 10:21:48 PM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET
 Friday, November 09, 2007

Here is my quick and dirty laundry list of issues that I've been having with MSBuild over the past few days.

  • You can't detect which target is being executed, therefore conditional execution of tasks cannot be driven by targets. Instead, you need to start a crazy chain of adding targets and updating properties and adding the new target to DependsOnTargets for the original target. No wonder the build file becomes unwieldy so quickly.
  • It is very unintuitive and cumbersome to update property values. If I want to set a property one way in one case, and another way in a different case, it is not easy. Besides, the syntax for the CreateProperty task is way more complex than it needs to be to simply update a property.
  • Brutal gymnastics are required to get around customizing build properties outside of the confines of the Configuration mechanism for a given project. For example, let's say I want to change the DocumentationFile parameter used in csc.exe, or change the NoWarn directive. If you're calling an MSBuild task on your solution, you need to specify those command-line parameters as /p: parameters from the command-line or track what you want to do and add the actual command-line parameters to the Properties attribute. It should be as simple as overriding the default build properties that exist in the csproj file, but that doesn't work.
  • It lacks a way to list descriptive tags for all defined targets (c.f. "nant -projecthelp").

Apparently, I'm not the only one who sees this as a problem. I think Martin's idea of using a lightweight/script language to control the build is the way to go. Granted, I'm coming to this conclusion 4 years after he is, but the point is still valid today. I'd like to have more language elements in my build process to deal with branch, loop and flow so I can react better than I can with an XML file.

My bottom line: MSBuild may be a good tool for VS.NET to use because it can tightly control the format, but it is not a generic solution for controlling a medium-to-big size build process.

Friday, November 09, 2007 10:45:29 AM (Central Standard Time, UTC-06:00)  #    Comments [2] -
.NET
 Thursday, November 08, 2007

I've had some conversations with people about the label of ALT.NET. They are of the opinion that it causes controversy by setting up the "elitist" vs. "everyone else" mentality. This is not a new observations (see here and here, e.g.).

I'd like to propose that the divisiveness of the ALT.NET moniker be abolished as quickly as possible. To that end, my proposal for the name is Pragmatic.NET. It's both a state of mind and an homage to the Pragmatic Programmer series that touches on several of the topics important to this group.

Discuss...

Thursday, November 08, 2007 11:54:09 AM (Central Standard Time, UTC-06:00)  #    Comments [2] -
.NET

I'm more than a little disappointed that I missed the ALT.NET conference in Austin, but I'm extremely happy that it looks like the movement has crystallized and gained enough momentum to be a legitimate option for .NET developers. Steve Kronsnoble made an analogy to the Agile Manifesto, where it took a bunch of informal participants and related ideas and turned them into industry standards. Hopefully, when looking back on this event years from now, people will be able to identify this as the genesis of  .NET.

I really like the idea of ALT.NET, and it maps to discussions I've had with many developers about trying to find a "Garden Path" of .NET development. Some percentage of .NET developers will use whatever Microsoft tells them to without question. That's fine, but that's not how I think. I like to grab the best technology no matter where I find it (Open Source, other languages, etc.) . I want to talk about things like NHibernate, Spring.NET, Subsonic, the new ASP.MVC framework, Domain Driven Design, Test Driven Design, Unit Testing, and on and on. To me, that's the excitement of ALT.NET.

To do my part, I'd like to start a discussion on where and when to hold a local Milwaukee version of this OpenSpace conference. If you're passionate about .NET development and want to help shape this new movement in the Milwaukee area, please leave a comment so we can find a way to move the ball forward.

Thursday, November 08, 2007 10:02:04 AM (Central Standard Time, UTC-06:00)  #    Comments [5] -
.NET
 Monday, November 05, 2007
I've been working more with data-binding and the ObjectBindingSource component that I wrote about here. Here is some stripped-down sample code to help investigate more data-binding concepts.
class Customer { 
  int Id;
  BindingList Orders;
}

class Order {
  int OrderNumber;
  Product ProductInfo;
}

class Product {
  string Vendor;
  Product Self;
}
Assume that we want individual GUI components for the Customer object, and a grid to display the associated orders, with the related Product information displayed along with the Order. Here are some quick pseudo-code tips to get things wired up properly.
  • CustomerObjectBindingSource.DataSource = typeof(Customer)
  • CustomerObjectBindingSource.BindableProperties.Add("Orders"). (If you don't do this, the detail ObjectBindingSource won't work later on.)
  • OrdersObjectBindingSource.DataSource = CustomerObjectBindingSource and OrdersObjectBindingSource.DataMember = "Orders"
  • OrdersObjectBindingSource.BindableProperties.Add("Product")
  • DataGridView.DataSource = OrdersObjectBindingSource
  • Modify the DataGridView column for Product by setting:
    • column.DataSource = ProductsBindingSource
    • column.DisplayMember = "Name"
    • column.ValueMember = Self
  • **IMPORTANT** - Use the same object references everywhere for the product objects (i.e. in the DataGridView column and where you access them in your code). In the sample, I use the productBindingSource component for both the lookup in the grid and the way to lookup individual Product instances. Another alternative that I tested is to use a singleton class for the collection. If you don't do this, you will get the dreaded "DataGridViewComboBoxCell value is not valid" error when the grid tries to populate the Product value.

For concrete details, download this project. I look forward to your comments.

Monday, November 05, 2007 11:26:17 PM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET
 Saturday, October 27, 2007

Subtitle: How to force .NET Grids to respect Object-Oriented designs

Microsoft clearly intended the DataGridView to be used with databases and primitives. With the company inventing .NET making it difficult to write GUIs with a proper domain model, it's no wonder that the majority of .NET code out there is littered with data-access metaphors.

Take the following code (yes, I know there are fields here, but it takes less space):


public class County

{

    public County() {}

    public string name;

    public double taxRate;

}

public class CountyTax

{

    public CountyTax() {}

    public County County;

    public double Amount;

}

There is no way out of the box to get a DataGridView to display and edit the CountyTax object's County and Amount fields. I'd like to have a combo box to display a list of county names, select one, and then enter an amount. Later, I can calculate the tax by multiplying the TaxRate for the selected county and the Amount I entered. In other words, I want to employ good domain design principles.

Here are a couple of solutions, depending on whether or not you want to add extra code to each grid, and use reflection or get some design-time support in a fairly encapsulated solution with faster-than-reflection performance.

I haven't had a chance to check out Orcas, but I can only hope that Microsoft has finally seen the light and will treat object-oriented developers to a fully functioning grid.

Saturday, October 27, 2007 9:59:37 PM (Central Standard Time, UTC-06:00)  #    Comments [1] -
.NET
 Friday, October 12, 2007
Here is the target that I used to generate an FxCop report and integrate it seamlessly into the CC.NET web dashboard.

<FxCop
  TargetAssemblies="$(TargetAssembly)"
  RuleLibraries="@(FxCopRuleAssemblies)"
  AnalysisReportFileName="FxCop.xml"
  FailOnError="False"
  ApplyOutXsl="False"
  OutputXslFilename="Vendor\FxCop\Xml\FxCopReport.xsl"
  Verbose="False"
  IncludeSummaryReport="True"
  WorkingDirectory="$(MSBuildProjectDirectory)"
  ToolPath="$(MSBuildProjectDirectory)\Vendor\FxCop"/>

The key here is to be sure that ApplyOutXsl is set to False. If it's set to True, then the output will not get logged into the CC.NET log, which means when the dashboard tries to find it, it won't be there.

The other thing of note here is that I have all of my third-party tools, like FxCop, Sandcastle, Enterprise Library, etc. in a Vendor subdirectory of my project. By doing this, I can pick up the one Vendor folder and get another project up to speed quickly (through copying or Subversion externals).

Friday, October 12, 2007 9:48:36 AM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET
 Thursday, October 11, 2007

When customizing the appearance of the CC.NET Web Dashboard, you often need to modify the file c:\Program Files\CruiseControl.NET\webdashboard\dashboard.config. However, you won't see the changes you make there reflected back in the browser until that file is reloaded.

The easiest way to reload dashboard.config is to quickly modify web.config (add a space and delete it), and save. This forces IIS to reload the web application, which in turn causes dashboard.config to give up it's new settings. This is especially useful in a hosted environment where you don't have access to administration-level tools.

An alternative would be to just bounce the entire web server by stopping and starting the service, but that's not always feasible nor practical.

Thursday, October 11, 2007 11:58:27 AM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET
 Wednesday, October 10, 2007

When you need to extract more information from the MSBuild script, you can use the following syntax:


  msbuild /v:diag build.proj

There are other verbosity options available, too. Very handy when you need to easily find out what's going on behind the scenes.

Wednesday, October 10, 2007 11:36:46 AM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET
 Tuesday, October 09, 2007
I'm working a lot on agile .NET project setup right now. One of the standards in this arena is CruiseControl.Net. We also use Subversion and MSBuild, which means we need to use MSBuild Tasks to use the custom Subversion tasks. The documentation for MSBuildTasks is, well, "Open Sourcey". For the Subversion tasks, not all tasks have example MSBuild fragments. In addition, the descriptions of most properties or classes are just one sentence circular summaries.

For example, if you need to commit just one file inside the MSBuild script, you would use the SvnCommit task. You might do this as part of a depoyment process where you set version numbers on files before creating an installer. This is the snippet that I finally settled on to update just that one file:

<ItemGroup>
  <CodeFiles Include="Properties\AssemblyInfo.cs" />
</ItemGroup>

<!-- Later on, inside a Target, use this -->
<SvnCommit
  Targets="@(CodeFiles)"
  Message="$(CCNetLabel)"
  Password="pwd"
  UserName="user"
/>

The reason for this is that SvnCommit descends from SvnClient, which is too generalized of a base class. For example, the SvnCommit.RepositoryPath property does not work as one might expect. Specifically, in my case, when I specified the RepositoryPath attribute in the msbuild file, I received the following error. It turns out that you should just not specify the RepositoryPath attribute at all (see the documentation for "svn help commit" to see that a URL is not passed in on the command-line, but rather, svn figures out the URL from the working copy).

    svn: 'svn://x.y.z/project/trunk' is a URL, but URLs cannot be commit targets

Also, SvnCommit.LocalPath should not be used. It ends up generating a command-line similar to the following, which ends up committing everything in the LocalPath and down. Remember, all I wanted was to update one specific file, so it turns out that the LocalPath attribute is getting in the way here.


svn.exe commit "full\path\to\my\working\directory" 
  "Properties\AssemblyInfo.cs" --username user --password pwd 
  --message "1.8.1.2" --non-ineractive --no-auth-cache

To sum up:

  • Don't specify the RepositoryPath attribute in an SvnCommit task
  • Don't specify the LocalPath attribute in an SvnCommit task
  • Specify a ToolPath entry that points to the folder that holds svn.exe if it's not in the default location (c:\Program Files\Subversion\)
  • Setting the Verbose attribute does not work because it is defined as a nullable boolean

Edited on 10/10/2007 for clarity due to comments made by Steve Trefethen. Thanks, Steve!

Tuesday, October 09, 2007 1:46:22 PM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET
 Wednesday, August 22, 2007
I was getting a strange problem at a client's site recently where on occasion, an ASP.NET application that called a web service would throw different exceptions. The fact that I could claim "It works on my machine" meant little consolation. Stranger still, when debugging the application, it would blow up at different spots. When it finally blew up on a call to Response.Redirect, the client suddenly remembered some code that he used in a similar situation before. The theory was that there is some kind of misconfiguration in the servers somewhere, so this should not be needed, but this work-around has since been added and no additional errors have been reported.



// svc is a WebService that you would use in your ASP.NET application

svc.Proxy = new System.Net.WebProxy("127.0.0.1");

((System.Net.WebProxy)svc.Proxy).BypassList = new string[] { "NameOfLocalMachine" };

Wednesday, August 22, 2007 12:02:12 PM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET | ASP.NET
 Thursday, June 14, 2007
If you've come across this error when starting up an application, be sure to check the format of your app.config file. It turns out that this exception is of the type System.Configuration.ConfigurationErrorsException.

The real problem was that I had ended up generating a malformed config file (see the schema in c:\Program Files\Microsoft Visual Studio 8\Xml\Schemas\DotNetConfig.xsd) by putting configSections after appSettings. Once I put the configSections element back to the top of the config file, everything was fine again.

Thursday, June 14, 2007 9:48:41 PM (Central Standard Time, UTC-06:00)  #    Comments [1] -
.NET
 Wednesday, June 13, 2007
I recently created a Windows Service using .NET, and in order to install the service, you need to execute this command:
installutil myservice.exe

However, when I did this, I received a System.BadImageFormatException. It turns out that my PATH settings were still pointing to the 1.1 .NET framework tools. Changing the PATH to point to .NET 2.0 (c:\Windows\Microsoft.Net\Framework\v2.0.50727) fixed the problem and the service can now register successfully.

Wednesday, June 13, 2007 9:06:38 AM (Central Standard Time, UTC-06:00)  #    Comments [1] -
.NET
 Tuesday, May 29, 2007
I hate when we lose functionality in applications. I'm writing a pretty classic ASP.NET application right now. One assembly is the Data Access Layer, and I try to write enough unit tests to actually show that things stand a chance of working (both now and in the future). Also, I occasionally like to work at home, disconnected from work's servers (database and other). That means that I have MSSQL installed on my laptop, which has local copies of the databases that I would need. I also have my web.config checked into source control so others on the team can do a simple checkout and have the web site working with a simple build of the MSBuild script. Given that setup, how would one go about being a responsible unit tester? It seems that what I want is a way to set a default connection string in the main config file, and allow a user.config to (optionally) exist. If it did exist, it could override the settings that were in the main config file to point to a new database.

There is a new attribute, configSource, that looks promising because it can be used to redirect .NET from looking at the app.config (or web.config) and instead make it look at an arbitrary generic user.config file for its content. The problem with this approach is that it requires every machine to have this user.config file in the same place. What I want is more like what the old file attribute of appSettings provided. Unfortunately, the new tools in ASP.NET 2.0 get the connection string information from the connectionStrings section, so using the appSettings approach is out-dated.

For now, I'll use configSource, but it is a pain to have to tell each memeber of the dev team that they need to create their very own user.config file and place it in a certain directory, since this usage means that you wouldn't want to check user.config into your source control system.

Take a look at J.D. Meier's paper, How To Reference Web Services and Databases During Development, for some concrete samples on how this looks.

Tuesday, May 29, 2007 11:54:59 AM (Central Standard Time, UTC-06:00)  #    Comments [1] -
.NET | ADO.NET
 Thursday, May 17, 2007
I've been spending a lot of time on .NET 3.0 lately. One of the areas that is a lot of fun for me to dig into is WPF, since it's such a departure from my usual data/service/remoting pigeon-hole. I know a lot of people hate grids as a metaphor, but when I saw this free WPF grid demo, I knew grids would be with us for yet another generation of user interfaces. Long live the grid!!
Thursday, May 17, 2007 7:59:02 AM (Central Standard Time, UTC-06:00)  #    Comments [2] -
.NET
 Thursday, March 22, 2007
The following application shows a subtle difference in dealing with enums using Enum class methods and when using reflection. In this sample, I am looking to find the number of elements in the enum. Enum.GetValues and Enum.GetNames are not implemented in the .NET Compact Framework, so I cannot use those methods.

By using reflection, I figured I would gain the upper hand and take control of my enum woes. Unfortunately, calling GetFields on an enum type adds an extra entry named "value__" to the returned list. After browsing through the decompilation of Enum, I found that value__ is just a special instance field used by the enum to hold the value of the selected member. I also noticed that the actual enum members are really marked as static. So, to get around this problem, all you need to do is call GetFields with the BindingFlags set to only retrieve the public, static fields (see the code example below).


using System;

using System.Reflection;

 

namespace EnumReflection

{

    class Program

    {

        enum Test

        {

            One,

            Two,

            Three

        }

 

        static void Main(string[] args)

        {

            Type enumType = typeof(Test);

 

            //The following prints 3, but we can't use this method in .NET CF

            Console.WriteLine(Enum.GetValues(enumType).Length);

 

            FieldInfo[] infos;

            infos = enumType.GetFields();

 

            //The following prints 4! There is an extra, unrelated Int32 entry named "value__"

            //at the zeroth element of the info array.

            Console.WriteLine(infos.Length);

 

            //The following prints the 3 enum elements. The value__ field is removed by

            //specifying we only want the public, static fields.

            infos = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);

            foreach (FieldInfo fi in infos)

            {

                Console.WriteLine(fi.Name);

            }

        }

    }

}

Thursday, March 22, 2007 10:16:48 AM (Central Standard Time, UTC-06:00)  #    Comments [0] -
.NET | Compact Framework
 Thursday, March 15, 2007
I needed to implement a dialog that could be used to stop from displaying over and over again. We've all seen countless variations on this theme. I also didn't want to go to the extent of using hooks to accomplish this.

I came across the SHMessageBoxCheck function, and it appears to give me what I need. Granted, it is far from perfect, but it works for me. I used the declaration from PInvoke.net, but I received a PInvokeStackImbalance exception from MDA. I modified the DllImport to use PreserveSig to true, and the error is gone. I did update the wiki to mention this finding, so hopefully others will be able to verify.

All in all, this function works well. But, by trying to be lazy and use a pre-existing solution, it definitely took longer than it would have had I written my own custom dialog. I'm sure that won't be the last time that happens. ;-)

Thursday, March 15, 2007 8:49:05 AM (Central Standard Time, UTC-06:00)  #    Comments [1] -
.NET
 Thursday, March 08, 2007
I read Scott Hanselman's well-written article HOW TO: Debug into a .NET XmlSerializer Generated Assembly. I can add a few more little (and most likely obvious) things to his