Wednesday, 9 January 2013

MS CRM 2011 integration with SharePoint 2010 !!!


MS CRM 2011 provides OOB support for SharePoint integration.This is good post about OOB SharePoint integration.
http://blogs.msdn.com/b/crm/archive/2010/10/08/crm-with-sharepoint-integration-introduction.aspx

We got a new requirement from one of our client where client want to create new documents folders in different SharePoint libraries.

I found good post about SharePoint Client Object Model. Following topics are covered on this post
  1. How to connect with SharePoint 2010 using SharePoint Client Object Model.
  2. How to retrieve SharePoint 2010 documents libraries.
  3. How to create folder in a document library


Download SharePoint Client Object Model and add the reference of following API in your project

Microsoft.SharePoint.Client
Microsoft.SharePoint.Client.Runtime

Here is the sample code.

//create client context
ClientContext _clientContext = new ClientContext(“http://server/SharePointDev”);
_clientContext.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
//create web object
Web web = _clientContext.Web;
_clientContext.Load(web);
_clientContext.ExecuteQuery();

 //read entire document libraries from SharePoint site
var DocumentLibraries = _clientContext.LoadQuery(web.Lists.Where(p => p.BaseType == BaseType.DocumentLibrary && p.Hidden == false));
_clientContext.ExecuteQuery();

If you want to read specific libraries then code will be like
var DocumentLibraries = _clientContext.LoadQuery(web.Lists.Where(p => p.BaseType == BaseType.DocumentLibrary && p.Hidden == false && (p.Title == " library1 " || p.Title == " library2")));
_clientContext.ExecuteQuery();

// check if document libraries are available
if (DocumentLibraries.Count() > 0)
{
foreach (var DocumentLibrary in DocumentLibraries)
{
//Inside each library, create a folder
CreateFolder(_clientContext, web, DocumentLibrary.Title, _FolderName);

//Get Library URL
string url = DocumentLibrary.DefaultViewUrl;
int index = url.LastIndexOf("/Forms/");
url = url.Substring(0, index);
int index1 = url.LastIndexOf("/");
string libURLName = url.Substring(index1 + 1);

//Create SharePoint Document Location Record in CRM.
//string _CreatedFolderPath=_siteUrl+"/"+DocumentLibrary.Title+"/"+_FolderName;
string _CreatedFolderPath = _siteUrl + "/" + libURLName + "/" + _FolderName;
CreateDocumentLocationRecord(CrmService, DocumentLibrary.Title, _CreatedFolderPath, entity.Id);
}
}

private List GetDocumentLibrary(ClientContext _clientContext, Web web, string libraryName)
{
try
{
if (web != null)
{
var query = _clientContext.LoadQuery(
web.Lists.Where(p => p.Title == libraryName));
_clientContext.ExecuteQuery();
return query.FirstOrDefault();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return null;
}

private void CreateFolder(ClientContext _clientContext, Web web, string libraryName, string folder)
{
try
{
var list = GetDocumentLibrary(_clientContext, web, libraryName);
if (list != null)
{
var folders = list.RootFolder.Folders;
_clientContext.Load(folders);
_clientContext.ExecuteQuery();
var newFolder = folders.Add(folder);
_clientContext.ExecuteQuery();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

private void CreateDocumentLocationRecord(IOrganizationService service,string _locationName,string _locationURL,Guid _regarding)
{
try
{
// Instantiate an account object.
Entity DocumentLocation = new Entity("sharepointdocumentlocation");
//set the fields values
DocumentLocation["name"] = _locationName;
DocumentLocation["regardingobjectid"] = new EntityReference("account", _regarding);
DocumentLocation["absoluteurl"] = _locationURL;
//create the record
Guid DocumentLocationid = service.Create(DocumentLocation);

}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}






Wednesday, 6 June 2012

Contact Filtered Lookup based on Party List(Multi select lookup)

Create filtered lookup based on records selected in party list. We have requirement to create filtered contact lookup to selected accounts(associated child contacts) in a party list. This is quite simple like filter lookup in MS CRM 2011 but only different thing need to do is collect all GUID’s(accounts) from party list and then create FetchXML query to retrieve entire child contacts based on the all collected GUID’s(accounts) from party list.

Read party list using JavaScript and store all GUID's into Array object :-
   
var a = 0;
  var Guids = new Array();
  if (Xrm.Page.getAttribute("customers").getValue() != null) {
        var _List = Xrm.Page.getAttribute("customers").getValue();
        if (_List.length > 0) {
            for (a = 0; a < _List.length; a++) {
                Guids[a] = _List[a].id;
            }
        }
    }

Create FetchXML query to retrieve entire child contacts  :-

var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                   "<entity name='contact'>" +
                   "<attribute name='fullname' />" +
                   "<attribute name='contactid' />" +
                   "<order attribute='fullname' descending='false' />" +
                   "<link-entity name='account' from='accountid' to='parentcustomerid' alias='aa'>" +
                   "<filter type='or'>";
    for (var a = 0; a < _List.length; a++) {
        fetchXml += "<condition attribute='accountid' operator='eq' value='" + _List[a] + "'/>";
    }
    fetchXml += "</filter></link-entity></entity></fetch>";

Complete code:- 

function FilterLookup( _DisplayName, _FieldName, _Guids) {
    var viewId = "{65EC9B45-EE81-4F89-BAF6-E8603FF8E1E4}";
    var entityName = "contact";
    var viewDisplayName = "Contacts for " + _DisplayName;
    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                   "<entity name='contact'>" +
                   "<attribute name='fullname' />" +
                   "<attribute name='contactid' />" +
                   "<order attribute='fullname' descending='false' />" +
                   "<link-entity name='account' from='accountid' to='parentcustomerid' alias='aa'>" +
                   "<filter type='or'>";
    for (var a = 0; a < _List.length; a++) {
        fetchXml += "<condition attribute='accountid' operator='eq' value='" + _Guids[a] + "'/>";
    }
    fetchXml += "</filter></link-entity></entity></fetch>";

    //build grid layout
    var layoutXml = "<grid name='resultset' " +

                             "object='1' " +

                             "jump='fullname' " +

                             "select='1' " +

                             "icon='1' " +

                             "preview='1'>" +

                             "<row name='result' " +

                             "id='contactid'>" +

                             "<cell name='fullname' " +

                             "width='300' />" +

                         "</row>" +

                       "</grid>";


    //add new view view
 Xrm.Page.getControl(_FieldName).addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
}


Saturday, 28 April 2012

Auto Populate form fields with Associated lookup fields


let's say we have contact entity there is a lookup to associate parent customer(account). I want to auto populate some fields (Email address, Fax,Phone1 etc) in contact entity with parent customer's fields once parent customer is selected.


function GetRecord(_Filter) {
    try {
        var _Result = null;
        var _EndPoint = Xrm.Page.context.getServerUrl() + "/xrmservices/2011/organizationdata.svc";
        var _XMLHttpRequest = new XMLHttpRequest();
        _XMLHttpRequest.open("GET", _EndPoint + "/" + _Filter, false);
        _XMLHttpRequest.setRequestHeader("Accept", "application/json");
        _XMLHttpRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        var _Result = _XMLHttpRequest.send();
        if (_XMLHttpRequest.readyState == 4 && _XMLHttpRequest.status == 200) {
            _Result = this.parent.JSON.parse(_XMLHttpRequest.responseText).d;
        }
        return _Result;
    }
    catch (Err) {
        alert(Err);
        return;
    }
}


//set contacts fields based on the account selected
function SetFieldsValues() {
    var _RecordId = null;
    var _Columns = "EMailAddress1,Fax,Telephone1";
    var _Entity = "Account";
    if (Xrm.Page.getAttribute("parentcustomerid").getValue() != null) {
        _RecordId = Xrm.Page.getAttribute("parentcustomerid").getValue()[0].id;
        var _Filter = "/" + _Entity + "Set?$select=" + _Columns + "&$filter=" + _Entity + "Id eq (guid'" + _RecordId + "')";
        var _Result = GetRecord(_Filter);
        if (_Result != null && _Result.results.length == 1) {
            //set email address
            if (_Result.results[0].EMailAddress1 != null) {
                Xrm.Page.getAttribute('emailaddress1').setValue(_Result.results[0].EMailAddress1);
            }
            //set fax
            if (_Result.results[0].Fax != null) {
                Xrm.Page.getAttribute('fax').setValue(_Result.results[0].Fax);
            }

            //set Telephone
            if (_Result.results[0].Telephone1 != null) {
                Xrm.Page.getAttribute('telephone1').setValue(_Result.results[0].Telephone1);
            }
        }
    }

}


 
Call SetFieldsValues function inside OnChange event of the parent customer field.

You can change above code according to your requirement.

hope this helps someone...........!