Awesomium with .NET 4

Welcome!

Hello and welcome to the introduction of Awesomium.NET, the official .NET wrapper for Awesomium. In this article, we’ll talk about Awesomium, how it integrates with .NET, and the exciting new possibilities it opens for .NET developers.

 

What is Awesomium?

Awesomium is a flexible, windowless, web-browser framework that is meant to be used in your own applications. Think of it as if we took Chrome, chopped it into smaller, re-usable pieces, and served it to you on a nice shiny 32-bit BGRA pixel-buffer platter.

It is not an application, it is not a web-browser; it is a tool to add web-browser-like capabilities to another application.

Think of radical new browsing interfaces, multi-touch, HTML UI, in-game browsing, web-page capture, site scraping, automation, and awesome new web-browser mashups.

Awesomium is powerful and easy to use (it takes just 7 lines of code to render a page!) but gives you freedom when you want it.

The framework handles almost all the low-level tasks for you (network stack, HTML parsing, JS engine, layout, rendering etc.) but you can absolutely redefine much of the low-level behavior if you’d like (expose methods and data to Javascript, implement your own resource back-end, modify headers, and more).

“…I think this balance between ease-of-use and low-level flexibility gives developers the best of both worlds.”

What does this mean for .NET applications?

Let’s face it, the default WebBrowser control is fairly restrictive and out-of-date. It’s not much more than a wrapper around an IE ActiveX control and so you inherit all the limitations of Internet Explorer.

.NET WebBrowser Source Code

//-------------------------------------------------------------
//
//    Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
//
// Description:
//      WebBrowser is a wrapper for the webbrowser
//      activex control
//      Copied from webbrowser.cs in [....]
//
// History
//  04/17/05    KusumaV      Created
//  02/22/08    [....]       Expose the WebBrowser control
//  04/24/08    [....]     Implemented hosting the WebOC in the
//                         browser process for IE 7+ Protected
//                         Mode
//-------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows;
using MS.Win32;

// [...] //
namespace System.Windows.Controls
{
    /// <summary>
    /// This is a wrapper over the native WebBrowser control 
    /// implemented in shdocvw.dll. 
    /// </summary>
    /// <remarks>
    /// The WebBrowser class is currently not thread safe. 
    /// Multi-threading could corrupt the class internal state,
    /// which could lead to security exploits (see example in 
    /// devdiv bug #196538). So we enforce thread affinity. 
    /// </remarks>
    public sealed class WebBrowser : ActiveXHost
    {
        //----------------------------------------------

In short terms:

  • You are embedding IE in your application. Need we say more?
  • You are wrapping an ActiveX control; and if you want any kind of interoperability with the page, you need to go through a lot of COM Interop. Furthermore, you’re limited to Windows-only.
  • You depend on the version of IE your client has installed. If you intend to display specific web pages in your application, you cannot expect that they will be displayed the same way in all systems; you cannot even expect they will be displayed at all, if for example the pages are designed using modern HTML or Javascript features that the installed IE version does not support
  • You depend on your client’s Internet Options settings: What if, for example, your client, who does not use IE any longer, had once set a proxy through Internet Options, that is no longer valid?
  • The WebBrowser is not windowless. You have absolutely no control over what is painted or how it’s painted and can’t transform or animate it using any of the normal WPF facilities.
Testing .NET WebBrowser

Same .NET 2.0 application running in 2 different systems

How is Awesomium Different?

  • Awesomium is based on Chromium: a browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. As such, the Awesomium Web Browser Framework supports the latest in web standards: HTML5 semantics, JavaScript, and CSS3, as well as Flash™ and Silverlight™ plugins.
    HTML5, Flash™ and Silverlight™
  • Awesomium is Platform Independent! Even for .NET developers with the use of our Awesomium.Mono assembly that is part of the Awesomium.NET project.
    Windows, Mac OSX and Linux
  • Awesomium is independent and highly configurable. You do not need to rely on components or settings that your application cannot be aware of. Everything comes packed with your application.
  • Awesomium is windowless! It renders straight to a pixel buffer (a bucket that stores pixels in memory). That basically means that if you want to actually see a web-page on your screen, you’ll need to display it yourself (which is a good thing, it gives you the freedom to display it any way you want).
  • Awesomium uses a multi-process architecture for crash isolation, security sandboxing, and premium load-balancing across multiple CPU cores.

    Multi-Process Awesomium

The Awesomium.NET Project

The Awesomium.NET project wraps all the exciting features of Awesomium into a set of technology-related .NET assemblies.

The Awesomium.NET Assemblies:

Awesomium.NET Assemblies

New Features:

Starting with Awesomium SDK v1.6.3, we have a introduced a number of exciting new features to our .NET wrapper. Here are just some of them:

  • Rendering performance has been noticeably improved
  • Visual Studio integration has been greatly improved. The Windows installer now includes project templates and will automatically register all .NET controls in your VS Toolbox.
  • On Windows, Awesomium will be installed into the GAC (Global Assembly Cache) and all dependencies will be automatically deployed to your output directory when you link against the managed assembly.
  • Child Process configuration has been added. This will allow you to use your own executable to host the WebView child-process (that way, in the Task Manager, all sub-processes will share the name of your executable).
  • Mono support has been improved across all platforms. Now uses a single assembly for all platforms and automatically loads Awesomium dependencies via ldd on Linux.
  • Integrates all recent core changes (History API, Login Dialogs, Javascript Dialogs, etc.)

Presentation

Let us take a closer look to each of the assemblies in Awesomium.NET and explore some of their major features.

Awesomium.Core:

The Awesomium.Core assembly wraps the core engine of Awesomium. It’s compiled against .NET Framework 4 Client Profile and is the major dependency between all Windows Awesomium.NET assemblies. Awesomium.Mono is the platform-independent equivalent and is compiled against .NET Framework 2. If you want to use Awesomium in your application and don’t mind handling display, input, and event-handling, then Awesomium.Core or Awesomium.Mono is all you need. The major components available in Awesomium.Core are:

  • WebCore: The WebCore is the heart of Awesomium. It initializes, starts and stops the Awesomium core engine, acts as a WebView factory, controls the lifetime of web-views and takes care of updating their buffer and firing events. When used in a UI environment, the WebCore enables the auto-update feature which allows the core engine to automatically update the buffer of all views, process any changes and trigger events using the current synchronization context.

    Tips & Tricks:

    • When working with Awesomium, keep in mind that the Awesomium core engine and all components exposed through Awesomium.NET are not thread-safe.
    • When used in an non-UI environment, the only requirement is that all calls to the Awesomium API are made from the same thread that initialized the WebCore, or created the first WebView (if explicit initialization was not provided).
    • In UI environments, you can control the auto-update frequency by setting the WebCoreConfig.AutoUpdatePeriod configuration setting during initialization.
    • Note that there can only be a single Awesomium core engine (WebCore) running per process. Additionally, since most of the internal operation of Awesomium (including Shutdown) are performed asynchronously, it is suggested that you avoid restarting (Shutdown and Initialize again) the WebCore. The regular lifetime of the single WebCore, should complete when your application is about to exit and all UI (if any) is already destroyed.
    • When used in a UI environment that Awesomium.NET does not already provide a component for, you can check the WebCore.IsAutoUpdateEnabled property to make sure that auto-update is enabled. Not all UI environments provide a valid synchronization context.
    • When auto-update is not enabled, you should define your own timer to call WebCore.Update. The only requirement, as mentioned before, is that all calls are made from the same thread that initialized the WebCore.
    • A WebViewCollection (ReadOnlyObservableCollection of IWebView) exposed through the WebCore.Views property, allows the WebCore to become a friendly items source in an MVVM application.

    WebCore

  • IWebView: The IWebView interface exposes all methods, properties and events that are common to all web-view components provided by Awesomium.NET. It is implemented by the WebView and all WebControls so if you are using various kinds of web-view components in your application, the IWebView allows you to communicate with all of them using a common interface. What’s more, the WebViewCollection exposed through the WebCore.Views property, is a ReadOnlyObservableCollection of IWebView. The views may be WebViews or Windows Forms WebControls implementing INotifyPropertyChanged or WPF WebControls (DependencyObject) exposing DependencyProperties. Either way, they are ready to be bound to a view in an MVVM application. Additional features, such as the ability to bind directly to the buffer of a web-view using an Image control (WPF) or PictureBox (WinForms), are planned.

  • WebView: The WebView is sort of like a tab in Chrome: you can load web-pages into it, interact with it, and render it to a buffer. We give you the raw pixels, its your duty to display it or save to an image file. We actually provide two predefined methods for saving the buffer to PNG or JPEG format. You can start capturing web-pages right away by reading the Capturing Web-Pages With C# (.NET) tutorial.

    Tips & Tricks:

    • The WebView implements INotifyPropertyChanged through ViewModel which makes it ideal for use in an MVVM application. In fact, although Awesomium.NET provides a WPF WebControl, in more advanced scenarios the use of WebViews is more appropriate. Of course this means that user input needs to be manually processed and the pixel buffer has to be displayed accordingly.
    • You can create WebViews that render the HTML source of any web-page that they load, by using the WebCore.CreateSourceWebView function.
    • The Awesomium.Windows.Controls and Awesomium.Windows.Forms assemblies, provide a Utilities class with helper methods that can be used to turn technology specific user input data to their Awesomium equivalent, or copy a WebView’s pixel buffer to a technology specific bitmap or surface.



    There are no limits when it comes to rendering a WebView’s pixel buffer to various surfaces. All you need to do is convert the user input data of the specific surface or environment to their Awesomium equivalent and then copy the pixel buffer to your surface. Which is more or less what the components provided by Awesomium.NET already do. Awesomium.NET already includes components for use in WPF and Windows Forms while work is on progress for providing components and utilities for use in Gtk# (with Awesomium.Mono), XNA and Unity.
    WebView

Awesomium.Windows.Controls:

The Awesomium.Windows.Controls assembly provides WPF developers with a ready to use, drag-and-drop, standalone WPF control that handles all the basic embedding tasks (mouse/keyboard input, rendering, resizing, cursors, focusing, etc.) and various utilities that can help WPF developers take advantage of all Awesomium features. Here are some details of what you can find in the Awesomium.Windows.Controls assembly:

  • WebControl: The WPF WebControl has been our major .NET component since v1.6.2. Starting with Awesomium SDK v1.6.3, the WPF WebControl and WebSourceControl, are automatically added to the Visual Studio 2010 Toolbox during installation, allowing developers to simply drag-and-drop the control to any container or in XAML and automatically add all dependencies (managed and unmanaged) to their project. Performance of the WPF WebControl has significantly improved and many improvements are planned in future versions, including advanced design-time support. To read more about the WPF WebControl, see the Introducing the WebControl (WPF) article.

    Just one step to embed the Web to your WPF application:

    <Window 
        x:Class="WpfApplication1.MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:awe="http://schemas.awesomium.com/winfx"
        Title="MainWindow" 
        Height="350" 
        Width="525">
        <Grid>
            <awe:WebControl 
                Name="webControl" 
                Source="http://www.google.com"/>
        </Grid>
    </Window>
    
  • WebControlCommands: The WebControlCommands static class, exposes routed UI commands that are common to a WPF WebControl. The commands call important methods on the WPF WebControl they target. This class is an important utility when implementing a WPF UI hosting a WebControl. Future versions will allow developers to provide localization for the text of the commands. Note however that in addition to the WebControl specific routed UI commands defined in WebControlCommands, the WebControl reuses many of the ApplicationCommands and NavigationCommands available with the .NET Framework. In order to get the text of these commands displayed in your system’s locale, you may need to download a Microsoft .NET Framework 4 Client Language Pack (x86 x64). To see how to use the WebControlCommands class, read the Introducing the WebControl (WPF) article.

    Binding your UI to WebControl Commands & Properties

    <Slider 
    	DataContext="{Binding ElementName=Browser}"
    	Value="{Binding Zoom}" 	
    	Minimum="10" 
    	Maximum="400"
    	Width="120"
    	VerticalAlignment="Center"
    	AutoToolTipPlacement="TopLeft"
    	IsSnapToTickEnabled="True"
    	IsMoveToPointEnabled="True" 
    	SmallChange="1" 
    	LargeChange="10" 
    	TickFrequency="10" 
    	Focusable="False">
    	<Slider.ContextMenu>
    		<ContextMenu 
    			DataContext="{Binding PlacementTarget.DataContext, 
    			RelativeSource={RelativeSource Self}}">
    			<MenuItem 
    				Command="{x:Static awe:WebControlCommands.ResetZoom}" 
    				CommandTarget="{Binding}"/>
    		</ContextMenu>
    	</Slider.ContextMenu>
    </Slider>
  • WebControlContextMenu: The WebControlContextMenu is a predefined stylable context menu used by the WPF WebControl. Its contents are divided in arrays of context specific menu items that can easily be customized by developers. For details about how to customize or override the predefined context menu, read the Introducing the WebControl (WPF) article or the documentation of WebControlContextMenu.
  • Utilities: The Utilities static class (planned for v1.6.4), exposes methods and extensions that can be used to translate technology specific user input data to their Awesomium equivalent and copy the Awesomium pixel buffer to WPF specific bitmaps or surfaces. The class can be used to extend the functionality already provided by the WPF WebControl, or use a WebView in a WPF application (occasionally ideal in MVVM scenarios).
WPF VB.NET Application

WPF VB.NET Application

Awesomium.Windows.Forms:

Just like Awesomium.Windows.Controls, the Awesomium.Windows.Forms assembly provides Windows Forms developers with a ready to use, drag-and-drop, standalone Windows Forms control (that handles all the basic embedding tasks like mouse/keyboard input, rendering, resizing, cursors, focusing, etc.) and various utilities that can help Windows Forms developers take advantage of all Awesomium features. Here are some details of what you can find in the Awesomium.Windows.Forms assembly:

  • WebControl: Just like its WPF equivalent, the Windows Forms WebControl allows you to embed an Awesomium web-view control directly in your Windows Forms application, without any additional work. Starting with Awesomium SDK v1.6.3, the Windows Forms WebControl is also automatically added to the Visual Studio 2010 Toolbox during installation, allowing you to simply drag-and-drop the control to your container in the Visual Studio designer and automatically add all dependencies (managed and unmanaged) to your project. Performance of the Windows Forms WebControl has significantly improved and many improvements are planned in future versions, including advanced design-time support and a predefined context menu. At this point however, it is important to note that the Windows Forms WebControl is still in an experimental stage. Any feedback, is highly appreciated and you can provide it in our Support Forums.
  • Utilities: The Utilities static class, exposes methods and extensions that can be used to translate technology specific user input data to their Awesomium equivalent and copy the Awesomium pixel buffer to Windows Forms specific bitmaps or surfaces. The class can be used to extend the functionality already provided by the Windows Forms WebControl, or use a WebView in a Windows Forms application.

Installation and Redistribution:

Awesomium.NET is distributed with the Awesomium SDK, available for download in: http://www.awesomium.com/download. Here is a list of what is installed with the Windows installer and where to find it:

Awesomium.NET Assemblies:

The original Awesomium.NET assemblies and the Awesomium libraries linked to them, can be found after installation under:

%ProgramFiles%\Khrona LLC\Awesomium SDK\1.6.4\wrappers\Awesomium.NET\Assemblies
The same directory also includes the Awesomium.Mono assembly. For details about how to use the Awesomium.Mono assembly in Windows, OS X or Linux, please read: Getting Started with Awesomium.Mono.

 

In GAC:

The following assemblies are also automatically installed in GAC (Global Assembly Cache):

  • Awesomium.Core.dll
    Alongside:
    • Awesomium.Core.XML
    • Awesomium.dll
    • AwesomiumProcess
    • icudt42.dll
    • en-US.dll
  • Awesomium.Windows.Controls.dll
    Alongside:
    • Awesomium.Windows.Controls.XML
  • Awesomium.Windows.Forms.dll
    Alongside:
    • Awesomium.Windows.Forms.XML

VS Toolbox:

After installation, you should be able to find the following components in the Designer Toolbox of Visual Studio:

  • WebControl (WPF)
  • WebSourceControl (WPF)
  • WebControl (Windows Forms)

To ensure a successful installation of the Awesomium.NET components in Visual Studio’s Toolbox, Visual Studio must not be running during the installation of the Awesomium SDK. If you notice that the components are missing, you may have to uninstall and reinstall the SDK, after closing Visual Studio.

Redistribution:

To distribute the Awesomium and Awesomium.NET components used by your application, follow these steps:

  1. Expand the References folder in Solution Explorer (in VB.NET, go to the References tab of your project’s properties).
  2. Select the Awesomium.NET assemblies used by your application (usually any assembly starting with: Awesomium). Hold down CTRL and select all of them (if more than one is used). One of them, must always be: Awesomium.Core.dll: the major dependency of Awesomium.NET.
  3. In the Properties window, set Copy Local to True.
Copying Awesomium.NET references in C# & VB.NET

Copying Awesomium.NET references in C# & VB.NET

Next time you build your project, all Awesomium.NET assemblies including the necessary native Awesomium libraries, will be copied to your output directory. This is all you need to distribute your application. For more details about how to use Awesomium.NET in your applications, read: Getting Started with Awesomium.NET.

Samples:

The Windows installer of Awesomium SDK and Awesomium.NET, deploys an Awesomium.NET Samples solution under:

%MyDocuments%\Visual Studio 2010\Projects\Awesomium.NET\1.6.4\Samples

The solution includes the following samples, demonstrating uses of Awesomium.NET:

 

Core:

  1. BasicSample (C#, Console Application). This sample demonstrates how to use the core, windowless features of Awesomium. It renders a website and then saves the buffer to an image file. This sample is better explained in: Capturing Web-Pages With C# (.NET)
  2. CustomProcess (C#, Windowless Executable). This sample demonstrates how you can create a custom rendering process that can be used as the rendering processes for Awesomium, in place of the original: AwesomiumProcess. This allows you to use your own executable as a child process.

WPF:

  1. TabbedWPFSample (C#). The sample demonstrates an advanced scenario of using the WPF WebControl. It is an almost full featured web browser with tabs, much like modern browsers, which implements favicons, downloading and uploading files, using a custom rendering process etc.. A precompiled version of the sample is available when you install Awesomium SDK. See:
    Start Menu -> Awesomium v1.6.4 -> Awesomium.NET -> WPF Demo
  2. VBWPFSample (VB.NET). A WPF sample using VB.NET. The sample demonstrates how you can easily create a basic web browsing UI and bind it to an Awesomium.NET, WPF WebControl.

Windows Forms:

  1. WebControlSample (C# & VB.NET). The samples demonstrate the use of the new Windows Forms WebControl. Note that the Windows Forms WebControl is still on an experimental stage. The samples will demonstrate more detailed features in later releases of Awesomium.NET.
  2. WinFormsSample (C# & VB.NET). These are the most mature and stable samples of using Awesomium in a Windows Forms application. They use the core WebView and show you how to easily translate Windows Forms user input data to their Awesomium equivalent and how to render the Awesomium pixel buffer on a Windows Forms surface (a Form is used in the examples but it can be — and it should be actually — a child control). Many performance improvements have been applied to the samples in v1.6.3, taking advantage of new features provided by Awesomium.

Codeplex:

Our Codeplex project maintains updates to the Awesomium.NET Samples, redistributable Windows installer modules of Awesomium.NET, Utilities etc..

Licensing:

Awesomium and Awesomium.NET are free for evaluation, non-commercial use, and independent use (by companies who made less than $100K in revenue last year).

If you’re a larger company and would like to use Awesomium for commercial use, you can purchase a Pro License at https://awesomium.com/buy/

Conclusion:

You’re only a few steps from embedding the Web in your .NET application! What are you waiting for?

Additional Resources:

Last edited Jan 30, 2012 at 12:24 PM by Perikles, version 20