Monday, July 15, 2013

Asynchronous Patterns in CRM2011- Part 1

Last few weeks, I am trying my hands on creating windows 8 apps for CRM. I was going through a sample solution posted on http://blogs.msdn.com/b/crm/archive/2013/05/28/new-blog.aspx. The most important part of the sample solution is the two projects “WinRt.Microsoft.Crm.Sdk” and “WinRt.Microsoft.Crm.Sdk.Proxy”. These projects are updated versions of  the original SDK dlls to work with windows 8 apps. They have implemented the Event Based Asynchronous Pattern (EAP) to make OrganizationServiceProxy methods to work asynchronously.
I decided to write something about Async patterns and here we go. There are 3 types asynchronous programming patterns.
  • APM – Asynchronous Programming model
It is also known as IAsyncResult pattern. It requires a begin and an end method. For example BeginExecute() and EndExecute() methods. We generally calls the end method in the callback method. You can find the examples of this pattern in the Silverlight samples of CRM 2011 SDK  .
  • EAP – Event based Asynchronous Pattern
The event based asynchronous pattern consist of function/s  Async suffice (MethodNameAsync). These async function/s may have MethodNameCompleted event, which will be raised when the operation is completed. For more info please have a look at the http://msdn.microsoft.com/en-us/library/wewwczdw.aspx.
  • TAP - Task based Asynchronous Pattern
Task based is introduced from .NET 4.0. The Task-based Asynchronous Pattern (TAP) is based on the Task and Task<TResult> types in the System.Threading.Tasks. The biggest difference in TAP, APM and EAP is the initiation and completion of the async operation in a same method.
TAP is the recommend pattern for future development. In this blog we will talk about using TAP for CRM2011 applications that need async calls for example Silverlight and windows store apps.

Why use TAP

As mentioned above in TAP section, the biggest problem the with APM and EAP patterns is initiation and completion of the operation in separate methods.  This force us to put the program logic in different methods.  It makes the code difficult to read.
The good thing about TAP is that it is very easy to write a wrapper for APM and EAP and expose them as TAP implementations. This word document contains a lot of information about TAP.

Consuming the TAP pattern in VS2012

In .Net framework 4.5 TAP pattern can be consumed using a keyword “await”. An await expression must occur inside the body of an asynchronous method, with return type void, Task, or Task<TResult> for some TResult. The await keyword can also be used with .Net frame work 4.0 and Silverlight 5 by using Async Targeting Pack for Visual Studio 2012.
There are also other ways to consume TAP pattern by using methods like “ContinueWith” and “ContinueWhenAll”. For sample code have a look at the Mike Snider’s blog.

Using TAP pattern in Silverlight 5 and CRM2011

In this blog we will talk about how to use TAP pattern with CRM2011 and Silverlight 5. I am going to use  soapforsilverlight sample located at \sdk\samplecode\cs\silverlight\soapforsilverlight of CRM2011 SDK.
If we look at the code we can see the sample is using the following 2 methods to retrieve and display the accounts names. These methods are defined in MainPage.cs file.

        private void AccountList_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                QueryExpression query = new QueryExpression()
                {
                    EntityName = "account",
                    ColumnSet = new ColumnSet()
                    {
                        Columns = new System.Collections.ObjectModel.ObservableCollection<string>(new string[] { "name" }) 

                    },
                    Orders = new System.Collections.ObjectModel.ObservableCollection<OrderExpression>(new OrderExpression[]
                {
                    new OrderExpression() { AttributeName = "name", OrderType = OrderType.Ascending }
                })
                }; 

                query.PageInfo = new PagingInfo { Count = MaxRecordsToReturn, PageNumber = 1, PagingCookie = null }; 

                OrganizationRequest request = new OrganizationRequest() { RequestName = "RetrieveMultiple" };
                request["Query"] = query; 

                IOrganizationService service = SilverlightUtility.GetSoapService(); 

                service.BeginExecute(request, new AsyncCallback(AccountList_ClickCallback), service);
            }
            catch (Exception ex)
            {
                this.ReportError(ex);
            }
        } 

        private void AccountList_ClickCallback(IAsyncResult result)
        {
            try
            {
                OrganizationResponse response = ((IOrganizationService)result.AsyncState).EndExecute(result);
                EntityCollection results = (EntityCollection)response["EntityCollection"]; 

                StringBuilder sb = new StringBuilder();
                if (results.Entities.Count == 0)
                { sb.AppendLine("There are no Account records in the system."); } 

                foreach (Entity entity in results.Entities)
                {
                    sb.AppendLine("Account Name = " + entity.GetAttributeValue<string>("name"));
                }
                if (results.MoreRecords)
                {
                    sb.AppendLine("Only the first " + MaxRecordsToReturn + " records were returned.");
                }
                this.ReportMessage(sb.ToString()); 

            }
            catch (Exception ex)
            {
                this.ReportError(ex);
            }
        } 


There are two methods “BeginExecute” and “EndExecute” which represent the initiation and the completion of the “Execute” operation.  The “EndExecute” is called in the callback method.

Now we are going to write a TAP wrapper for this code. The BeginExcecute method is taking 3 parameters request, callback method and IOrganizationService. We are going to do the same in our wrapper code.

public static Task<OrganizationResponse> Execute(OrganizationRequest request,IOrganizationService service)
        {
            var tcs = new TaskCompletionSource<OrganizationResponse>(); 

            service.BeginExecute(request, (asyncResult) =>
            {
                try
                {
                    tcs.SetResult(((IOrganizationService)asyncResult.AsyncState).EndExecute(asyncResult));
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }, service); 

            return tcs.Task;
        } 

    } 


TaskCompletionSource is required to get the completed async task. The completion can represents the successful completion of the call, any exceptions and cancellation of the process etc.

TaskCompletionSource exposes 2 methods to set result. We are using tcs.SetResult. You can use TrySetResult. The same applies to set the exception for TaskCompletionSource.

Now we have a TAP wrapper. As I explained earlier, we would like to call this method using await keyword and to do that we need to create an asynchrous method. So here is my asynchronous method.
 
        //async function
        private async void getAccount()
        {
            try
            {
                QueryExpression query = new QueryExpression()
                {
                    EntityName = "account",
                    ColumnSet = new ColumnSet()
                    {
                        Columns = new System.Collections.ObjectModel.ObservableCollection<string>(new string[] { "name" })

                    },
                    Orders = new System.Collections.ObjectModel.ObservableCollection<OrderExpression>(new OrderExpression[]
                {
                    new OrderExpression() { AttributeName = "name", OrderType = OrderType.Ascending }
                })
                };

                query.PageInfo = new PagingInfo { Count = MaxRecordsToReturn, PageNumber = 1, PagingCookie = null };

                OrganizationRequest request = new OrganizationRequest() { RequestName = "RetrieveMultiple" };
                request["Query"] = query;

                IOrganizationService service = SilverlightUtility.GetSoapService();

                //calling the TAP wrapper
                var task = await Execute(service, request);

                // Get the results from the task
                var response = task.Results;

                //Manipulating the result
                EntityCollection results = (EntityCollection)task.Results[0].Value;

                StringBuilder sb = new StringBuilder();
                if (results.Entities.Count == 0)
                { sb.AppendLine("There are no Account records in the system."); }

                foreach (Entity entity in results.Entities)
                {
                    sb.AppendLine("Account Name = " + entity.GetAttributeValue<string>("name"));
                }
                if (results.MoreRecords)
                {
                    sb.AppendLine("Only the first " + MaxRecordsToReturn + " records were returned.");
                }
                this.ReportMessage(sb.ToString());
               
            }
            catch (Exception ex)
            {
                this.ReportError(ex);
            }


        }
I have added the contents of AccountList_Click and AccountList_ClickCallback methods to create this async method. As we can see we can get the result of the call in the same method. Now I will call this method in AccountList_Click.

        private void AccountList_Click(object sender, RoutedEventArgs e)
        {
           // calling the async method   
            getAccount();
        }
You are good to go. Please leave some feedback. In next part we will try to create a TAP wrapper for EAP pattern.

Thursday, May 30, 2013

CRM2011 and GeoFlow

Two weeks ago, I have attended a CRM infrastructure course at CRM enterprise academy. During this course, we were shown a demo of a new Excel 2013 add-in named GeoFlow.  It is a BI tool that can turn the thousands of rows of  data with some spatial information into interactive 3D tour on Bing Maps. It is still in beta and can be downloaded from here.

The example we were shown was using the leads data from CRM2011 with the city and lead source information. It was amazing. I don’t have a lot of CRM data right now but I managed to get some rental bond data for suburbs in NSW Australia. I tried to compare the rental bond data for different suburbs for the month of march in 2007, 2010 and 2013. Here is the screen shot.

image

This is how it looks like in real time.  You can do a whole lot of things with GeoFlow . For example adding multiple scenes, zoom in or out of the map, adding annotations, choosing chart types and selecting an item on the map to get more information etc.

 

 

Have a look at the article from Microsoft Research.

Monday, May 6, 2013

How to use ExecuteMultipleRequest with ServiceContext and Linq

Most of  CRM2011 developers must have used the service context and linq before. I have also blogged about it in the past in one of my plug-in tutorial. CRM rollup 12 has introduced a new method “ExecuteMultipleRequest”. This method receives a collection of requests (same or different type of requests). The method return the response collection. Here is the link to sample code from Microsoft.

I was playing around this method and came across some code from my favourite CRM expert “David Berry”. I tried to use his code with service context and here is the result. I have hard coded few things in my sample but you can change it as required.

The following code is retrieving all the contacts where parent customer id is C6CB814A-BA75-E011-8720-00155DA5304E and updating their phone number.

var ServiceContext = new OrganizationServiceContext(service);
Guid accountid = new Guid("C6CB814A-BA75-E011-8720-00155DA5304E");

// Create an ExecuteMultipleRequest object.
ExecuteMultipleRequest requestWithResults = new ExecuteMultipleRequest()
{
    // Assign settings that define execution behavior: continue on error, don't return responses. 
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        ReturnResponses = false
    }, 
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
};
               
requestWithResults.Requests.AddRange(from c in ServiceContext.CreateQuery("contact")
                                    where c["parentcustomerid"].Equals(accountid)
                                    select new UpdateRequest()
                                    {
                                        Target = new Entity("contact")
                                        {
                                            Id = c.Id,
                                            Attributes = { new KeyValuePair<string,object>("telephone1", "+61402234212") }
                                        }
                                    });

// Excute the requests
ExecuteMultipleResponse Response = (ExecuteMultipleResponse)service.Execute(requestWithResults);


If you are using any other entity collection then you can change ServiceContext.CreateQuery("contact") with that.

I have highlighted the following lines
ContinueOnError = false
ReturnResponses = false


These lines are self explanatory. The first line means that continue on error and the second line means that do not return the response. 
Please check the code from Microsoft for complete/detailed explanation.

Tuesday, April 30, 2013

How to disable “Convert the incoming email to contacts” option for the entire organisation

In CRM there an option to convert the incoming emails/appointments into contacts or leads. This option is available only on user level not on the organisation level. The default option is to create contacts.

image

User can enable or disable this option from File->Options—Email tab. But what if you are using queues to receive emails. Queues use email router to send or receive the emails and there is no option to disable “Automatically create records..” option.

I have read somewhere on the CRM forum that if you are using the email router,  “Automatically create records..” setting is derived from the user used in the deployment tab of the email router.

image 

If the “Access Credentials” is chosen “Other specified” then we may be able to achieve the result by changing personal settings of this user.

But if the “Access Credentials” is chosen “Local System Account”  then you don’t have an option as “System” user settings cannot be modified. So there is only one option available and

that is to disable for the whole organisation. This is also a better option if we have to disable auto creation option for every user in the organisation.

How to disable this option for the whole organisation

This can be achieved using  “OrgDBOrgSettings Tool” for CRM2011. Follow this link  to read a kb article on the tool.

  • Once you download the tool and make the changes to the Microsoft.Crm.SE.OrgDBOrgSettingsTool.exe.config as described in the kb article.
  • Run this command  Microsoft.Crm.SE.OrgDbOrgSettingsTool.exe Retrieve [/u] <OrgName>. The result will look like the following screen.

    image
  • Run this command Microsoft.Crm.SE.OrgDbOrgSettingsTool.exe Retrieve [/u] <OrgName>  AutoCreateContactOnPromote False. The result will look like the following screen.
  • image

  • Now run the retrieve command again Microsoft.Crm.SE.OrgDbOrgSettingsTool.exe Retrieve [/u] <OrgName>.
    image 
  • Check the “Current Value” of AutoCreateContactOnPromote. It will be “False”. There you go. It’s done.

 

 

     

Sunday, April 28, 2013

How to display a warning message on the CRM form

We use JavaScript for client side validation on CRM forms. Mostly we use the pop up message box (JavaScript alert function) to display the error/warning messages. The user has to press ok to proceed. If the validation code is running on the formload event then the system will keep poping up the message box everytime the user opens up the record unless the problem is fixed. But if you just want to display a warning message without forcing the user to press ok and fix the problem immediately.

The post is about displaying a warning message without the pop ups.  This solution will display a warning message if the field failed the validation. This does not require any immediate response from the user.

Here is the screen shot of the warning message on account form.
image
For this solution we need 3 web resources
  1. An Image web resource (warning or ! image in front of the message)
  2. A HTML web resource
  3. A JavaScript web resource
You can download the solution containing these web resources from here. Download the solution and publish it.
Here are steps to add the warning message to an account entity form.
  • Open the account entity form in a customise view.
  • Add a new section to the general on the form and move it to the top of the tab. Make sure the name of the tab is “general” and the name of section is “sect_alert_notification” as shown in the screen shot. We are using the tab and the section  name in the JavaScript  web resource.

    image
  • Add the “Notification.HTML” web resource to section. The following screen shots display  the properties of the web resource.

    image
    image
  • Add the “new_Notification.JS” JavaScript web resource to the entity form
  • Call the ShowNotification function on formload event and on onchange event of field you are validating.
    image
  • Update the validation code as required in "ShowNotification” function.
    function ShowNotification() 
    { 
        var Validated= false;
        // Add Validation code Here     
    
    
        if (Validated==false)
         {  
            Xrm.Page.ui.tabs.get("general").sections.get("sect_alert_notification").setVisible(true);
           
        }
       else
       {
          Xrm.Page.ui.tabs.get("general").sections.get("sect_alert_notification").setVisible(false);
       }
    }
    
  • Publish the customisation and test the solution.
Thanks to my colleague Russel Devine for the code. Please leave the feedback as required.

Tuesday, April 9, 2013

Social CRM has finally arrived

Social CRM is finally here, bigger and better than ever before. So what is social CRM? According to Wikipedia
“Social CRM (Customer Relationship Management) is use of social media services, techniques and technology to enable organisations to engage with their customers”
Microsoft is trying to incorporate social into dynamic CRM for some time.

First came the “Activity feeds”. It brought the social sites like features into CRM. Activities feed provides the face book like functionalities. You can follow the accounts, contacts, users and opportunities etc. and write post on the walls like face book. But it is still the communication between internal users.

Then came the “Yammer” integration in roll up 12. It took the conversation out to the external customers. You can communicate with internal users and customers using yammer integration. It is a work in progress and it may kill the activity feed in future.

And now comes the Netbreeze. I am very excited about this collaboration. Microsoft acquired Netbreeze, a social media monitoring and analytics company. I did not go the convergence 2013 but I have an access to “Virtual Convergence”. There are a lot of new features coming out in the next release but Netbreeze integration is my favourite one.

The demo was just amazing. The demo was regarding social feeds for CRM products. Here are some of screen sheets.
image

You can analyse the product you are interested in. For example the following screen shot displays the information about Microsoft CRM.
image

You can drill down further to any of the above information. For example channels or sentiments as shown in the following screen shots.
image

image

You an drill down further to the individual posts. You can even respond to the feeds straight from the system.
image

There are a lot of other things you can do. Anyway I believe it’s a start of an exciting journey.

Please leave feedback.

Saturday, March 30, 2013

CRM2011 roll up 13 and the new SDK is released.

Microsoft released the  roll up 13 for CRM2011. The rollup 13 introduces the support for windows server 2012 and ADFS 2.1. The rollup also resolved the numbers of issues. For the complete list of hot fixes and updates read the following kb article.

http://support.microsoft.com/kb/2791312

Microsoft also released new SDK (version 1.0.15) to support roll up 13. Here is the download link.

http://www.microsoft.com/en-au/download/details.aspx?id=24004

If you have not work with SDK version 1.0.14 then a look at “EntityMetadata” spreadsheet. It lists the metadata about all the out of the box entities ( Entities, entity privileges, attributes, picklist values, relationships and global option sets).