RSS

Monthly Archives: August 2013

Using CRM LookUp functionality in a Silverlight WebResource with CRM Look and Feel

Introduction

In this blog, I will show you how to use the LookUp functionality of CRM in a Silverlight WebResource.

I am trying to create a LookUp for the Account inside a Contact record.

Design

Let’s first go for the Design.

In the Design, let’s add a RichTextBox and a LookUp image similar to the CRM LookUp image.

<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  x:Class="SilverlightApplicationLookUpDemo.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <sdk:Label Height="20" Width="50" x:Name="lblLookup" HorizontalAlignment="Left" Content="Account" Margin="62,56,0,0" VerticalAlignment="Top"/>
        <RichTextBox Background="White" FontSize="10" VerticalScrollBarVisibility="Disabled" IsReadOnly="True" Height="21" HorizontalAlignment="Left" Margin="112,54,0,0" Name="txtLookUp" VerticalAlignment="Top" Width="200" TabIndex="1" />
        <Image Height="21" Width="21" HorizontalAlignment="Left" Margin="313,53,0,0" Name="ImgLookUp" MouseLeftButtonDown="LocalImage_MouseLeftButtonDown" Source="/SilverlightApplicationLookUpDemo;component/Images/btn_off_lookup.png" VerticalAlignment="Top"/>
    </Grid>
</UserControl>

It will look like below.

Capture

Code Behind

In the Code Behind, let’s insert the Event that will be fired, when the Image gets clicked.

The whole code will look something like this.

using System.Json;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace SilverlightApplicationLookUpDemo
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void LocalImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string lookupId = string.Empty;
            string lookupName = string.Empty;
            string contactId = "7C1EF3C4-39D3-E211-8A25-B4B52F566DF2";
            string baseUrl = "https://example.crm.dynamics.com";
            string objectTypesContact = "2";

            //Relative URL for the LookUp
            string lookUpRecordUrl = "/_controls/lookup/lookupinfo.aspx?AllowFilterOff=1&DefaultType=1&" +
"DisableQuickFind=0&DisableViewPicker=0&LookupStyle=single&ShowNewButton=1&ShowPropButton=1&" +
"browse=false&currentid=" + contactId + "&objecttypes=" + objectTypesContact;

           //Complete URL to open the LookUp
           string lookUpUrl = baseUrl + lookUpRecordUrl;

           //Open the Modal Window for the LookUp
           dynamic returnedParams = HtmlPage.Window.Invoke("showModalDialog", lookUpUrl, null, "dialogWidth:500px;dialogHeight:700px");

           //For earlier Rollups, it will return a json object
           if (returnedParams.items)
           {
               lookupId = returnedParams.items[0].id;
               lookupName = returnedParams.items[0].name;
           }

           //For Rollup 12, as in Rollup 12 returnedparams would
           //be a json string instead of a json object.
           else
           {
               JsonValue jsonValue = JsonValue.Parse(returnedParams);
               JsonObject jsonObject = jsonValue as JsonObject;

               //user selected
               lookupId = jsonObject["items"][0]["id"].ToString();
               lookupName = jsonObject["items"][0]["name"].ToString();
           }

           //Add style to the TextBox
           txtLookUp.Foreground = new SolidColorBrush(Colors.Blue);

           //Add selected item to the fiscal period TextBox
           Paragraph paragraph = new Paragraph();
           Underline underline = new Underline();
           Run run = new Run() { Text = lookupName };

           underline.Inlines.Add(run);
           paragraph.Inlines.Add(underline);
           txtLookUp.Blocks.Clear();
           txtLookUp.Blocks.Add(paragraph);
       }
    }
}

Now let’s add the WebResource to a Contact entity.

Output

So, after implementing, we will see something like this.

Image

Image

Notes

  1. For the demo, I have hard-coded the Contact Id and objecttype for Contact, but we can also pass them as QueryString Parameter/Custom Parameter for the Web Resource.
  2. For Server URL, we can use the “SilverlightUtility.GetServerBaseUrl()" function.
  3. The “SilverlightUtility.cs" can be found at location sdk\samplecode\cs\silverlight\soapforsilverlight\soapforsilverlightsample in the SDK provided by Microsoft.

By Dibyasingh Tripathy
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

Advertisements
 
2 Comments

Posted by on August 7, 2013 in WebResources

 

Tags: , , , , , , , , , , , , , , ,

ExecuteMultipleRequest For Bulk Operation

Introduction

In the Microsoft Dynamics CRM 2011 Update Rollup 12, a new message request named ExecuteMultipleRequest is added. Let’s explore more about the usage.

What it does?

It accepts Collection of Requests as input and returns Collection of Responses. The request is executed batch by batch.

For Online CRM, maximum Batch Size is 1000. So, for Online CRM, maximum 1000 requests can be executed at a time.

For On Premise, Batch Size can be increased.

Example

Below are the examples of the ExecuteMultipleRequest.

  • Bulk Lead Creation

    //The method takes IOrganization service and total number of records to be created as input
     private void CreateLeadMultiple(IOrganizationService service, int batchSize)
     {
         //To execute the request we have to add the Microsoft.Xrm.Sdk of the latest SDK as reference
         ExecuteMultipleRequest req = new ExecuteMultipleRequest();
         req.Requests = new OrganizationRequestCollection();
         req.Settings = new ExecuteMultipleSettings();
         req.Settings.ContinueOnError = true;
         req.Settings.ReturnResponses = true;
    
         try
         {
             for (int i = 0; i < batchSize; i++)
             {
                 Entity lead = new Entity("lead");
                 lead["subject"] = "Test Lead";
                 lead["firstname"] = "Requested Lead";
                 lead["lastname"] = "Name " + i;
                 var createRequest = new CreateRequest();
    
                 createRequest.Target = lead;
                 req.Requests.Add(createRequest);
              }
    
              var res = service.Execute(req) as ExecuteMultipleResponse;  //Execute the collection of requests
          }
    
          //If the BatchSize exceeds 1000 fault will be thrown.In the catch block divide the records into batchable records and create
          catch (FaultException<OrganizationServiceFault> fault)
          {
              if (fault.Detail.ErrorDetails.Contains("MaxBatchSize"))
              {
                  var allowedBatchSize = Convert.ToInt32(fault.Detail.ErrorDetails["MaxBatchSize"]);
                  int remainingCreates = batchSize;
    
                  while (remainingCreates > 0)
                  {
                      var recordsToCreate = Math.Min(remainingCreates, allowedBatchSize);
                      CreateLeadMultiple(service, recordsToCreate);
                      remainingCreates -= recordsToCreate;
                  }
              }
          }
    }
    
  • Bulk Entity State and Status Change

    Here is another example of changing the State and Status of records by ExecuteMultipleRequest.

    This code will work, if the total Records <=1000, otherwise we have to break the records into batches to execute one by one.

    for (int i = count; i < ent.Entities.Count; i++)
    {
        SetStateRequest changeState = new SetStateRequest();
        changeState.EntityMoniker = new EntityReference();
        changeState.EntityMoniker.Id = ent.Entities[i].Id;
        changeState.EntityMoniker.LogicalName = ent.Entities[i].LogicalName;
        changeState.State = new OptionSetValue(0);
        changeState.Status = new OptionSetValue(1);
        req.Requests.Add(changeState);
    }
    
    // Here req is the object of ExecuteMultipleRequest class.
    var res = service.Execute(req) as ExecuteMultipleResponse;
    

By Ranjan Parhi
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 
1 Comment

Posted by on August 7, 2013 in SDK Messages

 

Tags: , , , , , , , , , , , , , , , ,

CRM2011 Add Entity Level ‘Notes’ Section Accessible and Viewable from Custom HTML WebResources

Introduction

In this article, we will create an Entity level ‘Notes‘ Section accessible and viewable from Custom HTML WebResource.

Notes

Background

In one of my projects, there is a requirement to add a “Notes” Section to the custom HTML page, which will function same as entity level ‘Notes‘ in CRM. And that page is accessible from the Ribbon Button of an Entity form. I faced the challenge and figured out a way to do it.

Implementation

Steps which are needed to be followed:-

  • Create an HTML WebResource.
  • Add following Code to the row of table of your HTML page. Here my page is accessible through Order Level Form, hence Entity code is 1088.
    <tr style="height: 200px">
            <td colspan="4">
                <div id="tab6" class="ms-crm-InlineTab" isviewporttab="1">
                    <table style="height: 100%; width: 100%" class="ms-crm-InlineTabBody" cellspacing="0"
                        cellpadding="0">
                        <colgroup>
                            <col width="100%" />
                            <tbody>
                                <tr>
                                    <td valign="top">
                                        <div class="ms-crm-FormSection-Container">
                                            <table style="height: 100%; table-layout: fixed;" id="{19E2776E-C7EF-4ae2-99BB-549FF9DA0B23}"
                                                class="ms-crm-FormSection" cellspacing="0" cellpadding="3" columns="2" valign="top"
                                                isviewportsection="1" label="Notes">
                                                <colgroup>
                                                    <col width="115" />
                                                    <col />
                                                    <col width="115" />
                                                    <col />
                                                    <tbody>
                                                        <tr height="5">
                                                            <td>
                                                            </td>
                                                            <td>
                                                            </td>
                                                            <td>
                                                            </td>
                                                            <td>
                                                            </td>
                                                        </tr>
                                                        <tr height="25" valign="top">
                                                            <td style="height: 200px; overflow: hidden;" id="notescontrol_d" class=" FormSection_CellPadding"
                                                                rowspan="5" colspan="4" formxmlcolspan="2" isautoexpanding="TRUE">
                                                                <div style="display: none;" id="notescontrol_c" class="ms-crm-FieldLabel-LeftAlign ms-crm-Field-Normal"
                                                                    sl="false">
                                                                    <label for="notescontrol">
                                                                        Note Text</label></div>
                                                                <iframe style="width: 100%; height: 100%; min-height: 200px;" id="notescontrol" class="noteData"
                                                                    tabindex="51" src=""
                                                                    frameborder="0" name="notescontrol" scrolling="no" notesxml="" url="">
                                                                </ iframe>
                                                            </td>
                                                        </tr>
                                                        <tr height="25" valign="top">
                                                        </tr>
                                                        <tr height="25" valign="top">
                                                        </tr>
                                                        <tr height="25" valign="top">
                                                        </tr>
                                                        <tr height="100%" valign="top">
                                                        </tr>
                                                    </tbody>
                                                </colgroup>
                                            </table>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </colgroup>
                    </table>
                </div>
            </td>
        </tr>
    
  • On load of your custom page add the following code.
    window.onload = function () {
         var iframe = document.getElementById('notescontrol');
         var entityId = window.parent.Xrm.Page.data.entity.getId();
         var noteUrl = document.location.protocol + "//" + document.location.host + "/" + Xrm.Page.context.getOrgUniqueName() + "/_controls/notes/notesdata.aspx?EnableInlineEdit=true&EnableInsert=true&id=%7b" + entityId + "%7d&ParentEntity=1088";
         iframe.src = noteUrl;
         iframe.url = noteUrl;
    }
    
  • Add your WebResource to your Ribbon ButtonorderRibbon
  • Finally we can see that the “Note” Section is created in your Custom Pageimg3

By Puja Jain
Senior Software EngineerĀ @Team DynamicsCRM.
Mindfire Solutions

 
2 Comments

Posted by on August 1, 2013 in WebResources

 

Tags: , , , , , , , , , , , , , , ,

 
%d bloggers like this: