CAT | C#
20
Error – Exception has been thrown by the target of an invocation.
No comments · Posted by Carson.Junginger in .NET 4.0, ASP.NET, C#, MVC, Umbraco
I have recently been working with Umbraco 5 (Jupiter), the newest version rebuilt from the ground up using ASP.NET MVC. One of the stranger issues that I ran into occurred after adding a Surface Controller, and a corresponding custom View to the pre-compiled site. The following error showed up after a build/save all:
The pre-application start initialization method Start on type System.Web.WebPages.Deployment.
Since I opened the site up as an ASP.NET MVC3 Web Site, adding the view added the following to the Web.config:
<add key="webpages:Enabled" value="true" />
Since it does this behind the scenes, I was confused about how the error started, and wasn’t able to catch it until doing a compare on a fresh Umbraco web.config, and the one that was in the project root. Hopefully this saves some of you some time
17
ASP.NET MVC CheckBoxFor explained
No comments · Posted by Carson.Junginger in .NET 3.5, .NET 4.0, ASP.NET, C#, MVC
I have had a number of people ask about the CheckBoxFor method, and why it renders a hidden input tag with a value of false alongside the checkbox input. Here’s an example:
@Html.CheckBoxFor(m => m.IsEnabled)
will render
<input id="IsEnabled" type="checkbox" value="true" name="IsEnabled">
<input type="hidden" value="false" name="IsEnabled">
The reason this is done is because a form will not post anything to the server for an unchecked checkbox. In ASP.NET MVC, most of the time you are going to want a “false” value to be posted to the model binder, so the hidden value of false is there so that a value is posted back whether the checkbox is checked or not. If the checkbox is not checked, the form value for “IsEnabled” will be “false”, and if it is checked, both values will be posted as “true,false”. The model binder understands this, and will automatically take the true value from the collection of values. I have read that Ruby on Rails and MonoRail also use a similar technique.
No tags
4
LINQ to SQL Connection String
No comments · Posted by Carson.Junginger in .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0, C#, LINQ, LINQ to SQL, ORM
Sometimes when working with LINQ to SQL the designer can act screwy and generate a bunch of connection strings in the Web.config, or build the connection string used to access the server into the binary. I am going to show a method I use to ensure that LINQ2SQL uses the correct connection string by creating a partial class with the same name as the generated data context.
First, create a new partial class in the same namespace as your LINQ2SQL DBML file. Name the class the same name as the file with “DataContext” at the end. For example, if my LINQ2SQL file is “Example.dbml” my class name will be “ExampleDataContext.”
Next, add a default constructor like the one shown, replacing the constructor name and connection string key to your own values:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.Linq;
namespace Example
{
partial class ExampleDataContext
{
public ExampleDataContext()
: base(ConfigurationManager.ConnectionStrings["ExampleConnectionString"].ConnectionString, mappingSource)
{
}
}
}
Now, whenever you edit your DBML file, make sure to set the “ApplicationSettings” property to false, and delete the connection string that was auto-generated.
Now your data layer will always use the correct connection string (when you use the default constructor), and the DBML designer will stop tossing in extra connection strings.
No tags
2
Mystery Constants: Maintainability
No comments · Posted by Larry.Smithmier in C#, Examples, IntelliSense, Legacy, Maintainability, Visual Studio
Working with legacy code is always one of my favorite things to do. I believe it helps me write more maintainable code, and the little mysteries are always quite engaging. The most recent example that I feel compelled to share is related to the setting of a database value based on the selection made in a radio button group. In this particular instance, a set of custom localization routines help cloud the issue by abstracting the text from the code, but the central fault is more universal. There was an undocumented naming convention that was initially followed within the database, but the constraints on columns were not always put in place to enforce the convention and the code itself was not designed to assist in any way.
On to specifics (altered to insure confidentiality).
- Initially, in the UI there are three radio buttons that correspond to an integer column in the database (color). The value is set on a public property of an object that corresponds to the table (widgets) in the database. There is a corresponding dimension table (widgetColorCode) in the database, but there is a missing foreign key constraint and the naming convention doesn’t make it easy to track down the dimension domain.
- Time passes.
- A new UI is built for a new company that only manufactures red Widgets. The combo boxes are removed, and the value is set upon submission to the constant 1.
- A derivative of the new UI is commissioned that is for a company only supplying blue Widgets. There is nothing in the code to help the programmer find what value this property should have.
So the code for the Widget class looks something like this:
public class Widget
{
public int Color { get; set; }
}
I am a firm believer in having enumerations corresponding to all dimensions in a project. There is a performance hit for converting an enumeration to an integer, but it is far outweighed by the increased maintainability of the code. By explicitly setting the values for the enumeration and adding an XML comment relating it to the dimension table, you can greatly increase the maintainability of the code. When starting from scratch on a project, I will typically have something along the lines of:
////// corresponds to the Widget fact table /// public class Widget { public WidgetColor Color { get; set; } } ////// corresponds to the WidgetColorCode dimension table /// public enum WidgetColor { Red = 1, White = 2, Blue = 3 }
But, that is a personal preference, and refactoring the entire code base at this point can’t be justified. What can be done quickly to lessen the impact of this when further maintenance is required? Visual Studio comes to the rescue! By simply adding an XML comment to the property, we can define the dimension so that hovering over the property will display the dimension information (Please excuse the missing pointer in the image, trust me, I am hovering over the Color property.):
////// corresponds to the Widget fact table /// public class Widget { ////// corresponds to the WidgetColorCode dimension table /// 1: Red, 2: White, 3: Blue /// public int Color { get; set; } }
C# · DotNet · enumerations · Example · IntellliSense · Legacy code · Maintainability · Visual Studio
12
Creating a Telerik RadUpload User Control For Use in a RadGrid
No comments · Posted by Larry.Smithmier in .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0, C#, Examples, RadGrid, RadUpload, Telerik, Visual Studio
I have been working with Telerik controls for a little over two months (the ASP.NET AJAX suite) and have been continuously impressed with the quality and power they provide. I am working on a project that requires the upload of several different file types which need to be displayed in a grid once uploaded. The cleanest solution I could think of was to create a User Control to handle the uploads and embed it within the grid through the EditFormSettings FormTemplate. So first, I created a simple upload User Control as follows:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UploadControl.ascx.cs"
Inherits="WebApplication1.UserControls.UploadControl" %>
Submit
with the code behind set up to store the uploaded files in the database using LINQ:
protected void btnSubmit_Click(object sender, EventArgs e)
{
LinerModelDataContext dataContext = new LinerModelDataContext();
foreach (UploadedFile file in RadUpload1.UploadedFiles)
{
byte[] bytes = new byte[file.ContentLength];
file.InputStream.Read(bytes, 0, file.ContentLength);
Attachment attachment = new Attachment();
attachment.FileName = file.GetName();
attachment.BinaryAttachment = bytes;
attachment.CustomerID = this.CustomerID;
dataContext.Attachments.InsertOnSubmit(attachment);
}
dataContext.SubmitChanges();
}
I then just added the EditFormSettings section to RadGrid1 and I was able to upload files:
But my grid wasn’t refreshing and I wasn’t getting any notification that the upload was complete. So, to provide the user experience I wanted, I exposed an event to the grid from the upload control by modifying the code behind of the UserControl. I added a delegate, and exposed the event as follows:
public delegate void UploadHandler();
public partial class UploadControl : System.Web.UI.UserControl
{
...
public event UploadHandler Upload;
protected void btnSubmit_Click(object sender, EventArgs e)
{
LinerModelDataContext dataContext = new LinerModelDataContext();
foreach (UploadedFile file in RadUpload1.UploadedFiles)
{
byte[] bytes = new byte[file.ContentLength];
file.InputStream.Read(bytes, 0, file.ContentLength);
Attachment attachment = new Attachment();
attachment.FileName = file.GetName();
attachment.Attachment1 = bytes;
attachment.CustomerID = this.CustomerID;
dataContext.Attachments.InsertOnSubmit(attachment);
}
dataContext.SubmitChanges(ConflictMode.ContinueOnConflict);
if (Upload != null)
{
Upload.Invoke();
}
}
and changing the FormTemplate to be:
(please note that the syntax highlighter I am using mangled the code by changing OnUpload to be onupload in the above source) and adding the handler to the main page:
protected void UploadControl1_Upload()
{
RadGrid1.MasterTableView.IsItemInserted = false;
RadGrid1.Rebind();
}
Event · Example · Telerik · UserControl
7
Debugging Code: Always Break for Thrown Exceptions
No comments · Posted by Larry.Smithmier in .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0, C#, Examples, Visual Studio
I love working with legacy code, really I do. I find the effort of trying to put myself mindset of the people who originally coded the applications enjoyable. It is somewhat satisfying to be able to get enough of a feel for the code to get a feel for what they were attempting to do as well as what got done. In most cases, it is quite easy to see which libraries and sections were implemented first, and which were either rushed to completion or tacked on as an afterthought. It often makes me spend the extra 15 minutes to fully implement something rather than simply patching over a flaw and planning on implementing the ‘real code’ at some mythic future date. Coming in cold to a project, doing a search for TODO is a good start, but I have also found a lot of cases where that isn’t good enough; so, I have begun setting Visual Studio (VS) to break on any thrown exception. If you aren’t familiar with how to change the way VS handles exceptions in debug mode, here is where you can make the changes:
Doing this helps me track down gems like this (from actual code, I made minor changes to keep from exposing client specific information):
//TEMPORARY - make sure the ID contains at least one alpha
try
{
int i = int.Parse(newID);
newID = newID.Remove(4, 1).Insert(2, "X");
}
catch { }
To be fair to the coder, TryParse has only been in the framework since 2.0, and this code could well have have begun life as a 1.1 application, but the TEMPORARY in the comment was obviously overly optimistic. My solution was to replace the above with:
int i;
//make sure the ID contains at least one alpha
if (int.TryParse(newID, out i))
{
newID = newID.Remove(4, 1).Insert(2, "X");
}

