Monday, 16 April 2012

Excel 2010 unable to open file created by ExcelLibrary

This post documents a workaround for a bug in ExcelLibrary. If you create a file of size less than 7KB, Excel 2010 is unable to open the file. To solve this, prepopulate the worksheet with at least 200 rows containing empty cells.

for (int rowIndex = 0; rowIndex < 200; rowIndex++)
{
    sheet.Cells[rowIndex, 0] = new Cell(string.Empty);
}

Monday, 12 December 2011

How to force view compilation in an ASP.NET MVC project

When you build an ASP.NET MVC project, the default behaviour is to exclude view files from compilation. To include views unload the project (in Solution Explorer right click the project and select Unload Project) and edit the project file (right click the project node and select Edit <project name>.csproj).  Locate the MvcBuildViews setting and change this to true.  On reloading the project, building will now compile all views.

Note that this will include all view files in the project's Views folder on disk, even if these are not added to the project.

Tuesday, 4 October 2011

Using the ASP.NET membership provider in an MVC controller

You can refer to the default ASP.NET membership provider in the controller action using the Membership.Provider object, just as in ASP.NET Web Forms. This is because ASP.NET MVC uses the same ASP.NET infrastructure as Web Forms. This is how the default AccountController, built when you select the ASP.NET MVC 3 Internet Application template, provides authentication functionality. It declares an IMembershipService interface dependency, to abstract the authentication functionality, and instantiates this with the AccountMembershipService concrete class in the controller’s Initialize method:

public IMembershipService MembershipService { get; set; }
protected override void Initialize(RequestContext requestContext)
{
    if (FormsService == null) { FormsService = new
    FormsAuthenticationService(); }
    if (MembershipService == null) { MembershipService = new
    AccountMembershipService(); }

    base.Initialize(requestContext);
}


The IMembershipService interface and AccountMembershipService implementation are in the AccountModels file.

Of course you can check whether the current identity is authorized without having to directly use the Membership.Provider object, by using the AuthorizeAttribute attribute.

[Authorize]
public ActionResult About()
{
    return View();
}


Adding this attribute to the action method declaration will make the MVC runtime check whether the identity is authenticated. If the identity is not authenticated, the runtime will throw a SecurityException exception.

Thursday, 29 September 2011

C# arithmetic operators

Because I have a terrible memory…

Operation Operator Remarks 
Add+Redefined on strings to provide string concatenation, so no other separate string concatenation operator is required corresponding to VB’s & operator.
Increment++The ++x form is a prefix operation. The result of the operation is the value of the operand after it has been incremented.
The x++ form is a postfix operation. The result of the operation is the value of the operand before it has been incremented.
Decrement--The --x form is a prefix operation. The result of the operation is the value of the operand after it has been decremented.
The x-- form is a postfix operation. The result of the operation is the value of the operand before it has been decremented.
Division/Redefined for each type – i.e. there is no separate integer division operator.
Modulus%

A full list of C# operators is in MSDN.

Friday, 16 September 2011

The next release of .NET

A while ago some concerns were expressed regarding Microsoft’s plans for .NET, based on an article that was written in response to a Windows 8 preview in May (see earlier post). During the preview session, not much was mentioned about these plans.

In last week’s Windows 8 Build event, MS provided details on the forthcoming release of .NET 4.5. The following session outlines the new features in .NET 4.5 supporting Windows 8.

http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-834T

Essentially this is a mainly incremental release (although including some substantial changes to the CLR to support new Windows 8 technologies). There is no evidence or suggestion that there are any plans to replace .NET with any framework based on HTML 5 and/or Javascript as suggested elsewhere.

Wednesday, 14 September 2011

How to generate an entity from a stored procedure using EF

If you want to generate an entity from a stored procedure, you can do this using Entity Framework. Here’s how.

Add a new ADO.NET Entity Data Model item and generate the entity model from the required database as usual. In the Choose Your Database Objects step of the Entity Data Model Wizard, select the required stored procedures and click Finish.


Next, double click the generated .edmx node in Solution Explorer to open the EF designer, right click the designer surface and select Model Browser. In the Model Browser tab that appears, under the XXXModel.Store node (under the top .edmx node), right click the stored procedure and select the option Add Function Import. This will bring up the following dialogue.


To generate an entity that will contain all the columns returned from the stored procedure, click Get Column Information (which retrieves the schema from the stored procedure), then click Create New Complex Type to generate a type that returns all columns, or Entities to map the results to an existing entity. You can rename the type if required.


Now we can use this. If using Web Forms, we can set a grid view’s datasource using the method generated for the entity:

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      using (var myEntity = new Entities())
      {
         GridView1.DataSource = myEntity.procSupplierDepotList();
         GridView1.DataBind();
      }
   }
}


If the stored procedure takes input parameters, the generated method will expect corresponding arguments.

GridView1.DataSource = myEntity.procSupplierDepotList(id);

This will automatically generate the grid view columns from the data fields returned by the generated method. To display a subset of the fields, you can either set AutoGenerateColumns to false and specify the columns, e.g.

<asp:GridView ID="GridView1" runat="server” AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Name"><ItemTemplate><asp:Literal runat="server" Text='<%# Eval("SupplierName") %>' /></ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Code"><ItemTemplate><asp:Literal runat="server" Text='<%# Eval("SupplierCode") %>' /></ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>


Alternatively, you can create an entity in the entity model that contains just the fields you want to display and set the generated method to return a collection of this entity. Note that you can modify the return value by double clicking the method in the Function Imports node.

Tuesday, 13 September 2011

Getting AjaxLink to work in MVC 3

In a master/detail scenario, I had a view listing master items with a details link for each item. I wanted the details link to display child details using AJAX.

To do this you need the Ajax.ActionLink helper method. This takes (among other overloads) the following form:

@Ajax.ActionLink("Details", "Details", new { id = item.Id }, new AjaxOptions { UpdateTargetId = "divDetails" })

Here we are specifying the link text, the controller action, the route value and the target HTML element to update with the result of the Ajax request.

The Details action should return a PartialResult.

I had trouble getting this to work, as the Details action just posted back to a new page instead of the target element. Eventually I discovered that the key to getting this working is to add the following script (in _Layout.cshtml):

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>