Category Archives: .NET

SharePoint 2013 – Could not connect to Search HostController error

When i try to move the Search crawler and other component to different server i got this error. The below powershell command solved the issue

$acl = Get-Acl HKLM:\System\CurrentControlSet\Control\ComputerName       

$person = [System.Security.Principal.NTAccount] "Users"

$access = [System.Security.AccessControl.RegistryRights]::FullControl

$inheritance = [System.Security.AccessControl.InheritanceFlags] "ContainerInherit, ObjectInherit"

$propagation = [System.Security.AccessControl.PropagationFlags]::None        

$type = [System.Security.AccessControl.AccessControlType]::Allow        

$rule = New-Object System.Security.AccessControl.RegistryAccessRule($person, $access, $inheritance, $propagation, $type)        

$acl.AddAccessRule($rule)        

Set-Acl HKLM:\System\CurrentControlSet\Control\ComputerName $acl

$sh = Get-SPServiceInstance | ? {$_.TypeName -eq "Search Host Controller Service"}

$sh.Unprovision()        

$sh.Provision($true)

 

 

Source http://mmman.itgroove.net/2012/12/search-host-controller-service-in-starting-state-sharepoint-2013-8/

Thanks

 

 

Deleted any photos? Easily fix it using this Product

Failed to connect to hosts in the cluster – SharePoint 2013

Recently got this error when i try to run the PS command to stop the Distributed cache

stop-spdistributedcacheserviceinstance

 

Eventually it happened because the “Remote Registry” service under the Services was not started in the App server. I started the service then i could able to execute the above command.

 

Fix your Microsoft Access Issue easily using this Product

How to find Concurrent Users for SharePoint and ASP.NET using IIS Logs

This post is about finding the number of concurrent users. The concurrent users helps to do the capacity planning for SharePoint. Below are the main attributes required to do the capacity planning for SharePoint 2010/2013.

Average daily RPS

Average RPS at peak time

Total number of unique users per day

Average daily concurrent users

Peak concurrent users at peak time

Total number of requests per day

 

One of the main attribute for the planning is the Concurrent users. Below are the steps required to find the concurrent users

  1. Enable the IIS Logs in the server
  2. Collect the logs for particular period
  3. Install Log Parser Tool
  4. Analyse the Log file using the Log Parser.
  5. Finally can plot a graph or use the data in any form

You can download the load.txt and the bat file in the skydrive

Step 1:

Before collecting the IIS log files, make sure the below attributes are enabled in the IIS. These attributes are the key to do analysis. The below fields can be enabled in IIS.

Field

Column name

Date

date

Time

time

Client IP Address

c-ip

User Name

cs-username

Method

cs-method

URI Stem

cs-uri-stem

Protocol Status

sc-status

Protocol SubStatus

sc-substatus

Bytes Sent

sc-bytes

Bytes Received

cs-bytes

Time Taken

time-taken

User Agent

cs-user agent

IIS Log

Step 2:

After enabling the necessary attributes, allow the application to be used for few days. After few days collect the IIS log from the c:\inetpub\logs\logfiles\. The log files will be scattered with multiple directories. Usually it is better to set s particular directory to the IIS site for easy gathering of log files. The log files will be *.log extension. Usually the analysis is done out of the server. So collect all the files and copy it to the local desktop for analysis.

Step 3:

Install the log parser tool in the local laptop or the desktop where the log files are collected. The log parser can be downloaded from the below location

http://www.microsoft.com/en-us/download/details.aspx?id=24659

After installing the logparser better to add the logparser exe path to the environment Path folder. It will be easy to execute the logparser from any directory from command prompt if added the path to environment variable PATH.

Step 4:

To get the concurrent users follow the below steps

Copy the below text into the Load.txt file

select EXTRACT_FILENAME(LogFilename),LogRow,

date, time, cs-method, cs-uri-stem, cs-username, c-ip, cs(User-Agent), cs-host, sc-status, sc-substatus, sc-bytes, cs-bytes, time-taken,

add(
   add(
      mul(3600,to_int(to_string(to_localtime(to_timestamp(date,time)),’hh’))),
      mul(60,to_int(to_string(to_localtime(to_timestamp(date,time)),’mm’)))
   ),
   to_int(to_string(to_localtime(to_timestamp(date,time)),’ss’))
) as secs,

to_int(to_string(to_localtime(to_timestamp(date,time)),’yy’)) as yy,
to_int(to_string(to_localtime(to_timestamp(date,time)),’MM’)) as mo,
to_int(to_string(to_localtime(to_timestamp(date,time)),’dd’)) as dd,

to_int(to_string(to_localtime(to_timestamp(date,time)),’hh’)) as hh,
to_int(to_string(to_localtime(to_timestamp(date,time)),’mm’)) as mi,
to_int(to_string(to_localtime(to_timestamp(date,time)),’ss’)) as ss,

to_lowercase(EXTRACT_PATH(cs-uri-stem)) as fpath, 
to_lowercase(EXTRACT_FILENAME(cs-uri-stem)) as fname, 
to_lowercase(EXTRACT_EXTENSION(cs-uri-stem)) as fext

from *.log

where sc-status401

After copying the above text into load.txt run the log parser. Assume that all the IIS files are in the c:\iislogs\. Run the command prompt in admin mode. use the commnd to navigate to the log folder say cd c:\iislogs.

In my case the log files are in d:\log files\april 2013

image

image

Run the below command in the command prompt to create a bigo.csv in the log folder which later can be used for analysis.

logparser -i:IISW3C file:load.txt -o:csv -q >bigo.csv

The above command will create a bigo.csv in the folder. I have created a bat file based on the blog mentioned here http://blogs.msdn.com/b/markarend/archive/2012/02/24/measuring-concurrent-site-users.aspx

Create a Batch file named ConCurrentUser.bat and add the below script into it

SET inputCSV=%1
if ‘%inputCSV%’==” GOTO USAGE

REM outputCSV has no extension, it’s added later
SET outputCSV=UserConcurrency

SET concurrencyPeriod=%2
if ‘%concurrencyPeriod%’==” GOTO USAGE

SET concurrencyField=%3
if ‘%concurrencyField%’==” SET concurrencyField=c-ip

REM Set a filter to match requests that should be excluded
REM %%Service%% matches our service accounts (like search), exclude them
REM …if you don’t want a filter, use SET filter=0 IS NULL
SET filter=(cs-username LIKE ‘%%Service%%’)

echo.
echo Counting Concurrent Users
echo inputCSV         : %inputCSV%
echo outputCSV        : %outputCSV%.csv
echo concurrencyField : %concurrencyField%
echo concurrencyPeriod: %concurrencyPeriod% seconds

echo.
echo First stage, quantizing to %concurrencyPeriod% seconds…
logparser -i:CSV -o:CSV “SELECT DISTINCT %concurrencyField%, date, QUANTIZE(TO_TIMESTAMP(time,’hx:mx:sx’), %concurrencyPeriod%) AS Period, COUNT(*) as Requests INTO temp1-%outputCSV%.csv FROM %inputCSV% WHERE %concurrencyField% IS NOT NULL AND NOT %filter% Group By  Date, Period, %concurrencyField%”

echo.
echo Second stage, grouping…
logparser -i:CSV -o:CSV “SELECT date, to_string(to_timestamp(Period,’hx:mx:sx’),’hh’) as Hour, Period, count(%concurrencyField%) as UserCount, sum(Requests) as RequestCount INTO temp2-%outputCSV%.csv From temp1-%outputCSV%.csv Group by date, Period”
logparser -i:CSV -o:CSV “SELECT Hour, avg(UserCount) as Concurrent-Users(q%concurrencyPeriod%), sum(RequestCount) as Total-Requests(q%concurrencyPeriod%) INTO %outputCSV%-%concurrencyPeriod%.csv From temp2-%outputCSV%.csv GROUP BY Hour ORDER BY Hour”

GOTO DONE

:USAGE

echo.
echo # Usage:
echo #
echo # ConcurrentUsers inputCSV seconds [fieldname]
echo #
echo # inputCSV : csv file (or *.csv) of log entries with fields: date, time, c-ip or [fieldname], other
echo # seconds  : concurrency quantization level.  Typical values 300 and 600 seconds
echo # fieldname: field to evaluate for concurrency.  Typical values c-ip (default) and cs-username
echo #
echo # Example  : ConcurrentUsers BigO.csv 300
echo.

:DONE

Now run the below command in the command prompt to get the concurrent users for multiple periods

ConcurrentUser BigO.csv 300

ConcurrentUser BigO.csv 1200

ConcurrentUser BigO.csv 3600

Using the result from the above command we can plot the graph in the excel.

Graph

Certification Failed, Charm Settings Privacy Policy not Added

First time when i upload the package for certification on my windows store it was failed. When i check the failed details it was stated that Privacy Policy was not added to the Charm Settings in the App. I thought it was an URL entry in the App Description page in the store release. I added the URL in the App Description section for the release and saved it again. It was again failed for certification with the same message. Then when i further analyse, i found out that we need to add the Command Privacy Policy to the Settings Charm in the App manually using the C# code.

In the App.Xaml.cs add the following lines of code

Declaration

using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;

In the OnLaunched Event add the below code.

protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            /// Above code for launching and at the last add the code below
            try
            {
                SettingsPane.GetForCurrentView().CommandsRequested += App_CommandsRequested;
            }
            catch (Exception)
            {
            }
        }
Further down add the below code
void App_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            args.Request.ApplicationCommands.Add(new SettingsCommand("privacypolicy", "Privacy Policy", OpenPrivacy));
        }

        private async void OpenPrivacy(IUICommand cmd)
        {
            Uri privacyUrl = new Uri(www.bing.com/privacy(your url here));
            await Windows.System.Launcher.LaunchUriAsync(privacyUrl);
        }

Thats it, now when you open the App and go to settings charm you can see privacy policy option. When you select the Privacy Policy it will open the IE to navigate the URL.

Enable Search Charm Settings For Windows 8 App

This blog discuss on how to enable Search Charm settings and direct the search query to the custom Search Xaml Page. Below are the steps needs to be done to enable search

  1. Enable Search Contract in VS 2012
  2. Create SearchPage.Xaml for the search result
  3. Add the code to the SearchPage.Xaml to search and show the result.
  4. Modify App.Xaml.cs to enable Search and query submit event.

 

Step 1:Enable Search Contract in VS 2012

In the Visual Studio 2012 open the App project. Once the project is loaded locate the file “Package.appxmanifest” and open it by double click on it.

image

On the windows select the declaration tab, you can see the Available Declarations. Drop down to select the Search and Add to the list below. Then save it and build.

image

Step 2: Create SearchPage.Xaml for the search result

Using the VS 2012 Basic Page template create a SearchPage.Xaml for the application. For the sample purpose i will use my App to show the screenshot of the page and the code.

image

Below is the sample Xaml from my screen

<Grid Style="{StaticResource LayoutRootStyle}">
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="1">
            <TextBlock Margin="15,0,0,0" Text="Search Results" FontSize="25" FontStyle="Oblique"/>
            <ItemsControl Margin="15" Name="lstLinks" Width="450" HorizontalAlignment="Left" >
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <HyperlinkButton Content="{Binding Path=Name}" Tag="{Binding Path=URL}" Click="HyperlinkButton_Click_1" FontSize="20"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </StackPanel>
        <!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button x:Name="backButton" Click="GoBack" IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}" Style="{StaticResource BackButtonStyle}"/>
            <TextBlock x:Name="pageTitle" Grid.Column="1" Text="{StaticResource AppName}" Style="{StaticResource PageHeaderTextStyle}"/>
        </Grid>
        
        <VisualStateManager.VisualStateGroups>

            <!-- Visual states reflect the application's view state -->
            <VisualStateGroup x:Name="ApplicationViewStates">
                <VisualState x:Name="FullScreenLandscape"/>
                <VisualState x:Name="Filled"/>

                <!-- The entire page respects the narrower 100-pixel margin convention for portrait -->
                <VisualState x:Name="FullScreenPortrait">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton" Storyboard.TargetProperty="Style">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PortraitBackButtonStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>

                <!-- The back button and title have different styles when snapped -->
                <VisualState x:Name="Snapped">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton" Storyboard.TargetProperty="Style">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedBackButtonStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="pageTitle" Storyboard.TargetProperty="Style">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedPageHeaderTextStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Grid>

The sample screen consists of the ItemsControl to display the search result and will navigate to the page when selected. The ItemsControl consists of hyperlink button, when click on the HyperLinkButton it navigates to the Page.

image

Step 3: Add the code to the SearchPage.Xaml to search and show the result

Add the following code to the search page xaml.cs for the search result to be handled. _searchPane_SuggestionsRequested event will search for the keyword entered with the suggestion list and show the suggested text when the user type the keyword in the search pane. ProcessSearchQuery will be fired everytime when the user press enter or click search after typing keyword. In that method we can write our processing logic. In the below sample i am matching the search keyword with the suggestion list and if it matches i am adding the suggestion text to the List. The List has the HyperLink button which will navigate to the relevant page. You can add your own code in here to process.

 

public sealed partial class SearchPage : W8.MathFormulas.Common.LayoutAwarePage
    {
        private SearchPane _searchPane;
        public static SearchPage Current;

        private readonly string[] _suggestedNames = { "Algebra", "Calculus", "Geometry", "Trigonometry", "Statistics" };
        public SearchPage()
        {
            this.InitializeComponent();
            Current = this;
            _searchPane = SearchPane.GetForCurrentView();

        }

        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            //searchText.Text = (string)navigationParameter;
        }

        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _searchPane.SuggestionsRequested += new TypedEventHandler<SearchPane, SearchPaneSuggestionsRequestedEventArgs>(_searchPane_SuggestionsRequested);
        }

        void _searchPane_SuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs args)
        {
            var queryText = args.QueryText;

            if (string.IsNullOrEmpty(queryText))
            {
                //searchText.Text = "Enter search keyword";
            }
            else
            {
                var request = args.Request;
                foreach (string suggestion in _suggestedNames)
                {
                    if (suggestion.StartsWith(queryText, StringComparison.CurrentCultureIgnoreCase))
                    {
                        // Add suggestion to Search Pane
                        request.SearchSuggestionCollection.AppendQuerySuggestion(suggestion);

                        // Break since the Search Pane can show at most 5 suggestions
                        if (request.SearchSuggestionCollection.Size >= 5)
                        {
                            break;
                        }
                    }
                }
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            _searchPane.SuggestionsRequested -= new TypedEventHandler<SearchPane, SearchPaneSuggestionsRequestedEventArgs>(_searchPane_SuggestionsRequested);
        }

        internal void ProcessSearchQuery(string queryText, string language)
        {
            lstLinks.Items.Clear();
            foreach (string suggestion in _suggestedNames)
            {
                if (suggestion.Contains(queryText))
                {
                    DataModel.SearchResult search = new DataModel.SearchResult();
                    search.Name = suggestion;
                    search.URL = "SplitPage.Xaml|" + suggestion;
                    lstLinks.Items.Add(search);
                }
            }
        }

        private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
        {
            HyperlinkButton btn = ((HyperlinkButton)sender);
            if (btn.Tag != null)
            {
                string urlText = btn.Tag.ToString();
                string[] parse = urlText.Split('|');
                if (parse[0] == "ItemsPage.Xaml")
                {
                    this.Frame.Navigate(typeof(ItemsPage), parse[1]);
                }
                else if (parse[0] == "SplitPage.Xaml")
                {
                    this.Frame.Navigate(typeof(SplitPage), parse[1]);
                }
            }


        }
    }

 

Step 4: Modify App.Xaml.cs to enable Search and query submit event

Now edit the App.xaml.cs file to enable the search events. Create a function called “EnsureMainPageActivatedAsync” in the App.Xaml.cs and move all the code from the OnLaunched event to the new function. Once modified the code of OnLaunched and the function EnsureMainPageActivatedAsync will look like below

protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            await EnsureMainPageActivatedAsync(args);
        }

 

async private Task EnsureMainPageActivatedAsync(IActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active

            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();
                //Associate the frame with a SuspensionManager key                                
                SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate
                    try
                    {
                        await SuspensionManager.RestoreAsync();
                    }
                    catch (SuspensionManagerException)
                    {
                        //Something went wrong restoring state.
                        //Assume there is no state and continue
                    }
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(ItemsPage), "AllGroups"))
                {
                    throw new Exception("Failed to create search page");
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }

 

I am using the Split Page Template project for the windows 8 App so you can see some code related to that at the last lines. Basically it make sure that mainpage (ItemPage) is initialised. Next step is to enable three main event for the search contract windows OnSearchActivated, OnQuerySubmitted and OnWindowCreated

 
The below event is fired when you enable search charm from desktop and touch or click on your app.
protected override async void OnSearchActivated(SearchActivatedEventArgs args)
        {
            await EnsureMainPageActivatedAsync(args);
            Frame page = (Frame)Window.Current.Content;
            if (SearchPage.Current != null)
            {
                if (page.Content.GetType().Name != "SearchPage")
                {
                    page.Navigate(typeof(SearchPage));
                }
                SearchPage.Current.ProcessSearchQuery(args.QueryText, args.Language);
            }
            else
            {
                if (page!= null)
                {
                    page.Navigate(typeof(SearchPage));
                    SearchPage.Current.ProcessSearchQuery(args.QueryText, args.Language);
                }
            }
        }
The below event is fired everytime when you type the search keyword and click on the search button or press enter. 
In the below event we check whether the search page is active if not show the page and then call the Process SearchQuery
private void OnQuerySubmitted(object sender, SearchPaneQuerySubmittedEventArgs args)
        {
            Frame page = (Frame)Window.Current.Content;
            if (SearchPage.Current != null)
            {
                if (page.Content.GetType().Name !="SearchPage")
                {
                    page.Navigate(typeof(SearchPage));
                }
                SearchPage.Current.ProcessSearchQuery(args.QueryText, args.Language);
            }
            else
            {
                if (page != null)
                {
                    page.Navigate(typeof(SearchPage));
                    SearchPage.Current.ProcessSearchQuery(args.QueryText, args.Language);
                }
            }
        }

        protected override void OnWindowCreated(WindowCreatedEventArgs args)
        {
            // Register QuerySubmitted handler for the window at window creation time and only registered once
            // so that the app can receive user queries at any time.
            SearchPane.GetForCurrentView().QuerySubmitted += new TypedEventHandler<SearchPane, SearchPaneQuerySubmittedEventArgs>(OnQuerySubmitted);
        }

wCF RIA Service to return simple types except IQuerable

WCF RIA Domain service will always return the IQuerable tyoe not the primitive types like int, or List. In some cases it is eminent that we need to just return the ID field which is int or List<string> customerList to the client not the whole table. The below sample will explain how to do it.

 

Step 1: Create the domain service by right click on the web project of the RIA Service and select New Item and select the Domain Service from the List

image

 

Step 2: Name the domain service to relevant table name in my case “CustomerService.cs”. Click on Add and the list of Tables will be displayed. Select the Customer Table. If you check Enable Editing then Insert and update methods are added to the service. Click Ok to generate the class.

image

 

Step 3: The CustomerService with the below code will be added.

[EnableClientAccess()]
   public class CustomerService : LinqToEntitiesDomainService<AdventureWorksLTEntities>
   {

       // TODO:
       // Consider constraining the results of your query method.  If you need additional input you can
       // add parameters to this method or create additional query methods with different names.
       // To support paging you will need to add ordering to the ‘Customers’ query.
       public IQueryable<Customer> GetCustomers()
       {
           return this.ObjectContext.Customers;
       }

       public void InsertCustomer(Customer customer)
       {
           if ((customer.EntityState != EntityState.Detached))
           {
               this.ObjectContext.ObjectStateManager.ChangeObjectState(customer, EntityState.Added);
           }
           else
           {
               this.ObjectContext.Customers.AddObject(customer);
           }
       }

       public void UpdateCustomer(Customer currentCustomer)
       {
           this.ObjectContext.Customers.AttachAsModified(currentCustomer, this.ChangeSet.GetOriginal(currentCustomer));
       }

       public void DeleteCustomer(Customer customer)
       {
           if ((customer.EntityState != EntityState.Detached))
           {
               this.ObjectContext.ObjectStateManager.ChangeObjectState(customer, EntityState.Deleted);
           }
           else
           {
               this.ObjectContext.Customers.Attach(customer);
               this.ObjectContext.Customers.DeleteObject(customer);
           }
       }
   }                      

 

Step 4: Now add the new method which adds the primitive type.

The first method will return the string and the second method will return List of string.

[Invoke]
       public string GetCustomerEmailId(int customerId)
       {
           var sal = from c in this.ObjectContext.Customers where c.CustomerID == customerId select c.EmailAddress;
           return sal.FirstOrDefault().ToString();
       }

       [Invoke]
       public List<string> GetEmailList(string customerName)
       {
           var salList = from c in this.ObjectContext.Customers where c.FirstName.StartsWith(customerName) select c.EmailAddress;
           return salList.ToList();
       }

Step 5: Build the solution to create a proxy file for the client. Now navigate to the silverlight project and add the below code for calling the service. Basically in the below code i have declared 2 property EmailId and EmailList. Inherited the MainPage from INotifyPropertyChanged to trigger the property change for Xaml to update. Then called the webservice and set these property.

 

using Projectname.Web.Services;
using System.ServiceModel.DomainServices.Client;

public partial class MainPage : Page, INotifyPropertyChanged
    {
        private string _email = string.Empty;
        private List<string> _emailList = null;
        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public MainPage()
        {
            InitializeComponent();
            this.DataContext = this;
            MyCustomerContext ctx = new CustomerContext();
            ctx.GetCustomerEmailId(2, EmailIdCompleted,null);
        }

        public string EmailID
        {
            get
            {
                return _email;
            }
            set
            {
                _email = value;
                this.RaisePropertyChanged("EmailID");
            }
        }

        public List<string> EmailList
        {
            get
            {
                return _emailList;
            }
            set
            {
                _emailList = value;
                this.RaisePropertyChanged("EmailList");
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void exitApp_Click(object sender, RoutedEventArgs e)
        {
            try
            {
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void GetEmailsButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CustomerContext ctx = new CustomerContext();
                ctx.GetEmailList(NameTextBox.Text, EmailListCompleted, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void EmailListCompleted(InvokeOperation<IEnumerable<string>> args)
        {
            this.EmailList = args.Value.ToList();
        }

        private void EmailIdCompleted(InvokeOperation<string> args)
        {
            this.EmailID = args.Value.ToString();
        }
    }

Step 6: Add the same to the XAML for the Binding

 

<navigation:Page
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           mc:Ignorable="d"
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           d:DesignWidth="1024" d:DesignHeight="768"
           Title="CustomerByDate Page" xmlns:riaControls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.DomainServices" xmlns:my="clr-namespace:BusinessApplication2.Web.Models" xmlns:my1="clr-namespace:BusinessApplication2.Web.Services" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit">
    <Grid x:Name="LayoutRoot">
        <StackPanel>
            <Border BorderBrush="Gray" Margin="2,2,2,2" BorderThickness="2,2,2,2" Background="Black" HorizontalAlignment="Stretch" Height="40">
                <TextBlock Text="Sample using simple data type value return on RIA Service" FontSize="20" Foreground="White" />
            </Border>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center">
                <TextBlock VerticalAlignment="Center" Text="Enter name to search:" Margin="5,0,5,0" />
                <TextBox Text="{Binding Path=CustomerName}" Margin="5,0,5,0" Width="163" Name="NameTextBox"/>
                <Button Margin="5,0,5,0" Name="GetEmailsButton" Click="GetEmailsButton_Click" Width="111" Height="30" Content="Get Emails"/>
                <ComboBox Name="CustomerList" ItemsSource="{Binding EmailList}" Width="247" Height="25" Margin="2,0,5,0"/>
                <TextBlock VerticalAlignment="Center" Text="Email Address = " Margin="5,0,5,0" />
                <TextBox Text="{Binding Path=EmailID}" Margin="5,0,5,0" Width="163"/>
            </StackPanel>
        </StackPanel>
    </Grid>
</navigation:Page>

 

Below is the Executed code.

 

image

Calling WCF RIA Service from Code behind

Assume that there is a RIA Service usually under ProjectName.Web and inside the Service folder with the file name ArtifactService.cs and with the below implementation

 

namespace ProjectName.Web.Services
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Data;
    using System.Linq;
    using System.ServiceModel.DomainServices.EntityFramework;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;
    using ProjectName.Web.Models;

    [EnableClientAccess()]
    public class ArtifactService : LinqToEntitiesDomainService<PROJEntities>
    {

        public IQueryable<Artifact> GetArtifacts()
        {
            return this.ObjectContext.Artifacts;
        }

        public IQueryable<Artifact> GetArtifactById(string projectId)
        {
            if (!string.IsNullOrEmpty(projectId))
            {
                Guid filterValue = Guid.Parse(projectId);
                return this.ObjectContext.Artifacts.Where(i => i.ProjectId == filterValue);
            }
            else
            {
                return null;
            }
        }
        public void InsertArtifact(Artifact artifact)
        {
            if ((artifact.EntityState != EntityState.Detached))
            {
                this.ObjectContext.ObjectStateManager.ChangeObjectState(artifact, EntityState.Added);
            }
            else
            {
                this.ObjectContext.Artifacts.AddObject(artifact);
            }
        }

        public void UpdateArtifact(Artifact currentArtifact)
        {
            this.ObjectContext.Artifacts.AttachAsModified(currentArtifact, this.ChangeSet.GetOriginal(currentArtifact));
        }

        public void DeleteArtifact(Artifact artifact)
        {
            if ((artifact.EntityState != EntityState.Detached))
            {
                this.ObjectContext.ObjectStateManager.ChangeObjectState(artifact, EntityState.Deleted);
            }
            else
            {
                this.ObjectContext.Artifacts.Attach(artifact);
                this.ObjectContext.Artifacts.DeleteObject(artifact);
            }
        }
    }
}

 

In the MainPage.cs we can execute the service with the below way

 

using ProjectName.Web.Services;
using ProjectName.Web.Models;
using System.ServiceModel.DomainServices.Client;

public partial class MainPage : UserControl
    {
public MainPage()
        {
            InitializeComponent();
ArtifactContext raCtx = new ArtifactContext();
                        raCtx.Load(raCtx.GetArtifactByIdQuery("id parameter"), new Action<LoadOperation<Artifact>>(ArtifactLoaded), false);
                        raCtx = null;
         }
        
private void ArtifactLoaded(LoadOperation<Artifact> args)
         {
             datagridData.AutoGenerateColumns = true;
             datagridData.ItemsSource = args.Entities;
             if (args.Entities.Count() > 0)
             {
                 datagridData.SelectedIndex = 0;
             }
             else
             {
                 datagridData.ItemsSource = null;
             }
        }
    }

Datagrid cell coloring and Header Style Wrapping using XAML

Sometime there is a need to change the Datagrid header text to wrap and change the width and the style. The below sample will discuss about the coloring and changing the header style

 

The full source is available here in the SkyDrive

 

Preview of the code

image

 

XAML:

First the Styles needed for the Cell

 

<Style x:Key="dataGridHeaderStyle" TargetType="dataprimitives:DataGridColumnHeader">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" TextWrapping="Wrap" TextAlignment="Center" />
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="RAGCellBorderStyle" TargetType="Border">
            <Setter Property="HorizontalAlignment" Value="Stretch" />
            <Setter Property="VerticalAlignment" Value="Stretch" />
            <Setter Property="BorderThickness" Value="1,1,1,1"/>
            <Setter Property="BorderBrush" Value="Black"/>
        </Style>
        <Style x:Key="RAGCellLabelStyle" TargetType="sdk:Label">
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="FontWeight" Value="Bold" />
        </Style>

 

Then apply the style to the DataGrid.

 

<sdk:DataGrid  MinHeight="200" VerticalAlignment="Stretch" AutoGenerateColumns="False" ItemsSource="{Binding}" Name="rAGDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Margin="2,0,2,5">
    <sdk:DataGrid.Columns>
        <sdk:DataGridTemplateColumn x:Name="empricalTypeColumn" Header="Emprical Type" Width="80">
            <sdk:DataGridTemplateColumn.HeaderStyle>
                <Style TargetType="dataprimitives:DataGridColumnHeader">
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <TextBlock Text="{Binding}" TextWrapping="Wrap" TextAlignment="Center" />
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </sdk:DataGridTemplateColumn.HeaderStyle>
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <sdk:DatePicker SelectedDate="{Binding Path=EmpricalType, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Background="DodgerBlue" Style="{StaticResource RAGCellBorderStyle}" >
                        <sdk:Label Content="{Binding Path=EmpricalType, StringFormat=\{0:d\}}" Style="{StaticResource RAGCellLabelStyle}"  />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Resourcing" Width="82" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Resourcing, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Resourcing, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Resourcing, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>

        <sdk:DataGridTemplateColumn Header="Approval" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}" >
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Approval, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Approval, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Approval, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>

        <sdk:DataGridTemplateColumn Header="Project Plan" Width="60" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=ProjectPlan, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=ProjectPlan, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=ProjectPlan, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>

        <sdk:DataGridTemplateColumn Header="Milestone" Width="74" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Milestone, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Milestone, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Milestone, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Financial" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Financial, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Financial, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Financial, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Business Case" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Business, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Business, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Business, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Risks" Width="50" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Risks, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Risks, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Risks, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Methodology" Width="90" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Methodology, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Methodology, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Methodology, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Supply Service" Width="65" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=SupplyService, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=SupplyService, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=SupplyService, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Sponsor" Width="67" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Sponsor, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Sponsor, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Sponsor, Mode= OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
       
    </sdk:DataGrid.Columns>
    <sdk:DataGrid.RowHeight>35</sdk:DataGrid.RowHeight>
</sdk:DataGrid>

 

Converter class

 

public class StatusColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return new SolidColorBrush(Colors.Gray);
            }
            double? health = (double?)value;

            Brush retColor = Utility.GetHealthColor(health);
            return retColor;

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

 

Supporting Class for converter

public static class Utility
    {
        public static Brush GetHealthColor(double? health)
        {
            Brush retColor;
            if (health == 4)
            {
                retColor = new SolidColorBrush(Colors.Blue);
            }
            else if (health <= 1.99 && health >= 0)
            {
                retColor = new SolidColorBrush(Colors.Red);
            }
            else if (health > 1.99 && health <= 2.99)
            {
                retColor = new SolidColorBrush(Colors.Orange);
            }
            else if (health > 2.99 && health <= 3.99)
            {
                retColor = new SolidColorBrush(Colors.Green);
            }
            else
            {
                retColor = new SolidColorBrush(Colors.Gray);
            }
            return retColor;
        }
    }

 

Datasource

 

public class RAG
    {

        public RAG(Int32 ragId, DateTime empType,double res,double app,double prjPlan, double mile,double fin,double business
            , double risks, double method, double supply,double sponsor)
        {
            this.RAGID = ragId;
            this.EmpricalType = empType;
            this.Resourcing = res;
            this.Approval = app;
            this.ProjectPlan = prjPlan;
            this.Milestone = mile;
            this.Financial = fin;
            this.Business = business;
            this.Risks = risks;
            this.Methodology = method;
            this.SupplyService = supply;
            this.Sponsor = sponsor;
        }

        #region Primitive Properties

        public global::System.Int32 RAGID
        {
            get
            {
                return _RAGID;
            }
            set
            {
                if (_RAGID != value)
                {
                    _RAGID = value;
                }
            }
        }
        private global::System.Int32 _RAGID;
     
        public global::System.DateTime EmpricalType
        {
            get
            {
                return _EmpricalType;
            }
            set
            {
                _EmpricalType = value;
            }
        }
        private global::System.DateTime _EmpricalType;
      
        public global::System.Double Resourcing
        {
            get
            {
                return _Resourcing;
            }
            set
            {
                _Resourcing = value;
            }
        }
        private global::System.Double _Resourcing;
    
        public global::System.Double Approval
        {
            get
            {
                return _Approval;
            }
            set
            {
                _Approval = value;
            }
        }
        private global::System.Double _Approval;

        
        public global::System.Double ProjectPlan
        {
            get
            {
                return _ProjectPlan;
            }
            set
            {
                _ProjectPlan = value;
            }
        }
        private global::System.Double _ProjectPlan;

      
        public global::System.Double Milestone
        {
            get
            {
                return _Milestone;
            }
            set
            {
                _Milestone = value;
            }
        }
        private global::System.Double _Milestone;

         
        public global::System.Double Financial
        {
            get
            {
                return _Financial;
            }
            set
            {
                _Financial = value;
            }
        }
        private global::System.Double _Financial;

        
        public global::System.Double Business
        {
            get
            {
                return _Business;
            }
            set
            {
                _Business = value;
            }
        }
        private global::System.Double _Business;

        public global::System.Double Risks
        {
            get
            {
                return _Risks;
            }
            set
            {
                _Risks = value;
            }
        }
        private global::System.Double _Risks;
          
        public global::System.Double Methodology
        {
            get
            {
                return _Methodology;
            }
            set
            {
                _Methodology = value;
            }
        }
        private global::System.Double _Methodology;

        public global::System.Double SupplyService
        {
            get
            {
                return _SupplyService;
            }
            set
            {
                _SupplyService = value;
            }
        }
        private global::System.Double _SupplyService;

        public global::System.Double Sponsor
        {
            get
            {
                return _Sponsor;
            }
            set
            {
                _Sponsor = value;
            }
        }
        private global::System.Double _Sponsor;

        #endregion
    }

 

Collection Class

 

public class RAGCollection : ObservableCollection<RAG>
    {
        public RAGCollection()
            : base()
        {
            Add(new RAG(1,DateTime.Now,1.2,2.1,3.1,4.0,1,5,2.5,3.5,1.5,5));
            Add(new RAG(2, DateTime.Now.AddDays(2), 2.2, 1.1, 1.1, 3.0, 2, 4, 1.5, 2.5, 3.5, 2.5));
            Add(new RAG(3, DateTime.Now.AddMonths(-10), 1.2, 2.1, 3.1, 4.0, 1, 5, 2.5, 3.5, 1.5, 5));
            Add(new RAG(4, DateTime.Now.AddDays(-20), 1.2, 2.1, 3.1, 4.0, 1, 5, 2.5, 3.5, 1.5, 5));
        }
    }

 

The Full XAML with style and the converter and the header changes

<UserControl x:Class="Forum_2011.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Forum_2011.Converter"
             xmlns:dataprimitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="1024" d:DesignWidth="768" xmlns:my="clr-namespace:Forum_2011.DataSource" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" Loaded="UserControl_Loaded">
    <UserControl.Resources>
        <CollectionViewSource x:Key="rAGViewSource" d:DesignSource="{d:DesignInstance my:RAG, CreateList=True}" />
        <local:StatusColorConverter x:Key="colorConvert"/>
        <Style x:Key="dataGridHeaderStyle" TargetType="dataprimitives:DataGridColumnHeader">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" TextWrapping="Wrap" TextAlignment="Center" />
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="RAGCellBorderStyle" TargetType="Border">
            <Setter Property="HorizontalAlignment" Value="Stretch" />
            <Setter Property="VerticalAlignment" Value="Stretch" />
            <Setter Property="BorderThickness" Value="1,1,1,1"/>
            <Setter Property="BorderBrush" Value="Black"/>
        </Style>
        <Style x:Key="RAGCellLabelStyle" TargetType="sdk:Label">
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="FontWeight" Value="Bold" />
        </Style>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel DataContext="{StaticResource rAGViewSource}">
            <Border BorderBrush="Gray" BorderThickness="2,2,2,2" Background="Black" Height="40" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                <TextBlock Text="Red Amber Green (RAG)" Foreground="White" FontSize="20"/>
            </Border>
            <sdk:DataGrid  MinHeight="200" VerticalAlignment="Stretch" AutoGenerateColumns="False" ItemsSource="{Binding}" Name="rAGDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Margin="2,0,2,5">
                <sdk:DataGrid.Columns>
                    <sdk:DataGridTemplateColumn x:Name="empricalTypeColumn" Header="Emprical Type" Width="80">
                        <sdk:DataGridTemplateColumn.HeaderStyle>
                            <Style TargetType="dataprimitives:DataGridColumnHeader">
                                <Setter Property="ContentTemplate">
                                    <Setter.Value>
                                        <DataTemplate>
                                            <TextBlock Text="{Binding}" TextWrapping="Wrap" TextAlignment="Center" />
                                        </DataTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </sdk:DataGridTemplateColumn.HeaderStyle>
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <sdk:DatePicker SelectedDate="{Binding Path=EmpricalType, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Background="DodgerBlue" Style="{StaticResource RAGCellBorderStyle}" >
                                    <sdk:Label Content="{Binding Path=EmpricalType, StringFormat=\{0:d\}}" Style="{StaticResource RAGCellLabelStyle}"  />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Resourcing" Width="82" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Resourcing, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Resourcing, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Resourcing, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>

                    <sdk:DataGridTemplateColumn Header="Approval" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}" >
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Approval, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Approval, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Approval, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>

                    <sdk:DataGridTemplateColumn Header="Project Plan" Width="60" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=ProjectPlan, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=ProjectPlan, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=ProjectPlan, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>

                    <sdk:DataGridTemplateColumn Header="Milestone" Width="74" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Milestone, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Milestone, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Milestone, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Financial" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Financial, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Financial, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Financial, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Business Case" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Business, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Business, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Business, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Risks" Width="50" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Risks, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Risks, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Risks, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Methodology" Width="90" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Methodology, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Methodology, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Methodology, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Supply Service" Width="65" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=SupplyService, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=SupplyService, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=SupplyService, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Sponsor" Width="67" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Sponsor, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Sponsor, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Sponsor, Mode= OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                   
                </sdk:DataGrid.Columns>
                <sdk:DataGrid.RowHeight>35</sdk:DataGrid.RowHeight>
            </sdk:DataGrid>
        </StackPanel>
    </Grid>
   
</UserControl>

 

The Code behind for the mainpage.cs

public partial class MainPage : UserControl
    {
        private DataSource.RAGCollection ragColData;
        public MainPage()
        {
            InitializeComponent();
            ragColData = new DataSource.RAGCollection();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            // Do not load your data at design time.
             if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
             {
                 //Load your data here and assign the result to the CollectionViewSource.
                 System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["rAGViewSource"];
                myCollectionViewSource.Source = ragColData;
             }
        }
    }

 

 

 

Colour converter based on Status string.

Declare a class and inherit from the IValueConverter
using System; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Ink; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 
using System.Windows.Data;

public class StatusColorConverter:IValueConverter 
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
        { 
            string status = (string)value; 
            if (value == null) 
            { 
                return new SolidColorBrush(Colors.LightGray); 
            } 
            if (string.IsNullOrEmpty(status)) 
            { 
                return new SolidColorBrush(Colors.LightGray); 
            } 
            else if (status.Trim() == "Open") 
            { 
                return new SolidColorBrush(Colors.Orange); 
            } 
            else if (status.Trim() == "Closed") 
            { 
                return new SolidColorBrush(Colors.Green); 
            } 
            else 
            { 
                return new SolidColorBrush(Colors.LightGray); 
            } 
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
        { 
            throw new NotImplementedException(); 
        } 
    }
Using it in XAML, Below are just the main elements for the understanding. The original XAML page will have more declaration
<navigation:Page xmlns:local="clr-namespace:ProjectName.Converters"
           Title="Page Title Here">
    <navigation:Page.Resources>
        <local:StatusColorConverter x:Key="statusColor" />
    </navigation:Page.Resources>
</navigation:Page>
<Grid>
<Border BorderBrush="White" BorderThickness="2" Background="{Binding Path=Status,Converter={StaticResource colorConvert}}" 
CornerRadius="10,10,10,10" Width="200" Height="150">
<TextBlock Text="{Binding Path=StatusText}" />
</Border>
</Grid>