Database Safe Values, Using Generics, and Extension Methods

In my early years as a Developer I was using DotNetNuke and often had large Data Access Layers (DALs) to abstract the database away from my application. I quickly found myself checking to ensure that a value returning from the Database wasn’t NULL (\0), so I created a helper class that had a number of methods for each data type I interacted with.  This created was done similar to this code below:

 public static double ConvertNullDoubleobject field)
 {
       if (field != DBNull.Value)
           return Convert.ToDouble(field);
       return 0; // or if my application had Defaults Global.DefaultDouble
 }

This seemed like a great solution at the time, but is quite a lot of code, as you are writing a method for every…single…datatype that your application interacts with. Being in a Small Business you didn’t really get the ability to refactor code that often, so once it was written you stuck by it.

Moving along in my career I stepped into Environment that already had full DALs in place so I would mimic what the previous developer did in order to keep the code base easily maintainable, as there is never a lack of fun trying to understand more than one persons point of view across a piece of code.

Tonight I was scanning through twitter and noticed Ben Alabaster [@BenAlabaster] asking a quite a unique question on twitter. So I piped in with my two cents, and then the conversation sparked beyond twitter to msn, then eventually to Skype. Here is the unique Single Helper Method we came up with:

For .NET 2.0, a static method:

public static T ConvertDBNullToSafeOrDefaultTypeValue<T>(object field)
{
      if (field != DBNull.Value)
          return (T)Convert.ChangeType(field, typeof(T));
      return default(T);
}

For .NET 3.5, an Extension method:

public static T ConvertDBNullToSafeOrDefaultTypeValue<T>(this object field)
{
      if (field != DBNull.Value)
           return (T)Convert.ChangeType(field, typeof(T));
      return default(T);
}

This solution provides a source code friendlier way of returning values from a database and validating the data against your business rules [you can replace default(T) is a Generic way of handling your applications default values].

Happy Coding!

How to Change ASP.NET MVC ValidationMessageFor from <span> to <label>

When it comes to providing a more usable interface for your user, I find that labels are the key. Being able to style a label as an error message and position it where you need it for your user is great, the added functionality being, if the user clicks on the label it lands their cursor nicely in the corresponding field [provided you have filled in the ‘for’ attribute].

When it comes to ASP.NET MVC, Microsoft made the choice to go with a <span> tag instead of the <label>.  I’m not sure why they made this decision, and please feel free to comment below if I’m breaking an html rule here, but a label for error validation just seems to be a no brainer to me.

If you feel the same here is a snippet of Code I created to be change a ValidationMessageFor Extension Method into a Method that provides the label error messaging.

I know that Regular Expression can cause some performance issues, and I don’t call myself a RegEx Master, so if you find a more efficient way to do this please Contact Me, and I will be sure to post the code change.

Remember: “friends don’t let friends __doPostBack();”

Happy Coding!

Clearing the Skies around Windows Azure

 

 

As I tour around Canada doing talks on Windows Azure at conferences and user groups, I found that the biggest concern around the cloud computing paradigm shift is cost. Slightly confused as to how a key offering of a platform is a sticking point against its adoption, I asked for some feedback. Here are some findings:

 

  • If I invest in developing against a particular platform, how simple is it to migrate to a different platform?
  • If the project that is deployed to the cloud doesn’t require the grade of redundancy and scalability in the cloud, is it possible to host the project in house in order to save money?
  • How is cost accumulated for billing?

There are a few things that I’ve taken away from some of the feedback that I’ve gathered at the talks that I’ve done thus far. There is definitely a lack in understanding of the billing model of Windows Azure, but there is also a misunderstanding of the advanced infrastructure that Microsoft has unveiled. In this post, I plan to clarify some of the misunderstandings about the Windows Azure Platform.

Will I get a Migration Migraine?

To speak towards the first point, there are always many things to consider when choosing one platform over another. Each platform will normally have different offerings to attract a market from their competition. It’s ultimately up to the Developer or Systems Architect to make the decision to leverage those offerings, which could potentially “lock” an application into a particular platform.

If you are worried about your application being “locked” into the Windows Azure platform, you can opt out of the choice to use the Storage Services and leverage a [potentially larger] database instead. It’s the cost that will ultimately steer you in one direction or another on platform, and further more the features of said platform. On the plus side, leveraging Storage Services over a database while using Windows Azure gives you the ability to limit the cost of your application, while increasing the response speed of data transactions (Storage Services can be partitioned and scaled across multiple nodes, and also have a ).

If you feel the need to pull your application off of the Azure Platform, you can export the data in the Storage Service into a CSV, or Excel formatted file using the Azure Storage Explorer. The only extra cost of migration would be writing a script in order to migrate the data into your next storage solution, which is slightly more work then if you were migrate directly from one database to another, assuming there is a clear migration path between the two.

Windows Azure Billing Overview

Considering that the billing model for Windows Azure is a little complex, I though I’d take some time to break it down into sections, and outline some common misconceptions in each section, so it can be better understood. When deploying to Windows Azure you will be billed for the following categories: Compute Time, Storage Services, SQL Azure, AppFabric, Data Transfers.

Windows Azure Costs

The Core Costs

The Chart Above taken from my presentation “Taking it to the Cloud with Windows Azure” is an outline of how the charges are broken down. The Core Costs [cost that are billed each month for the service] of Windows Azure are Compute time, Storage Services, and Data Transfer.

Compute Time is billed out depending on the Instance Size you are running your application on. This cost is accumulated in real-time hours as long as you have resources allocated to a particular instance, I will review this in more detail below.

Storage Services aren’t necessarily required, however you are able to store Diagnostic information in table storage to keep track of errors and restarts of your applications in the cloud. Storage Services are also handy when you are using Worker Roles [behaves much like a Windows Service] to process long running/scheduled tasks, or tasks that require heavy lifting.

Data Transfer is metered by the amount of data that is travelling in or out of the data center. This is where you can benefit by optimizing your web application by using the ASP.NET MVC Framework to help minimize the size of your pages leaving the data center.

Situational Costs

That covers the “Core Costs” of Windows Azure, which leaves the additional three items at the bottom of the chart SQL Azure, App Fabric and Simultaneous Staging Environments.

SQL Azure is a full scale RDBMS running in the cloud, it is built on SQL Server 2008, and carries a few minor limitations over a regular SQL Server installation. SQL Azure isn’t a Core Cost as you can leverage Storage Services to create a Non-Relational Entity based Storage System and manage any needed relationships in Code. However, a lot of applications do require a more robust system, which will require a Relational Database.

Windows Azure AppFabric [not to be confused with Windows Server AppFabric] offers both Access Control Services for Cloud based Security as well as a Service Bus in which you could expose an on premise Database to the Cloud. Both could be leveraged in unique scenarios, but not necessary for all applications as .NET Roles and Membership Providers can still be leveraged in the cloud.

Simultaneous Staging Environments are costs that will occur from time to time when you are in the staging phase of a deployment. This occurs when you have both the Production and Staging Environments of your Hosted Service in use at the same time. I will explain this more in detail below.

Calculating Costs on Azure Compute Hours: Compute Sizes

The first thing you have to understand when calculating Windows Azure compute costs is that compute instances come in four (4) unique sizes to enable complex applications and workloads. These virtual compute instances are virtual machines running within one of currently six (6) data centre containers:

Compute Instance Size CPU Memory Instance Storage I/O Performance
Small 1.6 GHz 1.75 GB 225 GB Moderate
Medium 2 x 1.6 GHz 3.5 GB 490 GB High
Large 4 x 1.6 GHz 7 GB 1,000 GB High
Extra Large 8 x 1.6 GHz 14 GB 2,040 GB High

 

This is important to remember as the compute costs are directly related to the size of instance you choose. (Note: The default instance size is currently SMALL, if you wish to modify this it can be found in the Properties screen of your Web Role.)

Compute cost per size is as follows (note: prices are subject to change):

  • $0.12 / hour for the SMALL instance
  • $0.24 / hour for the MEDIUM instance
  • $0.48 / hour for the LARGE instance
  • $0.96 / hour for the EXTRA LARGE instance

When you check your bill, all instance hours are converted to SMALL instance hours and is billed at $0.12 / hour. If you have two (2) MEDIUM Instances running, you will be billed for four (4) SMALL instances. It is important to note that instance hours are accumulated by each hosted service that contains a deployed project, regardless if the service is running or suspended.

Deployment and Staging Environment

One of the nice features of Windows Azure is it gives you a staging environment in which you can test your application in parallel to your Production Deployment before promoting the new code into production.

In this screenshot (below), you can see the production and staging environments. The Production Environment has an active deployment, you can identify when charges are accumulating by the cube under each of the environments. If the Cube is Blue the Instance is Accruing Charges, likewise when the cube is Grey the Instance is inactive and no longer accruing charges. If both your Production and Staging environments have a Deployment [Cubes are Blue] Both Instances are Subject to Billing.

Note: In order to deactivate a deployment you must Suspend the application and Delete the Deployed Cloud Service Package.

Windows Azure Deployment Portal

Calculating Azure Storage Space

Windows Azure Storage is calculated in two ways: (1) storage space measured in GB hours and (2) storage is billed by storage transactions. Now, I know what you’re thinking: “What exactly is a ‘GB hour’?” Assume there is 750 billable hours in a month. This means you can store 750GB of data for a billing period and you will get charged for 750GB. However, you could alternatively store 750GB for one (1) hour. As a result, your account would accrue 1 GB in storage charges since storage is billed at the following rates:

  • $0.15 / GB Stored / Month
  • $0.01 / 10K Storage Transaction

(Please note that billing fees are subject to change.)

The newly release Windows Azure Drive (XDrive) which is currently in beta will also be subject to this same pricing model, as the XDrive is a Page Blob which is mounted into Blob Storage and can be configured for capacities between 16MB – 1TB in size (up to 16 drives per VM).

Calculating Azure Data Transaction Costs

The last of the standard costs for Windows Azure is data transfer. Data transfer is the equivalent of bandwidth allocation in the traditional hosting model. These costs are calculated over the course of a month and billed out in terms of GB of data transferred, there is a separate rate for data being transferred in and out of Windows Azure.

North American & Europe Data Rates

  • $0.15 / GB Outgoing Data Transfer
  • $0.10 / GB Incoming Data Transfer

Asia Pacific Data Rates

  • $0.45 / GB Outgoing Data Transfer
  • $0.30 / GB Incoming Data Transfer

How to Forecast SQL Azure Charges

SQL Azure is another form of storage which is subject to both data storage and data transfer charges. SQL Azure databases are interesting as you can have as many databases as you need to consume your applications data. Charges are accumulated based on actual data usage per database.

From the pricing page for Windows Azure, the consumption rates for SQL Azure are as follows:

  • Web Edition:
    • Up to 1 GB relational database = $9.99 / month
    • Up to 5 GB relational database = $49.95 / month**
  • Business Edition:
    • Up to 10 GB relational database = $99.99 / month
    • Up to 20 GB relational database = $199.98 / month**
    • Up to 30 GB relational database = $299.97 / month**
    • Up to 40 GB relational database = $399.96 / month**
    • Up to 50 GB relational database = $499.95 / month**
  • Data transfers = $0.10 in / $0.15 out / GB – ($0.30 in / $0.45 out / GB in Asia)*

* No charge for inbound data transfers during off-peak times through October 31, 2010

** SQL Azure 50 GB Business Edition Database and 5 GB Web Edition Database will be available starting on June 28, 2010.

Understanding AppFabric Billing

As you may or may not be aware, AppFabric is a place in which you can expose a endpoint as a pipeline from the cloud to a non-cloud based system. This makes it a relatively unique platform to meter for billing. Microsoft has decided to make a “pay-as-you-go” model, as well as a number of packages to make a more customized experience for your particular business requirement.

Bundled in with AppFabric is Access Control which is a flexible and configurable security model for Windows Azure. Access Control is billed out based on a transactional basis.

  • Access Control: $1.99 per 100k transactions
  • Service Bus: $3.99 per connection on a “pay-as-you-go” basis, or:
    • Pack of 5 connections $9.95
    • Pack of 25 connections $49.75
    • Pack of 100 connections $199.00
    • Pack of 500 connections $995.00

Bringing it all together

Hopefully, you now have a better understanding of Windows Azure billing. I’ve covered all of the current items that would be billable in Windows Azure. There are however a couple of pricing models that are available as part of Introductory offers Microsoft has put forth to get people to try Windows Azure. If you are thinking of moving to this platform and would like to calculate some estimates of what your applications may cost to run in the cloud consult the TCO and ROI Calculator. To find out more information, check out the following resources:

Help Me, Help You… Windows Azure at Tech Days.

techdays_magnify Today at 5pm I received an important email that I had been waiting for, this email confirmed me as being a Session Leader at Tech Days 2010 in Canada.  This means I will be creating the slides and demos that will appear in the “Using Microsoft Visual Studio 2010 to Build Applications that run on Windows Azure”.  I have been speaking on Windows Azure across Canada, and up until now I’ve been showing off what I wanted to show you, now it’s your turn.

It’s a hard knock life, for us

office-space Being a Developer is challenging at times, we have to figure out the problems of the world. Although we all live in the same world, we all face different challenges; currently my challenge is to encompass a little bit of each of your lives into one hour of your time. This leaves me with one question what are the battles you’re going to be taking into the cloud? For this I need your help, Please leave a comment, or Contact me and let me know one thing that you think you can benefit from knowing about Windows Azure.

The Next Generation of Defensive Coding

If you’re a Software Developer, hopefully you understand the concept of Defensive Coding. If you’re not familiar with the term here is a quick example to explain the concept.

public string SomeMethod(string prefix, string rootWord, string suffix)
{
	// Ensure Parameters contain values.
	if(string.IsNullOrEmpty(prefix))
		throw new ArgumentNullException("Prefix cannot be null");

	if(string.IsNullOrEmpty(rootWord))
		throw new ArugmentNullException("RootWord cannot be null");

	if(string.IsNullOrEmpty(suffix))
		throw new ArugmentNullException("Suffix cannot be null");

	return string.Format("{0}{1}{2}", prefix, rootWord, suffix);
}

Defensive coding gives the benefit of ensuring that your method is being used properly by who ever is implementing your code, if the proper requirements aren’t met the code throws an exception and warns the Developer what particular parameters expects in order for the function to complete properly.

This concept has been used for years and has suited its purpose well. However there are certain things that this method doesn’t provide. Wouldn’t it be nice if these conditions could be validated by the IDE, before compiling your project? Enter Code Contracts.

codecontracts_sm Code Contracts were added to .NET 4, but are available to be used in previous versions of the .NET Framework by installing them from the Microsoft DevLabs Project Site. To use Code contracts you will have to Add a Reference to the System.Diagnostics.Contracts namespace.

 

Static Checking which is the feature of Code Contracts that works without explicitly compiling your code [Visual Studio Background Compilation is necessary], is unfortunately only available in Visual Studio 2010. [Aside: I use the term unfortunately here lightly, you really should Upgrade to Visual Studio 2010, Microsoft has done an amazing job, and you won’t be sorry]

To Mimic the code that I’ve shown above, however this time leveraging the Code Contracts.

public string SomeMethod(string prefix, string rootWord, string suffix)
{
	// Ensure Parameters contain values.
	Contract.Assert(!string.IsNullOrEmpty(prefix));
	Contract.Assert(!string.IsNullOrEmpty(rootWord));
	Contract.Assert(!string.IsNullOrEmpty(suffix));

	return string.Format("{0}{1}{2}", prefix, rootWord, suffix);
}

As you can see the implementation is much neater and easier to read than the blocks of if statements.  This is not the only functionality of Code Contracts either, you can let the contract pass the value through by using the Assume Method which assumes that the value is valid. Other Advantages include Code Based Documentation [Outlining what is expected by the method (in Code, because no one likes making XML Comments)], Business Rule Validation, Can be evaluated on TFS Gated Check-in.

Once I start using Code Contracts in more depth, I’ll be sure to start giving you more real life implementation scenarios. As always be sure to check back!

Until then, Happy Coding!

You asked, Microsoft Delivered. Free Time on Windows Azure.

If you were one of the developers at one of my talks that was tempted to try Windows Azure, but didn’t want to pay to give the platform a shot, here is your chance.  Previously, the only way to get some time on Azure was to have an MSDN Subscription but Microsoft noticed that a lot of their audience that wanted to try out the Azure a Platform didn’t have a subscription.

Microsoft has announced the Windows Azure Introductory Special which offers 25 free hours per month on a Small instance, a Web Edition SQL Azure Database, 2 Service Bus connections to AppFabric, and 500MB of Transfers coming to, and going from the Cloud.  This is a fairly decent starting point for someone trying to launch an existing application to Windows Azure.

How do I get started?

If you just came across my blog there are a few posts that you may want to check out to get up to speed on Windows Azure:

You can also get some tools and an a free IDE to help you deploy your project to the cloud.

Where do I sign up?

Head on over to the Windows Azure Offers page, and click the Buy Now button under the Introductory Special.

What do I do next?

Head out to TechDays 2010 for some Training on Windows Azure.

[Update]

The Microsoft DPE Team in Canada is Dedicated to answering your questions about Windows Azure. If you have a question you would like to ask directly to a Microsoft Representative email the Canadian team at

[/Update]