Tuesday, April 30, 2013

Dynamics CRM 2011 - Trigger a workflow from JavaScript

Recently I had a requirement to trigger a workflow on click of ribbon button when it meets certain criteria. Refer below link for calling JavaScript function from custom ribbon button.
http://ankit.inkeysolutions.com/2012/01/crm-2011-how-to-use-visual-ribbon.html
The criteria values are checked using JavaScript and if all criteria are satisfied then the workflow is to be triggered. The function below will take two inputs where entityId is the id of the record for which the workflow will execute and workflowProcessId is the id of the workflow which we want to execute. 




function startWorkflow(entityId, workflowProcessId) {
  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\">" +  Xrm.Page.context.getAuthenticationHeader() +  "<soap:Body>" +"<Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +"<Request xsi:type=\"ExecuteWorkflowRequest\">" +"<EntityId>" + entityId + "</EntityId>" +  "<WorkflowId>" + workflowProcessId + "</WorkflowId>" + "</Request>" +"</Execute>" +"</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/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
  xmlHttpRequest.send(xml);
}
 

How to retrieve the Selected Record Ids of a Sub Grid in CRM 2011 using javascript

Retrieve the Selected Record Ids of a Sub Grid in CRM 2011 using javascript
Code Snippet:
var gridControl = document.getElementById("yourSubGridName").control;
var ids = gridControl.get_selectedIds();

Thursday, April 25, 2013

CRM Field Masking with JQuery

It’s always a good thing to make the user experience as nice as possible. One thing missing from CRM is the ability to mask fields. You’ve probably seen this online on sites that ask for your phone number or social security number where the text box already contains the hyphens in the necessary spots. This clues the user in as to what format you’re expecting from them and leads to cleaner data.
Recently I had a client that needed all their zip codes to be entered along with the carrier code, which is the 4 number suffix at the end of a zip code. I figured this would be a great opportunity to implement some field masking.
Using a JQuery masking plugin written by Josh Bush. I was able to add a single line function to define my masking. To do the same, download and upload it to your CRM system as a web resource.
Next, jump onto the form that you want to add a field mask to and add the JQuery and JQuery Mask library.

sc_jquery1.6.2.min
sc_Jquery_mask
sc_global

A list of the necessary libraries
You’ll also notice that I have my own Global javascript file in the list. This file contains a reference to a Mask function that will call the JQuery Mask plugin. You can choose to register each field mask function call individually or you can place them all on a single function. I’ve shown both examples below.

function Mask(field, format)
{   
$("#"+field).mask(format);
}

function maskFields()
{
Mask("address1_postalcode", "99999-9999");
Mask("telephone1", "(999) 999-9999");
Mask("telephone2", "(999) 999-9999");
Mask("fax", "(999) 999-9999");
}

The next step is to define an OnLoad function call. We’ll be calling the Mask function above and passing it in the schema name of the field and the mask value we want applied.
Finally, the function call
You’ll also need to register one more function call on the OnSave. The reason for this is that the JQuery plugin doesn’t save the value to the CRM form. We need to take care of this. We do this by comparing the value in the html to the value on the field. If they’re different, then this means the user changed the field. Insert the following into your global and register it in the OnSave.
function formatFields(){  

formatField("address1_postalcode");           
formatField("fax");           
formatField("telephone1");           
formatField("telephone2");
}
function formatField(fieldName){           
if(Xrm.Page.getAttribute(fieldName).getValue() != $("#"+fieldName).val())                       
Xrm.Page.getAttribute(fieldName).setValue($("#"+fieldName).val());
}
And that’s all there is to it. Here are the results.
The JQuery plugin allows us to define all sorts of field masks and you can add dynamic logic to change the mask based on the country. Happy CRMing!
UPDATE:
To get optional formatting, take a look at examples on the jquery plugin page:
http://digitalbush.com/projects/masked-input-plugin/
Refer http://taoofcrm.com/2011/05/19/crm-field-masking-with-jquery/

Friday, April 19, 2013

Microsoft CRM Services



What is a web service in Microsoft CRM?
A web service is a programming interface exposed by an application. It follows industry standards that allow it to be consumed ( used ) by any software technology that understands the web service standards defined by W3C.
CRM Live exposes two web services: CrmService & CrmMetadataService
CrmService is used to fetch data, set data, make programmatic configuration changes, etc.
CrmMetadataService is used to query about the metadata. The metadata describes the entities, attributes, relationships, and so on, of the organization.
The WSDL, which stands for web service description language, can be fetched from your CRM system via the Settings-Download WSDL. You use this to create your web reference’s.
The endpoint URL for each of these in an internet facing deployment of CRM can be discovered thru the CrmDiscoveryService Web Service. You’ll also use the CrmDiscoveryService  for policy information during the authentication process. 
The reference for the discovery service is at
https://MyOrgName/MSCRMServices/2007/Passport/CrmDiscoveryService.asmx
Then in your code set the URL for the CrmService and CrmMetadataService using the endpoint returned from the discovery services. The URLs can be retrieved from your ticket response object.

Example :
// STEP 1: Retrieve a policy from the Discovery Web service.
CrmDiscoveryService discoveryService = new CrmDiscoveryService();
discoveryService.Url = String.Format("https://{0}/MSCRMServices/2007/Passport/CrmDiscoveryService.asmx",_hostname);
RetrievePolicyRequest policyRequest = new RetrievePolicyRequest();
RetrievePolicyResponse policyResponse = (RetrievePolicyResponse)discoveryService.Execute(policyRequest);
// STEP 2: Retrieve a Passport ticket from the Passport service.
LogonManager lm = new LogonManager();
string passportTicket = lm.Logon(UserID, Password, _partner, policyResponse.Policy, _environment);
// STEP 3: Retrieve a CrmTicket from the Discovery Web service.
RetrieveCrmTicketRequest crmTicketRequest = new RetrieveCrmTicketRequest();
crmTicketRequest.OrganizationName = _organization;
crmTicketRequest.PassportTicket = passportTicket;
RetrieveCrmTicketResponse crmTicketResponse = (RetrieveCrmTicketResponse)discoveryService.Execute(crmTicketRequest);
// STEP 4: Create and configure an instance of the CrmService Web service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.AuthenticationType = AuthenticationType.Passport;
token.CrmTicket = crmTicketResponse.CrmTicket;
token.OrganizationName = crmTicketResponse.OrganizationDetail.OrganizationName;
CrmService crmService = new CrmService();
crmService.Url = crmService.CrmAuthenticationTokenValue = token;
// STEP 5: Invoke the desired CrmService Web service methods.
lead newlead = new lead();
newlead.description = "Lead Test";
newlead.subject   = "My Lead";
newlead.firstname ="Sai";
newlead.lastname  = "Krishna";


// Call the Create method to create an lead
Guid leadID = crmService.Create(newlead);
When using the CRM Web Services, there are times when you need to work with custom entities that aren't described in the current WSDL that you have. The DynamicEntity lets you program against types that you don't have the full description in the WSDL. This can be very helpful when you don't have access to fetch the systems current WSDL files.
Let's look at a code snippet to do this.

Here at the steps .
1. Create all the attribute values
2. Create Dynamic Entity
3. Set the attribute properties
4. Create the Target
5. Execute the Request
I'll show how to create a Customer entity and associate an existing account id to the new entity. The CRM SDK support a variety of property type objects. Be sure to use the correct object type with the definition of the attribute. Mismatching this is a common error. I'll save you some time with this tip: Use LookUpProperty instead of Guid type when relating entities together. Even though the value you set will be a GUID, it only works with the LookupProperty object.
// Create Properties
LookupProperty accountid = new LookupProperty();
accountid.Name = "new_accountid";
accountid.Value = new Lookup();
accountid.Value.Value = new Guid("260FB27F-25E6-DC11-BEDA-0013210AC0BE");
accountid.Value.type = EntityName.account.ToString();

StringProperty name = new StringProperty();
name.Name = "new_CustomerName";
name.Value = "Krishna";
DateTime userTime = new DateTime();
userTime = dtExpDate;

CrmService.CrmDateTime LaunchDate = new CrmService.CrmDateTime();
LaunchDate.Value = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:s}", userTime);
CrmDateTimeProperty LaunchDate = new CrmDateTimeProperty();
LaunchDate.Name = "new_LaunchDate";
LaunchDate.Value = LaunchDate;

// Create the DynamicEntity object.
DynamicEntity AcmeEntity = new DynamicEntity();

// Set the name of the entity type.
AcmeEntity.Name = "new_Customer";

// Set the properties
KeyEntity.Properties = new Property[] { name, accountid, LaunchDate };

// Create the target.
TargetCreateDynamic targetCreate = new TargetCreateDynamic();
targetCreate.Entity = KeyEntity;

// Create the request object.
CreateRequest create = new CreateRequest();

// Set the properties of the request object.
create.Target = targetCreate;

// Execute the request.
CreateResponse created = (CreateResponse)crmService.Execute(create); 

That's it. Now we have an instance of the entity type
new_Customer that is related to the account id. Don't forget to check out the SDK for complete samples and descriptions of all the property objects.  Also, if you get errors, the first to check is that the attribute type matches the property object that you are using.

Wednesday, April 17, 2013

Automatic flow for Visits in CRM

Since workflow normally waits for a future date so let me give you a simple solution for this.
- Create a custom field at contact named next Visit
- Create two workflows:

#1 Update Next Visit (This workflow sets the next Visit first time and will not execute thereafter)
Fire this workflow on create of contact/account or on change of Visit field.
If Visit contains data Then
Update Contact Next Visit Field by adding 3 Months in Visit field

2) Birthday Reminder (This workflow sends reminder emails and updates Next Visit Field after each execution by adding 3 months)
If Next Visit contains data Then
Wait untill 5 days Before Visit
Send Email reminder to user - Receptionist
Update Next Visit= After 3 months of Current Visit

Calling external JS files from MS CRM 4.0 form

function LoadFunction() { }
//create a Script loader object + function to be called when the script has
//finished loading
window.ScriptLibrary = new ScriptLoader(LoadFunction);
//url , false - cache, true - no cache
ScriptLibrary.Load('//FileName.js', true); 


Another Example:
//create the function which will load the file
function LoadExternalScript(scriptFile)
{
var netRequest = new ActiveXObject("Msxml2.XMLHTTP");
netRequest.open("GET", scriptFile, false);
netRequest.send(null);
eval(netRequest.responseText);
}

//call the above function by passing your file name(absolute path)
LoadExternalScript("/ISV/js/filename.js");
//now call the OnLoad function, which has defined in the external JS file
//also you can define and call other function, in the external JS files
OnLoad();

Wednesday, March 6, 2013

Step by step: Installing CRM 2011 On-premise and Migrating from Dynamics CRM 4.0 (32 bits, on-premise).

click here/here for step by step: Installing CRM 2011 On-premise and Migrating from Dynamics CRM 4.0 (32 bits, on-premise).

click here for detailed explaination.

Wednesday, February 27, 2013

Change the sa password in SQL Server

Login into SQL Server using Windows Authentication.
In Object Explorer, open Security folder, open Logins folder. Right Click on SA account and go to Properties.

The Simple trick is to check the box “Map to credential” as shown below after providing a new password and click Okay.

SQL Server 2008 Designer Behavior Change: Saving Changes Not Permitted

The Save (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.
The following actions might require a table to be re-created:
  • Dropping a column
  • Changing column nullability
  • Changing the order of the columns
  • Changing the data type of a column
To change this option, on the Tools menu, click Options, expand Designers, and then click Table and Database Designers. Select or clear the Prevent saving changes that require the table to be re-created check box.

Friday, February 15, 2013

Check the Microsoft Certification

Use the below link to Check/Share the Microsoft Certication Details
https://mcp.microsoft.com/authenticate/validatemcp.aspx
use the Transcript ID and access code as your password
You are now ready to share your qualifications with your employer, friends, and colleagues. 
Provide them with your Transcript ID and the Access Code, and direct them to https://mcp.microsoft.com/authenticate/validatemcp.aspx. Remember, you can change your Access Code at any time. 
If you decide to stop sharing your transcript, simply change your Access Code at https://mcp.microsoft.com/mcp/tools/MCPDirectoryPreferences.aspx and refrain from sharing the new Access Code with anyone.

The below link is used to update your Certification details 
https://www.microsoft.com/learning/members/en/us/mcp/mcp-default.aspx 


Thursday, February 7, 2013

Tools used in Microsoft CRM 2011

1. The following tools are all part of the CRM 2011 Software Development Kit (SDK) SDK Download: http://www.microsoft.com/download/en/details.aspx?id=24004 
4. Metadata Document Generator - http://metadatadocgenerator.codeplex.com 
5. Visual Ribbon Editor - http://crmvisualribbonedit.codeplex.com 
6. SiteMap Editor - http://sitemapeditor.codeplex.com 
7. Odata Query Designer - http://crm2011odatatool.codeplex.com 
8. Fiddler - http://www.fiddler2.com 
10. JavaScript Conversion - http://crm2011scriptconvert.codeplex.com 
12. Metadata Document Generator for Microsoft Dynamics CRM 2011 (Form Reporter) - http://metadatadocgenerator.codeplex.com 

Setting Blank iFrame in CRM 2011

when you need to default an iFrame to a blank page.  When this is the case, through JavaScript, you’ll then want to set the page to the desired URL.

With CRM 4.0, you could set your page to “/_root/blank.aspx”.  This page however, is no longer an option inside CRM 2011.

With CRM 2011, I like to use the loading screen “/_static/loading.htm”.  Although this page contains an animated .gif and slightly more HTML than a blank page, the reason I prefer this page is because it is already cached by the browser and provides the user with a nice loading graphic.

Add a new iFrame and in the URL filed give the above highlighted text.

Monday, January 28, 2013

Trick to get FetchXML in MSCRM 4.0

Just use following steps and enjoy.....
  • Use the advance find of MS CRM; 
  • define your query and click on Find button; 
  • Press CTRL+N, this will create a new IE window but will keep the context; 
  • Replace the url in the address bar                 javascript:alert(resultRender.FetchXml.value); 

Monday, January 21, 2013

What is REST/SOAP?

What Is REST?

REST represents Representational State Transfer. REST is an architectural style in which every resource is addressed by using a unique URI. In Microsoft Dynamics CRM, a resource can be an entity collection or a record.
REST works the way the Internet works. You interact with resources by using HTTP verbs such as GET , POST , MERGE , and DELETE . Various libraries can be used to process the HTTP requests and responses. REST provides a standard interface that you can use with any programming language. REST allows for either synchronous or asynchronous processing of operations. The capability to perform asynchronous operations makes REST well suited for AJAX and Silverlight clients.
OData sends and receives data by using either ATOM or JavaScript Object Notation (JSON). ATOM is an XML-based format usually used for RSS feeds. JSON is a text format that allows for serialization of JavaScript objects.

Limitations

The REST endpoint provides an alternative to the WCF SOAP endpoint, but there are currently some limitations.
Only Create, Retrieve, Update, and Delete actions can be performed on entity records.
a.Messages that require the Execute method cannot be performed.
b.Associate and disassociate actions can be performed by using navigation properties.
Authentication is only possible within the application.
a.Use of the REST endpoint is limited to JScript libraries or Silverlight web resources.

What Is SOAP?

Unlike the REST endpoint for web resources, the SOAP endpoint uses the Organization service. This is the same service used when writing applications that exist outside of the Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online application. The differences are:
a.Requests are sent to a different URL: <organization URL>/XRMServices/2011/Organization.svc/web.b.Authentication is provided by the application.
Because authentication is provided by the application, you must create web resources in the application before the code that uses the service can operate.

Comparison of Programming Methods

You can use the SOAP endpoint for Web Resources with JScript libraries or by using Microsoft Silverlight. The process for using this endpoint is very different, depending on the technology used.

Using the SOAP Endpoint with JScript

With JScript, you will be using XmlHttpRequest to POST requests to the service. The body of the request must contain the XML appropriate for the message you are using. You must also parse the XML returned in a response. With XmlHttpRequest , it is possible to make synchronous requests. However it is highly recommended to always use asynchronous requests. Because manually configuring each request is very time consuming, it is expected that you will reuse existing libraries or create your own. Microsoft Dynamics CRM 2011 does not provide a comprehensive set of JScript libraries. The specific syntax used when calling JScript libraries depends on how they are designed. Several sample JScript libraries are provided with the Microsoft Dynamics CRM SDK, but these are not intended to represent the only or best library design. The content in the Microsoft Dynamics CRM SDK focuses on helping you create your own libraries.

What is meant by sandbox? How it is differentiate between standard environments?

 a. Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online support the execution of plug-ins in an isolated environment. In this isolated environment, also known as a sandbox.
b. Use of the full power of the Microsoft Dynamics CRM SDK to access the web services. Access to the file system, system event log, network, and more is prevented in the sandbox.
c. It is more secure, supports run-time monitoring and statistics reporting, and is supported on all Microsoft Dynamics CRM deployments.
d. In registration Sandbox, known as partial trust:
e. Outside sandbox is full trust: Full trust is supported for on-premise and Internet- Facing Microsoft Dynamics CRM deployments.
f. Microsoft Dynamics CRM Online deployment, plug-ins must be registered in the sandbox (partial trust) because no full trust run-time environment is supported. Partial trusts are also supported for on-premise deployments.
g. Sandboxed plug-ins can access the network through the HTTP and HTTPS protocols.
h. Access to localhost (loopback) is not permitted.
i. IP addresses cannot be used. Plug-ins must use a named web address that requires DNS name resolution.
j. Anonymous authentication is supported and recommended.
k. Full trust is supported for on-premises and internet facing Microsoft Dynamics CRM deployments. For a Microsoft Dynamics CRM Online deployment, plug-ins must be registered in the sandbox (partial trust) where they are isolated as previously described.

IOrganizationService Methods in CRM 2011

NameDescription
public methodAssociateCreates a link between records.
public methodCreateCreates a record.
public methodDeleteDeletes a record.
public methodDisassociateDeletes a link between records.
public methodExecuteExecutes a message in the form of a request, and returns a response.
public methodRetrieveRetrieves a record.
public methodRetrieveMultipleRetrieves a collection of records.
public methodUpdateUpdates an existing record.

The IOrganizationService Web service provides a set of methods used to perform the most common operations on system and custom entities and on the metadata for your organization. These operations can also be performed by using the IOrganizationService.Execute method and the corresponding message.

Create

Use the IOrganizationService.Create method to create an instance (record) of any entity that supports the Create message, including custom entities.

Retrieve

Use the IOrganizationService.Retrieve method to retrieve an instance (record) of an entity..

RetrieveMultiple

Use the IOrganizationService.RetrieveMultiple method to retrieve a collection records. The query can be specified using a query expression or Fetch XML query. If the query includes an aggregate function, xxx.

Update

Use the IOrganizationService.Update method to update an existing record.

Delete

Use the IOrganizationService.Delete method to delete an existing record.

Associate

Use the IOrganizationService.Associate method to create a link between two records that participate in a relationship.

Disassociate

Use the IOrganizationService.Disassociate method to delete the link between two records.

Execute

Use the IOrganizationService.Execute method to execute a message. This includes common processing like create and delete of data records and metadata, or it can be specialized processing such as import or detect duplicates.