Thursday, August 18, 2011

Using the Flags attribute with an Enumeration

I was recently tasked with adding an attribute to an object.  This object persists in the database and I assumed that adding an attribute meant I would add a new property to the class, add a new column to the database and tie it all together.

Well, that wasn't the case.  The implementation that was already in place used an enumeration for the collection of possible attributes.  That enumeration allowed more then one value to be stored.  The enumeration was then converted into an integer as it was stored in the database.  All I had to do to add the new attribute was add an additional value to the enumeration.

This served as yet another epiphany on how something works and then the realization that I have seen and used this before in many places already. What I am talking about is using an enumeration of values as a bitmask.

Now the trick if you want to call it that is each numeric value of the enumeration was 2 multiplied by the preceding value (except for zero and one) and the enumeration has a Flags attribute.  Here is some example code:

[Flags]
public enum Colors : int
{
    None = 0,
    Red = 1,
    Blue = 2,
    Yellow = 4,
    Green = 8,
    White = 16
}

Since the values of the enumeration above are actually numeric they are represented by the following table:

Color Number 32 Bit Definition
None 0 00000000000000000000000000000000
Red 1

00000000000000000000000000000001

Blue 2

00000000000000000000000000000010

Yellow 4

00000000000000000000000000000100

Green 8

00000000000000000000000000001000

White 16

00000000000000000000000000010000

Since the enumeration is of type integer it will be stored as a 32 bit number. Since the integers are 32 bit each bit represents an enumeration value so the enumeration can only have 32 items.  If I wanted more then 32 items in the enumeration I could change the type of the enumeration to long.  This would store the value as a 64 bit number therefore giving you a capacity of 64 items in the enumeration.

Here is some example code showing how to add and remove colors:

Colors myColors = Colors.None;

//lets add some colors
myColors = myColors | Colors.Red;
myColors = myColors | Colors.Green;
myColors = myColors | Colors.Blue;
myColors = myColors | Colors.White;

//lets remove a color
myColors = myColors ^ Colors.White;

The table below represents the value of the myColors variable at each addition and removal of a color.

Colors Number 32 Bit Definition
None 0 00000000000000000000000000000000
Red (1) 1

00000000000000000000000000000001

Red (1), Green (8)   1+8=9 9

00000000000000000000000000001001

Red (1), Green (8), Blue (2)  1+8+2=11 11 00000000000000000000000000001011
Red (1), Green (8), Blue (2), White (16)  1+8+2+16=27 27 00000000000000000000000000011011
Red (1), Green (8), Blue (2) 1+8+2=11 11 00000000000000000000000000001011

Notice the 32 bit representation of the value of the colors above.  Each bit that is ON is 1 and the ones that are OFF are 0.

So how would you figure out what enumeration item values where ON with out the computer?  All you need to know is the enumeration value and the values of the individual enumeration items.  Lets take the value 27 for example. Going from highest enumeration item value that can go into the value we can figure out what colors are ON in the enumeration value.

27 – 16 (White) = 11
11 – 8 (Green) = 3
3 – 2 (Blue) = 1
1 – 1 (Red) = 0
Answer = White, Green, Blue and Red.

The value of myColor variable would get saved to the database as an integer value. I wondered how or if I could use SQL to figure out which items where ON or OFF.  As long as I know the value of the enumeration items I am looking for I can use that information to query the data.  Look at the following SQL script to see how to do it.

declare @colors as table (
    id int,
    name nvarchar(100) not null,
    colors int not null
)

insert @colors (id, name, colors)
values
(1, 'Red', 1),
(2, 'Red, Green', 9),
(3, 'Red, Green, Blue', 11),
(4, 'Red, Green, Blue, White', 27),
(5, 'Red, Green, Blue', 11)

--lets get all the rows that have white in them
--we know white is 16
select *
from @colors
where colors & 16 = 16

--lets get all the rows that have blue and green but not white
--we know blue = 2m green = 8 and white = 16
select *
from @colors
where colors & 2 = 2 and colors & 8 = 8 and colors & 16 = 0

 

My Thoughts

While the initial issue with using this technique is that you are limited to the number of items in the enumeration depending on what data type you use.  I feel if you know you will use less then the maximum number of items in the enumeration this implementation would work.  Not having to add a new column to a database table every time you add an attribute sounds like a real win.

Monday, July 25, 2011

Finally found a cool use of a SQL Cross Join

Setup:
Lets say you have a list of contacts stored in a contacts table and a list of attributes stored in an attributes table.  So lets say that each contact can have one or more attributes and each attribute can be used on one or more contacts.  To do this we would need to use a many to many table, something that stores the id of the contact and the id of the attribute.  For example:

create table ContactsAttributes (
    ContactID int not null,
    AttributeID int not null
)

Now lets say we just added 2 new attributes (attribute id: 10 and 11) to the attribute table and we needed to add them to 3 specific contacts (contact id: 1,2,3).  In this instance it would be easier to just write out the insert statements like so:

insert ContactsAttributes (ContactID, AttributeID)
values
(1, 10),
(1, 11),
(2, 10),
(2, 11),
(3, 10),
(3, 11)

As you can see this is pretty straight forward.  Now lets say we added 10 attributes and we needed to add all 10 of these attributes to 20 specific contacts.  Since there are 10 attributes that need to be added to 20 contacts that would be 200 items to write in the table constructor of the insert statement.  Using a Cross Join like below would be considerably less code and way cooler.

DECLARE @contacts AS TABLE (id int)
DECLARE @attributes AS TABLE (id INT)

INSERT @contacts (id) VALUES
(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11)
,(12),(13),(14),(15),(16),(17),(18),(19),(20)

INSERT @attributes ( id ) VALUES
(10),(11),(12),(13),(14),(15)
,(16),(17),(18),(19),(20)

INSERT INTO ContactsAttributes
SELECT c.id, a.id
FROM @contacts c
CROSS JOIN @attributes a

Using the cross join basically returns all possible combinations of the id column in the contacts table variable with the id column of the attributes table variable.  This is what is known as a Cartesian Product.  To see the results as they would be inserted comment out or remove the “INSERT INTO ContactsAttributes” line.

Saturday, May 14, 2011

JavaScript: Get your console on…

Since I have been listening to both the “Official jQuery Podcast” and the “yayQuery podcast” JavaScript and jQuery have been on my mind lately.  It doesn’t hurt that some bugs I have fixed at work required mucking around in some jQuery.  Someone from one of those podcasts referenced some things that you can do with the console in both IE and Firefox (with Firebug). Today I wanted to show some of the power of playing with the console.

I will be using IE 9 as my example browser today but you can do these things in Firefox and Google Chrome.  So first lets open IE 9 and go to www.devdave.com.  Press F12 to open up the developer tools of IE (documentation).  You should notice an explorer bar, usually across the bottom of the screen.

image
  1. In the HTML tab press the arrow button. (This will allow you to select an html element on the screen.)
  2. Move the mouse and click the div containing the random quotes displayed on the site.
  3. Note that there is a tree view that represents the document object model and it is now highlighting the object that you selected.  Note that here you can see the class that this object has applied to it.  We are going to use that along with some jQuery to make that div slide up without having to write the code in the page.

Now that we know the class assigned to the div we can use that as a selector in jQuery.  Two tabs over from the HTML tab there is a Console tab clicking that will open up a new part of the developer tools.

image At the bottom of the screen you should see >> .  This is where you can type some JavaScript.  In order for the following to work the page you are working with needs to already have loaded jQuery.  Since this page has already done that lets go ahead and type

$(".tm-section")

into the console and press enter.  Note that the console is displaying a bunch of information regarding the object you selected.  If the selector you typed was correct you should see that the length property returns a value of 1.  If we had mistyped the selector then the length would be 0.

This would be a great way to practice using different types of selectors.

Since we have the correct selector we can type this to make the selected object slide up.

$(".tm-section").slideUp("slow")

And then we can type this to make it slide down.

$(".tm-section").slideDown("slow")

 

image So one line to write code might not be enough. Lets say you wanted to write a function or two. The console window has a button on the far right of where you type commands it’s the chevron symbol next to the green play button.  Clicking that will open a text area where you can write multiple lines of code.  Write the following in the script area and click the Run Script button.

 

function toggle(){
   $(".tm-section").slideToggle('slow', function(){
     alert("done");    
   });
}

toggle();

Pressing the Run Script button multiple times will cause the slide to toggle and an alert message to be displayed when its done.

As you can see this technique can really help in debugging or interrogating already running JavaScript. I have used this technique to debug asynchronous data paging issues, Google map marker issue.or just figuring out the correct selector syntax to select one or more objects in the DOM.

Podcasts I listen to

I know, not really a technical post but I would like to list out the podcasts I listen to.  Since I started working at a new job my commute takes just about an 1 hour to get to work.  The good thing about that is it gives me more time to listen to a full podcast instead of having to break it up between the drive to and from work.

Here is the list of podcasts along with links to their websites:

Friday, April 15, 2011

JavaScript, the revealing module pattern

Lately I have been doing a lot of things with JavaScript and jQuery.  After doing some research I found some information on the revealing module pattern.  This pattern has really helped me to organize the work I do in JavaScript.  I find this to be very easy to read and debug.

  1. var Module1 = function () {
  2.     var selectors = {
  3.         nameTextBox: '#nameTextBox',
  4.         cancelButton: '#cancelButton'
  5.     }
  6.  
  7.     var urls = {
  8.         cancelUrl: 'http://homepage.com'
  9.     }
  10.  
  11.     var privateFunction1 = function (msg) {
  12.         alert(msg);
  13.     }
  14.  
  15.     var privateFunction2 = function (msg) {
  16.         privateFunction1(msg);
  17.     }
  18.  
  19.     var init = function () {
  20.         $(selectors.cancelButton).click(function () {
  21.             window.location = urls.cancelUrl;
  22.         });
  23.     }
  24.  
  25.     return {
  26.         selectors: selectors,
  27.         urls: urls,
  28.         init: init,
  29.         publicFunction: privateFunction2
  30.     }
  31. } ();
  32.  
  33. $(document).ready(function () {
  34.     Module1.init();
  35.  
  36.     Module1.publicFunction("Testing 123");
  37. });

The module consists of lines 1 – 31, you can see that all items defined in the module are locally scoped to the module.  Lines 25 – 30 define what will be publicly accessible outside of the module.  Note that line 29 defines a different public name in comparison to its internal name.  Also note that objects inside of the module can access each other.  Line 16 is calling the private function on line 11.  Trying to call privateFunction1 from outside the module would not be possible.

Also in this example I am showing some common things I like to do.  For example lines 2 – 5 define an object for selectors.  I make this selector object public incase the page that consumes this module needs to change the values.  Everywhere else in the module I call the selectors from the selector object.  This way if I need to change a value either manually in this script or dynamically from the page it is only done in one place.  Note lines 7 – 9 define the same thing although this time its urls.  Since I do a lot of my work in MVC I assign the url values on the consuming page using the url helpers.

In another post I will go over the organization and utilization of this pattern in an MVC 3 application.

Sunday, March 20, 2011

Modifying the jQuery UI Calendar Date Selection

While working on an application I had a need to modify the way dates where selected from the jQuery UI calendar control.  I needed to only allow the end user the capability of selecting a Monday.  After some searching of the internet I found the following solution.

/* date picker week */
$(".dateweek").datepicker({
    showOn: 'both',
    buttonImage: '/Content/Images/ui/calendar.png',
    buttonImageOnly: true,
    firstDay: 1,
    beforeShowDay: function (date) { return [date.getDay() == 1, ""] }
});

I can’t remember where exactly I got it although I did make some modifications to it.  The code I actually used is above.

Thursday, February 24, 2011

Fun with the SQL Output clause

The other day I was brushing up on my SQL skills by watching some training videos on Pluralsight. As I was watching, the presenter showed how the Output clause works. After playing around with it some more I decide to do this blog post.

So lets get started.  First lets create a temp table to work with.

create table #temptable (
    ID int not null identity primary key,
    FirstName nvarchar(100) null,
    LastName nvarchar(100) null,
    Cartoon nvarchar(100) null
)

Now lets insert some data using the output clause as part of the insert.  Note the script below is using the Table Row Constructor syntax.  This becomes extremely powerful when used with the output clause.

insert into #temptable
output inserted.ID, inserted.FirstName, inserted.LastName, inserted.Cartoon
values
('Fred','Flintstone', 'The Flinsones'),
('Wilma','Flintsone', 'The Flinsones'),
('Pebbles','Flintstone', 'The Flinsones'),
('Dino','', 'The Flinsones'),
('Barney','Rubble', 'The Flinsones'),
('Betty','Rubble', 'The Flinsones'),
('Bamm-Bamm','Rubble', 'The Flinsones'),
('George','Jetson', 'The Jetsons'),
('Jane','Jetson', 'The Jetsons'),
('Judy','Jetson', 'The Jetsons'),
('Elroy','Jetson', 'The Jetsons')

When this script is ran in SQL it will insert the rows into the temp table and return a result set that looks like this:

ID FirstName LastName Cartoon
1 Fred Flintstone The Flinsones
2 Wilma Flintsone The Flinsones
3 Pebbles Flintstone The Flinsones
4 Dino   The Flinsones
5 Barney Rubble The Flinsones
6 Betty Rubble The Flinsones
7 Bamm-Bamm Rubble The Flinsones
8 George Jetson The Jetsons
9 Jane Jetson The Jetsons
10 Judy Jetson The Jetsons
11 Elroy Jetson The Jetsons

The inserting of data and the returned result set is done as a single transaction or round trip to the server.  The other benefit to this is the result set included the ID (identity) of each row.  Normally I would have re-queried the data to get this information.

Now let me show you an update using the output clause.  In the script below I am fixing the misspelling of Flintstone.

update #temptable
set Cartoon = 'The Flintstones'
output inserted.ID, deleted.Cartoon OldCartoonValue, inserted.Cartoon NewCartoonValue
where Cartoon = 'The Flinsones'

When the script is ran in SQL it will update the rows and return a result set that looks like this:

ID OldCartoonValue NewCartoonValue
1 The Flinsones The Flintstones
2 The Flinsones The Flintstones
3 The Flinsones The Flintstones
4 The Flinsones The Flintstones
5 The Flinsones The Flintstones
6 The Flinsones The Flintstones
7 The Flinsones The Flintstones

Note that once again a single transaction to the server and a result set that references the ID’s that where updated along with the old cartoon value and the new cartoon value.  Keep reading below to learn more about the inserted and deleted column prefixes.

Now let me show you a delete with the output clause.  In this script below I am deleting any rows that have the last name of “Rubble”.

delete #temptable
output deleted.ID, deleted.FirstName, deleted.LastName, deleted.Cartoon
where LastName = 'Rubble'

When the script is ran in SQL it will delete the rows and return a result set that looks like this:

ID FirstName LastName Cartoon
5 Barney Rubble The Flintstones
6 Betty Rubble The Flintstones
7 Bamm-Bamm Rubble The Flintstones

Not that once again a single transaction to the server and a result set that references the rows that where deleted.  Imagine if you used this in some sort of logging situation.

When using the output clause there are two special column prefixes to use:

  • Deleted: Is a column prefix that specifies the value added by the insert or update operation. Columns prefixed with INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed but before triggers are executed. (DELETED cannot be used with the OUTPUT clause in the INSERT statement.)
  • Inserted: Is a column prefix that specifies the value added by the insert or update operation. Columns prefixed with INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed but before triggers are executed.(INSERTED cannot be used with the OUTPUT clause in the DELETE statement.)

Wednesday, February 2, 2011

Getting custom extension methods to work in ASP.NET MVC 3 & Razor View Engine

I am going through the process of converting my site to use ASP.NET MVC 3 with the new razor view engine.  I use many extension methods that I have added to the HtmlHelper.  I store all these helpers in the following namespace “DevDave.Infrastructure.Helpers”.

In MVC 2 I added the namespace “DevDave.Infrastructure.Helpers” to the web.config file in the root of my MVC project like so:

<pages>
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="DevDave.Infrastructure.Helpers"/>
  </namespaces>
</pages>

This allowed me to use my custom helpers in all of my pages. So naturally I figured that the same thing would work for the MVC 3 application.  As it turns out it doesn’t, I get this stupid error instead:

image

As you can see it can’t seem to find my extension method “MainMenu”.  Now I did figure out that you could just add a using statement to the top of each page like this:

@using DevDave.Infrastructure.Helpers

Well I don’t want to have to put this in every view so then I tried to add the using statement into the _ViewStart file in the root of the views folder.  Like so:

@{
    using DevDave.Infrastructure.Helpers;
    
    Layout = "~/Views/Shared/_Layout.cshtml";
}

This did not work either something about having a using statement inside a code nugget.  So I moved it to its own line like so:

@using DevDave.Infrastructure.Helpers

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

This still did not work.

To fix this I had to add the name space to the web.config inside of the views folder instead.  Like so:

<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
      <add namespace="DevDave.Infrastructure.Helpers"/>
    </namespaces>
  </pages>
</system.web.webPages.razor>

This fixed the problem.

Getting Ninject to work with MVC 3

Before getting started lets make sure everyone is on the same page.  The screenshots and descriptions below assume the use of the following products and tools.

  • Visual Studio 2010
  • ASP.NET MVC 3
  • .NET 4.0 framework

Lets start by creating a new ASP.NET MVC 3 Web Application

image

Lets go ahead and choose the Empty template.  We can bypass using a Test Project at this time.

image

Once the solution is created lets add the following folder structure:

image

Monday, January 24, 2011

Removing the mixed content warning when using Bing Maps API v7.0 over SSL

The other day I was building a store locator for a colleague of mine.  I the application up and running without any issues although when it came time to deploy to production I ran into a problem.  The production environment was being ran over SSL and since the link I used to get the Bing Maps API was not using the HTTPS version I would get a mixed content warning.

Luckily the API documentation from Microsoft recommended a different link.

Here is the one I was using prior to the SSL upgrade:

<script charset="UTF-8" type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

Here is the link I changed it to:

<script charset="UTF-8" type="text/javascript" src="https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&ssl=1"></script>

Now the problem is that this still does not work.  As it turns out there is an error in Microsoft’s documentation here.  Here is the correct version:

<script charset="UTF-8" type="text/javascript" src="https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&s=1"></script>

Note that the query string parameter at the end of the URL should be s=1 not ssl=1.  Making this caused the rest of the scripts loaded by the Bing Maps API to be delivered over SSL.  This got rid of the mixed content warning.

Sunday, January 16, 2011

LINQ to SQL data context modifications

Many times while working with LINQ to SQL I find my self needing some sort of read only version of the data context.  Many operations run against the data context are primarily reading data anyways.  Due to this there is no need for LINQ to SQL to keep track of the state of the items it gets from the database.  Below is an example of the data context modification I use for my personal website.

public partial class DevDaveDataContext
{
    public static DevDaveDataContext ReadOnly
    {
        get
        {
            return new DevDaveDataContext() { ObjectTrackingEnabled = false };
        }
    }

    public static DevDaveDataContext Instance
    {
        get
        {
            return new DevDaveDataContext();
        }
    }

}

With the above code in place, here are a couple different ways I could access the data context.

using (var db = DevDaveDataContext.ReadOnly)
{
    ...
}

var db = DevDaveDataContext.Instance;
var db = DevDaveDataContext.ReadOnly;

Monday, January 10, 2011

Localization in ASP.NET MVC2 with Data Annotations

Let’s start by getting everyone on the same page.  Create a new Project | C# | Web | ASP.NET MVC 2 Web Application using the .NET Framework 4. With or without a test project, it’s up to you.  In this example we will setting up both English and French translation.  Adding more languages should be straight forward.

Setting up the Resource folder structure.

image

 

At the root of your MVC application create a Resources folder.  Inside this folder create a folder structure like the one to the left.

I like to try and keep all the resources organized so under the Models and Views folders I like to break things apart by controller.  Ultimately how you choose to store these items is up to you.  Changes to the folder structure will affect the namespaces.

Adding resource files and what you need to know.
Adding a resource file is the easy part.  Making the setting changes that are needed turns out to be a repetitive process that will get old real fast.  Right click on the Views | Home folder and select Add | New Item.  In the Add new item dialog type the word resource into the search installed templates textbox in the upper right hand corner. Select the Resource File template and type Index.resx.
image

Once the file has been added it should open up in edit mode.  Make the following changes:
image

Accessing the resource details is pretty straight forward after this part.  For example you could type the fully qualified name of a resource property like “applicationname.Resources.Views.Home.Index.PageTitle”. 

image

That namespace tends to be a little long so add the following to the properties of the resource file.

Add a custom tool namespace to the resource file “ViewRes.Home”.  You will then be able to access the values like “ViewRes.Home.Index.PageTitle”.

This process turns out to be one of the repetitive processes I was referencing above.  In order to limit the namespace length this modification must be made on each file for each language although its not required.

Also note that the second part of the entered namespace will need to change depending on what folder you are in for example you may change the namespace to “ViewRes.Account”.

Let’s go ahead and add the French file.  Do the same as above but make sure the name of the resource file is Index.fr.resx.  Don’t forget to change the Custom Tool Namespace value in the properties of the resource file. Since this would be the French file make sure the values in the resource file are French.  I like to use Google translate (http://translate.google.com/) although I strongly recommend having this translation done professionally.  Here is the translation:

Message = Bienvenue sur ASP.NET MVC! Exemple de localisation
PageTitle = Page d'accueil avec une localisation

Note I use the following naming structure for my resource files:  {page}.{culture}.resx.  The culture value can be the short or long version of the culture string for example all of these would work.

  • Index.fr.resx
  • Index.en-fr.resx
  • etc…

If you do not include a culture in the file like we did with Index.resx then it will be considered the default.