Wednesday, March 30, 2016

Two Default Views for an entity in MS CRM 2011

HI All,

Please find the below Solution to fix the two default view for an entity.

1. Create a solution by taking your Entity only.
2. Export the solution and unzip it
3. open the Customization.xml file in VS studio
4. then search for the View in saved queries node tag
5. change <isdefault> value from 1 to 0.
6. then zip the solution and import it, publish it and check. there will be one default public view

Monday, March 28, 2016

Validate date MSCRM Javascript

function ValidateDates() {
    var Date1 = Xrm.Page.getAttribute("scheduledstart").getValue();
    var Date2 = Xrm.Page.getAttribute("scheduledend").getValue();
    if (Date1 != null && Date2 != null) {
        if (Date1.setHours(0, 0, 0, 0) < Date2.setHours(0, 0, 0, 0)) {
            alert("You must specify an end time that happens after the start time");
        }
    }
}

Wednesday, March 16, 2016

Get All Plugin Registation Steps (SQL) MSCRM

Hi All,

Please find the below SQL script to get all the plugin registration steps

SELECT T.PluginAssemblyIdName AS PluginName, S.name AS StepName,
S.description AS StepDescription, M.name AS Action, E.name AS Entity,
CASE S.Stage WHEN 20 THEN 'PRE' WHEN 40 THEN 'POST' ELSE 'OTHER' END AS Stage,
CASE S.StateCode WHEN 0 THEN 'Enabled' WHEN 1 THEN 'Disabled' ELSE 'Other' END AS State
FROM SdkMessageProcessingStepBase S -- Steps Table
JOIN SdkMessage M ON(S.SdkMessageId = M.SdkMessageId)
JOIN SdkMessageFilter F ON(S.SdkMessageFilterId = F.SdkMessageFilterId)
JOIN EntityAsIfPublishedLogicalView E ON(E.ObjectTypeCode = F.PrimaryObjectTypeCode)
JOIN PluginType T ON(T.PluginTypeId = S.PluginTypeId)



Tuesday, March 15, 2016

Get Business Unit Id For the User CRM Javascript

Hi All,

JavaScript  to get Business Unit ID For the User

var businessUnitId = GetBusinessUnitIDFortheUser (loggedInUser);

function GetBusinessUnitIDFortheUser(userId) {
    try {
        if (serverUrl == null) {
            serverUrl = GetCRMServerUrl();
        }

        var oDataEndpointUrl = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/";
        oDataEndpointUrl += "SystemUserSet?$select=BusinessUnitId&$filter=SystemUserId eq guid'" + userId + "'";
        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 == 1) {
                var userRecord = requestResults.results[0];
                if (userRecord.BusinessUnitId && userRecord.BusinessUnitId.Id) {
                    return userRecord.BusinessUnitId.Id;
                }
            }
        }

        return "";
    }
    catch (err) {
        return "";
    }
}


Get View ID Based on View Name MSCRM 2013 & CRM 2015

Hi All,

Get View ID Based on Name


GetViewIdByName("ViewName");

function GetViewIdByName(viewName) {
    var viewId = "";
    var fetchXml =
       "<fetch mapping='logical'>" +
          "<entity name='savedquery'>" +
          "<attribute name='savedqueryid' />" +
          "<filter>" +
          "<condition attribute='name' operator='eq' value='" + viewName + "' />" +
          "</filter>" +
          "</entity>" +
       "</fetch>";

    var retrievedViews = XrmServiceToolkit.Soap.Fetch(fetchXml);
    viewId = retrievedViews[0].attributes['savedqueryid'].value;
    return viewId;
}

Display View based on Roles in Javascript MSCRM CRM 2011

Hi All,

Display the View based on the role and View

if (document.getElementById('crmGrid') && document.getElementById('crmGrid').GetParameter('viewid')) {
            var currViewId = document.getElementById('crmGrid').GetParameter('viewid');

            if (currViewId) {
                var viewName = getTheViewName(currViewId);

                if (viewName) {
                    if (viewName.toLowerCase() == "Customer Name") {
                        return true;
                    }
Else
{
return false;
}
                }
            }
        }

function getTheViewName()
{
//get the View Name based on Role

}

Bing Map for Account Entity MSCRM

Hi All,

Create a Bing Map based on Latitude and Longitude for MSCRM

var infoboxLayer = new Microsoft.Maps.EntityCollection();
var pinLayer = new Microsoft.Maps.EntityCollection();
function GetMap() {
            var BingMapKey = GetBingMapKey();
            map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {
                credentials:”hdyudyidididididiididdlklklkaksdf”, zoom: 5, center: new Microsoft.Maps.Location(51.5464828, 0.1293497), labelOverlay: Microsoft.Maps.LabelOverlay.hidden
            });
Loopprospect = GetProspectRecords();
Loadmap();
}
Function GetProspectRecords()
{
// Your Account Fetch XML Code Here
}
Function Loadmap(){
//add pushpins
                    pinInfobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0, 0), { visible: false, offset: new Microsoft.Maps.Point(0, 20) });
                    infoboxLayer.push(pinInfobox);
                    var location = new Microsoft.Maps.Location(Loopprospect[i].attributes.latitude.value, Loopprospect[i].attributes.longitude.value);
                    var pushpinOptions = { icon: serverUrl + '/WebResources/new_RedPushpin' };
                    var pin = new Microsoft.Maps.Pushpin(location, pushpinOptions);
                    pin.Title = Loopprospect[i].attributes.name.value;
                    var getUrlforopenCustomer = serverUrl + "/main.aspx?etc=1&id=" + Loopprospect[i].attributes.accountid.value + "&pagetype=entityrecord";
                    var getSegment = "";
                    var getOpenRevenue = "";
                    if (Loopprospect[i].attributes.new_segment != undefined) {
                        getSegment = Loopprospect[i].attributes.new_segment.formattedValue;
                    }
                    //Check open Revenue
                    if (Loopprospect[i].attributes.openrevenue != undefined) {
                        getOpenRevenue = Loopprospect[i].attributes.openrevenue.value;
                    }
                    pin.Description = "Segment :" + getSegment + "<br/>" + "Open Revenue :" + getOpenRevenue + "<br/>" + "<a target='_blank' href='" + getUrlforopenCustomer + "'>Click to Open Customer</a>";
                    pinLayer.push(pin); //add pushpin to pinLayer
                    Microsoft.Maps.Events.addHandler(pin, 'mouseover', displayInfobox);
                }

                map.entities.push(pinLayer);
                map.entities.push(infoboxLayer);
}
function displayInfobox(e) {
            if (e.targetType == 'pushpin') {
                pinInfobox.setOptions({ title: e.target.Title, description: e.target.Description, visible: true });
                pinInfobox.setLocation(e.target.getLocation());
            }
        }

in the above code am using a Bing map to get Values from Account Entity(Latitude and longitude) and displaying the Value from account Entity.

Get Entity Type code in MSCRM C#

Hi All,

Please find the below script to get Entity Type code in c#

Int getvalue = GetEntityTypeCode(“account”);

private static int GetEntityTypeCode(string EntityName)
{
      RetrieveEntityRequest request = new RetrieveEntityRequest();
      request.LogicalName = EntityName;
      RetrieveEntityResponse response = (RetrieveEntityResponse)crmService.Execute(request);
      int objecttypecode = response.EntityMetadata.ObjectTypeCode.Value;
      return objecttypecode;
}

Get Object Type Code Based on Entity Name in Javascript

Hi All,

Please find the Javascript to get Account Type Code.

function onload() {
    var getAccountCode = getobjecttypecode("account");
    alert(getAccountCode);
}

function getobjecttypecode(entityName) {
    try {
        var lookupService = new RemoteCommand("LookupService", "RetrieveTypeCode");
        lookupService.SetParameter("entityName", entityName);
        var result = lookupService.Execute();

        if (result.Success && typeof result.ReturnValue == "number") {
            return result.ReturnValue;
        }
        else {
            return null;
        }
    }
    catch (ex) {
        throw ex;
    }

}

Debug JS in Browsers

Hi All,

Debug JS Using Browsers

è Open JS Script write debugger in onload Function.
è Publish the JS
è Then open IE and press F12 and refresh the IE.
è Then you can able to see the debugger hit.


(Eg)
function onload() {
debugger;
    // Your code here
}

Monday, March 14, 2016

Retrieve OptionSet Text in CRM 2011 using C# in Plugin

Retrieve Normal(Local) Option Set Text

// Get Normal option set Text
string optionsetText = entity.FormattedValues["new_optionset"];

 or

string optionsetText = entity.GetFormattedAttributeValue("new_optionset"); 

Retrieve Global Option Set Text 

// Retrieves Global Option set Selected Text
        // Parameters: 1. Entity Name   2. Service  3. Global Option Set Name   4. optionset selected value
        public string GetOptionsetText(Entity entity, IOrganizationService service,string  optionsetName,int optionsetValue)
        {
            string optionsetSelectedText = string.Empty;
            try
            {


                RetrieveOptionSetRequest retrieveOptionSetRequest =
                    new RetrieveOptionSetRequest
                    {
                        Name = optionsetName
                    };

                // Execute the request.
                RetrieveOptionSetResponse retrieveOptionSetResponse =
                    (RetrieveOptionSetResponse)service.Execute(retrieveOptionSetRequest);

                // Access the retrieved OptionSetMetadata.
                OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                // Get the current options list for the retrieved attribute.
                OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();
                foreach (OptionMetadata optionMetadata in optionList)
                {
                    if (optionMetadata.Value == optionsetValue)
                    {
                        optionsetSelectedText = optionMetadata.Label.UserLocalizedLabel.Label.ToString();
                         break;
                    }
                }
            }
            catch (Exception)
            {                throw;
            }
            return optionsetSelectedText;
        }

Day 11 - Customizing Option Sets Dropdown Fields with JavaScript

  In this Blog, we will see how to Customizing Option Sets Dropdown Fields with JavaScript label1 = formContext.getAttribute( "bosch_op...