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.