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