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#@&$%

Monday, July 9, 2012

Visual Studio Development Web Server, mp4 isn’t part of the set of built in known Mime types.

With HTML5 video element, I found the video missing when using Internet Explorer 9. IE9 supports the HTML5 video element, but the video was just missing.

Correcting the problem

Because Visual Studio’s Development Web Server is missing mp4 mime type, and to my knowledge there isn’t a way to add a missing mime type to Visual Studio’s Development Web Server built in know Mime types.

I added to the applications config.sys file:

<system.webServer>
  <staticContent>
    <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
  </staticContent>
</system.webServer>


This adds it to the IIS server, so now I need to switch from using the Development Web Server to Local IIS Server.


Within Visual Studio, I must be administrator when working under Local IIS. The process opening Visual Studio as Administrator:

Right click on Visual Studio’s shortcut icon > properties > shortcut tab > advanced button > check run as administrator checkbox.


Now when I open Visual Studio, I will be running Visual Studio as administrator.


Now set the application properties:


project > properties > Web > click Use Local IIS Server radio button. Project URL should be set to the application’s virtual directory path.


Now HTML5 videos should work using mp4. 


The purpose is solely for my notes.

Thursday, July 5, 2012

Adding #region to Visual Studio 2012 CSS page



I do like regions, because it seems to add an abstraction to the CSS page by the ability to collapse sections narrowing the viewing area.

This show how to wrap a region around CSS declarations:

Begin wrapping with: /*#region Fieldset Styling */

End with: /*#endregion*/

Below is CSS formatting a form section within a fieldset element:

Each HTML input element has a title label and is wrapped in a HTML div element. The HTML div element has a class attribute value equal to fields.




/*#region Fieldset Styling */

fieldset {

    margin: 8px;

    padding: 12px 0px 20px;

    font-size: 1.1em;

    background-color: #fff;

}

 

    fieldset > div {

        margin-top: 8px;

    }

 

.fields {

}

 

    .fields span {

        display: inline-block;

        text-align: right;

    }

 

        .fields span.RecoverEmail {

            width: 100%;

            text-align: left;

        }

 

        .fields span:not(:first-child) {

            font-size: 0.8em;

        }

 

        .fields span.UniqueStatus {

            display: none;

            text-align: left;

        }

 

            .fields span.UniqueStatus input {

                margin-bottom: -3px;

            }

 

            .fields span.UniqueStatus.show {

                display: inline;

            }

 

    .fields input {

        width: 50%;

        border: medium solid #c0c0c0;

        height: 24px;

        line-height: 28px;

        font-size: 13px;

    }

 

        .fields input:focus {

            border: medium solid #4d90fe;

            outline-style: none;

            outline-color: invert;

        }

 

        .fields input.smaller {

            width: 30%;

        }

 

        .fields input.medium {

            width: 40%;

        }

/*#endregion*/










These are my notes for later use.

Friday, March 30, 2012

My Captcha Image

This is a work in progress, and for my furthering my notes. Your comments are welcome.

I decide to code my personal Captcha Image. My Captcha idea is new, which probably can be found somewhere on the internet, however I tweaked the idea into a .NET Class (CaptchaDisplay class within my Captcha namespace)..

This Captcha class is instantiated from two areas. It is instantiated within an User control and a Generic Handler.

The User control’s code behind handles generating the Captcha characters, while the Generic Handler handles creating the Image from characters passed it through a query string. The characters are generated from the User Control.

I added an external appSettings page to the Web.config:

<appSettings file="appSettings.config"/>

Within the appSettings.config file:

<?xml version="1.0"?>
<appSettings>
<add key="Tumblers" value="j(mW*)UYRvxQ$4^54hT" />
</appSettings>
 
The key attribute – Tumblers - is used in the Captcha encryption. Tumblers is synonymous with a Key Lock mechanism. Tumblers wouldn’t be shown and are invisible. The Lock and Key can be found by the visitor, however to unlock or to be verified all three must fit or equal to the Captcha characters generated.

Download myCaptcha code here

The User Control is shown below:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CaptchaControl.ascx.cs"
    Inherits="CaptchaHandler.CaptchaControl" %>
 
<asp:HiddenField ID="captchaKey" ClientIDMode="Static" runat="server" />
<asp:Panel ID="Captcha" ClientIDMode="Static" runat="server">
</asp:Panel>

and its Code Behind page:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using deDogs.Captcha;
 
namespace CaptchaHandler
{
    public partial class CaptchaControl : System.Web.UI.UserControl
    {
        private int _width;
 
        public int Width
        {
            set
            {
                _width = value;
            }
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
            using (CaptchaDisplay captcha = new CaptchaDisplay(_width))
            {
                captcha.GetCharacters();
                string[] c = captcha.characters;
                string key =new string(captcha.SaltKey(c));
                string encodeKey =  HttpUtility.UrlEncode(key);
                captchaKey.Value = encodeKey;
 
                Image img = new Image();
                img.ImageUrl = "Captcha.ashx?key=" + encodeKey + "&w=" + _width;
                img.AlternateText = "Captcha Image";
                Captcha.Controls.Add(img);
            }
        }
    }
}
Generic Handler C# Code is shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using deDogs.Captcha;
using System.Drawing.Imaging;
 
namespace CaptchaHandler
{
    /// <summary>
    /// Display Captcha Characters Image
    /// </summary>
    public class CaptchaHandler : IHttpHandler
    {
 
        public void ProcessRequest(HttpContext context)
        {
            HttpContext.Current.Response.ContentType = "image/jpeg";
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.BufferOutput = false;
            try
            {
                Int32 width = Convert.ToInt32(HttpContext.Current.Request["w"]);
 
                if (width > 0) {
                    using (CaptchaDisplay captcha = new CaptchaDisplay(width))
                    {
                        try
                        {
                            string key = HttpUtility.UrlDecode(HttpContext.Current.Request["key"].ToString());
 
                            if (key != "")
                            {
                                //Decrypt key
                                char[] unSalted = captcha.SaltKey(key.ToCharArray());
                                captcha.characters = unSalted.SelectMany(x => new string[] { x.ToString() }).ToArray();
                                captcha.CaptchaImage();
                                captcha._bitMap.Save(HttpContext.Current.Response.OutputStream, ImageFormat.Jpeg);
                            }
                        }
                        catch (Exception)
                        {
 
                            throw;
                        }
                    }
                }
            }
            catch (Exception)
            {
                
                throw;
            }
 
        }
 
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Finally the Captch class shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using deDogs.Validation;
using System.Configuration;
using System.Web.SessionState;
namespace deDogs
{
    namespace Captcha
    {
        public class CaptchaDisplay : IDisposable
        {
            public CaptchaDisplay(int width)
            {
                this.fonts = new string[] { "Times New Roman", "Georgia", "Arial", "Comic Sans MS" };
                this.sizes = new int[] { 36, 48, 60, 72 };
                this.characterSet = @"ABDEFGHJKLMNQRTYZabdefghkmnqryz23456789*#@%$";
                this.colr = new Brush[] { Brushes.Black };
                this.backgroundColor = Brushes.White;
                this.salt = new char[] { 'g', '-', '$', 'k', '5', '?', 'O' };
                this._bitMap = new Bitmap(width, (int)(width * .32F));
            }
            public CaptchaDisplay() { }
 
            protected class CaptchaChars
            {
                public CaptchaChars() { }
 
                public CaptchaChars(string character, CaptchaRegion region)
                {
                    this.character = character;
                    this.region = region;
                    this.memoryStream = new MemoryStream();
 
                }
                public MemoryStream memoryStream { get; set; }
                public string character;
                public CaptchaRegion region;
                public int angle { get; set; }
            }
            protected class CaptchaRegion
            {
                public CaptchaRegion() { }
                public CaptchaRegion(float x, float y, float width, float height)
                {
                    this.x = x;
                    this.y = y;
                    this.width = width;
                    this.height = height;
                }
                public float x { get; set; }
                public float y { get; set; }
                public float width { get; set; }
                public float height { get; set; }
            }
            public Bitmap _bitMap;
 
            Brush color(Random rnd)
            {
                return colr[rnd.Next(0, colr.Length)];
            }
            PinTumblerLock pinTumblerLock;
 
            public char[] salt { get; private set; }
            public string[] characters;
            public string characterSet;
 
            public string[] fonts { get; set; }
            public int[] sizes { get; set; }
            public Brush[] colr;
            public Brush backgroundColor;
 
            public PinTumblerLock LockKey
            {
                get
                {
                    return pinTumblerLock;
                }
                set
                {
                    pinTumblerLock = value;
                }
            }
            public void GetCharacters()
            {
                Random rnd = new Random();
                int numChars = rnd.Next(4, 7);
                this.characters = new string[numChars];
 
                for (var i = 0; i < numChars; i++)
                {
                    this.characters[i] = this.characterSet.Substring(rnd.Next(0, this.characterSet.Length), 1);
                }
            }
 
            public void CaptchaImage()
            {
                Random rnd = new Random();
 
                CaptchaChars captchaChar;
                List<CaptchaChars> captchaChars = new List<CaptchaChars>();
 
                CharacterRange[] cR = { new CharacterRange(0, 1) };
 
                StringFormatFlags flags = StringFormatFlags.NoWrap | StringFormatFlags.NoClip;
                StringFormat sF = new StringFormat(flags);
                sF.SetMeasurableCharacterRanges(cR);
 
                RectangleF displayRectangleF = new RectangleF(0, 0, this._bitMap.Width, this._bitMap.Height);
 
                Font largeFont;
 
                int width = 80, height = 80;
 
                for (var c = 0; c < characters.Length; c++)
                {
                    HttpContext.Current.Trace.Write(characters[c]);
 
                    int angle = rnd.Next(0, 30);
                    angle = (angle % 2 == 0) ? -angle : angle;
 
                    captchaChar = new CaptchaChars(characters[c], new CaptchaRegion(0, 0, width, height));
                    captchaChar.angle = angle;
 
                    using (Bitmap bitMap = new Bitmap(width, height, PixelFormat.Format32bppArgb))
                    {
                        using (Graphics g = Graphics.FromImage(bitMap))
                        {
                            Rectangle rect = new Rectangle(new Point(0, 0), new Size(bitMap.Width, bitMap.Height));
                            g.FillRectangle(this.backgroundColor, rect);
 
                            largeFont = new Font(this.fonts[rnd.Next(0, this.fonts.Length)], this.sizes[rnd.Next(0, this.sizes.Length)], GraphicsUnit.Pixel);
                            Region[] charRegion = g.MeasureCharacterRanges(characters[c], largeFont, displayRectangleF, sF);
                            g.DrawString(characters[c], largeFont, colr[rnd.Next(0, colr.Length)], displayRectangleF);
 
                            bitMap.Save(captchaChar.memoryStream, ImageFormat.Jpeg);
                            captchaChars.Add(captchaChar);
                        }
                    }
                }
 
 
                this.Display(captchaChars);
 
            }
 
            void Display(List<CaptchaChars> c)
            {
                using (Graphics mainGraphic = Graphics.FromImage(this._bitMap))
                {
                    StringBuilder charSet = new StringBuilder();
                    Rectangle rect = new Rectangle(new Point(0, 0), new Size(this._bitMap.Width, this._bitMap.Height));
                    mainGraphic.FillRectangle(this.backgroundColor, rect);
 
                    int newX = 0;
                    float bwidth, bheight = 0;
                    foreach (CaptchaChars m in c)
                    {
                        bwidth = m.region.width;
                        bheight = m.region.height;
                        Bitmap bitMap = new Bitmap(m.memoryStream);
                        using (Graphics g = Graphics.FromImage(bitMap))
                        {
                            Rotate(m, g);
                            g.DrawImage(bitMap, 0, 0);
                            mainGraphic.DrawImage(bitMap, newX, 0);
                            newX += (int)m.region.width;
                            charSet.Append(m.character);
                        }
 
                    }
                    //Crop image bounding selected characters
                    this._bitMap = this._bitMap.Clone(new Rectangle(0, 0, newX, (int)bheight), PixelFormat.Format32bppArgb);
                    Lockup(charSet.ToString());
 
                    Distort();
                    Decorate();
                }
            }
 
            private void Lockup(string key)
            {
                PinTumblerLock lockup = new PinTumblerLock(key, (ConfigurationManager.AppSettings["Tumblers"]));
            }
 
            public char[] SaltKey(char[] key)
            {
                int len = key.Length;
 
                for (int i = 0; i < len; i++)
                {
                    key[i] ^= this.salt[i];
                }
                return key;
 
            }
            public char[] SaltKey(string[] key)
            {
                char[] c = string.Join(string.Empty, key).ToCharArray();
                return this.SaltKey(c);
            }
 
            void Rotate(CaptchaChars c, Graphics g)
            {
                g.TranslateTransform(c.region.width / 2, c.region.height / 2);
                g.RotateTransform(c.angle);
                g.TranslateTransform(-c.region.width / 2, -c.region.height / 2);
            }
 
            protected void Distort()
            {
                Random rnd = new Random();
                double distort = rnd.Next(5, 20) * (rnd.Next(10) == 1 ? 1 : -1);
 
                int width = this._bitMap.Width;
                int height = this._bitMap.Height;
                using (Bitmap copy = (Bitmap)this._bitMap.Clone())
                {
                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            // Adds a simple wave
                            int newX = (int)(x + (distort * Math.Sin(Math.PI * y / 84.0)));
                            int newY = (int)(y + (distort * Math.Cos(Math.PI * x / 44.0)));
                            if (newX < 0 || newX >= width) newX = 0;
                            if (newY < 0 || newY >= height) newY = 0;
                            this._bitMap.SetPixel(x, y, copy.GetPixel(newX, newY));
                        }
                    }
                }
            }
            protected void Decorate()
            {
                using (Graphics g = Graphics.FromImage(this._bitMap))
                {
                    Random rnd = new Random();
                    int width = this._bitMap.Width;
                    int height = this._bitMap.Height;
 
                    // Draw lines between original points to screen.
                    g.DrawCurve(new Pen(color(rnd), 3.0F), Points(5, rnd).ToArray());
 
                    foreach (Point pt in Points(5, rnd))
                    {
                        g.DrawRectangle(new Pen(color(rnd), 3.0F), new Rectangle(pt, new Size(rnd.Next(5, 20), rnd.Next(5, 20))));
                    }
                }
            }
 
            protected List<Point> Points(int pts, Random rnd)
            {
                List<Point> points = new List<Point>();
                int width = this._bitMap.Width - 20;
                int height = this._bitMap.Height - 20;
 
                for (int i = 0; i < pts; i++)
                {
                    points.Add(new Point(rnd.Next(0, width), rnd.Next(0, height)));
                }
                return points;
            }
 
            public void Dispose()
            {
                this._bitMap.Dispose();
                this._bitMap = null;
            }
        }
    }
}