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/