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>

Friday, 9 September 2011

Exception thrown the first time an NUnit test that opens a SQL connection is run

When running an NUnit test that opens a SQL connection, the first time the test is run you may get an error similar to the following:

System.Data.SqlClient.SqlException : A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - The pipe is being closed.)

Running the test again then passes.

This can happen in this scenario: NUnit has run data access code, creating a connection, then SQL Server is restarted. If this is the case, the cause of the exception is as follows. If SQL Server is restarted after ADO.NET has built a connection using the same connection string as that used by the failing test, ADO.NET will attempt to reuse that connection from the connection pool without checking whether the connection is invalid. Because SQL Server has been restarted the connection is no longer valid and the exception is thrown.

To demonstrate this, restart SQL Server, then run the test. The test will fail. If the test is run again, it will pass. Next, close NUnit, then restart SQL Server and reopen NUnit (in either order) and rerun the test. The test will pass.

Friday, 12 August 2011

Manage Nuget Packages error

I suddenly started getting a weird error when trying to open the Nuget package manager (by right clicking the project in VS Solution Explorer and selecting the Manage Nuget Packages option). A dialogue appears containing the following error message and stack trace:

The composition produced a single composition error, with 2 root causes. The root causes are provided below. Review the CompositionException.Errors property for more detailed information.

1) Not implemented (Exception from HRESULT: 0x80004001 (E_NOTIMPL))

Resulting in: An exception occurred while trying to create an instance of type 'NuGet.VisualStudio.SolutionManager'.



It turns out this is a known problem if your solution contains an Installshield LE Setup project.

http://docs.nuget.org/docs/reference/known-issues

The workaround is to temporarily unload all Installshield LE setup projects in the solution. The Nuget package manager should now open correctly. Alternatively, if you close the solution, open a solution that does not contain any Installshield LE setup projects, open the Nuget package manager, then go back to the original solution, Nuget will open fine without unloading the setup projects.