In this unit, we’ll cover the enhancements to ASP.NET in the .NET Framework 4. You’ll learn about changes to WebForms, AJAX and Dynamic Data and you’ll get introduced to ASP.NET MVC, now included in the framework.

Microsoft Virtual Academy

Free Microsoft Training…

Courses by Topics

  • C# / XAML
  • HTML5
  • Virtualization
  • Managing Desktop & Devices
  • Server Infrastructure
  • Management & Security
  • Private Cloud
  • Business Intelligence
  • Collaboration
  • Licensing
  • App Development

Courses by Products

  • Windows
  • Windows Server
  • Visual Studio
  • System Center
  • SQL Server
  • Windows Azure
  • Office


Free online training event: Developing ASP.NET MVC 4 Web Applications Jump Start (Sep 17)

Join me and Christopher Harrison (@geektrainer) for a free, full day online training event on Developing ASP.NET MVC4 Web Applications! There’s still space available, so register now.

MVA - ASP.NET MVC 4 Jump Start

Microsoft Virtual Academy (MVA) runs great, high quality live training events. Earlier this year, I had the opportunity to participate in the Building Web Apps with ASP.NET Jump Start with Scott Hanselman and Damian Edwards. For that event, we overviewed the Microsoft web platform, including a lot of new and preview features.

For this upcoming event, we’re going to be sticking closer to the curriculum for the Developing ASP.NET MVC 4 Web Applications certification exam (70-486) curriculum. Christopher is a full time, professional instructor (MCT, MCPD, MCITP) who’s helped people prepare for this exam, and we’re going to be basing the Jump Start content on what you’d learn in a 70-486 certification course.

Here’s an overview of what we’re planning to cover:

  • Overview of MVC
    • What is MVC?
    • How is MVC different from Web Forms?
    • Why use MVC?
  • Developing ASP.NET MVC 4 Controllers and Models
    • Creating Controllers
    • Adding Actions
    • Creating MVC Models
    • Working with Code First
  • Developing ASP.NET MVC 4 Views
    • Razor Syntax
    • HTML Helpers
    • Partial Views
  • Integrating JavaScript and MVC
    • Using AJAX
    • Using jQuery
  • Implementing Web APIs
    • Developing Web API Controllers
    • Calling HTTP Services from Client-Side Code
  • Deploying ASP.NET MVC Site Walkthrough
    • Creating a site on Windows Azure Web Sites
    • Deploying an ASP.NET MVC Application with Visual Studio Web Deploy
  • What’s Next and Resources
    • Sneak peak at Visual Studio 2013 (Preview) and ASP.NET MVC 5 tooling
    • A look at real-time communications with SignalR
    • Resources for keeping up with new ASP.NET releases

Note that this is a Jump Start to help you get started preparing for the certification exam, but with a one day event we’re only covering a portion of the content that’s on the exam. Don’t expect to watch this and breeze through the exam… but it’s a start.

And if you’re just new to ASP.NET MVC and want a full day (free!) day of training, this is a great opportunity. We’re working off some of the certification content, but you don’t need to be working towards the certification to take or benefit from the class.

To get you warmed up for it, here’s the one hour introduction to ASP.NET MVC 4 from the Building Web Apps with ASP.NET Jump Start this past February.

MailMessage.AlternateViews Property (Html Exemple)

Gets the attachment collection used to store alternate forms of the message body.


Use the AlternateViews property to specify copies of an e-mail message in different formats. For example, if you send a message in HTML, you might also want to provide a plain text version in case some of the recipients use e-mail readers that cannot display HTML content.

To add an alternate view to a MailMessage object, create an Attachment for the view, and then add it to the collection returned by AlternateViews. Use the Body property to specify the text version and use the AlternateViews collection to specify views with other MIME types. Use the MediaTypeNames class members to specify the MIME type for the alternate view.

The following code example demonstrates creating and sending an e-mail message with a plain text and an HTML alternate view.

		public static void CreateMessageWithMultipleViews(string server, string recipients)
			// Create a message and set up the recipients.
			MailMessage message = new MailMessage(
				"This e-mail message has multiple views.",
				"This is some plain text.");

			// Construct the alternate body as HTML.
			string body = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
			body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">";
			body += "</HEAD><BODY><DIV><FONT face=Arial color=#ff0000 size=2>this is some HTML text";
			body += "</FONT></DIV></BODY></HTML>";

			ContentType mimeType = new System.Net.Mime.ContentType("text/html");
			// Add the alternate body to the message.

			AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);

			// Send the message.
			SmtpClient client = new SmtpClient(server);
			client.Credentials = CredentialCache.DefaultNetworkCredentials;

      try {
			catch (Exception ex) {
			  Console.WriteLine("Exception caught in CreateMessageWithMultipleViews(): {0}",
                    ex.ToString() );
			// Display the values in the ContentType for the attachment.
			ContentType c = alternate.ContentType;
			Console.WriteLine("Content type");
			Console.WriteLine("Boundary {0}", c.Boundary);
			Console.WriteLine("CharSet {0}", c.CharSet);
			Console.WriteLine("MediaType {0}", c.MediaType);
			Console.WriteLine("Name {0}", c.Name);
			Console.WriteLine("Parameters: {0}", c.Parameters.Count);
			foreach (DictionaryEntry d in c.Parameters)
				Console.WriteLine("{0} = {1}", d.Key, d.Value);



Resolve: Origin is not allowed by Access-Control-Allow-Origin

This was the first q/a that popped up for me when trying to solve the same problem using .net MVC as the source of my data. I realize this doesn’t solve the php question but it is related enough to be valuable.

I am using .net mvc. The blog post from Greg Brant worked for me. Ultimately you create an attribute :

[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")]

That you are able to add to controller actions.


public class HttpHeaderAttribute : ActionFilterAttribute
   public string Name { get; set; }
   public string Value { get; set; }
   public HttpHeaderAttribute(string name, string value)
      Name = name;
      Value = value;

   public override void OnResultExecuted(ResultExecutedContext filterContext)
      filterContext.HttpContext.Response.AppendHeader(Name, Value);

and then using it with:

[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")]
public ActionResult MyVeryAvailableAction(string id)
    return Json( "Some public result" );


Other view of the problem in…

Creating Website Thumbnails in ASP.NET


Demo Program Screenshot

Download Source Code Download Source Code


Creating a small thumbnail image of a website can be a useful task. This is particularly the case with sites that are directories of websites. A thumbnail helps give the user some idea about the content of a site that they might click to visit.

Although there are a couple of gotchas, doing this from ASP.NET is fairly straight forward. The process involves creating a WebBrowser control to load and render the website image, and write that image to a bitmap.

Using the WebBrowser Control to Create a Thumbnail

The WebBrowser control is an ActiveX control. Normally, you create one of these by placing it on a Windows Form. Here, we’ll just create one dynamically without any form. One problem is that this control can only be created in a single-threaded apartment. This is the tricky part of this code. We need to create a new thread, set its apartment state to single-threaded apartment, and then run it. This worker thread will create the control and generate the thumbnail. Listing 1 shows my code for the WebsiteThumbnail class.

Listing 1. WebsiteThumbnail Class

using System;
using System.Drawing;
using System.Threading;
using System.Web;
using System.Windows.Forms;

public class WebsiteThumbnail
  protected string _url;
  protected int _width, _height;
  protected int _thumbWidth, _thumbHeight;
  protected Bitmap _bmp;

  /// <summary>
  /// Generates a website thumbnail for the given URL
  /// </summary>
  /// <param name="url">Address of website from which to generate the
  /// thumbnail</param>
  /// <param name="width">Browser width</param>
  /// <param name="height">Browser height</param>
  /// <param name="thumbWidth">Width of generated thumbnail</param>
  /// <param name="thumbHeight">Height of generated thumbnail</param>
  /// <returns></returns>
  public static Bitmap GetThumbnail(string url, int width, int height,
    int thumbWidth, int thumbHeight)
    WebsiteThumbnail thumbnail = new WebsiteThumbnail(url, width, height,
      thumbWidth, thumbHeight);
    return thumbnail.GetThumbnail();

  /// <summary>
  /// Protected constructor
  /// </summary>
  protected WebsiteThumbnail(string url, int width, int height,
    int thumbWidth, int thumbHeight)
    _url = url;
    _width = width;
    _height = height;
    _thumbWidth = thumbWidth;
    _thumbHeight = thumbHeight;

  /// <summary>
  /// Returns a thumbnail for the current member values
  /// </summary>
  /// <returns>Thumbnail bitmap</returns>
  protected Bitmap GetThumbnail()
    // WebBrowser is an ActiveX control that must be run in a
    // single-threaded apartment so create a thread to create the
    // control and generate the thumbnail
    Thread thread = new Thread(new ThreadStart(GetThumbnailWorker));
    return _bmp.GetThumbnailImage(_thumbWidth, _thumbHeight,
      null, IntPtr.Zero) as Bitmap;

  /// <summary>
  /// Creates a WebBrowser control to generate the thumbnail image
  /// Must be called from a single-threaded apartment
  /// </summary>
  protected void GetThumbnailWorker()
    using (WebBrowser browser = new WebBrowser())
      browser.ClientSize = new Size(_width, _height);
      browser.ScrollBarsEnabled = false;
      browser.ScriptErrorsSuppressed = true;

      // Wait for control to load page
      while (browser.ReadyState != WebBrowserReadyState.Complete)

      // Render browser content to bitmap
      _bmp = new Bitmap(_width, _height);
      browser.DrawToBitmap(_bmp, new Rectangle(0, 0,
        _width, _height));

Continue reading “Creating Website Thumbnails in ASP.NET”

Generate webpage thumbnail image (CSWinFormSaveWebpageToImage)

CSWinFormSaveWebpageToImage Overview


The project illustrates how to save the webpage as an image.

The code sample creates a WebBrowser to retrieve the target webpage’s
html code and uses be WebBrowser.DrawToBitmap method convert the html
code to .bmp image. In this code-sample, users can set the image’s width,
height and browser’s width, height, generate an appropriate image.

Demo the Sample.

Please follow these demonstration steps below.

Step 1: Open the CSWinFormSaveWebpageToImage.sln.

Step 2: Expand the CSWinFormSaveWebpageToImage web application and press
Ctrl + F5 to show the MainForm.cs form.

Step 3: We will see a WebBrowser control, two TextBox controls, a Button,
and a PictureBox control on the form, you can find the WebBrowser
show a web page, the Save Page button will save the current web
page of WebBrowser control.

Step 4: Click the button to save an image in web application, you can also
preview it on the PictureBox control.

Step 5: If you update the image’s size with TextBox controls text, you can
retrieve the image in the root directory of web application.

Step 6: You can even click the link of the Default.htm page to redirect the, and click Save Page button to save the online
website’s page as an image, if you find the image can not contain
whole content of pages, please adjust width or height TextBox of
MainForm.cs form.

Step 7: Validation finished.


Step 1. Create a C# “Windows Forms Application” in Visual Studio 2010 or
Visual Web Developer 2010. Name it as “CSWinFormSaveWebpageToImage”.

Step 2. Add one windows form and one class file and named them as
“MainForm.cs”, “WebPageThumbnail.cs”.

Step 3. The WebPageThumbnail class used to receive image’s information and
generate an appropriate image with html code.

// Constructor method
public WebpageThumbnail(string data, int browserWidth, int browserHeight, int thumbnailWidth, int thumbnailHeight, ThumbnailMethod method)
this.Method = method;
if (method == ThumbnailMethod.Url)
this.Url = data;
else if (method == ThumbnailMethod.Html)
this.Html = data;
this.BrowserWidth = browserWidth;
this.BrowserHeight = browserHeight;
this.Height = thumbnailHeight;
this.Width = thumbnailWidth;

/// <summary>
/// Create a thread to execute GenerateThumbnailInteral method.
/// Because the <a title="Auto generated link to System.Windows.Forms.WebBrowser" href="" target="_blank">System.Windows.Forms.WebBrowser</a> control has to
/// run on a STA thread while the current thread is MTA.
/// </summary>
public Bitmap GenerateThumbnail()
Thread thread = new Thread(new ThreadStart(GenerateThumbnailInteral));
return ThumbnailImage;

/// <summary>
/// This method creates WebBrowser instance retrieve the html code. Invoke WebBrowser_DocumentCompleted
/// method and convert html code to a bmp image.
/// </summary>
private void GenerateThumbnailInteral()
WebBrowser webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
if (this.Method == ThumbnailMethod.Url)
webBrowser.DocumentText = this.Html;
webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while (webBrowser.ReadyState != WebBrowserReadyState.Complete)

private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
WebBrowser webBrowser = (WebBrowser)sender;
webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight);
webBrowser.ScrollBarsEnabled = false;
this.ThumbnailImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
webBrowser.DrawToBitmap(ThumbnailImage, webBrowser.Bounds);
this.ThumbnailImage = (Bitmap)ThumbnailImage.GetThumbnailImage(Width, Height, null, IntPtr.Zero);

Continue reading “Generate webpage thumbnail image (CSWinFormSaveWebpageToImage)”