Friday, December 28, 2012

Read records synchronously using JSON in CRM 2011


function retrieveRecordsSynchronously() {
     var retrieveRecordsReq = new XMLHttpRequest();
     var ODataPath = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/AccountSet";
     retrieveRecordsReq.open('GET', ODataPath, false);
     retrieveRecordsReq.setRequestHeader("Accept", "application/json");
     retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
     retrieveRecordsReq.send(null);
     var records = JSON.parse(retrieveRecordsReq.responseText).d;
     //Read the first account name
     alert('First Account Name is: ' + records.results[0].Name);
 }

Automatical refreshing the form in crm 2011


function ForceRefreshForm() 

         if(Xrm.Page.data.entity.getIsDirty()) 
                 Xrm.Page.data.entity.save(); 
         else 
                 window.location.reload(true); 
}  

Set the CRM Form as Read Only


function setFormAsReadOnly() {
    // define the logic here
    disableFormFields(true);
}
function doesControlHaveAttribute(control) {
    var controlType = control.getControlType();
    return controlType != "iframe" && controlType != "webresource" && controlType != "subgrid";
}
function disableFormFields(onOff) {
    Xrm.Page.ui.controls.forEach(function(control, index) {
        if (doesControlHaveAttribute(control)) {
            control.setDisabled(onOff);
        }
    });
}

Passing configuration data using Plug-in registration tool (Secured vs. Unsecured)


  • CRM plugin registration tool contain “Unsecure & Secure” configuration sections while registering a “Step”
  • We can pass configuration data and can be used in the plug-in logic.
Secured vs. Unsecured
Below are key differentiations between Secured and Unsecured data configuration
  • Access
    • Data passed through “Unsecure” section is PUBLIC (i.e., It can be read by any user in CRM).
    • Only users with “System Administrator” role have access to the data passed through “Secure” configuration section
  • Storage
    • “Unsecure” config data will be stored along with the Plugin ‘Step’ registration information (i.e., In SdkMessageProcessingStep entity)
    • “Secure” config data will be stored in a separate entity named “SdkMessageProcessingStepSecureConfig
      • Only “System Administrator” has Read access on this entity, hence only users with ‘Sys Admin’ role can access this data
    • Both “Secured & Unsecured” configuration data stored as “Plain text” in DB
  • Outlook Sync
    • “Unsecured” configuration data is downloaded to the user’s computer when they go offline making it Unsecure
    • “Secured” configuration data is NOT downloaded to User’s Computer when they go Offline
How to read Configuration data in Plug-in
In our plug-in class, we can define a constructor that passes two parameters (i.e., unsecure configuration and secure configuration)

public class AccountCreateHandler: IPlugin{
  public AccountCreateHandler(string unsecure, string secure){
    // Do something with the parameter strings.
  }
  public void Execute(IPluginExecutionContext context){
    // Do something here.
  }
}

 If you want to read “Secure” configuration in the plug-in code, either change the user context in plugin registration as “CRM administrator ” or Impersonate to “CRM Administrator” role user in the code

Adding button/Javascript to a Ribbon


Replace the <RibbonDiffXmlwith the below code.It will add the button on Account main form with javascript code

<RibbonDiffXml>
<CustomActions>
<CustomAction Id="CA_MyFirstButton" Location="Mscrm.Form.account.MainTab.Save.Controls._children" Sequence="31">
<CommandUIDefinition>
<Button Id="B_MyFirstButton" Command="MSCRM.Form.account.MainTab.Save.Controls._children" LabelText="My First Button" ToolTipTitle="My First Button Tool Tip Title" ToolTipDescription="My First Button Tool Tip Description"
TemplateAlias="o1" Image16by16="/_imgs/ribbon/saveandclose16.png" Image32by32="/_imgs/ribbon/saveandclose32.png" /></CommandUIDefinition>
</CustomAction>
</CustomActions>
<Templates>
<RibbonTemplates
Id="Mscrm.Templates"/>
</Templates>
<CommandDefinitions>
<CommandDefinition Id="MSCRM.Form.account.MainTab.Save.Controls._children">
<EnableRules />
<DisplayRules />
<Actions>
<JavaScriptFunction FunctionName="hello" Library="$webresource:new_test">
<CrmParameter Value="CommandProperties"></CrmParameter>
</JavaScriptFunction>
</Actions>
</CommandDefinition>
</CommandDefinitions>
<RuleDefinitions>
<TabDisplayRules/>
<DisplayRules/>
<EnableRules/>
</RuleDefinitions>
<LocLabels/>
</RibbonDiffXml>

create a web resource test and add the below function

function hello(){
alert("My First Button with Custom button");
}

whenever you click on the custom button it shows an alert

Saturday, December 22, 2012

CRUD operations using Jquery in MS CRM 2011


function onLoad(context) {
    var accountId = Xrm.Page.data.entity.getId();
    //ReadMethod("MostRecent");
    //deleteAccount("41FB760C-2C4B-E211-AB64-0800270618E2");
    //WriteMethod("SAI KRISHNA YADAV");
    //updateRecord(accountId, "AccountSet");
}

function ReadMethod(queryName) {
    try {
        // debugger;
        var serverUrl;
        //serverUrl = Xrm.Page.context.getServerUrl() + oDataQuery;
        var accountId = Xrm.Page.getAttribute("primarycontactid").getValue()[0].id;
        $.ajax({
            type: "GET",
            url: "http://test/CRM2011VM/XRMServices/2011/organizationData.svc/ContactSet?$select=FullName&$filter=ContactId eq guid'" + accountId + "'",
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (result) {
                //debugger;
                if (result != undefined && result.d != undefined && result.d.results != undefined && result.d.results != null) {
                    // for (var i = 0; i < result.d.results.length; i++) {
                    alert(result.d.results[0].FullName);
                    //WriteMethod(result.d.results[0].FullName);
                    //}
                }
            },
            error: function (res) {
                //  debugger;
                alert(res.responseText);
            }
        });

    } catch (e) {
        debugger;
        alert(e.Description);
    }
}

function WriteMethod() {
    try {
        var serverUrl;
        var serverUrl = Xrm.Page.context.getServerUrl();
        var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/AccountSet";

        // Define attribute values for the CRM object you want created
        var newAccount = new Object();
        newAccount.Name = "Samplee";
        newAccount.Telephone1 = "123";
        newAccount.Fax = "456";

        //Parse the entity object into JSON
        var jsonEntity = window.JSON.stringify(newAccount);

        //Asynchronous AJAX function to Create a CRM record using OData
        $.ajax({ type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: serverUrl + ODATA_ENDPOINT,
            data: jsonEntity,
            beforeSend: function (XMLHttpRequest) {
                //Specifying this header ensures that the results will be returned as JSON.
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                var NewCRMRecordCreated = data["d"];
                alert("CRM GUID created: " + NewCRMRecordCreated.AccountId);

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("failure");
            }
        });

    } catch (e) {
        debugger;
        alert(e.Description);
    }
}

function deleteAccount(id) {
    // Get Server URL
    var serverUrl = Xrm.Page.context.getServerUrl();
    //The OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    //Asynchronous AJAX function to Delete a CRM record using OData
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + "/" + "AccountSet" + "(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            //Specify the HTTP method DELETE to perform a delete operation.
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            alert("Record deleted successfully!!!!");
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            alert("Error while deletion – " + errorThrown);
        }
    });
}


function updateRecord(id, odataSetName) {
    // Get Server URL
    var serverUrl = Xrm.Page.context.getServerUrl();
    var newAccount = new Object();
    newAccount.Name = "Samplee";
    newAccount.Telephone1 = "123";
    newAccount.Fax = "456";
    var jsonEntity = window.JSON.stringify(newAccount);
    //The OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    //Asynchronous AJAX function to Update a CRM record using OData
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        data: jsonEntity,      
        url: Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/AccountSet(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            //Specify the HTTP method MERGE to update just the changes you are submitting.
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            alert("Updated successfully");
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (XmlHttpRequest && XmlHttpRequest.responseText) {
                alert("Error while updating " + odataSetName + " ; Error – " + XmlHttpRequest.responseText);
            }
        }
    });
}


Add the onLoad function in Form onload/onChange of any field..

Friday, November 23, 2012

Getting Rid of the CRM Export to Excel Message

When you export to Excel from CRM and open the exported spreadsheet in Excel, you will receive the warning:

This warning is due to a security feature in Excel 2007 and greater that checks the contents of a file to make sure that they match the file extension.
Given that the CRM data is exported using XML and saved with an .xls format, Excel doesn’t think that the format of the file is correct.


While this is probably designed to prevent some legitimate security concerns,
it winds up having the opposite effect for people who export frequently from
Excel—since this message will be popping up for them so frequently that they
will be conditioned to always click “Yes.” As a result, more legitimate security
warnings are easily ignored.


There are two options for getting rid of this warning:
1. Group Policy – “Getting IT Right” blog has a good post
on how to globally suppress this warning using group policy.
http://blog.meteorit.co.uk/2010/07/01/annoying-file-format-warning-whenexporting-crm-records-to-excel/
2. Per Computer – You can easily get rid of this warning using a simple
registry change on your computer. The following instructions are for Excel
2010. If you have 2007, the only change is that the location of the registry
folder will be …\Microsoft\OFFICE\12.0\EXCEL\SECURITY.
 1. Open your Registry (Start -> Run -> regedit.exe)
 2. Navigate to HKEY_CURRENT_USER\SOFTWARE\MICROSOFT\OFFICE\14.0\EXCEL\SECURITY
 3. Right click in the right window and choose New -> DWORD
 4. Type “ExtensionHardening” as the name (without the quotes)
 5. Verify that the data has the value “0I


Normal warnings apply—don’t modify your registry unless you know what
you are doing!

Document your CRM installation

Everybody knows the importance of documentation of a project.

There is a free tool which you can download from Codeplex: CRM 4 documentation.

If you want to use this tool on a standalone machine or a machine without internet connection, then you should download and install the following files first:

vstor30.exe
vstor30sp1-KB949258-x86.exe

I do know that this is not a new tool, but not everybody heard about this before. Happy documentation!

Update owner in Plugin MS CRM 2011

This code should run in a POST plug-in:

SecurityPrincipal assignee = new SecurityPrincipal();
assignee.Type = SecurityPrincipalType.User;

// PrincipalId is some known Guid belonging to the user or team that will own this record.
assignee.PrincipalId = new Guid("guid");

// Create the target object for the request.
TargetOwnedAccount target = new TargetOwnedAccount();

//use the below code for custom entity
//TargetOwnedDynamic dyn = new TargetOwnedDynamic();
//dyn.EntityName = "new_book";
//dyn.EntityId = id;

// Set the properties of the target object.
// EntityId is some known Guid belonging to the account that is being assigned to the user.
target.EntityId = id;

// Create the request object.
AssignRequest assign = new AssignRequest();

// Set the properties of the request object.
assign.Assignee = assignee;
assign.Target = target;

// Execute the request.
ICrmService service = context.CreateCrmService(true);
try
{
AssignResponse assignResponse = (AssignResponse)service.Execute(assign);
}
catch (Exception ex)
{
//TODO: Exceptionhandling
}

Thursday, November 22, 2012

Get rid of "Do you want to close this window?" in CRM

You might get this question when opening CRM in Internet Explorer:

The webpage you are viewing is trying to close the window.
Do you want to close this window?
yes no

This message appears in CRM 4.0 only when you are using Internet Explorer 7.0 and you have enabled the application mode setting.Nevertheless, it is an annoying message which you can get rid of!

To do so, open the default.aspx file which resides in the root of the CRM Web site. In this file there are these three lines of code:

var oMe = window.self;
oMe.opener = window.self;
oMe.close();
Modify the second line of this snippet and end up with these three lines:
var oMe = window.self;
oMe.open('','_self','');
oMe.close();

You will no longer receive that message.  Keep in mind that following any update or migration, you might need to reapply the change.

Multiple Column Sort in CRM

Have you ever wondered how to sort multiple columns on an Entity Grid
view?  It's quite simple.
1. Click on the first column header
2. Hold down "shift" key
3. Click on the second column header
Now you will have a second column as the sub-group of the first.

Thursday, November 8, 2012

Retreive parent record values from child entity lookup


function retrieverecord() {
  if (Xrm.Page.getAttribute("childlookupid").getValue() != null) {
    //acount guid no
    var parentcustomerID = Xrm.Page.data.entity.attributes.get("childlookupid").getValue()[0].id;
    var xml = "<?xml version='1.0' encoding='utf-8'?>" +
    "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
    " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
    " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
    GenerateAuthenticationHeader() +
    "<soap:Body>" +
    "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entityName>parentEntity</entityName>" +
    "<id>" + parentcustomerID + "</id>" +
    "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
        "<q1:Attributes>" +
            "<q1:Attribute>parentattributevalue[attributenames]</q1:Attribute>" +            
        "</q1:Attributes>" +
    "</columnSet>" +
    "</Retrieve>" +
    "</soap:Body>" +
    "</soap:Envelope>";
    var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);
    var resultXml = xmlHttpRequest.responseXML;

    var errorCount = resultXml.selectNodes('//error').length;

    if (errorCount != 0) {
        var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
        alert(msg);
    }
    //Display the retrieved value.
    else {
        alert(resultXml.selectSingleNode("//q1:parentattributevalue").nodeTypedValue);
        var cost = resultXml.selectSingleNode('//q1:parentattributevalue').nodeTypedValue;
         
       Xrm.Page.getAttribute("childattribute").setValue(parseInt(cost));
//for retreiving the option set text
//resultXml.selectSingleNode('//q1:parentattributevalue').attributes[0].text;
    }
}
}

Thursday, November 1, 2012

Connecting to CRM Online from an outside caller


Open Visual Studio
Add the following references from the SDK\bin folder.
Microsoft.Xrm.Client.dll
Microsoft.Xrm.Sdk.dll

Add the following references from .NET.
System.Data.Services.dll
System.Data.Services.Client.dll
System.Runtime.Serialization.dll

DEVICE REGISTRATION
You can skip this next step and jump to CREATE EARLY BOUND TYPES if you follow the enhancement in the Eliminating manual device registration post.

There’s a section titled “To Generate your individual device ID and password” in the Create Early Bound Entity Classes with the Code Generation Tool (CrmSvcUtil.exe), but it’s easy to miss.  Follow the instructions from that section:

Open and build the DeviceRegistration project: SDK\Tools\DeviceRegistration\DeviceRegistration.csproj.
Run the executable file from the command line. To register your device, set the /operation parameter to Register.
C:\deviceregistration.exe /operation:Register
Copy the displayed device ID and password values and use them as the deviceid and devicepassword parameter values when you run the CrmSvcUtil tool.

Generate the Class by using below command
crmsvcutil.exe /url:https://demo1.api.crm5.dynamics.com/XRMServices/2011/Organization.svc /o:demo1.cs /n:demo1namespace /u:"emailid" /p:"password" /di: DeviceID /dp: DevicePassword /serviceContextName:demo1context

Add the webform
Add the GridView
goto--> Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using demo1namespace;
using System.Linq;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Client;
using Microsoft.Crm.Sdk;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Metadata;


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ClientCredentials cc = new ClientCredentials();
        cc.UserName.UserName = "";
        cc.UserName.Password = "";
        ClientCredentials dc = new ClientCredentials();
        dc.UserName.UserName = "DeviceID";
        dc.UserName.Password = "DevicePassword";
        Uri url = new Uri("https://demo.crm5.dynamics.com/XRMServices/2011/Organization.svc");
        using (OrganizationServiceProxy proxy = new OrganizationServiceProxy(url, null, cc, dc))
        {
            proxy.EnableProxyTypes();
            IOrganizationService orgserivce = (IOrganizationService)proxy;
           demo1context context = new demo1context(proxy);
            var query = from con in context.ContactSet
                        where con.LastName.Contains("sample")
                        select new
                        {
                            con.MiddleName,
                            con.LastName,
                            con.FirstName,
                            con.CreatedOn,
                            con.CreatedBy,
                        };
            GridView1.DataSource = query;
            GridView1.DataBind();
        }
    }
}


Monday, October 22, 2012

how to hide marketing module for some user roles in ms crm 2011?

We have sale, marketing and service modules in the CRM. We want to show the sale module only to the sales user,  marketing module only to marketing users, service module to service users.

Create a custom Entity named “HideModule”.

Export the site map[Keep a backup].

Edit the sitemap.
In sales for all the SubArea add the Privilege only to “create” on the custom entity “HideModule”.  
<Privilege Entity="new_HideModule" Privilege="Create" />
In Marketing for all the SubArea add the Privilege only to “Read” for the custom entity “HideModule”.  
<Privilege Entity="new_HideModule" Privilege="Read" />
In Settings for all the SubArea add the Privilege only to “Write” for the custom entity “HideModule”.  
<Privilege Entity="new_HideModule" Privilege="Write" />

Save and import the soluntion.

In security roles give the Create Privilege on “HideModule” to all sales roles, Read Privilege on “HideModule” to all marketing roles, Write Privilege on “HideModule” to all service roles.  

Wednesday, October 3, 2012

query to kill all the process [used when restoring the database]


use  master
DECLARE @dbname sysname
SET @dbname = 'DataBase Name'

DECLARE @spid int
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname)
WHILE @spid IS NOT NULL
BEGIN
EXECUTE ('KILL ' + @spid)
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname) AND spid > @spid
END

Thursday, September 13, 2012

Role-based Security vs Object-based Security


Role-based security in Microsoft Dynamics CRM focuses on grouping a set of privileges together that describe the tasks that are performed for a user in a specific job function. The basic concepts of role-based security include the following:

  • Users are assigned one or more roles based on their job function or tasks
  • Roles are associated with permissions (privileges and access levels) for the different business objects (entities)
  • Users gain access to entities or groups of entities in the system via membership in a role that has been assigned the necessary privileges and access levels to perform the users’ jobs.

Object-based security in Microsoft Dynamics CRM focuses on how users gain access to individual instances of business objects (entities).

Role-based Security
Role-based security in Microsoft Dynamics CRM is based on the interaction of privileges and access levels, which work together through the use of security roles.
Privileges define what actions a user can perform on each entity in Microsoft Dynamics CRM. Privileges are pre-defined in Microsoft Dynamics CRM and cannot be changed; examples of privileges include Create, Read, Write, and Delete.
Access levels indicate which records associated with each entity the user can perform actions upon.The access level associated with a privilege determines (for a given entity type) the levels within the organizational hierarchy (User, team and Business Unit) at which a user belonging to a specific role can act on that type of entity.
Each security role provides a combination of privileges and access levels specific to a Microsoft Dynamics CRM job function.

Object-based Security
Object-based security applies to individual instances of entities and is provided by using access rights. An access right is granted to a user for a particular entity instance.
The relationship between an access right and a privilege is that access rights apply only after privileges have taken effect. For example, if users do not have the privilege to read accounts, they will be unable to read any account, regardless of the access rights another user might grant them to a specific account through sharing.

Auto Numbering in MS CRM


we can achieve the auto numbering solution in multiple ways few are below
Option 1:Very simple, supported and mostly acceptable way of auto numbering is to read the attribute Max value and then add 1 to get next auto number. For example you have a custom entity named Project and you want to auto number Project_Ref_Number attribute. But do not retrieve all records. Just retrieve the record with maximum number value by using following two properties of PageInfo Class in SDK and set descending order.
PageInfo.Count = 1;
PageInfo.PageNumber = 1;
One more consideration should be taken in account to register your auto number plugin to at PreCreate rather at PostCreate.
Issues:In multi-user environment, this approach can come up with duplicate numbers in Project_Ref_Number when more than one user is creating project records.
Option 2:This technique requires a bit more work but still supported way of doing things and all the time you will be getting 100% unique number.
You need to create a new table for project entity in a different database and not in CRM default database.
create table dbo.ProjectNumbers
(
 Project_Ref_Number int identity(1,1) primary key clustered,
 Projectid uniqueidentifier not null
)
go
Create a stored procedure for inserting a record into new database. This will increase the performance of your insert query.
create procedure dbo.proc_new_ProjectNumber
@ProjectId uniqueidentifier,
@Project_Ref_Number int output
as
insert into dbo.ProjectNumber
(
 ProjectId
)
values
(
 @ProjectId
)
select @Project_Ref_Number = scope_identity()
go
In your Plugin/Callout:
1.   Access you database using ADO.NET
2.   Execute stored procedure and get next number from returned results
3.   Set the value of the returned number to target entity attribute approperiatly.
4.   All Done
Issues:
1.   You have to setup database.
2.   You have to read and insert into external database.
Option 3:
This option used a lock mechanism on a text file placed somewhere at your webserver. You can create one file to store next number for all entities or you can create one file for each entity. In your Plugin/Callout:
1.   Put a lock on file.
2.   Read the file and read the number there.
3.   Update the number by adding 1.
4.   Release the lock.
5.   Use this number and set your target entity attribute appropriately.

string ProjectAutoNumber = “FilePath”
lock(this)
{                            
TextReader textReader = File.OpenText(ProjectAutoNumber);
AutoNumber = textReader.ReadLine();
textReader.Close();
AutoNumber = (long.Parse(AutoNumber) + 1).ToString();
TextWriter textWriter = File.CreateText(ProjectAutoNumber);
textWriter.WriteLine(AutoNumber);
textWriter.Close();
}
Issues:
1.   Resource locking
2.   File system Read/write cost
all these options works well but still I am looking for some more robust solution.GUID’s are instantly available and 100% unique.
NOTE: you can use the auto numbering using the dates also.



Retrieve more than 10000 records from Export to Excel in MS CRM


update [CRM_MSCRM].[dbo].[OrganizationBase] SET [MaxRecordsForExportToExcel] = 300000 where NAME ='CRM'

Second Approach:-
We can create a report with the same query used in Advanced Find and run the report here you can get all the records with option Export to Excel.

Wednesday, September 12, 2012

Generate the plugin registration.exe and device registration.exe for crm 2011 from sdk


First build[Microsoft Visual Studio 2010] the plugin registration folder file from crm sdk
then it will show the bin--> debug folder with exe file

Second  build[Microsoft Visual Studio 2010] the Device registration folder file from crm sdk
then it will show the bin--> debug folder with exe file

then goto cmd-> goto that folder[Device Registratiom.exe] type the below command

E:\sdk\tools>cd deviceregistration

E:\sdk\tools\deviceregistration>cd bin

E:\sdk\tools\deviceregistration\bin>cd debug

E:\sdk\tools\deviceregistration\bin\Debug>deviceregistration.exe /operation:register
Error: Device is already registered.
Device ID: ----------------------
Device Password: -----------------------

It will generate the Device ID and Password as above.
open the command prompt once again go to bin folder in sdk

E:\sdk\bin>crmsvcutil.exe /url:https://demo1.api.crm5.dynamics.com/XRMServices/2011/Organization.svc /o:demo1.cs /n:demo1namespace /u:"emailid" /p:"password" /di: DeviceID /dp: DevicePassword /serviceContextName:demo1context

For OnPremise

E:\sdk\bin>CrmSvcUtil.exe /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration" /out:CRM2011VM.cs /url:http://test:5555/CRM2011VM/XRMServices/2011/Organization.svc /domain:CRM2011VM /username:administrator /password:p@ssword /namespace:Xrm /serviceContextName:XrmServiceContext

Tuesday, September 11, 2012

Error while importing the managed solution


A managed solution cannot overwrite the SavedQuery component with Id=xxxx-xxx-xxx-xxx-xxxx  which has an unmanaged base instance.The most likely scenario for this error is that an unmanaged solution has installed a new unmanaged SavedQuery component on the target system, and now a managed solution from the same publisher is trying to install that same SavedQuery component as managed. This will cause an invalid layering of solutions on the target system and is not allowed.

If yes, you need to remove Activity feed configuration from source system before exporting your solution. You need to follow below steps
1. Open your Dev envornment.
2. Navigate to Activity Feeds Configuration under Setting->System.
3. Delete all configuration records except for user entity.
4. Delete user entity record.

 Now you can export your solution, make sure to click on “Publish All Customization” during export step.
Once solution imported into production envirnment, you can configure activity feed again.

Display Date from datetime in MS CRM


Write the below script in onchange of date field

var m_names = new Array("January", "February", "March", 

"April", "May", "June", "July", "August", "September", 
"October", "November", "December"); 
var d = new Date(); 
var curr_date = d.getDate(); 
var curr_month = d.getMonth(); 
var curr_year = d.getFullYear(); 
alert(curr_date+"-"+m_names[curr_month] +"-"+ "-" + curr_year); 

Friday, August 31, 2012

Privileges Problems!!!


Dear All,
If you are facing with the below error
 You don’t have enough privileges to access the Microsoft Dynamics CRM object or perform the requested operation. For more information ,Contact your Microsoft Dynamics CRM administrator.

Check the Append and AppendTo privileges for that particular entity set to Org level.

Limit the No. of records per page in MS CRM


if the user want to see only 10 records per view in the entire CRM
You can set this in the Personal options by setting the Records Per Page:
Though records per page can set minimum 25 and  maximum  250.
if some one wants to restrict to 10 records per page??
Then run the below SQL against the Organization you desired to do so.
update UserSettings  set PagingLimit=10 where SystemUserId='User GUID'

Friday, August 24, 2012

How to Speed up the Performance of MS CRM Forms

  • Add your CRM site to the list of trusted sites
  • Disable Form Assistant
  • When you have scores of data in the CRM database, the Form Assistant loads the data during the form loads. Shutting this functionality off could greatly boost the loading time of the form.
  • Disable Antivirus scan for CRM site
  • One of the major factors that affect CRM's performance is the Antivirus scan. Disabling this, the difference in load time of the form becomes quite noticible.
  • Use a higher version on IE. (IE7 or higher)

Thursday, August 23, 2012

How to save a record in CRM 2011 using javascript


In CRM 2011, you could save an entity record using javascript.
There are 3 types of save possible using javascript in CRM 2011.

1. Equivalent to 'SAVE' button found on the entity form
Xrm.Page.data.entity.save();

2. Equivalent to 'SAVE AND NEW' button found on the entity form
Xrm.Page.data.entity.save('saveandnew');

3. Equivalent to 'SAVE AND CLOSE'  button found on the entity form
Xrm.Page.data.entity.save('saveandclose');

Wednesday, August 22, 2012

Checking condition for last 15 days date using JavaScript in MS CRM


var currentDate = new Date();
var dateOfContact = crmForm.all.new_submissiondate.DataValue;
if(dateOfContact != null)
{
  var pastMaxDate = new Date();

  currentDate.setHours(0);
  currentDate.setMinutes(0);
  currentDate.setSeconds(0); 
  currentDate.setMilliseconds(0);
 
  pastMaxDate.setDate(currentDate.getDate()-14);
  pastMaxDate.setHours(0);
  pastMaxDate.setMinutes(0);
  pastMaxDate.setSeconds(0);
  pastMaxDate.setMilliseconds(0);

  //Checking condition for last 15 days
  if( !((dateOfContact <= currentDate) && (dateOfContact >= pastMaxDate)) )
  {
    crmForm.all.new_submissiondate.DataValue = null;
    alert("Valid date range is from "+ pastMaxDate.toLocaleDateString() + " to till today.");
  }
}

Tuesday, August 21, 2012

Microsoft Dynamics CRM E-mail Router


Email router will not send any mails unless we configure Outlook.
We cannot install CRM Email in Windows Server 2008 32-bit editions, Windows Server 2003, Windows Vista, and Windows XP editions are not supported for installing and running Microsoft Dynamics CRM E-mail Router or E-mail Router Configuration Manager.

Please refer the below link for further assistance

Friday, August 17, 2012

Check the User Security Role in CRM 2011/4.0 using JScript


if(UserHasRole("System Administrator")==true)
{
alert("System Administrator");
}
if(UserHasRole("SalesHead")==true)
{
alert("SalesHead");
}

function UserHasRole(roleName)  
{  
 //get Current User Roles, oXml is an object  
 var oXml = GetCurrentUserRoles();  
 if(oXml != null)  
 {  
  //select the node text  
  var roles = oXml.selectNodes("//BusinessEntity/q1:name");  
  if(roles != null)  
  {  
   for( i = 0; i < roles.length; i++)  
   {  
    if(roles[i].text == roleName)  
    {  
     //return true if user has this role  
     return true;  
    }  
   }  
  }  
 }  
 //otherwise return false  
 return false;  

  
function GetCurrentUserRoles()  
{  
 var xml = "" +  
 "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +  
 "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +  
 GenerateAuthenticationHeader() +  
 " <soap:Body>" +  
 " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +  
 " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +  
 " <q1:EntityName>role</q1:EntityName>" +  
 " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +  
 " <q1:Attributes>" +  
 " <q1:Attribute>name</q1:Attribute>" +  
 " </q1:Attributes>" +  
 " </q1:ColumnSet>" +  
 " <q1:Distinct>false</q1:Distinct>" +  
 " <q1:LinkEntities>" +  
 " <q1:LinkEntity>" +  
 " <q1:LinkFromAttributeName>roleid</q1:LinkFromAttributeName>" +  
 " <q1:LinkFromEntityName>role</q1:LinkFromEntityName>" +  
 " <q1:LinkToEntityName>systemuserroles</q1:LinkToEntityName>" +  
 " <q1:LinkToAttributeName>roleid</q1:LinkToAttributeName>" +  
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +  
 " <q1:LinkEntities>" +  
 " <q1:LinkEntity>" +  
 " <q1:LinkFromAttributeName>systemuserid</q1:LinkFromAttributeName>" +  
 " <q1:LinkFromEntityName>systemuserroles</q1:LinkFromEntityName>" +  
 " <q1:LinkToEntityName>systemuser</q1:LinkToEntityName>" +  
 " <q1:LinkToAttributeName>systemuserid</q1:LinkToAttributeName>" +  
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +  
 " <q1:LinkCriteria>" +  
 " <q1:FilterOperator>And</q1:FilterOperator>" +  
 " <q1:Conditions>" +  
 " <q1:Condition>" +  
 " <q1:AttributeName>systemuserid</q1:AttributeName>" +  
 " <q1:Operator>EqualUserId</q1:Operator>" +  
 " </q1:Condition>" +  
 " </q1:Conditions>" +  
 " </q1:LinkCriteria>" +  
 " </q1:LinkEntity>" +  
 " </q1:LinkEntities>" +  
 " </q1:LinkEntity>" +  
 " </q1:LinkEntities>" +  
 " </query>" +  
 " </RetrieveMultiple>" +  
 " </soap:Body>" +  
 "</soap:Envelope>" +  
 "";  
  
 var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");  
  xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);  
 xmlHttpRequest.setRequestHeader("SOAPAction"," http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");  
 xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");  
 xmlHttpRequest.setRequestHeader("Content-Length", xml.length);  
 xmlHttpRequest.send(xml);  
  
 var resultXml = xmlHttpRequest.responseXML;  
 return(resultXml);  
}


Go to Entitiesà Select an entityà Forms [Open the main Form]à select Form Properties à the below screen will appearsà click on Add à create new àcopy the above code and publish



Note: No need to add any Function in Event Handlers. 
we can use the same code in CRM 4.0 Form OnLoad.