Wednesday, July 25, 2012

How to create a hyperlink in CRM 2011 using Javascript?


Introduction:

             Today I am going to Explain one important topic in MS CRM.Some days back I have to  create one hyperlink in account Entity and the hyperlink text will be the name of account + parent account name and after click on that link the Google search page will open with the search text as hyperlink text(fullname).

So,Today I am going to Explain how to create the Hyperlink with Google search Functionality.

First you have to create a one field with name Google Search and the type of the field will be Text and using java script I am converting this into hyperlink.

Lets discuss Step by Step

1.Create a Field name Google Search (Settings->Customization->Customize System ->Components->Entity->Account->Field->New->Save and Close)


2.Put this Field in Form of Account.(Open Form and just Drag and Drop the Field Google Search)


3.Now Our Objective is Put the Text of accountname in Google Search Field and make it hyperlink using Javascript.
4.So for that We need to create the Javascript File.
5.Open Notepad and put the text below.

function ConvertToLink(recordtype)
{

             var ctrl = Xrm.Page.ui.controls.get("new_googlesearch")._control;  
if(Xrm.Page.ui.getFormType() == 2)
{

                               var strDisplayText;
                               var strSearchString;
         switch(recordtype)
         {
                                          case 'Account':
                     strDisplayText = Xrm.Page.data.entity.attributes.get("name").getValue();
                                 strSearchString = strDisplayText;
                                                                break;
                                          case 'Contact':
                   if(Xrm.Page.data.entity.attributes.get("parentcustomerid").getValue() != null)
{
           strDisplayText = Xrm.Page.data.entity.attributes.get("fullname").getValue() + "(" + Xrm.Page.data.entity.attributes.get("parentcustomerid").getValue()[0].name +")";
          strSearchString = Xrm.Page.data.entity.attributes.get("fullname").getValue() + " " + Xrm.Page.data.entity.attributes.get("parentcustomerid").getValue()[0].name;
                    }
else
{
strDisplayText = Xrm.Page.data.entity.attributes.get("fullname").getValue();
strSearchString = Xrm.Page.data.entity.attributes.get("fullname").getValue();
}
break;
                                }
                    if(trim(strSearchString).length >=0)
{
strSearchString=strSearchString.replace(/&/g, "" ).replace(/>/g, "").replace(/</g, "").replace(/'/g, "");
var btn = "<a href='javascript: void(0);' onclick=\"window.open(\'http://www.google.com/search?q=" + strSearchString + "\', \'windowname1\', \'resizable=1, scrollbars=1\');  return false;\" style='color:blue;text-decoration:underline !important'>" + strDisplayText + "</a>";

ctrl.get_element().innerHTML += btn;  
}
}
                     ctrl.get_element().firstChild.style.display = 'none';

}
function errorDisplay(XmlHttpRequest, textStatus, errorThrown)
{
     alert(errorThrown);
}

function trim(str)
{
    if(!str || typeof str != 'string')
        return null;

    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}

new_googlesearch is the Id of the Google Search Field.

6.Now Save the File With Name GoogleSearchFunction.js.(dont forget to include .js Extension).
7.Now we need to add this Javascript to Web Resources.
8.Now Go to Settings->Customization->Customize System ->Web Resources->New and Add Following detail.


9.Now Save it and Publish it.
10.Now Go to Settings->Customization->Customize System ->Components->Entity->Account->Open Form->Form Properties(its is in header)
11.In Events Tab Add Form Google Search Function(new_GoogleSearchFunction) Library.
12.Then Add Form Libraries
   Control:Form
   Event:OnLoad
13.Click on Add Event Handler.
     Library:new_GoogleSearchFunction
     Function Name:ConvertToLink
     Parameter:'Account' or (you can pass also 'Contact' if you want to do same functionality in Contact Form.because above javascript will be useful for Both Entity Account and Contact.I have used Switch statement in Javascript.)
and click on OK



14.Now Save it and Publish it.
15 Now open any Existing Account and check.


->Now If you look at the Final Output you will see only hyperlink is there Now if you want same hyperlink inside the Text-Box then you just add the Following Lines in GoogleSearchFunction.js File.
(Settings->Customization->Customize System ->Components->Entity->Account->Open Form->Form Properties(its is in header)->Edit Form Libraries)

function ConvertToURL()
{
var urlField =Xrm.Page.data.entity.attributes.get("new_google");

if(urlField.getValue()==null)
urlField.setValue(Xrm.Page.data.entity.attributes.get("name").getValue())

var urlField1=document.getElementById("new_google")
urlField1.readOnly = true
urlField1.style.color = "blue";
urlField1.style.textDecoration="underline";
urlField1.style.cursor='hand';
urlField1.onclick = OpenGoogleUrl;
}

function OpenGoogleUrl(evt)
{
var str=Xrm.Page.data.entity.attributes.get("name").getValue()
window.open("http://www.google.co.in/search?q=" +str );
}

->Now create one More field name Google(The Hyperlink will be shown inside the textbox)

     Library:new_GoogleSearchFunction
     Function Name:ConvertToURL

->Click OK->Save->Publish and check



Friday, July 20, 2012

Find the Form Type in CRM 2011.


Introduction

             Here I am going to show you how to determine whether open Form is New Form or its just an existing Record.


alert(Xrm.Page.ui.getFormType())

If its output is 1 then its a New Form and if its output is 2 then it just Existing Record Form with fill up its data means its update Form.Others Form Types are:


1= "create";
2="update"
3="readonly"
4="disabled";
6="bulkedit";



Thursday, July 19, 2012

Jscript Reference for Microsoft CRM 2011


Introduction

           Here’s a some guide covering about Microsoft CRM 2011’s syntax for common Jscript requirements.
Most of the examples are provided as functions so that you can easily test in the OnLoad event of the Account form or any Form.

  • Refresh the CRM Form
      function ReLoadContact()
      {
           window.location.reload(true);
      }
  • Get the value of a Text field
Note: this example reads and pops the value of the Main Phone (telephone1) field on the Account form

Function AlertTextField() {
var MainPhone = Xrm.Page.data.entity.attributes.get("telephone1").getValue();
alert(MainPhone);
}
  • Get the GUID value of a Lookup field
Note: this example reads and pops the GUID of the primary contact on the Account form

Function AlertGUID() {

var primaryContactGUID = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].id;

alert(primaryContactGUID);

}
  • Get the Text value of a Lookup field.
Note: this example reads and pops the name of the primary contact on the Account form
Function AlertText() {

var primaryContactName = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].name;

alert(primaryContactName);

}

  • Get the database value of an Option Set field
Note: this example reads and pops the value of the Address Type (address1_addresstypecode) field on the Account form

Function AlertOptionSetDatabaseValue() {
var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
AddressTypeDisplayValue = AddressType.getValue();
if(AddressTypeDisplayValue !=null) {
alert(AddressTypeDisplayValue);
}
}

  • Get the text value of an Option Set field
Note: this example reads and pops the value of the Address Type (address1_addresstypecode) field on the Account form

Function AlertOptionSetDisplayValue() {
var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
AddressTypeDisplayValue = AddressType.getSelectedOption().text;
if(AddressTypeDisplayValue !=null) {
alert(AddressTypeDisplayValue);
}
}
  • Get the database value of a Bit field
// example GetBitValue("telephone1");

Function GetBitValue(fieldname) {

Return Xrm.Page.data.entity.attributes.get(fieldname).getValue();

}

  • Get the value of a Date field
returns a value like: Wed Nov 30 17:04:06 UTC+0800 2011

and reflects the users time zone set under personal options
// example GetDate("createdon");
Function GetDate(fieldname) {
Return Xrm.Page.data.entity.attributes.get(fieldname).getValue();
}

  • Get the day,month and year parts from a Date field
// This function takes the fieldname of a date field as input and returns a DD-MM-YYYY value
// Note: the day, month and year variables are numbers
Function FormatDate(fieldname) {
var d = Xrm.Page.data.entity.attributes.get(fieldname).getValue();
if(d !=null) {
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;// getMonth() considers Jan month 0, need to add 1
var curr_year = d.getFullYear();
return curr_date + "-" + curr_month + "-"+ curr_year;
}
else return null;
}

// An example where the above function is called
alert(FormatDate("new_date2"));

  • Set the value of a string field:
Note: this example sets the Account Name field on the Account Form to “ABC”

function SetStringField() {
var Name = Xrm.Page.data.entity.attributes.get("name");
Name.setValue("ABC");
}



  • Set the value of an Option Set (pick list) field:

Note: this example sets the Address Type field on the Account Form to “Bill To”, which corresponds to a database value of “1”

 function SetOptionSetField() {
    var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
    AddressType.setValue(1);
}


  • Set a Date field / Default a Date field to Today:

//set date field to now (works on date and date time fields)
Xrm.Page.data.entity.attributes.get("new_date1").setValue(new Date());


  • Set a Date field to 7 days from now:

 function SetDateField() {
    var today = new Date();
    var futureDate = new Date(today.setDate(today.getDate() + 7));
    Xrm.Page.data.entity.attributes.get("new_date2").setValue(futureDate);
    Xrm.Page.data.entity.attributes.get("new_date2").setSubmitMode("always"); // Save the Disabled Field
}

  • Set the Time portion of a Date Field:

// This is a function you can call to set the time portion of a date field
function SetTime(attributeName, hour, minute) {
        var attribute = Xrm.Page.getAttribute(attributeName);
        if (attribute.getValue() == null) {
            attribute.setValue(new Date());
        }
        attribute.setValue(attribute.getValue().setHours(hour, minute, 0));
}

// Here's an example where I use the function to default the time to 8:30am
SetTime('new_date2', 8, 30);


  • Set the value of a Lookup field:

Note: here I am providing a reusable function…

 // Set the value of a lookup field
function SetLookupValue(fieldName, id, name, entityType) {
    if (fieldName != null) {
        var lookupValue = new Array();
        lookupValue[0] = new Object();
        lookupValue[0].id = id;
        lookupValue[0].name = name;
        lookupValue[0].entityType = entityType;
        Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
    }
}
Here’s an example of how to call the function (I retrieve the details of one lookup field and then call the above function to populate another lookup field):

 var ExistingCase = Xrm.Page.data.entity.attributes.get("new_existingcase");
if (ExistingCase.getValue() != null) {
    var ExistingCaseGUID = ExistingCase.getValue()[0].id;
    var ExistingCaseName = ExistingCase.getValue()[0].name;
    SetLookupValue("regardingobjectid", ExistingCaseGUID, ExistingCaseName, "incident");
}


  • Split a Full Name into First Name and Last Name fields:

function PopulateNameFields() {
    var ContactName = Xrm.Page.data.entity.attributes.get("customerid").getValue()[0].name;
    var mySplitResult = ContactName.split(" ");
    var fName = mySplitResult[0];
    var lName = mySplitResult[1];
    Xrm.Page.data.entity.attributes.get("firstname").setValue(fName);
    Xrm.Page.data.entity.attributes.get("lastname").setValue(lName);
}


  • Set the Requirement Level of a Field:

Note: this example sets the requirement level of the Address Type field on the Account form to Required.

Note: setRequiredLevel(“none”) would make the field optional again.

 function SetRequirementLevel() {
    var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
    AddressType.setRequiredLevel("required");
}


  • Disable a field:

function SetEnabledState() {
    var AddressType = Xrm.Page.ui.controls.get("address1_addresstypecode");
    AddressType.setDisabled(true);
}

  • Force Submit the Save of a Disabled Field:

 // Save the Disabled Field
Xrm.Page.data.entity.attributes.get("new_date1").setSubmitMode("always");

  • Show/Hide a field:

 function hideName() {
    var name = Xrm.Page.ui.controls.get("name");
    name.setVisible(false);
}


  • Show/Hide a field based on a Bit field

 function DisableExistingCustomerLookup() {
   var ExistingCustomerBit = Xrm.Page.data.entity.attributes.get("new_existingcustomer").getValue();
    if (ExistingCustomerBit == false) {
       Xrm.Page.ui.controls.get("customerid").setVisible(false);
    }
    else {
       Xrm.Page.ui.controls.get("customerid").setVisible(true);
    }
}

  • Show/Hide a nav item:

Note: you need to refer to the nav id of the link, use F12 developer tools in IE to determine this

 function hideContacts() {
    var objNavItem = Xrm.Page.ui.navigation.items.get("navContacts");
    objNavItem.setVisible(false);
}


  • Show/Hide a Section:

Note: Here I provide a function you can use.  Below the function is a sample.

 function HideShowSection(tabName, sectionName, visible) {
    try {
        Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(visible);
    }
    catch (err) { }
}

HideShowSection("general", "address", false);   // "false" = invisible

  • Show/Hide a Tab:


Note: Here I provide a function you can use. Below the function is a sample.

 function HideShowTab(tabName, visible) {
    try {
        Xrm.Page.ui.tabs.get(tabName).setVisible(visible);
    }
    catch (err) { }
}

HideShowTab("general", false);   // "false" = invisible

  • Save the form:


 function SaveAndClose() {
    Xrm.Page.data.entity.save();
}


  • Save and close the form:

function SaveAndClose() {
    Xrm.Page.data.entity.save("saveandclose");
}


  • Close the form:

Note: the user will be prompted for confirmation if unsaved changes exist

 function Close() {
    Xrm.Page.ui.close();
}


  • Determine which fields on the form are dirty:

 var attributes = Xrm.Page.data.entity.attributes.get()
 for (var i in attributes)
 {
    var attribute = attributes[i];
    if (attribute.getIsDirty())
    {
      alert("attribute dirty: " + attribute.getName());
    }
 }

  • Determine the Form Type:

Note: Form type codes: Create (1), Update (2), Read Only (3), Disabled (4), Bulk Edit (6)

 function AlertFormType() {
    var FormType = Xrm.Page.ui.getFormType();
     if (FormType != null) {
        alert(FormType);
    }
}


  • Get the GUID of the current record:

 function AlertGUID() {
    var GUIDvalue = Xrm.Page.data.entity.getId();
    if (GUIDvalue != null) {
        alert(GUIDvalue);
    }
}

  • Get the GUID of the current user:

 function AlertGUIDofCurrentUser() {
    var UserGUID = Xrm.Page.context.getUserId();
     if (UserGUID != null) {
        alert(UserGUID);
    }
}

  • Get the Security Roles of the current user:

(returns an array of GUIDs, note: my example reveals the first value in the array only)

 function AlertRoles() {
    alert(Xrm.Page.context.getUserRoles());
}

  • Determine the CRM server URL:

// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
    serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}


  • Refresh a Sub-Grid:

var targetgird = Xrm.Page.ui.controls.get("target_grid");
targetgird.refresh();


  • Pop the lookup window associated to a Lookup field:

window.document.getElementById('new_existingcase').click();


  • Change the default entity in the lookup window of a Customer or Regarding field:

Note: I am setting the customerid field’s lookup window to offer Contacts (entityid 2) by default (rather than Accounts).   I have also hardcoded the GUID of the default view I wish displayed in the lookup window.

 function ChangeLookup() {
    document.getElementById("customerid").setAttribute("defaulttype", "2");
    var ViewGUID= "A2D479C5-53E3-4C69-ADDD-802327E67A0D";
    Xrm.Page.getControl("customerid").setDefaultView(ViewGUID);
}

  • Pop an existing CRM record:

Note: this example pops an existing Case record.  The GUID of the record has already been established and is stored in the variable IncidentId.

 //Set features for how the window will appear
var features = "location=no,menubar=no,status=no,toolbar=no";

// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
    serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}

window.open(serverUrl + "/main.aspx?etn=incident&pagetype=entityrecord&id=" + encodeURIComponent(IncidentId), "_blank", features, false);


  • Pop the Create form of a CRM record type:

Note: this example pops the Case form from the Phone Call form, defaulting the Case’s CustomerID based on the Phone Call’s SenderID and defaulting the Case Title to “New Case”

 //Collect values from the existing CRM form that you want to default onto the new record
var CallerGUID = Xrm.Page.data.entity.attributes.get("from").getValue()[0].id;
var CallerName = Xrm.Page.data.entity.attributes.get("from").getValue()[0].name;

//Set the parameter values
var extraqs = "&title=New Case";
extraqs += "&customerid=" + CallerGUID;
extraqs += "&customeridname=" + CallerName;
extraqs += "&customeridtype=contact";

//Set features for how the window will appear
var features = "location=no,menubar=no,status=no,toolbar=no";

// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
    serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}

//Pop the window
window.open(serverUrl + "/main.aspx?etn=incident&pagetype=entityrecord&extraqs=" + encodeURIComponent(extraqs), "_blank", features, false);


  • Pop a Dialog from a ribbon button

Note: this example has the Dialog GUID and CRM Server URL hardcoded, which you should avoid.  A simple function is included which centres the Dialog when launched.

 function LaunchDialog(sLeadID) {
    var DialogGUID = "128CEEDC-2763-4FA9-AB89-35BBB7D5517D";
    var serverUrl = "https://avanademarchdemo.crm5.dynamics.com/";
    serverUrl = serverUrl + "cs/dialog/rundialog.aspx?DialogId=" + "{" + DialogGUID + "}" + "&EntityName=lead&ObjectId=" + sLeadID;
    PopupCenter(serverUrl, "mywindow", 400, 400);
    window.location.reload(true);
}

function PopupCenter(pageURL, title, w, h) {
    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2);
    var targetWin = window.showModalDialog(pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
}


  • Pop a URL from a ribbon button

Great info on the window parameters you can set here:  http://javascript-array.com/scripts/window_open/

 function LaunchSite() {
    // read URL from CRM field
    var SiteURL = Xrm.Page.data.entity.attributes.get("new_sharepointurl").getValue();
    // execute function to launch the URL
    LaunchFullScreen(SiteURL);
}

function LaunchFullScreen(url) {
 // set the window parameters
 params  = 'width='+screen.width;
 params += ', height='+screen.height;
 params += ', top=0, left=0';
 params += ', fullscreen=yes';
 params += ', resizable=yes';
 params += ', scrollbars=yes';
 params += ', location=yes';

 newwin=window.open(url,'windowname4', params);
 if (window.focus) {
     newwin.focus()
 }
 return false;
}

  • Using a SWITCH statement

function GetFormType() {
    var FormType = Xrm.Page.ui.getFormType();
    if (FormType != null) {
        switch (FormType) {
            case 1:
                return "create";
                break;
            case 2:
                return "update";
                break;
            case 3:
                return "readonly";
                break;
            case 4:
                return "disabled";
                break;
            case 6:
                return "bulkedit";
                break;
            default:
                return null;
        }
    }
}



  • Pop an Ok/Cancel Dialog

function SetApproval() {
    if (confirm("Are you sure?")) {
        // Actions to perform when 'Ok' is selected:
        var Approval = Xrm.Page.data.entity.attributes.get("new_phaseapproval");
        Approval.setValue(1);
        alert("Approval has been granted - click Ok to update CRM");
        Xrm.Page.data.entity.save();
    }
    else {
        // Actions to perform when 'Cancel' is selected:
        alert("Action cancelled");
    }

}


Xrm.Page.data.entity.attributes – The data fields represented by fields on the form
Xrm.Page.ui.controls – The user interface controls on the form
Xrm.Page.ui.navigation.items – The navigation items on the form



Wednesday, July 11, 2012

Important Link for MS CRM 2011.

How to set status Completed in Phone call in CRM 2011?

Introduction;

                       I am going to show you how to set status of Phone call in CRM 2011.For that first you have to create the Phone call activities and then after you can set the status of that Phonecall.That means First create a Phone call and then after you set the status of that Phone call.

    SetStateRequest stateform = new SetStateRequest();
    stateform.EntityMoniker = new EntityReference();
    stateform.EntityMoniker.LogicalName = "phonecall";
    stateform.EntityMoniker.Id = new Guid(accid.ToString()); //This is activityId of that Phone call.
    stateform.State = new OptionSetValue(1);
    stateform.Status = new OptionSetValue(2);

If you want to check more status code about phone call or any Entity then Click on this URL.
http://rc.crm.dynamics.com/rc/regcont/en_us/op/articles/statestatus.aspx
                      

Monday, July 9, 2012

How to Attach Notes in Entity in CRM 2011.


Introduction:
                   Hello Today I am going to show tou how to Add Notes in Entity.Here I have insert one Record into the Account entity and after that i am inserting Notes into that Record.

For this First you have to create Console Application.

See the Class Code here.

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

using System.ServiceModel.Description;
using System.ServiceModel;
public class Program
    {
        private static IOrganizationService _service;
        private static OrganizationServiceProxy _serviceProxy;
        private static OrganizationServiceContext orgContext;
        static public void Main(string[] args)
        {
            Program p = new Program();
            p.InsertAccount();
            Console.WriteLine("Inserted eith Notes");
            Console.ReadKey();
        }
        private void InsertAccount()
        {
            try
            {
                string file = "insertlead.txt";
                GetCRMService();
                Entity entity = new Entity("account");
                entity["name"] = "Kartik G Patel";

                entity["emailaddress1"] = "kartik@gmail.com";
                 Guid Accountid=_service.Create(entity);

                


                Entity annotation = new Entity("annotation");
                annotation["objectid"] = new EntityReference("account", Accountid);
                annotation["subject"] = "Kartik Comments";
                annotation["notetext"] = Convert.ToString("This is Kartik's Comment.");
                _service.Create(annotation);
            



            }
            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }
    
        public static void GetCRMService()
        {
            try
            {

                string file = "connection.txt";
                Uri organizationuri = new Uri("https://kartik.crm5.dynamics.com/XRMServices/2011/Organization.svc");
                Uri homeRealmUri = null;

                /*Live CRM*/
                var deviceIDcreds = new ClientCredentials();
                deviceIDcreds.UserName.UserName = "11pqlm4ldg5nqps9b4ivlngbfv";
                deviceIDcreds.UserName.Password = "J-n60IBG7h;Ga`b5##SsDQhP";



                /*Live CRM*/
                var liveIDCreds = new ClientCredentials();
                liveIDCreds.UserName.UserName = "username";
                liveIDCreds.UserName.Password = "password";

                /* If you are not using Live CRM
                ClientCredentials credential = new ClientCredentials();
                credential.Windows.ClientCredential = new NetworkCredential("username", "password", "Organization Name");
                */
                //_serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri, credential, null);
                _serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri, liveIDCreds, deviceIDcreds);
                _serviceProxy.EnableProxyTypes();

                _service = (IOrganizationService)_serviceProxy;
                orgContext = new OrganizationServiceContext(_serviceProxy);
                File.AppendAllLines(file, new string[] { "connection tested" });
            }
            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }
    }

In My code you can see the comments where i show you if you are not using Live CRM then just Replace

var deviceIDcreds = new ClientCredentials();
deviceIDcreds.UserName.UserName = "11pqlm4ldg5nqps9b4ivlngbfv";
deviceIDcreds.UserName.Password = "J-n60IBG7h;Ga`b5##SsDQhP";

var liveIDCreds = new ClientCredentials();
liveIDCreds.UserName.UserName = "username";
liveIDCreds.UserName.Password = "password";

with

ClientCredentials credential = new ClientCredentials();
credential.Windows.ClientCredential = new NetworkCredential("username", "password", "Organization Name");
_serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri, credential, null);

Download the Sample Code from Here
 Download

How to Hide / Show a Tab in CRM 2011 using Javascript OR Toggle visibility of Tab in CRM 2011


To show a tab:

Xrm.Page.ui.tabs.get("yourtabname").setVisible(true);


To hide a tab:
Xrm.Page.ui.tabs.get("yourtabname").setVisible(false);

How to get lookup Text value / Id in CRM 2011


Code Snippet:

var lookupObject = Xrm.Page.getAttribute("yourlookupattributename");

    if (lookupObject != null)
  {

        var lookUpObjectValue = lookupObject.getValue();

        if ((lookUpObjectValue != null))
        {

         var lookuptextvalue = lookUpObjectValue[0].name;

         var lookupid = lookUpObjectValue[0].id;

        }

  }

Thursday, July 5, 2012

How to set value of anyfield during event using Javascript in CRM 2011?


Introduction:
             The below javascript show you how to set the value any field using javascript.

function getvalue()
{
  crmForm.all.firstname.DataValue = "Kartik";
// or crmForm.all.firstname.value = "Kartik" ;
}