You may get an error like the one above appear with a System.Data.UpdateException type.  This exception actually comes from the database, and is wrapped by the entity framework library.  The error stems from the fact that SQL Server has an entity with a not null datetime (not datetime2, but the "old-school" datetime property), and no date was supplied to the EntityObject entity.  In .NET, a default date ignores whatever SQL Server may use as a minimum, and supply a 1/1/0001 date (the value of DateTime.MinValue), a value far short of the minimum value of 1/1/1753 that SQL Server expects.

The easy way to find out is before savechanges() is called, use the watch window to examine all of the properties of the object, and look for the 1/1/0001 date.  It's usually pretty easy to find that way.

Posted by bmains | 2 comment(s)
Filed under:

I recently got this error with an upgraded project to VS 2010 (web forms).  I searched the internet for the error, which I thought wasn't really an error due to a corruption since I could get an MVC app to run and another smaller web forms application.  But this one wouldn't run with the local web server.  No matter what I did, I got the error.  There were some other unrelated changes I needed to make, but that didn't fix the error.

The application was configured to use the local web server, so I tried adding the directory as a virtual in IIS.  And once I did this, the issue was resolved.  For me, while there are other possible causes for the problem, using IIS was the resolution.  Hope this helps someone.

Posted by bmains | with no comments
Filed under: ,

ASP.NET MVC is a wonderful thing.  One of the many great features is the ability to customize all of the .NET framework's code by swapping out one implementation and using another.  One such instance is creating a custom view engine, which you can do as illustrated in this example: http://www.singingeels.com/Articles/Creating_a_Custom_View_Engine_in_ASPNET_MVC.aspx.  The point of my article is not to illustrate how this can be done, but about how to customize it for your needs.  By default, the web forms view engine looks for views in the folder of the controller or the shared folder.  So if you try to trigger an action method "Index" within the controller of type CustomerController, a partial view (.ascx) or the view (.aspx) is sought for in the ~/Shared folder or ~/Customer folder.

Now, I tend to like to use partial views in order to separate and reuse functionality a lot.  So I tend to have a lot of partial views that tend to get reused across pages and I don't want everything to be in the shared folder (by default, partial views have to be in the shared folder or in the same folder as the controller).  So I added some code to the view engine that allowed me to create subfolders within the shared folder and for the view engine to look for the classes there.  Imagine this folder structure:

Shared
    Customers
    Orders
    Products

So the shared folder breaks up my partial views into the folder above. 

Thinking long-term, rather than hard-coding all these folder references and assigning them to the ViewLocationFormats and PartialViewLocationFormats properties, I wanted something that I wouldn't have to worry about changing later.  So in true ASP.NET MVC framework form, I created some extra code to create the ability to automatically add references to subfolders too.  In order to do this, it's required to use the VirtualPathProvider class to extract the URL, as in the following code:

public MyViewEngine() {
var locations = new List<string>
{
    "~/Views/{1}/{0}.aspx",
    "~/Views/{1}/{0}.ascx",
    "~/Views/Shared/{0}.aspx",
    "~/Views/Shared/{0}.ascx"
};

var dir = this.VirtualPathProvider.GetDirectory("~/Views/Shared");
var subs = dir.Directories.OfType<VirtualDirectory>();

foreach (var sub in subs)
{
    locations.Add("~" + sub.VirtualPath.Substring(sub.VirtualPath.IndexOf("/", 2)) + "{0}.ascx");
}

base.ViewLocationFormats = locations.ToArray();
base.PartialViewLocationFormats = base.ViewLocationFormats;
}

This is the constructor for the custom view engine.  It contains some additional code to use the VirtualPathProvider property (a property of our custom view engine) to extract the subdirectories of the shared folder.  You see the four hard-coded references at the beginning, and so we need to create virtual path strings (which start with "~" and work from the beginning of the virtual directory) to add to the custom list.  When working with folders using VirtualPathProvider, the issue becomes the way paths are referenced.  By default, the path may be:

/MyVirtualFolder/Views/Shared/Customers/

When you need:

~/Views/Shared/Customers/

And so some additional work to format the path is needed (the substring strips off the virtual directory folder.  Now we have a component that will allow the MVC framework to look for partial views in all subdirectories in the shared folder.

Posted by bmains | 77 comment(s)
Filed under: ,

I was going back through an application I am currently working on for a client and trying to come up with a way to bridge a gap between that application and a new web site they want, which has two separate application architectures and ORM solutions.  I realized how some of my errors have come to light, and how the SRP principle could have came in handy.  Let me explain.

When using an ORM solution like LINQ to SQL or ADO.NET Entity Framework, each of these ORM's generates its own class and so you can't simply reuse these objects if each project has it's own class definition generated.  One of my coding blunders has come to light in relation to SRP. Imagine having a plain old CLR object (POCO) that receives data from an ORM generated class as such:

//Class to receive data from a Customer LINQ to SQL class
public class CustomerData
{
   public int Key { get; set; }
   public string Name { get; set; }
   .
   .
}

One of the convenient ways to load this object that I would do would be to add a method that does this, within CustomerData:

public static CustomerData FromCustomer(Customer linqToSqlObj)
{

    return new CustomerData
    {
        Key = linqToSqlObj.Key,
        Name = linqToSqlObj.Name
    };
}

And so this static method helped quickly create an instance.  The problem with this approach is that now I have a class customized for my LINQ to SQL project.  If I want to say use it for a shared project, a project that's shared across multiple projects which may have multiple ORM's, this shared project can't have access to the data access layer (well it shouldn't if it's a shared project) and so the challenge then becomes how can you create this class?

There are a couple of approaches.  One I've used is to use extension methods.  This allows an attachment of a method to do the conversion in a project that can access both objects.  This class could look like:

public static class CustomerDataExtensions
{
    public static CustomerData FromCustomerFromCustomer(this Customer linqToSqlObj)
    {

        return new CustomerData
        {
            Key = linqToSqlObj.Key,
            Name = linqToSqlObj.Name
        };

    }
}

This extension method appends a conversion method onto the LINQ object.  In this way, the responsibilities are separated, even though they may appear not to be.

Posted by bmains | with no comments
Filed under: ,

I got this error when I tried to run this code in my view.

<img src='<%= Url.Content("~/Content/Images/logo.gif") %>' />

At first I didn't realize the underlying issue but then quickly realized that when the MVC framework can't find a resource available on disk, it attempts to serve up the resource using a controller.  My folder structure actually had changed during the project and no the logo resided in Content/Images/Framework, but the URL was using the old directory.

When it can't find the file being accessed, the framework attempts to route the file through the route table established on the global.asax, which is exactly what it was trying to do; it was looking for a controller with the name ContentController, with an Images action method.  And since that can't be found, nothing gets returned.

The RouteTable.Routes property (of RouteCollection type) returns a RouteExistingFiles property.  The default value is false, meaning files on disk do not go through the routing process.  If you set this value to true, existing file routes go through the routing process, which requires a controller.

Posted by bmains | 1 comment(s)
Filed under: ,

I've been just getting into MVC lately and run into a weird error, mostly weird because it's mostly due to the error message itself than the actual problem.  The problem is very easy to fix, but first, a little background.  In the various MVC frameworks out there, there are two ways to render controls: using these two syntaxes:

<%= Html.HelperMethod() %>

<% Html.HelperMethod(); %>

Note the syntaxes; the first syntax returns a string.  This string gets rendered directly to the output stream.  The second option uses the current context to render the HTML directly to the browser via the HttpResponse.  It's up to you to determine which of these options the helper method you are currently using, which is helped along using the inline documentation.  But I ran into an interesting situation: if you forget (or don't realize) that the options you are using happen to use the <%= %> syntax and includes a semi-colon, you may get the ) expected error.  Why, I don't know, but that's what I been running into.

Some of the issues may be with the HTML helper themselves; for instance, some of the features you may use may need to use the latter option of rendering rather than the former, which seems to have been what my issue was, but I haven't yet placed my entire finger on it.

Posted by bmains | with no comments
Filed under: ,

The latest release of Telerik's RadControls framework for ASP.NET AJAX has a really cool feature: RadCompression.  Telerik provides a HTTP module that compresses your JavaScript files, Silverlight applications, and AJAX/web service requests.  While it may not work with every request (it doesn't support web service page methods and it doesn't support certain application types), it does work really well in what it does.

We added this to our application in our development environment, and noticed that it did improve the web site speed on our local machine by up to 20% (as a rough estimate from visual tests and not actually performing benchmarking).

It's very easy to add; all you need to do is add the reference to the module in the config file, as documented here: http://www.telerik.com/help/aspnet-ajax/radcompression.html

Posted by bmains | with no comments
Filed under: ,

Looking at the MSDN documentation for the events pertaining to Sys.UI.DataView, I noticed that it lacked in comparison to the CHM file that comes with the MS AJAX 4.0 Preview 5 download.  One of these events is the rendered event, which fires at the end of the binding (itemRendered fires for each rendered item).  The rendered event is a great way to apply any view-wide operations using JQuery in one single shot.

For instance, if your view renders div elements with a specific class:

<ul .. class="list sys-template">
   <li>
      <span class="HeaderTemplate">Header</span>
      <div> <!-- related panel --></div>
   </li>
</ul>

Using jquery you could write some code to target every instance of this like:

view.add_rendered(function(sender, e) {
    $("span.HeaderTemplate + div").hide();
    $("span.HeaderTemplate").click(function() {
         $(this).toggle("slide", {direction: "down"}, 500);
    });
});

Note that the use of toggle requires the JQuery UI library.  The first statements finds every DIV that occurs after a SPAN.HeaderTemplate element.  The hide() method hides this immediately.  Following this, the click method adds a click event handler to the header to show/hide the div's below it.  This makes for an easy collapsible panel.

Posted by bmains | 5 comment(s)
Filed under: , ,

I been thinking about when I should differentiate between methods and properties.  For instance, suppose that I have the following class:

public class OrderProcessor
{
    public bool RoundToNearestCent { get; set; }
    public bool RoundDown { get; set; }
}

This class has two boolean properties, and you would use this class like so:

var o = new OrderProcessor();
o.RoundToNearestCent = true;
o.RoundDown = false;

o.DoSomething();

When designing software, you have to think about the accessibility of a class's members.  We have two properties that are accessible at any time and can be changed independently.  While this may be a bad example to explain for what I'm going to illustrate, you have to decide whether to allow the properties to be edited independently or not.  For instance, if we were to change the class to this:

public class OrderProcessor
{
    public bool RoundToNearestCent { get; private set; }
    public bool RoundDown { get; private set; }

    public void SetRoundingRules(bool nearestCent, bool roundDown) { .. }
}

Now we have a single method that does the work, and will do the work of setting the properties.  The consumer will no longer be able to set the properties in this manner.  While it may not be the best example, it illustrates how you can constrol the flow of using your components.  Instead of potentially setting one of the properties, the user has to call the method and specify all the settings at one time, instead of individually.

This can be more useful when you need to guarantee that a method has been called.  For instance, if adding a Process() method, the process method can ensure that the SetRoundingRules method has been called through a variable, as shown below.

public class OrderProcessor
{
    private bool _hasSetRoundingRules = false;
    public bool RoundToNearestCent { get; private set; }
    public bool RoundDown { get; private set; }

    public void SetRoundingRules(bool nearestCent, bool roundDown) {
        _hasSetRoundingRules = true;
        .
        .

    }

    public void Process()
    {
         if (!_hasSetRoundingRules)
              throw new Exception();
         .
         .
    }
}

This can also be done using properties, if the properties use the bool? type instead of bool.  That way if neither value has a value (is null), an exception can be thrown.  Though this type of logic is much easier to implement with a method.

Posted by bmains | with no comments

I recently have been thinking about tabular displays and how to make them better.  For instance, suppose that your final output of an application looked like the following:

<table id="tbl">
 <thead>
  <tr>
   <th>One Header</th>
   <th>Two Header</th>
   <th>Three Header</th>
   <th>Four Header</th>
   <th>Five Header</th>
   <th>Six Header</th>
   <th>Seven Header</th>
   <th>Eight Header</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
  </tr>
  <tr>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
   <td>Value</td>
  </tr>
  .
  .
  .
  .

</table>

Imagine this is for a form of some sort.  Think in reverse of a GridView control in ASP.NET; the GridView control renders a dynamic number of rows; this example is more suited for an application you may build that is columns-based, say to render a comparison between products, or maybe the headers a representative of people, and the rows contains some attributes about them (name, height, weight, and other stats).

So, this example using JavaScript and JQuery is  meant to enable a new way of paging columns-based data; however, it could be adapted to page row-based data.  Now, if you have a lot of data in the column-based form, it will  force a horizontal scrollbar, something that is against standards in most organizations (and is not a preferred approach anyway unless culturally significant).  To offset this, the script I'm about to show you will show only 4 columns at a time, allowing the user to page left/right.  To do this, I will use a looping construct to loop through the columns and rows to change visibility.  The script looks like:

<script type="text/javascript">
 var leftColumn = 0;
 var columnCount = 4;

 $(document).ready(function() {
  var t = $("#tbl");
  $("#output").html(t.outerWidth().toString() + ", " + t.outerHeight().toString());
  
  refresh();
 });

 
 function refresh() {
  var table = $("#tbl")[0];
  var headerRow = tbl.getElementsByTagName("THEAD")[0].rows[0];
  var rightColumn = leftColumn + columnCount;
  
  if (leftColumn <= 0) leftColumn = 0;
  if (leftColumn >= headerRow.cells.length - 3) leftColumn--;
  
  for (var r = 0, rlen = table.rows.length; r < rlen; r++) {
   for (var c = 0, clen = headerRow.cells.length; c < clen; c++) {   
      table.rows[r].cellsCoffee.style.display = ((leftColumn <= c && c < rightColumn) ? "table-cell" : "none");
   }
  }
 }
</script>

To begin, to figure out which 4 columns to show is determined by the leftColumn variable; it stores the current column index of the far left visible column.  The column count stores the number of columns to display, so that is configurable and can be something other than 4 columns.  When the document loads (using JQuery's document ready event), the UI initializes to show the 4 columns.  The refresh method actually shifts the columns, and it does this using math.

 The THEAD definition is special, because that is the easy way to figure out how many columns their are; there isn't any explicit way to figure columns (unless a COLGROUP is specified); so the header easily figures out there are 8 columns available.  Two loops take place; first, it loops through each row to show/hide the appropriate cells, while the rest get hidden.  It iterates through the rows first, then the columns, and changes the display accordingly.

To page, I included two buttons that will page left/right.  You may have notice the if checkes in the previous JS code; it simply ensures the paging isn't out of the valid range of values.

<button id="navleft">Move Left</button>
<button id="navright">Move Right</button>

JQuery hooks up to the click event, and refreshes the UI after it increments or decrements the left column index.

$("#navleft").click(function() {
  leftColumn--;
  refresh();
 });
 
 $("#navright").click(function() {
  leftColumn++;
  refresh();
 });

And that is all that it takes to use JavaScript, and JQuery (even if I don't fully take advantage of it) to create a way to page columns of a table.  It works really well and is fast.

Posted by bmains | with no comments
Filed under: ,

Recently, Rick Strahl blogged about his issues with MVC and using some of the essential methods were available in ASP.NET web forms development, considerably the GetWebResourceUrl method (as detailed here: http://west-wind.com/weblog/posts/842507.aspx).  The GetWebResourceUrl method is a useful method to reference files (CSS, JS, images, etc.) stored as embedded resources in an assembly.  In web forms originally, using the statement Page.ClientScript.GetWebResourceUrl would handle creating these URL's.

Rick notes that in your MVC views, you can continue to use some of these methods, but there are issues with using them because of the lack of the same page lifecycle you have in web forms, and how you can create a custom component to fill this void.  I would like to illustrate another possible option if you are looking to accomplish this within a controller.

But first, I have to take you back to ASP.NET web forms (my apologizes to those strongly in the MVC camp).  Web pages could have direct access to this ClientScript property (of type ClientScriptManager) to use GetWebResourceUrl, and so there weren't any accessibility issues within the page.  Within custom components, the HttpContext object gives you access to the page via the Handler property, which is the current handler processing the request (in case of ASPX files, this is the Page class).  In any component, it's possible to get a reference to the page (provided the page is executing the request) using:

Page page = (Page)HttpContext.Current.Handler;

Now that the page instance is available, an embedded resource can be retrieved using:

page.ClientScript.GetWebResourceUrl(page.GetType(), "<resource name>");

Again, this would be in some sort of component or outside the realm of the page; if in an ASP.NET page, user control, or custom control (or anything else that inherits from Control), you can reference the page directly via the page property.

Within MVC, there are several options.  The ViewPage class inherits from page, but as previously mentioned, there may be issues with this here.  However, the controller can also reference the page.  While not directly being able to access the page through a Page property, it can using a similar approach as mentioned above.

The controller class has a HttpContext property, of type HttpContextBase.  This class has a CurrentHandler property, which is a reference to the Page.  Through this, you can cast it to Page and call the GetWebResourceUrl method as shown below:

var url = ((Page)HttpContext.CurrentHandler).ClientScript.GetWebResourceUrl(this.GetType(), "<resource name>");

To get the URL from the controller to the view, you have to return it via the action result or assign it to the ViewData collection, so there are a few options.  Note I'm still learning MVC, so there may be other areas to do this, and there may be other caveats.

Posted by bmains | with no comments
Filed under:

There has quite been the ASP.NET vs. MVC debates going on the internet these days.  I must admit, I'm amused by it because it really comes down to personal preference, and what you are comfortable with.  Most importantly, it should be dependent on what's best for the project at the moment.  However, I do have one fear of what may be coming...

A while back, an open source initiative, Web Client Software Factory (http://www.codeplex.com/websf) was deployed as a viable option for creating applications using a composite development approach.  This was something similar to the MVC framework: a better object-oriented approach to what web forms gave you.  But since MVC came out, WCSF was last deployed Feb 28th, 2008.  And so MVC is the new platform to develop applications in this manner, and I'm thanking God I didn't attempt to build an application using a framework no longer being updated.

A similar thing is happening with LINQ to SQL; it's going away (it's still around, but it's solely being maintained so what good is it if you don't get any enhancements).  LINQ to SQL was created to get people into LINQ, only to tell them that you waisted your time because ADO.NET Entity Framework (not available at the time, and not released until many months later) was the future.  if you invested in LINQ to SQL, it would still work, but you don't get the cool enhancements, updates, and new development, and there isn't a migration tool that I know of.

Is this ASP.NET's future?   A good product to get people into .NET, but is no longer an important piece in application development?  Time will tell.  I actually have been reading about the MVC framework and do look forward to using it.  Don't take this as a "I'm against MVC" posting; I am not.  I just hope that those who invested millions of dollars into ASP.NET web forms will suddenly be looking at using a maintained product with no future.  I certainly hope that isn't the case.

Posted by bmains | with no comments
Filed under:

You may have gotten this error when trying to update data, as I recently did.  After reading up on the subject, I found this which helped:   http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/2bb60aae-7510-4eae-846b-1dad25f2f181

By establishing a log for the data context, I figured out what the issue was.  LINQ to SQL attempts to get the current object by retrieving all of the information using the previous values that weren't changed.  So if you have a 15 column table, and two values changed, LINQ to SQL attempts to find the record using the 13 unchanged values, and performing the update on the other 2, as something like:

update [dbo].Table1 set Field1 = @p13, Field2 = @p14 where Field3 = @p0 and Field4 = @p1 and ... [and so on]

So if something changed about one of those thirteen values, it won't find the record and an error will occur.  This is what I was doing; I posted recently about an issue with an exception being thrown when the foreign key already has the value.  If you have a PK reference as an EntityRef<>, if that reference is loaded, you cannot change it.  You can if you add a method to it that does:

public void ClearReference()
{
     _SomeType = default(EntityRef<SomeType>);
}

This actually clears the reference.  You can't do obj.SomeType = null because it detects the value has changed (even though its being set to null) and the exception still ensued.  So I originally was clearing both the key and the type, setting both to null.  Setting the key causes Row not found error because the original key no longer exists and it looks for a null check.  And thus, one of the 13 original values was changed without LINQ to SQL knowing it, and an error ensued.

Because I actually have to clear the variable, and not the property reference, I don't know if an extension method can be used to clear it; it is something I'm going to investigate.

Posted by bmains | with no comments
Filed under:

I got this error when setting up some LINQ to XML code and I couldn't figure out why I kept getting this error as it made no sense.  After doing a quick search, I realized my root element was this:

var o = new XElement("statement", query.Statement);

and I realized that it was housing content and couldn't be stored in this way.... the root element was a text node like:

<statement>some statement</statement>

And so, switching it to:

XElement queryElement = new XElement("query", new XElement("statement", query.Statement));

 

And so switching it to this, with a root element like:

<query>
    <statement>my statement</statement>
</query>

Helped.  The other thing that solved the issue was how I was creating the document.  I was trying to create the entire XML tree and then assign it to the document via its content property in the constructor.  This didn't work, and the solution was to first create the document, then create the root node and add it, along with the rest of the document.

XDocument document = new XDocument();

XElement queryElement = new XElement("query");

document.Add(queryElement);


Maybe that is a bug, I'm not sure, but I can't assign query directly via the constructor.  I get an error.

You can create the XML in one shot, via the way LINQ to XML works, but I can't in this scenario based on how I have to write the content out, which is why you don't see that in my example.

Posted by bmains | 2 comment(s)
Filed under: ,

Do we really even need IStateManager anymore now that we have ASP.NET AJAX?  In the olden days IStateManager was used to retain the state changes made to a list-bases resource.  These changes would occur on the server and be available on the next postback.  Let's provide a brief example, and I have the perfect one: the DropDownList control.  The DropDownList control (and other ListControl derivatives) have an Items property of type ListItemCollection.  This list class implements IStateManager, so any changes to the Items collection on the server is retained and "permanently" available, at least available while that page was existant.  So a page could bind a list, then later on use server code to change the list (say in a postback scenario), and these changes are retained.  Some developers even wrap the DropDownList in an updatepanel in order for this to work, or use the AjaxControlToolkit (ACT) extender to manage multiple related drop downs.

Note: I Expect You to Understand IStateManager and what it's used for beyond this point.

Now that the focus and the toolset is moving toward a rich client-side AJAX-centric applications, more based on JavaScript than using the server-based UpdatePanel approach, do we even need to consider IStateManager for any custom controls we may develop?  In some cases, I say no, that this isn't as much of a concern anymore.

In some cases, I still say yes, and here is why.  Suppose you have a list of drop down items for a customized drop down control.  Your control can and does manipulate the list of items on the client, while retaining an equivalent list on the server (which is the norm for ASP.NET AJAX controls in most cases).  You may want those two lists to retain the same values, and so one way to do this is to ensure the list retains its values using IStateManager, and post back the changes to the list in a hidden field or something else.

ASP.NET AJAX doesn't have a direct way to postback values, so storing information in hidden fields or another client-side mechanism is the common choice for doing this.  This means that a list of entries may be written in a JSON, or other, format and be processed on the server.  The server can process hidden field information in LostPostData, and thus modify the list at the appropriate time, which IStateManager can then do its work at the appropriate time.

My random thought for today (or actually tonight technically).

Posted by bmains | 1 comment(s)
Filed under: ,
More Posts Next page »