Microsoft CRM: Exporting Custom Reports to Excel

 

Peter Hecke
Microsoft Corporation

February 2005

Applies to:
   Microsoft Business Solutions CRM 1.2

Requires:
   Microsoft Customer Relationship Management 1.2
   Microsoft Visual Studio .NET 2003
   Microsoft Office Excel 2003 Professional

Summary   Learn how to develop a custom report that displays aggregate (summary) business data within the Microsoft Customer Relationship Management Web application and then export the report data to a Microsoft Excel spreadsheet for analysis. You can also set up a live data feed between the custom Microsoft CRM report and a Microsoft Excel spreadsheet for dynamic business data updates. (18 printed pages)

Download a C# version of the sample code for this article: Reporting.exe.

Contents

Introduction
Installation and Setup
Create Excel Reports
Web Page Design
Security Concerns
Additional Information

Introduction

There are several methods available to display Microsoft Customer Relationship Management (CRM) business data within Microsoft Office applications. You can use the export capability that is built into Microsoft CRM, or you can use the Microsoft Office Information Bridge Framework for Microsoft CRM.

Your business may want to combine business data to analyze in a report, such as retrieving a summary of sales accounts organized by territory. This type of information is not available from standard Microsoft CRM reports. The solution presented here shows you how to accomplish your goal. By using custom business logic, you can retrieve aggregate information, such as accounts by territory, leads by quality, and lead conversions by business entity type, and display it within a custom report. You can then export the information to a Microsoft Excel spreadsheet. This article also shows you how to set up a live data feed between Excel and Microsoft CRM.

The following figure shows the sample solution's custom report within Microsoft CRM.

Click here for larger image.

Figure 1. A custom report integrated into Microsoft CRM (click the graphic for a larger image)

This sample supports exporting the custom report's business data in XML format. You can use Excel's capability to import XML data to load the custom report data into Excel. Figure 2 shows the custom report information after it has been imported into an Excel spreadsheet. A chart of the number of accounts for each territory was later added.

Click here for larger image.

Figure 2. The custom report exported to an Excel spreadsheet (click the graphic for a larger image)

Installation and Setup

To install and set up this solution, download and run the self-extracting Reporting.exe program file. Extract the files to a local folder on the Microsoft CRM server. A CRMReporting folder containing the complete code for this article's solution should now exist in the local folder.

Install and Build the Web Interface

The Reporting Web interface provides the ability to view the custom report, export the report data to Excel, and print a copy of the Web page.

Two steps are required to install and build the Reporting Web interface:

  • Map a virtual directory in IIS to the CRMReporting folder.
  • Build the Web interface.

Map a virtual directory in IIS to the CRMReporting folder

  1. Copy the CRMReporting folder to C:\inetpub\wwwroot\.
  2. Click Start, point to Programs, point to Administrative Tools, and then click Internet Information Services (IIS) Manager.
  3. Expand the tree view for your server, and then expand the Web Sites node.
  4. Right-click Microsoft CRM Version 1.2 or Default Web Site, click New, and then click Virtual Directory.
  5. The Virtual Directory Creation Wizard opens. Click Next.
  6. On the Virtual Directory Alias page, enter an alias of CRMReporting. Click Next.
  7. On the Web Site Content Directory page, browse to the CRMReporting folder in C:\inetpub\wwwroot\. Click Next.
  8. On the Access Permissions page, make sure that the Read and Run scripts check boxes are selected. Click Next, and then click Finish.
  9. Right-click the new CRMReporting virtual directory in IIS Manager and click Properties.
  10. On the Directory Security tab, in the Authentication and access control section, click Edit.
  11. Make sure the Anonymous access check box is not selected and the Integrated Windows authentication check box is selected. Click OK two times to close the dialog boxes.

Build the Web interface

  1. In Microsoft Visual Studio .NET, open the DataSource.cs file in the CRMReporting project and change the Web server address value in the _strCRMURL class variable to the address of your Microsoft CRM Web server.

    Note   If your server is configured to start Microsoft CRM using a URL of https://localhost, you do not have to change the _strCRMURL default value.

  2. On the Build menu, click Build Solution.

    Note   If the references to the Microsoft.Crm.Platform.Proxy.dll or Microsoft.Crm.Platform.Types.dll are unresolved, just remove and re-add the references. To do this, expand References in Solution Explorer, right-click the assembly, and select Remove. Then right-click References and choose Add Reference to re-add the reference. The default location of Microsoft.Crm.Platform.Proxy.dll and Microsoft.Crm.Platform.Types.dll is on the Microsoft CRM server in the C:\Inetpub\wwwroot\bin folder. They are also available on CD1 of the Microsoft CRM installation CDs.

  3. Save the project and close Visual Studio .NET.

Integrate the Report Web Page with Microsoft CRM

With the custom Web page in place on your server, modify the Microsoft CRM configuration files to complete the integration of the Web page.

Three steps are required to integrate the Reporting Web interface:

  • Modify the Web configuration file to enable use of the ISV configuration file.
  • Modify the ISV configuration file.
  • Restart IIS to enable your customizations.

Modify the Web configuration file

To enable your customizations, you may have to modify the C:\Inetpub\wwwroot\web.config file on the Microsoft CRM server. In the section titled "ISV Integration" of the web.config file, examine the value of the ISVIntegration setting. If the value is set to Off, change the value of ISVIntegration to On as shown in the following code, save the changes, and close the web.config file.

<add key="ISVIntegration" value="On"/>

Modify the ISV configuration file

To add a custom side navigation tab that displays the Reporting Web interface page, you must modify the isv.config file for the Microsoft CRM application. This configuration file is used to add custom Web pages, toolbar buttons, and menu items to the application.

  1. Before you overwrite the current isv.config file, make a backup copy so that the current settings can be restored. The file is located in the C:\Inetpub\wwwroot\_Resources folder.
  2. Move or copy the custom isv.config file from the CRMReporting folder to the C:\Inetpub\wwwroot\_Resources folder on your Microsoft CRM server.

If you have existing modifications to the isv.config file, copy the <NavBarItem> lines from the Reporting version of isv.config and paste them into your site's copy of the isv.config file. The following example text shows what the relevant part of your isv.config file might look like, assuming you have no other customizations. Note that you may have to change the host name of localhost in the URL depending on your Microsoft CRM installation configuration.

<Areas>
   <Home code="home"/>
   <Workplace code="workplace"/>
   <Sales code="sfa"/>
   <Service code="cs"/>
   <!-- Custom navigation bar item in the Reports area -->
   <Reports code="reports">
      <NavBarItem Icon="/_imgs/ico_18_1038.gif"
      Title="Leads and Accounts Summary Report"
      Url="https://localhost/CRMReporting/WebForm1.aspx"
      Id="navRep"/>
   </Reports>
</Areas>

A key component of the <NavBarItem> tag is the title. This is the text that is displayed on the side tab in the Microsoft CRM application user interface. The URL must be the URL of the custom application you created and deployed on the Microsoft CRM Web server. After the changes are completed, save and close the isv.config file.

Restart the IIS server

To see your changes in the Microsoft CRM Web application, you must restart IIS by following these steps:

Note   You can also restart IIS from a Command Prompt window by running iisreset.

  1. Click Start, point to Programs, point to Administrative Tools, and then click Internet Information Services (IIS) Manager.
  2. Right-click the server host name, point to All Tasks, and then click Restart IIS.
  3. In the Start/Stop/Restart dialog box, click OK.

Test the Solution

To verify that the Reporting sample is installed correctly, follow these steps:

  1. Start Microsoft CRM.

  2. Open the Reports area by clicking Reports on the bottom navigation bar of the Microsoft CRM Home page.

  3. Click the Leads and Accounts Summary Report tab in the side navigation bar. Three tables that contain data should be displayed, as shown in the following figure.

        Click here for larger image.

    Figure 3. The Leads and Accounts Summary Report custom Web page (click the graphic for a larger image)

Create Excel Reports

The following sections demonstrate how to:

  • Import Microsoft CRM data into Excel.
  • Create a new spreadsheet using the imported data.
  • Load saved XML data into an existing spreadsheet.
  • Establish a live data feed between Microsoft CRM and Excel.

Import Microsoft CRM Data into Excel

To view the data from the Leads and Accounts Summary Report in Excel follow these steps:

  1. Start Microsoft CRM and open the Reports area by clicking Reports on the bottom navigation bar.
  2. In the side navigation bar, click Leads and Accounts Summary Report to display the report page.
  3. Click the (export) button in the toolbar of the report page.
  4. In the File Download dialog box, click the Open button. If a second File Download dialog box is displayed, click Open again. The Microsoft Excel application is displayed.
  5. In the Open XML dialog box, select Use the XML Source task pane and click OK.
  6. If a dialog box is displayed notifying you that Excel will create a schema based on the XML source data, click OK.
  7. A blank spreadsheet is displayed within Excel and the XML Source task pane shows the imported data hierarchy.
  8. In the XML Source pane, drag any one of the folders under the CRMReporting folder, for example LeadsByQuality, onto a spreadsheet cell. A table for the folder's data is created in the spreadsheet.
  9. With the table still selected, click the Refresh XML Data button in the List toolbar to fill in the table with imported Microsoft CRM data. If the List toolbar is not shown, you can display the toolbar by the opening the View menu, pointing to Toolbars, and clicking List.
  10. Repeat steps 8 and 9 to create tables from the other two XML Source pane folders.

At this point you can create Excel graphs from the table data, add text, and define cell styles to enhance the Excel spreadsheet. Save and close the spreadsheet.

Import an XML Data File into Excel

In the previous section, you created a spreadsheet directly from the imported Microsoft CRM data. Now you are going to save the imported data to a file and create an XML map of the data file in Excel. Using this method, the Excel spreadsheet refers to an XML data file that can be updated with new data from the Reporting Web page. When you open the spreadsheet, it will display the updated data from Microsoft CRM.

To create a spreadsheet that uses an external XML data file, follow these steps:

  1. In Microsoft CRM, open the Reports area by clicking Reports on the bottom navigation bar.
  2. In the side navigation bar, click Leads and Accounts Summary Report to display the report page.
  3. On the report web page, click the (Export) button.
  4. In the File Download dialog box, click the Save button.
  5. In the Save As dialog box, save the downloaded file to a folder on your local file system. You can change the file name, but make sure that you leave the file type as Microsoft Excel Worksheet. Close the Download complete dialog box.
  6. In Windows Explorer, double-click the worksheet file that you just created. The Microsoft Excel application is displayed and prompts you with an Open XML dialog box.
  7. Select Use the XML Source task pane and click OK.
  8. If a dialog box is displayed notifying you that Excel will create a schema based on the XML source data, click OK. A blank spreadsheet is displayed within Excel and the XML Source task pane shows the imported data hierarchy.
  9. In the XML Source pane, drag one or more of the folders under the CRMReporting folder, for example LeadsByQuality, onto a spreadsheet cell. One or more data tables are created in the spreadsheet.
  10. Save and close the spreadsheet.

Note   Follow these next steps after account or lead data has been changed in Microsoft CRM.

You are now going to update the existing XML data file with new data from Microsoft CRM. When the spreadsheet that refers to that XML data file is opened in Excel, the updated data is read from the data file and displayed in Excel.

  1. Follow steps 1 through 4 in the previous procedure again. Overwrite the existing XML data file by saving the exported XML data in a file that has the same name and is in the same folder as you did previously in step 4.
  2. In Windows Explorer, open the spreadsheet that you saved in step 10. The updated Microsoft CRM data is shown.

Use an Excel Web Query to Obtain Live Data

This section describes how to create a dynamically updated Excel table that obtains its data from Microsoft CRM. This method uses the Excel Web query feature to periodically obtain Microsoft CRM data from the Reporting Web page.

The sample download contains a spreadsheet called LiveSalesReport.xls that demonstrates the Web query feature (figure 4). For more information about Web queries in Excel, see the Excel Help topic Query for data from a Web page.

Click here for larger image.

Figure 4. The LiveSalesReport spreadsheet (click the graphic for a larger image)

To configure the Web query, follow these steps:

  1. Open the LiveSalesReport.xls file in Excel. The file is located in the CRMReporting folder.

  2. Excel displays a Query Refresh dialog box. Click Enable automatic refresh.

  3. Select the cells of all three data tables in the spreadsheet.

  4. The URL used in the Web query for the sample spreadsheet is https://localhost/CRMReporting/WebForm1.aspx. If your installation is different, change the URL of the report's Web page in the Web query. If you do not have to change the URL, go to step 8.

  5. On Excel's Data menu, point to Import External Data, and click Edit Query.

  6. In the Edit Web Query dialog box, enter a valid address for the report Web page and click Go. The Web page should load into the dialog box, as shown in the following figure.

        Click here for larger image.

    Figure 5. The Edit Web Query dialog box showing the report Web page (click the graphic for a larger image).

  7. Click the yellow arrows to the left of each table to select the tables that the Web query will obtain data from. Click Import.

  8. You can specify how frequently to update the spreadsheet tables from the custom report's Web page data. On the Data menu, point to Import External Data, and click Data Range Properties.

  9. In the External Data Range Properties dialog box, specify a refresh period in minutes.

    Figure 6. The External Data Range Properties dialog box

  10. Click OK. Save the spreadsheet to a file.

Excel updates the spreadsheet with Microsoft CRM data at the refresh interval that you specified.

Web Page Design

The report Web page in this solution exports its data in XML format, which can be imported into Excel. For each table in the report, the business logic in the code-behind page (described in the next section) uses the Microsoft CRM SDK to obtain aggregate business data by issuing a Fetch XML query to the Microsoft CRM database. The aggregate data is returned from Microsoft CRM and stored in a DataTable object. A DataSet object manages the DataTable objects and also generates the XML code that is exported. The Datagrid controls on the Web page are bound to the DataTable objects that are contained within the DataSet object.

The Web page user interface is managed by code in the WebForm1 class while a separate DataSource class provides the database access code. This greatly simplifies the code-behind page to binding the Web controls to their data and exporting XML to Excel.

Additional tables of Microsoft CRM data can be added to the Web page by following these steps:

  1. Create a new Get method in the DataSource class that queries the Microsoft CRM database and returns the data results in a DataTable object.
  2. Add the returned DataTable object to the DataSet object in the DataSource.Refresh method.
  3. Create a new control on the Web page and bind the control to the DataTable object in the WebForm1.Update method.

The Code-Behind Page

The WebForm1 class in the code-behind page creates a DataSource object, authenticates the user, binds the DataGrid controls on the Web form with their data, and supports exporting the generated XML data to Excel. The printing of the Web page report is accomplished in the Web page HTML code using a script function. The complete source code for the Web page can be found in the WebForm1.aspx and WebForm1.aspx.cs files in the CRMReporting folder.

A new DataSource object is created and stored in a private class variable. The name parameter is used internally in the DataSource class to assign a name to the DataSet. That name becomes the name of the root node in the generated XML. The URL parameter is used for Microsoft CRM authentication.

private DataSource _dataSource = new DataSource("CRMReporting",
                                     "https://localhost/MSCRMServices/");

The Page_Load method authenticates the user and handles any exception thrown from the DataSource.Authenticate method. If error logging is enabled, a detailed message is written to the Application log. The method also invokes the Update method to bind the Datagrid controls to their data tables in the DataSource object.

private bool ErrorLoggingEnabled = false;
protected System.Web.UI.WebControls.Label messageLabel;
protected System.Diagnostics.EventLog eventLog;

private void Page_Load(object sender, System.EventArgs e)
{
   try
   {
      _dataSource.Authenticate();
   }
   catch (CRMReporting.DataSourceException ex) 
   {
      // Process Platform Errors.
      messageLabel.Text = ex.Message;
      if( ErrorLoggingEnabled )
         eventLog.WriteEntry(String.Format("{0}\n{1}",ex.Message,
                             ex.InnerException.Message),
                             System.Diagnostics.EventLogEntryType.Error);
      return;
   }

   if (!Page.IsPostBack)
      Update();
}

The exportButton_Click method is the event handler for the (Export) button. This method first updates the data in the DataSource object and handles any thrown exceptions. The method then obtains an XML representation of the table data from the DataSet object and exports the XML to Excel using a MIME formatted message in the HTTP response.

private void exportButton_Click(object sender,
                                System.Web.UI.ImageClickEventArgs e)
{
   try
   {
      // Update the data in the data source.
      _dataSource.Refresh();
   }
   catch (CRMReporting.DataSourceException ex) 
   {
      // Process Platform Errors.
      messageLabel.Text = ex.Message;
      if( ErrorLoggingEnabled )
         eventLog.WriteEntry(String.Format("{0}\n{1}",ex.Message,
                             ex.InnerException.Message),
                             System.Diagnostics.EventLogEntryType.Error);
      return;
   }

   // Set the content type and disposition so that the table will be
   // opened by Microsoft Excel as a spreadsheet.
   Response.ContentType = "application/x-msexcel";
   Response.AddHeader("Content-Disposition", 
                      "attachment; filename=export.xls");
   Response.Charset = "";
   // Send XML to Excel.
   Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
   Response.Write(_dataSource.DataSet.GetXml());
   Response.End();
}

The Update method updates the data in the DataSource and handles any thrown DataSource exceptions. The method then binds all the page controls to their table data in the DataSource object.

private void Update()
{
   try
   {
      // Update the data in the data source.
      _dataSource.Refresh();
   }
   catch (CRMReporting.DataSourceException ex) 
   {
      // Process Platform Errors.
      messageLabel.Text = ex.Message;
      if( ErrorLoggingEnabled )
         eventLog.WriteEntry(String.Format("{0}\n{1}",ex.Message,
                             ex.InnerException.Message),
                             System.Diagnostics.EventLogEntryType.Error);
      return;
   }

   // Bind the datagrid controls to the data source.
   DataGrid1.DataSource = _dataSource.DataSet;
   DataGrid1.DataMember = _dataSource.DataSet.Tables[0].TableName;

   DataGrid2.DataSource = _dataSource.DataSet;
   DataGrid2.DataMember = _dataSource.DataSet.Tables[1].TableName;

   DataGrid3.DataSource = _dataSource.DataSet;
   DataGrid3.DataMember = _dataSource.DataSet.Tables[2].TableName;

   Page.DataBind();
}

Microsoft ASP.NET calls the WebForm1_Init method before the Page_Load event occurs. The method obtains the current value of the custom ErrorLogging application setting from the web.config file.

private void WebForm1_Init(object sender, System.EventArgs e)
{
   if( System.Configuration.ConfigurationSettings.
                               AppSettings["ErrorLogging"].Equals("On") )
      ErrorLoggingEnabled = true;
}

Error logging is turned off in the web.config file in this sample solution. You can turn error logging on by changing the ErrorLogging application setting in the web.config file from Off to On. You can view any logged application events in the Event Viewer application. To run the Event Viewer, click Start, point to Programs, point to Administrative Tools, and click Event Viewer.

The DataSourceException Class

The DataSourceException class provides an application-specific exception message for the DataSource class. The DataSourceException constructor takes another exception as an argument. That exception is assigned to the DataSourceException.InnerException property.

public class DataSourceException : System.ApplicationException
{
   public DataSourceException( string message, Exception inner ) :
      base(message,inner)
   { }
}

The complete source code for the DataSourceException class can be found in the CRMReporting\DataSource.cs file.

The DataSource Class

The DataSource class manages user-authentication with Microsoft CRM, obtains the aggregate data from the Microsoft CRM database for each table, and manages each data table. DataTable objects are used to hold the Microsoft CRM data, and a DataSet object is used to manage the DataTable objects. The complete source code for the DataSource class can be found in the CRMReporting\DataSource.cs file.

The Authenticate method must be called after the DataSource object is created and before any other DataSource methods are called. The Authenticate method authenticates the current user with Microsoft CRM. Any SOAP exceptions thrown by Microsoft CRM are caught and a new DataSourceException object that contains a reference to the SOAP exception is thrown.

private string _strCRMURL = "https://localhost/MSCRMServices/";
private CUserAuth _userAuth; // user authentication
private BizUser   _bizUser;  // business user
private CRMQuery  _query;    // database query

public bool Authenticate()
{
   try
   {
      // Authenticate the user.
      _bizUser = new BizUser();
      _bizUser.Credentials = 
         System.Net.CredentialCache.DefaultCredentials;
      _bizUser.Url = String.Concat(_strCRMURL,"BizUser.srf");

      _query = new CRMQuery();
      _query.Credentials = _bizUser.Credentials;
      _query.Url = String.Concat(_strCRMURL,"CRMQuery.srf");

      _userAuth = _bizUser.WhoAmI();
   }
   catch (System.Web.Services.Protocols.SoapException ex )
   {
      throw new DataSourceException(
         "The user could not be authenticated.", ex);
   }
   return true;
}

The Refresh method obtains the report data from the Microsoft CRM database in the form of filled DataTable objects and adds each table to the DataSet object. If a table already exists in the DataSet object, that table is removed and a new copy is added.

private DataSet _ds; // dataset containing all data tables

public void Refresh()
{
   // Check if the data already exists. If it does, remove
   // the old copy.
   if( _ds.Tables.Contains("LeadsByQuality") )
      _ds.Tables.Remove("LeadsByQuality");

   // Load the latest data from the Microsoft CRM database.
   _ds.Tables.Add( GetLeadsByQuality() );

   if( _ds.Tables.Contains("AccountsByTerritory") )
      _ds.Tables.Remove("AccountsByTerritory");
   _ds.Tables.Add( GetAccountsByTerritory() );

   if( _ds.Tables.Contains("LeadsByEntity") )
      _ds.Tables.Remove("LeadsByEntity");
   _ds.Tables.Add( GetLeadConversions() );
}

For each table that is displayed in the Web form, there is a corresponding Get method in the DataSource class that obtains the table data from Microsoft CRM. The GetLeadsByQuality method is shown in the following code. The GetAccountsByTerritory and the GetLeadConversions methods are similar and can be found in the downloaded source code sample.

Notice that the Fetch XML string in the GetLeadsByQuality method is querying for an aggregate data value to be returned. The %CODE% value in the Fetch XML string will be replaced by the FetchCountData method, which is described next.

public DataTable GetLeadsByQuality()
{
    // Create a Fetch XML template to retrieve a count of all Leads
    // corresponding to a specific lead quality code. The %CODE% value
    // in the Fetch XML string is a placeholder that will be replaced
    // by the FetchCountData() method.
    string strFetchXML = 
        @"<fetch mapping='logical' aggregate='true'>
            <entity name='lead'>
                <attribute name='leadid' aggregate='count'
                           alias='number'/>
                <filter type='and'>
                    <condition attribute='leadqualitycodename'
                               operator='like' value='%CODE%'/>
                </filter>
            </entity>
        </fetch>";  

    // Populate a hash table with lead quality codes to be used in the
    // Fetch XML template, and the corresponding row titles to be used
    // for reporting the results.
    Hashtable hashDBCodesAndRowTitles = new Hashtable();
    hashDBCodesAndRowTitles.Add("Hot", "Hot");
    hashDBCodesAndRowTitles.Add("Cold", "Cold");
    hashDBCodesAndRowTitles.Add("Warm", "Warm");

    // Create a new data table with two columns.
    DataTable table = new DataTable("LeadsByQuality");

    DataColumn dataColumn = new DataColumn();
    dataColumn.DataType = System.Type.GetType("System.String");
    dataColumn.ColumnName = "Quality-Code";
    dataColumn.Caption = dataColumn.ColumnName;
    dataColumn.AutoIncrement = false;
    dataColumn.ReadOnly = true;
    dataColumn.Unique = false;
    table.Columns.Add(dataColumn);

    dataColumn = new DataColumn();
    dataColumn.DataType = System.Type.GetType("System.String");
    dataColumn.ColumnName = "Leads";
    dataColumn.Caption = dataColumn.ColumnName;
    dataColumn.AutoIncrement = false;
    dataColumn.ReadOnly = true;
    dataColumn.Unique = false;
    table.Columns.Add(dataColumn);

    // Populate the data table with new rows of data.
    DataRow dataRow;
    foreach( string key in hashDBCodesAndRowTitles.Keys )
    {
        dataRow = table.NewRow();
        dataRow["Quality-Code"] = hashDBCodesAndRowTitles[key];

        try
        {
            dataRow["Leads"] = FetchCountData(strFetchXML, key);
        }
        catch (System.Web.Services.Protocols.SoapException ex )
        {
            StringBuilder message = new StringBuilder();
            message.Append(
                  "An error occurred while fetching the aggregate ");
            message.Append("lead count for quality code ");
            message.Append(hashDBCodesAndRowTitles[key]);
            message.Append(".");
            throw new DataSourceException(message.ToString(), ex);
        }
        table.Rows.Add(dataRow);
    }
    return table;
}

The FetchCountData method issues the Fetch XML query to Microsoft CRM and returns the aggregate data value. The %CODE% substring is first replaced with the passed database code before the query is issued. The result is returned from Microsoft CRM in XML format that is parsed to obtain the integer return value.

private int FetchCountData(string strFetchXML, string strCode) 
{
   XmlDocument xmlDoc = new XmlDocument();
   xmlDoc.LoadXml(_query.ExecuteQuery(_userAuth,
                                strFetchXML.Replace("%CODE%", strCode)));
   XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlDoc);

   xmlNodeReader.Read();
   xmlNodeReader.MoveToContent();
   while(xmlNodeReader.Read())
   {
      XmlNode xmlNode = xmlDoc.ReadNode(xmlNodeReader);
      if (xmlNode.Name.CompareTo("result") == 0)
      {
         return int.Parse(xmlNode.InnerText);
      }
   }
   return 0;
}

Security Concerns

To protect private company business information, you should establish the appropriate security measures to make sure that no unauthorized person is allowed access to the custom report Web page and the Microsoft CRM data displayed within it. The Web page can be accessed from within the Microsoft CRM application as well as directly from a web browser.

One way to secure the Web page is to set advanced security permissions (ACLs) on the WebForm1.aspx page so that only those user accounts that have access to your Microsoft CRM installation have read access to the report Web page.

Additional Information

For more information about the Microsoft Office Information Bridge Framework, see the MSDN documentation.