Published: 17 Nov 2010
By: Xianzhong Zhu
Download Sample Code

In this article, we are going to continue to explore the other three important helpers - WebImage, WebMail, and Crypto.

Contents [hide]

The Experience ASP.NET MVC 3 Beta series

  • Part 1 In the coming ASP.NET MVC 3.0 a lot of new good things will be added or enhanced. In this article, we are going to focus upon the new view engine Razor to see how it will simplify the view design.
  • Part 2 In addition to the introduction of a new view engine Razor, ASP.NET MVC 3 Beta has also introduced numerous new HtmlHelpers, such as Chart, Crypto, WebGrid, WebImage, WebMail, etc. This article aims to introduce the two commonly-used new helper controls – WebGrid and Chart using relevant examples.
  • Part 3 In this installment, I'll first tell you a short story about unobtrusive JavaScript. Then, we'll delve into the unobtrusive client-side validation support. Finally, we will research into a more interesting story - the unobtrusive jQuery-Based Ajax support.
  • Part 4 In this article, we are going to continue to explore the other three important helpers - WebImage, WebMail, and Crypto.
  • Part 5 Starting from this article, let's explore some more advanced concepts and related utilizations associated with flexible Dependency Injection support introduced in ASP.NET MVC 3 Beta.
  • Part 6 In the last article, we've mainly discussed the new-styled DI support in ASP.NET MVC 3 Beta/RC in relation to the two new services - IControllerActivator and IViewPageActivator. Obviously, both of them are connected with controllers and views. In this article, however, we will shift our attention to the Model (generally called viewmodal in many blogs) related DI manipulations.
  • Part 7 Since ASP.NET MVC 1, CSRF (Cross Site Request Forgery) has been considered by introducing a set of anti-forgery helpers. In this article, we are to detail into CSRF related concepts and ASP.NET MVC's helper functions again CSRF.
  • Part 8 In this series of articles, we are going to explore as many as possible aspects of cache programming in the latest ASP.NET MVC 3 RC2 framework. And also, all the related samples have been tested against the latest ASP.NET MVC 3 RC 2.
  • Part 9 In the first part of this series, we've mainly explored Output Cache related issues. In this second part, however, we are going to delve into the general Data Cache topic.
  • Introduction

    In the last article I've showed you the elementary usage of the two newly-introduced helpers - WebGrid and Chart in ASP.NET MVC 3 Beta. In this article, we are going to continue to explore the other three important helpers - WebImage, WebMail, and Crypto.

    NOTE

    The development environments we'll utilize in this series are:

    1. Windows XP Professional (SP3);

    2. .NET 4.0;

    3. Visual Studio 2010;

    4. ASP.NET MVC 3 Beta (http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0abac7a3-b302-4644-bd43-febf300b2c51);

    First of all, let's set up a sample project sketch convenient for the subsequent discussion.

    Sample project sketch

    Suppose you've installed ASP.NET MVC 3 Beta. Now, start up your Visual Studio 2010 IDE to create an ASP.NET MVC 3 web application, naming it Mvc3Crypto_Image_Mail. And as usual, in the subsequent dialog box select the template "Internet Application" as the project template and Razor as the view engine. And for simplicity, we don't add the related unit test project.

    Next, let's shift to the real story, starting with the WebImage helper.

    The WebImage Helper

    If your get used to ASP.NET Webforms Image control, you will find ASP.NET MVC framework lacks such a control. Joyfully, in the current ASP.NET MVC 3 Beta a similar control has been introduce - WebImage. Now, whether in the view or in the controller you can easily deal with image operations, such as uploading, cropping, adding watermark, flipping, and generating thumbnail. For brevity, let's only discuss some cases. However, for all the rest samples please refer to the downloadable source project.

    Let's first look at the definition of the WebImage helper.

    The WebImage helper definition

    Open Object Browser in Visual Studio 2010, you will easily from the namespace System.Web.Helpers find the WebImage helper's definition.

    Listing 1: The WebImage helper definition

    If you are familiar with image editing tools or ever develop some image related applications, you will realize all the above members are commonly-used ones. To use this class, there are still several pointed worth stressing.

    First, if an image actually has been uploaded then you get the image name from the image's FileName property. When the user uploads the image, FileName contains the user's original name, which includes the path from the user's computer. It might look like this:

    Second, stronger than the ASP.NET Image control, the WebImage helper supports a good many popular image formats, as shown below.

    Listing 2: Plentiful image formats support

    OK, now let's save spaces to some concrete samples.

    Upload Image - using WebMatrix style

    Open the HomeCtroller controller and add a simple action named UploadImage, as shown below.

    Now, right click the action UploadImage and add a new view named UploadImage, as shown below.

    Listing 3: The view UploadImage.cshtml

    You have to admit that the Razor-styled syntax is an excellent thing introduced in ASP.NET MVC 3 Beta. It not only greatly simplifies the view design but introduces an ASP.NET Webforms-styled behind-code programming model.

    As you've seen, the first part in the above code serves just as the behind code in the ASP.NET Webforms case. Let's next refer to the running-time snapshot to detail into the inner implementation logic.

    When the view first starts up the initial running-time snapshot looks like Figure 1.

    Figure 1: The initial snapshot when uploading image

    The initial snapshot when uploading image

    Next, we browse a local .bmp (or any other supported formats) file and click the button "Start upload". At this time, the IsPost property equals to true, and then the subsequent code gets executed. By invoking the method GetImageFromRequest of the WebImage, all the related data with the uploaded image will be stored in the WebImage instance. Finally, the image is uploaded on the server side by invoking the Save method. Shortly afterwards, when the image is uploaded to the server side the image is displayed at the bottom part. Figure 2 illustrates the corresponding running-time snapshot.

    Figure 2: After the image gets uploaded the image is shown below

    After the image gets uploaded the image is shown below

    Have you learned the executing time of the last part starting with @if(imagePath!="")? When the view first starts up the value of variable imagePath is null, so this part does not get executed. After the image gets uploaded, however, the last part starts to execute. Then, the image is rendered at the bottom.

    One more word is it is necessary for us to research further into the new Razor-syntax based view life cycle.

    To make a better contrast, let's look at the traditional ASPX view engine related solution relevant to uploading images.

    Upload Image - using traditional MVC idea

    First of all, let's add another action named UploadImage2 into the Home controller.

    Second, right click the above action UploadImage2 to add a new view named UploadImage2.cshtml. Then, replace the initial content of the view with the following:

    Note in the above code the part enctype="multipart/form-data" is a MUST HAVE for file uploading operation. Then, the second part action='@Url.Action("SaveImageAndReturnPath")' should not be strange to you. This means when the user clicks the button "Start upload" the action SaveImageAndReturnPath will get invoked.

    Next, let's look into the method SaveImageAndReturnPath related implementation.

    Herein, the method GetImageFromRequest is still the key. Then, by calling the Save method the image is persisted on the server side. Next, we construct a <img/> element with the src property assigned the above image related path. At last, we return the html using the Content property.

    Till now, as you've guessed, since we have utilized a simple Content property and not used Ajax style as soon as the image gets uploaded a complete postback takes place. So, you will see the image get rendered with a whole update. This is really regrettable. For Ajax-styled implementation, I suggest you to try a jQuery-based solution like this.

    Someone may ask, "Why we do not use the Ajax.BeginForm solution" built in ASP.NET MVC? In fact, according to my research, the current Ajax.BeginForm implementation has not provided support for the Ajax-styled solution associated with file upload.

    Let's next look at another important image manipulation - cropping and image.

    Crop an Image

    As shown above, the WebImage helper also supports cropping an image using its Crop method:

    If you are familiar with any kind of image editor you will work with the method Crop more easily. To make a more interesting sample, I suggest you to fall back upon JCrop (a jQuery plugin which allows users to select an area of an image to keep) to do the related test. In fact, there has already been an excellent article detailing into this on the Internet. Please refer to here.

    Therefore, I will not waste space to chatter about the Crop method any more.

    Watermark support

    First, add a new action called Watermark into the Home controller.

    Then, right click the above method to add a new view named Watermark, as shown in the following.

    As you've seen, we directly deal with the image on the web side. By invoking the method AddTextWatermark, we easily accomplish the task of watermarking the current image using the specified text. Again, in the above implementation we used the WebMatrix-styled view programming.

    Due to space limitation, we are going to stop the discussion with the WebImage helper. But do not worry. As for the other important methods such as AddImageWatermark, Resize, Flip, and Write, we have all provided corresponding samples. Please refer to the downloadable source project accompanying this article.

    Let's next shift our attention to another important and commonly-used helper - WebMail.

    The WebMail Helper

    If you are familiar with the .NET supported System.Web.Mail class you may have known adding generally-used e-mail sending support is not a difficult problem in the traditional ASP.NET Webforms development. In the case of early ASP.NET MVC framework, however, there was much trouble with this. Joyfully, ASP.NET MVC 3 Beta has introduced a related helper named WebMail which has greatly simplified the e-mail handling work. In subsequent introduction, you will find that the WebMail helper is not only powerful but also easy to use. Let's create a related sample.

    As usual, let's add the two simple actions into the Home controller first.

    Then, right click the above two actions to add two associated views with the same name as the related action. Let's first look at the view EmailRequest related coding.

    Listing 4: Code for the view EmailRequest.cshtml

    Here, we've constructed a simple form to send an e-mail to ask help from the server side. Easily seen, as the post of the form happens, the action ProcessRequest will be invoked.

    As seen above, when the action ProcessRequest returns the related view ProcessRequest will be triggered. Let's look at the related coding.

    Listing 5: Code for the view ProcessRequest.cshtml

    Again, we've leveraged the WebMatrix-styled programming. First, we abstract the two items of data through the Request object. Then, by invoking the related static methods of the static class WebMail we have easily accomplished the task of sending out an e-mail. As you've seen, here we select the gmail as our e-mail service provider. So, the properties, such as SmtpServer, SmtpPort, EnableSsl, and all the related ones should be set up properly. For other e-mail service support you should provide the corresponding data. In fact, you can easily find this info through the e-mail service website.

    In the above sample, we've not considered the attachment related stuff. In fact, it's also a piece of cake. But for the concrete related sample, please check out the downloadable source project- there are two views named SendFile.cshtml and ProcessFile.cshtml respectively tackling this problem.

    Next, let's explore another newly-introduced important helper - Crypto.

    The Crypto Helper

    Hash functions are fundamental to modern cryptography. These functions map binary strings of an arbitrary length to small binary strings of a fixed length, known as hash values. Hash functions are commonly used with digital signatures and for data integrity.

    The hash is used as a unique value of fixed size representing a large amount of data. Hashes of two sets of data should match if the corresponding data also matches. Small changes to the data result in large unpredictable changes in the hash.

    In cryptography, a salt consists of random bits that are used as one of the inputs to a key derivation function. The other input is usually a password or pass-phrase. In detail, salt data results in complicating dictionary attacks that use pre-encryption of dictionary entries: each bit of salt used doubles the amount of storage and computation required.

    For best security, the salt value is kept secret. To determine a password from a stolen hash, an attacker cannot simply try common passwords. Rather, they must calculate the hashes of random characters, which is much slower.

    In ASP.NET MVC 3 Beta, the helper Crypto has been introduced to use hashing algorithms to create properly salted and hashed passwords. Listing x below illustrates the complete declaration of the class Crypto.

    As shown from the above definition, the method GenerateSalt can be used to generate a salt. You can also use the Hash method to hash a string or a byte array, with the default hash algorithm sha256. Let's next detail into some of the generally-used methods in this Crypto class.

    The Hash method

    There are totally two forms of definitions for the method Hash. Look at the following stripped using .NET Reflector.

    Seen from above, the default hash algorithm is sha256. Apparently, you can select to use any other hash algorithms supported by .NET, such as SHA, SHA1, MD5, SHA256, SHA384, and SHA512. For more details about the supported hash algorithms, please refer to here in MSDN.

    On the other hand, as indicated above, simply using the Hash method will not automatically utilize the salt. For example:

    This helper returns a hash for the specified data. The default algorithm is "sha256". Therefore, to salt the above hash, you can resort to another method named GenerateSalt and revise the code like the following:

    in fact, in typical cases, such as with password, you can fall back upon another ready method named HashPassword which builds in the salt functionality. Again, let's pick up .NET Reflector to look into the inner implementation of this method.

    Above, another internal and static method HashWithSalt is invoked.

    Note, by default, the method HashWithSalt also calls the sha256 hash algorithm.

    Therefore, with the method HashPassword, the preceding code can also be expressed like this:

    The methods SHA1, SHA256 and VerifyHashedPassword

    Again, let's pick up .NET Reflector to look into the inner implementation of the two methods - SHA1 and SHA256.

    They are both apparently to understand, aren't they? In the behind implementation they both invoke the previous Hash method with the related default hash method as the parameter. In another word, under cases with no salt support you can directly leverage these two methods.

    As hinted from the name, the method VerifyHashedPassword is used to verify the password. Let's next construct a concrete sample to piece some of the above important methods together.

    A complete sample

    Open the above sample project Mvc3Crypto_Image_Mail and add at the end of the controller HomeController the following two actions:

    Now, right click the first action to add a new view named CryptoHelperTest. Then, replace the view content with the following:

    In the above code, there are some pointed deserved to be take notice of. The first is we called two HtmlHelper methods which can help to trigger the client-side unobtrusive jQuery-base Ajax JavaScript functionality. To start this, we should also add the related script reference in the Master page file _Layout.cshtml, like the following:

    The detailed discuss has been covered in another article on DotNetSlackers.

    The second point to notice is we constructed a simple Ajax-styled form. Note there we invoke another action DealwithHash in the Home controller. And also, we specify a <div/> element with id being resultDiv serves to show the Ajax calling returned result.

    Let's next track to see the detailed implementation of the action DealwithHash, as shown below.

    First, through the familiar Request method we obtain the passed original password. Then, if it's an Ajax calling then we continue to do with the passed data.

    Next, we call the method GenerateSalt of the class Crypto to generate a salt. And then, we call the method HashPassword to hash the original password. At last, we use another method VerifyHashedPassword to check if the original password and the hashed one match. Easily seen, since the method HashPassword has built in the salt functionality we don't need to generate the salt any more. To purposefully put the method GenerateSalt here is just to get you familiarized with it.

    At last, we constructed a <fieldset/> element populating all our calculated interested data and use the Content property of the controller to return it to the client side.

    Well, let's now take a look at the running-time results. When you start up the sample project Mvc3Crypto_Image_Mail and populate the url http://yourserver/home/CryptoHelperTest in the address bar and press ENTER key, you will see the initial snapshot, as shown in Figure 3 below.

    Obviously, this is a pretty simple example. Now, if you enter "abc" and hit the button "Submit" then server-side action DealwithHash will be triggered with the string passed in. then, you will see the returned data shown in the bottom part in the Ajax way. Figure 4 below gives the running-time snapshot.

    On the whole, the helper Crypto in ASP.NET MVC 3 Beta will help to greatly simplify the hash related encryption operations.

    Summary

    In this article, I've showed you still the elementary usage of the three newly-introduced helpers, WebImage, WebMail, and Crypto, in ASP.NET MVC 3 Beta with relevant examples. In practical cases, things will surely become far more complex than given here. And also, these functionalities are still in the Beta version; the finial release may change some. So it's only for new learners' reference.

    The Experience ASP.NET MVC 3 Beta series

  • Part 1 In the coming ASP.NET MVC 3.0 a lot of new good things will be added or enhanced. In this article, we are going to focus upon the new view engine Razor to see how it will simplify the view design.
  • Part 2 In addition to the introduction of a new view engine Razor, ASP.NET MVC 3 Beta has also introduced numerous new HtmlHelpers, such as Chart, Crypto, WebGrid, WebImage, WebMail, etc. This article aims to introduce the two commonly-used new helper controls – WebGrid and Chart using relevant examples.
  • Part 3 In this installment, I'll first tell you a short story about unobtrusive JavaScript. Then, we'll delve into the unobtrusive client-side validation support. Finally, we will research into a more interesting story - the unobtrusive jQuery-Based Ajax support.
  • Part 4 In this article, we are going to continue to explore the other three important helpers - WebImage, WebMail, and Crypto.
  • Part 5 Starting from this article, let's explore some more advanced concepts and related utilizations associated with flexible Dependency Injection support introduced in ASP.NET MVC 3 Beta.
  • Part 6 In the last article, we've mainly discussed the new-styled DI support in ASP.NET MVC 3 Beta/RC in relation to the two new services - IControllerActivator and IViewPageActivator. Obviously, both of them are connected with controllers and views. In this article, however, we will shift our attention to the Model (generally called viewmodal in many blogs) related DI manipulations.
  • Part 7 Since ASP.NET MVC 1, CSRF (Cross Site Request Forgery) has been considered by introducing a set of anti-forgery helpers. In this article, we are to detail into CSRF related concepts and ASP.NET MVC's helper functions again CSRF.
  • Part 8 In this series of articles, we are going to explore as many as possible aspects of cache programming in the latest ASP.NET MVC 3 RC2 framework. And also, all the related samples have been tested against the latest ASP.NET MVC 3 RC 2.
  • Part 9 In the first part of this series, we've mainly explored Output Cache related issues. In this second part, however, we are going to delve into the general Data Cache topic.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Xianzhong Zhu

    I'm a college teacher and also a freelance developer and writer from WeiFang China, with more than fourteen years of experience in design, and development of various kinds of products and applications on Windows platform. My expertise is in Visual C++/Basic/C#, SQL Server 2000/2005/2008, PHP+MyS...

    This author has published 81 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
    A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
    Exception Handling and .Net (A practical approach)
    Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    Book Review: SignalR: Real-time Application Development
    A book review of SignalR by Simone.
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.

    You might also be interested in the following related blog posts


    Introducing SharePoint 2010 Training at U2U read more
    12 ASP.NET MVC Best Practices read more
    The Telerik CAB Enabling Kit and SCSF - Tutorial 5: The RadPanelBar UIExtensionSite read more
    MvcContrib working on Portable Areas read more
    Business Apps Example for Silverlight 3 RTM and .NET RIA Services July Update: Part 25: ViewModel read more
    Default Templated Views read more
    Telerik Announces Support for Microsoft Silverlight 3 read more
    Going Controller-less in MVC: The Way Fowler Meant It To Be read more
    Afternoon of ASP.NET MVC [16 June] (free Headspring event) read more
    ASP.NET MVC and the templated partial view (death to ASCX) read more
    Top
     
     
     

    Please login to rate or to leave a comment.