Productive Edge | Microsoft at Productive Edge

CAT | .NET 4.0

Mar/12

22

Umbraco 5 Data Migration / Restore Issue

I recently migrated an Umbraco 5 site from a live environment to my local environment to make some changes, and ran into an issue. I backed up the database of the live site and restored it locally, updated the connection string located in the Hive config file to point to my local database (located at ~\App_Data\Umbraco\HiveConfig\web.config), and the site still would not load. I was presented with the following screen:

Umbraco 5
Install Umbraco 5.0.0 RTM
Welcome to Umbraco 5
It looks like Umbraco isn’t installed yet – click here to launch the install wizard.
Umbraco 5.0.0 RTM runs on ASP.NET MVC3. This is a standard MVC-powered page included as a demo of how your MVC application can serve pages alongside those managed by Umbraco CMS.
To learn more about ASP.NET MVC visit http://asp.net/mvc


After a few minutes of troubleshooting, I discovered that the issue was simply that the production environment was using a different user account for Umbraco to access the database than I was using locally, and even though I changed the connection string to reflect this, I forgot to associate the username with the database after the restore:

Umbraco SQL Server Login Properties

After checking the appropriate database roles for my user account everything was working again. Since Umbraco 5 doesn’t error or give any warning about why it is at the install screen, this wasted a little bit of my time. Hopefully this helps one of you troubleshoot a similar issue.

-Carson

· · · · ·

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.PreApplicationStartCode threw an exception with the following error message: Exception has been thrown by the target of an invocation.

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

·

Feb/12

17

ASP.NET MVC CheckBoxFor explained

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

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

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();
        }

· · ·

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:

image image

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");
            }

· ·

Tightly-coupled, loosely bound. This has been my mantra for enterprise software development for the past 7 or so years. I have always been in favor of compile time over run time errors at (nearly) any cost. I don’t feel that I am dogmatic about it, I understand the need for flexibility in internal interfaces and early in a projects life cycle. But, at the point you have down stream systems that depend on your application to perform, the rules change. You are reading this entry using an application that has a loosely coupled, forgiving interface with the content it receives for rendering (see Joel’s discussion of inherent folly of this choice http://www.joelonsoftware.com/items/2008/03/17.html), so large systems don’t require the level of synchronization I prefer to function. I believe, however, they require it to function well.

Apparently, I am not alone in my belief. The .NET 4.0 framework now has an mscorlib level component that helps enforce the coupling at compile time. The System.Diagnostics.Contracts namespace contains a suite of static classes that, coupled with a post-processing code re-writer, provides static and run time implementations of preconditions, post-conditions, and invariants. In this post I am going to start with some simple examples of how the syntax works. In future posts, I hope to delve into the implications of this system as well as how our best practices need to be updated to take advantage of the power of these structures.

The first thing you need to do is to install the new contract tool set as outlined in http://blogs.msdn.com/bclteam/archive/2010/01/26/i-just-installed-visual-studio-2010-now-how-do-i-get-code-contracts-melitta-andersen.aspx. Please note that unless you are using Premium or Ultimate, you will not get Static evaluation, only run time.

You then turn static checking on in the settings in Project Properties > Code Contracts and select “Perform Static Contract Checking” so it looks like this:

Code Contracts Properties screen for Visual Studio.

Through static checking, we should see compile time errors. Unfortunately, the combination of VS 2010 RC I am using along with the Release 1.2.30312.0 of the Code Contracts for .NET doesn’t have the static version working properly. So for this example we are going to have to look at run time errors. That is set on the same Project Property page:

Code Contracts Properties screen for Visual Studio.

Lets start with a simple sample program with some properties.

    class Program
    {
        public string Name { get; set; }
        public int Age { get; set; }

        static void Main(string[] args)
        {
            Program program = new Program();
            program.Age = -7;
            program.Name = "jon";
        }
    }

Within the program above, we can see a common pattern for properties. If we look at the underlying IL of one of the setter methods, we see what we should expect:

.method public hidebysig specialname instance void
        set_Age(int32 'value') cil managed
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
  // Code size       8 (0x8)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  stfld      int32 Contracts.Program::'k__BackingField'
  IL_0007:  ret
} // end of method Program::set_Age

After modifying the code to include the required using statement:

using System.Diagnostics.Contracts;

and updating the property to have the following contract statement:

        public int Age
        {
            get { return _age; }
            set
            {
                Contract.Requires(value >= 0);
                _age = value;
            }
        }

When a command line program is run with a bad argument, the following exception is thrown:

Unhandled Exception: System.Diagnostics.Contracts.__ContractsRuntime+ContractException: Precondition failed: value >= 0
   at System.Diagnostics.Contracts.__ContractsRuntime.TriggerFailure(ContractFailureKind kind, String message, String userMessage, String conditionText, Exception inner) in :line 0
   at System.Diagnostics.Contracts.__ContractsRuntime.ReportFailure(ContractFailureKind kind, String message, String conditionText, Exception inner) in :line 0
   at System.Diagnostics.Contracts.__ContractsRuntime.Requires(Boolean condition, String message, String conditionText) in :line 0
   at Contracts3.Program.set_Age(Int32 value) in c:\Contracts\Program.cs:line 19
   at Contracts.Program.Main(String[] args) in c:\Contracts\Program.cs:line 33

and looking at the IL I find where the rewrite has added wrappers to handle the pre-conditions:

.method public hidebysig specialname instance void
        set_Age(int32 'value') cil managed
{
  // Code size       74 (0x4a)
  .maxstack  3
  IL_0000:  ldsfld     int32 System.Diagnostics.Contracts.__ContractsRuntime::insideContractEvaluation
  IL_0005:  ldc.i4.4
  IL_0006:  bgt        IL_003c
  .try
  {
    IL_000b:  ldsfld     int32 System.Diagnostics.Contracts.__ContractsRuntime::insideContractEvaluation
    IL_0010:  ldc.i4.1
    IL_0011:  add
    IL_0012:  stsfld     int32 System.Diagnostics.Contracts.__ContractsRuntime::insideContractEvaluation
    IL_0017:  ldarg.1
    IL_0018:  ldc.i4.0
    IL_0019:  clt
    IL_001b:  ldc.i4.0
    IL_001c:  ceq
    IL_001e:  ldnull
    IL_001f:  ldstr      "value >= 0"
    IL_0024:  call       void System.Diagnostics.Contracts.__ContractsRuntime::Requires(bool,
                                                                          string,
                                                                          string)
    IL_0029:  nop
    IL_002a:  leave      IL_003c
  }  // end .try
  finally
  {
    IL_002f:  ldsfld     int32 System.Diagnostics.Contracts.__ContractsRuntime::insideContractEvaluation
    IL_0034:  ldc.i4.1
    IL_0035:  sub
    IL_0036:  stsfld     int32 System.Diagnostics.Contracts.__ContractsRuntime::insideContractEvaluation
    IL_003b:  endfinally
  }  // end handler
  IL_003c:  nop
  IL_003d:  ldarg.0
  IL_003e:  ldarg.1
  IL_003f:  stfld      int32 Contracts3.Program::_age
  IL_0044:  br         IL_0049
  IL_0049:  ret
} // end of method Program::set_Age

The re-writing is being done by ccrewrite, and can be conditionally compiled in. There is also a structure set up to allow runtime code to catch the contract exception to be handled internally.
links: http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts(v=VS.100).aspx

No tags

Last week, Igor brought up a good point about the usefulness of the standard property syntax as a language construct (To Bean or not to Bean!). How much real benefit is there in building boilerplate getters and setters into your code? I brought up the C#:
public string Name { get; set; }

syntactic sugar, it still isn’t as clean or concise as Ruby:

class Person
   attr_accessor :first_name, :last_name
end

or what he envisioned for Java:

//context of another
class Person p = new Person();
p.firstName := "John";

where the getter and setter are automatically appended to the Person object by the compiler.

Well, .NET 4.0 still isn’t quite as cool and concise, but it is getting closer with the introduction of the ExpandoObject. By adding the following using statement:

using System.Dynamic;

you now get the ability to write code like:

dynamic p = new ExpandoObject();
p.firstName = "John";

Oh, and did I mention that you get IntelliSense with it as well?

IntelliSense with ExpandoObject properties.

You still get IntelliSense with ExpandoObject dynamic properties.

When using ExpandoObject(s) with .NET 4.0 and C#, you get IntelliSense for all of the dynamically generated fields.

link: http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(v=VS.100).aspx

No tags

Theme Design by devolux.nh2.me