Saturday, August 31, 2013

Code Normalization

When you hear about normalization, it is typically in reference to data models. However, code normalization is a way to take the concept and benefits of normalization from the database domain and to apply it to code. Code normalization is used to describe a wide variety of techniques, with the simplest being the use of a pre-processor to strip out comments and white spaces, and a more complex application of code normalization being used to reduce executable code to canonical forms that can be analyzed to detect obfuscated or mutating malware.

Sunday, August 25, 2013

CodeIgniter: "The upload path does not appear to be valid" error

The "The upload path does not appear to be valid." error when using the CodeIgniter upload library can be quite puzzling. The problem usually occurs when a call to "$this->load->library('upload', $config)" doesn't load the configuration settings, so adding the following statement after loading the upload library usually sorts out the problem (assuming your configuration array is named $config):

You can also choose to create an upload.php file within the config directory and place the $config array within that file instead of the call to the initialize function.


Friday, August 23, 2013

Enums (Enumerations) in ASP.NET MVC DropDownLists

Getting an Enum within an ASP.NET MVC DropDownLists can be performed using reflection if you do not want to have to create the entries manually. You can get SelectListItem objects from the Enum as follows:

var listItems = from MyEnumType e in Enum.GetValues(typeof(MyEnumType))
select new SelectListItem() { Text = e.ToString(), Value = ((int)e).ToString() };

You can then use the resulting object reference to pass to a SelectList constructor and use it within a DropDownList like this:

var selLst = new SelectList(listItems, "Value", "Text");

Further, you can use it within an ASP.NET MVC DropDownList in the manner described below.

In the controller, assign it to a ViewData item (you can use a View Model instead, if you prefer)

ViewData["VTypes"] = selLst;

In the view, use the ViewData item to obtain an IEnumerable object type (assuming you are using the Razor view engine):

@Html.DropDownListFor(mdl => mdl.VType, (IEnumerable)ViewData["VTypes"])

Sunday, August 18, 2013

Entity Framework: An object with the same key already exists in the ObjectStateManager

I attempted to obtain the current values of a database row to compare them with a value that I was setting using the Entity Framework. When all was set, I tried to update the database with the modified object using the following:
db.Entry(objNew).State = System.Data.EntityState.Modified;
...and that was when the Entity Framework threw an exception with the message:
An object with the same key already exists in the ObjectStateManager

The problem is that when I fetched an existing value, the object state manager had one object so when I tried to set the state of the other object to modified, it noticed that an object with the same key already exists. There are two ways to deal with this problem.

Solution 1: Update the existing object

This is a pretty straightforward solution. Instead of setting the state of the new object to modified, I change the state of the old object, but instead of setting each property manually, it can be done like this:
followed by a db.SaveChanges() call.
Solution 2: Detach the old object

To detach an object, you simply have to set the state to Detached, just as you would when you want to set the state of the new object to Modified. Here's how it is done:
db.Entry(objOld).State = System.Data.EntityState.Detached;
You can then update the database with the new object, as you would do normally.

Thursday, August 15, 2013

Linked List Data Structure

A linked list data structure is perhaps the simplest following an array. It consists of a set of elements wherein each element points to the next. It does not require a contiguous area of memory unlike an array. Adding to a linked list can be as simple as setting the new element as the first element of the list or finding the last item of the list and making the new item the last item. Removing an element requires searching for the previous element of the list, unless the element to be removed is the first item, in which case the removal is quite simple. Searching for an element is no simpler than an array, which requires a comparison with each of the elements. A variation of the sorted list, like a sorted array, makes searching for elements easier while adding complexity to the addition of new elements. However, addition of a new item to the middle of a linked list is much simpler than adding to the middle of an array - an array requires all subsequent elements to be shifted whereas a linked list requires the pointer of the previous element to be set to the new element and the pointer from the new element to be set to the next element. Linked lists are good for implementing stacks with addition and removal occurring from the head of the linked list.

ASP.NET Razor: Output String Without Encoding

If you are using the ASP.NET Razor view engine and have to output a string without encoding, you have to replace the @variable_name with an @Html.Raw(variable_name). Sure, it seems like additional effort to do it in the Razor view engine when compared to the <%: and %> in ASP.NET ASPX view engine but it is an edge case that you would barely encounter 20% of the time when building applications with ASP.NET.

Wednesday, August 14, 2013

ASP.NET HEAD runat server

The HEAD tag within an ASPX file typically has a runat="server" atttribute to make it into a server control. A lot of programmers wondered why this was necessary. Well, it is not but if you do turn it into a server side control, you get the ability to dynamically add tags into the HEAD tag and get URL resolution as well (and it provides the ability to use the tilda to generate absolute URLs). For example, the Page object has a Title attribute and you cannot use it unless you make the HEAD a server side control. Similarly, you can add meta tags 'programatically' instead of placing it within a markup - why would you want to do something like that is something the CMS folk can answer from their experience of getting the page information from a database of a content management system and using the ASPX markup as a mere template.

Tuesday, August 13, 2013

Apress: ASP.NET MVC 4 Books

If you're looking for a good book to read about and learn ASP.NET MVC, Apress has a pair of books on ASP.NET MVC 4 that are available on Amazon.

The book targeted at ASP.NET Web Forms developers is the Beginning ASP.NET MVC 4 book:

It explains the concept of the model, view, and controller components of the MVC pattern and how they are using in the ASP.NET MVC framework and discusses the use of AJAX and configuring routing. Essentially, you can gain knowledge about the use of the ASP.NET framework using this book. The examples are illustrative rather than ones you can follow along so if you haven't got ASP.NET programming experience, it could get difficult to try to code the examples yourself.

If you would like to go beyond the basics, the Pro ASP.NET MVC 4 book is for you:

This book has a 4.5 star rating (with 67 reviews) and explains design issues for you application when using the ASP.NET MVC framework and helps understand the concept of filters, provides an introduction to using custom view engines, dealing with advanced model binding issues, using APIs, and dealing with deployment issues. The examples are simple enough to follow along and that would leave you wanting to see more complex examples, but it does help you understand the concepts rather than leading you to the solution of every problem you would encounter.

Monday, August 12, 2013

Python Modules

Modules are used in Python to separate code into multiple files and thus make your source code more manageable. This presentation provides a quick guide to using modules in Python.

Decimal Numbers in HTML5 Input Number

The HTML5 number input element type helps eliminate the need to validate numeric input through client-side Javascript as the validation would be performed by the web browser. However, one common problem faced by web developers is that the number input element type indicates that any number with a decimal point is invalid input.

This is because, by default, the step for the number input element type is 1 therefore the validation enforces the use of whole numbers. You can enforce the number of decimal points by setting the step to a value such as 0.1 for one decimal place, or you can set step="any" to allow any number of decimal places. You would therefore have something like the following:

<input step="any" type="number" />

Saturday, August 10, 2013

ASP.NET MVC: Why Should I Move From Web Forms

Having used ASP.NET MVC quite extensively, I can tell you that ASP.NET Web Forms is quite good for prototyping. However, when you get to building Internet applications, ASP.NET MVC provides you with a lot of control over the markup of your application. Sure, it is more effort when you want to build the user interface and at times I did think that something I was building would have taken lesser time to build with ASP.NET Web Forms - quite possibly one of the reasons why Microsoft announced one ASP.NET, a statement that you can mix ASP.NET MVC and ASP.NET WebForms code within the same project.

ASP.NET MVC provides scaffolding (through code-generation) to reduce the effort involved in creating ASP.NET MVC user interfaces. Well, it is supposed to - it is still buggy when dealing with relationships between entities but when you have unrelated entities it works perfectly. This is most likely something that would be fixed in the next release or in one of the updates to Visual Studio. You can also take advantage of a wide variety of HTML/CSS/Javascript user interface components that you can use with ASP.NET MVC so if you need to build a user interface coherent with one built using PHP, Python, or Ruby, you don't have to create subclasses of the Label, TextBox, GridView, and ListView controls or add 'hacky' (seriously, doing a find-and-replace on the generated markup is an unnecessary CPU overhead) event handlers to alter the markup. The additional effort that you put into create the MVC views does pay off because with model binding, ASP.NET MVC can perform validation with nothing more than annotations (attributes) on your model. HTML 5 control rendering is also possible through adding attributes to your model. Sure, purists would argue that you shouldn't be adding attributes on your model to affect the presentation of your application but all you are doing is further describing the type of data being stored using the model and the view simply adapts (if you want it to).

I would also like to mention that when you do see performance benchmarks comparing a Hello World page in ASP.NET MVC, make sure that the benchmarks compared the ASP.NET MVC framework to another MVC framework - there are some comparisons of a Handler-like (ASHX) processing mechanism on other platforms to a Hello World on ASP.NET MVC and that just isn't fair - as soon as you use MVC, you've got routing and that adds additional processing to the application so you are bound to get lower performance scores when compared to a non-MVC framework.