Thursday, April 10, 2014

ColdFusion 10 CFLOOP bug with decimal steps

Back in the ColdFusion MX 6.1 era, I stumbled across a bug. A CFLOOP tag with a step of 0.2 would inexplicably skip a number (32.0, I believe) as it counted up. The bug persisted through version 7.x. I had a workaround in place, so I didn’t give it much thought after that.

Recent ColdFusion conversations made me think of this bug, so I decided to code up a quick test to see if it was still an issue with CF10. What I discovered was far worse than I remembered.

Start with a simple loop from 0 to 40 with a step of 0.2. Display each step and add a comma after all but the last number:
<cfloop index="i" from="0" to="40" step="0.2">
      <cfoutput>#i#</cfoutput>
      <cfif i LT 40>, </cfif>
</cfloop>

Hmmm… 40 is missing. When counting up by integers, 40 is included. This was the first hint that something was not quite right.


The list is a bit tough to read, so let’s break it up by inserting a <BR> before each integer (skipping the initial zero).

<cfloop index="i" from="0" to="40" step="0.2">
      <cfif int(i) EQ i and i GT 0><BR></cfif>
      <cfoutput>#i#</cfoutput>
      <cfif i LT 40>, </cfif>
</cfloop>

This should have produced a nice column of integers with each row ending in x.8! 

There is a line break after 0.8, as expected, but no line breaks again until 8.8 and no more again until 37.8? This makes no sense. Since the problem occurs in the first 10 digits, let’s reduce the TO value to 10 and include “int(i)” and the result of the evaluation “int(i) eq i” in the output:
<cfloop index="i" from="0" to="10" step="0.2">
      <cfif int(i) EQ i and i GT 0><BR></cfif>
      <cfoutput>#int(i)# EQ #i#:#int(i) EQ i#</cfoutput>
      <cfif i LT 10>, </cfif>
</cfloop>


So, this output is telling me that when i = 2 , int(i) EQ i evaluatees to 1 EQ 2! Worse, it is saying 4 <> 4, 5 <> 5, 6 <> 6 but 7 = 7? I tried the other rounding functions: FIX, ROUND and CEILING with varying degrees of weirdness. (ROUND appeared to work, but I don’t trust it completely.) I also tried JavaCast() but the results were still off. The string comparison function COMPARE (x,y) had the same problem. When I tried int(2.0) by itself, it did not yield “1”, so I suspect the problem is data type conversion in the processing of the loop steps.

The Workaround
I used the same workaround here that I used years ago with the original problem. Multiply the FROM, TO and STEP by 10 and divide the value as appropriate inside the loop.
<cfloop index="i" from="0" to="100" step="2">
      <cfif i MOD 10 EQ 0 and i GT 0><BR></cfif>
      <cfoutput>#numberformat(i/10,"09.9")#</cfoutput>
      <cfif i LT 100>, </cfif>
</cfloop>

And the results turn out as expected:

Conclusion
Avoid decimal steps.

Thursday, February 13, 2014

ASP.NET MVC5 (Novice) Protecting your site with a login wrapper

The default MVC framework includes login and registration pages. They are functional, but by default the main pages in the site are not configured as login-protected.

 

As with much of MVC, the login wrapper has been abstracted to a configuration component – a filter in this case.

 

In the solution explorer under ~/App_Start, double, double-click “FilterConfig.cs”

 

Add the following lines to RegisterGlobalFilters:

 

filters.Add(new System.Web.Mvc.AuthorizeAttribute());

filters.Add(new RequireHttpsAttribute());

 

I disabled RequireHttpsAttribute during development.

 

The entire site is now protected by the login wrapper with the exception of the account related pages. The account pages are excluded from the login wrapper because of the [AllowAnonymous] attribute.

 

 

For a much more comprehensive treatment, see “Deploy a Secure ASP.NET MVC 5 app with Membership, OAuth, and SQL Database to a Windows Azure Web Site” by Rick Anderson.

 

This is a beginning-to-end explanation of how to create and deploy a site. To skip to the security section, scroll to the middle of the page and look for “Protect the Application with SSL and Authorize Attribute”. He even explains how to create security levels!

 

 

 

 

ASP.NET MVC5 (Novice) Creating different layouts for different views

I’m creating a simple login-protected site. I want to have a main layout for the core site and a separate layout for the login and other account-related pages.

 

It took me a while to stumble on the most ‘elegant’ answer for ASP.NET MVC 5. The easiest/best solution (also restated here) is to copy _ViewStart.cshtml from the View folder root to the view folder that you want to style differently.

 

Create a new layout in ~/Views/Shared … (_Layout-Account.cshtml in my case)

 

and edit ~/Views/Account/_ViewStart.cshtml to point to the new Layout.

 

This will override the main _ViewStart.cshtml in the Views folder. There are many other approaches, like adding conditional logic to the main _ViewStart.cshtml page, but creating a _ViewStart.cshtml page for each view you

 

Shailendra Chauhan made an excellent blog post exploring many different ways of rendering layouts in ASP.NET MVC.

Thursday, December 26, 2013

MVC 5 Entity Framework and Dealing with Multi-key tables

I have a legacy table with 100 columns and 3 key fields. The Create, Delete, Details, and Edit pages created by adding “MVC 5 Controller with views, using Entity Framework” can only handle single key tables out of the box.

The Database
The data I need is in a single table on Microsoft SQL Server 2008 R2. The table I’m using has 3 keys: [Order_], [Company_Name] and [Acct_]

In the server explorer, click “Add Connection” and follow the prompts to add the table.

Adding the Entity Data Model
Return to the Solution Explorer and right click on Models and [Add] -->[ADO.NET Entity Data Model].
(New Item --> Data --> ADO.NET Entity Data Model)

I called my model [Order]

Since the database already exists, choose [Generate from Database]

The name of the database is “temp” (not my choice and not something I can change), so leaving defaults on the data connection page means the entity connection settings in Web.Config will be “tempEntities”

As of 12/24/2013, Entity Framework 6.0 isn’t widely supported, so I chose 5.0

Choose the specific table(s) needed. In my case, I just need one: [ORDERS]
Again, leaving the default value, the Model Namespace is tempModel. Click [Finish]


The edmx diagram is created. At the top, you can see the 3 keys.

Build the Project
You need to build the project at this point before continuing or the controller build process will error out.

Adding the Controller
Right click on Controllers and add [Controller…] to add a controller scaffold.

Choose the “MVC 5 Controller with views, using Entity Framework”

I called my controller [OrderController]. Choose the Model class we just created [ORDER (WebApplication4.Models)] and the Data context class is the one we created [tempEntities (WebApplication4.Models)].

When this step completes, you’ll see the [OrderController.cs] under Controllers and an [Order] folder under Views that contains Create, Delete, Details, Edit and Index.cshtml.

Browsing for the First Time
The temp.ORDERS table has about 48,000 rows and over 100 columns (!). I didn’t need all of the columns, so I cut out all except the three key fields for this exercise.

@model IEnumerable<WebApplication4.Models.ORDER>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
       
        <th>
            @Html.DisplayNameFor(model => model.ORDER_)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.COMPANY_NAME)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ACCT_)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.ORDER_)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.COMPANY_NAME)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ACCT_)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>

*Notice the commented “id=item.PrimaryKey” parameter.

Even with this reduced display, 48,000 rows still crashed my browser, so I added a counter that breaks out of the loop after the first 50 rows.

@{int counter = 0;}
@foreach (var item in Model) {
    counter = counter + 1;
    if (counter == 50) { break; }
                …

This results in output that looks like this:


Since the primary key is commented out of the edit, details and delete links, clicking any of them at this point will cause a 400 error.

The account I’m using does not have write access to the database, so “Details” is the only link I will activate. Uncommenting [Details] and replacing “PrimaryKey” with one of the real keys [ORDER_]will result in an exception:

            @Html.ActionLink("Details", "Details", new { id = @item.ORDER_}) |


“The number of primary key values passed must match number of primary key values defined on the entity.” The entity requires three key values and I am only passing in 1. A quick look at the tempController.cs shows how the [Details] action is handled:

The [id] value is passed in by querystring and is used by Find(id)to retrieve the proper record. It took a bit of searching to learn how to use Find() with multiple keys. A comma delimited list will work , for example: db.ORDERS.find(firstcolvar, “plain_text”, 3) looks for 3 keys.
#1 specified by the var firstcolvar,
#2 looks for the plain text “plain_text” and
#3 looks for the integer 3.

Note: The values must match the column data type.

The variable “id” is defined as a string by default, so I decide to pass all 3 key values in as a comma delimited string. I edited the Details Html.ActionLink code on Index.cshtml as follows:

@Html.ActionLink("Details", "Details", new {id= @item.ORDER_+','+@item.COMPANY_NAME+','+@item.ACCT_}) |

All 3 key values, separated by commas.

In the ActionResult Details inside OrderController.cs, I need to parse each of the 3 keys out. I use split to pull the values into an array of strings, then I use each of the values individually in the Find() method.

One tricky part: the third key is an integer, not a string, so I cast the value in the call to the Find method (highlighted).
            string[] splitid = id.Split(',');
            ORDER order = db.ORDERS.Find(splitid[0],splitid[1],Convert.ToInt32(splitid[2]));

Another tricky part: the order of the keys is important, and I have the order wrong above!

The class ORDER in the Models was created automatically from the SQL table.

The order of the keys presented to the find method must match the order of the keys in the Models/Order.edmx/Order.tt/ORDER.cs file.


Company_Name first, ACCT_ second, and ORDER_ third. The ActionLink in Index.cshtml becomes:

@Html.ActionLink("Details", "Details", new { id = @item.ORDER_ + ',' + @item.COMPANY_NAME + ',' + @item.ACCT_ }) |

And the ActionResult in OrderController becomes:

            string[] splitid = id.Split(',');
            ORDER order = db.ORDERS.Find(splitid[1], int.Parse(splitid[2]),splitid[0]);

At this point the details link works!


The next goal is to figure out how to do this with a complex query (in LINQ?) against 2 databases, one of which does not have a key.


Friday, December 6, 2013

Learning One ASP.NET MVC 5

MVC 5 Tutorials
MVC 5 Books
MVC 4 Books

What I like most about these books is they both take a real world scenario and build it out completely, explaining details in a way that video tutorials can't. It is not easy for a novice to translate the MVC 4 examples to MVC 5, but if you build for MVC 4 in Visual Studio 2013, you can follow along with the MVC 4 books almost exactly.

2/10/2014 Removed most of my editorial blather.
4/14/2014 Wrox publish date bumped out yet again.
8/6/2014 Wrox finally released their book. I have changed language stacks to ColdFusion/Java, so this is the last time I will update this page or my ASP.NET content.

Friday, November 8, 2013

"Hello World!" Using One ASP.NET MVC 5 From the Visual Studio 2013 Empty Template

I am in the process of learning MVC 5 and Visual Studio 2013. I am not a stranger to MVC concepts, but I am new to ASP.Net. I thought this might be helpful for new ASP.Net students who have already played with the pre-built MVC 5 template and want to start their own app from scratch.

Update 2/10/2014 
To avoid confusion, I changed the title of this post. This is not how to build a complete sample MVC 5 site from the ground up; it is just a tutorial on getting the empty template running. MVC5 books are out now that will explain site construction in extreme detail.

Create an ASP.Net 4.5 Empty MVC 5 Project
Create a new project/solution.

Choosing the MVC template will load a complete web application shell including controller, views…etc. We want an empty MVC shell with no pre-built pages. Choose Empty (C#) and check MVC.

If you try to run or debug the app immediately after creation, you’ll get an error: “Server Error in ‘/’ Application. The resource cannot be found.” The template is missing the default controller and view needed to display properly.

In the solution explorer, twist open Views and App_Start. Notice that pages are completely absent from Controllers, Models and the root. The Views folder contains a web.config file thinly stocked with Razor definitions.


App_Start contains the RouteConfig.cs file which is where you’ll find the default controller and action definition. According to line 19, the app will look for a controller named “Home” to start.

Create the Default Controller “HomeController”
Right click on Controllers and go to [Add]-->[New Scaffold Item…]

Choose “MVC 5 Controller – Empty” and click [Add]

Change the name of the controller to “HomeController” so it agrees with the default in the RouteConfig.cs file. 

Open the HomeController.cs file and notice the default code returns the view for the Index action.

Create the Default View “Index”
Now we need to create the index.cshtml view that the controller is looking for. Right-click on the Home folder under "Views" in Solution Explorer. Choose [Add] à MVC 5 View page (Razor).


Change the name of the view item to “Index” to match the ActionResult in the Controller.

Open Index.cshtml and insert “Hello World!” between the div tags on lines 13/14.

Click Save, then [Ctrl]+[Shift]+W to view your page in a browser.

Success!










Friday, November 1, 2013

Understanding Visual Studio 2013 and TFS - Projects vs Team Projects

As a developer, I left the Microsoft stack back in 2000 and am very excited to return to the fold with a cutting-edge, large scale One ASP.Net / MVC 5 app. As I am reorienting myself to the Visual Studio 2013 environment, I am learning some things that other new users might find useful.

Visual Studio Solutions and Projects
According to Microsoft, a Project in Visual Studio is "used in a solution to logically manage, build, and debug the items that make up your application... A solution includes one or more projects, plus files and metadata that help define the solution as a whole. Visual Studio automatically generates a solution when you create a new project. " [1

A project groups files for an app and a solution groups projects.


Team Foundation Service (TFS) and Team Foundation Server (also TFS)
TFS is Microsoft's answer to version control, but it is also a tool for project planning and build automation. MSDN Blogger Steve Lange has a great post on the differences between Team Foundation Server and Team Foundation Service that includes a handy PowerPoint brief summarizing the service features. In a nutshell, the service is a cloud based version of the locally hosted server. Microsoft provides the Team Foundation Service free for the first 5 users, so it is well worth checking out.

TFS Team Project
Visual Studio Project and a Team Project are completely different groupings. Reuse of the name is very confusing and, in fact, is what motivated me to create this blog post.  An Article on TFS in MSDN Magazine dated April 2011 describes a team project as a “container for artifacts, including source code (organized into folders, branched folders and branches) and containing one or more Visual Studio solutions, Team Build configuration files, Team Load Test Agents, an optional SharePoint repository containing the pertinent documents for the project…” In other words, a team project is a source control container for one or more Visual Studio solutions. [2]


A TFS team project groups Visual Studio solutions. In this diagram, a new "Web Application" as created in Visual Studio would be a project that is part of a larger solution, which is checked into a team project repository.

TFS Collection
A TFS Collection is a group of Team Projects. The default collection created when you first register with TFS is called DefaultCollection… Unfortunately, with the Team Foundation Service provided with Visual Studio only one collection is allowed per account. [3] If you are running a Team Foundation Server, it is possible to create multiple collections.

A collection groups team projects. (Multiple team projects as pictured above are not possible in the Team Foundation Service provided with Visual Studio.)

Workspaces
What is a workspace and how does it fit into this picture? “Your workspace is a local copy of your team’s codebase.” [4] It is where you actually work on the code.

Local Workspaces vs Server Workspaces
When tying your workspace to your Team Project, you have the option to work locally, which copies all files from the repository, or you can work in server mode, which only copies files one at a time.  (The MSDN article titled “Decide between using a local or a server workspace” has a great explanation of why this would be desirable.)

Team Project Settings: Speed Server Workspaces with Asynchronous Check-in
“You can reduce the time the system takes to check out files to server workspaces by selecting Enable asynchronous checkout in server workspaces. If you select this option: The PendChange permission is no longer enforced [and] Checkout locks are disabled.” [5]