Wednesday, September 28, 2011

Debugging Silverlight Web Resources in CRM2011

In CRM2011, Silverlight Web resources can be debugged in Microsoft Visual Studio. For this you need to follow below steps:

• Build your Silverlight application.

• Upload the built version of the .xap file from the Web application project ClientBin folder.

• View your Silverlight application in the context it is designed to be used in.

• In your Silverlight application project, from the Visual Studio menu, select Debug and then Attach To Process….

• In the Attach to Process dialog box, find an iexplore.exe process where the Type column value is Silverlight, x86. (See below screen shot)



• Select that process and press Attach to close the dialog box and start debugging.

• In your Silverlight application project, set a breakpoint.

• Refresh the browser window or, in the Silverlight application, perform the action that you need to test your code.

Hope this help

Wednesday, September 21, 2011

Working with Charts in CRM 2011

Dynamics CRM 2011 provides us the Charts, with the help of the Charts we can Graphically represent the Organization data. We can create the System Charts and User Charts in the CRM. The System Chats can be viewed by the All users of the Organization and the User Charts can only be view by those whom the Chart Assigned or Shared.

We can create the following different form of charts:
• Column
• Bar
• Line
• Pie
• Funnel

To create a chart, specify fields to be displayed on the category and series axes. Normally, the category axis displays data from numeric or non-numeric fields. The series axis displays data from numeric fields.

The Chart Designer supports creating only single-series charts. To create multi-series charts or comparison charts, we need to write the code.

Also we can Export and Import the Charts.

Note: We can create and attach charts to only those record types in Microsoft Dynamics CRM that support the new ribbon interface in the Web application. This is because all of the chart controls are only present in the ribbon interface of Microsoft Dynamics CRM.

We can create the charts from the CRM Views or by the Coding.

Create the Charts through CRM Views: You need to create the CRM view on the required Entity and then create the chart on this. As shown in the below screen shot we have create the view of all opportunity and then create the Sales Pipeline Chart for that view. As shown in the below screenshot.




Now open the Opportunity Entity and Create the Chart as shown in the below screenshot.






Create the Chart by the Coding:

Below we have given that how to create the Sample Chart through Coding.

To create the chart the Main things are the Fetch XML, Data XML and the Presentation XML.
 Suppose if you need to create the Sales Pipe line funnel then you need to create the following three items.
1.       Fetch XML View: For creating the fetch xml view, you need to create the Saved Query for that as given below.

                           savedquery newSavedQuery = new savedquery();
               newSavedQuery.name = "Sales Pipeline Funnel";
               newSavedQuery.fetchxml = @"
                                      <fetch version='1.0'
                                             output-format='xml-platform'
                                             mapping='logical'
                           distinct='false'>
                                             <entity name='opportunity'>
               <attribute name='name'/>
               <attribute name='customerid'/>
                         <attribute name='estimatedvalue'/>
               <attribute name='statuscode'/>
               <attribute name='opportunityid'/>
               <order attribute='name' descending='false'/>
                           </entity>
                                      </fetch>
                       ";
               newSavedQuery.returnedtypecode = EntityName.opportunity.ToString();
               newSavedQuery.layoutxml = @"<grid name='resultset' object='3' jump='name'
               select='1' icon='1' preview='1'>
               <row name='result' id='opportunityid'>
                       <cell name='name' width='300' />
                       <cell name='customerid' width='150' />
                                      <cell name='estimatedvalue' width='100' />
                                      <cell name='statuscode' width='100' />
               </row>
                                </grid>";
               newSavedQuery.querytype = new CrmNumber();

 newSavedQuery.querytype.Value = SavedQueryType.MainApplicationView;

 Guid viewId = service.Create(newSavedQuery);
2.       Presentation: Then you need to write the following Presentation for that.
string presentationXml = @"
    <Chart Palette='BrightPastel'>
        <Series>
            <Series _Template_='All' ShadowOffset='2' 
BorderColor='64, 64, 64' BorderDashStyle='Solid' 
BorderWidth='1' IsValueShownAsLabel='true' 
Font='Tahoma, 6.75pt, GdiCharSet=0' 
LabelForeColor='100, 100, 100' 
CustomProperties='FunnelLabelStyle=Outside' 
ChartType='Funnel'>
    <SmartLabelStyle Enabled='True' />
    <Points />
            </Series>
        </Series>
        <ChartAreas>
            <ChartArea _Template_='All' BackColor='Transparent' 
BorderColor='Transparent' BorderDashStyle='Solid'>
<Area3DStyle Enable3D='True' IsClustered='True' />
            </ChartArea>
        </ChartAreas>
        <Legends>
            <Legend _Template_='All' Alignment='Center' 
LegendStyle='Table' Docking='Bottom' 
IsEquallySpacedItems='True' BackColor='White' 
BorderColor='228, 228, 228' BorderWidth='0' 
Font='Tahoma, 8pt, GdiCharSet=0' 
ShadowColor='0, 0, 0, 0' ForeColor='100, 100, 100'>
            </Legend>
        </Legends>
        <Titles>
            <Title _Template_='All' 
Font='Tahoma, 9pt, style=Bold, GdiCharSet=0' 
ForeColor='102, 102, 102'>
            </Title>
        </Titles>
        <BorderSkin PageColor='Control' 
            BackColor='CornflowerBlue' 
            BackSecondaryColor='CornflowerBlue' />
    </Chart>";
 
3.       Data Xml: Below we have created the Data XML for that. In the Data XML we need to provide the Presentation and the Fetch XML view Id, as given below.
// Set the data XML string.
string dataXml = @"
    <datadefinition>
        <fetchcollection>
            <fetch mapping='logical' 
count='10' 
aggregate='true'>
<entity name='opportunity'>
    <attribute name='estimatedvalue_base' 
        aggregate='sum' 
        alias='sum_estimatedvalue_base'/>
    <attribute name='stepname' groupby='true' alias='stepname'/>
    <order alias='stepname' descending='false' />
</entity>
            </fetch>
        </fetchcollection>
        <categorycollection>
            <category>
<measurecollection>
    <measure alias='sum_estimatedvalue_base'/>
</measurecollection>
            </category>
        </categorycollection>
    </datadefinition>";
 
// Create the visualization entity instance.
savedqueryvisualization newSavedQueryVisualization = new savedqueryvisualization();
 
newSavedQueryVisualization.name = "Example Visualization";
newSavedQueryVisualization.presentationdescription = presentationXml;
newSavedQueryVisualization.datadescription = dataXml;
newSavedQueryVisualization.savedqueryid = new Lookup();
newSavedQueryVisualization.savedqueryid.Value = viewId;
 
Guid newSavedQueryVisualizationId = service.Create(newSavedQueryVisualization);
After doing the above things please call the Publish request, As given below.
//Publish the Opportunity entity customizations.
PublishXmlRequest request = new PublishXmlRequest();
 
request.ParameterXml = @"
      &ltimportexportxml&gt
            &ltentities&gt
&ltentity&gtopportunity&lt/entity&gt
&lt/entities&gt
            &ltnodes/&gt
            &ltsecurityroles/&gt
            &ltsettings/&gt
            &ltworkflows/&gt
        &lt/importexportxml&gt";
   // Execute the request.
PublishXmlResponse response = (PublishXmlResponse)service.Execute(request);
 For more details about the Charts you can use the following link.
Also you can refer the CRM 2011 SDK.




Tuesday, September 13, 2011

How to interact with CRM form fields from within the Silverlight page

At times you may have a need to interact with the CRM form to read/update back the latest information after the processing completes from a custom application.

Say we add a button on the Entity form and when user will click on this button then we can read as well as set the value of the entity form fields. Below we have given the example to read the activityparty.

When you click on the button then it will open a child window. To access the CRM form we will need to use the Parent window from which this child window was called. Here we are reading the values of the Sender attribute of the Email.

dynamic win = HtmlPage.Window;
dynamic opener = win.parent.opener;
ScriptObject xrm = (ScriptObject)opener.GetProperty("Xrm");
ScriptObject page = (ScriptObject)xrm.GetProperty("Page");
dynamic dynamicPage = page;

dynamic lookupItems = dynamicPage.data.entity.attributes.get("to").getValue();
HtmlPage.Window.Invoke("readLookup", lookupItems);

“To” attribute is of the type lookup and it will be an array of objects. To read the values for this lookup you need to write the following script on the html page.

function readLookup(source) {

if (source == null) {
return;
}

var array = new Array();
array = source;
for (i = 0; i < array.length; i++) {
alert(array[i].entityType);
alert(array[i].id);
alert(array[i].name);
}

}

Now say you want to update the Subject of the Email from within the Silverlight custom application, you can refer the CRM form and update the controls on the form as shown below

dynamicPage.data.entity.attributes.get("subject").setValue("Test 1234");

Since Subject is a text field it could be done as simply as above.

But to set the value for the lookup and date type of attributes, there is still more to be done. For this we need to add a java script web resource on the required entity. This web resource will contain the function to set the lookup and the date value. We then need to call this function from the Silverlight page. Code below explains how this can be done

dynamic parent = win.parent.opener;
parent.setLookupValue();
he SetLookupValue will contain the code to set the value for the lookup. As given below.

Xrm.Page.data.entity.attributes.get("regardingobjectid").setValue(array);


Hope this helps in designing richer Silverlight applications that interact better with the CRM forms.

Tuesday, September 6, 2011

Retrieve related entity records along wih the Primary entity using Retrieve Method

We have always known the Retrieve request to be able to retrieve the data of the requested entity based on the id provided. However in CRM 2011, the Retrieve request can read not only the properties of the primary entity but also the referenced entity like in a 1-N or N-N or N-1 relationship. Given that it supports all the three types of relationships it could be an advantage over the LinkEntity feature.

For example, if we want to retrieve the active contacts related to an account then, we can design the query as shown in the below code,

using (OrganizationServiceProxy _orgserviceproxy = new OrganizationServiceProxy(new Uri(OrganizationUri), null, Credentials, null))
{

//create the query expression object
QueryExpression query = new QueryExpression();

//Query on reated entity records
query.EntityName = "contact";

//Retrieve the all attributes of the related record
query.ColumnSet = new ColumnSet(true);

//create the relationship object
Relationship relationship = new Relationship();

//add the condition where you can retrieve only the account related active contacts
query.Criteria = new FilterExpression();
query.Criteria.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, "Active"));

// name of relationship between account & contact
relationship.SchemaName = "contact_customer_accounts";

//create relationshipQueryCollection Object
RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();

//Add the your relation and query to the RelationshipQueryCollection
relatedEntity.Add(relationship, query);

//create the retrieve request object
RetrieveRequest request = new RetrieveRequest();

//add the relatedentities query
request.RelatedEntitiesQuery = relatedEntity;

//set column to and the condition for the account
request.ColumnSet = new ColumnSet("accountid");
request.Target = new EntityReference { Id = accountID, LogicalName = "account" };

//execute the request
RetrieveResponse response = (RetrieveResponse)_orgserviceproxy.Execute(request);

// here you can check collection count
if (((DataCollection)(((RelatedEntityCollection)(response.Entity.RelatedEntities)))).Contains(new Relationship("contact_customer_accounts")) &&((DataCollection)(((RelatedEntityCollection)(response.Entity.RelatedEntities))))[new Relationship("contact_customer_accounts")].Entities.Count > 0)
return true;
else
return false;
}

One limitation though, is that it is only available with the Retrieve Request and not the Retrieve Multiple request. Wonder why this has not be added for Retrieve Multiple request as this can be of great help to return all the data required in one request.