Thursday, December 12, 2013

Pass Custom Parameters to an entity form through a URL in CRM 2013

This blog posted back in 2012, described how to pass custom parameters to an entity in CRM 2011. The other day tried to use the same code to make it in CRM 2013 but unfortunately that would not work. You will be able to pass a single parameter through the URL using the same code as before, but to pass more than one parameters, you need to use the new openEntityForm client API.

In 2011, the parameters would be concatenated to make a string and pass that as the extraqs query string

var extraqs = "Parameter_Source=Hello";
extraqs += "parameter_Source2=8";

//Set features for how the window will appear.
var features = "location=no,menubar=no,status=no,toolbar=no";
// Open the window.
window.open(Xrm.Page.context.getServerUrl() +"/main.aspx?etn=account&pagetype=entityrecord&extraqs=" + encodeURIComponent(extraqs), "_blank", features, false);

Using the new client API to open the record, this would now be presented as follows

var parameters = {};
parameters["myparam_test"] = "1";

parameters["parameter_test"] = "100";

//use the openEntityForm to open the record

Introduction to Actions in CRM 2013

Until CRM 4 there were Workflows that could be used for asynchronous processing of business logic, generally used for setting up automated actions and defining sales process in Dynamics CRM.

Since CRM 2011, the workflows became a category under Processes and there was another category Dialogs introduced. Dialogs provided for execution of Dialog scripts to set up process flows for the Salesforce. These could be used to guide the sales people through the sales process using a question/answer format. The Dialog included execution of automated steps like the workflows.

With CRM 2013, the Processes have been extended to now include Business Process Flow and Actions in addition to the categories from the previous versions. In our earlier blog we have discussed the concept of Business Process Flow. This article will concentrate on Actions.

What are Actions?

Actions are messages that can defined for an entity. Existing examples messages include Create, Update, Set State, Assign etc. With Actions, the CRM platform has enabled the creation of custom actions for entities to extend the XRM platform.

Where to use Actions?

An example of a custom action could be “Approve”. Often times we have to design an approval process for Dynamics CRM. Once the item is approved, certain actions need to be performed. In previous versions it would either be implemented as a Workflow that is manually executed from the Workflows Dialog or it involved added of a custom attribute that when checked would imply the item is approved and then the workflow would capture the update of this field to process any automated actions defined.

How to setup an Action?

Let us take an example of an approval process. When an item is “Approved”, we want to send email notifying the concerned parties of the approval. 



Here is an action created for “Approve”

It accepts an input parameter for the ApprovedBy User. You can specify parameters of any of the following data types

These parameters could be defined as input/output parameter.
  
In the workflow actions, it sends a mail from the ApprovedBy user to the Owner of the Order notifying them of the order being approved. You can also call custom workflow assemblies here.

Note the schema name generated “new_Approve”. This is the name of the new message that will not be available for the Order entity.

These actions are available for further implementation of custom business logic through the use of plugins. In some scenarios, say we need to validate certain conditions are met before the item can be approved. In this case we can register a plugin in the Pre-Stage of the Approve Message. The plugin could validate the conditions and throw an exception to abort the processing of the Approve Message.

How to use Actions?

Since Actions are implemented as custom messages/requests, they can be implemented similar to any other OOB messages like Create or Update.

Using C# code, you can invoke the Approve request using the following code                 

                    //get current user details 
                    WhoAmIRequest userReq = new WhoAmIRequest();

                    WhoAmIResponse resp = (WhoAmIResponse) proxy.Execute(userReq);



         OrganizationRequest req = new OrganizationRequest("new_Approve");
                    req["ApprovedBy"] = new EntityReference("systemuser", resp.UserId);
                    req["Target"] = new EntityReference("salesorder",orderid);

                    //execute the request
                    OrganizationResponse response = proxy.Execute(req);
 

Through jscript it can be invoked as follows.
if (typeof (SDK) == "undefined")
{ SDK = { __namespace: true }; }

SDK.Action = {

    _getClientUrlfunction () {      

        var ServicePath = "/XRMServices/2011/Organization.svc/web";

        var clientUrl = "";
        if (typeof GetGlobalContext == "function") {
            var context = GetGlobalContext();
            clientUrl = context.getClientUrl();
        }
        else {
            if (typeof Xrm.Page.context == "object") {
                clientUrl = Xrm.Page.context.getClientUrl();
            }
            else
            { throw new Error("Unable to access the server URL"); }
        }
        if (clientUrl.match(/\/$/)) {
            clientUrl = clientUrl.substring(0, clientUrl.length - 1);
        }
        return clientUrl + ServicePath;
    },
    ApproveRequest : function (salesOrderId, approvedById) {
        var requestMain = ""
        requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
        requestMain += "  <s:Body>";
        requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
        requestMain += "      <request xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
        requestMain += "        <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>Target</b:key>";
        requestMain += "            <b:value i:type=\"a:EntityReference\">";
        requestMain += "              <a:Id>" + salesOrderId + "</a:Id>";
        requestMain += "              <a:LogicalName>salesorder</a:LogicalName>";
        requestMain += "              <a:Name i:nil=\"true\" />";
        requestMain += "            </b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>ApprovedBy</b:key>";
        requestMain += "            <b:value i:type=\"a:EntityReference\">";
        requestMain += "              <a:Id>" + approvedById + "</a:Id>";
        requestMain += "              <a:LogicalName>systemuser</a:LogicalName>";
        requestMain += "              <a:Name i:nil=\"true\" />";
        requestMain += "            </b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "        </a:Parameters>";
        requestMain += "        <a:RequestId i:nil=\"true\" />";
        requestMain += "        <a:RequestName>new_Approve</a:RequestName>";
        requestMain += "      </request>";
        requestMain += "    </Execute>";
        requestMain += "  </s:Body>";
        requestMain += "</s:Envelope>";
        var req = new XMLHttpRequest();
        req.open("POST", SDK.Action._getClientUrl(), false)
        req.setRequestHeader("Accept""application/xml, text/xml, */*");
        req.setRequestHeader("Content-Type""text/xml; charset=utf-8");
        req.send(requestMain);
        //work with the response here
        //var strResponse = req.responseXML.xml;       

    },
    __namespace: true
};
   

Here in this above script RequestName indicates the Unique Name of Action and Parameters contains collection of key value pairs that can be passed to Action. In above script We can use below function using below syntax.
SDK.Action.ApproveRequest(salesOrderId, approvedById);

You can register plugin on the Approve message. The input parameters of the Approve message will receive the input parameters as defined in the Approve Action.

The plugin registration tool will start showing this message for the Order entity to register plugin against.





Once the plugin is registered, in the code you can access the input parameters just like you do for other messages as shown below 


To get access to the image of the Order record



EntityReference entityRef = localContext.PluginExecutionContext.InputParameters["Target"] as EntityReference;



To read the ApprovedBy input parameter



EntityReference approvedBy = localContext.PluginExecutionContext.InputParameters["ApprovedBy"] as EntityReference;



In the pre-stage, you can throw an InvalidPluginExecution error to abort the Approve operation.



Conclusion:

 Actions is a powerful tool in the hands of the developer to truly extend the CRM platform for XRM implementations.
  

Wednesday, November 6, 2013

How to restore a hidden button on the CRM 2013 Command Bar

The new Dynamics CRM 2013’s command bar has deliberatly limited space for buttons due to the ‘intentionally constrained’ user interface design. The idea being that if you limit the space for buttons, then designers will be forced to only show those that are absolutely necessary and the user experience will be improved. As result, many of the buttons from the CRM 2011 Ribbon Bar have been removed from the CRM 2013 Command Bar.
The CRM2011 Ribbon Buttons are still there, but hidden using a new RibbonXml Display Rule named 'Mscrm.HideOnCommandBar'. This article shows you how to restore those buttons to the Command Bar that your users absolutely must have using the Ribbon Workbench for CRM2013.
1. Create a solution containing the entities that you wish to restore buttons for. This example uses the ‘Case’ entity, and we are restoring the ‘Connect’ button on the ‘Form’ command bar.
Before customising, the Form Command Bar looks like the following:
You’ll notice that only 5 buttons are shown until buttons are added to the ‘overflow’ menu. The ‘Connect’ button is not here since it was deemed unessential.
2. Open the solution containing the Case entity in the Ribbon Workbench for CRM 2013 and select the ‘incident’ entity if not already selected. You will see by default the Command Bar is selected.
 
3. In order to locate the button we want to restore, click on the ‘Ribbon’ selector to show the Ribbon. This will show the Ribbon Design surface.
4. Select the ‘Form’ ribbon using the dropdown on the top right of the design surface, then select the ‘Connect’ button and Right-Click ‘Customize Command’
5. Locate the Customised Command in the ‘Solution Elements’ tab under ‘Commands’
6.  In the Edit Display Rules dialog, select the ‘Mscrm.HideOnCommandBar’ rule and click the ‘<Remove’ button.
7.  Important: Locate the following Display Rules, and set the ‘IsCore’ property to ‘True’ – this will prevent them from being customised as well:
a.      Mscrm.HideOnCommandBar
b.      Mscrm.CreateConnection
c.      Mscrm.IsConnectionsEnabledPrimary
d.      Mscrm.HideOnModern
8. Important: Locate the ‘Mscrm.FormStateExistingOrReadOnlyOrDisabled’ Enable Rule, and set the ‘IsCore’ property to ‘True’
9. Click ‘Publish’
10 Now when you refresh the Case Form, you will see the Connect button again.
11  You’ll notice that only the default button is shown – so if you use the drop down, you’ll only get the ‘Connect to Another’ option. To enable the ‘To Me’ button repeat the process for the ‘To Me’ button:
Remember to make sure that only the buttons that are really needed are included - the Command Bar has been constrained intentially to give your users the best experience.

Thursday, October 17, 2013

CRM 2013 NEW FEATURES: JAVASCRIPT NOTIFICATIONS

RM 2013 come with a set of new JavaScript functions that we can use for sending notifications to the user.  There are form notifications and field notifications.  Here’s an example of a form notification at work…
The function below was registered on the OnSave event of my form.   It notifies the user that a Save has occurred and timestamps the notification.  I post 3 notifications to demonstrate the 3 different types available (error, warning and information):
function NotifyOnSave() {
    var today = new Date();
    Xrm.Page.ui.setFormNotification('Error! A Save occured at ' + today, 'ERROR');
    Xrm.Page.ui.setFormNotification('Warning! A Save occured at ' + today, 'WARNING');
    Xrm.Page.ui.setFormNotification('Information: A Save occured at ' + today, 'INFORMATION');
}
Here’s what appears after the Save:

It’s a little hard to tell on the screenshot but what has happened is each of those 3 notifications has been posted a second time to the form (note: the UI only shows 3 rows of notification, the user has to scroll down to see the other 6 notifications).  The Information notification appears twice due to the sort order applied by the UI:  Information notifications first, then Error notifications followed by Warning notifications.   This is the default behavior  of setFormNotification().   We have options though, we can assign each notification a unique ID and then we can overwrite a previous notification and avoid duplication in a scenario like this.  Here’s the revised JavaScript (note the unique ID added as a 3rd parameter):
function NotifyOnSave() {
    var today = new Date();
    Xrm.Page.ui.setFormNotification('Error! A Save occured at ' + today,'ERROR','1');
    Xrm.Page.ui.setFormNotification('Warning! A Save occured at ' + today,'WARNING','2');
    Xrm.Page.ui.setFormNotification('Information: A Save occured at ' + today,'INFORMATION','3');
}

If you want to clear a notification you use clearFormNotification() and you identify the notification by its unique ID:
    Xrm.Page.ui.clearFormNotification('1'); 

We also get field notification in CRM 2013.  The syntax for these is:
Xrm.Page.getControl(fieldName).setNotification(message);


Tuesday, July 30, 2013

Change the header color of form using Javascript.

InjectHeaderCSS("00C78C","F6F8FA");

function InjectHeaderCSS(startColor, endColor) {

var headerCSSIE9 = ".ms-crm-Form-HeaderContainer{ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#" + startColor + ", endColorstr=#" + endColor + "); }";
var headerCSSIE10 = ".ms-crm-Form-HeaderContainer{background: -ms-linear-gradient(top,  #2989d8 0%,#" + startColor + " 0%,#F6F8FA 100%,#" + endColor + " 100%);}";

var headerchrome = ".ms-crm-Form-HeaderContainer{background: -webkit-linear-gradient(top,  #2989d8 0%,#" + startColor + " 0%,#F6F8FA 100%,#" + endColor + " 100%);}"

var head = document.getElementsByTagName('head')[0];
var styleElement = document.createElement('style');
styleElement.setAttribute('type', 'text/css');
if (styleElement.styleSheet) {
    if (Mscrm.Utilities.isIE9()) {
        styleElement.styleSheet.cssText = headerCSSIE9;
    } else if (Mscrm.Utilities.isIE10()) {
        styleElement.styleSheet.cssText = headerCSSIE10;
    } else if (Mscrm.Utilities.isChrome()) {
        styleElement.styleSheet.cssText = headerchrome;
    } else {
        styleElement.styleSheet.cssText = headerCSSIE9;
    }
}
else {

    if (Mscrm.Utilities.isIE9()) {
        styleElement.appendChild(document.createTextNode(headerCSSIE9));
    } else if (Mscrm.Utilities.isIE10()) {
        styleElement.appendChild(document.createTextNode(headerCSSIE10));
    } else if (Mscrm.Utilities.isChrome()) {
        styleElement.appendChild(document.createTextNode(headerchrome));
    } else {
        styleElement.appendChild(document.createTextNode(headerCSSIE9));
    }
}
head.appendChild(styleElement);

 }

Monday, July 29, 2013

Default Activity ‘Filter on’ to ‘All’ Dynamics CRM 2011 UR12

//default the Activities 'Filter on' to 'All' for Account and Contact for rollup 12 

function filterAllActivities() {

    document.getElementById("navActivities").onclick = function () {
        Mscrm.Details.loadArea(this, "areaActivities");
        document.getElementById("areaActivitiesFrame").onload = function () {
            var entityName = Xrm.Page.data.entity.getEntityName();
            var entity = entityName.charAt(0).toUpperCase() + entityName.substr(1);
            var doc = this.contentWindow.document;
            var filterOn = doc.getElementById("crmGrid_" + entity + "_ActivityPointers_datefilter");
            filterOn.value = "All";
            var evt = document.createEvent("HTMLEvents");
            evt.initEvent("change", false, true);
            filterOn.dispatchEvent(evt);
        };
    };
}

Monday, July 1, 2013

How to get FetchXml of Advance Find View?

    var advFind = _mainWindow.$find("advFind"),
    iOldMode = advFind.get_fetchMode();
    advFind.set_fetchMode(Mscrm.FetchModes.ignoreEmpty);
    var sFetchXml = advFind.get_fetchXml();

Monday, May 27, 2013

Opening Forms using the Xrm.Utility.openEntityForm



Using the openEntityForm

Opening a New Form

To simply open a form for creating a new record you can use the following line of code. Simply replace account with the entity of your choice.

Xrm.Utility.openEntityForm("account");

Open a Form with an Existing Record

If you want to open a specific record you just add the guid for that record like this:

Xrm.Utility.openEntityForm("account","A85C0252-DF8B-E111-997C-00155D8A8410″);

Disable / Enable fields, sections, tabs and the whole Form in MS CRM 2011


When working with the MS CRM form , Your requirement will be to enable (set to read/write) or disable (set to read / only) selected fields, sections, tabs and the Whole form.

Please have a glance below code for these functionalities to work out.

1)     Enable / Disable a field

Xrm.Page.getControl(“fieldname”).setDisabled(false);

2)    Enable / Disable a Section

function sectiondisable (sectionname, disablestatus)

{

var ctrlName = Xrm.Page.ui.controls.get();

for(var i in ctrlName) {

var ctrl = ctrlName[i];

var ctrlSection = ctrl.getParent().getName();

if (ctrlSection == sectionname) {

ctrl.setDisabled(disablestatus);

}

}

}  // sectiondisable

3)    Enable / Disable a Tab

function tabdisable (tabname, disablestatus)
{
 var tab = Xrm.Page.ui.tabs.get(tabname);
 if (tab == null) alert("Error: The tab: " + tabname + " is not on the form");
 else {
     var tabsections =  tab.sections.get();
     for (var i in tabsections) {
         var secname = tabsections[i].getName();
         sectiondisable(secname, disablestatus);
     }
  }
}   // tabdisable


4)    Enable / Disable a Form

function formdisable(disablestatus)
{
    var allAttributes = Xrm.Page.data.entity.attributes.get();
    for (var i in allAttributes) {
           var myattribute = Xrm.Page.data.entity.attributes.get(allAttributes[i].getName());
           var myname = myattribute.getName();        
           Xrm.Page.getControl(myname).setDisabled(disablestatus);
    }
} // formdisable

5)     Enable / Disable All Controls in the TAB

function DisableAllControlsInTab(tabControlNo)
{
var tabControl = Xrm.Page.ui.tabs.get(tabControlNo);
    if (tabControl != null)
{  
      Xrm.Page.ui.controls.forEach
(
     function (control, index)
{        
if (control.getParent().getParent() == tabControl && control.getControlType() != "subgrid")
{              control.setDisabled(true);
        }    
});
      }
 }
function EnableAllControlsInTab(tabControlNo)
 {    
var tabControl = Xrm.Page.ui.tabs.get(tabControlNo);    
if (tabControl != null)
{      
 Xrm.Page.ui.controls.forEach
(    
function (control, index)
{        
if (control.getParent().getParent() == tabControl && control.getControlType() != "subgrid")
{            
control.setDisabled(false);
        }
    });
    }
 }
 Hope this will help.

Regards,

Friday, May 24, 2013

Get Required Attendee(Activity Party) value from Appointment.


Guid Id = new Guid("D77839B3-CBC2-E211-8DC3-B4B52F6714CA");
            XrmServiceContext _context = new XrmServiceContext(_service);
            Appointment appointment = _context.AppointmentSet.Where(p=>p.ActivityId==Id).SingleOrDefault();
            if (appointment != null)
            {
               
                EntityCollection receipt = new EntityCollection();
                receipt = appointment.GetAttributeValue<EntityCollection>("requiredattendees");
                for (int i = 0; i < receipt.Entities.Count; i++)
                {
                    ActivityParty ap = receipt[i].ToEntity<ActivityParty>();

                    string id,name;

                    if (ap.PartyId.LogicalName == "account")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                    if (ap.PartyId.LogicalName == "contact")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                    if (ap.PartyId.LogicalName == "systemuser")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                }
            }

Thursday, May 23, 2013

Find the day of the week.


 var startday = Xrm.Page.getAttribute("new_quotestart").getValue().getDay();

Find the Number of Days between two Days.



function CalculateDaysOpen()
{
        var FormType = Xrm.Page.ui.getFormType();
        if (FormType != null && FormType==2)
{
                  var currentDate=new Date();
 var createdDate=Xrm.Page.data.entity.attributes.get("createdon").getValue();
                  cycletime = Math.abs(currentDate- createdDate)
          alert(Math.round(cycletime / 86400000));
         }
}

Get Current User's Teams in crm 2011 using javascript.


function GetCurrentUserTeams() {

  var user = Xrm.Page.context.getUserId();
  var userId = user.substring(1,37);

    var xml = "" +
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
    GenerateAuthenticationHeader() +
    " <soap:Body>" +
    " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
    " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
    " <q1:EntityName>team</q1:EntityName>" +
    " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
    " <q1:Attributes>" +
    " <q1:Attribute>name</q1:Attribute>" +
    " </q1:Attributes>" +
    " </q1:ColumnSet>" +
    " <q1:Distinct>false</q1:Distinct>" +
    " <q1:LinkEntities>" +
    " <q1:LinkEntity>" +
    " <q1:LinkFromAttributeName>teamid</q1:LinkFromAttributeName>" +
    " <q1:LinkFromEntityName>team</q1:LinkFromEntityName>" +
    " <q1:LinkToEntityName>teammembership</q1:LinkToEntityName>" +
    " <q1:LinkToAttributeName>teamid</q1:LinkToAttributeName>" +
    " <q1:JoinOperator>Inner</q1:JoinOperator>" +
    " <q1:LinkCriteria>" +
    " <q1:FilterOperator>And</q1:FilterOperator>" +
    " <q1:Conditions>" +
    " <q1:Condition>" +
    " <q1:AttributeName>systemuserid</q1:AttributeName>" +
    " <q1:Operator>Equal</q1:Operator>" +
    "<q1:Values>" +
    //code to get the owner
    "<q1:Value xsi:type=\"xsd:string\">" + userId + "</q1:Value>" +
    "</q1:Values>" +

    " </q1:Condition>" +
    " </q1:Conditions>" +
    " </q1:LinkCriteria>" +
    " </q1:LinkEntity>" +
    " </q1:LinkEntities>" +
    " </query>" +
    " </RetrieveMultiple>" +
    " </soap:Body>" +
    "</soap:Envelope>" +
    "";
    var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);
    var resultXml = xmlHttpRequest.responseXML;
    //alert(resultXml.xml);

    // Save all entity nodes in an array.
    var entityNodes = resultXml.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

    var teamnames = new Array();
    var teamids = new Array();

    for (var i = 0; i < entityNodes.length; i++) {

        var entityNode = entityNodes[i];
        var teamidNode = entityNode.selectSingleNode("q1:teamid");
        var teamNode = entityNode.selectSingleNode("q1:name");
        var teamid = (teamidNode == null) ? null : teamidNode.text;
        var team = (teamNode == null) ? null : teamNode.text;

        teamnames[i] = team;
        teamids[i] = teamid;
    }

    alert(teamnames);
}


Above script will not work in CRM 2013. For CRM 2013,the script is as below

function GetCurrentUserTeams()
{
    var teamName="Communities Team";
if (teamName != null && teamName != "") {
// build endpoint URL
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 + "'";
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++) {
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) {
for (var i = 0; i < currentUserTeams.length; i++) {
var userTeam = currentUserTeams[i];
// check to see if the team guid matches the user team membership id
if (GuidsAreEqual(userTeam.TeamId, teamId)) {
return true;
}
}
}
else {
return false;
}
}
}
else {
alert("Team with name '" + teamName + "' not found");
return false;
}
return false;
}
 }
 else {
 alert("No team name passed");
 return false;
 }
}
function getUserTeams(teamToCheckId) {
 // 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 requestResults = eval('(' + service.responseText + ')').d;
if (requestResults != null && requestResults.results.length > 0) {
 return requestResults.results;
 }
 }
}
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) {
 // compares two guids
 var isEqual = false;
 if (guid1 == null || guid2 == null) {
 isEqual = false;
 } else {
 isEqual = (guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase());
 }
 return isEqual;
}