Tuesday, February 14, 2017

Sample JavaScript to retrieve using Web API in Dynamics CRM 2016 / 365

function executeWebApiQuery(query, type) {
    var result = null;
    var clientURL = Xrm.Page.context.getClientUrl();
    var req = new XMLHttpRequest()
    req.open(type, encodeURI(clientURL + query), false);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json;charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState == 4) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                result = JSON.parse(this.response);

            }
            else {
                var error = JSON.parse(this.response).error;
                alert("Error : " + error.message);
            }
        }
    };
    req.send(null);
    return result;
}


var query = "/api/data/v8.1/businessunits(" + BUID + ")?$select=name";
var type = "GET";
var queryResult = executeWebApiQuery(query, type);
if (queryResult.Value.length > 0) {
    var BUName = queryResult.Value[0].name;
}

Friday, April 22, 2016

MS CRM - retrieve more than 5000 records C# using Fetchxml


     string fetchtogetactivecustomer = @"<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' />
    <filter type='and'>
      <condition attribute='statecode' operator='eq' value='0' />
    </filter>
  </entity>
</fetch>";
 EntityCollection customersList = GetAllRecords(fetchtogetactivecustomer, service);

        public static EntityCollection GetAllRecords(string fetchxml ,  IOrganizationService service)
        {
            EntityCollection recordsList = new EntityCollection();
            // Define the fetch attributes.
            // Set the number of records per page to retrieve.
            int fetchCount = 5000;
            // Initialize the page number.
            int pageNumber = 1;

            // Specify the current paging cookie. For retrieving the first page,
            // pagingCookie should be null.
            string pagingCookie = null;

            while (true)
            {
                // Build fetchXml string with the placeholders.
                string xml = CreateXml(fetchxml, pagingCookie, pageNumber, fetchCount);

                // Excute the fetch query and get the xml result.
                RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(xml)
                };

                EntityCollection returnCollection = ((RetrieveMultipleResponse)service.Execute(fetchRequest1)).EntityCollection;

                foreach (var c in returnCollection.Entities)
                {
                    recordsList.Entities.Add(c);
                }



                // Check for morerecords, if it returns 1.
                if (returnCollection.MoreRecords)
                {

                    // Increment the page number to retrieve the next page.
                    pageNumber++;

                    // Set the paging cookie to the paging cookie returned from current results.                          
                    pagingCookie = returnCollection.PagingCookie;
                }
                else
                {
                    // If no more records in the result nodes, exit the loop.
                    break;
                }
            }
            return recordsList;
        }


        public static string CreateXml(string xml, string cookie, int page, int count)
        {
            StringReader stringReader = new StringReader(xml);
            XmlTextReader reader = new XmlTextReader(stringReader);

            // Load document
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            return CreateXml(doc, cookie, page, count);
        }

        public static string CreateXml(XmlDocument doc, string cookie, int page, int count)
        {
            XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

            if (cookie != null)
            {
                XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
                pagingAttr.Value = cookie;
                attrs.Append(pagingAttr);
            }

            XmlAttribute pageAttr = doc.CreateAttribute("page");
            pageAttr.Value = System.Convert.ToString(page);
            attrs.Append(pageAttr);

            XmlAttribute countAttr = doc.CreateAttribute("count");
            countAttr.Value = System.Convert.ToString(count);
            attrs.Append(countAttr);

            StringBuilder sb = new StringBuilder(1024);
            StringWriter stringWriter = new StringWriter(sb);

            XmlTextWriter writer = new XmlTextWriter(stringWriter);
            doc.WriteTo(writer);
            writer.Close();

            return sb.ToString();
        }

Wednesday, January 20, 2016

MS CRM 2011 - Enable button based on users security role - Custom rule using javascript

// JavaScript source code
function VisibleButtonBasedOnUserRole() {
    try
    {
        var CRMRole = UserHasRole("System Administrator");
        if (CRMRole) {
            return true;
        } else {
            return false;
        }
    }
    catch (ex) {
        alert(ex.message);
    }

}

function UserHasRole(roleName) {
    var serverUrl = Xrm.Page.context.getServerUrl();
    var BUId = getAuthorizedBU();
    var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
 
    oDataEndpointUrl += "RoleSet?$top=1&$filter=Name eq '" + roleName + "' and BusinessUnitId/Id eq(guid'" + BUId + "')";
    var service = GetRequestObject();

    if (service != null) {
        service.open("GET", oDataEndpointUrl, false);
        service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
        service.setRequestHeader("Accept", "application/json, text/javascript, */*");
        service.send(null);

        var requestResults = eval('(' + service.responseText + ')').d;


        if (requestResults != null && requestResults.results.length == 1) {
            var role = requestResults.results[0];

            var id = role.RoleId;

            var currentUserRoles = Xrm.Page.context.getUserRoles();

            for (var i = 0; i < currentUserRoles.length; i++) {
                var userRole = currentUserRoles[i];
         
                if (GuidsAreEqual(userRole, id)) {
                    return true;
                }
            }
        }
    }

    return false;
}

function getAuthorizedBU() {

    var BUId = null;
    var serverUrl = Xrm.Page.context.getServerUrl();
    var UserID = Xrm.Page.context.getUserId();

    var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
    oDataEndpointUrl += "/SystemUserSet?$select=BusinessUnitId&$filter=SystemUserId eq (guid'" + UserID + "')";


    var service = GetRequestObject();

    if (service != null) {
        service.open("GET", oDataEndpointUrl, false);
        service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
        service.setRequestHeader("Accept", "application/json, text/javascript, */*");
        service.send(null);

        var requestResults = eval('(' + service.responseText + ')').d;

        if (requestResults != null && requestResults.results.length == 1) {
            var businessUnit = requestResults.results[0];
            BUId = businessUnit.BusinessUnitId.Id;
        }
    }

    return BUId;
}

function GetRequestObject() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex) {
            return null;
        }
    }
}


function GuidsAreEqual(guid1, guid2) {
    var isEqual = false;

    if (guid1 == null || guid2 == null) {
        isEqual = false;
    }
    else {
        isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();
    }

    return isEqual;
}

Monday, January 18, 2016

Accessing WCF Service at WCF Client using Custom Binding created programmatically

           
               EndpointAddress remoteAddress = new EndpointAddress(WebServiceURL);

                TestServiceClient serviceClient = new TestServiceClient(GetBinding(), remoteAddress);

                serviceClient.ClientCredentials.UserName.UserName = userNameValue;
                serviceClient.ClientCredentials.UserName.Password = passwordValue;
                serviceClient.Open();

                UpdatePaymentStatusRequest newRequest = new UpdatePaymentStatusRequest();
                newRequest.Status="Paid";
                UpdatePaymentStatusResponse newResponse=newRequest.UpdateStatus(newRequest);

                serviceClient.Close();




 public static CustomBinding GetBinding()
        {
            CustomBinding binding = new CustomBinding();
            binding.Name = "Name_of_your_binding";
            binding.CloseTimeout = TimeSpan.Parse("00:05:00");
            binding.OpenTimeout = TimeSpan.Parse("00:05:00");
            binding.ReceiveTimeout = TimeSpan.Parse("00:10:00");
            binding.SendTimeout = TimeSpan.Parse("00:10:00");
            binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap12, System.Text.Encoding.UTF8));
            //   HttpsTransportBindingElement hbe = new HttpsTransportBindingElement();
            HttpTransportBindingElement hbe = new HttpTransportBindingElement();
            //  hbe.RequireClientCertificate = true;
            hbe.AllowCookies = false;
            hbe.AuthenticationScheme = System.Net.AuthenticationSchemes.Basic;
            hbe.BypassProxyOnLocal = false;
            hbe.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            hbe.KeepAliveEnabled = true;
            hbe.ManualAddressing = false;
            hbe.MaxBufferPoolSize = Convert.ToInt64(int.MaxValue);
            hbe.MaxBufferSize = int.MaxValue;
            hbe.MaxReceivedMessageSize = Convert.ToInt64(int.MaxValue);
            hbe.ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
            hbe.Realm = "";
            hbe.TransferMode = TransferMode.Buffered;
            hbe.UnsafeConnectionNtlmAuthentication = false;
            hbe.UseDefaultWebProxy = true;
            binding.Elements.Add(hbe);
            return binding;
        }

Reference :

http://technologybooth.blogspot.sg/2013/08/initializing-wcf-client-programmatically.html

Thursday, May 28, 2015

MS CRM 2011 - Send Email with attachment ( C# )

      private static void SendEmail(string fromUserEmailId, List<string> toUsersEmails, string attachmentfileLocation, IOrganizationService orgService)
      {       
          EntityReference fromUser=GetUserbyEmailId(fromUserEmailId,orgService);
           List<Entity>  emailFromList =new List<Entity>();
          if(fromUser!=null)
          {
                Entity emailFrom=new Entity("activityparty");
                emailFrom["partyid"] = fromUser;
                emailFromList.Add(emailFrom) ;
          }
         List<Entity> emailToList=new List<Entity>();        
          foreach (string toUser in toUsersEmails)
          {
            
              EntityReference toUserID = GetUserbyEmailId(toUser, orgService);
              if (toUserID != null)
              {
                  Entity emailTo = new Entity("activityparty");
                  emailTo["partyid"] = toUserID;
                  emailToList.Add (emailTo);
              }
          }
            Entity newEmail = new Entity("email");
            newEmail["from"] = emailFromList.ToArray<Entity>();
            newEmail["to"] = emailToList.ToArray<Entity>();
            newEmail["subject"] = "test subject";
            newEmail["description"] = " test description";
            newEmail["directioncode"] = true;
            Guid newEmailId= orgService.Create(newEmail);
            AddAttachmentToEmail(new EntityReference(newEmail.LogicalName, newEmailId), attachmentfileLocation, orgService);
       
              // Use the SendEmail message to send an e-mail message.
              SendEmailRequest sendEmailreq = new SendEmailRequest
              {
               EmailId = newEmailId,
               TrackingToken = "",
               IssueSend = true
              };
              SendEmailResponse sendEmailresp = (SendEmailResponse)orgService.Execute(sendEmailreq);
      }
    
    
      private static void AddAttachmentToEmail(EntityReference email, string fileLocation, IOrganizationService service)
      {
          // Open a file and read the contents into a byte array
          FileStream stream = System.IO.File.OpenRead(fileLocation);
          byte[] byteData = new byte[stream.Length];
          stream.Read(byteData, 0, byteData.Length);
          stream.Close();
        
          // Encode the data using base64.
          string encodedData = System.Convert.ToBase64String(byteData);
          // Add attachment
          Entity newAttachment = new Entity("activitymimeattachment");
          newAttachment["body"] = encodedData;
          newAttachment["filename"] = Path.GetFileName(fileLocation);
          newAttachment["objectid"] = email;
          newAttachment["objecttypecode"] = "email";
          // Create the attachment
          service.Create(newAttachment);
      }
      private static EntityReference GetUserbyEmailId(string emailID, IOrganizationService orgService)
      {
          string fetchQuerytoGetSystemUser = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                              <entity name='systemuser'>
                                                <attribute name='fullname' />
                                                <attribute name='businessunitid' />
                                                <attribute name='title' />
                                                <attribute name='address1_telephone1' />
                                                <attribute name='systemuserid' />
                                                <order attribute='fullname' descending='false' />
                                                <filter type='and'>
                                                  <condition attribute='internalemailaddress' operator='eq' value='" + emailID + "' />"
                                                + @"</filter>
                                              </entity>
                                            </fetch>";
          EntityCollection usersList = orgService.RetrieveMultiple(new FetchExpression(fetchQuerytoGetSystemUser));
          if (usersList != null && usersList.Entities != null && usersList.Entities.Count > 0)
          {
              return new EntityReference(usersList[0].LogicalName, usersList[0].Id);
          }
          return null;
      }
 

Sunday, March 1, 2015

MS Excel - Using Index Match instead of Vlookup



=INDEX ( Column I want a return value from , MATCH ( My Lookup Value , Column I want to Lookup against , Enter “0” ))

 Example,

=IFERROR(INDEX(Sheet5!I:I,MATCH('duplicated clean'!A3,Sheet5!A:A,0)),"")

Reference:

http://www.randomwok.com/excel/how-to-use-index-match/

http://fiveminutelessons.com/learn-microsoft-excel/how-use-index-match-instead-vlookup

Wednesday, January 28, 2015

SSRS - Show blank / Empty rows in Table

1.Insert a new rows in the table

2.Set the visibility using the following expression

=IIF(CountRows() < 1 = 0, true, false)

Note:
Similarly we can show multiple empty rows.
in my case ,i added 10 empty rows & set the row visibility using below expression

=IIF(CountRows() < 1 = 0, true, false) - first row
=IIF(CountRows() < 2 = 0, true, false) - 2nd row, etc..

SSRS - Forcing subreport Contains Empty data / no rows to Show



1.Add a dataset ("dataset2)" in sub report with following query

SELECT ' ' AS DUMMY
 
 
2.Add a empty textbox with following expression
=First(Fields!DUMMY.Value, "DataSet2")
 

Reference:

https://coderwall.com/p/meqrng/forcing-a-ssrs-subreport-to-show


Wednesday, November 12, 2014

MS CRM - SSRS Reports Display Values in Footer - CRM User Name , Execution Time, Page Number

Current CRM User Name

1.Create a dataset & use the below query

SELECT     fullname
FROM         FilteredSystemUser
WHERE     (systemuserid = dbo.fn_FindUserGuid())

2. use the below expression for textbox in Footer

= "Prepared by " & First(Fields!fullname.Value, "DataSet2")

Execution Time

=Globals!ExecutionTime

=Format(Globals!ExecutionTime, "dd/MM/yyyy hh:mm:ss tt")

Page Number

="Page "&Globals!PageNumber &" of "&Globals!TotalPages

Tuesday, November 11, 2014

MS CRM -SSRS Date Parameter - Set dafault Value First Day & Last day of Last Month

Date From: (previous month first day)


=DateSerial(Year(Now), Month(Now), "1").AddMonths(-1)

 

Date To : (previous month last day)

=DateSerial(Year(Now), Month(Now), "1").AddDays(-1)

 

Reference:

http://stackoverflow.com/questions/7842877/first-and-last-day-of-current-month

 

Tuesday, August 12, 2014

Simple Console App to connect to MS CRM

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Description;
//using XrmClasses; // Early Binding Classes

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            CreateAccount();
            Console.ReadLine();
        }


        private static void CreateAccount()
        {

            try
            {
                _service = GetCRMService("<CRM Org Service URL>", false, "<UserName>", "<Password>", "<Domain>");

                //Late Binding
                Entity account = new Entity("account");
                account["name"] = "New Account1";
                _service.Create(account);

                //Early Binding
                //Account newAccount = new Account();
                //newAccount.Name = "New Account2";
                //_service.Create(newAccount);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                WriteLog(ex.Message);
            }
        }


        public static IOrganizationService _service = null;

        // GetCRMService for CRM on premises

        public static IOrganizationService GetCRMService(string CrmUrl, string  isDefaultCredential, string UserName, string Password, string Domain)
        {
            if (_service == null)
            {
               
                //string CrmUrl = (ConfigurationManager.AppSettings["CrmUrl"] != null) ? ConfigurationManager.AppSettings["CrmUrl"] : string.Empty;

                //string isDefaultCredential = (ConfigurationManager.AppSettings["DefaultCredential"] != null) ? ConfigurationManager.AppSettings["DefaultCredential"] 
: string.Empty;

                //string Domain = (ConfigurationManager.AppSettings["Domain"] != null) ? ConfigurationManager.AppSettings["Domain"] : string.Empty;

                //string UserName = (ConfigurationManager.AppSettings["Username"] != null) ? ConfigurationManager.AppSettings["Username"] : string.Empty;

                //string Password = (ConfigurationManager.AppSettings["Password"] != null) ? ConfigurationManager.AppSettings["Password"] : string.Empty;

                //CrmUrl += "/XRMServices/2011/Organization.svc";

                ClientCredentials credentials = new ClientCredentials();

                if (isDefaultCredential == "true")
                {
                    credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(Domain))
                    {
                        throw new Exception("Error: Non-default connection requires username, password and domain!");
                    }
                    else
                    {
                        credentials.Windows.ClientCredential = new System.Net.NetworkCredential(UserName, Password, Domain);
                    }

                }

                if (!string.IsNullOrEmpty(CrmUrl) && CrmUrl.Contains("https"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain,

                   SslPolicyErrors sslPolicyErrors) { return true; };
                }

                OrganizationServiceProxy orgServiceProxy = new OrganizationServiceProxy(new Uri(CrmUrl), null, credentials, null);
                orgServiceProxy.EnableProxyTypes();
                orgServiceProxy.Timeout = new TimeSpan(0, 10, 0);

                _service = (IOrganizationService)orgServiceProxy;
                return _service;
            }
            else
            {
                return _service;
            }
        }

        // GetCRMService for CRM Online
        public static IOrganizationService GetOnlineService()
        {
            IOrganizationService _service;
           
            var liveIDCreds = new ClientCredentials();
            liveIDCreds.UserName.UserName = "username";

            liveIDCreds.UserName.Password = "password";

            var deviceIDcreds = new ClientCredentials();
            deviceIDcreds.UserName.UserName = "11ltfz36jrxd4sdycpkfk7a0gq";

            deviceIDcreds.UserName.Password = "aeKwQN#c/V`RR!!ObqFA,Pz7";
            OrganizationServiceProxy orgServiceProxy =
new OrganizationServiceProxy(new Uri("orgnizationurl"), null, liveIDCreds, deviceIDcreds);

            orgServiceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
           
            orgServiceProxy.EnableProxyTypes();

            _service = (IOrganizationService)orgServiceProxy;
           
            return _service;
        }
                   
    }
}

static string logFilePath = @"D:\IntegrationLog.txt";

public static void WriteLog(string Message)
        {
            using (StreamWriter sw = new StreamWriter(logFilePath, true))
            {
                sw.WriteLine(Message);
            }

        }

Note:

In AD :-

ClientCredentials clientCredentials=new ClientCredentials();

clientCredentials.Windows.ClientCredential = new NetworkCredential(userName, password,domain);

In IFD :-
clientCredentials.UserName.UserName =domain + @"\" + userName;
clientCredentials.UserName.Password = password;


OrganizationServiceProxy service = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(organizationUri, HomeRealmUri, credentials, null);


for more details:




Tuesday, July 22, 2014

MS CRM 2013 - Set Current User's Team as Owner using Javascript


function SetCurrentUserTeam() {
    try {
        var teamName2;
        var TeamId2;
        var type = Xrm.Page.ui.getFormType();
        if (type == 1) {
            var serverUrl = Xrm.Page.context.getServerUrl();
            var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
            // query to get the teams that match the name
            //  oDataEndpointUrl += "TeamSet?$select=Name,TeamId&$filter=Name eq '" + teamName + "'";
            //  oDataEndpointUrl += "TeamSet?$select=Name,TeamId&$filter=teamtype/Value eq 0";
            oDataEndpointUrl += "TeamSet?$select=Name,TeamId";
            var service = GetRequestObject();
            if (service != null) {
                // execute the request
                service.open("GET", oDataEndpointUrl, false);
                service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
                service.setRequestHeader("Accept", "application/json,text/javascript, */*");
                service.send(null);
                // parse the results
                var requestResults = eval('(' + service.responseText + ')').d;
                if (requestResults != null && requestResults.results.length > 0) {
                    var teamCounter;
                    // iterate through all of the matching teams, checking to see if the current user has a membership
                    for (teamCounter = 0; teamCounter < requestResults.results.length; teamCounter++) {
                        // alert(requestResults.results.length);
                        var team = requestResults.results[teamCounter];
                        var teamId = team.TeamId;
                        // get current user teams
                        var currentUserTeams = getUserTeams(teamId);
                        // Check whether current user teams matches the target team
                        if (currentUserTeams != null) {
                            //   alert(currentUserTeams.length);
                            if (currentUserTeams.length > 0) {

                                var currentTeam = currentUserTeams[0];

                                var teamCounter2;
                                // iterate through all of the matching teams, checking to see if the current user has a membership
                                for (teamCounter2 = 0; teamCounter2 < requestResults.results.length; teamCounter2++) {
                                    var team2 = requestResults.results[teamCounter];
                                    if (team2.TeamId == currentTeam.TeamId)
                                        teamName2 = team2.Name;
                                }
                                TeamId2 = currentTeam.TeamId;

                            }

                        }
                    }
                    var lookupValue = new Array();
                    lookupValue[0] = new Object();
                    lookupValue[0].id = TeamId2;

                    lookupValue[0].name = teamName2;

                    lookupValue[0].entityType = "team";

                    Xrm.Page.data.entity.attributes.get('ownerid').setValue(lookupValue);
                    Xrm.Page.getControl('ownerid').setDisabled(true);
                }
            }
        }
        else {
            Xrm.Page.getControl('ownerid').setDisabled(true);
        }
    }
    catch (ex) {
        alert(ex.message);
    }

}

function getUserTeams(teamToCheckId) {
    try {
        // gets the current users team membership

        var userId = Xrm.Page.context.getUserId().substr(1, 36);
        var serverUrl = Xrm.Page.context.getServerUrl();
        var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
        oDataEndpointUrl += "TeamMembershipSet?$filter=SystemUserId eq guid' " + userId + " ' and TeamId eq guid' " + teamToCheckId + " '";
        var service = GetRequestObject();
        if (service != null) {
            service.open("GET", oDataEndpointUrl, false);
            service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
            service.setRequestHeader("Accept", "application/json,text/javascript, */*");
            service.send(null);
            var requestResults2 = eval('(' + service.responseText + ')').d;
            if (requestResults2 != null && requestResults2.results.length > 0) {
                return requestResults2.results;
            }

        }
    }
    catch (ex2)
    { alert(ex2.message); }
}


function GetRequestObject() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    } else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        } catch (ex) {
            return null;
        }
    }
}

for more details:
http://microsoftcrmkartik.blogspot.com/2013/05/get-current-users-teams-in-crm-2011.html

Tuesday, July 1, 2014

MS CRM- Retrieve Records in N:N Relationship

   //The relationship schema
                       string relationshipName = "new_account_new_contact";

                       //Create a query that will check to see if the relationship already exists between contacts related to the Account
                       QueryExpression query1 = new QueryExpression(relationshipName)
                       {
                           NoLock = true,
                           ColumnSet = new ColumnSet(true),//only get the row ID, since we don't need any actual values
                           Criteria =
                           {
                               Filters =
                                                  {
                                                     new FilterExpression
                                                     {
                                                       // FilterOperator = LogicalOperator.And,
                                                         Conditions =
                                                         {
                                                             //Get the row for the relationship where the account and contact are the account
                                                             new ConditionExpression("accountid", ConditionOperator.Equal, entity.Id),
                                                         
                                                         },
                                                       
                                                     },
                                                 }
                           }
                       };

                       EntityCollection retrievedRelations = service.RetrieveMultiple(query1);

                       EntityReferenceCollection existingContactsList = new EntityReferenceCollection();
                       foreach (Entity retrievedRelation in retrievedRelations.Entities)
                       {
                      
                           EntityReference existingContact = new EntityReference("contact", (Guid)
retrievedRelation .Attributes["contactid"]);
                          existingContactsList.Add(existingContact );
                       }
                       service.Associate("account", newAccountId, new Relationship(relationshipName), existingContactsList);

 Associate/Disassociate plugin messages in CRM

http://rajeevpentyala.wordpress.com/2013/04/17/associatedisassociate-plugin-messages-in-crm/

 

  Plugin to associate a record
http://msdynamicscrmblog.wordpress.com/2013/04/29/associate-and-disassociate-many-to-many-relationship-records-using-c-in-microsoft-dynamics-crm-2011/

  

how to use AssociateRequest
http://mileyja.blogspot.com/2011/05/how-to-use-associate-requests-to.html

 


Wednesday, May 21, 2014

Hide Sitemap Areas Based On Security Roles in MS CRM





Q: in MS CRM, I would like to  show only Sales area to the sales team, Marketing area to Marketing team and Service area to service team, how..?

A: create a custom entity ,Add it to all the subareas with “read” privilage. In the site map.remove the read permission with newly created security role & apply the role for the user.

For more details:

http://www.hellokg.com/2013/12/18/hide-sitemap-areas-based-on-security-roles-in-dynamics-crm-2013/