Introduction to Microsoft Silverlight

هذا الموضوع متوفر أيضا باللغة العربية، ومتوفر شرح فيديو أيضا، انظر هنا.

Contents

Contents of this article:

  • Contents
  • Overview
  • What is Silverlight
    • Definition
    • Platform Support
    • Rich Interactive Application
    • RIA Stats
    • Why Silverlight
    • Silverlight vs. Flash
    • Silverlight vs. WPF
    • Rich vs. Reach
    • Showcase
    • Deep Zoom
  • Deep Inside
    • Silverlight and XAML
    • Deployment Process
    • Silverlight Architecture
  • Silverlight 5
  • Tooling
    • Microsoft Visual Studio 2010
    • Microsoft Expression Studio 4
  • What’s Next
  • Demo
  • Summary

 

Overview

In this article we’ll have a brief introduction to Microsoft Silverlight, see how it fits with other technologies today, and watch it in action. Get ready!

 

What is Silverlight

Definition

Silverlight is a Microsoft technology aimed to help developers create rich interactive Web applications with the best user interface features and functionalities. It’s available as a plugin for almost all famous browsers available today, and it’s used to deliver the next generation media and Web applications.

Figure 1 - Silverlight Logo

Figure 1 - Silverlight Logo

When we say rich applications we don’t mean those with amazing interfaces and lots of graphics. Indeed, we mean by “rich” those have lots of functionalities not available for standard Web applications. Common examples of rich applications are online document editors and image processors; both are very interactive and offer lots of functionalities that are usually not available for standard Web applications. And that actually what Silverlight is devoted for, its main goal is to allow for developing rich interactive applications for the Web.

Platform Support

Unlike many other Microsoft technologies, Silverlight applications can run everywhere. It’s said to be cross-platform, cross-browser, and cross-device. It can run on Windows, Linux, and even Mac, it can run on Internet Explorer, Mozilla Firefox, Google Chrome, and many others, and it also can run on PCs, mobile devices, and handhelds. Really it can run everywhere without any code changes!

One more interesting thing is that Silverlight Web applications can be hosted on any server. You can host your Silverlight application on a Windows, Linux, or Mac server without any additional code changes or configuration.

Rich Interactive Applications

We have been talking about rich interactive applications for a while; now let’s see what a rich interactive application really means.

A Rich Interactive/Internet Application (RIA) is a Web application that’s very interactive with the user and has lots of functionalities. It’s very similar to desktop applications comparing interactivity and features; however, it’s a Web application that runs on the browser not the desktop. So we can say that RIA applications have the best functionalities and user interface features of desktop applications and Web applications.

Figure 2 - RIA

Figure 2 - RIA

Today, there’re lots of technologies available for creating RIA applications. The most famous platforms are Adobe Flash, Microsoft Silverlight, and Sun Java. Worth mentioning that every platform of the above mentioned (that includes Silverlight of course) is available through a plugin for the browser, and therefore its runtime must be installed on user’s machine in order to be able to run the application.

RIA Stats

Now someone asks: Who wins the race? What’s the best RIA platform that one can spend his time and effort to learn?

First of all, let’s have a look at the following diagrams that represent penetration rates of Adobe Flash, Microsoft Silverlight, and Sun Java. The first diagram we have comes from http://riastats.com and it shows that Adobe Flash is installed on almost 96% of internet-connected machines. Microsoft Silverlight comes in the second place with about 74% of total internet-connected machines. And Sun Java comes third with about 73% of internet-connected machines.

Figure 3 - RIA Stats

Figure 3 - RIA Stats

StatOWL shows a bit different data with more details:

Figure 4 - Stats from StatOWL

Figure 4 - Stats from StatOWL

Looking at the above diagrams we can see that Microsoft Silverlight did a great job in a very short time (first release was on 2007.) However, we can’t depend much on this data since, as you know, Microsoft Silverlight is installed automatically on Windows machines via Windows Update.

Now, let’s have a look at Microsoft Silverlight features and see what makes it the best RIA platform yet.

Why Silverlight

Other than being delivered by Microsoft, some features of Silverlight are:

  • It’s FREE.
  • It runs on all popular browsers, platforms, and devices.
  • It can be run in browser and as a desktop application.
  • Easy to create excellent UIs that looks “WOW”.
  • Enables business application development.
  • Supports 2D/3D animations/graphics.
  • Natively supports CLR and .NET Framework.
  • Can be automated using JavaScript.
  • Supports a variety of media (audio/video) formats with streaming capabilities.
  • Supports a variety of rich controls including the DataGrid.
  • Supports a variety of enterprise technologies including WCF.

In addition, Silverlight is considered to be the main development framework for Windows Phone.

Figure 5 - Windows Phone

Figure 5 - Windows Phone

Silverlight vs. Flash

Silverlight and Flash are very similar, so which is better, Silverlight or Flash? Since I’m a Microsoft developer and since you are reading now in a .NET blog, and although I haven’t ever developed for Flash, I can say that Silverlight is the best RIA platform ever!!! However, we need to be more serious.

InfoWorld did a review and compared between Silverlight and Flash, and the results were so great, Silverlight passed Flash and scored 8.3 points, while Flash got 7.8 points only.

Figure 6 - Silverlight vs. Flash, InfoWorld

Figure 6 - Silverlight vs. Flash, InfoWorld

Silverlight vs. WPF

Windows Presentation Foundation (WPF) is a graphical subsystem utilizing DirectX for rendering UI in Windows-based application, developed by Microsoft and introduced as part of Microsoft .NET Framework 3.0 and Windows Vista. WPF is considered to be the replacement for WinForms (that considered now Feature-Complete,) while WinForms relies on the older GDI subsystem, WPF relies on DirectX.

On the other hand, Silverlight is actually a subset of WPF, and formerly Silverlight was codenamed WPF/E (WPF/Everywhere) because it’s considered to be the cross-platform version of WPF. And while WPF focuses on desktop development, Silverlight focuses on Web development.

Figure 7 - Silverlight vs. WPF

Figure 7 - Silverlight vs. WPF

Rich vs. Reach

The following diagram compares some of the available Web development technologies in terms of richness (i.e. UI functionalities) and reach (platform and browser support.)

Figure 8 - Rich vs. Reach

Figure 8 - Rich vs. Reach

From the above diagram we can see that WPF has the best UI features today. However, it’s devoted primarily for desktop development, and it can run only on Windows platforms.

On the other hand, ASP.NET can run everywhere, but unfortunately it doesn’t support the UI functionalities required for today’s Web.

And finally, Silverlight has the best of UI functionalities, and it also supports a wide range of platforms and browsers (its platform/browser support is expanded each release.)

Showcase

To get a solid understanding of what Silverlight can do, check out some of the Silverlight applications from around the world:

And one of the most impressive applications is SilveOs (http://silveos.com/); a mini-operating system for the Web.

And thousands of Silverlight applications are available here too:  http://www.silverlight.net/showcase.

Deep Zoom

And another great feature of Silverlight is the DeepZoom technology that was introduced by Microsoft as part of Silverlight. DeepZoom allows you to view very large high resolution images. It reduces the time of initial load by downloading only the region being viewed at the resolution it’s displayed at. Subsequent regions are downloaded as the user pans to (or zooms into) them.

Figure 9 - Deep Zoom, Microsoft Silverlight

Figure 9 - Deep Zoom, Microsoft Silverlight

 

Deep Inside

Silverlight and XAML

Like WPF, user interface in Silverlight is declared in a specific language called Extensible Markup Language (or XAML, pronounced ‘Zammel’.) XAML is an XML-based language created by Microsoft which is used to initialize structured values and objects. XAML elements are mapped directly to CLR objects (e.g. a <Button> element maps to a Button object.)

Figure 10 - XAML Logo

Figure 10 - XAML Logo

Former ASP.NET developers are somewhat familiar with the nature of XAML. You have a WYSIWYG XAML designer that you use to design the interface of your application. The code for this interface is available through a code-behind file, where you can write in your preferred .NET language.

The concept of two files for the same page (e.g. a XAML file for the interface and a CS file for the C# code) separates two main roles in application development, design and development. The designer can work in the XAML file, and the developer can work in the code file, and both files are linked together. This also leads to a loosely-coupled design that separates user interface code from the business logic.

Figure 11 - Designer vs. Developer

Figure 11 - Designer vs. Developer

Deployment Process

What steps you would follow to deploy your Silverlight application to your users? That’s what this section is devoted for.

When you build your Silverlight application, the XAML markup, as well as the code and all other resources, is compiled into .NET assemblies which are then compressed using ZIP and stored in a XAP (.xap) file.

Figure 12 - XAP Files

Figure 12 - XAP Files

The XAP file can then be hosted in a Web server and referenced by Web pages declaring the Silverlight plugin object. And when the user navigates to the page, the XAP file is downloaded to his PC and executed on the Web page by the Silverlight runtime.

Figure 13 - Silverlight Application Deployment Process

Figure 13 - Silverlight Application Deployment Process

So all you need is just to develop your application, get the XAP file, insert the plugin into a Web page, and then publish the page and the XAP file to the Web.

Silverlight Architecture

The following illustration shows the essential architecture and components of Microsoft Silverlight. It shows how the presentation (interface) core components fit together with other .NET and Silverlight components, and what services does the provider offer.

Figure 14 - Silverlight Architecture

Figure 14 - Silverlight Architecture

 

Silverlight 5

The current stable version of Silverlight is Silverlight 4. Back to PDC 2010 the 5th version of Silverlight was introduced, it’s still in Beta but it’s supposed to be released soon.

Figure 15 - Silverlight 5 Logo

Figure 15 - Silverlight 5 Logo

Here’s a brief overview of the forthcoming Silverlight 5 features:

  • Media:
    • Hardware Video Decode
    • Better Power Management
    • Remote Control Support
  • Text and Printing:
    • Better Text Rendering
    • Full OpenType Support
  • Graphics:
    • GPU Accelerated Graphics
    • 3D Graphics Support
  • XAML:
    • XAML Debugging
  • Application Development:
    • Windows Azure Support
    • P/Invoke
  • Testing and Performance:
    • Automated UI Testing
    • Faster Startup
    • Hardware Acceleration
    • 64-bit Support

More about Silverlight 5 can be found here: http://www.microsoft.com/silverlight/future.

 

Tooling

The most common tools for Silverlight are Microsoft Visual Studio 2010 and Microsoft Expression Studio 4.

Microsoft Visual Studio 2010

Best for developers, good for designers. Check it out here: http://www.microsoft.com/visualstudio/en-us.

Figure 16 - Microsoft Visual Studio 2010

Figure 16 - Microsoft Visual Studio 2010

Microsoft Expression Studio 4

Consists of a 5 tools:

  • Microsoft Expression Blend
    Visual user interface builder for Silverlight and WPF.
  • Microsoft Expression Web
    WYSIWYG website designer and editor.
  • Microsoft Expression Design
    Raster and vector graphics editor.
  • Microsoft Expression Media
    Digital asset and media manager.
  • Microsoft Expression Encoder
    Profession media (video/audio) encoder
Figure 17 - Microsoft Expression Studio 4

Figure 17 - Microsoft Expression Studio 4

 

What’s Next

To start with Silverlight, you have to install the following components:

 

Demo

In the following example, we’ll create the Hello World application in Silverlight. Follow those steps:

First, ensure that Silverlight SDK is installed on your PC, and launch Visual Studio 2010 and select New Project.

Figure 18 - Creating a New Silverlight Application

Figure 18 - Creating a New Silverlight Application

From the New Project dialog, select your desired language from the left and select Silverlight as project type. From the middle pane, select Silverlight Application to start.

Now another dialog appears asks you to specify whether to create another Web application to host the Silverlight application or not. As you know, Silverlight applications run inside a plugin defined in a Web page, and that dialog asks if to create a new Web Application project for you to host the Silverlight application or to create just a simple HTML page to host it. Leave the dialog with no changes and ensure that you have selected Silverlight 4 from the Silverlight Version combo box and click OK to proceed.

Figure 19 - New Silverlight Application Settings

Figure 19 - New Silverlight Application Settings

Now let’s have a look at what Visual Studio has created for us. Looking at the Solution Explorer we can see that Visual Studio has created two projects, one is the Silverlight project, and the other is a Web project that’s going to host this Silverlight application.

Figure 20 - Silverlight Project in Solution Explorer

Figure 20 - Silverlight Project in Solution Explorer

Looking at the Web project we can see that VS has included two test pages in that project, the first is an ASPX page and the second is a simple HTML page, both define the Silverlight plugin and both are ready to show you your Silverlight application when you browse to them. The difference is that ASPX pages can define ASP.NET elements and code, while the simple static HTML cannot.

Back to the Silverlight application, we can see that it define 4 files:

  1. App.xaml:
    Define application-wide interface elements.
  2. App.xaml.cs (C# code file, linked to App.xaml):
    Define the startup logic and any other application-wide code.
  3. MainPage.xaml:
    The main application page; contains the interface elements.
  4. MainPage.xaml.cs (C# code file, linked to MainPage.cs):
    The business logic and code for the main application page.

Then we have two pages, the first is App.xaml that defines the application-wide elements and code (inside App.xaml.cs,) and the second is MainPage.xaml that defines the main page of your application where you can define your interface elements and code them (inside MainPage.xaml.cs.)

Now let’s design our interface. Go to MainPage.xaml and inside the <Grid> element define a Button (you can also drag the button from the Toolbox to the designer to define it):

<Button Width="100" Height="25" Content="Say Hello" Click="Button_Click" />
Figure 21 - Button in the Page

Figure 21 - Button in the Page

From the previous line of code we can see that we have defined a Button control using a <Button> element, and we have also set the control’s characteristics and properties using the element attributes. And to have our button respond to user clicks, we have wired up the Click event into the function Button_Click() that we’re going to define it in the code file.

Now go to MainPage.xaml.cs and define the Click event handler for the button:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Hello, World!");
}
Figure 22 - The Code-Behind File

Figure 22 - The Code-Behind File

Now run the application and try it.

Figure 23 - Running Silverlight Application

Figure 23 - Running Silverlight Application

Before we leave this section, let’s have a look over the plugin required for Silverlight. Go to and of the test pages on the Web project and step down until you reach the <object> element that defines the plugin. Simply, the Silverlight application requires only the following HTML code to define its plugin:

<div id="silverlightControlHost">
  <object data="data:application/x-silverlight-2,"
    type="application/x-silverlight-2" width="100%" height="100%">
      <param name="source" value="ClientBin/SilverlightApplication1.xap"/>
      ...
  </object>
  <iframe id="_sl_historyFrame"
      style="visibility:hidden;height:0px;width:0px;border:0px"></iframe>
</div>

As you see, we have references the XAP file in the page by using the source parameter. When you build your application in Visual Studio, it will create a new folder besides the test page called ClientBin and put the XAP file inside it so you can reference it in the page.

Clear, aih?

 

Summary

  • Silverlight is a cross-platform application framework for writing and running rich Internet applications (RIA.)
  • Its runtime is available as a cross-browser, cross-platform, and cross-device plug-in.
  • It’s the main development framework for Windows Phone.
  • It’s a subset of WPF so it depends on XAML for UI design.
  • You define the interface using XAML, and write the code using your preferred .NET language.
  • The XAML markup, as well as the code, is compiled into .NET assemblies and compressed into a XAP file.
  • The XAP file is then referenced by a prepared Web page and then downloaded to client’s PC when he navigates to the page.
  • Version 4 is the current stable version of Silverlight.
  • Silverlight 5 is currently in beta and it will be released soon.
  • You use Visual Studio 2010 and Microsoft Expression Studio for developing and designing your Silverlight application.
  • Microsoft Expression Studio is preferred for you if you are a designer.

 

Examples of COM Automation in Silverlight 4

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Read: Introducing COM Automation in Silverlight 4

Sample 1: TalkingApps Preview Download
Sample 2: FeaturedBlogs Preview Download
Sample 3: FileSurfer PreviewDownload

 

Contents

Contents of this article:

  • Contents
  • Introduction
  • Concepts
    • Finding COM Components
    • Accessing the COM Component
    • COM and Late Binding
  • Preparing Your Project
  • OOB Characteristics
  • Sample 1: Talking Apps
  • Sample 2: Office Automation
    • Word Automation
    • Outlook Automation
    • Excel Automation
  • Sample 3: File Surfer
  • What’s next

 

Introduction

In the previous lesson we talked about COM automation support introduced in Silverlight 4 and we said that COM automation is available only for Silverlight OOB (Out-of-Browser) applications that have Elevated Trust, and that’s one of the security restrictions imposed by Silverlight.

Today, we’re going to talk about COM automation in more details and give few Silverlight examples that make use of this great feature.

 

Concepts

Finding COM Components

COM components expose their interfaces and classes via Windows Registry. COM classes exposed to public available in this machine are registered in the Registry at HKCRCLSID (which is a repository for all COM classes registered in this machine.) Because the machine may have thousands of COM components installed, every COM class is identified with a GUID (Globally Unique Identifier.) This GUID is very long and difficult to remember (it’s something like {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}) so COM classes are using another way to identify themselves; that is the ProgID (Programmatic ID.)

ProgID for a COM class is a simple and clear string that identifies that class and represents it. For example, Microsoft Word exposes its functionalities through a COM class that you can reach it using the ProgID Word.Application. So, instead of the GUID of a class, you simply refer to it using its simple and easy-to-remember ProgID.

Then, how to find the right COM component? Or how to know if a COM component exposes a certain functionality that I need? Google it, that’s the only way! If you are looking for a COM component that does something you need just google it. And always have the COM component in your right hand, and have its documentation in the other. And don’t miss a chance to ask MSDN for help.

Accessing the COM Component

Now you have the COM component and know what to do with it. The next step is to create a new instance from the COM class using its ProgID. This is can be done using the AutomationFactory class found in the namespace System.Runtime.InteropServices.Automation (exist in System.Windows.dll.) This class exposes a few functions and only one property. The only property is IsAvailable that returns whether or not COM is supported by the operating system (COM is supported only in Windows.) Of the few functions AutomationFactory supports, we care about only CreateObject() that takes the ProgID as an input and returns the created object.

COM and Late Binding

When you assign an object to a variable that assignment can be made as early-binding or late-binding.

Early-binding is that what you make every day and all the time. By default, object assignment is made as early-binding, means that you create a variable of specific type and bind that object to that variable. Then, the compiler always knows the type of object assigned and the members (methods, properties, etc.) it supports and that allows him to do some checks, optimizations, and perform some memory allocations before application start.

In addition, early-bound variables can be thought as strongly-typed objects, means that you can check for their exposed members, use some IDE features like Intellisense and Object Explorer, and also receive compiler errors when you try to make calls to members that don’t exist (for instance.)

Late-binding on the other hand is made at runtime, means that the compiler doesn’t have enough information about the type at compile time. That means that no type checks, no method lookups or Intellisense, no verifications, no optimizations, and also no compilation errors from the late-bound object.

Is there any benefit from late-binding? Does it have anything to do with COM? Actually, it’s not as ugly as you think, it has lots of benefits and it also the core of COM automation in Silverlight (and .NET 4.0 too.)

Late-binding allows you not to embed COM types and interfaces in your .NET assembly, and that would help reduce your application size dramatically, and also protects you from versioning fails and falling in the DLL Hell.

Worth mentioning that late-binding was introduced in .NET 4.0 via the dynamic keyword and DLR (Dynamic Language Runtime) libraries. Before .NET 4.0, late-binding was supported only via reflection. Regarding Silverlight, late-binding was introduced in version 4 supporting easier COM automation and HTML DOM.

After all, to create a COM object in Silverlight you first ensure that Microsoft.CSharp.dll and Microsoft.Core.dll are referenced to your project. After that, you can call AutomationFactory.CreateObject() and assign the returned object to a dynamic variable and start coding with it.

 

Preparing Your Project

Now, let’s get to work. We’ll now prepare a Silverlight application for communication with COM components. Remember that this process requires a Silverlight 4 application running as OOB and having the elevated trust.

Start with a Silverlight project and ensure that you have selected version 4 from the New Application dialog. (The application will run as OOB, so you can safely uncheck the web application hosting option.)

Figure 1 - Creating New Silverlight Application

Figure 1 - Creating New Silverlight Application

After creating the project, open project properties and from the bottom of the Silverlight tab check the option “Enabling running application out of browser” (check figure 2.)

Figure 2 - Configuring Silverlight to run as OOB

Figure 2 - Configuring Silverlight to run as OOB

Then click Out-of-Browser Settings button and from the bottom of this dialog too check the “Require elevated trust when running” option (check figure 3.)

Figure 3 - Enabling Elevated Trust

Figure 3 - Enabling Elevated Trust

Now click OK and close project properties and save the project.

Next, add support for dynamic variables and late-binding feature to the project by referencing Microsoft.CSharp.dll (and System.Core.dll too if it’s not currently referenced) in the project.

Figure 4 - Adding Reference to Microsoft.CSharp.dll

Figure 4 - Adding Reference to Microsoft.CSharp.dll

 

OOB Characteristics

First of all, you can launch your OOB application by clicking Run or pressing F5 (figure 5.)

Figure 5 - Running OOB Application

Figure 5 - Running OOB Application

OOB applications can also run in a web page (by default, you’ll redirect the user to a web page where he can install the application to his PC.) Try browsing to TestPage.html (in Bin<debug|release>, check figure 6) or referencing the project in web application Keep in mind that COM support is not available for OOB applications running in the web.

Figure 6 - OOB Applications from the Web

Figure 6 - OOB Applications from the Web

When running OOB application from a web page the user can right click the application and chooses to install it on his machine (figure 7.) This behavior is the default, but you can disable it from the Out-of-Browser Settings dialog (check figure 3.)

Figure 7 - Installing Silverlight OOB App

Figure 7 - Installing Silverlight OOB App

When trying to install an OOB application that requires elevated trust the user may accept a security warning before the installation goes on (figure 8.)

Figure 8 - Installing Elevated Trust App

Figure 8 - Installing Elevated Trust App

You can also order the application to launch the installation process via Application.Install(), but this requires to be called in response to a user-initiated action (e.g. clicking a button.)

Another great feature of ApplicationClass is IsRunnignOutOfBrowser that returns whether the application is running OOB.

 

Sample 1: Talking Apps

Our first example is an application that makes use of the speech API and speech COM library, sapi.dll, to read a textual input from the user. The code uses the SAPI.SpVoice class that has the Speak() function that we’ll make use of.

First, design a window that has an input text box and a button to read the text. You might get help from the following XAML:


    
        
        
        
    

    

    

    

The application might look like this:

Figure 9 - The Talking App

Figure 9 - The Talking App

Now, start coding the Click event of the button:

Remember to include a using statement for System.Runtime.InteropServices.Automation.

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (!Application.Current.IsRunningOutOfBrowser)
    {
        MessageBox.Show("This application cannot be run from the browser.");
        return;
    }
    if (!AutomationFactory.IsAvailable)
    {
        MessageBox.Show("Your operating system does not support COM.");
        return;
    }

    try
    {
        using (dynamic obj = AutomationFactory.CreateObject("SAPI.SpVoice"))
        {
            obj.Speak(inputTextBox.Text);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("An error has occurred.n" + ex.Message);
    }
}

In the previous code we have checked first for whether the application is running as OOB or not (using Application.IsRunningOutOfBrowser property.) After that, we made a second check for ensuring that COM automation is supported by the operating system (i.e. the user must be working on Windows.)

Then, we have created our first COM object using AutomationFactory.CreateObject() function specifying the class ProgID which is SAPI.SpVoice. As you see, we have assigned the created object to a dynamic variable and we have also encapsulated the object in a using statement to ensure that system resources get released quickly as soon as we finish working with the object.

You can try an updated version and download it from here:

PreviewDownload

 

Sample 2: Microsoft Office Automation

We won’t dig into Microsoft Office SDK or even one of its products, we don’t have much space here, and it also requires a punch of articles in its own. Instead, we’ll have just a few examples and two samples that clear up the ambiguities of COM automation. More help can be found in the documentation of the Office programming model available in MSDN.

Word Automation

Microsoft Word exposes its programming model via COM components that you can reach its main Application object via the ProgID Word.Application. This model allows you to almost do everything programmatically from creating and opening documents to saving and printing them, even running macros and recording them is available through this model.

The following code creates a Word document and writes some text to it:

using (dynamic app = AutomationFactory.CreateObject("Word.Application"))
{
    dynamic doc = word.Documents.Add();

    dynamic par = document.Content.Paragraphs.Add();
    par.Range.Text = "Hello, World!";
    par.Range.Font.Bold = true;

    word.Visible = true;
}

More information about Word object model can be found here: http://msdn.microsoft.com/en-us/library/kw65a0we.aspx.

Outlook Automation

Like all other Microsoft Office products, Microsoft Outlook can be managed completely by the code using its programming model exposed through the ProgID Outlook.Application. The following code sends an email using Outlook (thanks to Jeff Prosise for providing the code):

using (dynamic app = AutomationFactory.CreateObject("Outlook.Application"))
{
    dynamic mail = app.CreateItem(0);
    mail.Recipients.Add("");
    mail.Subject = "Hello, World!";
    mail.Body = "Silverlight COM Automation is so cool ;)";
    mail.Save();
    mail.Send();
}

A full documentation of Outlook programming model can be found here: http://msdn.microsoft.com/en-us/library/ms268893.aspx.

Excel Automation

The following sample uses Excel automation to export some data of a DataGrid to an Excel file:

Figure 10 - The FeaturedBlogs App

Figure 10 - The FeaturedBlogs App

PreviewDownload

More about Excel programming model can be found here: http://msdn.microsoft.com/en-us/library/wss56bz7.aspx.

 

Sample 3: File Surfer

The last sample here makes use of the most powerful file managing COM component exposed through the ProgID Scripting.FileSystemObject. This class gives your application the power to do almost everything on file system even if your Silverlight application lonely (without COM support) that runs with elevated trust don’t have such those privileges (remember what we have said about COM automation? It’s the ultimate power for Silverlight.)

The next is an example of a code that creates a text file on drive C: and writes some text to it:

using (dynamic fso = AutomationFactory.CreateObject("Scripting.FileSystemObject"))
{
    string path = "C:\file.txt";

    dynamic file = fso.CreateTextFile(filePath, true);
    file.WriteLine("Hello, World!");
    file.Close();

    file = fso.OpenTextFile(filePath, 1, true);
    file.Close();
}

And the following is an application that helps you surfing the file system with no restrictions as if you were using File Explorer:

Figure 11 - The FileSurfer App

Figure 11 - The FileSurfer App

PreviewDownload

 

What’s next

You might like to check Justin Angel’s hot article about COM automation in Silverlight, lots of examples are available there.

Introducing COM Automation in Silverlight 4

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Read: Examples of COM Automation in Silverlight 4

SilverlightIn April 2010 Silverlight 4 was released to the world with one of its great features ever, COM-automation support, that allows you to create cutting-edge applications that do everything you can imagine.

What COM is

COM (Common Object Model) is a Microsoft technology introduced in 1993 and currently used by many programming languages (including C++ and VB6) for developing and building software components. Simply, you can think about COM as the counterpart for .NET assemblies in languages like C++ and VB6, .NET assemblies hold program objects and so do COM components, there’re many differences of course and one of them is that COM components are much more capable than .NET assemblies and that what makes accessing them is a great improvement to Silverlight.

Today there’s much COM components available, Microsoft Office is an example of a COM-based SDK, lots of Windows features are introduced through COM interfaces (Text-to-Speech is a good example,) and lots of 3rd party software (e.g. Adobe Reader) expose their functionalities through COM-based interfaces. Thus, you can’t leave COM automation behind if you’re willing to create cutting-edge Silverlight applications that do almost everything.

Silverlight OOB Applications

Another great improvement to Silverlight over Adobe Flash is its support for installing and running offline as a desktop application with no network presence. Those Silverlight desktop clients are described as OOB (Out-of-Browser) applications and they have been introduced in Silverlight 3 and extended their functionalities in version 4.

OOB applications are sophisticated desktop clients that can run on any platform with no such code changes required. WPF applications are much capable of course but they support only the Windows platform.

Notice that COM is a Microsoft technology that won’t run in a non-Windows machine.

Silverlight 4 and COM

Starting from version 4, you have the ability to call COM-components through your Silverlight application with a small amount of simple and clear code. But don’t expect much, you still constrained by two security restrictions:

  1. Your application needs to be running OOB.
  2. Your application must have the Elevated Trust.

Both requirements are easy as two mouse clicks; you simply set application requirements in project properties.

Programmatically, to start communicating with a COM component you make use of the AutomationFactory class found in namespace System.Runtime.InteropServices.Automation (exist in the main System.Windows.dll.) Combined the AutomationFactory class with dynamic coding (and the dynamic keyword) you can create your COM objects in Silverlight and play with it.

In the next few lessons we’ll discuss Silverlight COM automation in details and see it in action though many useful examples that will move your application to infinity. Enjoy!

 

Building Applications that Can Talk

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Overview

Stephen Hawking is one of the most famous people using speech synthesis to communicate

Stephen Hawking is one of the most famous people using speech synthesis to communicate

In this article we are going to explore the Speech API library that’s part of the TTS SDK that helps you reading text and speaking it. We’re going to see how to do it programmatically using C# and VB.NET and how to make use of LINQ to make it more interesting. The last part of this article talks about…… won’t tell you more, let’s see!

Introduction

The Speech API library that we are going to use today is represented by the file sapi.dll which’s located in %windir%System32SpeechCommon. This library is not part of the .NET BCL and it’s not even a .NET library, so we’ll use Interoperability to communicate with it (don’t worry, using Visual Studio it’s just a matter of adding a reference to the application.)

Implementation

In this example, we are going to create a Console application that reads text from the user and speaks it. To complete this example, follow these steps:

As an example, we’ll create a simple application that reads user inputs and speaks it. Follow these steps:

  1. Create a new Console application.
  2. Add a reference to the Microsoft Speech Object Library (see figure 1.)

    Figure 1 - Adding Reference to SpeechLib Library

    Figure 1 - Adding Reference to SpeechLib Library

  3. Write the following code and run your application:
// C#

using SpeechLib;

static void Main()
{
    Console.WriteLine("Enter the text to read:");
    string txt = Console.ReadLine();
    Speak(txt);
}

static void Speak(string text)
{
    SpVoice voice = new SpVoiceClass();
    voice.Speak(text, SpeechVoiceSpeakFlags.SVSFDefault);
}
' VB.NET

Imports SpeechLib

Sub Main()
    Console.WriteLine("Enter the text to read:")
    Dim txt As String = Console.ReadLine()
    Speak(txt)
End Sub

Sub Speak(ByVal text As String)
    Dim voice As New SpVoiceClass()
    voice.Speak(text, SpeechVoiceSpeakFlags.SVSFDefault)
End Sub

If you are using Visual Studio 2010 and .NET 4.0 and the application failed to run because of Interop problems, try disabling Interop Type Embedding feature from the properties on the reference SpeechLib.dll.

Building Talking Strings

Next, we’ll make small modifications to the code above to provide an easy way to speak a given System.String. We’ll make use of the Extension Methods feature of LINQ to add the Speak() method created earlier to the System.String. Try the following code:

// C#

using SpeechLib;

static void Main()
{
    Console.WriteLine("Enter the text to read:");
    string txt = Console.ReadLine();
    txt.Speak();
}

static void Speak(this string text)
{
    SpVoice voice = new SpVoiceClass();
    voice.Speak(text, SpeechVoiceSpeakFlags.SVSFDefault);
}
' VB.NET

Imports SpeechLib
Imports System.Runtime.CompilerServices

Sub Main()
    Console.WriteLine("Enter the text to read:")
    Dim txt As String = Console.ReadLine()
    txt.Speak()
End Sub

<Extension()> _
Sub Speak(ByVal text As String)
    Dim voice As New SpVoiceClass()
    voice.Speak(text, SpeechVoiceSpeakFlags.SVSFDefault)
End Sub

I Love YOU ♥

Let’s make it more interesting. We are going to code a VBScript file that says “I Love YOU” when you call it. To complete this example, these steps:

  1. Open Notepad.
  2. Write the following code:
    CreateObject("SAPI.SpVoice").Speak "I love YOU!"

    Of course, CreateObject() is used to create a new instance of an object resides in a given library. SAPI is the name of the Speech API library stored in Windows Registry. SpVoice is the class name.

  3. Save the file as ‘love.vbs’ (you can use any name you like, just preserve the vbs extension.)
  4. Now open the file and listen, who is telling that he loves you!

Microsoft Speech API has many voices; two of them are Microsoft Sam (male), the default for Windows XP and Windows 2000, and Microsoft Ann (female), the default for Windows Vista and Windows 7. Read more about Microsoft TTS voices here.

Thanks to our friend, Mohamed Gafar, for providing the VBScript.

Configuring ASP.NET with IIS

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Problem

The problem arises when you install IIS after installing ASP.NET. If you do this, IIS will configure itself for the ASP.NET version that ships with your Windows edition that might be an older version (e.g. version 2.0) and you won’t be able to run any web application built using a later version of ASP.NET.

Solution

The solution is simply to reconfigure ASP.NET for IIS. You don’t need to reinstall ASP.NET or the .NET Framework; you just need to reapply ASP.NET configuration to the IIS.

When you open the IIS Manager, you can check Application Pools and see which version of ASP.NET is currently configured. Here, we have IIS installed after ASP.NET, so the IIS is configured for version 2.0 (as you can see in figure 1.)

Figure 1 - IIS Application Pools Configuration - .NET 2.0

Figure 1 - IIS Application Pools Configuration - .NET 2.0

To solve this, we’ll get help from the aspnet_regiis.exe tool that will reconfigure IIS to the version of ASP.NET you choose. This tool is located in %windir%Microsoft.NETFrameworkv<version> (replace <version> with the version of .NET Framework you like to use.)

Let’s get this done. Open the Command Prompt in administrative mode (Start->Cmd->Ctrl+Shift+Enter) and go to the .NET Framework directory mentioned before.

Now, run the ASP.NET IIS Registration tool using the following command:

aspnet_regiis.exe -i

When the tool finishes its job, you’ll get a message inform you that everything was completed successfully.

Now go to IIS Manager again and check the Application Pools. You can now find that IIS is configured for ASP.NET 4.0 which is installed on that machine (see figure 2.)

Figure 2 - IIS Application Pools Configuration - .NET 4.0

Figure 2 - IIS Application Pools Configuration - .NET 4.0

Enjoy your day!

Consuming URL Shortening Services – 1click.at

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Read more about URL Shortening Services here.

Source- Elsheimy.Samples.ShortenSvcs.zip

Contents

Contents of this article:

  • Contents
  • Overview
  • Introduction
  • API
  • What’s next

Overview

Another article of our endless series that talks about accessing URL shortening services programmatically.

This article is talking about 1click.at shortening service, how you can use it, and how to access it via your C#/VB.NET application.

Introduction

We can’t say that 1click.at is not one of the well-known services nor it has anything special, however, as long as it provides an API we are very interested in it.

When you visit service website, http://1click.at, you can see that nothing easier from 1click.at, just push your long URL into the text box and click the shortening button.

API

1click.at provides you a very simple easy-to-use API. This API contains only one function that’s used for shortening URLs. Another good thing is that this function doesn’t require any kind of authentication for users. Therefore, you need just to send it your long URL (as you did with the website.)

The shortening function function is called http://1click.at/api.php, it accepts 3 arguments:

  1. action:
    Yet, it can accept only one value, shorturl, which orders the function to shorten the specified url.
  2. url:
    The long URL to be shortened.
  3. format:
    The format of the returned data from the function. Can be simple, xml, or json.

As you know, the .NET BCL doesn’t support JSON (some third-party components do,) and thus, we won’t cover JSON data returned from the function. Rather, we’ll concentrate on plain and XML data returned.

When the format of this function is XML, the returned data, if the function succeeded, is like the following if this is your first time you shorten this URL:

<result>
    <url>
        <keyword>GFbA1zL</keyword>
        <url>http://WithDotNet.net</url>
        <date>2010-12-17 20:14:04</date>
        <ip>0.0.0.0</ip>
    </url>
    <status>success</status>
    <message>http://WithDotNet.net added to database</message>
    <shorturl>http://1click.at/GFbA1zL</shorturl>
    <statusCode>200</statusCode>
</result>

If, however, this isn’t your first time you shorten this URL, you would get data like this:

<result>
    <status>fail</status>
    <code>error:url</code>
    <message>http://WithDotNet.net already exists in database</message>
    <shorturl>http://1click.at/GFbA1zL</shorturl>
    <statusCode>200</statusCode>
</result>

Anyway, you can retrieve the value of shorturl and forget about the rest.

Now, let’s try this function. We’ll try to shorten the URL http://WithDotNet.net with our function. First, connect the arguments, e.g. http://1click.at/api.php?action=shorturl&url=http://WithDotNet.net&format=xml. Now copy this address and paste it into your favorite browser. If everything was OK, you should see the short URL after clicking ‘Go’ in the browser toolbar.

Now, let’s do it in C# and VB.NET. Check the following function that tries to shorten long URLs via the id.gd API:

// C#

string Shorten(string url, bool xml)
{
    url = Uri.EscapeUriString(url);
    string reqUri =
String.Format("http://1click.at/api.php?action=shorturl&url={0}&format={1}",
        url, xml ? "xml" : "simple");

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(reqUri);
    req.Timeout = 10000; // 10 seconds

    // if the function fails and format==txt throws an exception
    Stream stm = req.GetResponse().GetResponseStream();

    if (xml)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(stm);

        // error checking for xml
        if (doc["result"]["statusCode"].InnerText != "200")
            throw new WebException(doc["result"]["statusCode"].InnerText);

        return doc["result"]["shorturl"].InnerText;
    }
    else // Text
        using (StreamReader reader = new StreamReader(stm))
            return reader.ReadLine();
}
' VB.NET

Private Function Shorten(url As String, xml As Boolean) As String
	url = Uri.EscapeUriString(url)
	Dim reqUri As String = "http://1click.at/api.php?action=shorturl&url={0}&format={1}"
	If (xml) Then
		reqUri = String.Format(reqUri, url, "xml")
	Else
		reqUri = String.Format(reqUri, url, "simple")
	End If

	Dim req As HttpWebRequest = DirectCast(WebRequest.Create(reqUri), HttpWebRequest)
	req.Timeout = 5000
	Dim stm As Stream = req.GetResponse().GetResponseStream()

	If xml Then
		Dim doc As New XmlDocument()
		doc.Load(stm)

		' error checking for xml
		If doc("result")("statusCode").InnerText <> "200" Then
			Throw New WebException(doc("result")("statusCode").InnerText)
		End If

		Return doc("result")("shorturl").InnerText
	Else
		' Simple
		Using reader As New StreamReader(stm)
			Return reader.ReadLine()
		End Using
	End If
End Function

Notice that we have used the function System.Net.Uri.EscapeUriString() to eliminate unacceptable characters from the URL by encoding them.

Notice too that we have included our code in a Try-Catch block so we can catch exceptions before they blow up our application.

What’s next

Consider reading other articles in this series here.

.NET Interoperability at a Glance 3 – Unmanaged Code Interoperation

هذه المقالة متوفرة باللغة العربية أيضا، اقرأها هنا.

See more Interoperability examples here.

Contents

Contents of this article:

  • Contents
  • Read also
  • Overview
  • Unmanaged Code Interop
  • Interop with Native Libraries
  • Interop with COM Components
  • Interop with ActiveX Controls
  • Summary
  • Where to go next

Read also

More from this series:

Overview

This is the last article in this series, it talks about unmanaged code interoperation; that’s, interop between .NET code and other code from other technologies (like Windows API, native libraries, COM, ActiveX, etc.)

Be prepared!

Introduction

Managed code interop wasn’t so interesting, so it’s the time for some fun. You might want to call some Win32 API functions, or it might be interesting if you make use of old, but useful, COM components. Let’s start!

Unmanaged Code Interop

Managed code interoperation isn’t so interesting, but this is. Unmanaged interoperation is not easy as the managed interop, and it’s also much difficult and much harder to implement. In unmanaged code interoperation, the first system is the .NET code; the other system might be any other technology including Win32 API, COM, ActiveX, etc. Simply, unmanaged interop can be seen in three major forms:

  1. Interoperation with Native Libraries.
  2. Interoperation with COM components.
  3. Interoperation with ActiveX.

Interop with Native Libraries

This is the most famous form of .NET interop with unmanaged code. We usually call this technique, Platform Invocation, or simply PInvoke. Platform Invocation or PInvoke refers to the technique used to call functions of native unmanaged libraries such as the Windows API.

To PInvoke a function, you must declare it in your .NET code. That declaration is called the Managed Signature. To complete the managed signature, you need to know the following information about the function:

  1. The library file which the function resides in.
  2. Function name.
  3. Return type of the function.
  4. Input parameters.
  5. Other relevant information such as encoding.

Here comes a question, how could we handle types in unmanaged code that aren’t available in .NET (e.g. BOOL, LPCTSTR, etc.)?

The solution is in Marshaling. Marshaling is the process of converting unmanaged types into managed and vice versa (see figure 1.) That conversion can be done in many ways based on the type to be converted. For example, BOOL can simply be converted to System.Boolean, and LPCTSTR can be converted to System.String, System.Text.StringBuilder, or even System.Char[]. Compound types (like structures and unions) are usually don’t have counterparts in .NET code and thus you need to create them manually. Read our book about marshaling here.

Figure 1 - The Marshaling Process
Figure 1 – The Marshaling Process

To understand P/Invoke very well, we’ll take an example. The following code switches between mouse button functions, making the right button acts as the primary key, while making the left button acts as the secondary key.

In this code, we’ll use the SwapMouseButtons() function of the Win32 API which resides in user32.dll library and has the following declaration:

BOOL SwapMouseButton(
    BOOL fSwap
    );

Of course, the first thing is to create the managed signature (the PInvoke method) of the function in .NET:

// C#
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SwapMouseButton(bool fSwap);
' VB.NET
Declare Auto Function SwapMouseButton Lib "user32.dll" _
    (ByVal fSwap As Boolean) As Boolean

Then we can call it:

// C#

public void MakeRightButtonPrimary()
{
    SwapMouseButton(true);
}

public void MakeLeftButtonPrimary()
{
    SwapMouseButton(false);
}
' VB.NET

Public Sub MakeRightButtonPrimary()
    SwapMouseButton(True)
End Sub

Public Sub MakeLeftButtonPrimary()
    SwapMouseButton(False)
End Sub

Interop with COM Components

The other form of unmanaged interoperation is the COM Interop. COM Interop is very large and much harder than P/Invoke and it has many ways to implement. For the sake of our discussion (this is just a sneak look at the technique,) we’ll take a very simple example.

COM Interop includes all COM-related technologies such as OLE, COM+, ActiveX, etc.

Of course, you can’t talk directly to unmanaged code. As you’ve seen in Platform Invocation, you have to declare your functions and types in your .NET code. How can you do this? Actually, Visual Studio helps you almost with everything so that you simply to include a COM-component in your .NET application, you go to the COM tab of the Add Reference dialog (figure 2) and select the COM component that you wish to add to your project, and you’re ready to use it!

Figure 2 - Adding Reference to SpeechLib Library
Figure 2 – Adding Reference to SpeechLib Library

When you add a COM-component to your .NET application, Visual Studio automatically declares all functions and types in that library for you. How? It creates a Proxy library (i.e. assembly) that contains the managed signatures of the unmanaged types and functions of the COM component and adds it to your .NET application.

The proxy acts as an intermediary layer between your .NET assembly and the COM-component. Therefore, your code actually calls the managed signatures in the proxy library that forwards your calls to the COM-component and returns back the results.

Keep in mind that proxy libraries also called Primary Interop Assemblies (PIAs) and Runtime Callable Wrappers (RCWs.)

Best mentioning that Visual Studio 2010 (or technically, .NET 4.0) has lots of improved features for interop. For example, now you don’t have to ship a proxy/PIA/RCW assembly along with your executable since the information in this assembly can now be embedded into your executable; this is what called, Interop Type Embedding.

Of course, you can create your managed signatures manually, however, it’s not recommended especially if you don’t have enough knowledge of the underlying technology and the marshaling of functions and types (you know what’s being said about COM!)

As an example, we’ll create a simple application that reads user inputs and speaks it. Follow these steps:

  1. Create a new Console application.
  2. Add a reference to the Microsoft Speech Object Library (see figure 2.)
  3. Write the following code and run your application:
// C#

using SpeechLib;

static void Main()
{
    Console.WriteLine("Enter the text to read:");
    string txt = Console.ReadLine();
    Speak(txt);
}

static void Speak(string text)
{
    SpVoice voice = new SpVoiceClass();
    voice.Speak(text, SpeechVoiceSpeakFlags.SVSFDefault);
}
' VB.NET

Imports SpeechLib

Sub Main()
    Console.WriteLine("Enter the text to read:")
    Dim txt As String = Console.ReadLine()
    Speak(txt)
End Sub

Sub Speak(ByVal text As String)
    Dim voice As New SpVoiceClass()
    voice.Speak(text, SpeechVoiceSpeakFlags.SVSFDefault)
End Sub

If you are using Visual Studio 2010 and .NET 4.0 and the application failed to run because of Interop problems, try disabling Interop Type Embedding feature from the properties on the reference SpeechLib.dll.

Interop with ActiveX Controls

ActiveX is no more than a COM component that has an interface. Therefore, nearly all what we have said about COM components in the last section can be applied here except the way we add ActiveX components to our .NET applications.

To add an ActiveX control to your .NET application, you can right-click the Toolbox, select Choose Toolbox Items, switch to the COM Components tab and select the controls that you wish to use in your application (see figure 3.)

Figure 3 - Adding WMP Control to the Toolbox
Figure 3 – Adding WMP Control to the Toolbox

Another way is to use the aximp.exe tool provided by the .NET Framework (located in Program FilesMicrosoft SDKsWindowsv7.0Abin) to create the proxy assembly for the ActiveX component:

aximp.exe "C:WindowsSystem32wmp.dll"

Not surprisingly, you can create the proxy using the way for COM components discussed in the previous section, however, you won’t see any control that can be added to your form! That way creates control class wrappers for unmanaged ActiveX controls in that component.

Summary

So, unmanaged code interoperation comes in two forms: 1) PInvoke: interop with native libraries including the Windows API 2) COM-interop which includes all COM-related technologies like COM+, OLE, and ActiveX.

To PInvoke a method, you must declare it in your .NET code. The declaration must include 1) the library which the function resides in 2) the return type of the function 3) function arguments.

COM-interop also need function and type declaration and that’s usually done for you by the Visual Studio which creates a proxy (also called RCW and PIA) assembly that contains managed definitions of the unmanaged functions and types and adds it to your project.

Where to go next

Read more about Interoperability here.

More from this series:

.NET Interoperability at a Glance 2 – Managed Code Interoperation

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

See more Interoperability examples here.

Contents

Contents of this article:

  • Contents
  • Read also
  • Overview
  • Introduction
  • Forms of Interop
  • Managed Code Interop
  • Summary
  • Where to go next

Read also

More from this series:

Overview

In the previous article, you learnt what interoperability is and how it relates to the .NET Framework. In this article, we’re going to talk about the first form of interoperability, the Managed Code Interop. In the next article, we’ll talk about the other forms.

Introduction

So, to understand Interoperation well in the .NET Framework, you must see it in action. In this article, we’ll talk about the first form of .NET interoperability and see how to implement it using the available tools.

Just a reminder, Interoperability is the process of communication between two separate systems. In .NET Interop, the first system is always the .NET Framework; the other system might be any other technology.

Forms of Interop

Interoperability in .NET Framework has two forms:

  • Managed Code Interoperability
  • Unmanaged Code Interoperability

Next, we have a short discussion of each of the forms.

Managed Code Interop

This was one of the main goals of .NET Framework. Managed Code Interoperability means that you can easily communicate with any other .NET assembly no matter what language used to build that assembly.

Not surprisingly, because of the nature of .NET Framework and its runtime engine (the CLR,) .NET code supposed to be called Managed Code, while any other code is  unmanaged.

To see this in action, let’s try this:

  1. Create a new Console application in the language you like (C#/VB.NET.)
  2. Add a new Class Library project to the solution and choose another language other than the one used in the first project.
  3. In the Class Library project, add the following code (choose the suitable project):
    // C#
    
    public static class Hello
    {
        public static string SayHello(string name)
        {
            return "Hello, " + name;
        }
    }
    ' VB.NET
    
    Public Module Hello
        Public Function SayHello(ByVal name As String) As String
            Return "Hello, " & name
        End Function
    End Module
  4. Now, go back to the Console application. Our goal is to call the function we have added to the other project. To do this, you must first add a reference to the library in the first project. Right-click the Console project in Solution Explorer and choose Add Reference to open the Add Reference dialog (figure 1.) Go to the Projects tab and select the class library project to add it.

    Figure 1 - Add Reference to a friend project

    Figure 1 - Add Reference to a friend project

  5. Now you can add the following code to the Console application to call the SayHello() function of the class library.
    // C#
    
    static void Main()
    {
        Console.WriteLine(ClassLibrary1.Hello.SayHello("Mohammad Elsheimy"));
    }
    ' VB.NET
    
    Sub Main()
        Console.WriteLine(ClassLibrary1.Hello.SayHello("Mohammad Elsheimy"))
    End Sub

How this happened? How could we use the VB.NET module in C# which is not available there (or the C#’s static class in VB which is not available there too)?

Not just that, but you can inherit C# classes from VB.NET (and vice versa) and do all you like as if both were created using the same language. The secret behind this is the Common Intermediate Language (CIL.)

When you compile your project, the compiler actually doesn’t convert your C#/VB.NET code to instructions in the Machine language. Rather, it converts your code to another language of the .NET Framework, which is the Common Intermediate Language. The Common Intermediate Language, or simply CIL, is the main language of .NET Framework which inherits all the functionalities of the framework, and which all other .NET languages when compiled are converted to it.

So, the CIL fits as a middle layer between your .NET language and the machine language. When you compile your project, the compiler converts your code to CIL statements and emits them in assembly file. In runtime, the compiler reads the CIL from the assembly and converts them to machine-readable statements.

How CIL helps in interoperation? The communication between .NET assemblies is now done through the CIL of the assemblies. Therefore, you don’t need to be aware of structures and statements that are not available in your language since every statement for any .NET language has a counterpart in IL. For example, both the C# static class and VB.NET module convert to CIL static abstract class (see figure 2.)

Figure 2 - CIL and other .NET languages

Figure 2 - CIL and other .NET languages

Managed Interop is not restricted to C# and VB.NET only; it’s about all languages run inside the CLR (i.e. based on .NET Framework.)

If we have a sneak look at the CIL generated from the Hello class which is nearly the same from both VB.NET and C#, we would see the following code:

.class public abstract auto ansi sealed beforefieldinit ClassLibrary1.Hello
       extends [mscorlib]System.Object
{

    .method public hidebysig static string  SayHello(string name) cil managed
    {
      // Code size       12 (0xc)
      .maxstack  8
      IL_0000:  ldstr      "Hello, "
      IL_0005:  ldarg.0
      IL_0006:  call       string [mscorlib]System.String::Concat(string,
                                                              string)
      IL_000b:  ret
    } // end of method Hello::SayHello

} // end of class ClassLibrary1.Hello

On the other hand, this is the code generated from the Main function (which is also the same from VB.NET/C#):

.class public abstract auto ansi sealed beforefieldinit ConsoleApplication1.Program
       extends [mscorlib]System.Object
{

    .method private hidebysig static void  Main() cil managed
    {
      .entrypoint
      .maxstack  8
      IL_0000:  ldstr      "Mohammad Elsheimy"
      IL_0005:  call       string [ClassLibrary1]ClassLibrary1.Hello::SayHello(string)
      IL_000a:  call       void [mscorlib]System.Console::WriteLine(string)
      IL_000f:  ret
    } // end of method Program::Main

} // end of class ConsoleApplication1.Program

You can use the ILDasm.exe tool to get the CIL code of an assembly. This tool is located in Program FilesMicrosoft SDKsWindows<version>bin.

Here comes a question, is there CIL developers? Could we write the CIL directly and build it into .NET assembly? Why we can’t find much (if not any) CIL developers? You can extract the answer from the CIL code itself. As you see, CIL is not so friendly and its statements are not so clear. Plus, if we could use common languages to generate the CIL, we we’d like to program in CIL directly? So it’s better to leave the CIL for the compiler.

Now, let’s see the other form of .NET interoperation, Unmanaged Code Interoperability.

Summary

So, the secret of Managed Code Interoperation falls in the Common Intermediate Language or CIL. When you compile your code, the compiler converts your C#/VB.NET (or any other .NET language) to CIL instructions and saves them in the assembly, and that’s the secret. The linking between .NET assemblies of different languages relies on the fact that the linking is actually done between CILs of the assemblies. The assembly code doesn’t (usually) have any clue about the language used to develop it. In the runtime, the compiler reads those instructions and converts them to machine instructions and execute them.

Next, we’ll talk about the other form of .NET Interoperation, it’s the interoperation with unmanaged code.

Where to go next

Read more about Interoperability here.

More from this series:

.NET Interoperability at a Glance 1 – Introduction

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

See more Interoperability examples here.

Contents

Contents of this article:

  • Contents
  • Read also
  • Overview
  • Introduction
  • Summary
  • Where to go next

Read also

More from this series:

Overview

.Net Framework Logo
Image via Wikipedia

In this article and the few following it, we’ll try to take a tour in Interoperability in .NET Framework.

In this lesson, we’ll start by an introduction to the concept of Interoperability. In the next few lessons, we’ll have a look at Interoperability and how it fits into the .NET Framework and other technologies.

Since Interoperability is a very huge topic and cannot be covered in just a few articles, we’ll concentrate on Interoperability in .NET Framework (not any other technologies) and summarize its uses.

Here we go!

Introduction

Let’s get hands on the concept of Interoperability and it’s relation to the .NET Framework.

Concept

Interoperability (reduced to Interop) is the ability of two diverse systems or different systems to communicate (i.e. inter-operate) with each other. When I say ‘two systems’ I assume that the first one is always the .NET Framework, since we are interested in .NET and also the interoperability is a very huge topic and cannot be summarized in just a few articles. The other system might be any other software, component, or service based on any technology other than the .NET Framework. For example, we could interoperate with Win32 API, MFC applications, COM/ActiveX components, and so on.

So we have two different systems, the first is the .NET Framework, while the other is any other technology. Our goal is to communicate with that stranger; that’s the main goal of Interoperability in .NET Framework.

Goals and Benefits

Here comes a question (or a few questions!), why do I need interoperation? Why I do need to communicate with other systems at all? If I need specific features, couldn’t I just use existing functionalities of .NET Framework to accomplish my tasks? I can even redevelop them!

We can summarize the answer of those questions in a few points:

  • First, in many cases, you can’t redevelop those components because the functionalities they offer is either very difficult (sometimes impossible) or maybe you don’t sufficient knowledge to redevelop them! Unless if you are very brilliant and have enough knowledge of the Assembly language, you can develop your API that would replace current system API, and then you’ll have also to interoperate with your API to be able to call it from your .NET Framework application.
  • If you’re not convinced yet, this is should be for you. You might be not having enough time to redevelop the component that may take a very long time and effort to complete. Imagine how much time would take to code, debug, and test your component. Plus, you can rely on existing components and trust them, many bugs can appear in your code from time to time and you’ll have to fix them all!
  • Other 3rd party component might not exist, or maybe the company you work for require you to use such those components.
  • You don’t need to reinvent the wheel, do you?

So, including Interop code in your .NET projects is sometimes inevitable (especially when working with Windows API) that you definitely can’t keep yourself away from them.

Summary

So you have now basic understanding of what Interoperability means. As a reminder, Interoperability is the process of two diverse systems communicate with each other. For us, the first system is the .NET Framework. The other system is any other technology (Windows API, MFC, COM/ActiveX, etc.)

You can’t live without Interop, actually you did some interoperation in your work (you may be actually do that every day.)

Now you are ready to take a look at how Interop fits in .NET Framework.

Where to go next

Read more about Interoperability here.

More from this series: