RSS

Tag Archives: MS Dynamics CRM 2011

Use of Shared Variables in Plugin

Introduction

Shared Variables will be useful for sharing the data during complex Plug-in development by sharing the data between Plugins registered on both the pre and post events.

Any value stored in the Plug-in context of Pre-event will be available in the Post-event of the Plug-in. This way, we can avoid storing the values in a custom attribute. Certain data validation which needs to be done at post-event can be achieved by passing the value from Pre-event of the Plug-in. This also helps for performing business logic like updating related records asynchronously.

Using the Code

The below code snippet illustrates the usage of Shared Variable. This sample explains the data validation done at Post-event operation based on the value received from the Pre-event operation where a flag is updated with a value at the Pre-event level and sent to the Post-event through shared variable.

//Pre-Create (Entity Name) Plug-in
if (pluginContext.MessageName == "Create")
{
    if (pluginContext.InputParameters.ContainsKey("Target")
                             && 
        pluginContext.InputParameters["Target"] is Entity)
    {
        Entity targetEntity = context.InputParameters["Target"] as Entity;
        if (targetEntity != null)
        {
            bool setFlag = false;

            //Check data validation for attributes
            string country = targetEntity.Attributes["address1_country"];
            OptionSetValue industryCode = (OptionSetValue)target.Attributes["industrycode"];

            // Country is US and Industry Type is Accounting are Preferred
            if (country.ToLower() == "us" && industryCode.Value == 1)
            {
                setFlag = true;
            }
            
            pluginContext.SharedVariables.Add("flag", setFlag);
        }
    }
}

//Post-Create (Entity Name) Plug-in
if (pluginContext.MessageName == "Create")
{
    if (pluginContext.InputParameters.ContainsKey("Target")
                           && 
        pluginContext.InputParameters["Target"] is Entity)
    {
        Entity targetEntity = pluginContext.InputParameters["Target"] as Entity;
        if (targetEntity != null)
        {
            if (pluginContext.SharedVariables.ContainsKey("flag"))
            {
                bool recievedFlag = (bool)pluginContext.SharedVariables["flag"];
                if (recievedFlag)
                {
                    // Do whatever you want to do
                }
             }
         }
    }
}

This method lets you to pass data between Plug-ins without having to customize the system by creating hidden fields on entities.

Note: SharedVariables (collection of key/value pairs) property is available in the IPluginExecutionContext of the execution pipeline.

By Gitanjali
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 

Tags: , , , , , , , , , , , , , , , , , ,

CRM 2013 Multi Pick List

Background

In One of our previous Blogs CRM 2011 Multi Pick list, we have discussed about creating Multiple Pick List in the MS Dynamic CRM form. But the previous post was for CRM 2011. As the CRM 2013 is supported across different browsers, we have to change a little in the code to make it compatible for all major browsers. Here is the modified Blog for Multi Pick List in MS Dynamics CRM 2013.

Let’s start

In this article, we will create a Multiple Pick List for Dynamic CRM form. User can enter multiple data from Pick List by CheckBox. This will also work on all the four major browsers (IE, Firefox, Chrome and Safari).
5-1-2013 1-35-04 PM

Requirement

There was a requirement in a project, where user wanted to select, not only one, but also multiple value from a Pick List.

Solution

Steps which are needed to be followed:-

  1. Creation of Field.
  2. Create Web Resource.
  3. Add function to the form.

Creation of Field

There are two fields which are created on the entity you want to make Multi Pick List :-

  1. OptionSet Field :- all the option which must be entered
  2. Data Field:- Multiple Lines of Text Field. In which data is stored.

Include both the field on the form.

Create Web Resource

Create a Web Resource with the following code:-

// var_sc_optionset >>  Provide logical-name for Option Set field
// var_sc_optionsetvalue >> Provide logical-name for field which will
//                          store the multi selected values for Option Set
// OS >> Provide Options of the Optionset field
//       (Ex:- Xrm.Page.getAttribute("Option Set field logical-name").getOptions())
// OSV >> Provide text field object which will store the
//        multi selected values for Option Set
//       (Ex:- document.getElementById("text field logical-name"))

// Method to convert an optionset to multi select OptionSet
function ConvertToMultiSelect(var_sc_optionset, var_sc_optionsetvalue, OS, OSV) {

    if (OS != null && OSV != null) {

        document.getElementById(var_sc_optionset).style.display = "none";

        // Create a DIV container
        var addDiv = document.createElement("div");
        addDiv.id = var_sc_optionsetvalue + "_m";
        addDiv.style.width = "100%";
        addDiv.style.height = "80px";
        addDiv.style.background = "#ffffff";
        addDiv.style.color = "white";
        addDiv.style.overflow = "auto";
        addDiv.style.border = "1px #6699cc solid";
        document.getElementById(var_sc_optionset).parentNode.appendChild(addDiv);

        // Declaration of variables will be used in the loop depending upon the browser
        var initialValue = 0;
        var maxValue = 0;

        var nAgt = navigator.userAgent;

        if (nAgt.indexOf("Firefox") != -1) {  // If the broswer is "Firefox" 

            initialValue = 1;
            maxValue = OS.length;

        }
        else if (nAgt.indexOf("Chrome") != -1 || nAgt.indexOf("IE") != -1) { // If the browser is Chrome or IE

            initialValue = 0;
            maxValue = OS.length - 1;
        }
        else if (nAgt.indexOf("Safari") != -1) {  // If the browser id "Safari"

            initialValue = 1;
            maxValue = OS.length;
        }

        // Initialise checkbox controls
        for (var i = initialValue; i < maxValue; i++) {
            var pOption = OS[i];
            if (!IsChecked(pOption.value, var_sc_optionsetvalue)) {
                var addInput = document.createElement("input");
                addInput.type = "checkbox";
                addInput.style.border = "none";
                addInput.style.width = "25px";
                addInput.style.align = "left";
                addInput.style.color = "#000000";
                addInput.onclick = function () {

                    OnSave(var_sc_optionset, var_sc_optionsetvalue);
                    createTable(var_sc_optionsetvalue);
                }
            }
            else {

                var addInput = document.createElement("input");
                addInput.type = "checkbox";
                addInput.checked = true;
                addInput.setAttribute("checked", true);
                addInput.checked = "checked";
                addInput.defaultChecked = true;
                addInput.style.border = "none";
                addInput.style.width = "25px";
                addInput.style.align = "left";
                addInput.style.color = "#000000";
                addInput.onclick = function () {

                    OnSave(var_sc_optionset, var_sc_optionsetvalue);
                    createTable(var_sc_optionsetvalue);
                }

            }

            //Create Label
            var addLabel = document.createElement("label");
            addLabel.style.color = "#000000";
            addLabel.innerHTML = pOption.text;

            var addBr = document.createElement("br"); // it's a 'br' flag

            document.getElementById(var_sc_optionset).nextSibling.appendChild(addInput);
            document.getElementById(var_sc_optionset).nextSibling.appendChild(addLabel);
            document.getElementById(var_sc_optionset).nextSibling.appendChild(addBr);
        }
    }
}

// Check if it is selected
function IsChecked(pText, optionSetValue) {

    var selectedValue = Xrm.Page.getAttribute(optionSetValue).getValue();

    if (selectedValue != "" && selectedValue != null) {
        var OSVT = selectedValue.split(",");

        for (var i = 0; i < OSVT.length; i++) {
            if (OSVT[i] == pText)
                return true;
        }
    }

    return false;
}

// var_sc_optionsetvalue >> Provide logical-name for field which will
//                          store the multi selected values for Option Set
// optionSet>> Provide logical-name of Option Set field 
function OnSave(optionSet, var_sc_optionsetvalue) {

    var OS = document.getElementById(optionSet);
    var options = Xrm.Page.getAttribute(optionSet).getOptions();
    var getInput = OS.nextSibling.getElementsByTagName("input");
    var result = "";
    var result1 = "";
    var nAgt = navigator.userAgent;

    for (var i = 0; i < getInput.length; i++) {
        if (getInput[i].checked) {
            result += getInput[i].nextSibling.innerHTML + ",";

            if (nAgt.indexOf("Firefox") != -1) {  //If the broswer is "Firefox"
                result1 += options[i + 1].value + ",";
            }

            else if (nAgt.indexOf("Chrome") != -1 || nAgt.indexOf("IE") != -1) { //If the browser is Chrome or IE

                result1 += options[i].value + ",";
            }

            else if (nAgt.indexOf("Safari") != -1) {  //If the browser id "Safari"

                result1 += options[i + 1].value + ",";

            }

        }
    }

    //save value
    Xrm.Page.getAttribute(var_sc_optionsetvalue).setValue(result1);
}

// var_sc_optionsetvalue >> Provide logical-name for field which will
//                          store the multi selected values for Option Set
function createTable(var_sc_optionsetvalue) {
    // Get OptionSet value
    var OptionValue = Xrm.Page.getAttribute(var_sc_optionsetvalue);
    var c_OptionValue = Xrm.Page.getControl(var_sc_optionsetvalue);
    var d_OptionValue = var_sc_optionsetvalue + "_d";

    if (OptionValue.getValue() != null) {

        var OptionValueHtml = "<div style=\"overflow-y:auto;width:100%;display: none; min-height: 5em; max-height: 1000px;\">";

        OptionValueHtml += "<table style='width:100%;height: 100%;'>";
        var OptionValueV = OptionValue.getValue();

        var OptionValueT = OptionValueV.split(",");
        var cols = 0;
        for (var row = 0; row < OptionValueT.length - 1; row++) {
            OptionValueHtml += "<tr  style='height:20px;'>";
            for (var i = cols; i < cols + 3; i++) {
                OptionValueHtml += "<td style='width:33%;'>";
                if (OptionValueT[i] != null || OptionValueT[i] != undefined) {

                    OptionValueHtml += OptionValueT[i];
                }
                OptionValueHtml += "</td>";
            }
            cols = cols + 3;
            OptionValueHtml += "</tr>";
            if (cols >= OptionValueT.length) {
                break;
            }
        }

        OptionValueHtml += "</table>";
        OptionValueHtml += "</div>";
        document.getElementById(d_OptionValue).innerHTML = OptionValueHtml;
    }  
}

Add function to the form

There are three functions need to be added

  • On Load :-

    1. Function name :- ConvertToMultiSelect.
      Parameter :- “new_multipicklistoption”, “new_multipicklistvalue”, Xrm.Page.getAttribute(“new_multipicklistoption”).getOptions(), document.getElementById(“new_multipicklistvalue”)
    2. Function name :- createTable
      Parameter :- “new_multipicklistvalue”.

5-1-2013 1-11-58 PM

  • On Save :-

    1. Function Name :- OnSave
      Parameter :- “new_multipicklistoption”, “new_multipicklistvalue”

5-1-2013 1-12-52 PM

Reference

CRM 2011 Multi Pick list

By Ranjan Parhi
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 
2 Comments

Posted by on January 30, 2014 in WebResources

 

Tags: , , , , , , , , , , , , , , , , , , , , , ,

Calling external Web Service from a CRM 2011 Plug-in

Introduction

This blog explains how to call external Web Service from a CRM 2011 Plug-in.

Background

Sometimes we need to call a Web Service from a Plug-in. We had a similar requirement, but while trying to access the service, we got the following error.

“Could not find default endpoint element that references contract ‘ServiceReference.Service′ in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.”

Problem

The reason for this is because the configuration information for the Web Service from the client side is missing.

Using the Code

So, now in case of our plugin, we need to define the binding and endpoint information programmatically. Something like this…

using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using TestPluginConnectWebService.TestService;

namespace TestPluginConnectWebService
{
    public class TestConnectWebService : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            //Context = Info passed to the plugin at runtime
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            //Service = access to data for modification
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);

            // Adding Basic Http Binding and its properties.
            BasicHttpBinding myBinding = new BasicHttpBinding();
            myBinding.Name = "BasicHttpBinding_Service";
            myBinding.Security.Mode = BasicHttpSecurityMode.None;
            myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
            myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

            // Endpoint Address defining the asmx Service to be called.
            EndpointAddress endPointAddress = new EndpointAddress(@"http:///ReturnRecords/GetRecords.asmx");

            // Call to the Web Service using the Binding and End Point Address.
            GetGrantRecordsSoapClient myClient = new GetGrantRecordsSoapClient(myBinding, endPointAddress);

            var ab = myClient.GetGrants();

            if (ab != null)
            {
                 throw new InvalidPluginExecutionException("Success");
            }
            else
            {
                 throw new InvalidPluginExecutionException("Failure");
            }
        }
    }
}

This way we would be able to access our Web Service inside Plug-in.

Note

The following are some of the points that needs special attention.

Sandboxed Plug-ins can access network through the HTTP and HTTPS protocols. This capability provides support for accessing popular Web resources like Social Sites, News Feeds, Web services, and more.
The following Web access restrictions apply to this Sandbox capability.

  • Only the HTTP and HTTPS protocols are allowed.
  • Access to localhost (loopback) is not permitted.
  • IP addresses cannot be used. You must use a named Web address that requires DNS name resolution.

Reference – [MSDN] Plug-in Isolation, Trusts, and Statistics

By Dibyasingh Tripathy
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 

Tags: , , , , , , , , , , , , , , , , , , , , , ,

CRM 2011 Multi Pick list

Introduction

In this article we will create a multiple pick list for dynamic CRM form. In which user can enter multiple data from pick list by check box. This will also work on Firefox and Chrome

5-1-2013 1-35-04 PM

Requirement

There was a demand in a project where user want to select not only one but multiple value from a pick list.

Solution

Steps which are needed to be followed:-

  1. Creation of field.

  2. Create Web resource.

  3. Add function to the form.

Creation of Field

There are two fields which are created on the entity you want to make multipicklist :-

  1. Option Set field :- all the option which must be entered

  2. Data Field:- Multiple Lines of Text Field. In which data is stored.

Include both the field on the form.

Create Web resource

Create a web resource with the following code:-

// var_sc_optionset >>  Provide schema-name for Option Set field
// var_sc_optionsetvalue >> Provide schema-name for field which will
//                          store the multi selected values for Option Set
// OS >> Provide Option Set field object
//       (Ex:- document.getElementById("Option Set field schema-name"))
// OSV >> Provide text field object which will store the
//        multi selected values for Option Set
//       (Ex:- document.getElementById("text field schema-name"))

//Method to convert an optionset to multi select Option Set
function ConvertToMultiSelect(var_sc_optionset, var_sc_optionsetvalue, OS, OSV) {

    if (OS != null && OSV != null) {
        OS.style.display = "none";

        // Create a DIV container
        var addDiv = document.createElement("div");
        addDiv.id = var_sc_optionsetvalue + "_m";
        addDiv.style.width = "100%";
        addDiv.style.height = "80px";
        addDiv.style.background = "#ffffff";
        addDiv.style.color = "white";
        addDiv.style.overflow = "auto";
        addDiv.style.border = "1px #6699cc solid";
        OS.parentNode.appendChild(addDiv);

        // Initialise checkbox controls
        for (var i = 1; i < OS.options.length; i++) {
            var pOption = OS.options[i];
            if (!IsChecked(pOption.innerHTML, OS, OSV)) {
                var addInput = document.createElement("input");
                addInput.type = "checkbox";
                addInput.style.border = "none";
                addInput.style.width = "25px";
                addInput.style.align = "left";
                addInput.style.color = "#000000";
                addInput.onclick = function () {
                    OnSave(OS, var_sc_optionsetvalue);
                    createTable(var_sc_optionsetvalue);
                }

            }
            else {
                var addInput = document.createElement("input");
                addInput.type = "checkbox";
                addInput.checked = "checked";
                addInput.style.border = "none";
                addInput.style.width = "25px";
                addInput.style.align = "left";
                addInput.style.color = "#000000";
                addInput.onclick = function () {
                    OnSave(OS, var_sc_optionsetvalue);
                    createTable(var_sc_optionsetvalue);
                }

            }
            //Create Label
            var addLabel = document.createElement("label");
            addLabel.style.color = "#000000";
            addLabel.innerHTML = pOption.innerHTML;

            var addBr = document.createElement("br"); //it's a 'br' flag

            OS.nextSibling.appendChild(addInput);
            OS.nextSibling.appendChild(addLabel);
            OS.nextSibling.appendChild(addBr);
        }
    }
}

//Supported functions

// Check if it is selected
function IsChecked(pText, OS, OSV) {
    if (OSV.value != "") {
        var OSVT = OSV.value.split(",");

        for (var i = 0; i < OSVT.length; i++) {
           if (OSVT[i] == pText)
              return true;
        }
    }

    return false;
}

// var_sc_optionsetvalue >> Provide schema-name for field which will
//                          store the multi selected values for Option Set
// OS >> Provide Option Set field object
// Save the selected text, this field can also be used in Advanced Find
function OnSave(OS, var_sc_optionsetvalue) {
    var getInput = OS.nextSibling.getElementsByTagName("input");
    var result = "";

    for (var i = 0; i < getInput.length; i++) {
        if (getInput[i].checked) {
            result += getInput[i].nextSibling.innerHTML + ",";
        }
    }

    //save value
    control = Xrm.Page.getControl(var_sc_optionsetvalue);
    attribute = control.getAttribute();
    attribute.setValue(result);
}

function createTable(var_sc_optionsetvalue) {
    //get option set value
    var OptionValue = Xrm.Page.getAttribute(var_sc_optionsetvalue);
    var c_OptionValue = Xrm.Page.getControl(var_sc_optionsetvalue);
    var d_OptionValue = var_sc_optionsetvalue + "_d";

    if (OptionValue.getValue() != null) {

        c_OptionValue.setVisible(true);
        var OptionValueHtml = "<div style=\"overflow-y:auto;width:100%; min-height: 5em; max-height: 1000px;\">";

        OptionValueHtml += "<table style='width:100%;height: 100%;'>";
        var OptionValueV = OptionValue.getValue();

        var OptionValueT = OptionValueV.split(",");
        var cols = 0;
        for (var row = 0; row < OptionValueT.length - 1; row++) {
            OptionValueHtml += "<tr  style='height:20px;'>";
            for (var i = cols; i < cols + 3; i++) {
                OptionValueHtml += "<td style='width:33%;'>";
                if (OptionValueT[i] != null || OptionValueT[i] != undefined) {

                    OptionValueHtml += OptionValueT[i];
                }
                OptionValueHtml += "</td>";
            }
            cols = cols + 3;
            OptionValueHtml += "</tr>";
            if (cols >= OptionValueT.length) {
                break;
            }
        }

        OptionValueHtml += "</table>";
        OptionValueHtml += "</div>";
        document.getElementById(d_OptionValue).innerHTML = OptionValueHtml;
    }
    else {
        c_OptionValue.setVisible(false);
    }
}

Add function to the form

There are three function which are needed to be added

  1. On Load :-

    1. Function name :- ConvertToMultiSelect.
      Parameter :- “new_multipicklistoption”, “new_multipicklistvalue”, document.getElementById(“new_multipicklistoption”), document.getElementById(“new_multipicklistvalue”)

    2. Function name :- createTable
      Parameter :- “new_multipicklistvalue”.
      5-1-2013 1-11-58 PM

    1. On Save :-
      1. Function Name :- OnSave
        Parameter :- document.getElementById(“new_multipicklistoption”), “new_multipicklistoption”

5-1-2013 1-12-52 PM

Reference

Multi-Select Option Sets in Dynamics CRM: Part 1(See Part 2 for the Latest Code)

By Sukant Shekhar
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 
 

Tags: , , , , , , , , , , , , , , , , , , ,

Customization of CRM Application on Basis Of Security Role

Introduction

This article is about the change in CRM Application page made as per the role.

Requirement

There was a need which was made in a project to show only those views, buttons and links which are relevant for a particular role. Here are few steps which I took to customize the CRM as per Role.

Changes which are need to be made

  1. Change in the security role
  2. Customization of all the CRM form (Home page, Form Data Entry page, Form grid page)
  3. Changing the views according to the roles

Change in the security role

Change in the security role is made in the Setting → Administration → Security Role.

The privilege can be given on the basis of

  1. None:- That privilege will not be given
  2. User :- That user will able to do operation on his/her records only.
  3. Business Unit :- That user will able to do operation on his/her business unit records only.
  4. Parent Business Unit :- That user will able to do operation on his/her parent business unit records only.
  5. Organization :- That user will able to do operation on all records.

Security Role

Customization of all the CRM form (Home page, Form Data Entry page, Form grid page)

There are two things which are needed to be changed:-

  1. Ribbon Button
  2. Site map

Ribbon button Customization

Steps(Example :- Advance Find):-
  1. Create an entity in the name of the button (new_advancefindrole)
  2. Give the permission to the entity(new_advancefindrole) in the Security Role under custom entity(Read).
  3. Open the ribbon solution in a ribbon editor.
  4. Add a new button and copy  the (detail,action , display rule, enable rule ) from advance find to new button
  5. Add a new display rule
    1. Entity Privilege rule
    2. Give the name of the entity(new_advancefindrole)
    3. Privilege depth :- Basic
    4. Privilege type :- Read
    5. Default :- true
    6. Invert Result :- false
  6. Hide the original advance find button(we can’t change the display rule in original advance find as it is managed)
  7. Save the customization
  8. Give permission under security role to entity(new_advancefindrole) to read to show in different roles.

Site Map

Steps(Example :- Settings):-

  1. Create an entity in the name of the button (new_settingsrole)
  2. Give the permission to the entity(new_settingsrole) in the Security Role under custom entity(Read)
  3. Export the “Site map” solution from the CRM
  4. Open Customization.xml in an xml editor
  5. Find “Area Id=<AreaName>(Ex :- Settings)” tag. Paste the Code Below
  6. Paste this code under every subarea of the settings
  7. Save the solution zip it , import it and publish it
  8. give permission under security role to entity(new_settingsrole) to read to show in different roles.

Changing the views according to the roles

Showing the view according to the role. There are two method in which this can be done :-

  1. By plug-in
  2. By creating personal view and sharing it with team

By Plug-in

Steps:-

  1. Create the Plug-in with following code.
  2. By this plug-in the view Starting from “My” will not be shown
  3. Register it :-
    1. Message :- RetriveMultiple
    2. Primary Entity :- savedquery
    3. Eventing :- Per-operation
    4. Execution Mode:- Synchronous
    5. Deployment:- Server

Plug-in Code:-

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Microsoft.Crm.Sdk;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;

namespace Excitation.PluginHideSystemViews
{
    public class CheckView : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                // Obtain the execution context from the service provider.
                Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
                // Obtain the organization service reference.
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                // The InputParameters collection contains all the data passed in the message request.
                if (CheckRole(context.UserId, "Salesperson", service))
                {

                    if (context.InputParameters.Contains("Query") == true && context.InputParameters["Query"] is QueryExpression)
                    {
                        QueryExpression qe = (QueryExpression)context.InputParameters["Query"];

                        if (qe.EntityName == "savedquery")
                        {
                            if (qe.Criteria != null)
                            {
                                if (qe.Criteria.Conditions != null)
                                {
                                    /*The query is edited to look at views not starting with "My" at the begining of the View Name*/
                                    ConditionExpression queryCondition = new ConditionExpression("name", ConditionOperator.NotLike, "My%");
                                    qe.Criteria.Conditions.Add(queryCondition);
                                    //context.InputParameters.Properties[ParameterName.Query] = qe;
                                    context.InputParameters["Query"] = qe;
                                }
                            }
                        }

                    }
                }
                else
                {
                    QueryExpression qe = (QueryExpression)context.InputParameters["Query"];
                    context.InputParameters["Query"] = qe;
                }
            }
            catch (Exception e)
            {

            }
        }

        //check if the user belongs to the specified role....
        private static bool CheckRole(Guid UserGuid, string SecurityRole, IOrganizationService CrmService)
        {
            #region Retrieve records from an intersect table via QueryExpression

            //Create Query Expression to fetch Role Entity
            QueryExpression Query = new QueryExpression()
            {
                //Setting the link entity condition and filter condition criteria/
                LinkEntities =
                        {
                            new LinkEntity
                            {
                                LinkFromEntityName = "role",
                                LinkFromAttributeName = "roleid",
                                LinkToEntityName = "systemuserroles",
                                LinkToAttributeName = "roleid",
                                LinkCriteria = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions =
                                    {
                                        new ConditionExpression
                                        {
                                            AttributeName = "systemuserid",
                                            Operator = ConditionOperator.Equal,
                                            Values = { UserGuid }
                                        }
                                    }
                                }
                            }
                        }
            };
            Query.EntityName = "role";

            Query.ColumnSet = new ColumnSet(true);

            // Obtain results from the query expression.
            EntityCollection UserRoles = CrmService.RetrieveMultiple(Query);

            // Searching for a specified Security Role into the list
            String test = "";
            test = UserGuid + "   \n";

            foreach (Entity UserSecurityRole in UserRoles.Entities)
            {
                test += (String)UserSecurityRole.Attributes["name"] + "  \n";
                if ((String)UserSecurityRole.Attributes["name"] == SecurityRole)
                {
                    return true;
                }
            }
            Entity testE = new Entity("new_transfer_opp");
            testE.Attributes["new_name"] = test;
            CrmService.Create(testE);
            if (UserRoles.Entities.Count == 0)
            {
                //return false as the role does not present
                return false;
            }
            else
            {
                return false;
            }

            #endregion

        }
    }
}

By creating personal view and sharing it with team

Steps(Example:- Sale manager):-

  1. Create a team(Sales manager) and add user to that team (Team is added under Administration)
  2. Create a view by Advance find Save that view
  3. Go to saved view and share the view to the team you want to see that view.

View Cutomization

By Sukant Shekhar
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 

Tags: , , , , , , , , , , , , , , , , , , ,

Closing Opportunity using SOAP Request with Close Date

Project scenario

Using SOAP request I need to close opportunity from a custom HTML page. While closing opportunity, I need to send date also as close date for ‘Close Opportunity’.

Explanation of Code

Here format of date is very much different which is used to send through SOAP. I faced problem and stuck for 3 to 4 hours for this.

Finally I did.

Suppose,

var dateToSend = new Date();

Take a Date object and format it as :

dateToSend.format("yyyy-MM-ddThh:mm:ss.sszzz");

Only this Date format is taken by SOAP request.

Total SOAP request is as follows :

function CreateSoapXml(Id, Description, ActualRevenue, CloseDate, CompetitorId, Subject, Status) {
    var callback;

    xml += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    xml += " <s:Body>";
    xml += " <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    xml += " <request i:type=\"b:LoseOpportunityRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
    xml += " <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    xml += " <a:KeyValuePairOfstringanyType>";
    xml += " <c:key>OpportunityClose</c:key>";
    xml += " <c:value i:type=\"a:Entity\">";
    xml += " <a:Attributes>";
    xml += " <a:KeyValuePairOfstringanyType>";
    xml += " <c:key>opportunityid</c:key>";
    xml += " <c:value i:type=\"a:EntityReference\">";
    xml += " <a:Id>" + Id + "</a:Id>";
    xml += " <a:LogicalName>opportunity</a:LogicalName>";
    xml += " <a:Name i:nil=\"true\" />";
    xml += " </c:value>";
    xml += " </a:KeyValuePairOfstringanyType>";
    xml += " <a:KeyValuePairOfstringanyType>";
    xml += " <c:key>description</c:key>";
    xml += " <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">" + Description + "</c:value>";
    xml += " </a:KeyValuePairOfstringanyType>";
    xml += " <a:KeyValuePairOfstringanyType>";
    xml += " <c:key>competitorid</c:key>";
    xml += " <c:value i:type=\"a:EntityReference\">";
    xml += " <a:Id>" + CompetitorId + "</a:Id>";
    xml += " <a:LogicalName>competitor</a:LogicalName>";
    xml += " <a:Name i:nil=\"true\" />";
    xml += " </c:value>";
    xml += " </a:KeyValuePairOfstringanyType>";
    xml += " <a:KeyValuePairOfstringanyType>";
    xml += " <c:key>actualrevenue</c:key>";
    xml += " <c:value i:type=\"a:Money\">";
    xml += " <a:Value>" + ActualRevenue + "</a:Value>";
    xml += " </c:value>";
    xml += " </a:KeyValuePairOfstringanyType>";
    xml += " <a:KeyValuePairOfstringanyType>";
    xml += " <c:key>subject</c:key>";
    xml += " <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">" + Subject + "</c:value>";
    xml += " </a:KeyValuePairOfstringanyType>";
    xml += " <a:KeyValuePairOfstringanyType>";
    xml += " <c:key>actualend</c:key>";
    xml += " <c:value i:type=\"d:dateTime\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">" + CloseDate + "</c:value>";
    xml += " </a:KeyValuePairOfstringanyType>";
    xml += " </a:Attributes>";
    xml += " <a:EntityState i:nil=\"true\" />";
    xml += " <a:FormattedValues />";
    xml += " <a:Id>00000000-0000-0000-0000-000000000000</a:Id>";
    xml += " <a:LogicalName>opportunityclose</a:LogicalName>"
    xml += " <a:RelatedEntities />";
    xml += " </c:value>";
    xml += " </a:KeyValuePairOfstringanyType>";
    xml += " <a:KeyValuePairOfstringanyType>";
    xml += " <c:key>Status</c:key>";
    xml += " <c:value i:type=\"a:OptionSetValue\">";
    xml += " <a:Value>" + Status + "</a:Value>";
    xml += " </c:value>"
    xml += " </a:KeyValuePairOfstringanyType>";
    xml += " </a:Parameters>";
    xml += " <a:RequestId i:nil=\"true\" />";
    xml += " <a:RequestName>LoseOpportunity</a:RequestName>";
    xml += " </request>";
    xml += " </Execute>";
    xml += " </s:Body>";
    xml += "</s:Envelope>";
}

//Then send SOAP request as :

var req = new XMLHttpRequest();
req.open("POST", GetServerUrl(), (callback != null));
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
req.send(xml);

if (req.readyState == 4) {
    if (req.status == 200) {
        alert("Opportunity Closed");
        Cancel();
        //window.opener.location.reload();
    }
    else {
        //errorCallback(_getError(req.responseXML));
        alert("There is an error occured");
    }
}

By Anish Thakur
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 

Tags: , , , , , , , , , , , , , , , , ,

Convert a Multiple Line of Text field to a Button using JavaScript

First of all create a new field of type “Multiple Lines of Text” and name it as “new_button“.
And also create a “JavaScript Webresource” and add the following method in onload event.
ButtonImage
function OnFormLoad() {
    ConvertTextFieldToButton('new_button', 'ButtonText', '100px', ButtonClickFunction, 'Button Label');
}
 
function ConvertTextFieldToButton(fieldname, buttontext, buttonwidth, clickevent, title) {
    if (document.getElementById(fieldname) == null) {
        return;
    }
 
    var functiontocall = clickevent;
    document.getElementById(fieldname).value= buttontext;
    document.getElementById(fieldname).readOnly = true;
    document.getElementById(fieldname).style.borderRight = "#3366cc 1px solid";
    document.getElementById(fieldname).style.paddingRight = "5px";
    document.getElementById(fieldname).style.borderTop = "#3366cc 1px solid";
    document.getElementById(fieldname).style.paddingLeft = "5px";
    document.getElementById(fieldname).style.fontSize = "11px";
    document.getElementById(fieldname).style.backgroundImage = "url(/_imgs/btn_rest.gif)";
    document.getElementById(fieldname).style.borderLeft = "#3366cc 1px solid";
    document.getElementById(fieldname).style.width = buttonwidth;
    document.getElementById(fieldname).style.cursor = "hand";
    document.getElementById(fieldname).style.lineHeight = "18px";
    document.getElementById(fieldname).style.borderBottom = "#3366cc 1px solid";
    document.getElementById(fieldname).style.backgroundRepeat = "repeat-x";
    document.getElementById(fieldname).style.fontFamily = "Tahoma";
    document.getElementById(fieldname).style.height = "20px";
    document.getElementById(fieldname).style.backgroundColor = "#cee7ff";
    document.getElementById(fieldname).style.textAlign = "center";
    document.getElementById(fieldname).style.overflow = "hidden";

    if(window.attachEvent)
    {
        document.getElementById(fieldname).attachEvent("onmousedown", MouseDown_button);
        document.getElementById(fieldname).attachEvent("onmouseup", MouseUp_button);        
        document.getElementById(fieldname).attachEvent("onclick", functiontocall);
    }
    else
    {
        document.getElementById(fieldname).addEventListener("mousedown", MouseDown_button, false);
        document.getElementById(fieldname).addEventListener("mouseup", MouseUp_button, false);        
        document.getElementById(fieldname).addEventListener("click", functiontocall, false);
    }

    document.getElementById(fieldname).style.lineHeight = "14px";
    document.getElementById(fieldname + '_c').style.visibility = 'hidden';
    document.getElementById(fieldname + '_d').style.width=buttonwidth;
    document.getElementById(fieldname +'_container').style.width="112px";
    document.getElementById(fieldname).title = title;
    window.focus();
 
    //Method Call on Mouse down
    function MouseDown_button(evt) {
       var eventer;   
  
       if(evt.srcElement)
       {
           eventer = evt.srcElement;
       }
       else
       {
           eventer = evt.target;
       }

       eventer.style.borderWidth = "2px";
       eventer.style.borderStyle = "groove ridge ridge groove";
       eventer.style.borderColor = "#3366cc #4080f0 #4080f0 #3366cc";
    }
 
    //Method Call on Mouse up
    function MouseUp_button(evt) {
       var eventer;   
  
       if(evt.srcElement)
       {
           eventer = evt.srcElement;
       }
       else
       {
           eventer = evt.target;
       }
        
       eventer.style.border = "1px solid #3366cc";
    }
}
 
function ButtonClickFunction() {
    //Method call on button click
}

Notes:
It also supports single line of text.

By Puja Jain
Senior Software Engineer @Team DynamicsCRM.
Mindfire Solutions

 
5 Comments

Posted by on April 25, 2013 in WebResources

 

Tags: , , , , , , , , , , , , , , , ,

 
%d bloggers like this: