Tag Archives: ASP.NET

Generating Captcha images – ASP .NET MVC

Wikipedia describes Captcha images as

a type of challenge-response test used in computing as an attempt to ensure that the response is generated by a person

there are a few simple plug-ins that you can use in your ASP .NET MVC App, like reCaptcha, but to have a fully flexible and integrated solution you have to create you own, in this article we will define our implementation to handle Captcha images.

start by creating an empty MVC 3 Internet application.

go to the HomeController.vb class and add the following Action method.


GetCaptcha Action

Function GetCaptcha() As ActionResult
        'Captcha Image Size  Width - Height
        Dim width As Integer = 75
        Dim height As Integer = 20

        'Captcha String
        Dim fontFamily = "Tahoma"
        ' -  Generate Random
        Dim randomsize As Integer = 5
        Dim randomstringbuilder As New StringBuilder()
        Dim random As New Random(DateTime.Now.Millisecond)
        Dim ch As Char
        For i As Integer = 0 To randomsize - 1
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)))
        Dim captchaString = randomstringbuilder.ToString

        ' Create a new 32-bit bitmap image.
        Dim bitmap As New Drawing.Bitmap(width, height, Drawing.Imaging.PixelFormat.Format32bppArgb)

        ' Create a graphics object for drawing.
        Dim g As Drawing.Graphics = Drawing.Graphics.FromImage(bitmap)
        g.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
        Dim rect As New Drawing.Rectangle(0, 0, width, height)

        ' Fill in the background.
        Dim hatchBrush As New Drawing.Drawing2D.HatchBrush(Drawing.Drawing2D.HatchStyle.Wave, Drawing.Color.LightGray, Drawing.Color.White)
        g.FillRectangle(hatchBrush, rect)

        ' Set up the text font.
        Dim size As Drawing.SizeF
        Dim fontSize As Single = rect.Height + 1
        Dim font As Drawing.Font
        Dim format As New Drawing.StringFormat()
        format.Alignment = Drawing.StringAlignment.Center
        format.LineAlignment = Drawing.StringAlignment.Center

        ' Adjust the font size until the text fits within the image.
            fontSize -= 1
            font = New Drawing.Font(fontFamily, fontSize, Drawing.FontStyle.Bold)
            size = g.MeasureString(captchaString, font, New Drawing.SizeF(width, height), format)
        Loop While size.Width > rect.Width

        ' Create a path using the text and warp it randomly.
        Dim path As New Drawing.Drawing2D.GraphicsPath()
        path.AddString(captchaString, font.FontFamily, CInt(font.Style), font.Size, rect, format)
        Dim v As Single = 4.0F
        Dim points As Drawing.PointF() = {New Drawing.PointF(random.[Next](rect.Width) / v, random.[Next](rect.Height) / v), New Drawing.PointF(rect.Width - random.[Next](rect.Width) / v, random.[Next](rect.Height) / v), New Drawing.PointF(random.[Next](rect.Width) / v, rect.Height - random.[Next](rect.Height) / v), New Drawing.PointF(rect.Width - random.[Next](rect.Width) / v, rect.Height - random.[Next](rect.Height) / v)}
        Dim matrix As New Drawing.Drawing2D.Matrix()
        matrix.Translate(0.0F, 0.0F)
        path.Warp(points, rect, matrix, Drawing.Drawing2D.WarpMode.Perspective, 0.0F)

        ' Draw the text.
        hatchBrush = New Drawing.Drawing2D.HatchBrush(Drawing.Drawing2D.HatchStyle.DashedUpwardDiagonal, Drawing.Color.DarkGray, Drawing.Color.Black)
        g.FillPath(hatchBrush, path)

        ' Add some random noise.
        Dim m As Integer = Math.Max(rect.Width, rect.Height)
        For i As Integer = 0 To CInt(Math.Truncate(rect.Width * rect.Height / 30.0F)) - 1
            Dim x As Integer = random.[Next](rect.Width)
            Dim y As Integer = random.[Next](rect.Height)
            Dim w As Integer = random.[Next](m \ 50)
            Dim h As Integer = random.[Next](m \ 50)
            g.FillEllipse(hatchBrush, x, y, w, h)

        ' Clean up.

        Dim captchaImageResult As FileContentResult = Nothing
        Using mystream As New System.IO.MemoryStream()

            bitmap.Save(mystream, System.Drawing.Imaging.ImageFormat.Jpeg)
            captchaImageResult = MyBase.File(mystream.GetBuffer, "image/jpeg")

        End Using

        'Save the Captcha Hash in the Session
        Session("botdeflector") = Convert.ToBase64String(System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(captchaString)))

        'Return the Captcha Image
        Return captchaImageResult

    End Function

what is mostly happening here is the generation of the image, pasting in the Text that you want for the Captcha image, adding some noise, and in the end we save the hash for the generated text, this is what we will use later to verify that the user submitted the correct string of text, the most important part is saving the hash to the session state.

change the index page a little, adding a new form, an image tag with its source set as the captcha image, and a submit button.


    ViewData("Title") = "Home Page"
End Code

@Using Html.BeginForm

        <img src='@Url.Action("GetCaptcha")' alt='Captcha' />
        <input type="text" size="10" name="CaptchaAnswer" autocomplete="off" />
        <br />
        <input type="submit" value="Submit"/>

End Using

adding a new POST only index Action method


Index Action (POST)

      Function index(CaptchaAnswer As String) As ActionResult

        Dim captchaHash = Session("botdeflector")

        If captchaHash = Convert.ToBase64String(System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(UCase(CaptchaAnswer)))) Then

            ViewData("Message") = "YOU ARE A PERSON :>"

            ViewData("Message") = "YOU ARE A ROBOT!"

        End If

        Return View()

     End Function

the validation begins with converting the Captcha Answer the user supplied to it’s hash equivalent, then we get our saved hash from the current user session, compare them and return the result.

here is the complete project if you want it. and you can also use the following helper functions for random generation of strings or numbers

Generate Random Number Function

 Private Function generateRandomNumber(ByVal size As Integer) As String

        Dim builder As New StringBuilder()
        Dim random As New Random(DateTime.Now.Millisecond)
        Dim ch As Char
        For i As Integer = 0 To size - 1
            ch = random.Next(9).ToString
        Return builder.ToString()

    End Function

Generate Random String Function

   Private Function generateRandomString(ByVal size As Integer) As String

        Dim builder As New StringBuilder()
        Dim random As New Random(DateTime.Now.Millisecond)
        Dim ch As Char
        For i As Integer = 0 To size - 1
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)))
        Return builder.ToString()

    End Function

Leave a comment

Posted by on 3, Nov 2011 in .NET, ASP.NET, MVC, VB.NET


Tags: ,

SEO Friendly Slug URLs Extension Method

Here is a quick Extension Method that you can use to generate a friendly string for use in a URL.

Function ToFriendlyUrl(txt As String, Optional maxLength As Integer = 45) As String
If String.IsNullOrWhiteSpace(txt) Then

Return String.Empty
Dim str As String = RemoveAccent(txt).ToLower()

str = RegularExpressions.Regex.Replace(str, "[^a-z0-9\s-]", String.Empty)
str = RegularExpressions.Regex.Replace(str, "\s+", " ").Trim()
str = str.Substring(0, If(str.Length str = RegularExpressions.Regex.Replace(str, "\s", "-")

Return str

End If

End Function

we use Regular expressions to only allow letters and dashes, so now you can create SEO Friendly URL for your site just by using this extension method on any URL String.

Leave a comment

Posted by on 10, Oct 2011 in .NET, ASP.NET, MVC, VB.NET


Tags: , , ,

Twitter Html Helper – MVC 3

Twitter Logo
let us code a ‘Latest Tweets’ HTML Helper.

Create a new MVC 3 app and add a new module the following code

Twitter HTML Helper

Public Module MyExtensions

    Function Twitter(htmlHelper As HtmlHelper,
                     screenName As String,
                     Optional maxRows As Integer = 5) As MvcHtmlString

        'Construct the URL to call the Twitter API
        Dim twitterUrl = String.Format("{0}&count={1}",
                                       screenName, maxRows)

        'Get the Data as XML
        Dim rss = XDocument.Load(twitterUrl)

'Create a ul tag
Dim ulTag = New TagBuilder("ul")

'Loop each tweet

Dim tweets = rss.Descendants("status").Select(Function(x) x.Element("text").Value).ToList
For Each tweet In tweets

'Create a li tag
 ulTag.InnerHtml += New TagBuilder("li") With {.InnerHtml = tweet}.ToString


 Return MvcHtmlString.Create(ulTag.ToString(TagRenderMode.Normal))

 End Function

End Module

notice that the module marked as Public.

what we are doing here is Loading the XML feed for the twitter user specified, then create an unordered list, with the tweets as content

to use this extension method you have to import the namespace, so in your web.config file go to the <namespaces> section under the <pages> tag and add the following

add <namespace=”MyProject.MyExtensions” />

the namespace MyProject depends on your project name, and can be found under My Project > Application Tab > Root Namespace.

use this HTML Helper simply by typing



shown here is a way to interact with public API’s using XML documents, and integrating that with MVC’s Html Helper

Leave a comment

Posted by on 10, Aug 2011 in .NET, ASP.NET


Tags: , , , ,

Change Shared or Views folder location in an MVC 3 site

if you want to change the location of the shared folder in your MVC 3 App, then this is a must read.

when you create a new MVC 3 Web Application Project, a default folder structure is created for you that looks something like this


to change the shared folder location you must do the following steps

Move the shared folder to the Root

just drag the shared folder out of the views folder to the root of your app, like so


Copy the web.config

in order for the shared folder to work outside the views folder, it has to have a special web.config file within it. just copy the one inside the views folder and paste it into the shared folder.


Edit the _ViewStart.vbhtml page

now that the _layout page has changed its locations, we have to modify the _ViewStart.vbhtml page located in the Views folder, and edit the following


remove the “/Views” so now it directs to the _layout page located in the new shared folder location.


Code a custom view engine

if you tried to browse the site now you will get an error like this one


that is happening because MVC is using the default locations for the partial views, so its still looking for the _LogOnPartial.vbhtml in its old location, but you moved that file to a new location in the root of your app.

to change the default file location for the whole site we need to create a new class that inherits from RazorViewEngine

Public Class MyCustomViewEngine
    Inherits RazorViewEngine

    Sub New()

        MasterLocationFormats = New String() {"~/Shared/{0}.vbhtml"}

        ViewLocationFormats = New String() {"~/Views/{1}/{0}.vbhtml", "~/Shared/{0}.vbhtml"}

        PartialViewLocationFormats = New String() {"~/Views/{1}/{0}.vbhtml", "~/Shared/{0}.vbhtml"}

    End Sub

End Class


here we set new locations for the Master, Views, and PartialViews

Replace the default view engine and test

all we have to do now is plugin this new custom engine, go to the Global.asax file and add the following to the Application_Start()

  Sub Application_Start()

        ViewEngines.Engines.Add(New MyCustomViewEngine)

    End Sub

now if you run the app you will notice that it all works with the shared folder new location.


we managed to change the shared folder location and replace the default razor view engine with our own implementation that changes the locations of the master, views, and partial views of the app.


Posted by on 1, Aug 2011 in .NET, ASP.NET, MVC, VB.NET


Tags: , ,

Google Static Maps HTML Helper

one of the features that i like the most in ASP .NET MVC is HTML Helpers, i use them all the time, and i also use Google Maps very often too, so its natural to join them and create a simple HTML Helper Extension Method that you can use immediately in your applications.

Google Maps provides an API for generating map images from parametrized URLs called Google Static Maps API, so today we will create an Extension Method to the HtmlHelper class that you can use to easily embed a Google Static Map into any View Page.

we will start with some text from the API docs.

Google Static Maps API Query string parameters

Name requirement Description
center required
if markers not present
defines the center of the map
zoom required
if markers not present
Zoom levels
between 0 (the lowest zoom level) to 21+ (down to individual buildings)
size required defines the rectangular dimensions of the map image
format optional defines the format of the resulting image (png8,png,png32,gif,jpg,jpg-baseline)
maptype optional defines the type of map to construct (roadmap,satellite,terrain,hybrid)
language optional defines the language to use for display of labels on map tiles
markers optional define one or more markers to attach to the image at specified locations, more info
path optional defines a single path of two or more connected points to overlay on the image at specified locations, more info
visible optional specifies one or more locations that should remain visible on the map
style optional defines a custom style to alter the presentation of a specific feature (road, park, etc.) of the map, more info
sensor required specifies whether the application requesting the static map is using a sensor to determine the user’s location, more info

create a new MVC 3 Web application and add the following module into your Models folder

Google Static Map Extension Method (VB .NET)

Public Module HtmlHelpers

    Function GoogleStaticMap(helper As HtmlHelper,
                             title As String,
                             latitude As Decimal,
                             longitude As Decimal,
                             width As Integer, height As Integer,
                             Optional zoom As Integer = 15,
                             Optional language As String = "en") As MvcHtmlString

        'Google Static Map API - Base URL
        Dim googleApiUrl = ""

        'a string builder for quicker text manipulation
        Dim url = New System.Text.StringBuilder

        'Setup URL with all required query strings

        'Base Url
        url.Insert(0, googleApiUrl)




        'Markers "latitude,longitude"

        'Create an <img src="URL" alr="title" />
        Dim imgTag = New TagBuilder("img")

        imgTag.MergeAttribute("src", url.ToString)
        imgTag.MergeAttribute("style", "border:1px solid black;")
        imgTag.MergeAttribute("alt", title)

        'Return the Encoded HTML
        Return MvcHtmlString.Create(imgTag.ToString(TagRenderMode.SelfClosing))

    End Function

End Module

Explain The Code

using a string builder we construct the final parameterized URL, notice that the markers parameter is of format “latitude,longitude”, then a TagBuilder is used to create our IMG tag with the attributes required to show a Google Static Map, as IMG tags are self-closing we select the self-closing TagRenderMode and return the final encoded html with MvcHtmlString.Create method.

that’s it, we create the URL, and then create an IMG tag with that URL as source.

How to use it

in your Views/Home folder, open the Index.vbhtml page and use the following code.

    ViewData("Title") = "Index"
End Code

<h2>Google Static Maps - Example</h2>

@Html.GoogleStaticMap("My First Map", 12.250151, 64.33717, 550, 500)


  • Geocoding feature
  • show multiple location markers
  • use map styles to change the appearance of the map
  • use marker styles to change the appearance of the marker


there are just too many features available in Google Maps API, we talked here about a quick and portable implementation that can quickly and easily fit into any project with a “Contact Us” page that needs a map, I hope that this can help you start your own Advanced Google Maps HTML Helper.

1 Comment

Posted by on 23, Jul 2011 in .NET, ASP.NET, MVC, VB.NET


Tags: , , , , ,