MVC / Validating an email address with DataAnnotation

If you’re using MVC and want to capture an email address, there is a great built-in way to validate the address. When creating your model, add the [EmailAddress] DataAnnotation like below.

 [Required]
 [EmailAddress]
 [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
 [DataType(DataType.EmailAddress)]
 [Display(Name = "Email Address")]
 public string Email { get; set; }

Then you can add to your view:

 <li>
 <%: Html.LabelFor(m => m.Email) %>
 <%: Html.TextBoxFor(m => m.Email) %>
 </li>

And if you enter an invalid email you’ll get the error:

Invalid Email Address

MVC / Validating an email address with DataAnnotation

.net SMTP – Sending An Email Message With A Display Name

email-blueIf you’ve ever used .net to send email messages (and I hope you have!) you may have wanted to send the message from or to not only an address, but also include a name. The ‘display name’ is the name that appears in many email clients instead of the address (think ‘Chris Bitting’ instead of ‘cbitting@something.com’). .Net honors the email standard of “Display Name <email@domain.com>”.

Below is a quick example on how this looks in vb.net:

Dim mail As New System.Net.Mail.MailMessage("""Some Body"" <person@company.com>", """A Different Person"" <person2@company2.com>", "Subject", "Body")

Below is a full example on an email function (include Imports System.Net.Mail): Continue reading “.net SMTP – Sending An Email Message With A Display Name”

.net SMTP – Sending An Email Message With A Display Name

Parsing Html content using Html Agility Pack, Cookies & Proxy

stockpriceIf you’ve ever needed to parse (screen scrape?) some remote html, you may have wanted to pull info from a page that only renders content to a browser. The below example shows how to grab some content from a web page (using a web request) but also incorporates using cookies and a proxy to help and the Html Agility Pack to parse the returned html (allowing you to get a specific element):

Imports System.Net
Imports System.Web

Public Class Form1

    Public cookies As New CookieContainer

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        'create a web request
        Dim wreq As HttpWebRequest = WebRequest.Create("http://www.reuters.com/finance/stocks/overview?symbol=AMZN.OQ")

        'set the agent to mimic a recent browser
        wreq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5"

        'how you're getting the page
        wreq.Method = "get"

        'create a proxy
        Dim prox As IWebProxy = wreq.Proxy

        'set the proxy cred
        prox.Credentials = CredentialCache.DefaultCredentials

        'create the html doc & web
        Dim document As New HtmlAgilityPack.HtmlDocument
        Dim web As New HtmlAgilityPack.HtmlWeb

        'needs to use cookies
        web.UseCookies = True

        'set the cookie request
        wreq.CookieContainer = cookies

        'start a response
        Dim res As HttpWebResponse = wreq.GetResponse()

        'get a stream from the response
        document.Load(res.GetResponseStream, True)

        'get some data from the page. 
        'in the below example, i'm looling for a div with the class 'sectionQuoteDetail' and getting the content of the second span inside
        Dim strCurrentQuote = document.DocumentNode.SelectSingleNode("//div[@class='sectionQuoteDetail']//span[2]")

        MsgBox(strCurrentQuote.InnerText)

    End Sub

End Class

As a side note, the use of the proxy code above also solves the frequent HttpWebRequest WebException “The remote server returned an error: (407) Proxy Authentication Required” error.

Parsing Html content using Html Agility Pack, Cookies & Proxy

Creating a .dll library for use in vbscript (.vbs) using Visual Studio

dllSo for some reason you have the need to use vbscript (maybe a .vbs file, Excel script, etc) but like many others before you, you have run into a limitation of vbscript. I’m not going to discuss the reasons why / why not to use vbscript, I am already assuming you have a good reason. Onto the example. In this case, we are “fixing” the limitation of vbscript to not handle larger numbers well. We are going to extend our vbscript by creating a .dll library in Visual Studio that allows us to pass and return data in the format we need, in the example case, to round a large decimal number. Continue reading “Creating a .dll library for use in vbscript (.vbs) using Visual Studio”

Creating a .dll library for use in vbscript (.vbs) using Visual Studio

Downloading a remote file with vb.net / c# using WebClient

Can you believe it’s 2013 already? Me either. Anyhow, just wanted to provide a simple solution for a very popularly asked question: “how can I download a remote file?.” Well, below is a basic method using the WebClient class. It’s pretty cut and dry, just pass a remote file (ie: http://www.chrisbitting.com/image.jpg) and a local file (c:\temp\file.jpg) and it downloads. If you’re interested how to do this with cookies enabled for authentication, let me know!

vb.net

Private Sub dloadhttpFile(fileToDownload As String, localFile As String)
        'Examples:
        'fileToDownload = http://www.chrisbitting.com/image.jpg
        'localFile = c:\files\someimage.jpg

        Try
            'create an instance of WebClient - the heart of downloading a file
            Dim fileReader As New WebClient()

            'check if the file already exists locally
            If Not (System.IO.File.Exists(localFile)) Then
                fileReader.DownloadFile(fileToDownload, localFile)
            End If
        Catch ex As HttpListenerException
            Console.WriteLine(("Error Downloading: " & fileToDownload & " - ") + ex.Message)
        Catch ex As Exception
            Console.WriteLine(("Error Downloading: " & fileToDownload & " - ") + ex.Message)
        End Try
    End Sub

c#

   private void dloadhttpFile(string fileToDownload, string localFile)
        {
             //Examples:
             //fileToDownload = http://www.chrisbitting.com/image.jpg
             //localFile = c:\files\someimage.jpg

            try
            {
                //create an instance of WebClient - the heart of downloading a file
                WebClient fileReader = new WebClient();

                //check if the file already exists locally
                if (!(System.IO.File.Exists(localFile)))
                {
                    fileReader.DownloadFile(fileToDownload, localFile);
                }
            }
            catch (HttpListenerException ex)
            {
                Console.WriteLine("Error Downloading: " + fileToDownload + " - " + ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error Downloading: " + fileToDownload + " - " + ex.Message);
            }
        }
Downloading a remote file with vb.net / c# using WebClient

VB.net Measure string width & height – including multi-line strings

Dim fontToMeasure As New Font("Microsoft Sans Serif", 14, FontStyle.Bold)
Dim sizeOfString As New SizeF
Dim g As Graphics = Me.CreateGraphics

sizeOfString = g.MeasureString("This is line 1" & vbcrlf & "This is line 2", fontToMeasure)
Debug.WriteLine("String Height: " & sizeOfString.Height)
Debug.WriteLine("String Width: " & sizeOfString.Width)

If you want to limit the width (so it wraps), use below (300 was my width to set as max):

Dim fontToMeasure As New Font("Microsoft Sans Serif", 14, FontStyle.Bold)
Dim sizeOfString As New SizeF
Dim g As Graphics = Me.CreateGraphics

sizeOfString = g.MeasureString("This is line 1" & vbcrlf & "This is line 2", fontToMeasure, 300)
Debug.WriteLine("String Height: " & sizeOfString.Height)
Debug.WriteLine("String Width: " & sizeOfString.Width)
VB.net Measure string width & height – including multi-line strings