Model Binding Checkboxes to a List

Posted by Dan | Posted in ASP.NET MVC, Web Development | Posted on 12-28-2011

0

Model binding things other than textboxes could be tricky in ASP.NET MVC. To correctly model bind, one has to follow a specific naming/value conventions in the HTML.

Let’s say we have a model object called People, and we have a List of states people have lived in.

  public class People
  {
    public List<string> StatesLiveIn { get; set; }
  }

And in our View we have as follows:

@model TestBinder.Models.People
 
foreach (string state in new List<string>() { "NY","NJ","FL","IL","TX" })
{     
  @state <input  type="checkbox" value="@state" name="StatesLiveIn" /><br />      
}

Out controller simple looks like this:

    public ActionResult Index()
    {
      return View();
    }
 
    [HttpPost]
    public ActionResult Index(People p)
    {
      return View(p);
    }

If we put a trace point at the return line, and inspect after the user has submitted only NY and TX…

…we’ll see that it was correctly bound…

Encrypt In ColdFusion and Decrypt in PHP

Posted by Dan | Posted in ColdFusion, PHP | Posted on 11-02-2011

0

A while ago, I had to integrate vBulletin into a CMS application. The CMS was done in ColdFusion and had to pass info encrypted data over to vBulletin which is PHP. It would be naive to think that one could just pick an encryption scheme (which are standards like Blowfish, AES, SHA, etc.) and look up in the reference manual for both languages … and that would be it? Ha! While testing these, I realized that each language has its own options (or quirks; however you want to look at it). In addition, you have to consider Base64 encoding and cipher blocks.

Here’s what I used for ColdFusion to do encryption. I’m listing two methods from two different sources

Method 1: Encryption uses blowfish with base64 encoding, using the block cipher mode ECB and Java objects.

 
<cffunction name="EncryptBlowfish1" returntype="string" hint="Encrypts string using Blowfish Algorithm"
  description="Encryption uses blowfish with base64 encoding, using the block cipher mode ECB.">
 
  <!--- This function serves as a wrapper for enhanced Blowfish encryption. Based on discussion --->
  <!--- from http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/Cold_Fusion_Markup_Language/Q_24753297.html --->
 
  <cfargument name="Data" required="true" type="string" hint="Text to encrypt" />  
  <cfargument name="Key" required="true" type="string" hint="16-char key to be used for encryption." />
 
	<!--- get a cipher instance --->
	<cfset Cipher = createObject("java", "javax.crypto.Cipher")>
	<cfset encryptor = Cipher.getInstance("Blowfish/ECB/PKCS5Padding")>
 
	<!--- must convert the key string into a KeySpec object first --->
	<cfset keySpec = createObject("java", "javax.crypto.spec.SecretKeySpec").init(Arguments.Key.getBytes(), "Blowfish")>
 
	<!--- initialize the cipher for encrypting --->
	<cfset encryptor.init(Cipher.ENCRYPT_MODE, keySpec) />
 
	<!--- do the encrypt --->
	<cfset encryptedTextFromJava = encryptor.doFinal(Arguments.Data.getBytes()) />
 
	<!--- finally convert it to base64 and return --->	
  <cfreturn BinaryEncode(encryptedTextFromJava, "Base64") />
 
</cffunction>

Method 2: Much faster.

<!--- THIS IS MUCH FASTER THAN EncryptBlowfish1 --->
<cffunction name="EncryptBlowfish2" returntype="string" hint="Encrypts string using Blowfish Algorithm"
  description="Encryption uses blowfish with base64 encoding, using the block cipher mode ECB.">
 
  <!--- This function serves as a wrapper for enhanced Blowfish encryption. Based on discussion --->
  <!--- from http://www.petefreitag.com/item/222.cfm --->
 
  <cfargument name="Data" required="true" type="string" hint="Text to encrypt" />  
  <cfargument name="Key" required="true" type="string" hint="16-char key to be used for encryption." />
 
  <cfreturn Encrypt( Arguments.Data, ToBase64( Arguments.Key ), "BLOWFISH", "Base64" ) />  
 
</cffunction>

Now let’s test it!

<!--- YOU'LL NEED THIS TO DECRYPT! --->
<cfset myKey = "dan is too uber!" />
 
<cfoutput>
#EncryptBlowfish1( "This is so friggin cool that it works!", myKey )#
<hr />
#EncryptBlowfish2( "This is so friggin cool that it works!", myKey )#
</cfoutput>

This is how you would decrypt it in PHP:

$__key__ = "dan is too uber!";
 
function DecryptBlowfish( $data, $key )
{
  // Encryption uses blowfish with base64 encoding, using the block cipher mode ECB 
  // to decrypt the $data string.
  //    $data = the text to be decrypted.
  //    $key  = the key used to be used, not base64 encoded.  
 
  return mcrypt_decrypt( MCRYPT_BLOWFISH, $key, base64_decode( $data ), MCRYPT_MODE_ECB );
}

Companies Who Use ASP.NET

Posted by Dan | Posted in ASP.NET (Web Forms), ASP.NET MVC, C#, Web Development | Posted on 10-20-2011

0

During a job hunt, I compiled a list of companies that use ASP.NET. Most of them, without a surprise, are big corporate ones. Also, not all of them use ASP.NET exclusively for their entire site/business. Many of these sites have subsites for their many divisions, so a mix of technologies are used.

I’m going to keep updating as I find more.

Microsoft Amazon
 

Getting Started with the MongoDB C# Driver

Posted by Dan | Posted in C#, Databases, MongoDB | Posted on 08-20-2011

0

Here’s my attempt on writing a super-barebones tutorial for using the MongoDB C# Driver. It’s a very hands-on tutorial-by-example, showing you the basics of the driver by creating console apps.

I’m assuming you’ve installed the official MongoDB C# driver and read the intro. Heads up on how you set up the driver. The .msi sets it up in the GAC. The zip file has the assemblies that can just be referenced in your project.

After you’ve done those two things, you can proceed. :)

Dependencies

In projects, you have the option of utilizing the following namespaces:

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization.Options;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Wrappers;

The most commonly used are Bson, Driver, Serialization, and Serialization.Attributes. This tutorial will use these four in all code samples, so make sure you include them in your app, even if I don’t have it in the code samples. You can learn more about the API/namespaces by checking out the docs.

Connecting to a MongoDB Database

Connecting is pretty simple. Once you include the C# driver assemblies, you connect as follows:

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      MongoServer  server = MongoServer.Create("mongodb://work2");
      MongoDatabase Cars = server.GetDatabase("Cars");
    }
  }
}

That’s pretty much all you need to connect. Of course, I recommend putting the connection string in the Web.config, or some initializer.

Inserting a document on MongoDB

There are tons of ways to do this, but one of the simplest ways is to create a class, create an instances of that class, and pass it into a MongoDB object that serializes that object into BSON and submits it to your database.

So for this example, before inserting a document into the database from C#, one has to do two things (aside from the establishing a connection and choosing which db to write to):

  1. Create a Generic Collection object. In this case, it’s a MongoDB collection.
  2. Create a class that’s to be used by the Generic Collection.

Those two go together.

Also, note that while working with MongoDB in C#, the word “collection” may be thrown around loosely. In MongoDB you have a “Collection” that’s comparable to a Table in a traditional ER database. A MongoDB “Collection” holds “documents,” which is comparable to a “record” in a traditional ER database. On the opposite side, in C#, a collection is a data structure that unlike an Array, can be resized dynamically and is more flexible as far as functionality.

The MongoDB Generic Collection is a C# collection that can hold any type of object, but it has to know what type of object it’s holding. You let it know what kind of type by creating a class, and then when you create a collection, you specify the name of the class. So for example, this is the syntax for creating a Generic Collection that has Car objects (where person is defined in a class):

After that line of code, you populate the vehicles object (remember it’s a MongoDB Generic collection that holds Cars objects), by calling the method “GetCollection” from the Cars object we creating in the last section “Connecting to a MongoDB database”:

In the above statement, if MongoDB does not find a collection on the database called “vehicles,” it will create it for you.

What does that Cars class look like? Pretty simple:

  public class Cars
  {
    public string _id { get; set; }
    public string brand { get; set; }
    public string lname { get; set; }
    public Int32 miles { get; set; }
    public int age { get; set; }
  }

Then of course, before sending it to the MongoDB database, you create an object and set the values of the object:

      Cars newCar = new Cars();
      newCar._id = System.Guid.NewGuid().ToString();
      newCar.brand = "Honda";
      newCar.miles = 186000;
      newCar.age = 1;

And then insert it in MongoDB:

vehicles.Insert(newCar);

To put it in perspective, here’s the entire program:

namespace ConsoleApplication1
{
  public class Cars
  {
    public string _id { get; set; }
    public string brand { get; set; }
    public string lname { get; set; }
    public Int32 miles { get; set; }
    public int age { get; set; }
  }
 
  class Program
  {
    static void Main(string[] args)
    {       
 
      MongoServer  server = MongoServer.Create("mongodb://work2");
      MongoDatabase Cars = server.GetDatabase("Cars");
 
      MongoCollection vehicles;
 
      vehicles = Cars.GetCollection("vehicles");
 
      Cars newCar = new Cars();
      newCar._id = System.Guid.NewGuid().ToString();
      newCar.brand = "Honda";
      newCar.miles = 186000;
      newCar.age = 1;      
 
      vehicles.Insert(newCar);
    }
  }
}

The insert method should serialize the Cars object (newCar) and create the MongoDB document, mapping the properties of the Cars class to MongoDB document key-pair values.

Let’s see how this got created in our database:

Run:

db.vehicles.find()

(e.g. ignore the lname property. This was removed in the source code)

Inserting Complex Objects in MongoDB

Let’s try inserting an object with a more complex data structure. Let’s assume we have the following class:

  public class Cars
  {
    public string _id { get; set; }
    public string brand { get; set; }
    public string lname { get; set; }
    public Int32 miles { get; set; }
    public int age { get; set; }
 
    public Hashtable history { get; set; }
    public Hashtable complex { get; set; }
    public int[] magicNumbers { get; set; }
  }

Now let’s declare the class and its properties:

      newCar._id = System.Guid.NewGuid().ToString();
      newCar.brand = "Honda";
      newCar.miles = 186000;
      newCar.age = 1;
 
      newCar.history = new Hashtable();   
      newCar.history.Add("2010-08-14", "Puss 'N Boots");
      newCar.history.Add("2011-12-01", "Puff the Magic Dragon");
      newCar.history.Add("2009-03-07", "Fraggle Rock");      
 
      newCar.magicNumbers = new int[3];
      newCar.magicNumbers[0] = 60;
      newCar.magicNumbers[1] = 186000;
      newCar.magicNumbers[2] = 1440;
 
      newCar.complex = new Hashtable();
      newCar.complex.Add( newCar.magicNumbers[1], newCar.history );
      newCar.complex.Add( System.Guid.NewGuid().ToString(), newCar.history);

It outputs the following (formatted for better reading):

{
  "_id": "a07513c8-9cb5-46cd-a9cb-425cabc0dd76",
  "brand": "Honda",
  "lname": null,
  "miles": 186000,
  "age": 1,
  "history": 
  {
    "2010-08-14": "Puss 'N Boots",
    "2009-03-07": "Fraggle Rock",
    "2011-12-01": "Puff the Magic Dragon"
  },
  "complex": 
  [
    ["eb7b3d4d-87b1-43c1-9fe7-5a5e4b5b79de",
    {
        "2010-08-14": "Puss 'N Boots",
        "2009-03-07": "Fraggle Rock",
        "2011-12-01": "Puff the Magic Dragon"
    }],
    [
    186000,
    {
        "2010-08-14": "Puss 'N Boots",
        "2009-03-07": "Fraggle Rock",
        "2011-12-01": "Puff the Magic Dragon"
    }]
  ],
  "magicNumbers": [60, 186000, 1440]
}

Now let’s look at the entire code for all this:

namespace ConsoleApplication1
{
  public class Cars
  {     
    public string _id { get; set; }   
    public string brand { get; set; }  
    public string lname { get; set; }  
    public Int32 miles { get; set; }  
    public int age { get; set; }
 
    public Hashtable history { get; set; }
    public Hashtable complex { get; set; }
    public int[] magicNumbers { get; set; }
  }
 
  class Program
  {   
    static void Main(string[] args)
    {
 
      MongoServer  server = MongoServer.Create("mongodb://work2");          
      MongoDatabase Cars = server.GetDatabase("Cars");
 
      MongoCollection<Cars> vehicles;
 
      vehicles = Cars.GetCollection<Cars>("vehicles");
 
      Cars newCar = new Cars();
 
      newCar._id = System.Guid.NewGuid().ToString();
      newCar.brand = "Honda";
      newCar.miles = 186000;
      newCar.age = 1;
 
      newCar.history = new Hashtable();   
      newCar.history.Add("2010-08-14", "Puss 'N Boots");
      newCar.history.Add("2011-12-01", "Puff the Magic Dragon");
      newCar.history.Add("2009-03-07", "Fraggle Rock");      
 
      newCar.magicNumbers = new int[3];
      newCar.magicNumbers[0] = 60;
      newCar.magicNumbers[1] = 186000;
      newCar.magicNumbers[2] = 1440;
 
      newCar.complex = new Hashtable();
      newCar.complex.Add( newCar.magicNumbers[1], newCar.history );
      newCar.complex.Add( System.Guid.NewGuid().ToString(), newCar.history); 
 
      vehicles.Insert<Cars>(newCar);         
 
      Console.ReadLine();                
    }     
  }
}

Reading the 1st MongoDB document from the database

Before you query the database, you must make sure the class and member types match the values/objects that the MongoDB connection will return.

Let’s try to fetch the 1st document. To see what we’re expecting, let’s fetch it via the console first:

db.vehicles.find().limit(1)

which returns:

{
  "_id" : ObjectId("4d95f30058430000007a5943"),
  "ObjectId" : ObjectId("000000000000000000000000"),
  "brand" : "Ford",
  "lname" : null,
  "miles" : 2500,
  "age" : 1
}

Now that we know what it returns, let’s make sure we have the class in place that will handle the kind of key-value pairs in the MongoDB collection:

  public class Cars
  {
    public MongoDB.Bson.ObjectId _id { get; set; }
    public MongoDB.Bson.ObjectId ObjectId { get; set; }
    public string brand { get; set; }
    public string lname { get; set; }
    public Int32 miles { get; set; }
    public int age { get; set; }
 
    // Complex Properties
    public Hashtable history { get; set; }
    public Hashtable complex { get; set; }
    public int[] magicNumbers { get; set; }
  }

Notice that the properties history, complex, and magicNumbers are not part of the MongoDB document we queried. That’s OK. The MongoDB C# drivers are smart enough to map to to a null value when deserializing from MongoDB to a C# object.

Now how do you map values from a MongoDB connection to a C# object? Like so:

    Cars car = vehicles.FindOne();

The FindOne() method will return the first document. Now let’s add some context to this line of code, by adding MongoDB connection code (that we established before), writing it to the screen, and checking for nulls in the complex properties:

namespace ConsoleApplication1
{
  public class Cars
  {
    public MongoDB.Bson.ObjectId _id { get; set; }
    public MongoDB.Bson.ObjectId ObjectId { get; set; }
    public string brand { get; set; }
    public string lname { get; set; }
    public Int32 miles { get; set; }
    public int age { get; set; }
 
    // Complex Properties
    public Hashtable history { get; set; }
    public Hashtable complex { get; set; }
    public int[] magicNumbers { get; set; }
  }
 
  class Program
  {
    static void Main(string[] args)
    {
      MongoServer  server = MongoServer.Create("mongodb://work2");
      MongoDatabase Cars = server.GetDatabase("Cars");
 
      MongoCollection vehicles;
      vehicles = Cars.GetCollection("vehicles");
 
      Cars car = vehicles.FindOne();
 
      Console.WriteLine(car._id);
      Console.WriteLine(car.ObjectId);
      Console.WriteLine(car.brand);
      Console.WriteLine(car.lname);
      Console.WriteLine(car.miles);
      Console.WriteLine(car.age);
 
      if (car.history == null)
        Console.WriteLine("history was null");
      else
        Console.WriteLine(car.history);
 
      if(car.complex == null)
        Console.WriteLine("complex was null");
      else
        Console.WriteLine(car.complex);
 
      if (car.magicNumbers == null)
        Console.WriteLine("magicNumbers was null");
      else
        Console.WriteLine(car.magicNumbers);                  
 
      Console.WriteLine("ha made it this far!");
      Console.ReadLine();
    }
  }
}

This will print the following on to the screen:

Read All Documents from a MongoDB Collection

Let’s try to output all the documents from a collection. We’re going to create a new MongoDB collection under the Cars database. Through the MongoDB client, we’ve created four documents. Let’s read them from the console first:

db.bankaccount.find()

The four documents look like:

{ "_id" : ObjectId("4d9650301b6e000000004116"), "name" : "Batman" }
{ "_id" : ObjectId("4d9650391b6e000000004117"), "name" : "Spider-Man" }
{ "_id" : ObjectId("4d96503f1b6e000000004118"), "name" : "Superman" }
{ "_id" : ObjectId("4d9650431b6e000000004119"), "name" : "Spawn" }

So the first thing is to create a class that represents each MongoDB document:

public class BankAccount
  {
    public MongoDB.Bson.ObjectId _id;
    public string name;
  }

The class is used to create an object that will contain the data that is deserialized (from MongoDB to a C# object).

Here’s the code to query all documents, iterating through them and showing them on the screen:

      MongoCursor cursor = BankAccountCollection.FindAll();
 
      foreach (BankAccount ba in cursor)
      {
        Console.WriteLine(ba._id);
        Console.WriteLine(ba.name);
        Console.WriteLine("=============================");
      }

Looks straightforward enough. What is a cursor? We can think of a MongoDB Cursor as a DataSet in .NET. Later, we’ll see MongoDB Queries, which resemble a SqlCommand object in .NET. Queries are configurable objects to search for document data. The Query object is then passed into the a find method (there are several) of the MongoCollection. The find method then typically returns a Cursor, which is then iterated through. (More about this later.) Also note that a Cursor is not “populated” with documents until the there’s an attempt to retrieve the first result from the server.

Let’s see the entire program in action.

namespace ConsoleApplication1
{
  public class BankAccount
  {
    public MongoDB.Bson.ObjectId _id;
    public string name;
  }
 
  class Program
  {
    static void Main(string[] args)
    {
      MongoServer  server = MongoServer.Create("mongodb://work2");
      MongoDatabase BankAccountDatabase = server.GetDatabase("Cars");
 
      MongoCollection BankAccountCollection;
      BankAccountCollection = BankAccountDatabase.GetCollection("bankaccount");
 
      MongoCursor cursor = BankAccountCollection.FindAll();
 
      foreach (BankAccount ba in cursor)
      {
        Console.WriteLine(ba._id);
        Console.WriteLine(ba.name);
        Console.WriteLine("=============================");
      }      
 
      Console.WriteLine("\n\nha made it this far!");
      Console.ReadLine();
    }
  }
}

The above program outputs the following:

If we wanted to retrieve a specific query, rather than doing this (from the above code):

 MongoCursor cursor = BankAccountCollection.FindAll();

We would do:

      var query = Query.EQ("name", "Batman");
      var cursor = BankAccountCollection.Find(query);

One last thing to mention about the Find() method, as stated from docs:
The Find method (and its variations) don’t immediately return the actual results of a query. Instead they return a cursor that can be enumerated to retrieve the results of the query. The query isn’t actually sent to the server until we attempt to retrieve the first result (technically, when MoveNext is called for the first time on the enumerator returned by GetEnumerator). This means that we can control the results of the query in interesting ways by modifying the cursor before fetching the results.

Get only key-value pairs from a collection

In this example, we’re going to try to do something like this in SQL:

SELECT Column1, Column2
FROM  TABLE

We’re also going to be using the collection “bbu”. Let’s try to translate this query:

db.bbu.find({},{whichAPI:1}).limit(10)

Which would return the following:

{ "_id" : ObjectId("4d90fbd85843000000004359"), "whichAPI" : "SL" }
{ "_id" : ObjectId("4d90fbd8584300000000435a"), "whichAPI" : "SL" }
{ "_id" : ObjectId("4d90fbd8584300000000435b"), "whichAPI" : "SIT" }
{ "_id" : ObjectId("4d90fbd8584300000000435c"), "whichAPI" : "SL" }
{ "_id" : ObjectId("4d90fbd8584300000000435d"), "whichAPI" : "SL" }

First, we’re going to define the class. We’re going to establish all the properties that are needed for a class, but then only query and populate two colums from the class.

Define the class and all of its properties.

public class BBU
  {
    public MongoDB.Bson.ObjectId _id;
    public int counter;
    public string whichAPI;
  }

Now the actual program:

  class Program
  {
    static void Main(string[] args)
    {    
 
      MongoServer  server = MongoServer.Create("mongodb://work2");
      MongoDatabase BBUDatabase = server.GetDatabase("bbu");
 
      MongoCollection BBUCollection;
      BBUCollection = BBUDatabase.GetCollection("bbu");
 
      MongoCursor cursor = BBUCollection.FindAll().SetFields("id","whichAPI").SetLimit(5);
 
      foreach (BBU ba in cursor)
      {
        Console.WriteLine(ba._id + "----" + ba.whichAPI);
        Console.WriteLine("=============================");
      }      
 
      Console.WriteLine("\n\nha made it this far!");
      Console.ReadLine();                        
 
    }
  }

In the example above, SetLimit(5) will only return the top 5 documents.

Conclusion

I hope you got a good a sense of the basics of using the MongoDB C# driver. I’ve only scratched the surface of the API. I’ll be discussing more advanced topics in future posts.

For the meantime, I point you to the MongoDB Google Group: http://groups.google.com/group/mongodb-user?pli=1 where you’ll get informative responses, usually very quickly.

I also recommend you following the following folks on Twitter and these blogs/sites:

Lastly, I recommend you check out the MongoDB video presentations using the C# Driver and working in a Microsoft environment.

Validating Checkboxes in ASP.NET MVC

Posted by Dan | Posted in C#, Databases | Posted on 08-18-2011

0

So here’s a very barebones example that does validation to all the checkboxes on a page. Also, it does the following:

  • Maps the checkboxes to a dictionary object.
  • Creates a custom model binder (that maps the checkbox values to the dictionary object).

Let’s get started.

The Model

public class Event
{
  public string Name { get; set; }
  public Dictionary Weekdays { get; set; }
}

The Custom Model Binder

  public class EventBinder : IModelBinder
  {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      Event ev = new Event();      
 
      ev.Name = controllerContext.HttpContext.Request.Form["Name"];
 
      // Let's initialize all the keys to false
      ev.Weekdays = new Dictionary()
      {
        {"Monday", false },
        {"Tuesday", false },
        {"Wednesday", false },
        {"Thursday", false },
        {"Friday", false },
      };      
 
      // Now let's trigger to true when the checkbox is checked.
      if (controllerContext.HttpContext.Request.Form["Weekdays[Monday]"] == "on")
        ev.Weekdays["Monday"] = true;
 
      if (controllerContext.HttpContext.Request.Form["Weekdays[Tuesday]"] == "on")
        ev.Weekdays["Tuesday"] = true;
 
      if (controllerContext.HttpContext.Request.Form["Weekdays[Wednesday]"] == "on")
        ev.Weekdays["Wednesday"] = true;
 
      if (controllerContext.HttpContext.Request.Form["Weekdays[Thursday]"] == "on")
        ev.Weekdays["Thursday"] = true;
 
      if (controllerContext.HttpContext.Request.Form["Weekdays[Friday]"] == "on")
        ev.Weekdays["Friday"] = true;
 
      return ev;
    }
  }

The Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication6.Models;
 
namespace MvcApplication6.Controllers
{
  public class HomeController : Controller
  {
    public ActionResult Index()
    {
      // We need to instantiate an event object before setting the checkboxes to default.
      Event e = new Event();      
 
      // Let's initialize the checkboxes.
      e.Weekdays = new Dictionary()
      {
        {"Monday",    false },
        {"Tuesday",   false },
        {"Wednesday", false },
        {"Thursday",  false },
        {"Friday",    false },
      };
 
      ViewBag.IsFormValid = false;
 
      return View("Home", e);
    }
 
    [HttpPost]
    public ActionResult Index([ModelBinder(typeof(EventBinder))] Event e)
    {
      // Let's validate the name.
      if (e.Name.Length == 0)
      {
        ModelState.AddModelError("Name", "First name is required.");
      }
 
      // Validate the checkbox. Make sure they are all checked.
      foreach (var day in e.Weekdays)
      {
        if (day.Value == false)
        {
          ModelState.AddModelError("Weekdays[" + day.Key + "]", day.Key + " has to be checked!" );
        }
      }
 
      ViewBag.IsFormValid = false;
 
      if (ModelState.IsValid)
      {
        ViewBag.IsFormValid = true;
      }        
 
      return View("Home", e);
    }
  }
}

The View

@model MvcApplication6.Models.Event
@{
  Layout = null;
}
 
<!--
    .formErrors
    {
      color: Red;
    }
 
-->
<div>
<h1>Form Is: &lt;&lt; @ViewBag.IsFormValid &gt;&gt;</h1>
<h4>Fill out the name and check every checkbox so the form becomes true (valid).</h4>
@using (@Html.BeginForm("Index", "Home"))
    {
      // FirstName TextBox
      @Html.LabelFor(model =&gt; model.Name, "FirstName")
      @Html.TextBoxFor(model =&gt; model.Name, "FirstName")
      @Html.ValidationMessageFor(model =&gt; model.Name, null, new { @class = "formErrors" })   
<hr />
 
      // Weekday Checkboxes
      foreach (var day in Model.Weekdays)
      {
<input name="Weekdays[@day.Key]" type="checkbox" /> checked="checked" 
        }
        /&gt; @day.Key
 
        @Html.ValidationMessageFor(model =&gt; model.Weekdays[day.Key], null, new {@class="formErrors"})
 
      }      
<input type="submit" value="submit me" />
    }</div>

Visual Studio Theme

Posted by Dan | Posted in C# | Posted on 06-08-2011

0

I put together my own color theme with the help of StudioStyles. Theme inspired by TextMate and Sublime Text. Check it out:

ErrorDetail I/O Exception: peer not authenticated

Posted by Dan | Posted in ColdFusion, Java | Posted on 06-08-2011

0

Similar to this page, I was getting the following error:

ErrorDetail I/O Exception: peer not authenticated
Filecontent Connection Failure
Mimetype Unable to determine MIME type of file.
Statuscode Connection Failure. Status code unavailable.

Which you get when the JVM has an old version of an SSL certificate. More specifically, I was having problems connecting to ConstantContact, after noticing that they had just renewed their certificate:

Cracking my head open, and trying every solution in the world along what the people posted here, we just decided to reboot the server. This flushed the cache and it worked.

If you can afford to do this, then I recommend it if you want to go for the fastest solution. ConstantContact later provided other possible solutions.

Send A File Path from the Windows Context Menu to App

Posted by Dan | Posted in Automation / Scripting, C#, Windows | Posted on 05-26-2011

0

Here’s an easy way to pass the file path to a console app. I needed a way to right click on a folder or a file, and send the path to a console app, where the app does its thing with the file(s).

To show you what I mean:

When I right-click on “coolbeans” it runs the following console app, which simply displays the path:

The C# app is pretty straightforward. Basically, once you have the file path, you can apply any operations on the file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace dan_rocks
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine(args[0]);
      Console.ReadLine();
    }
  }
}

So there’s nothing crazy going on in the above sample. You basically just have to add a few entries to the Registry.

If you want to pass a folder path when you right-click on it, and select the option in the context menu, create a new entry:

HKEY_LOCAL_MACHINE/Software/Classes/Folder/Shell

If you want to pass in a file, do the following:

HKEY_CLASSES_ROOT\*\shell

Let’s pass in the filepath to note.exe:

Do that and you’ll see the following:

Tag a Revision using Subclipse

Posted by Dan | Posted in Development, Eclipse, Web Development | Posted on 05-20-2010

0

Tagging a revision is a simple task if you’re using the subclipse plugin for Eclipse. For this example, we’re going to tag the trunk in our repository. This also assumes that your repository uses the traditional “3 directory setup” of branches, tags, and trunk.

1. Make sure you have a SVN View tab in Eclipse.

To do this, go to:
Window > Show View > Other > SVN > SVN Repositories

2. Under “WebSites” (in the following screenshot), right click on the trunk, and select “Branch/Tag…”:

3. Make sure you use the appropriate tag version that adheres to your versioning needs. Also, make sure it’s under the “tags” folder: svn://WebSites/Project-2/tags/

Implementing the Strategy Pattern in ColdFusion

Posted by Dan | Posted in ColdFusion, Java | Posted on 05-02-2010

0

In spirit of the amazing book Head First Design Patterns, I wanted to put together a ColdFusion example that depicts the Strategy pattern. Essentially, the Strategy Pattern lets you group related algorithms together so that an object is able to select which algorithm to run at runtime.

So let’s say for example you had a parent class that has two properties and two methods. You now create a subclass that inherits the parent class, meaning that it will gobble up all the properties and methods (whether you like it or not) from the parent class. You can’t choose, for example, what methods you subclass needs, even if some methods don’t make sense for your subclass. It’s an all-or-nothing solution. Yes, you can override, but what if there were 10 methods to override? Also, what if you had to create other types of subclasses – you’ll have to override those as well. Things can get a little sloppy at the end. That’s where the strategy pattern comes in.

With this pattern, you first think about related methods and algorithms. (One method can have various algorithms; different implementations for doing the same thing.) For this blog post’s example, we’ll think of different ways a SuperHero can punch. To keep things simple, let’s give him two ways (two different algorithms for punching) he can punch. He can punch normally, or he can punch you, which freezes you as well. Let’s UML this to make things clearer.

First what the lines mean:


Here’s the UML diagram for our SuperHero scenerio:


From the diagram, you can see that the SuperHero abstract class is able to choose a punch set of algorithms (a strategy). We also see that Punch and PunchFreeze are implementation classes (classes that serve to implement an interface). Both of them have a punch() method that return void (nothing) – in this example, they’ll do stuff, and not return anything.

To make things a little more interesting, and to follow closer the example in the Strategy Pattern chapter of the book, we’re going to also create a subclass called Freezer that inherits the SuperHero class. Also, we’ll create another strategy for kicking. Here’s what the UML for that looks like:


Here’s the CF code:

SuperHero.cfc

<cfcomponent>
 
<!--- This is our abstract class. Responsibility to implement is delegated to --->
<!--- classes that implement interfaces. --->
 
<cffunction name="init" access="public" returntype="SuperHero">  
  <!--- Some other init code goes here.  --->  
  <cfargument name="name" type="string">  
  <cfargument name="gender" type="string">  
  <cfset this.name = arguments.name />  
  <cfset this.gender = arguments.gender />  
  <cfreturn this />  
</cffunction>
 
<cffunction name="setPunchAlgorithm" access="public">
  <!--- The next two lines are key. It's where you set the implementation --->
  <!--- of punch from an object that's being passed in. --->
  <cfargument name="PunchAlgorithm" type="IPunchAlgorithm" required="true" />  
  <cfset this.punchAction = PunchAlgorithm.punch />
</cffunction>
 
<cffunction name="setKickAlgorithm" access="public">
  <cfargument name="KickAlgorithm" type="IKickAlgorithm" required="true" />  
  <cfset this.kickAction = KickAlgorithm.kick />
</cffunction>
 
<!--- This function will be overridden.  --->
<cffunction name="energyProject" access="public" returntype="SuperHero" >  
  You have been pointed at by a weak flash light.  
  <cfreturn this />
</cffunction>
 
</cfcomponent>

IPunchAlgorithm.cfc

<cfinterface>
 
<cffunction name="punch" access="public" />
 
</cfinterface>

Punch.cfc

<cfcomponent implements="IPunchAlgorithm">
 
<cffunction name="punch" access="public">
  You have been punched normally. Ouch.
</cffunction>
 
</cfcomponent>

PunchFreeze.cfc

<cfcomponent implements="IPunchAlgorithm">
 
<cffunction name="punch" access="public">
  You have been punched and are now frozen, stuck. Good luck thawing!
</cffunction>
 
</cfcomponent>

IKickAlgorithm.cfc

<cfinterface>
 
<cffunction name="kick" access="public" />
 
</cfinterface>

Kick.cfc

<cfcomponent implements="IKickAlgorithm">
 
<cffunction name="kick" access="public">
  You have been kicked in the gut. Yummy.
</cffunction>
 
</cfcomponent>

Freezer.cfc

<cfcomponent extends="SuperHero">
 
<!--- We are overriding the energyProject from Freezer's parent class.  --->
<cffunction name="energyProject">
  You have been snowed on. 
</cffunction>  
 
</cfcomponent>

Now let’s actually use these the pattern:

run.cfm

<!--- Create context object.  --->
<cfset IceMan = CreateObject( "component", "SuperHero" ).init( Name = "Iceman", Gender = "Male" ) />
 
<!--- Create a strategy #1 for punching.  --->
<cfset PunchStrategy_1 = CreateObject( "component", "Punch" ) />
 
<!--- Create a different strategy for punching.  --->
<cfset PunchStrategy_2 = CreateObject( "component", "PunchFreeze" ) />
 
<!--- Tell the IceMan object that you'll be using the Punch Strategy #2, NOT #1.  --->
<cfset IceMan.setPunchAlgorithm( PunchStrategy_2 ) />
 
 
<!--- Now let's create a kicking strategy... --->
<cfset KickStrategy = CreateObject( "component", "Kick" ) />
 
<!--- ... and now let's tell the IceMan object that you'll be using the Kick Strategy.  --->
<cfset IceMan.setKickAlgorithm( KickStrategy ) />
 
 
<!--- Now let's see some action!  --->
 
<!--- Punch, using the strategy chosen! --->
<cfset IceMan.punchAction() />
 
<!--- Punch, using the strategy chosen! --->
<cfset IceMan.kickAction() />
 
 
<!--- Let's create another SuperHero object. --->
<cfset Frosty = CreateObject( "component", "SuperHero" ).init( Name = "Frosty the Snowman", Gender = "Unknown" ) />
 
<!--- Let's inspect the objects --->
<p>Notice that both objects have different number of methods - only the methods they need. </p>
<cfdump var="#IceMan#" /><hr />
<cfdump var="#Frosty#" /><hr />
 
 
<!--- Let's create another SuperHero object. --->
<cfset Frostman = CreateObject( "component", "Freezer" ).init( Name = "Calvin Hobbes", Gender = "Male" ) />
<cfset Frostman.energyProject() />

You can download all the CF code here with the original Visio diagram source.