Wednesday, 17 January 2018

Object Recognition using Microsoft CNTK

Lately I've been working on some advanced object recognition scenarios. I was looking for appropriate tools to do the job. Obviously I thought about using some kind of deep learning solution, but I was afraid of its complexity. I'm not a data scientist and have a very limited knowledge of neural networks. I needed a tool, which I could use as a black box: feed some data into it and then consume the result, without even understanding what's going on under the hood.

I was advised by domain experts to check out the Microsoft Cognitive Toolkit (CNTK). The big advantage of CNTK is rich documentation and end-2-end examples available. In my scenario (Object Recognition) I found following resources particularly useful:

  • Object Detection using CNTK

    This tutorial was my entry point. You will find there exact, step-by-step instructions on how to build an object recognition solution together with sample data sets. It also provides some scientific background for those who want to learn how this works.

  • End-2-end solution

    This one bases on the original tutorial from the first link. However, it takes it further by introducing the complete E2E solution, including:

    • managing reference pictures
    • building repository for metadata
    • training the object recognition model
    • managing training results
    • Advanced reporting based on PowerBI
    • Publishing the CNTK model as a web service, so recognition results can be easily consumed.

  • Upgrade to Faster R-CNN

    First 2 tutorials are using an algorithm called Fast R-CNN. It is good, but CNTK released also its improved version called Faster R-CNN. This tutorial provides scripts that utilize that improved algorithm. Because it bases on the same sample dataset, you can simply compare results from both tutorials. From my experience, Faster R-CNN is not actually quicker, but it provides better recognition rates.

After going through these 3 you should be able to build an object recognition solution on your own, without having any data-science background.

Wednesday, 19 October 2016

Force Service Fabric application delete

Usually you can easily delete an application from your Service Fabric cluster using the cluster explorer. However, there are times when this doesn't work - this may happen if one of services breaks and it can't heal itself.
In such situation you can use following PowerShell script to force the delete operation:
Connect-ServiceFabricCluster -ConnectionEndpoint <your-cluster-connection-endpoint>
$nodes = Get-ServiceFabricNode
foreach($node in $nodes)
{
    $replicas = Get-ServiceFabricDeployedReplica -NodeName $node.NodeName -ApplicationName "fabric:/Your-App"
    foreach ($replica in $replicas)
    {
        Remove-ServiceFabricReplica -ForceRemove -NodeName $node.NodeName -PartitionId $replica.Partitionid -ReplicaOrInstanceId $replica.ReplicaOrInstanceId
    }
}

Monday, 28 September 2015

VSO Build vNext – versioning assemblies with MSBuild

In this blog post I will show you how to version assemblies during the Visual Studio Online vNext build.

Why to version assemblies?

Versioning assemblies will help you to detect, which library version has been deployed to your environment. You can obviously do it manually for each of your projects, but it can be a mundane and error prone task. Instead, I’ll show you how to easily automate the process.

In result, each project library will be automatically versioned. The version number format will follow the recommended standard:

[Major version[.Minor version[.Build Number[.Revision]]]]

How to version assemblies?

By default the assembly version is defined in the AssemblyInfo.cs class, which can be found in the Properties folder.
[assembly: AssemblyVersion("1.0.0.0")]
If you have many projects it’s much easier to have a single file with all common assembly information shared by all projects. This way you will only need to update the property once and it will be picked up by all projects.

To do that create a separate file called CommonAssemblyInfo.cs and place it the solution’s root folder. Move the AssemblyVersion definition to that file. Then, link the file from all projects:

  1. Right click project
  2. Add Existing…
  3. Select the created CommonAssemblyInfo.cs
  4. Click small arrow next to the Add button
  5. Select Add as Link
  6. Drag the linked file to the Properties folder.
The result should look like this:
Obviously you can move more common properties to the CommonAssemblyInfo file e.g. AssemblyCompany, AssemblyCopyright etc.

Automate versioning

Now that we store the assembly version in a single file we can easily automate the versioning process. The idea is that before executing the actual build we will run another MSBuild script that updates the version in the Common file. The script will be using the AssemblyInfo target task from the MSBuild Community tasks.

The script takes 2 parameteres: BuildId & Revision:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <!-- path to MSBuild community tasks --> 
    <MSBuildCommunityTasksPath>.</MSBuildCommunityTasksPath> 
  </PropertyGroup>
  <Import Project=".\tasks\MSBuild.Community.Tasks.Targets"/>
  <Target Name="UpdateAssemblyInfo">
    <Message Text="Updating Assembly versions with Build Id $(BuildId) and Revision $(Revision)"></Message>
    <!-- update assembly and file versions in C-Sharp CommonAssemblyInfo  --> 
    <AssemblyInfo OutputFile="..\CommonAssemblyInfo.cs"
                     CodeLanguage="CS"
                     AssemblyVersion="1.0.$(BuildId).$(Revision.Replace('C',''))"
                     AssemblyFileVersion="1.0.$(BuildId).$(Revision.Replace('C',''))" >                  
    </AssemblyInfo>
  </Target>
</Project>
The script must be added to your source together with community tasks files, so you can reference it in your VSO build definition.

VSO Build definition

Now that we have all components it’s time to define the VSO build. The first step would be execution of our custom build task:
As you can see we use 2 environment variables here:
  • $(Build.BuildId) – id of the build
  • $(Build.SourceVersion) - The latest version control change set that is included in this build .If you are using TFS it will have the format “C1234”, so you need to remove the “C” prefix (see our build script above)
Then, we can use the regular MSBuild step to build the solution. All assemblies that have the CommonassemblyInfo.cs file linked should have the correct version number set. Now you can add more steps to the build definition: running unit tests, publishing artifacts, etc.

Alternative approach

You can also achieve the same functionality using PowerShell instead of MSBuild. There is a good example here. Which one you choose is up to your personal preference – I prefer my solution, as it requires less code.

Tuesday, 4 November 2014

SharePoint 2013 sticky footer

Adding a footer to SharePoint masterpage may be a bit tricky, since SharePoint automatically recalculates height and scrolling properties of some default div containers on page load. Today I will show how to add a so called "sticky footer" to a SharePoint masterpage using Javascript. The sticky footer will be displayed always at the bottom of the page, even if there is little content. We will base on the SharePoint 2013 "Seattle" masterpage.

Masterpage structure changes

First we need to add a footer container (div) to our masterpage, that will contain the footer content. We add this at the end of the default "s4-workspace" div, right after the "s4-bodyContainer" div:
<div id="s4-workspace" class="ms-core-overlay">
    <div id="s4-bodyContainer">
    (...)
    </div>
    <div id="footer">Your footer content goes here</div>
</div>
Now you need to populate your footer with content and set its CSS properties e.g. height.

Javascript code

Now that we have our footer container let's position it with some javascript code:
// generic function for resizing elements within their containers
function adjustContainerHeightToObject(container, content, offset){
 var container = $(container);
 var content = $(content, container);
 if (container.height() > content.height()) {
  content.height(container.height() + offset);
 }
}

// specific function for resizing the s4-body container
function resizeMainContent(){
    // as offset we provide the negative value of the height of our footer
    adjustContainerHeightToObject('#s4-workspace', '#s4-bodyContainer', -50); // for footer with 50px height
}

// call resize function on page load
_spBodyOnLoadFunctionNames.push("resizeMainContent");

_spBodyOnLoadFunctionNames.push() vs. $(document).ready()

Notice that instead of using regular jQuery ready() event we are using SharePoint's custom mechanism for calling function after the page loads. This will ensure that all SharePoint resizing code has already executed when calling our function.

Wednesday, 13 August 2014

SSIS Error: The requested OLE DB provider Microsoft.Jet.OLEDB.4.0 is not registered. If the 64-bit driver is not installed, run the package in 32-bit mode.

I have a SSIS solution that reads from an Excel file. I recently deployed it to a different server and tried executing it from Visual Studio. I got the following error:

[Excel Source [2]] Error: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "Excel Connection Manager" failed with error code 0xC0209303. There may be error messages posted before this with more information on why the AcquireConnection method call failed.

[Connection manager "Excel Connection Manager"] Error: The requested OLE DB provider Microsoft.Jet.OLEDB.4.0 is not registered. If the 64-bit driver is not installed, run the package in 32-bit mode. Error code: 0x00000000. An OLE DB record is available. Source: "Microsoft OLE DB Service Components" Hresult: 0x80040154 Description: "Class not registered".

Solution

As the error message suggests you need to run the package in the 32-bit mode. To do that:
  1. Right-click your solution
  2. Click 'Properties'
  3. Select 'Debugging' node
  4. Set 'Run64BitRuntime' property to False
  5. Save and re-run your solution

Tuesday, 22 April 2014

SSIS integration with Dynamics CRM using ExecuteMultipleRequest for bulk operations

There are several tutorials on the Web explaining how to integrate SSIS with Dynamics CRM using the script component. All of them however show you only the basic setup, where records from a data source are processed 1 by 1 when executing CRM commands (e.g. creating CRM records). In this post I would like to show you have to leverage the ExecuteMultipleRequest class from CRM SDK to create bulk operations for records from the SSIS data source.

Tutorial scenario

  1. At first we will create a simple database with 1 table that stores user names
  2. Then we will create an SSIS project
  3. Next, we will add our db table as data source, so SSIS can read information about users
  4. Then, we will add a script component that creates contacts in CRM for each user from the table
  5. Finally, we will modify the script to import CRM contacts in batches
  6. At the end we will compare execution time of both scripts

Basic setup

Database
Let's create a basic db table with only 2 columns:
CREATE TABLE Users (
 FirstName VARCHAR(100) NOT NULL,
 LastName VARCHAR(100) NOT NULL
 )
Now populate your table with some dummy data, in my case I've added 1000 records.

SSIS project
  1. Open "Sql Server Data Tools" (based on Visual Studio 2010)
  2. Got to File -> New -> Project...
  3. Select "Integration Services Project", provide project name and click OK
  4. When the project is created add a Data Flow task to your main package:
Data Source
  1. Double click your Dat Flow task to open it
  2. Double click "Source Assitance" from the toolbox
  3. On the first screen of the wizard select "SQL Server" as source type and select "New..."
  4. On second screen provide you SQL server name and authentication details and select your database
  5. A new block will be added to you Data Flow, representing your DB table. It has an error icon on, cause we haven't selected the table yet. Also, you will see a new connection manager representing you DB connection:
  6. Double click the new block, from the dropdown select the Contacts table we created and hit OK. The error icon should disappear
Script component
  1. Drag and drop the Script Component from the toolbox to you Data Flow area
  2. Create a connection (arrow) from your data source to your script:
  3. Double click your script componet to open it
  4. Go to "Input Columns" tab and select all columns
  5. Go to "Inputs and Outputs" tab and rename "Input 0" to "ContactInput"

1-by-1 import

Now that we have basic components setup let's write some code! In this step we will create a basic code for importing Contacts into CRM. I'm assuming you have basic knowledge of CRM SDK, therefore the CRM specific code will not be explained in details.

Open the script component created in the previous steps and click "Edit Script...". A new instance of Visual Studio will open with a new, auto-generated script project. By default the main.cs file will be opened - this is the only file you need to modify. However, before modyfing the code you need to add references to following libraries:

  • Microsoft.Sdk.Crm.Proxy
  • Microsoft.Xrm.Client
  • Microsoft.Xrm.Sdk
  • Microsoft.Runtime.Serialization
Now we are ready to write the code. Let's start by creating a connection to you CRM organization. This will be created in the existing PreExecute() method like this:
OrganizationService _service;

public override void PreExecute()
{
    base.PreExecute();
        
    var crmConnection = CrmConnection.Parse(@"Url=https://******.crm4.dynamics.com; Username=******.onmicrosoft.com; Password=*********;");
    _service = new OrganizationService(crmConnection);
}
Now that we have the connection created let's write code, that actually imports our contacts to CRM. This can be done be modyfing the existing method ContactInput_ProcessInputRow:
public override void ContactInput_ProcessInputRow(ContactInputBuffer Row)
{
    var contact = new Entity("contact");
    contact["firstname"] = Row.FirstName;
    contact["lastname"] = Row.LastName;
    _service.Create(contact);
}
Obviously the code above requires some null-checks, error handling etc but in general that's all you need to do in order to import your contacts into CRM. If you close the VS instance with the script project it will be automatically saved and built.

You can now hit F5 in the original VS window to perform the actual migration.

Bulk import

In the basic setup described above there is 1 CRM call for each record passed to the script component. Calling web services over the network may be a very time consuming operation. CRM team is aware of that and that is why they introduced the ExecuteMultipleRequest class, which basically allows you to create a set of CRM requests on the client side and send them all at once in a single web service call. In response you will receive an instance of the RetrieveMultipleResponse class, allowing you to process response for each single request.

Let's modify the script code to leverage the power of the ExecuteMultipleRequest class. To do that overwrite the ContactInput_ProcessInput method. The default method implementation can be found in the ComponentWrapper.cs file and it as simple as this:

 public virtual void ContactInput_ProcessInput(ContactInputBuffer Buffer)
{
     while (Buffer.NextRow())
     {
        ContactInput_ProcessInputRow(Buffer);
     }
}
As you can see by default it calls the ContactInput_ProcessInputRow method that we implemented in the previous step for each record from the source. We need to modify it, so it creates a batch of CRM requests and then send it to CRM at once:
List<Entity> _contacts = new List<Entity>();

public override void ContactInput_ProcessInput(ContactInputBuffer Buffer)
{
    int index = 0;
    while (Buffer.NextRow())
    {
        _contacts.Add(GetContactFromBuffer(Buffer));
        index++;

        // Let's use buffer size 500. CRM allows up to 1000 requests per single call
        if (index == 500)
        {
            ImportBatch();
            index = 0;
        }
    }
    ImportBatch();
}

private void ImportBatch()
{
    if (_contacts.Count > 0)
    {
        // Create and configure multiple requests operation
        var multipleRequest = new ExecuteMultipleRequest()
        {
            Settings = new ExecuteMultipleSettings()
            {
                ContinueOnError = true, // Continue, if processing of a single request fails
                ReturnResponses = true // Return responses so you can get processing results
            },
            Requests = new OrganizationRequestCollection()
        };

        // Build a CreateRequest for each record
        foreach (var contact in _contacts)
        {
            CreateRequest reqCreate = new CreateRequest();
            reqCreate.Target = contact;
            reqCreate.Parameters.Add("SuppressDuplicateDetection", false); // Enable duplicate detection 
            multipleRequest.Requests.Add(reqCreate);
        }

        ExecuteMultipleResponse multipleResponses = (ExecuteMultipleResponse)_service.Execute(multipleRequest);            

        // TODO: process responses for each record if required e.g. to save record id

        _contacts.Clear();
    }
}

private Entity GetContactFromBuffer(ContactInputBuffer Row)
{
    Entity contact = new Entity("contact");
    contact["firstname"] = Row.FirstName;
    contact["lastname"] = Row.LastName;
    return contact;
}

Execution time comparison

As you can see the code for sending requests in batches is a bit longer (but still quite simple I believe) so you may be tempted to go with the simpler version. If you don't care about performance too much (little data, no time limitations) then it might be the way to go for you. However, it's always better to know your options and take a conscious decision. SSIS packages usually process large amount of data, which often takes a lot of time. If you add additional step performing CRM operations via CRM SDK (i.e. via CRM web services) you may be sure this will affect significantly the execution time.

I've measured the execution time for both methods. Importing 1000 contacts into CRM took:

  • 1-by-1 - 2:22s
  • Bulk import - 0:44s
In my simple scenario bulk import was 3x faster than 1-by-1. The more data you send to CRM the bigger the difference may be.

Thursday, 17 April 2014

C#: Retrieve user data from Active Directory

This summary is not available. Please click here to view the post.

Tuesday, 24 December 2013

WPF DataGrid - Custom template for generic columns

Recently I had to bind a WPF DataGrid to a System.Data.DataSet. This is quite straightforward and there are many tutorials on how to achieve this.

By default all table columns are auto-generated using 4 predefined templates (Text, Hyperlink, CheckBox, and ComboBox) that support read-only and edit modes. If you wish to customize the way some columns are rendered you can also define a custom template and assign it to some columns by hooking into the AutoGeneratingColumns event of the DataGrid as described here.

Problem with generic columns

As you can see creating custom templates for columns is pretty straightforward as long as column names are fixed. If your WPF app uses a table that doesn't change dynamically you are all good. The problem starts when you use your datagrid to display tables, whose columns` names change e.g. tables loaded from a file at runtime. This is because you can't use the column name in your custom template.

Solution 1 - Create template programmatically

In this solution you build your custom template in code and assign it to the chosen column at runtime, in the AutoGeneratingColoumn event handler.
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    // First get the corresponding DataColumn
    var colName = e.PropertyName;
    var table this.DataContext as DataTable;
    var tableColumn = table.Columns[colName];

    // choose columns to customize e.g. by type
    if (YOUR CONDITION E.G. COLUMN TYPE)
    {
       var templateColumn = new DataGridTemplateColumn();
       templateColumn.Header = colName;
       templateColumn.CellTemplate = this.BuildCustomCellTemplate(colName);
       templateColumn.SortMemberPath = colName;
       e.Column = templateColumn;
    }
}

// builds custom template
private DataTemplate BuildCustomCellTemplate(string columnName)
{
    var template = new DataTemplate();

    var button = new FrameworkElementFactory(typeof (Button));
    template.VisualTree = button;

    var binding = new Binding();
    binding.Path = new PropertyPath(columnName);
     
    button.SetValue(ContentProperty, binding);

    return template;
}
The code above would create the following template for selected columns:

    
Obviously this is just an example - in real life you would need more than just a button that does nothing. In your code you can define full templates, use binding converters, assign commands etc. However, the code gets pretty complex. Therefore this solution is suitable for simple templates.

Solution 2 - Create template skeleton

Alternatively, you can create the template skeleton in XAML and replace all bindings in your event handler:


    
And the event handler:
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    (...)

    if (YOUR CONDITION E.G. COLUMN TYPE)
    {
       // Create wrapping template in code and populate all bindings accordingly 
       string xaml = @"";
       var template = (DataTemplate)XamlReader.Load(string.Format(xaml, "{Binding " + colName + "}", "{StaticResource customCellTemplate}"));
       templateColumn.CellTemplate = template;
       
       (...)
    }
}
The advantage of this approach is that you can create more complex templates in XAML and in your event handler code only populate all required bindings. The limitation of this method is that the custom template needs to be defined at the application level. I found this solution here.

Monday, 2 December 2013

Claims based authorization in MVC4

Recently I worked on a sample MVC4 application that was using Claims based authentication. I used the Identity and Access Visual Studio extension to help me configuring Windows Identity Foundation (WIF) in my app. In short, the tool updates your web.config by adding sections system.identityModel and system.identityModel.services to enable WIF. In result, my application is redirecting all unauthenticated users to my Identity Provider, which then generates a security token that is returned back to my app.

Once I had the authentication part done I started working on the authorization. I wanted it to be role-based i.e. very similar to what you use by default in the default MVC model:

[Authorize(Roles = "Administrator")]
public class AdminController : Controller
{
    // Controller code here
}
In theory, if your Identity Provider issues a token containing the Identity Role claim (http://schemas.microsoft.com/ws/2008/06/identity/claims/role) with the value of user's current role the above default authorization code should work. And it actually does! This is because some basic claims from the token are automatically used to populate the user's identity object, including roles. So when your app's authorization code checks user's role it will use values provided in the token (if any were provided).

Membership database issue

The above solution worked fine for me at the beginning. What I was not aware of is the fact that, by default, the Authorize attribute also connects to you Membership database, regardless the token content. By default as membership database MVC uses the local ASPNETDB.mdf file. I realized that when I moved the application to a different server, without moving the mdf file. Suddenly I started getting the following SQL exception when calling the Authorize attribute:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I guess there is an easy way to configure ASP not to connect to the database if roles are provided in the token. However, I decide to take a different approach to have more control over the code.

Custom authorization attribute

I decided to write a custom Authorization attribute, that would search for user's role directly in claims provided in the token:
public class ClaimsAuthorizeAttribute : AuthorizeAttribute
{
    private string claimType;
    private string claimValue;

    public ClaimsAuthorizeAttribute(string type, string value)
    {
        this.claimType = type;
        this.claimValue = value;
    }
  
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var identity = (ClaimsIdentity)Thread.CurrentPrincipal.Identity;
        var claim = identity.Claims.FirstOrDefault(c => c.Type == claimType && c.Value == claimValue);
             
        if (claim != null)
        {
            base.OnAuthorization(filterContext);
        }
        else
        {
             base.HandleUnauthorizedRequest(filterContext);
        }
    }
} 
This approach is more flexible as it allows me to use different types of claims for authorization in future, not only role. The usage of the attribute is still very simple:
[ClaimsAuthorize(ClaimTypes.Role, "Administrator")]
public class AdminController : Controller
{
    // Controller code here
}

Additional notes

When using claims based authorization it is often advised to use the existing ClaimsPrincipalPermission attribute together with the configured ClaimsAuthorizationManager. In my case this seemed like an overkill, especially that I wanted to keep the code similar to the default authorization model.

Saturday, 14 September 2013

OMPM - SQL-DMO Install Required

When trying to run the Office Migration Planning Manager for Office 2010 on a machine that has Sql Server 2008 or later installed you will often get the following error message:

SQL-DMO Install Required: This operation requires the SQL Server ODBC Driver, version 3.80 or later, which comes with SQL Server 2000, SQL Server 2005 and SQL Server Express.

This is caused by a missing dependency - SQL-DMO has been deprecated and is no longer part of the Sql Server. When you search the Web looking for solution you will be advised to install the "Backward Compatibility Components" which are part of the "Feature Pack for Microsoft SQL Server 2005". So I did. However, this caused another error:

Runtime Error!
(...)
R6034
An Application has made an attempt to load the C runtime library incorrectly.
Please contact the application's support Sql server team for more information.

Investigating this took me some time. It came out that when you search for "Feature Pack for Microsoft SQL Server 2005" in the Microsoft Download Center the first result you get is actually outdated. There is another download link at the bottom of the search results list, that points to the latest version:

Correct version: Feature Pack for Microsoft SQL Server 2005 SP4.

Installing this one fixed all issues and allowed me to run the OMPM. I had a 64x version of Sql Server 2008 R2.

Friday, 31 May 2013

How to read and write Excel cells with OpenXML and C#

Recently I needed to update an Excel spreadsheet and then retrieve some recalculated values. The tricky part was that some cells that I needed to retrieve information from were formula cells (e.g. =A1+5). I needed to update some other cells first and then get the value of recalculated formula.

Unfortunately, this is not directly possible with OpenXML. If you simply try updating some cells and then retrieving the relying ones, you will get the original values for those cells, not recalculated. . This is because formula cells don't store any values, just... formulas. You can only force recalculation by opening your document in the Excel application.

Knowing this I implemented a Refresh method, that opens the Excel app in background and then closes it immediately and saves changes. Below I present my sample code.

Prerequisites
In order to compile the following code you will need the Microsoft.OpenXML SDK 2.0 (DocumentFormat.OpenXML NuGet package) and reference to Microsoft.Office.Interop.Excel (used for opening the Excel app to recalculate formulas).

Solution
Let's start with an interface for my ExcelDocument class:

/// <summary>
/// Interface defining Excel Document methods
/// </summary>
public interface IExcelDocument
{
    /// <summary>
    /// Reads a value of a spreadsheet cell
    /// </summary>
    /// <param name="sheetName">Name of the spreadsheet</param>
    /// <param name="cellCoordinates">Cell coordinates e.g. A1</param>
    /// <returns>Value of the specified cell</returns>
    CellValue ReadCell(string sheetName, string cellCoordinates);

    /// <summary>
    /// Updates a value of a spreadsheet cell
    /// </summary>
    /// <param name="sheetName">Name of the spreadsheet</param>
    /// <param name="cellCoordinates">Cell coordinates e.g. A1</param>
    /// <param name="cellValue">New cell value</param>
    void UpdateCell(string sheetName, string cellCoordinates, object cellValue);

    /// <summary>
    /// Refreshes the workbook to recalculate all formula cell values
    /// </summary>
    void Refresh();
}
Once we have the interface we need its implementation:
public class ExcelDocument : IExcelDocument
{
    private readonly string _filePath;

    public ExcelDocument(string filePath)
    {
        _filePath = filePath;
    }

    /// <see cref="IExcelDocument.ReadCell" />
    public CellValue ReadCell(string sheetName, string cellCoordinates)
    {
        using (SpreadsheetDocument excelDoc = SpreadsheetDocument.Open(_filePath, false))
        {
            Cell cell = GetCell(excelDoc, sheetName, cellCoordinates);
            return cell.CellValue;
        }
    }

    /// <see cref="IExcelDocument.UpdateCell" />
    public void UpdateCell(string sheetName, string cellCoordinates, object cellValue)
    {
        using (SpreadsheetDocument excelDoc = SpreadsheetDocument.Open(_filePath, true))
        {
            // tell Excel to recalculate formulas next time it opens the doc
            excelDoc.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
            excelDoc.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;
            
            WorksheetPart worksheetPart = GetWorksheetPart(excelDoc, sheetName);
            Cell cell = GetCell(worksheetPart, cellCoordinates);
            cell.CellValue = new CellValue(cellValue.ToString());
            worksheetPart.Worksheet.Save();
        }
    }

    /// <summary>Refreshes an Excel document by opening it and closing in background by the Excep Application</summary>
    /// <see cref="IExcelDocument.Refresh" />
    public void Refresh()
    {
        var excelApp = new Application();
        Workbook workbook = excelApp.Workbooks.Open(Path.GetFullPath(_filePath));
        workbook.Close(true);
        excelApp.Quit();
    }

    private WorksheetPart GetWorksheetPart(SpreadsheetDocument excelDoc, string sheetName)
    {
        Sheet sheet = excelDoc.WorkbookPart.Workbook.Descendants<Sheet>().SingleOrDefault(s => s.Name == sheetName);
        if (sheet == null)
        {
            throw new ArgumentException(
                String.Format("No sheet named {0} found in spreadsheet {1}", sheetName, _filePath), "sheetName");
        }
        return (WorksheetPart) excelDoc.WorkbookPart.GetPartById(sheet.Id);
    }

   private Cell GetCell(SpreadsheetDocument excelDoc, string sheetName, string cellCoordinates)
    {
        WorksheetPart worksheetPart = GetWorksheetPart(excelDoc, sheetName);
        return GetCell(worksheetPart, cellCoordinates);
    }

    private Cell GetCell(WorksheetPart worksheetPart, string cellCoordinates)
    {
        int rowIndex = int.Parse(cellCoordinates.Substring(1));
        Row row = GetRow(worksheetPart, rowIndex);

        Cell cell = row.Elements<Cell>().FirstOrDefault(c => cellCoordinates.Equals(c.CellReference.Value));
        if (cell == null)
        {
            throw new ArgumentException(String.Format("Cell {0} not found in spreadsheet", cellCoordinates));
        }
        return cell;
    }

    private Row GetRow(WorksheetPart worksheetPart, int rowIndex)
    {
        Row row = worksheetPart.Worksheet.GetFirstChild<SheetData>().
                                Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex);
        if (row == null)
        {
            throw new ArgumentException(String.Format("No row with index {0} found in spreadsheet", rowIndex));
        }
        return row;
    }
}
I hope the code is self-explanatory and doesn't require more comments. You can optimize it for you needs e.g. when updating/reading multiple cells at once you may want to open the doc only once. Currently my code opens it and closes for each read/update request.

Wednesday, 22 May 2013

Preparation materials for MCSD Web Applications certification

I'm happy to announce that today I've become a Microsoft Certified Solutions Developer (MCSD) in Web Applications area. To achieve that I needed to pass 3 exams. Here is my short summary of each of them together with some useful preparation materials:

70-480 - Programming in HTML5 with JavaScript and CSS3

This exam begins your journey to the MCSD certificate. In general it covers exactly what is named in its title: HTML5 & CSS3. You could also use some jQuery knowledge. If you are a web developer with multiple years of experience this should be a piece of cake for you. In case you need to refresh your memory on some topics I recommend watching the free video tutorial at the Microsoft Virtual Academy:

70-486 - Developing ASP.NET MVC 4 Web Applications

This exam tests your knowledge of the Asp.Net MVC4 framework. To be honest I can't really remember if it includes WebApi questions, but it's worth to learn it anyway, as it's required for the last exam. Again, if you worked on several MVC4 projects there is nothing to be afraid of.

Before I took this exam I browsed the following book to make sure I'm not missing anything:


70-487 - Developing Windows Azure and Web Services

For me this was the hardest exam. It is because it covers a wide range of different topics. All required technologies are somehow related, but at the same time they are independent frameworks:
  • Windows Azure
  • WCF
  • MVC4 WebApi
  • Entity Framework
  • Other Data Access
Despite the exam`s title I was under impression that there were not that many questions related to Windows Azure. The basic overview of Azure features would suffice to answer most of them. There was a lot of questions related to WCF & Data Access though. Luckily there are excellent study guides available. Here are 2 that I liked most:
  • Study Guide #1
    My personal favourite; it relays strongly on pluralsight video trainings, which are usually very good.
  • Study Guide #2
    A nice alternative for those of you who don't have access to pluralsight. Most links are referencing free online materials.
If you read/watch all linked materials you will be good to go ;) Good luck future MCSDs!

Wednesday, 15 May 2013

XAML ListView - scroll SelectedItem to the middle

In the Windows Store app that I recently worked on I used several ListViews to present some data. I had 2 requirements for those lists:
  • The selected item should be always visible
  • In addition it should be displayed in the middle of the list when possible (it's not possible for the first element).
This is what I wanted to achieve:

The first requirement is quite easy to fulfill by using ListView.ScrollIntoView() method. However, this doesn't satisfy the second requirement, as you don't have any control on where exactly the item will appear.

Solution

Instead of working with the ListView directly I worked with the included ScollView control. Here is my method for scrolling with some comments:
public void ScrollToSelected(ListView list, Object selected)
{
    var scrollViewer = list.GetFirstDescendantOfType<ScrollViewer>();
    if (scrollViewer == null) return;

    // Calculate the offset to be used for scrolling.
    // In my case I use ViewPort height, index of the selected item and a fixed value 3 to adjust the result
    double halfList = scrollViewer.ViewportHeight/2;
    int itemIndex = list.Items.IndexOf(selected);
    double scrollOffset = itemIndex - halfList + 3;

    // If offset happens to be bigger than scrollable height use the scrollable height
    // Possible for items from the end of the list
    if (scrollOffset > scrollViewer.ScrollableHeight)
    {
        scrollOffset = scrollViewer.ScrollableHeight;
    }

    // scroll to calculated offset
    scrollViewer.ScrollToVerticalOffset(scrollOffset);
}

Tuesday, 14 May 2013

Windows Store - Your app doesn’t meet requirement 4.1

Recently I uploaded my first Windows 8 app to the Windows Store. At first, my app didn't pass the certification process because of the following issue (Notes from Testers):
The app has declared access to network capabilities and no privacy statement was provided in the Description page. The app has declared access to network capabilities and no privacy statement was provided in the Windows Settings Charm.

Luckily for me the issue is widely described here. In short, if your app uses internet you need to define a privacy policy. the privacy policy needs to be linked from the app description page and also avaiable from the Settings Charm.

Solution

This is what you need to do to satisfy this requirement:
  1. Create a webpage describing your privacy policy (how you use user data etc.).
  2. Deploy that webpage to any server, so it's available to everybody who wants to read it.
  3. Add a link to your privacy page on the app`s description page in the Windows Store Developer Center:
  4. Add a link to the privacy policy page to your Settings Charm.
    Here is how I do it (basing on this post):
    1. Open the App.xaml.cs file
    2. Reference the following namespace:
      using Windows.UI.ApplicationSettings;
    3. Create following methods for adding the new action called 'Privacy Policy" to your Settings pane:
      private void AddPrivacyPolicy(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
      {
          var privacyPolicyCommand = 
              new SettingsCommand("privacyPolicy", "Privacy Policy", (uiCommand) => ShowPolicyPage());
          args.Request.ApplicationCommands.Add(privacyPolicyCommand);
      }
      
      private async void ShowPolicyPage()
      {
          var uri = new Uri("http://YOUR-SERVER/privacy-policy.html")
          await Launcher.LaunchUriAsync(uri);
      }
    4. In the OnLaunched method register the newly created method:
      SettingsPane.GetForCurrentView().CommandsRequested += AddPrivacyPolicy;
  5. Rebuild your package and resubmit to the Windows Store. At this time that issue should be resolved.
When adding a Privacy Policy item to the Settings Charm you may consider using the Callisto project and its Settings Flyout support. It makes complex customization of that Settings Pane easier. In my case however it was shorter to add that single command in a regular way.

BTW I was really surprized how quick the certification process was - it took only 8h from the moment of submission! It's a huge improvment comparing to my experience with WP7 apps. I hope it stays that way.

Thursday, 25 April 2013

XAML - SelectedItem in ComboBox doesn't work

I'm currently working on a small Windows Store app. The app uses mainly default controls, with ComboBox being one of them. Recently I had a problem with selecting a default value in my ComboBox.

My XAML code looked like this:



In the design view this actually showed the correct selected item, however it didn't work when the app was ran.

Solution

The solution was actually very trivial. If you take a look at my code you'll see that the SelectedItem property is defined before the ItemSource property. It came out that the order does matter, so the SelectedItem should be defined after the ItemSource.

Wednesday, 24 October 2012

Using task based async WCF client methods in synchronous scenarios

If you are already working with the Visual Studio 2012 you may have noticed that the dialog box for generating Service References has changed a bit. It offers an additional option to generate task based asynchronous client methods (see picture below). In VS2010 you could generate async operations for the service client as well, but in VS2012 you have the additional choice:
  • Generate asynchronous operations
    This one gives you the exact same result as choosing to generate async operations in VS2010 i.e. for each service method you will have 2 additional client methods: *Async & *Completed. One of my previous posts partially explains how to use them and provide more links on that topic.
  • Generate task-based operations
    When writing your async code this option allows you to take advantage of the Task Parallel Library (TPL) that was introduced with .Net 4. This post is not meant to be a TPL tutorial, but there are many sites explaining the concept. My personal favourite is "Introduction to Async and Parallel Programming in .NET 4" by Dr. Joe Hummel. For now it is enough to say that using tasks (i.e. TPL library) can make handling your async scenarios easier and the async code more readable/maintainable.

The interesting thing is that since .Net 4.5 and its async/await feature you can easily benefit from using task-based async operation even in fully synchronous scenarios. You may start wondering what can be advantages of using async techniques & libraries in fully synchronous scenarios. The answer is: performance! If you are using regular synchronous methods, they block current thread until it receives the response. In case of task-based operations combined with async/await feature the thread is released to the pool while waiting for the service response.

Obviously this advantage only applies in some scenarios e.g. in web applications running on IIS, where requests are handled in parallel by threads from the pool. If you are working a single threaded client app you will not benefit from this approach.

Sample code

In this post I'll re-use the sample code from my last post. I'll convert synchronous calls to my sample web service so they use task-based async operations. So, let me remind you the interface of the web service that we will use:

[ServiceContract]
public interface IStringService
{
    [OperationContract]
    string ReverseString(string input);
}
Now, let's update the service client. There is actually not much conversion that needs to be done. First, you need to ensure that the generated code includes task-based async operations (right click on service reference -> "Configure service reference"). Once you have async operations generated, you need to transform the existing code to work with tasks and use async/await feature:
public async Task<string> ReverseAsync(string input)
{
    return await _client.ReverseStringAsync(input);
}
Comparing to the original, purely synchronous method we have following changes:
  • Async keyword added to the method signature
  • Method return type changed to Task<string> (i.e. original return type 'wrapped' with Task)
  • Different service client method used: ReverseStringAsync instead of ReverseString
  • Await keyword added before the client method call
  • "*Async" suffix added to the method name (recommended convention)
These changes are enough to start taking advantage of async features of .net 4.5. We only need to update our tests, but there is only a few changes here as well.

Updated integration test:

[TestMethod]
public void TestStringHelper_Reverse()
{
    StringHelper sh = new StringHelper();
    string result = sh.ReverseAsync("abc").Result;
    Assert.AreEqual("cba", result);
}
Notice that I only added a call to .Result property as this time the method returns Task.

And the unit test:

[TestMethod]
public void TestStringHelper_Reverse()
{
    // Create channel mock
    Mock<IStringServiceChannel> channelMock = new Mock<IStringServiceChannel>(MockBehavior.Strict);

    // setup the mock to expect the ReverseStringAsync method
    channelMock.Setup(c => c.ReverseStringAsync("abc")).Returns(Task.FromResult("cba"));

    // create string helper and invoke the ReverseAsync method
    StringHelper sh = new StringHelper(channelMock.Object);
    string result = sh.ReverseAsync("abc").Result;
    Assert.AreEqual("cba", result);

    //verify that the method was called on the mock
    channelMock.Verify(c => c.ReverseStringAsync("abc"), Times.Once());
 }
The main thing to notice here is that we use Task.FromResult to create a task wrapping our sample result when mocking the client method.

Asp.Net MVC

I already mentioned that described approach will only be beneficial in some types of apps e.g. webapps running on IIS. A sample Asp.Net MVC4 controller action using our async client could look as follows:
public async Task<ActionResult> Index()
{
    ViewBag.Message = "Reversed 'abc' string: "
                      + await _stringHelper.ReverseAsync("abc");
    return View();
}
Again, notice async and await keywords added to the action method, supported in MVC4.
A detailed tutorial for using aync/await with MVC4 can be found here.

Sample code for this post on my github:
https://github.com/filipczaja/BlogSamples/tree/master/MockingWCFClientWithMoqAsync

Monday, 15 October 2012

Mocking WCF client with Moq

Performing basic web service calls from your code using WCF is relativelly easy. All you have to do is add a new service reference to your project, pointing to the service url. WCF will automatically generate a client class for you, that you can use to call service methods.

The web service

Let's say we have a web service that performs various string transformation e.g. reverses specified strings (obviously it's not a real life scenario, as you wouldn't normally call a web serviec to do that). The service implements the following interface:

[ServiceContract]
public interface IStringService
{
    [OperationContract]
    string ReverseString(string input);
}
In the sample code for this post I created a basic WCF implementation of that service. However, the service itself doesn't need to be created using WCF, as long as it's using SOAP.

The client

The simplest class that consumes this service could look as follows:
public class StringHelper
{
    StringServiceClient _client;

    public StringHelper()
    {
        _client = = new StringServiceClient();
    }

    public string Reverse(string input)
    {
        return _client.ReverseString(input);
    }
}
The StringServiceClient is a class generated automatically when adding a service reference. All you have to do is istantiate it and call the chosen method.

There is one issue with that approach though: you cannot unit test your StringHelper.Reverse method, without actually calling the web service (because classes are strongly coupled). When writing proper unit tests you should mock all the class dependencies, so you can only focus on a single unit of code. Otherwise it becomes an integration test.

When using Moq you can only mock interfaces or virtual methods. The generated StringServiceClient doesn't implement any interface that would expose the service contract. Also, methods generated in that class are not virtual.

Luckly enough the code generated when adding the service reference contains the Channel interface that we can use. The channel interface extends the service contract interface, so you can invoke all service methods using its implementation. This mean we can update the client app can to remove the tight coupling:

public class StringHelper
{
    IStringServiceChannel _client;

    public StringHelper()
    {
        var factory = new ChannelFactory<IStringServiceChannel>("BasicHttpBinding_IStringService");
        _client = factory.CreateChannel(); 
    }

    public StringHelper(IStringServiceChannel client)
    {
        _client = client;
    }

    public string ReverseString(string input)
    {
        return _client.ReverseString(input);
    }
}
As you can see, instead of working with the generated client we create a channel instance using ChannelFactory and the binding name "BasicHttpBinding_IStringService". The binding name can be found in the app.config file. The app.config file is automatically updated with WCF enpoint configuration when adding the service reference.

Testing

A simple integration test for our client code:
[TestMethod]
public void TestStringHelper_Reverse()
{
    StringHelper sh = new StringHelper();
    string result = sh.Reverse("abc");
    Assert.AreEqual("cba", result);
}
This test would work with both versions of the client presented above.

Now for the actuall unit tests that mocks the service channel object using Moq:

[TestMethod]
public void TestStringHelper_Reverse()
{
    // Create channel mock
    Mock<IStringServiceChannel> channelMock = new Mock<IStringServiceChannel>(MockBehavior.Strict);

    // setup the mock to expect the Reverse method to be called
    channelMock.Setup(c => c.ReverseString("abc")).Returns("cba");

    // create string helper and invoke the Reverse method
    StringHelper sh = new StringHelper(channelMock.Object);
    string result = sh.Reverse("abc");
    Assert.AreEqual("cba", result);

    //verify that the method was called on the mock
    channelMock.Verify(c => c.ReverseString("abc"), Times.Once());
}

Sample code for the service, client & test on github:
https://github.com/filipczaja/BlogSamples/tree/master/MockingWCFClientWithMoq

Wednesday, 19 September 2012

The simplest chat ever... just got simpler

In my last post I described a simple chat implementation using the SignalR framework. At the time of writing it I thought it’s really as simple and clean as it can get. However, my work colleague Lukasz Budnik proved me wrong by suggesting a simpler solution that they used while creating hackathon.pl portal. He suggested replacing my server side components with a cloud hosted push notifications provider.

I admit I was thinking in a more traditional way, where all application components are hosted in-house, on servers owned by our company or our clients. Nowadays, it’s often a better idea to use exiting cloud hosted solutions than implementing some system components by ourselves. I definitely recommend considering this option if you have no important blockers preventing you from using SaaS solutions (e.g. like legal issues related to sending some data to third parties). Advantages that come with cloud are topic for another discussion though.

Let’s have a look how our chat application changes with this new approach. First of all, we need to choose a push provider. And yet again - Lukasz to the rescue with his latest post, describing various SaaS solutions. I decided to go with the PubNub, as its documentation already contains a chat example. So it’s a no-brainer, really.

The entire solution is now enclosed within a single html file. As mentioned at the beginning you don’t need to write any server code. The additional benefit is easier development and testing, as you don’t even need a web server, just your regular web browser.

The html file looks as follows. Please note that the html components are exactly the same as in my previous solution. In addition, PubNub allows you to bind events to DOM elements, so we don’t need jQuery in this example.

<label for="nick">Your chat nickname:</label>
<input id="nick" name="nick" type="text" />
<label for="message">Message:</label>
<input id="message" maxlength="100" name="message" type="text" />
<div id="chatWindow"></div>

<div pub-key="MY_PUBLISHER_KEY" sub-key="MY_SUBSCRIBER_KEY" ssl="off" origin="pubsub.pubnub.com" id="pubnub"></div>    
<script src="http://cdn.pubnub.com/pubnub-3.1.min.js"></script>
<script type="text/javascript"></script>

<script type="text/javascript">
(function () {
    // declare some vars first
    var chatWin = PUBNUB.$('chatWindow'),
        nick = PUBNUB.$('nick'),
        input = PUBNUB.$('message'),
        channel = 'chat';

    // subscribe to chat channel and define a method for handling incoming messages
     PUBNUB.subscribe({
          channel: channel,
          callback: function (message) {
              chatWin.innerHTML = chatWin.innerHTML + message;
          }
     });

     // submit message to channel when Enter key is pressed
     PUBNUB.bind('keyup', input, function (e) {
         if ((e.keyCode || e.charCode) === 13) {
             PUBNUB.publish({
                 channel: channel,
                 message: nick.value + ': ' + input.value
             });
         }
     });
})();
</script>

Thursday, 13 September 2012

The simplest chat ever with SignalR (and Asp.Net MVC)

Lately I was investigating some technologies for my current project and at some point I was advised to check out the SignalR library. I admit I’ve never heard about it before (shame on me). It was mentioned to me in the context of asynchronous web applications, with the main example being a web chat. Hmm, an interesting exercise I thought! Plus it should give me the general framework understanding. Let’s do it!

It was only later that I realised the chat implementation is the most common example for SignalR usage that you can find on the Web. One more can hurt though, so here is my version :)

Overview

In short, the app works in the following way: people can visit a single chat url and they join our chat automatically. This mean they will see all the messages posted to the chat since they have joined it. They can also post messages that will be seen by other chat members.

I’ve built it as part of a sample MVC4 application, although this could probably be any Asp.Net page, as I’m not using any MVC functionality at all. Two most important parts of this app are the view and the hub. The view displays chat components and handles user actions (i.e. sending messages to the hub). The hub listens for messages and publishes them to all connected clients.

The code

You will need to downlaod the SignalR library for the following code to work. The easiest way to do that is by searching for 'SignalR' in your Nuget package manager.

So I have my Chat controller, which is only used to display the view. As you can see it’s doing nothing else, so the view could probably be a static html page instead:

public class ChatController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

It’s a web chat, so we need some input fields for nickname & message. We also need an area for displaying our conversation. All these belong naturally to our view:




Now that we have basic visual components, let’s make them work. Firstly, we need to reference jQuery & SignalR libraries. I have those defined as bundles in my MVC app, but you can reference all files directly:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/SignalR")
Notice the third reference - we reference a script, that doesn’t physically exist. SignalR will handle that script request, generating in response javascript code allowing us to communicate with the chat hub. The /signalr part of the uri is configurable.

Now it’s time for the javascript code (see comments for explanation):

$(function () {
    // get the reference to chat hub, generated by SignalR
    var chatHub = $.connection.chat;
 
    // add a method that can be called by the hub to update the chat
    chatHub.publishMessage = function (nick, msg) {
        var chatWin = $("#chatWindow");
        chatWin.html(chatWin.html() + nick + ": " + msg );
    };
    
    // start the connection with the hub
    $.connection.hub.start();
    
    $(document).keypress(function (e) {
        if (e.which == 13) {
            // when the 'Enter' key is pressed, send the message to the hub
            chatHub.sendMessage($("#nick").val(), $("#message").val());
            $("#message").val("");
        }
    });
});
The hub code could not be any simpler. We need to implement a method that can be called by a client wishing to send a message. The method broadcasts that message to all connected clients:
public class Chat : Hub
{
    public void SendMessage(string nick, string message)
    {
        Clients.PublishMessage(nick, message);
    }
 }
In case you haven't noticed yet: we execute a hub server method from our client javascript code (see line 17 of js code) and the other way around i.e. client side js function from our C# hub code (see line 5 of hub code). How cool is that?!?

I must say I'm pressed how easy it is to use for programmers. If you are wondering how it's working under the hood I recommend you reading SignalR documentation on their GitHub page. And finally, here's the screenshot I've taken testing that chat using 2 different browsers:

You can download my VC2012 solution from here: DOWNLOAD.

Monday, 10 September 2012

AdMob ads in PhoneGap apps

Adding ads to your free mobile apps is one of the most common way of earning money in this business. There are multiple ads engine providers, but Google is still the leader. Google ads provider for mobile devices is called AdMob. It offers easy integration with Android, iPhone/IPad and WP7.

While integration with native apps is quite straightwforwrd and well documented, things get more complicated if you create your apps using PhoneGap and HTML5. In the past Admob offered "Smartphone Web" option, that could be presented within your HTML code for smartphone devices. Since May 2012 it's no longer available, as Google wants to make a clear division: use AdMob for purely mobile apps and AdSense for web pages.

Since mobile apps created using PhoneGap are actually web pages displayed within the native app and rendered using default browser engine it seems that AdSense is the way to go. It doesn't work though, with one of the reasons being that Google wants to crawl the sites it displays AdSense ads on.

Solution

So how do we display Google ads in HTML code that belongs to our PhoneGap app?
The answer is: WE DON'T! :)

Instead, we modify our native app container, that displays the HTML. Default PhoneGap templates for all systems (Android, WP7, iOS, ..) create a native, full-screen container for displaying your web app. We can shrink that main container and then display ads on the remaining free space using native AdMob SDK.

The only limitation of this method is that you cannot place your ad inside of your actual HTML appliaction. However, you can still place your ads in most commonly used spaces i.e. header or footer.

Android example

The sample code below presents the MainActivity of an Android app that uses PhoneGap. The code adds AdMob banner at the bottom of a mobile app:
import android.os.Bundle;
import org.apache.cordova.*;
import android.widget.LinearLayout; 
import com.google.ads.*;

public class MainActivity extends DroidGap {
    private static final String MY_AD_UNIT_ID = "YOUR_AD_UNIT_IT"; 
    private AdView adView;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // Loading your HTML as per PhoneGap tutorial
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
        
        // Adding AdMob banner
        adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID); 
        LinearLayout layout = super.root;  
        layout.addView(adView); 
        adView.loadAd(new AdRequest());
   }    
}

WP7 example

The sample code below presents default XAML created by PhoneGap template for WP7, modified to display AdMob banner at the bottom of a mobile app.