Click here to Skip to main content
Click here to Skip to main content

DNB Business Lookup and Analytics

, 2 Aug 2013
Rate this:
Please Sign up or sign in to vote.
Business Lookup and Analytics , is a Windows Store Application which can run on Desktop or Surface RT Tablet

Please note

This article is an entry in our DnB Developer Challenge. Articles in this sub-section are not required to be full articles so care should be taken when voting.

 

Note: Please use your windows live id and windows data mart primary account key to authenticate and access the windows data mart service.  Please read below the pre-requisites to know the application requirement,   

Introduction  

DNB Business Lookup and Analytics , is a Windows Store Application which can run on Desktop or Surface RT Tablet. It's a solution or an implementation to showcase or demonstrate the capabilities by making use of the D & B data in a meaningful way. I will be sharing the full source code shortly as of now It's still a work in progress implementation.  

Aim  

Build a Windows Store based D & B Business Lookup and Analytic's. 

Build a Windows Phone D & B Lookup App. 

Build a Azure based D & B Mash-up cloud service.

Demonstrate or Show a different model of D & B Data as a service. 

Here's the DNB Windows Phone and Windows Store Application screencast




 

Pre Requisites

The Application is developed using Windows 8 , VS 2012. 

Install Odata client tools for Windows Phone and Store from http://msdn.microsoft.com/en-us/jj658961

Little background about D & B 

D&B provides us a rich information related to various companies and industry data , with that one can analyze and and get to know more about the company sales, employees, company family hierarchy,

diversity ownership, bankruptcy history etc. D & B Global Database contains more than 215 million records about companies, and draws from 30,000 sources to update that data 1.5 million times per day. However for this challenge they have provided us a sandbox data which is made up of 10,000 business records.
   

How does the application helps D & B customers ? 


Our solution with the business look up and analytic's is targeted for entrepreneurs and other users who are interested in knowing the company related information end to end with the ability to view charts and know more about the company financial , demographics and other 
statistics 

D & B has already developed web based and mobile applications, it should help one to understand and get to know more about the company which she/he is interested in. However the whole intention of our Business Lookup and analytics development is targeting the Windows Store users so that one can install the application from the store and analyze the same in Desktop or Tablet. Also I have a plan to come-up with the Windows Phone App which will reuse some of the code base of Windows Store App development. The usage of tablets and mobile devices are increasing day by day. I'm sure it would help peoples in understanding the company related information if we are coming up with applications targeting tablets and mobile phones.      

There are various targeted users who can make use of this application and can benefit out of it. Below are some of the key users of this app. 

Suppliers : Wish to know more about the company revenue , perform some analytic's to understand the companies based on the Line of Business.  

Entrepreneurs: Wish to know about the companies doing a specific business. They need to understand the location where they can start a new company where they can make a maximum revenue. One can search companies by location or demographics and understand the company basic information, public info, firmographics information etc. Also the entrepreneurs would like to start a company where there is less crime, robbery or theft etc.  

Marketing Customers:  These are customer who do market research to understand the companies business , profit etc so that they can either compare against other companies doing the same business or they will try understand the companies which are making the maximum revenues. Also one might be interested in knowing the bankrupt , debarment , women owned, veteran companies.   

Here are the Windows Store App functionality

1. Search companies by demographics and view company basic information, public and firmographics information.  

2. Search near by companies by GeoLocation. 

3. Mashup's

    1. Get all Women owned minority companies.  

    2. Get all Women owned veteran companies. 

    3. Get all Women owned minority and veteran companies.
   
    4. Get all Women owned green certified companies.

4.  Analytic's

    1. Get all Bankrupt companies 

    2. Get all Debarment companies.

    3. Get all Green certified companies.  
   
    4. Get all minority companies.

    5. Get all out of business companies.  

    6. Get all Veteran companies. 

    7. Get all Women owned companies.  

In addition to all the above things , it's also planned the show up the companies which are considered to be in Environmental Hazard Risk areas. There are various scenarios in which one might need to understand the companies located in a geographic location where there would be a high risk of natural disasters. Say if an entrepreneur is interested in starting a new company , location is one important factor which really matters. One might not be interested in building a company in a location where there are more natural disasters. 

Also if you are depending upon a company supplies which is located at environmental hazard risk area, you never know when there will be an interruption in the supplies. In order to get these information we need to relay upon some source to get the information based on say ZipCode or Area. We are making use of a environmental hazard rank data mart service

(http://datamarket.azure.com/dataset/edr/environmentalhazardrank). 

There's one major constraint over the above mentioned environmental hazard rank service. As of today we can get only the environmental issues related information for any given US Zip Code. It might be a good

idea to switch some other service in near future if we get a chance to explore world wide environmental hazard risk information.  

Here's the data analytics part which I'm planning to work on. We will be showing up the chart based on the D &B data. For that we are

making use of an open-source Modern UI (Metro) Charts for Windows 8

library. It's available in nuget packages(http://nuget.org/packages/ModernChart/). One can easily install and make use of it. 

Barchart showing the annual sales in dollars based on the line ofbusiness of the companies. 

Bar chart showing the number of employees based on the company start yearor line of business.  

Bar chart showing the HQ annual sales in dollars for the company family hierarchy based on the line of business of the companies.   

Here's the Usecase diagram of the application.

List of Service consumed by the Windows Store and Windows Phone Application.

1. D & B Sandbox Service -  https://api.datamarket.azure.com/DNB/DeveloperSandbox/v1/ 

2. Environmental Hazard Rank Service - https://api.datamarket.azure.com/EDR/EnvironmentalHazardRank/v1/EnvironmentalHazardRankingByUSPostalZipCode 

3. 2006 - 2008 Crime in the United States (Data.gov) Service -  https://api.datamarket.azure.com/data.gov/Crimes/v1/CityCrime 
 

Background 

Understanding and knowledge of Windows Store Application Development. Knowledge of D &B data in Windows Data Mart and it's OData consumption would benefit for one to develop an application. 

Using the code 

We will see below on how to make use of D & B Windows Data Mart service. Below is the code snippet , a data service helper class for fetching the D & B Sandbox data.  We will see bits and pieces of DNBDataServiceHelper class which I have built as a part of this application development.

First our application will have to make a Service Reference for D & B Sandbox data. Here's the data mart service URL - https://api.datamarket.azure.com/EDR/EnvironmentalHazardRank/v1/

Our service helper , creates an instance of the DNBDeveloperSandboxContainer , which is a composed of  entities such as Demographics, Firmographics etc. It's like a data context , with the help of it we will be accessing all the D & B entity information.

Note – Only authorized users can access the data. When we are signing up the data mart service, we will be given a unique primary authentication key for accessing the D & B Sandbox information. We will have to make a note on this and use the same key in our application in order to access the D & B data.  

 public class DNBDataServiceHelper
    {
        DNBDeveloperSandboxContainer serviceClient = new DNBDeveloperSandboxContainer(new Uri("https://api.datamarket.azure.com/DNB/DeveloperSandbox/v1"));
     
        public string AuthenticationKey { get; set; }
        public DNBDataServiceHelper(string key)
        {
            this.AuthenticationKey = key;
            SetCredentials();
        }
 
        private void SetCredentials()
        {
            serviceClient.Credentials = new System.Net.NetworkCredential(AuthenticationKey, AuthenticationKey);
        }
}

Below is the code snippet for getting the D & B firmographics information by line of business. As of now we could not apply Odata substring filtering for the line of business field. That's the reason we are fetching all firmographics information and filtering the information based on the line of business. I have raised a question for D & B and following it up on how to perform a substring filtering for D & B Odata. Here's the question. http://www.codeproject.com/Messages/4606737/D-B-Odata-Related.aspx
 
 

 async public Task<list<firmographics>> GetFirmographicsByLineOfBusiness(string lineOfBusiness)
 {
            var query = serviceClient.Firmographics;

            if (pageCount > 0)
                query = query.AddQueryOption("$skip", pageCount * 100);
         
            DataServiceQuery<Firmographics> dataServiceQuery = (DataServiceQuery<Firmographics>)(query);
            TaskFactory<IEnumerable<Firmographics>> tf = new TaskFactory<IEnumerable<Firmographics>>();
            var firmographicsInfo = await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar));

            firmographicsInfo = (from firmographic in firmographicsInfo
                                where firmographic.LineOfBusiness.Trim().ToLower().Contains(lineOfBusiness.Trim().ToLower())
                                select firmographic).ToList();
            
            return firmographicsInfo.OrderBy(f => f.Company).ToList();
}

Here's the code snippet for fetching the demographics information based onthe demographics filtering parameter. Notice the Odata filtering applied for City , State abbreviation and ZipCode by adding a query
option and then executing the query to get the filtered demographic information.   

async public Task<list<demographics>> GetDemographics(DemographicsFilter demograhicsFilter)
{
     string filterValue = "";

     var query = serviceClient.Demographics;
     if (!string.IsNullOrEmpty(demograhicsFilter.CityName))
        filterValue = string.Format("City eq '{0}'", demograhicsFilter.CityName);
     if (!string.IsNullOrEmpty(demograhicsFilter.State) && filterValue != "")
        filterValue += string.Format("and StateAbbrv eq '{0}'", demograhicsFilter.State);
     else  if (!string.IsNullOrEmpty(demograhicsFilter.State))
        filterValue += string.Format("StateAbbrv eq '{0}'", demograhicsFilter.State);
     if (!string.IsNullOrEmpty(demograhicsFilter.ZipCode) && filterValue != "")
        filterValue += string.Format("and ZipCode eq '{0}'", demograhicsFilter.ZipCode);
     else if (!string.IsNullOrEmpty(demograhicsFilter.ZipCode))
        filterValue += string.Format("ZipCode eq '{0}'", demograhicsFilter.ZipCode);
            
     query = query.AddQueryOption("$filter", filterValue);

     if (pageCount > 0)
         query = query.AddQueryOption("$skip", pageCount * 100);

     DataServiceQuery<Demographics> dataServiceQuery = (DataServiceQuery<Demographics>)(query);
     TaskFactory<IEnumerable<Demographics>> tf = new TaskFactory<IEnumerable<Demographics>>();
     var demographicsInfo = await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar));
         
     if (!string.IsNullOrEmpty(demograhicsFilter.CompanyName))
       demographicsInfo = (from demographic in demographicsInfo
                           where demographic.Company.StartsWith(demograhicsFilter.CompanyName)
                           select demographic).ToList();

     if(!string.IsNullOrEmpty(demograhicsFilter.Country))
        demographicsInfo = (from demographic in demographicsInfo
                            where demographic.Country == demograhicsFilter.Country
                            select demographic).ToList();

     return demographicsInfo.OrderBy(d => d.Company).ToList();
}

Below is the code snippet for fetching the D & B LocationLatLong table data. We are making use of this information and showing up in the main screen of our application.   

async public Task<List<LocationLatLong>> GetLocationLatLong()
{
     var query = (from latLong in serviceClient.LocationLatLong
                         select latLong);
     DataServiceQuery<LocationLatLong> dataServiceQuery = (DataServiceQuery<LocationLatLong>)(query);
     TaskFactory<IEnumerable<LocationLatLong>> tf = new TaskFactory<IEnumerable<LocationLatLong>>();
     var locationInfo = await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                        iar => dataServiceQuery.EndExecute(iar));
     return locationInfo.OrderBy(l => l.Company).ToList();
}  

Here's the code snippet for returning the LocationLatLong Information based on DunNumber. We will be using the location latitude and longitude information for showing up the map so that should help for one to understand where the company is located.   

async public Task<LocationLatLong> GetLocationLatLongByDunNumber(string dunNumber)
{
     var query = serviceClient.LocationLatLong;
                    
     DataServiceQuery<LocationLatLong> dataServiceQuery = (DataServiceQuery<LocationLatLong>)(query);
     TaskFactory<IEnumerable<LocationLatLong>> tf = new TaskFactory<IEnumerable<LocationLatLong>>();
     List<LocationLatLong> locationInfo = null;

     locationInfo = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                          iar => dataServiceQuery.EndExecute(iar))).ToList();

     return (from location in locationInfo
             where location.DUNSNumber == dunNumber
             select location).FirstOrDefault();            
} 

Below is the code snippet for fetching the firmographics information. As of now with the D & B sandbox data, there are set of 10,000 firmographics information available for us. Based on the DunsNumber we can query and return the firmographics info.   

async public Task<Firmographics> GetFirmographicsInfoByDunNumber(string dunNumber)
{
    var query = serviceClient.Firmographics;

    DataServiceQuery<Firmographics> dataServiceQuery = (DataServiceQuery<Firmographics>)(query);
    TaskFactory<IEnumerable<Firmographics>> tf = new TaskFactory<IEnumerable<Firmographics>>();
    List<Firmographics> firmographicsInfo = null;

    firmographicsInfo = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                         iar => dataServiceQuery.EndExecute(iar))).ToList();

    return (from record in firmographicsInfo
            where record.DUNSNumber == dunNumber
            select record).FirstOrDefault();
}

Here's the code snippet for fetching the PublicRecords Information based on the DunsNumber. 

async public Task<PublicRecords> GetPublicRecordsByDunNumber(string dunNumber)
{
    var query = serviceClient.PublicRecords;

    DataServiceQuery<PublicRecords> dataServiceQuery = (DataServiceQuery<PublicRecords>)(query);
    TaskFactory<IEnumerable<PublicRecords>> tf = new TaskFactory<IEnumerable<PublicRecords>>();
    List<PublicRecords> publicRecords = null;

    publicRecords = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                          iar => dataServiceQuery.EndExecute(iar))).ToList();

    return (from record in publicRecords
            where record.DUNSNumber == dunNumber
            select record).FirstOrDefault();
}

Now let us see the most exciting part of searching for companies based on the GeoLocation. We will use using couple of things here, the Window 8 Location Sensor API's for getting the current user or customer location. I'm using Intel Ultrabook for developing this application , which provides built in Geo Sensor, a hardware device through which we can get the exact location latitude and longitude values.

Here's the code snippet for retrieving the GeoLocation based on GeoLocator class which is in Windows.Devices.Geolocation namespace. 

private Geolocator _geolocator = new Geolocator(); 
private CancellationTokenSource _cts = null;
async private void PageLoaded(object sender, RoutedEventArgs e)
{
    string errorMessage = string.Empty;
    try
    {
        // Get the cancellation token.
        _cts = new CancellationTokenSource();
        CancellationToken token = _cts.Token;
        // Get the location.
        Geoposition pos = await _geolocator.GetGeopositionAsync().AsTask(token);
        txtLatitude.Text = pos.Coordinate.Latitude.ToString();
        txtLongitude.Text = pos.Coordinate.Longitude.ToString();                
    }
    catch (System.UnauthorizedAccessException ex)
    {
        ShowErrorMessage(ex.Message);       
    }
} 

Here's the Windows Store application changes for enabling Location. We need to set the Location Capabilities so that our application can access Location based on the GeoLocator.



Here's the code snippet for fetching the LocationLatLong information based on the latitude , longitude and distance.

Note - The application makes use of an algorithm for getting the bounding co-ordinate values. Based on this information we will be building a query to fetch the LocationLatLang information by latitude , longitude and distance. You can find more information about the algorithm in http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#GeoLocationDemo , You could also see the Java implementation too. 

async public Task<list<locationlatlong>> GetCompaniesNearByLocation(double latitude, double longitude, double distance)
{
            double earthRadius = 3958.76; // In Miles.
            GeoLocation myLocation = GeoLocation.FromDegrees(latitude, longitude);
            GeoLocation[] boundingCoordinates = myLocation.BoundingCoordinates(distance);

            bool meridian180WithinDistance = boundingCoordinates[0].getLongitudeInDegrees() >
                                             boundingCoordinates[1].getLongitudeInDegrees();

            var query = serviceClient.LocationLatLong;
            DataServiceQuery<locationlatlong> dataServiceQuery = (DataServiceQuery<locationlatlong>)(query);
            TaskFactory<ienumerable<locationlatlong>> tf = new TaskFactory<ienumerable<locationlatlong>>();
            var locationLatLong = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar))).ToList();

            double distanceTo = myLocation.DistanceTo(myLocation);
            if (meridian180WithinDistance)
            {
                locationLatLong = (from location in locationLatLong
                                   where (double.Parse(location.Latitude) >= boundingCoordinates[0].getLatitudeInDegrees()
                                   && double.Parse(location.Latitude) <= boundingCoordinates[1].getLatitudeInDegrees())
                                   && (double.Parse(location.Longitude) >= boundingCoordinates[0].getLongitudeInDegrees()
                                   || double.Parse(location.Longitude) <= boundingCoordinates[1].getLongitudeInDegrees())
                                   && distanceTo <= (distance/ earthRadius)
                                   select location).ToList();
            }
            else
            {
                locationLatLong = (from location in locationLatLong
                                   where (double.Parse(location.Latitude) >= boundingCoordinates[0].getLatitudeInDegrees()
                                   && double.Parse(location.Latitude) <= boundingCoordinates[1].getLatitudeInDegrees())
                                   && (double.Parse(location.Longitude) >= boundingCoordinates[0].getLongitudeInDegrees()
                                   && double.Parse(location.Longitude) <= boundingCoordinates[1].getLongitudeInDegrees())
                                   && distanceTo <= (distance / earthRadius)
                                   select location).ToList();
            }
            
            return locationLatLong;
}

D & B Data as a Azure Service   

Here we will see how to provide D & B data as a azure service. As of now D & B has provided us Windows Data Mart service, which works fine. However the whole idea of implementing a cloud service allows us to provide a different model of service. I have come up with an WCF Service implementation , it's a kind of a wrapper around the Odata. What I mean is right now the WCF Service in turn is consuming the Odata service. The Service is accessible at  "http://dnbservice.cloudapp.net:8080/DNBService.svc"  

Below is the D & B service project solution snapshot.  
 



Here's the DNB Service Library Architecture.

DNB WCF Service Library project , an implementation which has interface and an implementation class which is nothing but a service contract. 
DNB Service Application project which references the DNB WCF Service Library, it's an application for required for hosting the WCF Service. It has an *.svc file and web.config which has the address , binding and contract related information. DNB Windows Azure Project, it's a web role project which makes use of the DNB Service Application. It's required for creating a service package and configuration files for Azure deployment.  

D & B Unit Testing Project , it's required for unit testing our service functionality.  

Let us deep dive a bit and try to understand the service implementation.  Here's the code snippet for the D & B Contract. It's still a work in progress implementation , I'm going to add more shortly.

    [ServiceContract]
    public interface IDNBService
    {
        [OperationContract]
        Task<List<Firmographics>> GetFirmographicsByLineOfBusiness(string lineOfBusiness, int pageCount);

        [OperationContract]
        Task<Demographics> GetDemographicsByDunNumber(string dunNumber);

        [OperationContract]
        Task<List<Demographics>> GetDemographics(DemographicsFilter demograhicsFilter, int pageCount);

        [OperationContract]
        Task<List<LocationLatLong>> GetLocationLatLong();

        [OperationContract]
        Task<PublicRecords> GetPublicRecordsByDunNumber(string dunNumber);

        [OperationContract]
        Task<Firmographics> GetFirmographicsInfoByDunNumber(string dunNumber);

        [OperationContract]
        Task<LocationLatLong> GetLocationLatLongByDunNumber(string dunNumber);

        [OperationContract]
        Task<string> GetDunNumberOnLocation(string latitude, string longitude);

        [OperationContract]
        Task<List<PublicRecords>> GetOutOfBusinessCompanies(string city, string stateAbbr, string country, int pageCount);

        [OperationContract]
        Task<List<PublicRecords>> GetBankruptedCompanies(string city, string stateAbbr, string country, int pageCount);

        [OperationContract]
        Task<List<PublicRecords>> GetDebarrmentedCompanies(string city, string stateAbbr, string country, int pageCount);

        [OperationContract]
        Task<List<Veteran>> GetVeteranCompanies(string city, string stateAbbr, string country, int pageCount);

        [OperationContract]
        Task<List<Green>> GetGreenCertifiedCompanies(string city, string stateAbbr, string country, int pageCount);

        [OperationContract]
        Task<List<Minority>> GetMinorityCompanies(string city, string stateAbbr, string country, int pageCount);

        [OperationContract]
        Task<List<Women>> GetWomenOwnedCompanies(string city, string stateAbbr, string country, int pageCount, string industryCodeDesc);

        [OperationContract]
        Task<List<LocationLatLong>> GetCompaniesNearByLocation(double latitude, double longitude, double distance, int pageCount);
    }

Below is the code snippet for D &B Service Contract Implementation. It's a class which implements IDNBService interface.  

You can notice below the Uri , which makes use of D & B Sandbox service. The methods for fetching various companies demographics, firmographics, location information everything is obtained from the sandbox container. Also the service is implemented in such a way that , one has to provide his/her authentication key for fetching any of the D & B data. The Authentication key is nothing but the D & B Windows Data Mart Authentication Key.   

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public partial class DNBService : IDNBService
{
        DNBDeveloperSandboxContainer serviceClient = new DNBDeveloperSandboxContainer(new Uri("https://api.datamarket.azure.com/DNB/DeveloperSandbox/v1"));
     
        public string AuthenticationKey { get; set; }
        public DNBService(string key)
        {
            this.AuthenticationKey = key;
            SetCredentials();
        }
        /// <summary>
        /// Set the Container Credentials. You need to set it with a valid Primary Account Key to access the DNB Sandbox Data.
        /// </summary>
        private void SetCredentials()
        {
            serviceClient.Credentials = new System.Net.NetworkCredential(AuthenticationKey, AuthenticationKey);
        }
        /// <summary>
        /// Get Firmographics Info by Line of Business 
        /// </summary>
        /// <param name="lineOfBusiness"></param>
        /// <param name="pageCount"></param>
        /// <returns>Task<List<Firmographics>></returns>
        async public Task<List<Firmographics>> GetFirmographicsByLineOfBusiness(string lineOfBusiness, int pageCount)
        {
            var query = serviceClient.Firmographics;
            if (pageCount > 0)
                query = query.AddQueryOption("$skip", pageCount * 100);
         
            DataServiceQuery<Firmographics> dataServiceQuery = (DataServiceQuery<Firmographics>)(query);
            TaskFactory<IEnumerable<Firmographics>> tf = new TaskFactory<IEnumerable<Firmographics>>();
            var firmographicsInfo = await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar));
            firmographicsInfo = (from firmographic in firmographicsInfo
                                where firmographic.LineOfBusiness.Trim().ToLower().Contains(lineOfBusiness.Trim().ToLower())
                                select firmographic).ToList();
            
            return firmographicsInfo.OrderBy(f => f.Company).ToList();
        }
        /// <summary>
        /// Get Demographics by DunNumber
        /// </summary>
        /// <param name="dunNumber">DUNS Number</param>
        /// <returns>Task<Demographics></returns>
        async public Task<Demographics> GetDemographicsByDunNumber(string dunNumber)
        {
            var query = serviceClient.Demographics;
            query = query.AddQueryOption("$filter", string.Format("DUNSNumber eq '{0}'", dunNumber));
       
            DataServiceQuery<Demographics> dataServiceQuery = (DataServiceQuery<Demographics>)(query);
            TaskFactory<IEnumerable<Demographics>> tf = new TaskFactory<IEnumerable<Demographics>>();
            var demographicsInfo = await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar));
            return demographicsInfo.ToList()[0];
        }

        /// <summary>
        /// Get Demographics by Demographics Filter
        /// </summary>
        /// <param name="DemographicsFilter">demographicsFilter</param>
        /// <param name="pageCount">pageCount</param>
        /// <returns>Task<List<Demographics>></returns>
        async public Task<List<Demographics>> GetDemographics(DemographicsFilter demograhicsFilter, int pageCount)
        {
            string filterValue = "";
            var query = serviceClient.Demographics;
            if (!string.IsNullOrEmpty(demograhicsFilter.CityName))
                filterValue = string.Format("City eq '{0}'", demograhicsFilter.CityName);
            if (!string.IsNullOrEmpty(demograhicsFilter.State) && filterValue != "")
                filterValue += string.Format("and StateAbbrv eq '{0}'", demograhicsFilter.State);
            else  if (!string.IsNullOrEmpty(demograhicsFilter.State))
                filterValue += string.Format("StateAbbrv eq '{0}'", demograhicsFilter.State);
            if (!string.IsNullOrEmpty(demograhicsFilter.ZipCode) && filterValue != "")
                filterValue += string.Format("and ZipCode eq '{0}'", demograhicsFilter.ZipCode);
            else if (!string.IsNullOrEmpty(demograhicsFilter.ZipCode))
                filterValue += string.Format("ZipCode eq '{0}'", demograhicsFilter.ZipCode);
            
            query = query.AddQueryOption("$filter", filterValue);
            if (pageCount > 0)
                query = query.AddQueryOption("$skip", pageCount * 100);
            DataServiceQuery<Demographics> dataServiceQuery = (DataServiceQuery<Demographics>)(query);
            TaskFactory<IEnumerable<Demographics>> tf = new TaskFactory<IEnumerable<Demographics>>();
            var demographicsInfo = await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar));
         
            if (!string.IsNullOrEmpty(demograhicsFilter.CompanyName))
                demographicsInfo = (from demographic in demographicsInfo
                                   where demographic.Company.StartsWith(demograhicsFilter.CompanyName)
                                   select demographic).ToList();
            if(!string.IsNullOrEmpty(demograhicsFilter.Country))
                demographicsInfo = (from demographic in demographicsInfo
                                    where demographic.Country == demograhicsFilter.Country
                                    select demographic).ToList();
            return demographicsInfo.OrderBy(d => d.Company).ToList();
        }
        /// <summary>
        /// Return LocationLatLong 
        /// </summary>
        /// <returns>Task<List<LocationLatLong>></returns>
        async public Task<List<LocationLatLong>> GetLocationLatLong()
        {
            var query = (from latLong in serviceClient.LocationLatLong
                         select latLong);
            DataServiceQuery<LocationLatLong> dataServiceQuery = (DataServiceQuery<LocationLatLong>)(query);
            TaskFactory<IEnumerable<LocationLatLong>> tf = new TaskFactory<IEnumerable<LocationLatLong>>();
            var locationInfo = await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar));
            return locationInfo.OrderBy(l => l.Company).ToList();
        }

        /// <summary>
        /// Return PublicRecords based on Dun Number
        /// </summary>
        /// <param name="dunNumber">dunNumber</param>
        /// <returns>Task<PublicRecords></returns>
        async public Task<PublicRecords> GetPublicRecordsByDunNumber(string dunNumber)
        {
            var query = serviceClient.PublicRecords;
            DataServiceQuery<PublicRecords> dataServiceQuery = (DataServiceQuery<PublicRecords>)(query);
            TaskFactory<IEnumerable<PublicRecords>> tf = new TaskFactory<IEnumerable<PublicRecords>>();
            List<PublicRecords> publicRecords = null;
            publicRecords = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                          iar => dataServiceQuery.EndExecute(iar))).ToList();
            return (from record in publicRecords
                       where record.DUNSNumber == dunNumber
                       select record).FirstOrDefault();
        }

        /// <summary>
        /// Return Firmographic Info by DunNumber
        /// </summary>
        /// <param name="dunNumber">dunNumber</param>
        /// <returns>Task<Firmographics></returns>
        async public Task<Firmographics> GetFirmographicsInfoByDunNumber(string dunNumber)
        {
            var query = serviceClient.Firmographics;
            DataServiceQuery<Firmographics> dataServiceQuery = (DataServiceQuery<Firmographics>)(query);
            TaskFactory<IEnumerable<Firmographics>> tf = new TaskFactory<IEnumerable<Firmographics>>();
            List<Firmographics> firmographicsInfo = null;
            firmographicsInfo = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                          iar => dataServiceQuery.EndExecute(iar))).ToList();
            return (from record in firmographicsInfo
                                where record.DUNSNumber == dunNumber
                                select record).FirstOrDefault();
        }

        /// <summary>
        /// Return LocationLatLong based on Dun Number
        /// </summary>
        /// <param name="dunNumber">dunNumber</param>
        /// <returns>Task<LocationLatLong></returns>
        async public Task<LocationLatLong> GetLocationLatLongByDunNumber(string dunNumber)
        {
            var query = serviceClient.LocationLatLong;
                    
            DataServiceQuery<LocationLatLong> dataServiceQuery = (DataServiceQuery<LocationLatLong>)(query);
            TaskFactory<IEnumerable<LocationLatLong>> tf = new TaskFactory<IEnumerable<LocationLatLong>>();
            List<LocationLatLong> locationInfo = null;
            locationInfo = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                          iar => dataServiceQuery.EndExecute(iar))).ToList();
            return (from location in locationInfo
                       where location.DUNSNumber == dunNumber
                       select location).FirstOrDefault();            
         }

        /// <summary>
        /// Get DUN Number based on the Location - Latitude , Longitude.
        /// </summary>
        /// <param name="latitude">latitude</param>
        /// <param name="longitude">longitude</param>
        /// <returns>Task<string></returns>
        async public Task<string> GetDunNumberOnLocation(string latitude, string longitude)
        {
            var query = (from loc in serviceClient.LocationLatLong
                         where loc.Latitude == latitude && loc.Longitude == longitude
                         select loc);
            DataServiceQuery<LocationLatLong> dataServiceQuery = (DataServiceQuery<LocationLatLong>)(query);
            TaskFactory<IEnumerable<LocationLatLong>> tf = new TaskFactory<IEnumerable<LocationLatLong>>();
            LocationLatLong locationInfo = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar))).FirstOrDefault();
            return locationInfo != null ? locationInfo.DUNSNumber : string.Empty;
        }
        /// <summary>
        /// Return OutOfBusinessCompany PublicRecords based on City, State , Country
        /// </summary>
        /// <param name="city">city</param>
        /// <param name="stateAbbr">stateAbbr</param>
        /// <param name="country">country</param>
        /// <param name="pageCount">pageCount</param>       
        /// <returns>Task<List<PublicRecords>></returns>
        async public Task<List<PublicRecords>> GetOutOfBusinessCompanies(string city, string stateAbbr, string country, int pageCount)
        {
            var query = serviceClient.PublicRecords;
            string filterValue = "";
            if (!string.IsNullOrEmpty(city))
                filterValue = string.Format("City eq '{0}'", city);
            if (!string.IsNullOrEmpty(stateAbbr) && filterValue != "")
                filterValue += string.Format("and StateAbbrv eq '{0}'", stateAbbr);
            else if (!string.IsNullOrEmpty(stateAbbr))
                filterValue += string.Format("StateAbbrv eq '{0}'", stateAbbr);
            if (!string.IsNullOrEmpty(city) || !string.IsNullOrEmpty(stateAbbr))
                filterValue += string.Format("and OutOfBusinessInd eq '{0}'", "O");
            else
                filterValue += string.Format("OutOfBusinessInd eq '{0}'", "O");
            query = query.AddQueryOption("$filter", filterValue);
            if (pageCount > 0)
                query = query.AddQueryOption("$skip", pageCount * 100);
            DataServiceQuery<PublicRecords> dataServiceQuery = (DataServiceQuery<PublicRecords>)(query);
            TaskFactory<IEnumerable<PublicRecords>> tf = new TaskFactory<IEnumerable<PublicRecords>>();
            List<PublicRecords> publicRecords = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar))).ToList();
            if (country != "")
                publicRecords = publicRecords.Where(p => p.Country == country).ToList();
            return publicRecords;
        }

        /// <summary>
        /// Return OutOfBusinessCompany PublicRecords based on State , Country
        /// </summary>
        /// <param name="city">city</param>
        /// <param name="stateAbbr">stateAbbr</param>
        /// <param name="country">country</param>
        /// <param name="pageCount">pageCount</param>       
        /// <returns>Task<List<PublicRecords>></returns>
        async public Task<List<PublicRecords>> GetBankruptedCompanies(string city, string stateAbbr, string country, int pageCount)
        {
            var query = serviceClient.PublicRecords;
            string filterValue = "";
            if (!string.IsNullOrEmpty(city))
                filterValue = string.Format("City eq '{0}'", city);
            if (!string.IsNullOrEmpty(stateAbbr) && filterValue != "")
                filterValue += string.Format("and StateAbbrv eq '{0}'", stateAbbr);
            else if (!string.IsNullOrEmpty(stateAbbr))
                filterValue += string.Format("StateAbbrv eq '{0}'", stateAbbr);
            if (!string.IsNullOrEmpty(city) || !string.IsNullOrEmpty(stateAbbr))
                filterValue += string.Format("and Bankruptcyindicator eq '{0}'", "B");
            else
                filterValue += string.Format("Bankruptcyindicator eq '{0}'", "B");           
            query = query.AddQueryOption("$filter", filterValue);
            if (pageCount > 0)
                query = query.AddQueryOption("$skip", pageCount * 100);
            DataServiceQuery<PublicRecords> dataServiceQuery = (DataServiceQuery<PublicRecords>)(query);
            TaskFactory<IEnumerable<PublicRecords>> tf = new TaskFactory<IEnumerable<PublicRecords>>();
            List<PublicRecords> publicRecords = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar))).ToList();
            if (country != "")
                publicRecords = publicRecords.Where(p => p.Country == country).ToList();
                    
            return publicRecords;
        }
        /// <summary>
        /// Return DebarrmentCompany PublicRecords based on State , Country
        /// </summary>
        /// <param name="city">city</param>
        /// <param name="stateAbbr">stateAbbr</param>
        /// <param name="country">country</param>
        /// <param name="pageCount">pageCount</param>       
        /// <returns>Task<List<PublicRecords>></returns>
        async public Task<List<PublicRecords>> GetDebarrmentedCompanies(string city, string stateAbbr, string country, int pageCount)
        {
            var query = serviceClient.PublicRecords;
            string filterValue = "";
                    
            if (!string.IsNullOrEmpty(city))
                filterValue = string.Format("City eq '{0}'", city);
            if (!string.IsNullOrEmpty(stateAbbr) && filterValue != "")
                filterValue += string.Format("and StateAbbrv eq '{0}'", stateAbbr);
            else if (!string.IsNullOrEmpty(stateAbbr))
                filterValue += string.Format("StateAbbrv eq '{0}'", stateAbbr);
            if (!string.IsNullOrEmpty(city) || !string.IsNullOrEmpty(stateAbbr))
                filterValue += string.Format("and Debarrment eq '{0}'", "Y");
            else
                filterValue += string.Format("Debarrment eq '{0}'", "Y");
            query = query.AddQueryOption("$filter", filterValue);
            if (pageCount > 0)
                query = query.AddQueryOption("$skip", pageCount * 100);
            DataServiceQuery<PublicRecords> dataServiceQuery = (DataServiceQuery<PublicRecords>)(query);
            TaskFactory<IEnumerable<PublicRecords>> tf = new TaskFactory<IEnumerable<PublicRecords>>();
            List<PublicRecords> publicRecords = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar))).ToList();         
            if (country != "")
                publicRecords = publicRecords.Where(p => p.Country == country).ToList();
                 
            return publicRecords;
        }

        /// <summary>
        /// Return Veteran Data based on City , State , Country
        /// </summary>
        /// <param name="city">city</param>
        /// <param name="stateAbbr">stateAbbr</param>
        /// <param name="country">country</param>
        /// <param name="pageCount">pageCount</param>       
        /// <returns>Task<List<Veteran>></returns>
        async public Task<List<Veteran>> GetVeteranCompanies(string city, string stateAbbr, string country, int pageCount)
        {
            string filterValue = "";
            var query = serviceClient.Veteran;
            if (!string.IsNullOrEmpty(city))
                filterValue = string.Format("City eq '{0}'", city);
            if (!string.IsNullOrEmpty(stateAbbr) && filterValue != "")
                filterValue += string.Format("and StateAbbrv eq '{0}'", stateAbbr);
            else if (!string.IsNullOrEmpty(stateAbbr))
                filterValue += string.Format("StateAbbrv eq '{0}'", stateAbbr);
            query = query.AddQueryOption("$filter", filterValue);
            if (pageCount > 0)
                query = query.AddQueryOption("$skip", pageCount * 100);
            DataServiceQuery<Veteran> dataServiceQuery = (DataServiceQuery<Veteran>)(query);
            TaskFactory<IEnumerable<Veteran>> tf = new TaskFactory<IEnumerable<Veteran>>();
            List<Veteran> veteranData = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar))).ToList();
            if (country != "")
                veteranData = veteranData.Where(p => p.Country == country).ToList();
            return veteranData;
        }
           
        /// <summary>
        /// Return Green Data based on City , State , Country
        /// </summary>
        /// <param name="city">city</param>
        /// <param name="stateAbbr">stateAbbr</param>
        /// <param name="country">country</param>
        /// <param name="pageCount">pageCount</param>       
        /// <returns>Task<List<Green>></returns>
        async public Task<List<Green>> GetGreenCertifiedCompanies(string city, string stateAbbr, string country, int pageCount)
        {
            string filterValue = "";
            var query = serviceClient.Green;
            if (!string.IsNullOrEmpty(city))
                filterValue = string.Format("City eq '{0}'", city);
            if (!string.IsNullOrEmpty(stateAbbr) && filterValue != "")
                filterValue += string.Format("and StateAbbrv eq '{0}'", stateAbbr);
            else if (!string.IsNullOrEmpty(stateAbbr))
                filterValue += string.Format("StateAbbrv eq '{0}'", stateAbbr);
            query = query.AddQueryOption("$filter", filterValue);
          
            if (pageCount > 0)
                query = query.AddQueryOption("$skip", pageCount * 100);
            DataServiceQuery<Green> dataServiceQuery = (DataServiceQuery<Green>)(query);
            TaskFactory<IEnumerable<Green>> tf = new TaskFactory<IEnumerable<Green>>();
            List<Green> greenData = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar))).ToList();
            if (country != "")
                greenData = greenData.Where(p => p.Country == country).ToList();
            greenData = greenData.Where(p => p.GreenBusinessIndicator == "Y").ToList();
            return greenData;
        }

        /// <summary>
        /// Return Minority data based on City , State , Country
        /// </summary>
        /// <param name="city">city</param>
        /// <param name="stateAbbr">stateAbbr</param>
        /// <param name="country">country</param>
        /// <param name="pageCount">pageCount</param>       
        /// <returns>Task<List<Minority>></returns>
        async public Task<List<Minority>> GetMinorityCompanies(string city, string stateAbbr, string country, int pageCount)
        {
            string filterValue = "";
            var query = serviceClient.Minority;
            if (!string.IsNullOrEmpty(city))
                filterValue = string.Format("City eq '{0}'", city);
            if (!string.IsNullOrEmpty(stateAbbr) && filterValue != "")
                filterValue += string.Format("and StateAbbrv eq '{0}'", stateAbbr);
            else if (!string.IsNullOrEmpty(stateAbbr))
                filterValue += string.Format("StateAbbrv eq '{0}'", stateAbbr);
            query = query.AddQueryOption("$filter", filterValue);
            if (pageCount > 0)
                query = query.AddQueryOption("$skip", pageCount * 100);
            DataServiceQuery<Minority> dataServiceQuery = (DataServiceQuery<Minority>)(query);
            TaskFactory<IEnumerable<Minority>> tf = new TaskFactory<IEnumerable<Minority>>();
            List<Minority> minorityData = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar))).ToList();
            if (country != "")
                minorityData = minorityData.Where(p => p.Country == country).ToList();
            return minorityData;
        }

        /// <summary>
        /// Return Women Owned Companies based on City , State , Country
        /// </summary>
        /// <param name="city">city</param>
        /// <param name="stateAbbr">stateAbbr</param>
        /// <param name="country">country</param>
        /// <param name="pageCount">pageCount</param>       
        /// <returns>Task<List<Women>></returns>
        async public Task<List<Women>> GetWomenOwnedCompanies(string city, string stateAbbr, string country, int pageCount, string industryCodeDesc)
        {
            string filterValue = "";
            var query = serviceClient.Women;
            if (!string.IsNullOrEmpty(city))
                filterValue = string.Format("City eq '{0}'", city);
            if (!string.IsNullOrEmpty(stateAbbr) && filterValue != "")
                filterValue += string.Format("and StateAbbrv eq '{0}'", stateAbbr);
            else if (!string.IsNullOrEmpty(stateAbbr))
                filterValue += string.Format("StateAbbrv eq '{0}'", stateAbbr);
            query = query.AddQueryOption("$filter", filterValue);
            if (pageCount > 0)
                query = query.AddQueryOption("$skip", pageCount * 100);
            DataServiceQuery<Women> dataServiceQuery = (DataServiceQuery<Women>)(query);
            TaskFactory<IEnumerable<Women>> tf = new TaskFactory<IEnumerable<Women>>();
            List<Women> womenOwnedData = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar))).ToList();
            if (country != "")
                womenOwnedData = womenOwnedData.Where(p => p.Country == country).ToList();
            if (industryCodeDesc != "")
                womenOwnedData = (from womenOwned in womenOwnedData
                                      where womenOwned.IndustryCodeDesc1.ToLower().Contains(industryCodeDesc.ToLower())
                                      select womenOwned).ToList();
            return womenOwnedData;
        }
        /// <summary>
        /// Get LocationLatLong Info by Latitude, Longitude and Distance
        /// Algorithm - http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#GeoLocationDemo
        /// <param name="latitude">latitude</param>
        /// <param name="longitude">longitude</param>
        /// <param name="distance">distance</param>
        /// <param name="pageCount">pageCount</param>       
        /// <returns>Task<List<LocationLatLong>></returns>        
        async public Task<List<LocationLatLong>> GetCompaniesNearByLocation(double latitude, double longitude, double distance, int pageCount)
        {
            double earthRadius = 3958.76; // In Miles.
            GeoLocation myLocation = GeoLocation.FromDegrees(latitude, longitude);
            GeoLocation[] boundingCoordinates = myLocation.BoundingCoordinates(distance);
            bool meridian180WithinDistance = boundingCoordinates[0].getLongitudeInDegrees() >
                                             boundingCoordinates[1].getLongitudeInDegrees();
            var query = serviceClient.LocationLatLong;
            if (pageCount > 0)
                query = query.AddQueryOption("$skip", pageCount * 100);
            DataServiceQuery<LocationLatLong> dataServiceQuery = (DataServiceQuery<LocationLatLong>)(query);
            TaskFactory<IEnumerable<LocationLatLong>> tf = new TaskFactory<IEnumerable<LocationLatLong>>();
            var locationLatLong = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar))).ToList();
            double distanceTo = myLocation.DistanceTo(myLocation);
            if (meridian180WithinDistance)
            {
                locationLatLong = (from location in locationLatLong
                                   where (double.Parse(location.Latitude) >= boundingCoordinates[0].getLatitudeInDegrees()
                                   && double.Parse(location.Latitude) <= boundingCoordinates[1].getLatitudeInDegrees())
                                   && (double.Parse(location.Longitude) >= boundingCoordinates[0].getLongitudeInDegrees()
                                   || double.Parse(location.Longitude) <= boundingCoordinates[1].getLongitudeInDegrees())
                                   && distanceTo <= (distance/ earthRadius)
                                   select location).ToList();
            }
            else
            {
                locationLatLong = (from location in locationLatLong
                                   where (double.Parse(location.Latitude) >= boundingCoordinates[0].getLatitudeInDegrees()
                                   && double.Parse(location.Latitude) <= boundingCoordinates[1].getLatitudeInDegrees())
                                   && (double.Parse(location.Longitude) >= boundingCoordinates[0].getLongitudeInDegrees()
                                   && double.Parse(location.Longitude) <= boundingCoordinates[1].getLongitudeInDegrees())
                                   && distanceTo <= (distance / earthRadius)
                                   select location).ToList();
            }
            
            return locationLatLong;
        }
} 

Here's the WCF Service Application configuration. Make a note on the service contract , behavior and the bindings. We are making use of basicHttpBinding for hosting our D & B WCF Service.  

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service behaviorConfiguration="DNBWCFService.CloudWCFServiceBehavior"
               name="DNBWCFService.DNBService">
        <endpoint address=""
                  binding="basicHttpBinding"                
                  contract="DNBWCFService.IDNBService" />
        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="DNBWCFService.CloudWCFServiceBehavior">
          <!--The useRequestHeadersForMetadataAddress behavior is contained in the KB981002- WCF: Hotfix rollup upodate. This behavior is required for WCF to correctly serve metadata when behind a load balancer (which is the case in Windows Azure)-->
          <useRequestHeadersForMetadataAddress>
            <defaultPorts>
              <add scheme="http"
                   port="81"/>
              <add scheme="https"
                   port="444"/>
            </defaultPorts>
          </useRequestHeadersForMetadataAddress>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>   
    </behaviors> 
  </system.serviceModel> 

Let us see the Azure web role service configuration changes. Below is the service definition which makes use of "Small" Virtual machine. We are defining the Http binding with port 8080. The service will be accessible in the configured port. 

<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="DNBWindowsAzure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2012-10.1.8">
  <WebRole name="DNBWCFServiceApplication" vmsize="Small">
    <Sites>
      <Site name="Web">
        <Bindings>
          <Binding name="Endpoint1" endpointName="Endpoint1" />
        </Bindings>
      </Site>
    </Sites>
    <Endpoints>
      <InputEndpoint name="Endpoint1" protocol="http" port="8080" />
    </Endpoints>
    <Imports>
      <Import moduleName="Diagnostics" />
    </Imports>
  </WebRole>
</ServiceDefinition>  

Here's the Service cloud configuration changes. You can notice here that we have set the instance count to 2. That's the number of azure service instance. One has to provide proper Azure storage account name, Account Key for this configuration. 

<?xml version="1.0" encoding="utf-8"?>
<ServiceConfiguration serviceName="DNBWindowsAzure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="3" osVersion="*" schemaVersion="2012-10.1.8">
  <Role name="DNBWCFServiceApplication">
    <Instances count="2" />
    <ConfigurationSettings>
      <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="DefaultEndpointsProtocol=https;AccountName=<Azure storage account name>;AccountKey=<Azure account key>" />
    </ConfigurationSettings>
  </Role>
</ServiceConfiguration>  

Here's the D &B Azure Cloud Service Dashboard, You can notice the service is running under multiple cores.

 

Snapshot of the D &B Azure Service running in 2 cores. We have two instances of the service. 



Below is the snapshot shows the cloud service deployment. When we are compiling and creating a package from our D & B Windows Azure Project, it creates a Service package file and Cloud service configuration file. We will have to use them and upload to Azure Cloud Service.

 


Crime Lookup App

As a part of the D & B application development , I thought it would be nice to have an integrated D & N Windows Phone app which shows the city crime information by making using of data mart service.

Here's one scenario where the crime information might be helpful. A customer wishes to start a new business in a location where she/he is not aware of the crime information such as violent crime, robbery , forcible rapes, property crime, burglary etc. As a person who is starting a new business , it's very important to know about the location which is safe for the company employees , not much of robbery, violent crimes or vehicle theft taking place.

Below is the screenshot of the app. Where he use can search for the city crime information based on the selected state, city. We are making use of 2006 - 2008 Crime in the United States (Data.gov) data mart service for showing the city crime information
 



Here's the code snippet , a helper class for fetching the city crime info.

 public class USCrimeServiceHelper
 {
        private const string azureDataUrl = "https://api.datamarket.azure.com/Data.ashx/data.gov/Crimes/";

        public delegate void CrimeDelegate(IEnumerable<citycrime> cityCrimeInfo);
        public event CrimeDelegate CrimeEvent;

        private static datagovCrimesContainer GetContext()
        {
            var _Uri = new Uri(azureDataUrl);
            var _Context = new datagovCrimesContainer(_Uri)
            {
                Credentials = new NetworkCredential(Resource.CrimeServiceAuthenticationKey, Resource.CrimeServiceAuthenticationKey)
            };
            return _Context;
        }

        public void QueryCrimeInfo(string city, string state)
        {
            var filteredCityCrimes = new DataServiceCollection<citycrime>();
            filteredCityCrimes.LoadCompleted += Crime_LoadCompleted;

            var query = GetContext().CityCrime;

            string filterValue = "";

            if (!string.IsNullOrEmpty(city))
                filterValue = string.Format("City eq '{0}'", city);
            if (!string.IsNullOrEmpty(state) && filterValue != "")
                filterValue += string.Format("and State eq '{0}'", state);
            else if (!string.IsNullOrEmpty(state))
                filterValue += string.Format("State eq '{0}'", state);

            query = query.AddQueryOption("$filter", filterValue);

            filteredCityCrimes.LoadAsync(query);
        }

        void Crime_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            var filteredCityCrimes = sender as DataServiceCollection<citycrime>;
            if (filteredCityCrimes.Continuation != null)
            {
                filteredCityCrimes.LoadNextPartialSetAsync();
                return;
            }

            if (CrimeEvent != null)
                CrimeEvent(filteredCityCrimes);
        }
 }
</citycrime></citycrime></citycrime>

Below is the code snippet for Windows Phone Application XAML.

<!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="Crime Lookup" Margin="9,-7,0,0" FontSize="36" />
        </StackPanel>
        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBlock x:Name="lblCity" HorizontalAlignment="Left" Margin="9,93,0,0" TextWrapping="Wrap" Text="City:" VerticalAlignment="Top" FontSize="24"/>
            <TextBox x:Name="txtCity" HorizontalAlignment="Left" Height="72" Margin="76,82,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="380"/>
            <TextBlock x:Name="lblState" HorizontalAlignment="Left" Margin="10,21,0,0" TextWrapping="Wrap" Text="State:" VerticalAlignment="Top" FontSize="24"/> 
            <toolkit:ListPicker x:Name="listPicker" CacheMode="BitmapCache" Margin="88,10,10,612" FontSize="24"/> 
            <Grid Margin="0,222,0,0">
                <ListBox Name="listBoxCrimeInfo" Margin="10,10,10,0" Background="#FF154291">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Border BorderThickness="3" Background="#FFE4F1F3" Width="500">
                                <StackPanel Orientation="Vertical">
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=City, StringFormat='City: {0}'}"></TextBlock>
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=Year, StringFormat='Year: {0}'}"></TextBlock>
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=Population, StringFormat='Population: {0}'}"></TextBlock>
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=ViolentCrime, StringFormat='Violent Crime: {0}'}"></TextBlock>
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=ForcibleRape, StringFormat='Forcible Rape: {0}'}"></TextBlock>
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=Robbery, StringFormat='Robbery: {0}'}"></TextBlock>
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=AggravatedAssault, StringFormat='Assault: {0}'}"></TextBlock>
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=ForcibleRape, StringFormat='Forcible Rape: {0}'}"></TextBlock>
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=PropertyCrime, StringFormat='Property Crime: {0}'}"></TextBlock>
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=Burglary, StringFormat='Burglary: {0}'}"></TextBlock>
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=LarcenyTheft, StringFormat='Larceny Theft: {0}'}"></TextBlock>
                                    <TextBlock Foreground="#FF412195" Text="{Binding Path=MotorVehicleTheft, StringFormat='MotorVehicle Theft: {0}'}"></TextBlock>
                                </StackPanel>
                            </Border>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </Grid>
            <Button x:Name="btnSearch" Click="SearchCrimes" Content="Search" HorizontalAlignment="Left" Margin="337,154,0,0" VerticalAlignment="Top"/>
        </Grid>
    </Grid> 

Below is the code behind, the List data binding. You can notice that we are creating an instance of the crime service helper class and invoking the method QueryCrimeInfo with two parameters city name and state to get the city crime information.

The crime service helper asynchronously loads all the matching crime info and returns the data when the crime information gets fully loaded or the event - Crime_LoadCompleted gets fired , in turn returns the crime info to the caller. 

 void BindCrimeInfo(IEnumerable<CityCrimeService.CityCrime> cityCrimeInfo)
 {
      listBoxCrimeInfo.ItemsSource = cityCrimeInfo;
      SystemTray.SetIsVisible(this, false);
 }
              
 private void SearchCrimes(object sender, RoutedEventArgs e)
 {
      var crimeServiceHelper = new USCrimeServiceHelper();
      crimeServiceHelper.CrimeEvent += BindCrimeInfo;
      SystemTray.SetIsVisible(this, true);
      crimeServiceHelper.QueryCrimeInfo(txtCity.Text.Trim(), listPicker.SelectedItem.ToString()); 
 }   

DNB Lookup - Windows Phone App 

This is something which I always had in my mind to come up with a windows phone app which makes use of D & B Sandbox data and show some meaningful and useful information.

Below is the app functionality at high level. 

1. Search Demographics , get all filtered list of demographics. Also view Public and Location Information. 

2. Search Firmographics , get all firmographics information based on given State and/or City.  

3. Get all green certified companies, with an option to filter by small business indicator.  

4. Get all women owned companies.  

5. Get all city crime information based on the State and City name.  

6. Get near by companies by Geo Location. 

Here's the application main screen. Which is a panoramic view

  

Now lets see the code snippets for the same.  

Here's the base "
DNBMobileBaseDataService" class. All other helper classes will be inheriting this class.  

public class DNBMobileBaseDataService
    {
        private const string azureDataUrl = "https://api.datamarket.azure.com/DNB/DeveloperSandbox/v1/";
         
        public string DomainName { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }

        public static DNBWinPhoneBusinessLookup.DNBDeveloperSandboxContainer.DNBDeveloperSandboxContainer GetContext(string domainName, string userName, string passWord)
        {
            var uri = new Uri(azureDataUrl);
            var context = new DNBWinPhoneBusinessLookup.DNBDeveloperSandboxContainer.DNBDeveloperSandboxContainer(uri);
            context.SendingRequest += (s, e) =>
            {
                var credentials = string.Format(@"{0}\{1}:{2}", domainName, userName, passWord);
                e.RequestHeaders["Authorization"] = string.Format(CultureInfo.InvariantCulture, "Basic {0}", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(credentials)));
            };
            return context;
        }
    }

Below is the code snippet for getting all filtered demographics. You can notice that we have built a partial class, which inherits the DNBMobileBaseDataService class for getting the data context to execute odata query.

The application will makes use of QueryDemographics with city and state as parameters , internally we are building the query based on city and state and then call LoadAsync to load the demographics information. Also by registering with the LoadComplete event, it gets fired when the query execution completes and the demographics gets loaded. 

public partial class DNBDemographicsServiceHelper : DNBMobileBaseDataService
    {
        public delegate void DemographicsDelegate(IEnumerable<Demographics> demographicsInfo);
        public event DemographicsDelegate DemographicsEvent;
        public void QueryDemographics(string city, string state)
        {
            string filterValue = "";
            var filteredDemographics = new DataServiceCollection<Demographics>();
            filteredDemographics.LoadCompleted += filteredDemographics_LoadCompleted;
            try
            {
                DomainName = DNBMobileSettingsReader.DomainName;
                UserName = DNBMobileSettingsReader.UserName;
                Password = DNBMobileSettingsReader.Password;
                var context = GetContext(DomainName, UserName, Password);
                var query = context.Demographics;
                if (!string.IsNullOrEmpty(city))
                    filterValue = string.Format("City eq '{0}'", city);
                if (!string.IsNullOrEmpty(state) && filterValue != "")
                    filterValue += string.Format("and StateAbbrv eq '{0}'", state);
                else if (!string.IsNullOrEmpty(state))
                    filterValue += string.Format("StateAbbrv eq '{0}'", state);
                query = query.AddQueryOption("$filter", filterValue);
                filteredDemographics.LoadAsync(query);
            }
            catch 
            {
                throw;
            }
        }
        void filteredDemographics_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            var filteredDemographics = sender as DataServiceCollection<Demographics>;
            if (filteredDemographics.Continuation != null)
            {
                filteredDemographics.LoadNextPartialSetAsync();
                return;
            }
            if (DemographicsEvent != null && filteredDemographics != null)
            {
                var filteredDemographicsList = (from demographics in filteredDemographics
                                                select demographics).ToList();
                DemographicsEvent(filteredDemographicsList);
            }
            else
            {
                DemographicsEvent(new List<Demographics>());
            }
        }      
    } 

Below is the screenshot for Demographics Search




There's an option to view Public Records and Location Information. Here's the screenshot which shows up on click on "Location Info" button. 



Here's the code snippet which for the same. Notice that we are fetching the location information based on the DunsNumber. 

private void LocationInfoButton_Click(object sender, RoutedEventArgs e)
{
            var LocationInfoButton = sender as Button;
            var dnbMobileDataService = new DNBDemographicsServiceHelper();
            dnbMobileDataService.LocatoinLatLongEvent += dnbMobileDataService_LocationLatLongEvent;
            dnbMobileDataService.GetLocationLatLongByDunsNumber(LocationInfoButton.Tag.ToString());
}

void dnbMobileDataService_LocationLatLongEvent(IEnumerable<DNBDeveloperSandboxContainer.LocationLatLong> locationLatLongInfo)
{
            MessagePrompt messagePrompt = new MessagePrompt();
            messagePrompt.Title = "Location Info";
            if (locationLatLongInfo.Count() > 0)
            {
                var ucLocationLatLong = new UCLocationLatLong();
                double latitude = 0;
                double longitude = 0;
                double.TryParse(locationLatLongInfo.First().Latitude, out latitude);
                double.TryParse(locationLatLongInfo.First().Longitude, out longitude);
                ucLocationLatLong.SetLocation(latitude, longitude);
                messagePrompt.Body = ucLocationLatLong;
            }
            else
            {
                messagePrompt.Body = "No records";
            }
            messagePrompt.Show();    
} 

Here's the XAML code snippet which is responsible for displaying the Map. We need to make use Microsoft.Phone.Maps assembly in order to render the maps.

One has to include the following thing in a PhoneApplication Page or UserControl.

xmlns:maps="clr-namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps" 

<Grid x:Name="ContentPanel" Background="{StaticResource PhoneChromeBrush}">
        <maps:Map
            x:Name="map"
            CartographicMode="Road"
            ColorMode="Light"
            PedestrianFeaturesEnabled="True"
            LandmarksEnabled="True"
            Height="600"
            Width="500"
            />
    </Grid> 

Here's the code behind which sets the location information and adds map layer.

public void SetLocation(double latitude, double longitude)
{
     AddMapLayer(new GeoCoordinate(latitude, longitude), Colors.Red);
}

private void AddMapLayer(GeoCoordinate geo, System.Windows.Media.Color color)
{
     map.Layers.Add(new MapLayer()
     {
          new MapOverlay()
          {
              GeoCoordinate = geo,
              PositionOrigin = new Point(0.5,0.5),
              Content = new Ellipse
              {
                  Fill = new SolidColorBrush(color),
                  Width = 10,
                  Height = 10
              }
           }
     });
     map.Center = geo;
     map.ZoomLevel = 16;
}  

Below is the code snippet for fetching the Firmographics information by DunsNumber , also based on State and City. 

Note we are using the same mechanism of building query , executing the same by calling LoadAsync , when the Load completes we will be returning the filtered list of firmographics.   

public partial class DNBDemographicsServiceHelper : DNBMobileBaseDataService
    {
        public delegate void FirmographicsDelegate(IEnumerable<Firmographics> firmographicsInfo);
        public event FirmographicsDelegate FirmographicsEvent;
        public void GetFirmographicsInfoByDunsNumber(string dunsNumber)
        {
            string filterValue = "";
            var filteredFirmographics = new DataServiceCollection<Firmographics>();
            filteredFirmographics.LoadCompleted += firmographicsByDunsNumber_LoadCompleted;
            try
            {
                DomainName = DNBMobileSettingsReader.DomainName;
                UserName = DNBMobileSettingsReader.UserName;
                Password = DNBMobileSettingsReader.Password;
                var context = GetContext(DomainName, UserName, Password);
                var query = context.Firmographics;
                filterValue += string.Format("DUNSNumber eq '{0}'", dunsNumber);
                query = query.AddQueryOption("$filter", filterValue);
                filteredFirmographics.LoadAsync(query);
            }
            catch
            {
                throw;
            }
        }
        void firmographicsByDunsNumber_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            var filteredFirmographics = sender as DataServiceCollection<Firmographics>;
            if (FirmographicsEvent != null)
                FirmographicsEvent(filteredFirmographics);  
        }
        public void QueryFirmographics(string city, string state)
        {
            string filterValue = "";
            var filteredFirmographics = new DataServiceCollection<Firmographics>();
            filteredFirmographics.LoadCompleted += filteredFirmographics_LoadCompleted;
            try
            {
                DomainName = DNBMobileSettingsReader.DomainName;
                UserName = DNBMobileSettingsReader.UserName;
                Password = DNBMobileSettingsReader.Password;
                var context = GetContext(DomainName, UserName, Password);
                var query = context.Firmographics;
                if (!string.IsNullOrEmpty(city))
                    filterValue = string.Format("City eq '{0}'", city);
                if (!string.IsNullOrEmpty(state) && filterValue != "")
                    filterValue += string.Format("and StateAbbrv eq '{0}'", state);
                else if (!string.IsNullOrEmpty(state))
                    filterValue += string.Format("StateAbbrv eq '{0}'", state);
                query = query.AddQueryOption("$filter", filterValue);
                filteredFirmographics.LoadAsync(query);
            }
            catch
            {
                throw;
            }
        }
        void filteredFirmographics_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            var filteredFirmographics = sender as DataServiceCollection<Firmographics>;
            if (filteredFirmographics.Continuation != null)
            {
                filteredFirmographics.LoadNextPartialSetAsync();
                return;
            }
            if (FirmographicsEvent != null && filteredFirmographics != null)
                FirmographicsEvent(filteredFirmographics);
            else
                FirmographicsEvent(new List<Firmographics>());
        } 

Here's the application screenshot for showing the firmographics information. 

 

You can see below the screen has More Info button which shows up more information about the firmographics. Below is the screenshot.



Below is the code snippet or code behind for displaying the Green Certified Companies. We are filtering the green business companies based on State and City. There is also an option for filtering by small business companies. That's done with the help of an indicator IsSmallBusiness. 

 public partial class DNBDemographicsServiceHelper : DNBMobileBaseDataService
    {
        public delegate void GreenCertifiedDelegate(IEnumerable<Green> greenCertifiedCompaniesInfo);
        public event GreenCertifiedDelegate GreenCertifiedEvent;
        private bool? IsSmallBusiness { get; set; }
        public void QueryGreenCertifiedCompanies(string city, string state, bool? isSmallBusiness)
        {
            IsSmallBusiness = isSmallBusiness;
            string filterValue = "";
            var filteredGreenCertifiedCompanies = new DataServiceCollection<Green>();
            filteredGreenCertifiedCompanies.LoadCompleted += filteredGreenCertifiedCompanies_LoadCompleted;
            try
            {
                DomainName = DNBMobileSettingsReader.DomainName;
                UserName = DNBMobileSettingsReader.UserName;
                Password = DNBMobileSettingsReader.Password;
                var context = GetContext(DomainName, UserName, Password);
                var query = context.Green;
                if (!string.IsNullOrEmpty(city))
                    filterValue = string.Format("City eq '{0}'", city);
                if (!string.IsNullOrEmpty(state) && filterValue != "")
                    filterValue += string.Format("and StateAbbrv eq '{0}'", state);
                else if (!string.IsNullOrEmpty(state))
                    filterValue += string.Format("StateAbbrv eq '{0}'", state);
                query = query.AddQueryOption("$filter", filterValue);
                filteredGreenCertifiedCompanies.LoadAsync(query);
            }
            catch 
            {
                throw;
            }
        }
        void filteredGreenCertifiedCompanies_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            var filteredGreenCertifiedCompanies = sender as DataServiceCollection<Green>;
            if (filteredGreenCertifiedCompanies.Continuation != null)
            {
                filteredGreenCertifiedCompanies.LoadNextPartialSetAsync();
                return;
            }
            if (GreenCertifiedEvent != null && filteredGreenCertifiedCompanies != null)
            {
                IEnumerable<Green> filteredGreenCertifiedList = new List<Green>();
                if (IsSmallBusiness != null && IsSmallBusiness.Value)
                {
                    filteredGreenCertifiedList = (from greenCertified in filteredGreenCertifiedCompanies
                                                  where greenCertified.SmallBusinessIndicator == "Y"
                                                  select greenCertified).ToList();
                }
                else
                {
                    filteredGreenCertifiedList = (from greenCertified in filteredGreenCertifiedCompanies
                                                  select greenCertified).ToList();
                }
                GreenCertifiedEvent(filteredGreenCertifiedList);
            }
            else
            {
                GreenCertifiedEvent(new List<Green>());
            }
        }
    } 

Here's the screenshot for showing the Green certified companies.

Below is the code snippet for showing all the companies by Geo Location. We are getting all the nearby companies based on the Latitude and Longitude. Shortly we will be seeing the code snippet on making use of GeoLocator , a windows phone framework class to get the Lat and Long. 

 public partial class DNBDemographicsServiceHelper : DNBMobileBaseDataService
    {
        public delegate void LocationLatLongDelegate(IEnumerable<LocationLatLong> locationLatLongInfo);
        public event LocationLatLongDelegate LocatoinLatLongEvent;
        private double Latitude { get; set; }
        private double Longitude { get; set; }
        private double Distance { get; set; }
        private string Country { get; set; }

        public void GetLocationLatLongByDunsNumber(string dunsNumber)
        {
            try
            {
                DomainName = DNBMobileSettingsReader.DomainName;
                UserName = DNBMobileSettingsReader.UserName;
                Password = DNBMobileSettingsReader.Password;
                var context = GetContext(DomainName, UserName, Password);
                var query = context.LocationLatLong;
                var filteredLocationLatLong = new DataServiceCollection<LocationLatLong>();
                filteredLocationLatLong.LoadCompleted += filteredLocationLatLong_LoadCompleted;
                string filterValue = "";
                filterValue += string.Format("DUNSNumber eq '{0}'", dunsNumber);
                query = query.AddQueryOption("$filter", filterValue);
                filteredLocationLatLong.LoadAsync(query);
            }
            catch
            {
                throw;
            }      
        }
        /// <summary>
        /// Search nearby comanpies. We are doing Async return of List Of LocationLatLong information
        /// The D & B Sanbox data for LocationLatLong is not indexed for Latitude, Longitude and Country fields
        /// As of now we have the parameters for lat, long and country as placeholders. At this point we are not doing anything this these params.
        /// </summary>
        /// <param name="latitude">Latitude</param>
        /// <param name="longitude">Longitude</param>
        /// <param name="city">City</param>
        /// <param name="country">Country</param>
        public void SearchNearByCompanies(double latitude, double longitude, string city, string country)
        {
            this.Latitude = latitude;
            this.Longitude = longitude;
            this.Country = country;
            try
            {
                DomainName = DNBMobileSettingsReader.DomainName;
                UserName = DNBMobileSettingsReader.UserName;
                Password = DNBMobileSettingsReader.Password;
                var context = GetContext(DomainName, UserName, Password);
                var query = context.LocationLatLong;
                var filteredLocationLatLong = new DataServiceCollection<LocationLatLong>();
                filteredLocationLatLong.LoadCompleted += filteredLocationLatLong_LoadCompleted;
                string filterValue = "";
                if (!string.IsNullOrEmpty(city))
                    filterValue = string.Format("City eq '{0}'", city);
                query = query.AddQueryOption("$filter", filterValue);
                filteredLocationLatLong.LoadAsync(query);
            }
            catch 
            {
                throw;
            }      
        }
        void filteredLocationLatLong_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            var filteredLocationLatLong = sender as DataServiceCollection<LocationLatLong>;
            if (filteredLocationLatLong.Continuation != null)
            {
                filteredLocationLatLong.LoadNextPartialSetAsync();
                return;
            }
            if (LocatoinLatLongEvent != null && filteredLocationLatLong != null)
                LocatoinLatLongEvent(filteredLocationLatLong);
            else
                LocatoinLatLongEvent(new List<LocationLatLong>());
        }     
    } 

Below is the screenshot shows the companies by GeoLocation. 



Here's the code snippet for getting the GeoLocation. What we are doing here is , creating an instance of GeoLocator and calling GetGeopositionAsync method to get the geo location. You could also notice we are making use of ReverseGeocodeQuery for getting the address. We need to know the city name based on the geo location. Once we get the latitude , longitude and city name , we can query and get all the LocationLatLong information.

  Geolocator geoLocator = new Geolocator();
  async private void GetGeoLocation()
        {
            var geoLocation = await geoLocator.GetGeopositionAsync();
            txtLongitude.Text = geoLocation.Coordinate.Longitude.ToString();
            txtLatitude.Text = geoLocation.Coordinate.Latitude.ToString();
            msgPrompt.Hide();
            if (reverseGeocodeQuery == null || !reverseGeocodeQuery.IsBusy)
            {
                reverseGeocodeQuery = new ReverseGeocodeQuery();
                reverseGeocodeQuery.GeoCoordinate = new GeoCoordinate(geoLocation.Coordinate.Latitude, geoLocation.Coordinate.Longitude);
                reverseGeocodeQuery.QueryCompleted += reverseGeocode_QueryCompleted;
                reverseGeocodeQuery.QueryAsync();
            }
        }
        void reverseGeocode_QueryCompleted(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
        {
            if (e.Error == null)
            {
                if(e.Result.Count > 0 )
                    geoAddress = e.Result[0].Information.Address;
            }               
        } 

Here's the code snippet for Location search

private void SeachNearByCompanies_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var dnbMobileDataService = new DNBDemographicsServiceHelper();
                dnbMobileDataService.LocatoinLatLongEvent += dnbMobileDataService_LocationLatLongEvent;
                dnbMobileDataService.SearchNearByCompanies(double.Parse(txtLatitude.Text.Trim()),
                                                           double.Parse(txtLongitude.Text.Trim()),
                                                           geoAddress.City,
                                                           geoAddress.Country
                                                           );
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void dnbMobileDataService_LocationLatLongEvent(IEnumerable<LocationLatLong> locationLatLongInfo)
        {
            lblTotalNumberOfRecords.Visibility = System.Windows.Visibility.Visible;
            lblTotalNumberOfRecords.Text = "Total Count : " + locationLatLongInfo.Count();
            this.NearByCompaniesListBox.ItemsSource = locationLatLongInfo;
        } 

Below is the code snippet for getting the Women owned companies. 

 public partial class DNBDemographicsServiceHelper : DNBMobileBaseDataService
    {
        public delegate void WomenOwnedDelegate(IEnumerable<Women> womenOwnedCompaniesInfo);
        public event WomenOwnedDelegate WomenOwnedEvent;
        public void QueryWomenOwnedCompanies(string city, string state)
        {
            string filterValue = "";
            var filteredWomenOwnedCompanies = new DataServiceCollection<Women>();
            filteredWomenOwnedCompanies.LoadCompleted += filteredWomenOwnedCompanies_LoadCompleted;
            try
            {
                DomainName = DNBMobileSettingsReader.DomainName;
                UserName = DNBMobileSettingsReader.UserName;
                Password = DNBMobileSettingsReader.Password;
                var context = GetContext(DomainName, UserName, Password);
                var query = context.Women;
                if (!string.IsNullOrEmpty(city))
                    filterValue = string.Format("City eq '{0}'", city);
                if (!string.IsNullOrEmpty(state) && filterValue != "")
                    filterValue += string.Format("and StateAbbrv eq '{0}'", state);
                else if (!string.IsNullOrEmpty(state))
                    filterValue += string.Format("StateAbbrv eq '{0}'", state);
                query = query.AddQueryOption("$filter", filterValue);
                filteredWomenOwnedCompanies.LoadAsync(query);
            }
            catch 
            {
                throw;
            }
        }

        void filteredWomenOwnedCompanies_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            var filteredWomenOwnedCompanies = sender as DataServiceCollection<Women>;
            if (filteredWomenOwnedCompanies.Continuation != null)
            {
                filteredWomenOwnedCompanies.LoadNextPartialSetAsync();
                return;
            }
            if (WomenOwnedEvent != null)
            {
                var filteredWomenOwnedList = (from demographics in filteredWomenOwnedCompanies
                                                  select demographics).ToList();
                WomenOwnedEvent(filteredWomenOwnedList);
            }
        }
    } 

Here's the screenshot for the Women owned companies.

 

Below is the code snippet for City Crime Service. An helper class for getting the city crime information. Note , we are making use of windows data mart service i.e data.gov for getting the crime information. The application will make use of the helper method , QueryCrimeInfo with the city and state name to query and return the crime information. 

public class USCrimeServiceHelper
    {
        private const string azureDataUrl = "https://api.datamarket.azure.com/Data.ashx/data.gov/Crimes/";
        public delegate void CrimeDelegate(List<CityCrime> cityCrimeInfo);
        public event CrimeDelegate CrimeEvent;
        private static datagovCrimesContainer GetContext()
        {
            var _Uri = new Uri(azureDataUrl);
            var _Context = new datagovCrimesContainer(_Uri)
            {
                Credentials = new NetworkCredential(DNBMobileSettingsReader.UserName, DNBMobileSettingsReader.Password)
            };
            return _Context;
        }
        public void QueryCrimeInfo(string city, string state)
        {
            var filteredCityCrimes = new DataServiceCollection<CityCrime>();
            filteredCityCrimes.LoadCompleted += Crime_LoadCompleted;
            var query = GetContext().CityCrime;
            string filterValue = "";
            if (!string.IsNullOrEmpty(city))
                filterValue = string.Format("City eq '{0}'", city);
            if (!string.IsNullOrEmpty(state) && filterValue != "")
                filterValue += string.Format("and State eq '{0}'", state);
            else if (!string.IsNullOrEmpty(state))
                filterValue += string.Format("State eq '{0}'", state);
            query = query.AddQueryOption("$filter", filterValue);
            filteredCityCrimes.LoadAsync(query);
        }
        void Crime_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            var filteredCityCrimes = sender as DataServiceCollection<CityCrime>;
            if (filteredCityCrimes.Continuation != null)
            {
                filteredCityCrimes.LoadNextPartialSetAsync();
                return;
            }
            if (CrimeEvent != null)
                CrimeEvent(filteredCityCrimes.ToList());
            else
                CrimeEvent(new List<CityCrime>());
        }
    } 

Below is the screenshot which displays the city crime info. 

 

Below is the code snippet of City Crime Info page. 

private List<string> GetStates()
        {
            return new List<string>()
            {
               "Alabama",
	           "Alaska",
	           "Arizona",
	           "Arkansas",
	           "California",
	           "Colorado",
	           "Connecticut",
	            "Delaware",
	            "District Of Columbia",
	            "Florida",
	            "Georgia",
	            "Hawaii",
	            "Idaho",
	            "Illinois",
	            "Indiana",
	            "Iowa",
	            "Kansas",
	            "Kentucky",
	            "Louisiana",
	            "Maine",
	            "Maryland",
	            "Massachusetts",
	            "Michigan",
	            "Minnesota",
	            "Mississippi",
	            "Missouri",
	            "Montana",
	            "Nebraska",
	            "Nevada",
	            "New Hampshire",
	            "New Jersey",
	            "New Mexico",
	            "New York",
	            "North Carolina",
	            "North Dakota",
	            "Ohio",
	            "Oklahoma",
	            "Oregon",
	            "Pennsylvania",
	            "Rhode Island",
	            "South Carolina",
	            "South Dakota",
	            "Tennessee",
	            "Texas",
	            "Utah",
	            "Vermont",
	            "Virginia",
	            "Washington",
	            "West Virginia",
	            "Wisconsin",
	            "Wyoming"
            };
        }
        
        void BindCrimeInfo(List<CityCrimeService.CityCrime> cityCrimeInfo)
        {
            lblTotalNumberOfRecords.Visibility = System.Windows.Visibility.Visible;
            lblTotalNumberOfRecords.Text = "Total Count : " + cityCrimeInfo.Count;
            listBoxCrimeInfo.ItemsSource = cityCrimeInfo;
            SystemTray.SetIsVisible(this, false);
        }

        private void SearchCrimes(object sender, RoutedEventArgs e)
        {
            try
            {
                var crimeServiceHelper = new USCrimeServiceHelper();
                crimeServiceHelper.CrimeEvent += BindCrimeInfo;
                SystemTray.SetIsVisible(this, true);
                crimeServiceHelper.QueryCrimeInfo(txtCity.Text.Trim(), listPicker.SelectedItem.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        } 

Now let us see the application settings screen. Below is the screenshot for the same. It's limited with the Domain, Username and Password. Internally the application consumes windows data mart Uri. One has to provide a valid windows live id and primary account key it's required for accessing the secure service in data mart.



Here's the logic for saving the application settings in IsolatedStorageSettings.

  private void SaveSettings(object sender, RoutedEventArgs e)
  {
            if (Validate() == false) return;

            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

            // Save Domain
            if (!settings.Contains("Domain"))
                settings.Add("Domain", txtDomainName.Text);
            else
                settings["Domain"] = txtDomainName.Text;
       
            // Save UserName
            if (!settings.Contains("UserName"))
                settings.Add("UserName", txtUserName.Text);
            else
                settings["UserName"] = txtUserName.Text;
       
            // Save Password
            if (!settings.Contains("Password"))
                settings.Add("Password", txtPassword.Password);
            else
                settings["Password"] = txtPassword.Password;
             
            settings.Save();

            MessageBox.Show("Saved Sucessfully!");
 }    

Now let us see the application settings reader. We will be using that to read the application settings from IsolatedStorageSettings.

public static class DNBMobileSettingsReader
    {
        private static IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        public static string DomainName
        {
            get
            {
                if (!settings.Contains("Domain"))
                    throw new Exception("Could not find a key named 'Domain' in IsolatedStorageSettings");
                return settings["Domain"].ToString();
            }
        }

        public static string UserName
        {
            get
            {
                if (!settings.Contains("UserName"))
                    throw new Exception("Could not find a key named 'UserName' in IsolatedStorageSettings");
                return settings["UserName"].ToString();
            }
        }

        public static string Password
        {
            get
            {
                if (!settings.Contains("Password"))
                    throw new Exception("Could not find a key named 'Password' in IsolatedStorageSettings");
                return settings["Password"].ToString();
            }
        }

        public static string Country
        {
            get
            {
                if (!settings.Contains("Country"))
                    throw new Exception("Could not find a key named 'Country' in IsolatedStorageSettings");
                return settings["Country"].ToString();
            }
        }
    } 

DNB Mash-up Service

It's a WCF service , hosted in window azure as a cloud service. As of now the consumers of this service is our DNB Business Lookup and Analytic's Windows Store Application.  

We will see the necessity of implementing D & B Mash-up service and then later we will see in details about it's usage in Windows Store Application. 
What does the mash-up's do for us ? 

The mash-up's combine data from multiple entities. We will be querying multiple entities and return the data based on the user request. Some times the mash up's comes with fetching the data from multiple sources. 

Consider an example of fetching the city crime information , one can make use of Data.gov a windows data mart service for querying the crime information based on the given State and City. Below you will see some of the data mash-up's implemented by combining various D & B sandbox entities. 

Here's what the service implements.  

1. Get all women owned companies which are green certified.

2. Get all women owned minority companies.

3. Get all women owned veteran companies.

4. Get all women owned minority and veteran companies. 

5. Get all Veteran minority companies.   

Below is the code snippet for the service contract 

    [ServiceContract]
    public interface IDNBService
    {
        [OperationContract]
        List<Women> GetAllWomenOwnedCompanies(string cityName, string state, string zipCode, string country);

        [OperationContract]
        List<Green> GetAllGreenCertifiedCompanies(string cityName, string state, string zipCode, string country);

        [OperationContract]
        List<Minority> GetAllMinorityCompanies(string cityName, string state, string zipCode, string country);

        [OperationContract]
        List<Women> GetAllWomenOwnedCompaniesWhichAreGreenCertified(string cityName, string state, string zipCode, string country);

        [OperationContract]
        List<Women> GetAllWomenOwnedMinorityCompanies(string cityName, string state, string zipCode, string country);

        [OperationContract]
        List<Women> GetAllWomenOwnedVetranCompanies(string cityName, string state, string zipCode, string country);

        [OperationContract]
        List<Women> GetAllWomenOwnedMinorityAndVetranCompanies(string cityName, string state, string zipCode, string country);

        [OperationContract]
        List<Veteran> GetAllVetranMinorityCompanies(string cityName, string state, string zipCode, string country);
    }    

Let us see the service implementation. 

Here's the service configuration. We need to have an application key for Service Uri , Username I.e the windows live id and Primary account key. 

<appSettings>
    <add key="UserName" value="<YourWindowLiveId>"/>
    <add key="PrimaryAccountKey" value="<YourPrimaryAccountKey>"/>
    <add key="DataServiceUri" value="https://api.datamarket.azure.com/DNB/DeveloperSandbox/v1">
</appSettings> 

Below is the code snippet for getting all women owned green certified companies. Here's the logic , 

1. Get all green certified companies based on the filtered condition. i.e based on the city and state

2. Get all women owned companies based on the filtered condition. 

3. Join the filtered green certified  and the women owned companies by DunsNumber.

public List<Women> GetAllWomenOwnedCompaniesWhichAreGreenCertified(string cityName, string state, string zipCode, string country)
        {
            var allGreenCertifiedCompanies = GetAllGreenCertifiedCompanies(cityName, state, zipCode, country);
            var allWomenOwnedCompanies = GetAllWomenOwnedCompanies(cityName, state, zipCode, country);

            DNBDeveloperSandboxContainer client = new DNBDeveloperSandboxContainer(dataServiceUri);
            client.Credentials = new System.Net.NetworkCredential(primaryAccountKey, primaryAccountKey);

            return (from women in allWomenOwnedCompanies
                    join green in allGreenCertifiedCompanies on
                    women.DUNSNumber equals green.DUNSNumber
                    select women).ToList();
        } 

Below is the code snippet for getting all the filtered set of women owned and green certified companies. 

public List<Women> GetAllWomenOwnedCompanies(string cityName, string state, string zipCode, string country)
        {
            List<Women> womenOwnedCompaniesList = new List<Women>();
            DNBDeveloperSandboxContainer client = new DNBDeveloperSandboxContainer(dataServiceUri);
            client.Credentials = new System.Net.NetworkCredential(primaryAccountKey, primaryAccountKey);

            string filterValue = "";
            DataServiceQueryContinuation<Women> token = null;

            var query = client.CreateQuery<Women>("Women");

            if (!string.IsNullOrEmpty(cityName))
                filterValue = string.Format("City eq '{0}'", cityName);
            if (!string.IsNullOrEmpty(state) && filterValue != "")
                filterValue += string.Format("and StateAbbrv eq '{0}'", state);
            else if (!string.IsNullOrEmpty(state))
                filterValue += string.Format("StateAbbrv eq '{0}'", state);
            if (!string.IsNullOrEmpty(zipCode) && filterValue != "")
                filterValue += string.Format("and ZipCode eq '{0}'", zipCode);
            else if (!string.IsNullOrEmpty(zipCode))
                filterValue += string.Format("ZipCode eq '{0}'", zipCode);

            query = query.AddQueryOption("$filter", filterValue);

            QueryOperationResponse<Women> response = (QueryOperationResponse<Women>)query.Execute();

            do
            {
                // if response is paged, prepare next page
                if (token != null)
                {
                    response = client.Execute<Women>(token)
                      as QueryOperationResponse<Women>;
                }

                // add query results
                womenOwnedCompaniesList.AddRange(response);
            }
            // repeat for next page if needed
            while ((token = response.GetContinuation()) != null);

            if (!string.IsNullOrEmpty(country))
                return womenOwnedCompaniesList.Where(w => w.Country == country).ToList();
            else
                return womenOwnedCompaniesList;
        }

        public List<Green> GetAllGreenCertifiedCompanies(string cityName, string state, string zipCode, string country)
        {
            List<Green> greenCompaniesList = new List<Green>();
            DNBDeveloperSandboxContainer client = new DNBDeveloperSandboxContainer(dataServiceUri);
            client.Credentials = new System.Net.NetworkCredential(primaryAccountKey, primaryAccountKey);

            string filterValue = "";
            DataServiceQueryContinuation<Green> token = null;
            var query = client.CreateQuery<Green>("Green");

            if (!string.IsNullOrEmpty(cityName))
                filterValue = string.Format("City eq '{0}'", cityName);
            if (!string.IsNullOrEmpty(state) && filterValue != "")
                filterValue += string.Format("and StateAbbrv eq '{0}'", state);
            else if (!string.IsNullOrEmpty(state))
                filterValue += string.Format("StateAbbrv eq '{0}'", state);
            if (!string.IsNullOrEmpty(zipCode) && filterValue != "")
                filterValue += string.Format("and ZipCode eq '{0}'", zipCode);
            else if (!string.IsNullOrEmpty(zipCode))
                filterValue += string.Format("ZipCode eq '{0}'", zipCode);

            query = query.AddQueryOption("$filter", filterValue);

            QueryOperationResponse<Green> response = (QueryOperationResponse<Green>)query.Execute();

            do
            {
                // if response is paged, prepare next page
                if (token != null)
                {
                    response = client.Execute<Green>(token)
                      as QueryOperationResponse<Green>;
                }

                // add query results
                greenCompaniesList.AddRange(response);
            }
            // repeat for next page if needed
            while ((token = response.GetContinuation()) != null);

            if (!string.IsNullOrEmpty(country))
                return greenCompaniesList.Where(w => w.Country == country).ToList();
            else
                return greenCompaniesList;
        }

Below is the code snippet for getting all the women owned minority companies. What we do here is , get all the filtered list of minority companies , also get all the filtered list of women owned companies. finally join both of these filtered list on DunsNumber to return the list of women owned minority companies.

public List<Women> GetAllWomenOwnedMinorityCompanies(string cityName, string state, string zipCode, string country)
        {
            var allMinorityCompanies = GetAllMinorityCompanies(cityName, state, zipCode, country);
            var allWomenOwnedCompanies = GetAllWomenOwnedCompanies(cityName, state, zipCode, country);
            DNBDeveloperSandboxContainer client = new DNBDeveloperSandboxContainer(dataServiceUri);
            client.Credentials = new System.Net.NetworkCredential(primaryAccountKey, primaryAccountKey);
            return (from women in allWomenOwnedCompanies
                    join green in allMinorityCompanies on
                    women.DUNSNumber equals green.DUNSNumber
                    select women).ToList();
        } 

Here's the code snippet for getting the filtered list of minority companies.

public List<Minority> GetAllMinorityCompanies(string cityName, string state, string zipCode, string country)
        {
            List<Minority> minorityCompaniesList = new List<Minority>();
            DNBDeveloperSandboxContainer client = new DNBDeveloperSandboxContainer(dataServiceUri);
            client.Credentials = new System.Net.NetworkCredential(primaryAccountKey, primaryAccountKey);
            string filterValue = "";
            DataServiceQueryContinuation<Minority> token = null;
            var query = client.CreateQuery<Minority>("Minority");
            if (!string.IsNullOrEmpty(cityName))
                filterValue = string.Format("City eq '{0}'", cityName);
            if (!string.IsNullOrEmpty(state) && filterValue != "")
                filterValue += string.Format("and StateAbbrv eq '{0}'", state);
            else if (!string.IsNullOrEmpty(state))
                filterValue += string.Format("StateAbbrv eq '{0}'", state);
            if (!string.IsNullOrEmpty(zipCode) && filterValue != "")
                filterValue += string.Format("and ZipCode eq '{0}'", zipCode);
            else if (!string.IsNullOrEmpty(zipCode))
                filterValue += string.Format("ZipCode eq '{0}'", zipCode);
            query = query.AddQueryOption("$filter", filterValue);
            QueryOperationResponse<Minority> response = (QueryOperationResponse<Minority>)query.Execute();
            do
            {
                // if response is paged, prepare next page
                if (token != null)
                {
                    response = client.Execute<Minority>(token)
                      as QueryOperationResponse<Minority>;
                }
                // add query results
                minorityCompaniesList.AddRange(response);
            }
            // repeat for next page if needed
            while ((token = response.GetContinuation()) != null);
            if (!string.IsNullOrEmpty(country))
                return minorityCompaniesList.Where(m => m.Country == country).ToList();
            else
                return minorityCompaniesList;
        } 

We will now see the DNB Mashup WCF Service hosting in Windows Azure as a cloud service. The whole idea of implementing the Mash-up service and deploying it to azure is to make the service available to the various clients who can consume the service in their application. Here in our case the Windows Store application will consume the same.  

First we need to log on to Windows Azure account and then create a new Cloud Service.  You can refer section "D & B Data as a Azure Service " of this article to understand on how to create, upload cloud service package, configuration etc. 

Below is the screenshot of DNB Mash-up azure cloud service running in a single core with single instance. One can browse the following service " http://dnbmashupservice.cloudapp.net/DNBMashupService.svc"  

 Here's the screenshot of the DNB Mash-up Service up and running in Windows Azure. 

 

Now we will see in reality the usage of DNB Mash-up service in Windows Store Application. Below is the screenshot of the Mash-up options available in the application. 

First and foremost the application will have to make a reference to the DNB Mash-up azure hosted service "http://dnbmashupservice.cloudapp.net/DNBMashupService.svc".



We will see below each of these mash-up and understand more on how we are making use of service and get the desired result based on the search criteria's. 

Below is the screenshot for the mash-up "Women owned veteran companies". What we are trying to do below is to get all the filtered women owned veteran companies by making use of the mash-up service. 



Here's the code snippet for the same.

 async private void SearchWomenOwnedMinorityCompanies(object sender, RoutedEventArgs e)
        {
            progressRing.IsActive = true;
            var dataMashupClient = new DNBServiceClient();
            var womenOwnedMinorityCompanies = await dataMashupClient.GetAllWomenOwnedVetranCompaniesAsync(txtCity.Text.Trim(), txtState.Text.Trim(), txtZipCode.Text.Trim(),
                txtCountry.Text.Trim());
            WomenOwnedGreenVeteranCompaniesListView.ItemsSource = womenOwnedMinorityCompanies;
            progressRing.IsActive = false;
        }

        async private void CompaniesListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dunNumber = (e.AddedItems[0] as DNBWinStoreApp.DNBMashupAzureService.Women).DUNSNumber;
            var dnbHelper = new DNBDataServiceHelper(DNBSettingsHelper.UserName, DNBSettingsHelper.Password, DNBSettingsHelper.ServiceUri);
            var demographicsInfo = await dnbHelper.GetDemographicsByDunNumber(dunNumber);
            this.Frame.Navigate(typeof(DNBCompanyBasicInfo), demographicsInfo);
        }  

Below is the screenshot for the mash-up "Women owned minority companies". Here we are making use of mash-up service to get all Women owned minority companies by joining the data from Minority and Women entities by DunsNumber.


 

Here's the code snippet on how it works internally. 

 async private void SearchWomenOwnedMinorityCompanies(object sender, RoutedEventArgs e)
 {
            progressRing.IsActive = true;
            var dataMashupClient = new DNBServiceClient();
            var womenOwnedMinorityCompanies = await dataMashupClient.GetAllWomenOwnedMinorityCompaniesAsync(txtCity.Text.Trim(), txtState.Text.Trim(), txtZipCode.Text.Trim(),
                txtCountry.Text.Trim());
            WomenOwnedMinorityCompaniesListView.ItemsSource = womenOwnedMinorityCompanies;
            progressRing.IsActive = false;
        }
        async private void CompaniesListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dunNumber = (e.AddedItems[0] as DNBWinStoreApp.DNBMashupAzureService.Women).DUNSNumber;
            var dnbHelper = new DNBDataServiceHelper(DNBSettingsHelper.UserName, DNBSettingsHelper.Password, DNBSettingsHelper.ServiceUri);
            var demographicsInfo = await dnbHelper.GetDemographicsByDunNumber(dunNumber);
            this.Frame.Navigate(typeof(DNBCompanyBasicInfo), demographicsInfo);
  } 

Below is the screenshot for Veteran minority companies. 


 
Here;s the code snippet for the same. 

  async private void SearchWomenOwnedMinorityCompanies(object sender, RoutedEventArgs e)
  {
            progressRing.IsActive = true;
            var dataMashupClient = new DNBServiceClient();
            var womenOwnedMinorityCompanies = await dataMashupClient.GetAllVetranMinorityCompaniesAsync(txtCity.Text.Trim(), txtState.Text.Trim(), txtZipCode.Text.Trim(),
                txtCountry.Text.Trim());
            VeteranMinorityCompaniesListView.ItemsSource = womenOwnedMinorityCompanies;
            progressRing.IsActive = false;
        }
        async private void CompaniesListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dunNumber = (e.AddedItems[0] as DNBWinStoreApp.DNBMashupAzureService.Veteran).DUNSNumber;
            var dnbHelper = new DNBDataServiceHelper(DNBSettingsHelper.UserName, DNBSettingsHelper.Password, DNBSettingsHelper.ServiceUri);
            var demographicsInfo = await dnbHelper.GetDemographicsByDunNumber(dunNumber);
            this.Frame.Navigate(typeof(DNBCompanyBasicInfo), demographicsInfo);
  } 

Below is the screenshot for Women owned green certified companies.

Here's the code snippet for the same. We are making use of mash-up service and getting all the women owned green certified companies by joining two different entities i.e Women and Green by DunsNumber.

 async private void SearchWomenOwnedMinorityCompanies(object sender, RoutedEventArgs e)
 {
            progressRing.IsActive = true;
            var dataMashupClient = new DNBServiceClient();
            var womenOwnedMinorityCompanies = await dataMashupClient.GetAllWomenOwnedCompaniesWhichAreGreenCertifiedAsync(txtCity.Text.Trim(), txtState.Text.Trim(), txtZipCode.Text.Trim(),
                txtCountry.Text.Trim());
            WomenOwnedGreenCertifiedCompaniesListView.ItemsSource = womenOwnedMinorityCompanies;
            progressRing.IsActive = false;
        }
        async private void CompaniesListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dunNumber = (e.AddedItems[0] as DNBWinStoreApp.DNBMashupAzureService.Women).DUNSNumber;
            var dnbHelper = new DNBDataServiceHelper(DNBSettingsHelper.UserName, DNBSettingsHelper.Password, DNBSettingsHelper.ServiceUri);
            var demographicsInfo = await dnbHelper.GetDemographicsByDunNumber(dunNumber);
            this.Frame.Navigate(typeof(DNBCompanyBasicInfo), demographicsInfo);
 } 

Below is the screenshot for the Women owned minority and veteran companies. 


 

Here's the code snippet for the same.

 async private void SearchWomenOwnedMinorityCompanies(object sender, RoutedEventArgs e)
 {
            progressRing.IsActive = true;
            var dataMashupClient = new DNBServiceClient();
            var womenOwnedMinorityCompanies = await dataMashupClient.GetAllWomenOwnedMinorityAndVetranCompaniesAsync(txtCity.Text.Trim(), txtState.Text.Trim(), txtZipCode.Text.Trim(),
                txtCountry.Text.Trim());
            WomenOwnedMinorityAndVeteranCompaniesListView.ItemsSource = womenOwnedMinorityCompanies;
            progressRing.IsActive = false;
        }
        async private void CompaniesListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dunNumber = (e.AddedItems[0] as DNBWinStoreApp.DNBMashupAzureService.Women).DUNSNumber;
            var dnbHelper = new DNBDataServiceHelper(DNBSettingsHelper.UserName, DNBSettingsHelper.Password, DNBSettingsHelper.ServiceUri);
            var demographicsInfo = await dnbHelper.GetDemographicsByDunNumber(dunNumber);
            this.Frame.Navigate(typeof(DNBCompanyBasicInfo), demographicsInfo);
 } 

DNB Windows Store App Analytic's  

We will see some of the analytic's that is done in Windows Store App. Below is the screenshot of the analytic's page.  

 

Here's the code snippet for getting the bankrupted companies. Notice that the D & B Sandbox returns the paged list of results, so we had to use "Next" and "Prev" buttons to get the next and previous set of results. 

Also you could notice we are making use of Dictionary to hold the paged records. This significantly improves the performance as we need not query the Odata but instead get the paged result if we have one in the dictionary. 

 async private void SearchCompanies(object sender, RoutedEventArgs e)
 {
            pageCount = 0;
            var dnbDataServiceHelper = new DNBDataServiceHelper(DNBSettingsHelper.UserName, DNBSettingsHelper.Password, DNBSettingsHelper.ServiceUri);
            var companyInfo = await dataServiceHelper.GetBankruptedCompanies(txtCity.Text.Trim(), txtState.Text.Trim(), txtCountry.Text.Trim(), pageCount);
            pagedPublicRecords.PublicRecordsDictionary[pageCount] = companyInfo;
            CompaniesListView.ItemsSource = companyInfo; CompaniesListView.ItemsSource = companyInfo;
            btnNext.IsEnabled = true;
            btnPrev.IsEnabled = false;
 }

async private void CompaniesListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
            var dunNumber = (e.AddedItems[0] as PublicRecords).DUNSNumber;
            var dnbHelper = new DNBDataServiceHelper(DNBSettingsHelper.UserName, DNBSettingsHelper.Password, DNBSettingsHelper.ServiceUri);
            var demographicsInfo = await dnbHelper.GetDemographicsByDunNumber(dunNumber);
            this.Frame.Navigate(typeof(DNBCompanyBasicInfo), demographicsInfo);
 }

 async private void NextButtonClick(object sender, RoutedEventArgs e)
 {
            pageCount += 1;
            if (pageCount > 0 && btnPrev.IsEnabled == false)
            {
                btnPrev.IsEnabled = true;
            }
            if (pagedPublicRecords.PublicRecordsDictionary.ContainsKey(pageCount))
                CompaniesListView.ItemsSource = pagedPublicRecords.PublicRecordsDictionary[pageCount];
            else
            {
                var companyInfo = await dataServiceHelper.GetBankruptedCompanies(txtCity.Text.Trim(), txtState.Text.Trim(), txtCountry.Text.Trim(), pageCount);
                pagedPublicRecords.PublicRecordsDictionary[pageCount] = companyInfo;
                CompaniesListView.ItemsSource = companyInfo;
            }
 }

 async private void PrevButtonClick(object sender, RoutedEventArgs e)
 {
            if (pageCount > 0)
                pageCount = pageCount - 1;
            else
            {
                pageCount = 0;
                btnPrev.IsEnabled = false;
            }
            if (pagedPublicRecords.PublicRecordsDictionary.ContainsKey(pageCount))
                CompaniesListView.ItemsSource = pagedPublicRecords.PublicRecordsDictionary[pageCount];
            else
            {
                var companyInfo = await dataServiceHelper.GetOutOfBusinessCompanies(txtCity.Text.Trim(), txtState.Text.Trim(), txtCountry.Text.Trim(), pageCount);
                pagedPublicRecords.PublicRecordsDictionary[pageCount] = companyInfo;
                CompaniesListView.ItemsSource = companyInfo;
            }
 } 

We will see some thing interesting about getting the Crime information based on the given State and City. Below is the screen shot for the same.

 
Below is the code snippet for the Crime Service Helper. Notice that we are making use of data mart service for getting the city crime information. 

 public class CrimeServiceHelper
 {
        private const string CRIME_ROOT_SERVICE_URL = "https://api.datamarket.azure.com/Data.ashx/data.gov/Crimes";
        async public Task<List<CityCrime>> GetCrimeInfo(string city, string state)
        {
            datagovCrimesContainer crimeContext = new datagovCrimesContainer(new Uri(CRIME_ROOT_SERVICE_URL));
            var query = crimeContext.CityCrime;
            string filterValue = "";
            if (!string.IsNullOrEmpty(city))
                filterValue = string.Format("City eq '{0}'", city);
            if (!string.IsNullOrEmpty(state) && filterValue != "")
                filterValue += string.Format("and State eq '{0}'", state);
            else if (!string.IsNullOrEmpty(state))
                filterValue += string.Format("State eq '{0}'", state);
            query = query.AddQueryOption("$filter", filterValue);
            var dataServiceQuery = (DataServiceQuery<CityCrime>)(query);
            TaskFactory<IEnumerable<CityCrime>> tf = new TaskFactory<IEnumerable<CityCrime>>();
            var resonse = (await tf.FromAsync(dataServiceQuery.BeginExecute(null, null),
                                       iar => dataServiceQuery.EndExecute(iar))).ToList();
            return resonse;
        }
 } 

Points of Interest      

I learnt a lot in handling Odata in Windows Store App. Playing with D & B data was so much fun, I came to know a lot about the companies demographics, financial information etc.     

Snapshots of Windows Store App

Here's the application settings. It's the first screen which gets popped up. The user has to key in their windows data mart username - Windows Live Id , Password - Primary AccountKey and then save settings in order to access the D & B Sandbox data. 


Here's the application Main screen 












History 

Version 1.0 - 7/9/2013 - Initial version , briefly explained the Windows Store Application developed.

Version 1.1 - 7/11/2013 - Updated article for DNB Cloud Service Changes. An Azure based cloud service , a new model for providing D & B customers to access the D & B data.

Version 1.2 - 7/14/2013 - Updated code for showing the company basic info, public info, firmographics info. Provided a new way of identifying companies by GeoLocation.

Version 1.3 - 7/21/2013 - Created CityCrime Lookup app, Updated article with the D & B WCF Service changes. . Released DNB Data Service Helper and CityCrime Info Application Source Code Under GPL3 Licence

Version 1.4 - 7/31/2013 - Created a Azure Cloud based Mash-up service, Created a brand new Windows Phone D & B Lookup App. Updated article for the same. Uploaded source code for Windows Store App, Windows Phone App, D & B Cloud Service , D & B Mashup Service.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

Share

About the Author

Ranjan.D
Web Developer
United States United States
Profile
 
Around 9 years of professional software development experience in analysis, design, development, testing and implementation of enterprise web applications for healthcare domain with good exposure to object-oriented design, software architectures, design patterns, test-driven development and agile practices.
 
In Brief
 
Analyse and create High Level , Detailed Design documents.
Use UML Modelling and create Use Cases , Class Diagram , Component Model , Deployment Diagram, Sequence Diagram in HLD.
 
Area of Working : Dedicated to Microsoft .NET Technologies
Experience with : C# , J2EE , J2ME, Windows Phone 8, Windows Store App
Proficient in: C# , XML , XHTML, XML, HTML5, Javascript, Jquery, CSS, SQL, LINQ, EF
 
Software Development
 
Database: Microsoft SQL Server, FoxPro
Development Frameworks: Microsoft .NET 1.1, 2.0, 3.5, 4.5
UI: Windows Forms, Windows Presentation Foundation, ASP.NET Web Forms and ASP.NET MVC3, MVC4
Coding: WinForm , Web Development, Windows Phone, WinRT Programming, WCF, WebAPI
 
Healthcare Domain Experience
 
CCD, CCR, QRDA, HIE, HL7 V3, Healthcare Interoperability
 
Others:
 
TTD, BDD
 
Education
 
B.E (Computer Science)
 
CodeProject Contest So Far:
 
1. Windows Azure Developer Contest - HealthReunion - A Windows Azure based healthcare product , link - http://www.codeproject.com/Articles/582535/HealthReunion-A-Windows-Azure-based-healthcare-pro
 
2. DnB Developer Contest - DNB Business Lookup and Analytics , link - http://www.codeproject.com/Articles/618344/DNB-Business-Lookup-and-Analytics
 
3. Intel Ultrabook Contest - Journey from development, code signing to publishing my App to Intel AppUp , link - http://www.codeproject.com/Articles/517482/Journey-from-development-code-signing-to-publishin
 
4. Intel App Innovation Contest 2013 - eHealthCare - http://www.codeproject.com/Articles/635815/eHealthCare
 
5. Grand Prize Winner of CodeProject HTML5 &CSS3 Article Content 2014

Comments and Discussions

 
Questionsource code Pinmemberkiquenet.com28-Oct-13 20:42 
AnswerRe: source code PinprofessionalRanjan.D28-Oct-13 23:49 
GeneralRe: source code Pinmemberkiquenet.com29-Oct-13 1:48 
QuestionRanjan !! the Winner!! PinprofessionalAbhishek Nandy18-Aug-13 20:12 
AnswerRe: Ranjan !! the Winner!! PinprofessionalRanjan.D19-Aug-13 9:06 
GeneralRe: Ranjan !! the Winner!! PinprofessionalAbhishek Nandy19-Aug-13 9:28 
QuestionYeeeeeeeeehhhhhhhhhhhhaaaaaaaaaaaaaaaaaaahhhhhhhhhh! PinmemberPhil Lee NZ17-Aug-13 17:49 
AnswerRe: Yeeeeeeeeehhhhhhhhhhhhaaaaaaaaaaaaaaaaaaahhhhhhhhhh! PinprofessionalRanjan.D18-Aug-13 1:45 
GeneralA mashup service is especially useful Pinmembernwhitfield15-Aug-13 18:13 
GeneralRe: A mashup service is especially useful PinprofessionalRanjan.D16-Aug-13 0:48 
GeneralMy vote of 5 Pinprofessionalroscler5-Aug-13 8:22 
GeneralRe: My vote of 5 PinprofessionalRanjan.D5-Aug-13 9:40 
GeneralRe: My vote of 5 PinmemberPhil Lee NZ17-Aug-13 17:53 
GeneralMy vote of 5 PinmemberSwatiBhat31-Jul-13 6:41 
GeneralRe: My vote of 5 PinprofessionalRanjan.D3-Aug-13 5:15 
GeneralMy vote of 5 Pinmemberrjgadag31-Jul-13 1:55 
GeneralRe: My vote of 5 PinprofessionalRanjan.D31-Jul-13 6:00 
GeneralMy vote of 5 PinprofessionalAbhishek Nandy31-Jul-13 1:53 
GeneralRe: My vote of 5 PinprofessionalRanjan.D31-Jul-13 6:00 
QuestionRelay service Pinmembermudnug30-Jul-13 21:26 
AnswerRe: Relay service PinprofessionalRanjan.D31-Jul-13 1:11 
QuestionQuery on TPL and Asynchronous pattern used Pinmembervvtrish29-Jul-13 8:41 
AnswerRe: Query on TPL and Asynchronous pattern used PinprofessionalRanjan.D29-Jul-13 11:59 
GeneralRe: Query on TPL and Asynchronous pattern used Pinmembervvtrish29-Jul-13 12:50 
GeneralRe: Query on TPL and Asynchronous pattern used PinprofessionalRanjan.D29-Jul-13 14:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140814.1 | Last Updated 2 Aug 2013
Article Copyright 2013 by Ranjan.D
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid