Tuesday 23 June 2015

Change Record Status using Javascript in CRM

Hi,

Sometimes we get the requirement to change the status of the record on the button click or some where using JavaScript.

Here is the JavaScript of it.

// Method Calling
vId = Xrm.Page.data.entity.getId();
vEntityName = Xrm.Page.data.entity.getEntityName();
changeRecordStatus(vId, vEntityName, 1, 2);

function changeRecordStatus(RECORD_ID, Entity_Name, stateCode, statusCode ) {
    var url = "";
    if (Xrm.Page.context.getClientUrl) {
        //Post UR 12
        url = Xrm.Page.context.getClientUrl();
    }
    else {
        //Pre UR 12
        url = Xrm.Page.context.getServerUrl();
    }
    // create the SetState request
    var request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    request += "<s:Body>";
    request += "<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    request += "<request i:type=\"b:SetStateRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
    request += "<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    request += "<a:KeyValuePairOfstringanyType>";
    request += "<c:key>EntityMoniker</c:key>";
    request += "<c:value i:type=\"a:EntityReference\">";
    request += "<a:Id>" + RECORD_ID + "</a:Id>";
    request += "<a:LogicalName>"+Entity_Name+"</a:LogicalName>";
    request += "<a:Name i:nil=\"true\" />";
    request += "</c:value>";
    request += "</a:KeyValuePairOfstringanyType>";
    request += "<a:KeyValuePairOfstringanyType>";
    request += "<c:key>State</c:key>";
    request += "<c:value i:type=\"a:OptionSetValue\">";
    request += "<a:Value>" + stateCode + "</a:Value>";
    request += "</c:value>";
    request += "</a:KeyValuePairOfstringanyType>";
    request += "<a:KeyValuePairOfstringanyType>";
    request += "<c:key>Status</c:key>";
    request += "<c:value i:type=\"a:OptionSetValue\">";
    request += "<a:Value>" + statusCode + "</a:Value>";
    request += "</c:value>";
    request += "</a:KeyValuePairOfstringanyType>";
    request += "</a:Parameters>";
    request += "<a:RequestId i:nil=\"true\" />";
    request += "<a:RequestName>SetState</a:RequestName>";
    request += "</request>";
    request += "</Execute>";
    request += "</s:Body>";
    request += "</s:Envelope>";
    //send set state request
    $.ajax({
        type: "POST",
        contentType: "text/xml; charset=utf-8",
        datatype: "xml",
        url: url + "/XRMServices/2011/Organization.svc/web",
        data: request,
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
            XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            Xrm.Page.data.refresh();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
   });
}
Hope this helps.

--
Happy CRM'ing
Gopinath.

Wednesday 17 June 2015

Disable AutoSave Functionality in CRM 2013/2015


Microsoft Dynamics CRM 2013/2015 has the ability to save records every 30 seconds automatically when you create new record or update existing record.

Sometimes it might cause performance issues, If you have plug-ins, workflows, or form scripts that execute when a record is saved, they’ll run each time auto-save occurs. This might lead to undesirable behaviors if these extensions weren’t designed to work with auto-save.

This feature can also be disabled at organization level in the System Settings
  • Dynamics CRM-> Settings tile
  • Click on Settings-> Administration tile
  • Click on System Settings icon
  • Set No to Enable auto save on all forms under Select the default save option for forms. 

Since it is organization level settings, once you set No auto save will not work on any entity. There is no option to disable auto save at the entity or form level, but a small script can be added to the OnSave event of a form that will disable it on the form level. Check out below how to do this.
  • Write following JavaScript code in your entity JavaScript file.
           function preventAutoSave(exeContext) {
          var eventArgs = exeContext.getEventArgs();
          if (eventArgs.getSaveMode() == 70) {
             eventArgs.preventDefault();
          }
      }
  • In the Form Properties window, in the Event Handlers section, set Event to OnSave.
  • Click on Add and choose the above code written JavaScript resource file
  • In the Handler Properties window, set Library to the web resource you added in the previous step.
  • Type preventAutoSave in the Function field. This is case sensitive. Do not include quotation marks.
  • Make sure that Enabled is checked.
  • Check Pass execution context as first parameter.
  • Click OK to close the Handler Properties dialog.
  • The Handler Properties dialog should look like this.
For more information on SaveEventArguements
 
Hope this helps.

--
Happy CRM'ing
Gopinath.

Monday 15 June 2015

Access Teams Vs Owner Teams in CRM 2013/2015

Hi,
 
Here is some information about Access Teams and Owner Teams.
 
Owner Team
·  As teams in Microsoft Dynamics CRM with security roles
·  Can own records
·  Privileges are granted by security roles and change dynamically as the role definition changes
·  Needs to be manually or programmatically created and managed
·  Will be cached in CRM Server when a user accesses the application

Access Teams
·  Can't be granted security roles
·  Can't own records
·  Accesses records through sharing
·  Sharing privileges are defined by an access team template but don't change dynamically for existing records if the template changes
·  Won't be displayed in most team views
·  Can be system managed, directly from the form of the record that it relates to
·   Won't be cached because it doesn't derive privilege or ownership checks

The advantage of splitting out these type of teams from owner-based teams is that the overhead of adding security roles to a team can be avoided where it is not required. When security roles are added, these can affect performance and scalability in some key ways:
 
· Team security roles act in a cumulative way, and as a result for each user who is a team member, the privileges for that user need to take into account all the roles of the teams that they are a member of.
· The more teams a user is a member of with security roles, the more complex the calculation that has to be performed.
· To reduce the impact of doing this on each request, the system caches the cumulative permissions for the user as they first connect to CRM.
· When a user has a large number of teams with security roles, this can cause a delay on initial connection after a restart or when the user’s record has been flushed from the cache after 20 minutes of inactivity.
· Whenever the user is added or removed from a team, or the team has its security roles changed, the cache for each user affected needs to be flushed and recalculated on the next connection.
· For rapidly changing teams or team memberships, this can introduce a significant performance and scalability impact to the system
· In these cases, access teams can avoid this impact for team memberships where this is not necessary, that is, where a combination of ownership and sharing is used, access teams can be used for the sharing cases, and avoiding the cache and calculation impact when they change.
 
Hope this helps.
 
--
Happy CRM'ing
Gopinath.

Access Aspx WebService method in Jquery Ajax

Hi,
 
Today, I got the requirement where I need to call a method which is in Aspx from JavaScript and do some operation. Somehow, I felt it is very simple requirement and someone must have done this before. I did some search and there are many sources for it. This post is the combination of many posts...
 
Created a Asp.net Web application.
Added a code within the method as shown below. Make sure you give [WebMethod].
[WebMethod]
public static string WebServiceCall(string Value)
{
    return "My name is: " + Value;
}
Used below the Jquery code to call the method which was written in .aspx.cs page.
Included.

<script src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
        function CallWebMethod() {
            $.ajax({
                type: "POST",
                url: "/Test.aspx/WebServiceCall",
                data: '{Value: "' + $("#<%=TextBox1.ClientID%>")[0].value + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });
        }

        function OnSuccess(response) {
            alert(response.d);
        }
</script>

Added a HTML button in .aspx page and called the Jquery function.
<body>
    <form id="form1" runat="server">
        <asp:Label ID="lblFirstName" runat="server" Text="Name"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <input id="btnClick" type="button" value="Click Me!" onclick="CallWebMethod();" />
    </form>
</body>
</html>
 
When I execute the code and click on the button I got the exception as "Authentication Failed."

 Fix for this : Goto -- App_Start -- RouteConfig and comment the below line as per the screen shot.

 Now the code should work properly.

Hope this helps.
--
Happy Coding
Gopinath.

Wednesday 10 June 2015

How to add zero's at the end of integer in C#

Hi,

I got the requirement to show .00 after the numbers like

Input
Output
2
2.00
2.2
2.20
2.22
2.22

We can achieve this in C# using single line of code.

double dblValue = 2.2;
string strValue = string.Format("{0:N2}", dblValue);

Hope this helps.

--
Happy Coding
Gopinath.

Create an Attachment in CRM using C#

Hi,

Here is the C# code for creating an attachment in CRM under an email.

  Entity attachment = new Entity("activitymimeattachment");
  attachment["subject"] = "My Subject";
  string fileName = "Sample.png";
  attachment["filename"] = fileName;
  byte[] byteArray= File.ReadAllBytes(@"CRM_Image.png");
  attachment["body"] = Convert.ToBase64String(byteArray);
  attachment["mimetype"] = "text/plain";
  attachment["attachmentnumber"] = 1;
  attachment["objectid"] = new EntityReference("email", new Guid("8236E256-D50E-E511-80DB-C4346BAC476C"));
  attachment["objecttypecode"] = "email";
  objService.Create(attachment);
 

Hope this Helps

--
Happy CRM'ing
Gopinath