serving the solutions day and night

Pages

Wednesday, September 11, 2013

MS Dynamics CRM Web Services 2011

MS Dynamics CRM 2011 provides two Web services. These services can be used to identify your organization and to access MS Dynamics CRM data.

IDiscoveryService Web Service - A single MS Dynamics CRM installation can host multiple organizations on multiple servers. The IDiscoveryService Web service returns a list of organizations that the specified user belongs to and the URL endpoint address for each organization.
http[s]://< hostname[:port]>/XRMServices/2011/Discovery.svc

To access the IDiscoveryService Web service, use Microsoft.Xrm.Sdk.dll assembly -> Microsoft.Xrm.Sdk.Discovery namespace.
Use the Execute method to execute a discovery service message.
RetrieveOrganizationRequest - Retrieves information about a single organization.
RetrieveOrganizationsRequest - Retrieves information about all organizations to which the user belongs.
RetrieveOrganizationsResponse

IOrganizationService Web Service - The Web service for accessing data and metadata in MS Dynamics CRM 2011
Organization Service Methods - Create, Retrieve, RetrieveMultiple, Update, Delete, Associate ( create a link between two records), Disassociate, Execute

IOrganizationService Entities

Best Practices for Developing with Microsoft Dynamics CRM

Tuesday, September 10, 2013

Programming Models for MS Dynamics CRM 2011


Key programmability scenarios for MS Dynamics CRM 2011



Early-bound – MS Dynamics CRM 2011 uses an entity data model and Windows Communication Foundation (WCF) Data Services technologies to provide a new set of tools that interact with Microsoft Dynamics CRM. For example: an organization service context that tracks changes to objects and supports .NET Language-Integrated Query (LINQ) queries to retrieve data from MS Dynamics CRM. Early bound classes generated directly from the metadata, which include all customizations.
CrmSvcUtil.exe - CRM Dynamics 2011 Code Generation Tool


Improve PrincipalObjectAccess (POA) and AsyncoperationBase table performance in MS Dynamics CRM 2011

PrincipalObjectAccess (POA) table

Grant permission for a user to see/edit/delete a record in CRM.

Permissions are granted is through either Direct or Inherited shares. 

Direct Shares are the user shares a record to another user or team through the 'share' button in the ribbon. These records will have a value in the AccessRightsMask colum of the POA table.

Inherited Shares are the result of a number of different configuration rules – such as the shares that cascade to an object based on the ownership of its parent record, Custom code that shares a record, or by the system due to relationship behaviors or system settings. These records will have a value in the InheritedAccessRightsMask colum of the POA table.

The shares granted on objects in CRM are stored in the PrincipalObjectAccess (POA) system table. Since almost every access to CRM data interacts with the POA table.

Friday, September 6, 2013

MS Dynamics CRM 2011 - Display Lists/Views Dynamically

Audit_matchlist.htm - HTML Page Code

This page will build fetchxml, display event list from event entity, matchtype option set, and bind the result in the frame.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
    <meta content="utf-8" http-equiv="encoding"/>
    <meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
    <meta http-equiv="CACHE-CONTROL" content="NO-CACHE"/>
    <link href="/WebResources/dns_CSS/audit.css" rel="Stylesheet" />

    <script src="../ClientGlobalContext.js.aspx" type="text/javascript"></script>
    <script src="/WebResources/dns_JavaScript/Jquery1.4.1.min.js" type="text/javascript" language="javascript"></script>
    <script src="/WebResources/dns_JavaScript/Jason.js" type="text/javascript" language="javascript"></script>
    <script src="/WebResources/dns_JavaScript/advancedfindview.js" type="text/javascript" language="javascript"></script>
    <script src="/WebResources/dns_JavaScript/DataOperations.js" type="text/javascript" language="javascript"></script>
    <script src="/WebResources/dns_JavaScript/audit.js" type="text/javascript" language="javascript"></script>
    <script type="text/javascript">
        var ECMRole = CheckUserRole("ECM");
       
        //alert(window.location.href);

Wednesday, September 4, 2013

MS Dynamics CRM - Bulk Delete using XRM

Import
MSDynamicsCRM2011.DNS.Entities
microsoft.crm.sdk.proxy
microsoft.xrm.client
microsoft.xrm.sdk
System.ServiceModel
System.Data.DataSetExtensions

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using GCEntity = BT.CRM2011.DNS.Entities;
using System.ServiceModel.Description;

namespace CRM.Audit.BulkDelete
{
    class Audit
    {
        private BulkDeleteResponse _bdRes;
        private Guid _bdResID;
        private Guid _bdGUID;
        private ConditionExpression _conExp;

//Delete Method
        public void Delete()
        {
            SystemJob(GCEntity.dns_audit.EntityLogicalName, "Audit Bulk Delete - Code", _conExp);
            Console.WriteLine("Audit Deleted");
            SystemJob(GCEntity.Contact.EntityLogicalName, "Contact Bulk Delete - Code", _conExp);
            Console.WriteLine("Contact Deleted");
            Console.ReadLine();
        }

Tuesday, September 3, 2013

MS Dynamics CRM 2011 - Ribbon Drop Down Menu

This blog will guide you, how to create drop down menu from the ribbon. It contains one group or button ('Audit') ,2 drop down menu and their commands/actions.



 1) Create a solution contains Application Ribbons and Site Map.

Friday, August 30, 2013

MS Dynamics CRM 2011 - EnableRule, ValueRule, OrRule & CustomRule in Ribbon Customizations

ValueRule - Enable the Custom button only when a specific filed on the form has a value.
For example, if the 'Email' field has value then the custom will be enable otherwise it will disable.

/RibbonDiffXml/RuleDefinitions/EnableRules/EnableRule/

<EnableRule Id="DNS.contact.form.EmailValue.EnableRule">
    <ValueRule Field="email" Value="null" InvertResult="true"/>
</EnableRule>

EnableRule for mulitple fields, use 'OrRule', for example

<EnableRule Id="DNS.contact.form.EmailValue.EnableRule">
    <OrRule>
        <Or>
            <ValueRule Field="email" Value="null" InvertResult="true"/>
        </Or>
        <Or>
              <ValueRule Field="leadsourcecode" Value="810520005"/>
        </Or>
    </OrRule>
</EnableRule>
           
EnableRule only works with Equal(=) condition, for different conditions (not equal) use 'InvertResult' attribute.

Refer the above id in the following location /RibbonDiffXml/CommandDefinitions/CommandDefinition/EnableRules

<EnableRule Id="Sample.account.form.CheckFaxValue.EnableRule"/>

CustomRule - call a javascript function based on the result.

<EnableRule Id="DNS.contact.form.EmailValue.EnableRule">
  <CustomRule FunctionName="DisableReportButton" Library="$webresource:dns_JavaScript/reports.js" Default="true" />
</EnableRule>

http://msdn.microsoft.com/en-us/library/gg334317.aspx
http://msdn.microsoft.com/en-us/library/gg328073.aspx
http://msdn.microsoft.com/en-us/library/gg309433.aspx

Thursday, August 29, 2013

Show Pipeline Custom Component in Visual Studio ToolBox

Show Pipeline Custom Component in Visual Studio ToolBox

Add the below code in the Project Build Events

"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\GacUtil.exe" /i "$(TargetPath)" /f
xcopy "$(TargetPath)" "C:\Program Files (x86)\Microsoft BizTalk Server 2010\Pipeline Components" /d /y



MS Dynamics CRM 2011 - Paging Retrieve Multiple Records

QueryExpression query = new QueryExpression(Contact.EntityLogicalName);
EntityCollection coll;
query.PageInfo.PageNumber = 1;
query.ColumnSet = new ColumnSet("firstname", "lastname");
do
{
    int RecordId = 1;
    coll = CRMServiceProxy.RetrieveMultiple(query);
    foreach (Entity e in coll.Entities)
    {
        Console.WriteLine(query.PageInfo.PageNumber + " - " + RecordId + " - " + e.Attributes["firstname"] + " - " + e.Attributes["lastname"]);
        RecordId++;
    }
    query.PageInfo.PageNumber++;
}
while (coll.MoreRecords);


public static OrganizationServiceProxy CRMServiceProxy
        {
            get
            {
                var uri = new Uri(System.Configuration.ConfigurationManager.AppSettings["CrmOrganizationUri"]);

                //Authenticate using credentials of the logged in user;      
                var cnt = new ClientCredentials();
                cnt.Windows.ClientCredential.Domain = System.Configuration.ConfigurationManager.AppSettings["CrmDomain"].ToString();
                cnt.Windows.ClientCredential.UserName = System.Configuration.ConfigurationManager.AppSettings["CrmUserName"].ToString();
                cnt.Windows.ClientCredential.Password = System.Configuration.ConfigurationManager.AppSettings["CrmPassword"].ToString();
                //cnts.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;

                var sp = new OrganizationServiceProxy(uri, null, cnt, null);
                sp.EnableProxyTypes();

                return sp;
            }
        }

Avoid Empty Nodes Using Table Looping Functoid in BizTalk

Avoid Empty Nodes Using Table Looping Functoid in BizTalk

You will find out lot of several posts to avoid empty nodes using Table Looping Functoid
My Flat Source File looks like this

SIDNameTitleSub1Sub1FeeSub2Sub2FeeSub3Sub3FeeSub4Sub4FeeSub5Sub5FeeRemark
1ABCDSWA12.50None
2BCDEDBAB13.50C15.00Completed


Flat file converted to the XML (StudentIn.xml) using pipeline components

Mapping


Monday, August 12, 2013

MS Dynamics CRM - Security Role

I have one situation, login user has multiple security roles, if the login user has permission for particular role, show some buttons/fields otherwise the hide buttons/fields.

It is not stright forward to find out the security role, So i wrote one javascript to find out the security role.

<script src="../ClientGlobalContext.js.aspx" type="text/javascript"></script>
<script src="/WebResources/gab_JavaScript/Jquery1.10.2.min.js" type="text/javascript" language="javascript"></script>
<script src="/WebResources/gab_JavaScript/Jason.js" type="text/javascript" language="javascript"></script>

function context() {
    if (typeof GetGlobalContext != "undefined") {
        return GetGlobalContext();
    }
    else {
        if (typeof Xrm != "undefined") {
            return Xrm.Page.context;
        }
    }
}

function GetServerUrl() {
    var Crmurl = window.location;
    var orgName = context().getOrgUniqueName();
    return Crmurl.protocol + "//" + Crmurl.host + "//" + orgName + "/xrmservices/2011/OrganizationData.svc/";
}

Here i am checking the user has "Content Manager" security role or not.

function BookAuditMatch() {
   var ECMRole = CheckUserRole("Book Content Manager");
   if (ECMRole) {
      //Do something
   }
}

This function will get all the user's security role Id, passing security role id to get the security role name. If it match, it is true otherwise false.
function CheckUserRole(roleName) {
    var currentUserRoles = Xrm.Page.context.getUserRoles();
    for (var i = 0; i < currentUserRoles.length; i++) {
        var userRoleId = currentUserRoles[i];
        var userRoleName = GetRoleName(userRoleId);
        if (userRoleName == roleName) {
            return true;
        }
    }
    return false;
}

This function calling odata web service and get the each security role name.
function GetRoleName(userRoleId) {
    var selectQuery = "RoleSet?$top=1&$filter=RoleId eq guid'" + userRoleId + "'&$select=Name";
    var VoterAddress = "";
    var odataSelect = GetServerUrl() + selectQuery;
    //alert(odataSelect);
    var roleName = null;
    $.ajax({
        type: "GET",
        async: false,
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: odataSelect,
        beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
        success: function (data, textStatus, XmlHttpRequest) {
            var result = data.d;
            if (!!result) {
                roleName = result.results[0].Name;
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            //alert('OData Select Failed: ' + odataSelect);
        }
    });
    return roleName;
}

File Lock Error In Visual Studio

Your project dll is referenced by another project, when you trying to build a project, you will get file lock issue in visual studio,

Unable to copy file "obj\Debug\BizTalk.MSDynamicsCRM2011.Schemas.dll" to "bin\BizTalk.MSDynamicsCRM2011.Schemas.dll". The process cannot access the file 'bin\BizTalk.MSDynamicsCRM2011.Schemas.dll' because it is being used by another process.




if exist "$(TargetPath).locked" del "$(TargetPath).locked"
if exist "$(TargetPath)" if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked"

if exist "$(ProjectDir)bin\$(TargetFileName).locked" del "$(ProjectDir)bin\$(TargetFileName).locked"
if exist "$(ProjectDir)bin\$(TargetFileName)" if not exist "$(ProjectDir)bin\$(TargetFileName).locked" move "$(ProjectDir)bin\$(TargetFileName)" "$(ProjectDir)bin\$(TargetFileName).locked"

Register dll in 'C:\Windows\Microsoft.NET\assembly\GAC_MSIL'
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\GacUtil.exe" /i "$(TargetPath)" /f

Wednesday, July 31, 2013

Dynamics CRM - Cross-Site Scripting Filter

In CRM, if your customization fetch xml contain extra attribute name which is does not belong in the Saved View, then IE will throw
"Internet Explorer has modified this page to help prevent cross-site scripting. Click here for more information... "



Example
Saved View contains - firstname, lastname
Cusomization fetch XML contain middlename
var fetchBaseXML = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">';
            fetchBaseXML += '    <entity name="contact">';
            fetchBaseXML += '        <attribute name="middlename" />';
            fetchBaseXML += '        <attribute name="lastname" />';
            fetchBaseXML += '        <attribute name="firstname" />';
           
Solution 1
Remove the attribute name from the customization fetch OR Add the attribute name in the Saved View.

Solution 2
Click Tools > Internet options > Security and click the Custom Level... button.
Scroll down the list and click the Disable radio button for the Enable XSS-filter option.
Restart the browser.
Click the Submit button again in the Report Administration screen in Maximo, and the SmartCloud Cost Management reports are now displayed.

Saturday, June 8, 2013

Retrieve Multiple Dynamics CRM 2011 Entity Records from BizTalk 2010 Server

Retrieve Multiple Dynamics CRM 2011 Entity Records from BizTalk 2010 Server
1)Create new map (MCRM_List.btm)

2) Added <Fetch><Query/></Fetch> schema in the SAuditXML.xml schema

3)Select Source Schema (SAuditXML), Desitnation Schema(DNS_BTS_CRM.organixationservice_schemas_microsoft_com_xrm_2011_contracts_services -> RetrieveMultiple)

4)Make Query(source) link to FetchExpression->Query(Destination)

Create/Update/Delete Dynamics CRM 2011 Entity Record from BizTalk 2010 Server

Create Dynamics CRM 2011 Entity Record from BizTalk 2010 Server

1)Create new map (MCRM_Create.btm)

2)Select Source Schema (SAuditXML), Desitnation Schema(DNS_BTS_CRM.organixationservice_schemas_microsoft_com_xrm_2011_contracts_services -> Create)

3)Rename Page name (Enity), make EnityName(source) link to LogicalName(Destination)


Thursday, June 6, 2013

Dynamics CRM 2011 and BizTalk 2010 Server Integration - Exception


Exception 1
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://schemas.microsoft.com/xrm/2011/Contracts/Services:entity. The InnerException message was 'There was an error deserializing the object of type Microsoft.Xrm.Sdk.Entity. End element 'value' from namespace 'http://schemas.datacontract.org/2004/07/System.Collections.Generic' expected. Found element 'Value' from namespace 'http://schemas.microsoft.com/xrm/2011/Contracts'. Line 1, position 4190.'. Please see InnerException for more details.

Solution
Data Type is wrong.

For example, In CRM attribute type is int, but in BizTalk Schema contains string and in the Map, Script Functionid contains <xsl:attribute name="xsi:type"><xsl:value-of select="'xs:string'" /> , the CRM will throw the above error.

Change to  int in the schema and <xsl:attribute name="xsi:type"><xsl:value-of select="'xs:int'" /> in the Map

Tuesday, June 4, 2013

Dynamics CRM 2011 and BizTalk 2010 Server Integration - Handling Fault Exception

Dynamics CRM 2011 and BizTalk 2010 Server Integration - Handling Fault Exception

1)Refer the previous blog Querying Dynamics CRM 2011 Entrity Record from BizTalk 2010 Server

 
2)Right click the project -> Select Add -> New Item ->  Schema (SFault.xsd) -> Press 'Add' button


Monday, June 3, 2013

Select Dynamics CRM 2011 Entity Record from BizTalk 2010 Server

Dynamics CRM 2011 BizTalk 2010 Server Integration - Select Dynamics CRM 2011 Entity Record from BizTalk 2010 Server

Step 1 - Create Schema and Orchestration

1)Import Dynamics CRM 2011 Organization Service SOAP Protocol to BizTalk Server 2010
   Create New Project (CRMORGSOAP.dll) and add refernece to this project.

2)Right click the project -> Signing -> Check 'Sign the assembly' -> Create <New> 'Strong Name     Key' or <Browse> existing one
  Select Deployment -> Enter Application Name ('DNS_BTS_CRM') -> Restart Host Instances - True
 
3)Right click the project -> Select Add -> New Item ->  Schema (SAudit.xsd) -> Press 'Add' button
  <Select> used for pass entity name and record id to CRM.
  <List> used for response result from CRM.
 

Wednesday, May 29, 2013

Import Dynamics CRM 2011 Organization Service SOAP Protocol into BizTalk Server 2010

Import Dynamics CRM 2011 Organization Service SOAP Protocol to BizTalk Server 2010

1)Open Visual Studio 2010, Select File menu -> New -> Project -> 'Empty BizTalk Server Project'

2)Right click the project, Select Add menu -> 'Add Generated Items...'
 
3)Select 'Consume WCF Service', press 'Add' button

Thursday, May 16, 2013

Intellisense in Dynamics CRM 2011 Customizations using Visual Studio

Intellisense in Dynamics CRM 2011 Customizations using Visual Studio

Goto Visual Studio -> Select XML Tab -> Select Schemas...


'XML Schemas' window will be popup, Press 'Add' button to add crm sdk schemas

(CRM2011\sdk_5.0.9690.3339\schemas\)

Friday, May 10, 2013

CDC - Change Data Capture

 Change Data Capture (CDC) records insert, update and delete activity on the table data (Audit trail for table).


The source of change data for change data capture is the SQL Server transaction log.

Enabling CDC, 2 steps process - 1) Database Level and  2) Table Level

Database Level
Run the stord procedure "exec sys.sp_cdc_enable_db"
CDC has been enabled on the database level. It created couple of tables in the system folder
To enable this functionality, the user must be a server sysadmin role.

Tuesday, May 7, 2013

BizTalk

BizTalk Server is an enterprise service bus (ESB) that can connect/communicate to various business servers. Biztalk is MS Integration and connectivity server solution. It provides the following functions: Enterprise Application Integration, Business Process Automation, Business-To-Business Communication, Message broker, and Business Activity Monitoring. BizTalk connects diverse system.

Dynamics CRM Workflow

Dynamics CRM Workflow
Typical workflow actions include sending an email message, creating a task, and updating a data field on a record.
Dynamics CRM workflow uses the Windows Workflow Foundation framework for its core infrastructure.
Dynamics CRM workflow is Asynchronous Processing Service.
Dynamics CRM workflow processes in one of three ways: Manually by the user, Automatically from a trigger event & From another workflow
Workflow Process Security - Creating and editing workflow processes & Running workflow processes (Manual or Automatic).
Settings -> Process Center -> Processes

Create a workflow process
Enter a process name, select entity, select Workflow as the category and select new bank process, Press OK


Monday, May 6, 2013

Dynamics CRM Diagnostics Page

Use the diagnostics page to Capture Network Performance
http://<YourCRMServerURL>/tools/diagnostics/diag.aspx
click the Run button to start the tests.
This page is available for both CRM Online and OnPremise.
 http://www.microsoft.com/en-us/download/details.aspx?id=23261

Dynamics CRM 2011 - Globally Define Error Report Preferences

Dynamics CRM will throw error, like below the image.
If you receive a lot of errors like this while using Dynamics CRM 2011, you may already know that you can change your personal options to automatically send these error reports to Microsoft, or to never send this. This will mean those errors will not pop up on your screen anymore as they will automatically be handled.

Microsoft Dynamics CRM – Exporting more than 10,000 rows to Excel


Log into SQL Management Studio, OPEN CRM Database

update OrganizationBase set MaxRecordsForExportToExcel = 30000 where OrganizationId = ‘GUID of your organization’ 

Update through XRM

Organization organization = new Organization();
organization.Id = “your org id”;
organization.MaxRecordsForExportToExcel = 30000;
service.Update(organization);


Dynamics CRM - Change Contact Name Format

UPDATE contactbase SET fullname = ISNULL(lastname, ”) + ‘, ‘ + ISNULL(firstname, ”)

import file is too large to upload

UPDATE ServerSettingsProperties SET IntColumn =15 where  columnname=‘ImportMaxAllowedFileSizeInMB’ 

Increase Grid Page Limit

Open the UserSettingsBase table,  change the PagingLimi.

JSON Not Defined in IE

Use a standards doctype...
<!DOCTYPE html>
add the X-UA-Compatible meta tag/header...
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

Friday, May 3, 2013

Team Foundation Server - The working folder is already in use by the workspace


C:\Program Files (x86)\Microsoft Visual Studio 11.0>tf workspaces
Collection: http://<ServerName>:8080/tfs/det_bbas
Workspace Owner               Computer  Comment
--------- ------------------- --------- ---------------------------------------
WorkSpaceName DomainName\LoginID DNS1234567

Collection: http://<ServerName>:8080/tfs/defaultcollection
Workspace Owner               Computer  Comment
--------- ------------------- --------- ---------------------------------------
WorkSpaceName LName, FName    DNS1234567

C:\>tf workspaces /computer:DNS1234567 /owner:* /format:detailed /server:http://<ServerName>:8080/tfs
 ===============================================================================
Workspace  : WorkSpaceName_TFS2012
Owner      : LName, FName
Computer   : DNS1234567
Comment    :
Collection : http://<ServerName>:8080/tfs
Permissions: Private
Location   : Local
File Time  : Current

Working folders:
 $/: C:\projects_tfs_2012

C:\>tf workspace /delete DNS1234567_tfs2012;svrsacc\kaderm /server:http://<ServerName>:8080/tfs
A deleted workspace cannot be recovered.
Workspace 'WorkSpaceName_tfs2012;svrsacc\kaderm' on server 'http://<ServerName>:8080/tfs' has 0 pending change(s).
Are you sure you want to delete the workspace? (Yes/No) yes

TFS tool - http://www.attrice.info/products.htm

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

Differences between Dynamics CRM Workflows and Dialogs and Plug-ins

Differences between Dynamics CRM Workflows and Dialogs
WorkflowsDialogs
Can be either started by a user or can be automated.Must be started by a user.
Asynchronous processes, and no user input. background process.Synchronous processes, require user input, a wizard-like interface will popup
Triggers are supported for workflowsTriggers are not supported for dialogs.


Differences between Workflows and Plug-ins
Plug-in Workflow
Executes immediately before or after the core operation (synchronous).Can also be queued to execute after the core operation (asynchronous). Queued to execute after the core operation (always asynchronous).
Synchronous plug-ins can increase the platform’s response time because they are part of the main platform processing. Asynchronous plug-ins have less impact on server response time because the code is run in a different process. Less impact on server response time because the code is run in a different process.
To register a plug-in with the platform requires a System Admin or System Customizer security role and membership in the Deployment Administrator group. Users can interactively create workflows in the Web application. However, to register a custom workflow activity, the deploying user must have the same security roles as those required for registering plug-ins.
A plug-in registered for synchronous or asynchronous execution is restricted to complete its execution within a 2 minute time limit. Works well for either short or long processes.
Both online and offline are supported. Works when the Microsoft Dynamics CRM for Outlook client is offline Workflows do not execute when offline.
Plug-ins execute to completion. Plug-ins must be written to be stateless where no in-memory data is persisted. Workflows can be paused, postponed, canceled, and resumed through SDK calls or by the user through the Web application. The state of the workflow is automatically saved before it is paused or postponed.
Plug-ins can perform data operations on behalf of another system user. Workflows cannot use impersonation.


Differences between Background(Asynronous) VS Run-time Workflow
Real Time Workflow:
1. An RTW triggered on a particular event (e.g. Create, Update, Assign and Delete) can also be configured to run on demand. This will still run immediately once triggered rather than being queued to run at later point of time as an asynchronous workflow would.

2. Unlike an async workflow, when a real time workflow runs it can do so in the context of the workflow owner, or can be configured based on user who made changes to record.

3. RTW do not contain any delay or wait activities step.

4. CRM users must have organizational permission on the following two security levels to create and activate a real time workflow:

CRM provides an option to convert existing asynchronous workflows into real time workflows without the need to define any manual steps & vice-versa...

Asynchronous Workflow:
Asynchronous workflows do remain an important option for carrying out high volumes of processes which aren't time critical, for example creating activities or sending emails. In these examples the operation will take place without halting the user process.

Customize the CRM Ribbon

Ribbon used to perform actions and add custom controls.
Displays actions that are relevant to each area of the application as users access them.
Dynamics CRM provides RibbonDiffXml definitions for all ribbons in the application for you to customize.
You can access the default ribbon definitions in the SDK\SampleCode\CS\Client\Ribbon\ExportRibbonXml\ExportedRibbonXml folder - this will generate all the entities ribbons

<RibbonDiffXml>
    <CustomActions>
        <CustomAction Id="Mscrm.DashboardTab.Favorite.CustomAction" Location="Mscrm.DashboardTab.Groups._children" Sequence="101">
            <CommandUIDefinition>
                <MaxSize Id="Mscrm.DashboardTab.Favorite.MaxSize" GroupId="Mscrm.DashboardTab.Favorite" Sequence="101" Size="LargeMedium" />
                <Scale Id="Mscrm.DashboardTab.Favorite.Scale.Popup" GroupId="Mscrm.DashboardTab.Favorite" Sequence="3001" Size="Popup" />
                <Group Id="Dns.DashboardTab.Favorite" Command="Mscrm.Enabled" Template="Mscrm.Templates.Flexible2" Sequence="100" Title="$LocLabels:Mscrm.DashboardTab.Favorite.TitleText" Description="$LocLabels:Mscrm.DashboardTab.Favorite.DescriptionText">
                    <Controls Id="Mscrm.DashboardTab.Favorite.Controls">
                        <Button Id="Mscrm.DashboardTab.Favorite.EmpApp" Command="Mscrm.DashboardTab.Favorite.EmpApp.Command" Sequence="201" ToolTipTitle="$LocLabels:Mscrm.DashboardTab.Favorite.EmpApp.LabelText" LabelText="$LocLabels:Mscrm.DashboardTab.Favorite.EmpApp.LabelText" ToolTipDescription="$LocLabels:Mscrm.DashboardTab.Favorite.EmpApp.Description" TemplateAlias="isv" />
                    </Controls>
                </Group>
                 <Tab Id="Mscrm.Isv.Global" Command="Mscrm.Isv.Global" Description="Place" Title="Place" Sequence="2000">
                    <Scaling Id="Mscrm.Isv.Global.Scaling">
                      <MaxSize/ />
                      <Scale/ />
                    </Scaling>
                    <Groups Id="Mscrm.Isv.Global.Groups">
                      <Group/>
                    </Groups>
                      </Tab>
            </CommandUIDefinition>
        </CustomAction>
        <HideCustomAction />
    </CustomActions>
    <Templates>
              <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
    </Templates>
     <CommandDefinitions />
     <RuleDefinitions />
</RibbonDiffXml>

Dynamics CRM Using SQL Server Reporting Services

Dynamics CRM uses the Reporting Services reports that is the Report Definition Language (RDL)
Report entity contains standard security settings like other entities.

2 Report permissions - Publish Reports, Add Reporting Services Reports.

Run reports in one of 3 areas - Reports View (Workplace -> My Work -> Reports subarea), Entity Ribbon, Entity Form


Sunday, April 28, 2013

Dynamics CRM Application Navigation Using Site Map

The site map is xml included in a solution’s customizations file. Create a solution specifically for site map and application ribbon changes.
<SiteMap>
    <SiteMap>
        <Area>
            <Group>
                <SubArea/>
                    <Privilege/>
                </SubArea>   
            </Group>
        </Area>
    </SiteMap>
</SiteMap>

Use XML Notepad 2007 to edit XML

The default site map that you export does not include any of the following elements: Title, Titles, Description, or Descriptions.  Dynamics CRM doesn’t require these elements for the six default application areas, but they are required for new areas.  The Title, Titles, Description, and Descriptions elements apply to the Area, Group, and SubArea elements.

The Descriptions elements appear only in the Outlook client; the Titles elements appear in both the web and Outlook clients.

http://<crmserver>/<organizationname>/tools/solution/import/SolutionImportWizard.aspx.

Always export the latest site map and create a backup copy before making any edits.

Entity Display Areas


Thursday, April 25, 2013

CRM Feed Parse - JSON

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<feed xml:base="http://<SERVER_NAME>/<ORG>/XRMServices/2011/OrganizationData.svc/" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
  <title type="text">ContactSet</title>
  <id>http://<SERVER_NAME>/<ORG>/XRMServices/2011/OrganizationData.svc/ContactSet</id>
  <updated>2013-03-27T22:56:13Z</updated>
  <link rel="self" title="ContactSet" href="ContactSet" />
  <entry>
    <id>http://<SERVER_NAME>/<ORG>/XRMServices/2011/OrganizationData.svc/ContactSet(guid'a1034be1-0000-e211-a0c1-0050568c5ad0')</id>
    <title type="text">DAY NIGHT</title>
    <updated>2009-03-27T22:56:13Z</updated>
    <author>
      <name />
    </author>
    <link rel="edit" title="Contact" href="ContactSet(guid'a1034be1-0000-e211-a0c1-0050568c5ad0')" />
    <category term="Microsoft.Crm.Sdk.Data.Services.Contact" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
    <content type="application/xml">
      <m:properties>
        <d:FirstName>DAY</d:FirstName>
        <d:ContactId m:type="Edm.Guid">a1034be1-0000-e211-a0c1-0050568c5ad0</d:ContactId>
        <d:LastName>NIGHT</d:LastName>
      </m:properties>
    </content>
  </entry>
</feed>

Data Transfer From SQL Server to CRM 2011 using CozyRoc SSIS+

1)Open Sql Server Data Tools
2)Create New Integration Services Project
3)Right Click Connection Manager -> Select New Connection Manager
    Select OLEDB Type
    Select Exiting Data Connection or Create new connection
    Rename 'DNS_DB.conmgr' (DNS sql database connection)
   

Monday, April 22, 2013

Linq

For getting exact one instance it can be FirstOrDefault() method or SignleOrDefault() or just First() or Single().

The only difference is that methods without "OrDefault()" will throw an exception if enumeration will not satisfy their expectations, and methods with "OrDefault()" will just return null.

The dirrerence between Single and First is that Single expects exact one element in the collection and First expects at least one element.

How to get top 1 records from a query Just use FirstOrDefault() instead:

return (from a in dc.Applications
        where a.UserId == userId && a.chr_Version == version
        select a).FirstOrDefault<Application>();
SingleOrDefault() will throw an exception if there is more than one record, FirstOrDefault() will just take the first one.

Also you shouldn't have to cast to Application - your record already is of type Application.
For the first record you can try:
return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).FirstOrDefault();

For the first N use:
return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).Take(N);
Left Join SQL
select * from Employees e inner join States j on e.StateID = j.StateID left join Lookup c on (c.LookupValue = EmpTypeCode and c.LookupType ='TEMP') left join Lookup c1 on (c1.LookupValue = GovTypeCode and c1.LookupType ='PERM')

Linq
from el in db.Employees
join j in db.States on el.StateID equals j.StateID
join c1 in db.Lookup on new { etc = el.EmpTypeCode, ct1 = "TEMP" } equals new { etc = c1.LookupValue, ct1 = c1.LookupType }
into LeftJoinEmpLookup1 from c1 in LeftJoinEmpLookup1.DefaultIfEmpty()
join c2 in db.Lookup on new { gtc = el.GovTypeCode, ct2 = "PERM" } equals new { gtc = c2.LookupValue, ct2 = c2.LookupType }
into LeftJoinEmpLookup2 from c2 in LeftJoinEmpLookup2.DefaultIfEmpty()

Right Join SQL
select e.Name, d.Name from Employee e right join Department d on e.DeptID = d.ID
Linq
from dept in d
join employee in e on d.ID equals e.DeptID
into RightJoinDeptEmp from e in RightJoinDeptEmp.DefaultIfEmpty()

CRM Linq

//PickList values
private Dictionary<String, String> PickList(String entityName, String attID, string attName)
{
    Dictionary<String, String> dic = new Dictionary<String, String>();
    IOrganizationService service = (IOrganizationService)serviceProxy;
    QueryExpression qryExp = new QueryExpression(entityName);
    qryExp.ColumnSet = new ColumnSet(attName);
    EntityCollection entCollection = service.RetrieveMultiple(qryExp);
    dic = entCollection.Entities
        .Where(e => (e.Attributes.ContainsKey(attName)))
        .ToDictionary(e => e.Attributes[attID].ToString(), e => e.Attributes[attName].ToString());
    /*int i=1;
    foreach (var c in entCollection.Entities)
    {
        if (c.Attributes.ContainsKey(attName))
        {
        dic.Add(c.Attributes[attID].ToString(), c.Attributes[attName].ToString());
        }
    }*/
}

CRM Form Customization JavaScript



SAVE and Close Function
Save  -  Xrm.Page.data.entity.save();
Save &  Close  -  Xrm.Page.data.entity.save("saveandclose");
Save &  New  -  Xrm.Page.data.entity.save("saveandnew");
 Close - Xrm.Page.ui.close();

dns_JavaScript/Food.js
Read text box value

Xrm.Page.data.entity.attributes.get("dnsb_foodreason").getValue();
var fName = Xrm.Page.data.entity.attributes.get("fName").getValue();
check value is null or not
if (fName==null) fName = "";

Get html element value
var plFS = document.getElementById("dns_foodstatus");

Wednesday, April 17, 2013

XRM Data Transfer Error

Error 1
System.InvalidOperationException: Sequence contains no matching

Solution
PickList or OptionSet value is missing or Number  not matched

Error 2
System.Data.SqlClient.SqlException (0x80131904): Timeout expired.

Solution
Add DNS.dbml -> DNS.designer.cs -> DNSDataContext method
partial void OnCreated()
{
    //Set the timeout value to 300 = 50 Min.
    base.CommandTimeout = 3000;
}

CRM Plugin Code - Add/Update Entity, Connect WebService, Update Database

//Update Same Entity, Other entity, create new record in other entity  and connect to WebService
//Update to database  and
//Webservice update to database

using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;
using System.Xml;
using System.Net;
using GCEntity = CRMEnt.Entities;
using System.Text;
using System.ServiceModel;

CRM 2011/2013 Development Toolkit

http://msdn.microsoft.com/en-us/library/hh372957%28v=crm.6%29.aspx

With the Developer Toolkit, you can do the following:
  • Easily generate strongly typed proxy classes without having to run CrmSvcUtil.exe.
  • Generate plug-in code so you can immediately begin to write code for business logic.
  • Edit and register plug-ins without using the Plug-in registration tool.
  • Create new web resources or extract existing web resources, add them to your solution, edit them, and deploy changes all within Visual Studio.
  • Create and edit workflow and dialog processes from within Visual Studio.
  • Get easy access to entity and option set definitions, security role and field security profile information in Visual Studio.
Download SDK http://www.microsoft.com/en-us/download/details.aspx?id=40321

Monday, March 18, 2013

Dynamics CRM Import Solution Failure

Failure Error:- An item with the same key has already been added.

Because of "duplicate field names", there are 2 possible causes.
1)Duplication has occurred between a custom field, and a virtual field

CRM creates an additional attribute in the metadata for the text of the field for certain field types (boolean, picklist and lookup). This attrbiute is not physically stored, and is considered to be a 'virtual' field. The virtaul attribute has the name of the base field + a suffix of 'name'.
For example,
the addresstypecode picklist field  => addresstypecodename virtual field
new_parentcustomerid custom lookup field  => new_parentcustomeridname virtual field.

CRM will let you do this, but the import could fail.

The following script will list of any duplicates, run in the METABASE database

select
    e.name as entity, a.name as attribute, count(*)
from
    attribute a join entity e on a.entityid = e.entityid
group by
    e.name, a.name
having count(*) > 1

Saturday, March 16, 2013

Dynamics CRM Plugin Registration Tool

Download and Export
  1. Download and install latest Dynamics CRM SDK  from Microsoft.
  2. Export "pluginprofiler.solution" package (get it from sdk\bin) to your CRM solution.
Connect to the Microsoft Dynamics CRM Server
  1. Run the PluginRegistration.exe tool from sdl\bin folder of the SDK download.
  2. To run the Plug-in Registration tool, you must first install the Windows Identity Foundation
  3. Click Create New Connection.
  4. Click connect to the Microsoft Dynamics CRM Server, you should see a list of available organizations that you belong to in the Connections pane.

Friday, March 15, 2013

ILMerge

Download ILMerge from MicroSoft

"$(Programfiles)\Microsoft\ILMerge\ilmerge.exe” /out:$(TargetDir)$(AssemblyName).Merged.dll $(TargetDir)DNS.Crm.Activities.dll $(TargetDir)DNS.Crm.Entities.dll  $(TargetDir)DNS.Crm.BusinessLogic.dll /keyfile:$(TargetDir)DNSCRM.snk /targetplatform:v4,"%ProgramFiles%\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0" /log:$(AssemblyName).ILMerge.log

"C:\Program Files (x86)\Microsoft\ILMerge\ilmerge.exe” /out:$(TargetDir)$(AssemblyName).Merged.dll $(TargetDir)$(AssemblyName).dll $(TargetDir)BizTalk.MSDynamicsCRM2011.DNS.Entities.dll /keyfile:$(TargetDir)CRM.BookAudit.snk /targetplatform:v4,"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0" /log:$(AssemblyName).ILMerge.log

Past the above code in the post-build event command line: