Pages

Saturday, August 18, 2012

Code-First: From UML Class Diagram to Creating MS SQL Database

Over the years designing web applications, I have sketched thoughts onto paper; sketching out c# classes and database table relations. I knew there were great modeling programs to assist me, but I never bothered researching. I didn’t want to learn another language or program.

However, recently I learned of .Net 4.0+ EntityFramework and UML Modeling. These two allow me to create POCO classes, DB tables, and relationships between DB tables.
It is very straight forward, which I show the process I followed below:

My Sloution Explorer shows 4 projects:

DataLayer: a C# class project exposing a DbContext layer.

Model: a UML class diagram is created and C# classes are generated from its packages .
ModelLib: where the C# classes are stored after being generating.

WebApplication1: allows to initiate the Context and possibility create database.




First, Within a black .Net 4.0 solution, I Created a new Modeling Project, I dragged out an UML class diagram and made associations:


After creating class diagram, I right clicked on each package and selected Generate Code:



Clicking Generate Code a new C# class project is created and all modeled classes from the Class Diagram classes are created and saved within a specified folder.
  • The folder’s name, where the derived classes are saved, is derived from their package’s name.
  • The project’s name takes the model project’s name and apppends “Lib”

Second, I created a C# class project with only one C# class, which I named: Context.cs. This class is the context layer and will inherit from DbContext.

From MSN (MSDN DbContext):

DbContext Class

Entity Framework 5.0 Represents a combination of the Unit-Of-Work and Repository patterns and enables you to query a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.

DbSet<TEntity> Class

Represents a typed entity set that is used to perform create, read, update, and delete operations. DbSet is not publicly constructible and can only be created from a DbContext instance.


Lastly, I created a Web Application, and in the code behind initiated the Context class. Because of lazy loading, if I was to only initiate the Context class, no DB tables would be created. Therefore, I selected something from the Client table and converted to a List. By converted it to a list, it must make a round trip to the database, and therefore the database tables will be created.
Special Note: Reference:
  • EntityFramework
  • System.Data.Entity
  • Context namespace (dogPedalerEnityMSSQL)
This name was chosen because Entity Framework will name the database after the Context’s Namespace. If no Connection String is found in the web.config, then Entity Framework will create SQLExpress Database named dogPedalerEnityMSSQL.Context (Namespace.Class).

Complete, I found this to be great. Going from Model to Classes to Creating DB tables.
This is only for my notes, and additionally it would be great, if someone receives benefit from my notes.

Monday, August 13, 2012

Below is an example of the Captcha Control

Download the complete solution from CodePlex.

Captcha Control added to ASP.NET Page.

<li>

//Captcha Control
<cc1:CaptchaControl ID="myCaptchaControl" ClientIDMode="Static"
  Width="800"
  Height="75"
  ImageWidth="400"
  ImageHeight="75"
  Minimum="5"
  Maximum="6"
  CaptchaHandlerUrl="~/CaptchaHandler.ashx"
  Overlap="6"
  RefreshButtonPath="~/Images/refresh.png"  runat="server" />

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

Please enter characters displayed above&nbsp;

<asp:TextBox ID="CaptchaCharacters" ClientIDMode="Static" Text="" Width="100" ToolTip="Enter characters displayed above" runat="server">
</asp:TextBox>

<asp:RequiredFieldValidator runat="server" ValidationGroup="RegisterGroup" ontrolToValidate="CaptchaCharacters" CssClass="field-validation-error" ErrorMessage="*Required" />

</li>
 
Captcha Control will render out a HTML image element (image displaying characters) and a HTML input element of type button (refresh button - retrieving a new set of display characters).
Below the Capthca Control, I added a Textbox, which is where the user would type the Captcha characters and will be verified once the form is submitted.



Code Behind - Verifing Captcha Characters

Note: Captcha control had been place within a CreateUserWizard control. Referencing Captcha Control, I must FindControl within CreateUserWizard control (ID="RegisterUserWizardStep").

 //CreatingUser is raised before the Memebership Provider's CreateUser. Setting LoginCancelEventArgs Cancel property equal to true, the user will not be created.
protected void RegisterUser_CreatingUser(object sender, LoginCancelEventArgs e)
{
    var err = ((Literal)GetControl("ErrorMessage"));
    var parent = err.Parent;
    err.Text = "";

    Page.Validate();
    if (!Page.IsValid)
    {
       err.Text = "Required fields are empty or incorrect information was entered.";
       e.Cancel = true;
     }
     else
     {
       //Initiate the EncodeCaptcha class
       var ec = new EncodeCaptcha(GetCaptchaKey());

       //GetCaptchaCharacters returns clear Captcha characters represented in the displayed image.
       //Test they must be equal
       if (ec.characters != GetCaptchaCharacters())
       {
          err.Text = "Characters incorrectly entered. Please reenter correct characters displayed";
          e.Cancel = true;
       }
      }
}

//Return submited Captcha characters. the characters that the user had entered.
string GetCaptchaCharacters()
{
    return ((TextBox)GetControl("CaptchaCharacters")).Text;
}

//Return encrypted Captcha character string. The encrypted string had be UrlEncode, so the return
//string is UrlDecoded.
string GetCaptchaKey()
{
    var cc = GetControl("myCaptchaControl");
    var captchaCharacters = (HiddenField)cc.FindControl("Captcha-Key");

    return HttpUtility.UrlDecode(Request[captchaCharacters.UniqueID]);
}

//Abstracted findng fields within CreateUserWizard.
Control GetControl(string value)
{
    return RegisterUserWizardStep.ContentTemplateContainer.FindControl(value);
}

Sunday, August 12, 2012

New Update Captcha Image Control

I have updated my captcha image control. I believe it is sleeker and is overall better code wise.

Initiates an asynchronous call, and the returned result, will be a single image of alphanumeric characters. Image’s characters are presented in various font sizes and or (+/-) rotated in some degree.

This project offers the complete Visual Studio 2012 solution within a compressed zip file. Download the complete solution from CodePlex.

Shown below is the Captcha type which generates randomly selected characters and draws an image displaying those specific random characters.

Two files are involved rendering the Captcha image:
  • CaptchaControl.cs and CaptchaHandler.ashx
  • CaptchaControl.cs is a generic control rendering out an image and an Image Button. The rendered image’s ImageUrl property is dynamically set, and calls CaptchaHandler.ashx with an attached query string. The query string has a particular name/value pair specifying the particular Captcha characters.
CaptchaControl.cs generates and encodes characters appending the generated string to the rendering image’s query string.

CaptchaHandler.ashx returns a HTTPResponse bitmap and is displayed on the client side webpage.


CaptchaControl Class

Namespace: Captcha.Control
Assembly: CaptchaControl.dll

Syntax
public CaptchaControl : WebControl

Constructors
CaptchaControl(): base(HtmlTextWriterTag.Fieldset) Initializes a new instance of the CaptchaControl class

Properties
string RefreshButtonPath Absolute path to the Image Button’s image
string CaptchaHandlerUrl Absolute path to the Captcha Handler
int Minimum Minimum number of characters to be selected
int Maximum Maximum number of characters to be selected
int Overlap Amount of overlap between character placement.
int ImageWidth Captcha image’s width
int ImageHeight Captcha image’s height
string CharacterSet The character domain to select from. Default character set: ABDEGHMNQRTabdeghmnqr3456789#@&$%