Tuesday, October 18, 2011

CRM 2011 Get OptionSetValue Label Text

In CRM 2011, when you try to get the value of an OptionSet, you will always get an Integer value instead of the label value.

Below is the Helper method which is used to retrieve the label of the selected option set

public static string GetOptionSetValueLabel(IOrganizationService service, Entity entity, string attribute, OptionSetValue option)
{
string optionLabel = String.Empty;

RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = entity.LogicalName,
LogicalName = attribute,
RetrieveAsIfPublished = true
};

RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest);
AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
PicklistAttributeMetadata picklistMetadata = (PicklistAttributeMetadata)attrMetadata;

// For every status code value within all of our status codes values
// (all of the values in the drop down list)
foreach (OptionMetadata optionMeta in
picklistMetadata.OptionSet.Options)
{
// Check to see if our current value matches
if (optionMeta.Value == option.Value)
{
// If our numeric value matches, set the string to our status code
// label
optionLabel = optionMeta.Label.UserLocalizedLabel.Label;
}
}

return optionLabel;
}

Thursday, September 15, 2011

CRM 2011 Developer toolkit

CRM 2011 Developer toolkit is awesome!!!!! cuts down lot of development/deployment time.

Recommend everyone to use it.

P.S :- Still has some minor known issues as of August 2011

Friday, July 29, 2011

Thursday, July 21, 2011

Page Large Result Sets with FetchXML

int fetchCount = 5000;
// Initialize the page number.
int pageNumber = 1;
string pagingCookie = null;
string fetchXml = Common.GetFetchXmlForComponentInfo(((EntityReference)entity.Attributes["neu_whatifmodelid"]).Id.ToString(), fiscalyear.ToString());
while (true)
{
string xml = Common.CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);
componentinfocollection = service.RetrieveMultiple(new FetchExpression(xml));
foreach (var c in componentinfocollection.Entities)
{
yearlyinfo.Add(
new ComponentYearlyInformation
{
ComponentId = c.Attributes.Contains("neu_componentid") ? ((EntityReference)c.Attributes["neu_componentid"]).Id : Guid.Empty,
name = c.Attributes.Contains("neu_name") ? (string)c.Attributes["neu_name"] : string.Empty,
YearlyExpenditure = c.Attributes.Contains("neu_yearlyexpenditure") ? (decimal)c.Attributes["neu_yearlyexpenditure"] : 0,
FullyFundedAmount = c.Attributes.Contains("neu_fullyfundedamount") ? (decimal)c.Attributes["neu_fullyfundedamount"] : 0
}
);


}

if (componentinfocollection.MoreRecords)
{
// Increment the page number to retrieve the next page.
pageNumber++;
pagingCookie = componentinfocollection.PagingCookie;
}
else
{
// If no more records in the result nodes, exit the loop.
break;
}

}


public static string CreateXml(string xml, string cookie, int page, int count)
{
StringReader stringReader = new StringReader(xml);
XmlTextReader reader = new XmlTextReader(stringReader);

// Load document
XmlDocument doc = new XmlDocument();
doc.Load(reader);

return CreateXml(doc, cookie, page, count);
}

public static string CreateXml(XmlDocument doc, string cookie, int page, int count)
{
XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

if (cookie != null)
{
XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
pagingAttr.Value = cookie;
attrs.Append(pagingAttr);
}

XmlAttribute pageAttr = doc.CreateAttribute("page");
pageAttr.Value = System.Convert.ToString(page);
attrs.Append(pageAttr);

XmlAttribute countAttr = doc.CreateAttribute("count");
countAttr.Value = System.Convert.ToString(count);
attrs.Append(countAttr);

StringBuilder sb = new StringBuilder(1024);
StringWriter stringWriter = new StringWriter(sb);

XmlTextWriter writer = new XmlTextWriter(stringWriter);
doc.WriteTo(writer);
writer.Close();

return sb.ToString();
}


Reference : http://msdn.microsoft.com/en-us/library/gg309717.aspx

Tuesday, July 19, 2011

CRM 2011 plug-in tips and tricks (part 1) - Dev...

CRM 2011 plug-in tips and tricks (part 1) - Dev...: "There are a lot of examples of writing CRM 2011 plug-ins in the SDK , but none of them really describe the process of testing, troubleshooti..."

Wednesday, July 6, 2011

Configuring PPS in Sharepoint 2010

Good Blog post to refer for configuring PPS in SharePoint 2010

http://manojvnair.blogspot.com/2011/05/configure-performancepoint-services-in.html

Thursday, June 9, 2011

Setting Attribute from javascript


Xrm.Page.getControl("neu_yearstart").setDisabled(false);
Xrm.Page.getAttribute("neu_yearstart").setValue(FiscalYearStart);
Xrm.Page.getAttribute("neu_yearstart").setSubmitMode("always");
Xrm.Page.getControl("neu_yearstart").setDisabled(true);


setSubmitMode as always will save the values to the database . if this value is not set then the value is not saved to the database but it will be visible in the front end

for example on change of one field you are setting other field then on the UI you can see the value as changed but when the user hits the save button the value is not saved to the database.


Saturday, June 4, 2011

Hide Custom Button when form is in create mode


 <RibbonDiffXml>
        <CustomActions>
          <CustomAction Id="org.button.Form.CustomAction" Location="Mscrm.Form.account.MainTab.Save.Controls._children" Sequence="1">
            <CommandUIDefinition>
              <Button Id="org.button.Form.WhatifButton" Command="org.button.Command" LabelText="What If Analysis" ToolTipTitle="Launch" ToolTipDescription="tooltip" TemplateAlias="o1" Image16by16="$webresource:neu_button16x16" Image32by32="$webresource:neu_button32x32" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>
        <Templates>
          <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
        </Templates>
        <CommandDefinitions>
          <CommandDefinition Id="org.button.Command">
            <EnableRules>
              <EnableRule Id="org.account.WebClient.EnableRule" />
            </EnableRules>
            <DisplayRules>
              <DisplayRule Id="org.account.WebClient.DisplayRule" />
            </DisplayRules>
            <Actions>
              <Url Address="$webresource:helloworld.html" PassParams="true" WinMode="0" WinParams="width=1100,height=760,toolbar=no,location=no,resizable =yes" />
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>
        <RuleDefinitions>
          <TabDisplayRules />
          <DisplayRules>
            <DisplayRule Id="org.account.WebClient.DisplayRule">
              <FormStateRule State="Create"
                              InvertResult="true" />
            </DisplayRule>
          </DisplayRules>
          <EnableRules >
            <EnableRule Id="org.account.WebClient.EnableRule">
              <CrmClientTypeRule Type="Web" />
            </EnableRule>
          </EnableRules>
        </RuleDefinitions>
        <LocLabels />
      </RibbonDiffXml>

Add a custom button to entity ribbon



<RibbonDiffXml>
  <CustomActions>
    <CustomAction Id="org.button.Form.CustomAction" Location="Mscrm.Form.account.MainTab.Save.Controls._children" Sequence="1">
      <CommandUIDefinition>
        <Button Id="org.button.Form.WhatifButton" Command="org.button.Command" LabelText="What If Analysis" ToolTipTitle="Launch" ToolTipDescription="30 Years What If Analysis" TemplateAlias="o1" Image16by16="$webresource:neu_button16x16" Image32by32="$webresource:neu_button32x32" />
      </CommandUIDefinition>
    </CustomAction>
  </CustomActions>
  <Templates>
    <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
  </Templates>
  <CommandDefinitions>
    <CommandDefinition Id="org.button.Command">
      <EnableRules>
      </EnableRules>
      <DisplayRules>
      </DisplayRules>
      <Actions>
        <Url Address="$webresource:helloworld.html" PassParams="true" WinMode="0" WinParams="width=1100,height=760,toolbar=no,location=no,resizable =yes" />
      </Actions>
    </CommandDefinition>
  </CommandDefinitions>
  <RuleDefinitions>
    <TabDisplayRules />
    <DisplayRules/>
    <EnableRules />
  </RuleDefinitions>
  <LocLabels />
</RibbonDiffXml>

Thursday, June 2, 2011

How to pass Parameters from one Plugin Step to Ano...

How to pass Parameters from one Plugin Step to Ano...: "here is the way to pass some paramters and get in between the steps in MS CRM 2011, while writing plugin. this can be done by using SharedV..."

Wednesday, June 1, 2011

Get CRM 2011 CrmSvcUtil.exe and the Plugin Registration Tool to Work With WIF on Windows XP

Microsoft Dynamics CRM 2011 makes heavy use of the new Windows Identity Framework.   This been heavily integrated into most of the tools out there for development with the CRM 2011 platform.  This includes CrmSvcUtil.exe and the new plugin / plug-in registration tool.  This also presents a headache for anyone who would like to do any development for CRM 2011 with a Windows XP machine as WIF will not install on an XP machine.  You need to have Vista SP1+, Windows 7, or Windows Server.

It seems that there is an "unsupported" workaround for this.

1. If you were to happen to navigate to the following folder (C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation) on a supported machine that has the Windows Identity Framework (WIF) already installed you might find some assemblies in the directory structure and it's sub folders.

There are four assemblies in my installation:
- Microsoft.IdentityModel.dll
- Microsoft.IdentityModel.resources.dll
- Microsoft.IdentityModel.WindowsTokenService.dll
- Microsoft.IdentityModel.WindowsTokenService.resources.dll

2. If you were to happen to (accidentally of course) copy these assemblies and move them to the same folder as the CrmSvcUtil.exe file or the executable for the Plugin Registration Tool, they will function normally without needing to install the whole WIF framework package.

To build the plugin registration tool you just copy the 4 assemblies from that folder structure to the bin\debug folder and build the tool using Visual Studio.   It then functions normally.

Here is an example from the forums where someone has gotten this to work for CrmSvcUtil, and I have personally done this for the Plugin Registration Tool.  You will also notice that I was the naysayer in the thread at the time :)
http://social.microsoft.com/Forums/en/crmdevelopment/thread/8d8bd121-a34c-402d-86fd-b3c47709a0b4

I hope this helps!

Tuesday, May 24, 2011

Encrypt appsettings in web.config


Below are the steps to do this

1)   Encrypt appsettings in web.config using Aspnet_regiis.exe
using Aspnet_regiis.exe you can encrypt whole section only not a particular key.so when you need to encrypt a particular key in appSettings things get complicated. Here is a roundabout way of doing this. Modify your web.config

2)   <configsections>
<section type="System.Configuration.NameValueSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="secureAppSettings" />

<appsettings>......</appsettings>

<secureappsettings>
<add key="ipwd" value="secure-password"/>
</secureappsettings>
</configsections>

3)   Under secureAppSettings you can add any key value pairs.

Also secureAppSettings is the name i had given. You can give any. Save this web.config file and go to visual studio command prompt

4)   Type

aspnet_regiis -pef secureAppSettings  “ur web.config path”  -prov DataProtectionConfigurationProvider


5)   In code you can access it as usual

NameValueCollection secureAppSettings = (NameValueCollection)ConfigurationManager.GetSection("secureAppSettings")
String str= secureAppSettings["ipwd"];

Saturday, May 21, 2011

SQL Timeouts in CRM 4.0 - import of customizations fail


When importing customizations to CRM 4.0, the import fails with a message "generic SQL error". Digging a bit deeper the error message is really that a timeout has occured. The same error occurs when trying to create a new entity.
I increased the timeout as suggested in the link below
Increasing the timeout:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM\OLEDBTimeout
This value does not exist by default, and if it does not exist then the default value will be 30 seconds. To change it, add the registry value (of type DWORD), and put in the value you want (measured in seconds). Then you have to recycle the CrmAppPool application pool for the change to take effect

By Increasing the time out in the registry will solve the problem. Number of seconds depends on the amount of data in the database.


Tuesday, May 10, 2011

Set Lookup Field While Updating/Creating Record from Jscript Using CRM REST End Point


    var newaccount= new Object();
 
    newaccount.neu_name = "test";
    var contact_ref = new Object();
    contact_ref .Id = contactid;
    contact_ref .LogicalName = "contact";
    contact_ref .Name = "test contact";

    newaccount.primarycontactid = neumodelyear_ref;

//createRecord Method is available in jqueryrestdataoperationfunctions.js in SDK
    createRecord(newaccount, "accountSet", createnewaccountcompleted, null);

References:
http://technet.microsoft.com/es-ar/library/gg334767(en-us).aspx
http://technet.microsoft.com/en-us/library/gg309638.aspx
http://technet.microsoft.com/en-us/library/gg309558.aspx
http://msdn.microsoft.com/en-us/library/gg334427(MSDN.10).aspx

Wednesday, May 4, 2011

Generating EarlyBound CRM Entities using crmsvcutil.exe

To generate XRM.cs navigate to the sdk bin folder from the command prompt and use the below command
NOTE: This command works for crm 2011 online environment

CrmSvcUtil.exe /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration"   /url:https://crmtest.api.crm.dynamics.com/XRMServices/2011/Organization.svc   /out:Xrm.cs   /username:liveid   /password:password   /deviceid: deviceid /devicepassword: devicepassword   /namespace:Xrm   /servicecontextname:XrmServiceContext  /servicecontextprefix:Xrm


References:
http://msdn.microsoft.com/en-us/library/gg695782.aspx

Friday, April 29, 2011

Fetch XML 5000 Records Limitation


Have you ever tried to write a code which will get you all records from a specific entity? It's harder then you think it is! Everybody who is a bit aware of the CRM SDK thinks it should be a fetch statement like this:

<fetch mapping='logical'><entity name='account'><attribute name='accountid'/></entity>

WRONG!
This would only give you the first 5000 records in the database! It is written down in the SDK with small letters, but it could drive you crazy..

There are two solutions for this issue.
1) Add a registery setting to specify not to implement MaxRowsPerPage
2) Modify the fetch statement and merge several results

Here are the details for each solution
1st solution
Search in the SDK for the word "TurnOffFetchThrottling". You should add this as DWORD registery setting to HKLM\Software\Microsoft\MSCRM. Set the value to 1. You will now not have the 5000 records limit.

2nd solution
Modify your fetch statement to include paging and count numbers. Store all the data in an DataSet and perform that series of code over and over again as long as there is data coming.

Here's the script you should use to get all accountid's (for clarity and the ease of use I have added a function called "FetchDataSet").


private DataSet FetchAllAccountIds(){
int i=1;
bool bFinished = false;
DataSet dsAllData = new DataSet();
while (bFinished == false)
{
StringBuilder sbFetch = new StringBuilder();
sbFetch.AppendFormat("<fetch mapping='logical' page='{0}' count='5000'>", i);
sbFetch.Append("<entity name='account'>");
sbFetch.Append("<attribute name='accountid'/>");
sbFetch.Append("<attribute name='new_12_accountid'/>");
sbFetch.Append("</entity>");
sbFetch.Append("</fetch>");
DataSet dsTempResult = FetchDataSet(sbFetch.ToString());
dsAllData.Merge(dsTempResult);
if (dsTempResult.Tables[0].Rows[0]["morerecords"].ToString() == "0")
{
bFinished = true;
}
else
{
i++;
}
}
return dsAllData;
}

private DataSet FetchDataSet(string fetchXml)
{
string strResult = service.Fetch(fetchXml);
DataSet ds = new DataSet();
System.IO.StringReader reader = new System.IO.StringReader(strResult);
ds.ReadXml(reader);
return ds;
}


I hope this saves you some time!

Tuesday, April 26, 2011

Update Entity Record Using Rest EndPoint

Updating Complex Attribute types using rest end point in Jscript

          
            var lineitem = new Object();

             //Money Type Attribute
             var neu_amountchange_ref = new Object();
             neu_amountchange_ref.Value = neu_amountchange;
             lineitem.neu_AmountChange = neu_amountchange_ref;

             lineitem.neu_PercentChange = neu_percentchange;
             //updateRecord exists in JQueryRESTDataOperationFunctions.js
             updateRecord(id, lineitem, "neu_whatifmodellineitemSet", updateWhatifLineItmeCompleted, null);

Wednesday, April 20, 2011

Parse Json Date


 function getDateStringFromJson(jsondate) {

     var date = new Date(parseInt(jsondate.replace(/^\/Date\((\d+)\)\/$/gi, '$1'), 10));
     var curr_date = date.getDate();
     var curr_month = date.getMonth();
     curr_month = curr_month + 1;
     var curr_year = date.getFullYear();
     date= curr_month + '/'+ curr_date + '/'+ curr_year;
     return date;
 }

Friday, March 25, 2011

Get FetchXml From Advanced Find (CRM 4.0)

Open the advanced find and press CTRL+N , This will open the advanced find view in the new window.
Now design the query and click on the query button

In the address bar copy and paste the below script and press enter

javascript:void( new function() { var s=""; function f(p){ s+= p + "=" + eval("advFind." + p) + "\n\n"};f("FetchXml");prompt("my query:",s) } )


You will get the fetchxml in an alert



Thursday, March 17, 2011

Connecting to CRM 2011 Online


Connecting to CRM 2011 in the Cloud is trickier than connecting to CRM 2011 On Premise.

Check c:\Program Files to see if you have Windows Identity Foundation. If not you will need to install it.

You need to get some device credentials and this is done using a utility in the CRMSDK called DEVICEREGISTRATION. Go to \sdk\tools\deviceregistration directory and load deviceregistration.csproj. Compile the application and navigate to the \bin\debug folder. Open a command window and type

deviceregistration.exe /operation:Register

Thursday, February 17, 2011

PowerPivot tutorial videos


PowerPivot Video Tutorial
Materials

Set 1
Set 2
If you are interested in Business Intelligence video tutorials, I would recommend you to visit Microsoft’s Channel 9, plenty more of the good stuff there.

Converting multiple rows into a single comma separated row



Create Table #Names (name varchar(10))

Insert Into #Names(name) values ('varun')
Insert Into #Names(name) values ('vinod')
Insert Into #Names(name) values ('manognya')
Insert Into #Names(name) values ('aradhana')
Insert Into #Names(name) values ('manoj')

SELECT * FROM #Names

SELECT STUFF((SELECT   ', '+  name as [text()] from #Names  FOR  XML PATH('')),1,2,'')

DROP Table #Names




Microsoft Dynamics CRM 2011 Released for On-Premises and Partner-Hosted Deployments

Microsoft Corp. (Nasdaq “MSFT”) today announced that Microsoft Dynamics CRM 2011 for on-premises and partner-hosted deployments has been completed and released for customer download. This release complements the latest version of Microsoft Dynamics CRM Online, which delivers Microsoft Dynamics CRM 2011 as an on-demand service from Microsoft’s datacenters and was launched into 40 markets and 41 languages in January. With a single multitenant code base across cloud and on-premises deployment models, Microsoft Dynamics CRM 2011 delivers the Power of Productivity to sales, service and marketing organizations worldwide.

Microsoft Dynamics CRM 2011 is now globally available and existing customers with active Microsoft Software Assurance agreements can access the new version immediately via the Microsoft Download Center. ( http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c3f82c6f-c123-4e80-b9b2-ee422a16b91d ).

Read the rest of the press release here: http://www.microsoft.com/Presspass/press/2011/feb11/02-16OnPremisesPR.mspx

Congratulations to the CRM program team from the 12,000 members of the Microsoft Dynamics CRM. LinkedIn community.