Translate

Friday, 9 August 2013

Get current user role and name in rollup 14

  How to get "Current User Role and Role Name" in CRM for roll-up 14. 

     Hello CRM lovers, Here is my blog for  getting logged user Role and Role name for Roll-Up 12, Roll-Up 13, Roll-Up 14 and also in cross browser support. I will really help you. For achieving this you have to fallow these steps.

 

Step 1:-  First of all you have to add reference of J Query main file minimum version jquery1.4.1.min or higher version. you can download it from http://jquery.com/.

Step 2:-  Now you have to add reference of "json2" on your crm entity form, You can get it from sdk, you will find it in your sdk folder.

Step 3:-  Now add the fallowing code in your web resource. 



//******************************************************************************************
//*******Retrive Multiple recored on the basis of the criteria OData Rest Method************
//******************************************************************************************
function retrieveMultiple(odataSetName, filter, successCallback, errorCallback, _executionObj) {
    _executionObjMultiretrive = _executionObj;
    var context = Xrm.Page.context;
    var serverUrl = context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    //odataSetName is required, i.e. "AccountSet"  
    if (!odataSetName) {
        alert("odataSetName is required.");
        return;
    }
    //Build the URI 
    var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName;
    //If a filter is supplied, append it to the OData URI
    if (filter) {
        odataUri += filter;
    }
    //Asynchronous AJAX function to Retrieve CRM records using OData
    $.ajax({
        type: "GET",
        async: false,
        contentType: "application/json; charset=utf-8",
        datatype: "json", url: odataUri,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (successCallback) {
                if (data && data.d && data.d.results) {
                    successCallback(data.d.results, textStatus, XmlHttpRequest);
                }
                else if (data && data.d) {
                    successCallback(data.d, textStatus, XmlHttpRequest);
                }
                else {
                    successCallback(data, textStatus, XmlHttpRequest);
                }
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback)
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            else
                errorHandler(XmlHttpRequest, textStatus, errorThrown);
        }
    });
}
function errorHandler(xmlHttpRequest, textStatus, errorThrow) {
    alert("Error : " + textStatus + ": " + xmlHttpRequest.statusText);
}


Step 4 :-  Now add the fallowing three functions in your web resource, In third function you will get current logged user role name.

//**********************************************************************************
//***************** Function For getting the Current User Role********************
//**********************************************************************************
    function getOwnerRole(UserID) {
        var _Userid = UserID;
        if (_Userid != null) {
            var istrue = retrieveMultiple("SystemUserRolesSet", "?$filter=SystemUserId eq (guid'" + _Userid + "')", RetrieveDataFromSystemUser, null, null);
        }
    }

    function RetrieveDataFromSystemUser(data, textStatus, XmlHttpRequest) {
        //debugger;
        var executioncontext = _executionObjMultiretrive;
        var len = data.length;
        if (len > 0) {
            for (i = 0; i < len; i++) {
                if (data[i].RoleId != null) {

 //****************************************************************
//*** This is the first role user have
//*** User may have many roles so you can get all here during loop                    //******************************************************************************
      var userRoleId=data[0].RoleId;

      retrieveMultiple("RoleSet", "?$filter=RoleId eq (guid'" + data[i].RoleId + "')",         RetrieveRoleName, null, null);
                }
            }
        }
    }

    function RetrieveRoleName(data, textStatus, XmlHttpRequest) {
        //debugger;
        var executioncontext = _executionObjMultiretrive;
        var len = data.length;

        if (data[0].Name != null) {

              var userRoleName=data[0].Name;          
        }
    }           



So by fallowing all upper steps you can get current logged user Role Id and Role Name. It will work in cross browser and in all new Roll-Up 12,Roll-Up 13 and Roll-Up 14. 

Enjoy the great technology Dynamics CRM. Good luck.....!!!!! 
Thanks.

Tuesday, 23 July 2013

How to get CRM entity attribute value in HTML web resource

  Today i got the requirement of getting CRM entity attribute value in the html web resource which was attached with the crm entity or called on clicking on a navigation link or from a ribbon button.

    You can get parent window object and then you can get object of crmForm then you will get all attribute of entity as well as their values.

For CRM 2011 

var attrVal = window.parent.document.crmForm.<Attribute Name>.value;


For CRM 2013

var attrVal = window.parent.document.Xrm.Page.getAttribute("<Attribute Name>").getValue();


Step 1:- Add a HTML web resource which you want to use.

Step 2:- Add a java script function with the fallowing code in the head section of the HTML web resource.

 <script type="text/javascript" src="ClientGlobalContext.js.aspx"></script>
               <script type="text/javascript">
                   function ABC() {
                       debugger;
                       var form = document.forms[0];
                       var context = GetGlobalContext();
                       var attrVal = window.parent.document.crmForm.<Attribute Name>.value;   
                       // Your code for your functionality                                                                                            }
 </script>
<meta charset="utf-8">
Step 3:- Call java script function on body on load.

<body onload="ABC()">
  
   <form method="post" action="">
    //******************************************
    //********* your HTML **********************
    //******************************************
   </form>

</body>
Your final HTML web resource will look like.
 
<html>
     <head>
          <title> </title>
               <script type="text/javascript" src="ClientGlobalContext.js.aspx"></script>
               <script type="text/javascript">
                   function ABC() {
                       debugger;
                       var form = document.forms[0];
                       var context = GetGlobalContext();
                       var attrVal = window.parent.document.crmForm.<Attribute Name>.value;
                          //******************************************                                  //********* your Custom Code **********************
              //******************************************
                           }
       </script>
<meta charset="utf-8"> 
  <body onload="ABC()">  
   <form method="post" action="">
    //******************************************
    //********* your HTML **********************
    //******************************************
    </form>
  </body>   
</html>

Enjoy the great technology Dynamics CRM. Good luck.....!!!!! 

Thursday, 13 June 2013

Current fiscal year in crm 2011

How to get current fiscal year in CRM 2011.  


   Here is my new update. In this update of mine you can know how to get current fiscal year in CRM on the basis of CRM fiscal year settings.

   Normally fiscal year starts on 1 April to 31 March, but CRM 2011 provides the feature to set our custom fiscal period because fiscal period may differ organization to organization, so there may be need of custom fiscal period, and if custom fiscal period exist then i am sure there will need of current fiscal year. Unfortunately CRM does not stores current fiscal year, so you have to calculate current fiscal year.So in this blog you can get current fiscal year.

Fallow these steps.

Step 1:-  Click on Settings tab.





Step 2:-  Open fiscal year year setting.


Step 3:-  Set the start date and other setting regarding fiscal year.


Step 4:-  Now write this java script code to get current fiscal year in any  variable, you can write this where you want to use current fiscal year.

function getCurrentFiscalYear() {

    //Get Current Date
    var today = new Date();
    var todayDate = today.getMonth() + 1 + "/" + today.getDate() + "/" + today.getFullYear();

    //For rollup 11
    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>organization</q1:EntityName>" +
            "<q1:ColumnSet xsi:type='q1:ColumnSet'>" +
                "<q1:Attributes>" +
                    "<q1:Attribute>fiscalcalendarstart</q1:Attribute>" +

                "</q1:Attributes>" +
            "</q1:ColumnSet>" +
        "<q1:Distinct>false</q1:Distinct>" +

        "</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 result = xmlHttpRequest.responseXML.xml;

    var doc = new ActiveXObject("MSXML2.DOMDocument");
    doc.async = false;
    doc.loadXML(result);

    if (doc.selectSingleNode("//q1:fiscalcalendarstart") != null) {

        var startDate = doc.selectSingleNode("//q1:fiscalcalendarstart").attributes[0].nodeTypedValue

        //Organisation Fiscal start date
        var sDate = new Date(startDate);

        var currentDate = new Date(todayDate);

        if (startDate <= todayDate) {

            var diff = currentDate.getFullYear() - sDate.getFullYear();

            var CurrentFiscalYear = (parseInt(sDate.getFullYear()) + parseInt(diff));

            // alert(CurrentFiscalYear);


        }
        else {

            var diff = sDate.getFullYear() - currentDate.getFullYear();

            if (parseInt(diff) == 0) {

                var CurrentFiscalYear = (parseInt(sDate.getFullYear()) - parseInt(1));
                //alert(CurrentFiscalYear);

            }
            else {
                var CurrentFiscalYear = (parseInt(sDate.getFullYear()) - parseInt(diff));
                //alert(CurrentFiscalYear);
            }
        }
    }
}


Enjoy the great technology Dynamics CRM. Good luck.....!!!!! 

Monday, 10 June 2013

How to Convert Option Set in to a Check Box list ?

How to Convert Option Set in to a Check Box list with java script.

Here is my new update, in this blog you can find the process and code to convert option set into a check box list. And one important thing is that it will work on CRM roll-up 11, CRM roll-up 12 and CRM roll-up 13. So just enjoy the great technology like CRM.

Step 1:- First Create option set which you want to convert into Checkbox list.
Step 2:- Create another attribute to store value of option set.
Step 3:- Add both the fields on the entity form.
Step 4:- Create new web resource or update existing web resource with the fallowing code.  

    function Form_onload() {

    var _crtlSociaklNW = document.getElementById("new_socialnetwork");
    var _crtlTextSocial = document.getElementById("new_textsocial");

    if (_crtlSociaklNW != null && _crtlTextSocial != null) {

        _crtlSociaklNW.style.display = "none";
        var pdiv = document.createElement('div');
        pdiv.style = 'overflow-y:auto; height:100px; border:1px #6699cc solid;          background-color:#ffffff;';
        _crtlSociaklNW.parentNode.appendChild(pdiv);
        ///////////////////////////////////////////////////////////////////////////
///////////////////// Convert option set to check box//////////////////////
///////////////////////////////////////////////////////////////////////////
        for (var i = 1; i < _crtlSociaklNW.options.length; i++) {
            var OptionSetItems = _crtlSociaklNW.options[i];
            if (!IsChecked(OptionSetItems.text, _crtlTextSocial)) {
                var addInput = document.createElement('input');
                addInput.type = 'checkbox';
                addInput.style.pixelWidth = 30;
            }
            else {
                var addInput = document.createElement('input');
                addInput.type = 'checkbox';
                addInput.checked = true;
                addInput.style.pixelWidth = 30;
            }

            var addLabel = document.createElement('label');
            addLabel.innerText = OptionSetItems.text;
            var addBr = document.createElement('br');
            var formname = Xrm.Page.getAttribute("new_name").getValue();

            _crtlSociaklNW.nextSibling.appendChild(addInput);
            _crtlSociaklNW.nextSibling.appendChild(addLabel);
            _crtlSociaklNW.nextSibling.appendChild(addBr);

        }
    }
}
///////////////////////////////////////////////////////////////////////////
///////////////// To check if which check box is selected//////////////////
///////////////////////////////////////////////////////////////////////////
function IsChecked(pText, _crtlTextSocial) {
    if (_crtlTextSocial.value != "") {
        var _crtlTextSocial = _crtlTextSocial.value.split(",");
        for (var i = 0; i < _crtlTextSocial.length; i++) {
            if (_crtlTextSocial[i] == pText)
                return true;
        }
    }
    return false;
}
///////////////////////////////////////////////////////////////////////////
///function to save the selected Items from check box list to TextSocial///
///////////////////////////////////////////////////////////////////////////
function Form_onSave() {
  
    var _crtlSociaklNW = document.getElementById("new_socialnetwork");
  
    var txtSocialValue = "";
    var getInput = _crtlSociaklNW.nextSibling.getElementsByTagName("input");

    for (var i = 0; i < getInput.length; i++) {
        if (getInput[i].checked) {
            txtSocialValue += getInput[i].nextSibling.innerText + ",";
        }
    }
    Xrm.Page.getAttribute("new_textsocial").setValue(txtSocialValue);

}

Step 5:- Now call Form_onload() function on Form OnLoad event and Form_onSave() function on             form OnSave event. And then save and publish form.
            Now your form will look like this.
Step 6:- Select check boxes and then save then it will look like this.
Step 7:- Now Hide TextSocial on the entity form.
Step 8:- Now it will look like.
 Soon i will write my new post "How to hide these check boxes on the basis of condition"

Enjoy the great technology Dynamics CRM. Good luck.....!!!!! 

Thursday, 6 June 2013

How to filter view on dashboard with html web resource.

CRM-2011 How to filter view on dashboard ?

CRM-2011 How to filter view without date time attribute ?    

CRM-2011 How to filter view with HTML web resource ?   

CRM-2011 How to update fetch of a view ?   

CRM-2011 How to filter view on dashboard with HTML web resource ? 


Here you can get the answer of above questions regarding CRM 2011.


If you want to filter a view on the dashboard with date time and you do not have date time attribute and option set of for month and year in your entity then don’t worry you are on right place. I will provide you code and steps by which you can filter view with date time without having date time field in entity related to view. 

Step 1: First of all add a HTML web resource in your crm solution. And write the fallowing code in the                 web resource.


<html>
     <head>
          <title> </title>
               <script type="text/javascript" src="ClientGlobalContext.js.aspx"></script>
               <script type="text/javascript">
                       function submitForm() {
                            var form = document.forms[0];
                            var context = GetGlobalContext();
                            form.action = context.getServerUrl() + '/AdvancedFind/fetchData.aspx';                           
                            form.LayoutXml.value = '<grid name="resultset" object="10172" jump="atr_name" select="1" icon="1" preview="1"></grid>';
                            form.FetchXml.value = "<fetch version='1.0' mapping='logical'><entity name='Entity Schema Name'><attribute name='atr_xyz' /><attribute name='atr_name' /><attribute name='createdon' /><order attribute='atr_name' descending='false' /><filter type='and'><condition  attribute='atr_year' operator='eq' value='" + new Date().getFullYear() + "' /><condition attribute='atr_systemuserid' operator='eq-userid' /></filter></entity></fetch>";
                            form.submit();
                         }
                </script>
           <meta charset="utf-8">
      </head>
    <body onload="submitForm()">
        <form method="post" action="">
           <input name="FetchXml" type="hidden">
           <input name="LayoutXml" type="hidden">
           <input name="EntityName" value="entity svhema name" type="hidden">
           <input name="DefaultAdvFindViewId" value="32 Bit View Id" type="hidden">
           <input name="ViewId" value="00000000-0000-0000-00AA-000010001004" type="hidden">
           <input name="ViewType" value="10172" type="hidden">
           <input name="SortCol" value="atr_name" type="hidden" ;="">
           <input name="UIProvider" type="hidden">
           <input name="DataProvider" type="hidden">
       </form>
    </body>
</html>

Step 2: Create or Open dashboard to add web resource on dashboard.



Step 3:  Open dashboard and click on the web resource button to select the 
            web resource button you added in step 1.




Step 4:  Select web resource in web resource look up which you created in
            step 1 and then save and publish



Enjoy the great technology Dynamics CRM. Good luck.....!!!!! 

Tuesday, 28 May 2013

CRM Java Scripts for RollUp 12 Changes

  How to get "Object Type Code"in CRM for roll-up 12, How to disable view picker in crm 2011,how to disable New button in lookup dialog, how to call workflow with java script, how to attach event in rollup 12,All java scripts for rollup 12. 

1.Java Script for getting "object type code" of a crm entity :-

For Rollup 11,

var EntityTypeCode = crmForm.ObjectTypeCode;


For Rollup 12,13 for cross browser support.

var EntityTypeCode = Xrm.Page.context.getQueryStringParameters().etc;

2.Java Script for disabling filter lookup view selector :-


For Rollup 11,

document.getElementById(“Lookup Id").disableViewPicker = 1;

For Rollup 12,13 for cross browser support.

document.getElementById("Lookup Id")._behaviors[0].AddParam("DisableViewPicker", "1");
document.getElementById("Lookup Id ")._behaviors[0].set_showProperty(1);

3.Java Script for hiding New Button in filter lookup dialog :-

For Rollup 11,

crmForm.all.Lookup Id.AddParam("ShowNewButton", "0");

For Rollup 12,13 for cross browser support.

document.getElementById("Lookup Id")._behaviors[0].AddParam("ShowNewButton", "0");
document.getElementById("Lookup Id")._behaviors[0].set_showProperty(0);

4.Java Script for executing a workflow with java script :-

For Rollup 11,

var WorkflowId = "9533D5BB-A8FB-4D4C-A6E5-272F7C90EDC0";//Work flow guid to execute
var soapBody = "<soap:Body>" +
               "<Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
               "<Request xsi:type=\'ExecuteWorkflowRequest\'>" +
               "<EntityId>" + Entity Id + "</EntityId>" +
               "<WorkflowId>" + WorkflowId + "</WorkflowId>" +
               "</Request>" +
               "</Execute>" +
               "</soap:Body>";
var soapXml = "<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() +
                soapBody +
              "</soap:Envelope>";
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open("POST", "/MSCRMservices/2007/crmservice.asmx", false);
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");       
xmlhttp.send(soapXml);

For Rollup 12,13 and for cross browser support.

var WorkflowId = "9533D5BB-A8FB-4D4C-A6E5-272F7C90EDC0";//Work flow guid to execute
var soapBody = "<soap:Body>" +
               "<Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
               "<Request xsi:type=\'ExecuteWorkflowRequest\'>" +
               "<EntityId>" + Entity Id + "</EntityId>" +
               "<WorkflowId>" + WorkflowId + "</WorkflowId>" +
               "</Request>" +
               "</Execute>" +
               "</soap:Body>";
var soapXml = "<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() +
               soapBody +
              "</soap:Envelope>";
var xmlHttpRequest;
var doc;
var result;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome
xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", "/mscrmservices/2007/CrmService.asmx", false);        xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", soapXml.length);
xmlHttpRequest.send(soapXml);

5.Java Script for attach click event :-


For Rollup 11,

//Function Definition
FunctionName(Function parameters)
{
  // write your code
}
var elment = document.getElementById(“grid id”);
var func = "var efunction=function() { " +
              "FunctionName(Function parameters);" +
              " };";
eval(func);
//Attach to click event
elment.attachEvent("onclick", ef, false);

For Rollup 12,13 and for cross browser support.
FunctionName(Function parameters)
{
  // write your code
}
var elment = document.getElementById(“grid id”);
var func = "var efunction=function() { " +
              "FunctionName(Function parameters);" +
              " };";
eval(func);

if (elment!=null)
  {
           if(elment.attachEvent!=null)
            {
               elment.attachEvent("onclick", efunction, false);
            }
          else {
                var grid = Xrm.Page.getControl(grid id)._control.get_innerControl();
                grid._events.addHandler('OnClick', ef);                
                grid.onclick = efunction;
            }
  }
 

and it will work in IE7+, Mozila and in Crome properly

Enjoy the great technology Dynamics CRM. Good luck.....!!!!!