PlugIn which Supports All DataTypes To Retrieve In MS CRM 2011

PlugIn which Supports All DataTypes To Retrieve In MS CRM 2011

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Query;

using Microsoft.Xrm.Sdk.Messages;

using Microsoft.Xrm.Sdk.Metadata;

using System.Web.Services.Protocols;

namespace Test_AllTypes

{

public class AllTypes : IPlugin

{

Guid AllTypesID;

Guid OwnerID;

Guid LookupID;

string Name = string.Empty;

string Text = string.Empty;

string Picklist = string.Empty;

Boolean Chk;

string option = string.Empty;

int Number;

Double FloatNumber;

Decimal DecimalNumber;

string Description = string.Empty;

Money Currency;

DateTime Date;

public void Execute(IServiceProvider serviceProvider)

{

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

if (context.InputParameters.Contains(“Target”) && context.InputParameters[“Target”] is Entity)

{

Entity entity = (Entity)context.InputParameters[“Target”];

if (entity.LogicalName == “new_alltypes”)

{

IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

IOrganizationService service = factory.CreateOrganizationService(context.UserId);

AllTypesID = new Guid(entity.Attributes[“new_alltypesid”].ToString());

if (entity.Attributes.Contains(“ownerid”))

{

EntityReference OwnerId = (EntityReference)entity.Attributes[“ownerid”];

OwnerID = ((Microsoft.Xrm.Sdk.EntityReference)(entity.Attributes[“ownerid”])).Id;

}

if (entity.Attributes.Contains(“new_acclookup”))

{

EntityReference TaxType = (EntityReference)entity.Attributes[“new_acclookup”];

LookupID = ((Microsoft.Xrm.Sdk.EntityReference)(entity.Attributes[“new_acclookup”])).Id;

}

QueryExpression query = new QueryExpression

{

EntityName = “new_alltypes”,

ColumnSet = new ColumnSet(“new_name”, “ownerid”, “new_text”, “new_currency”, “new_acclookup”, “new_description”, “new_number”, “new_flotingnumber”, “new_decimalnumber”, “new_date”, “new_picklist”, “new_options”),

Criteria =

{

FilterOperator = LogicalOperator.And,

Conditions =

{

//The ObjectTypeCode must be specified, or else the query

//defaults to “email” instead of “template”.

new ConditionExpression

{

AttributeName = “new_alltypesid”,

Operator = ConditionOperator.Equal,

Values = {AllTypesID.ToString()}

}

}

}

};

foreach (Entity Demo in service.RetrieveMultiple(query).Entities)

{

Name = Demo.Attributes[“new_name”].ToString();

if (Demo.Attributes.Contains(“ownerid”))

{

OwnerID = ((Microsoft.Xrm.Sdk.EntityReference)(Demo.Attributes[“ownerid”])).Id;

}

Text = Demo.Attributes[“new_text”].ToString();

Picklist = ((Microsoft.Xrm.Sdk.OptionSetValue)(Demo.Attributes[“new_picklist”])).Value.ToString();

Chk = Convert.ToBoolean(Demo.Attributes[“new_options”]);

Number = Convert.ToInt32(Demo.Attributes[“new_number”]);

FloatNumber = Convert.ToDouble(Demo.Attributes[“new_flotingnumber”]);

DecimalNumber = Convert.ToDecimal(Demo.Attributes[“new_decimalnumber”]);

Currency = new Microsoft.Xrm.Sdk.Money(((Microsoft.Xrm.Sdk.Money)(Demo.Attributes[“new_currency”])).Value);

Date = Convert.ToDateTime(Demo.Attributes[“new_date”]);

Description = Demo.Attributes[“new_description”].ToString();

if (Demo.Attributes.Contains(“new_acclookup”))

{

LookupID = ((Microsoft.Xrm.Sdk.EntityReference)(Demo.Attributes[“new_acclookup”])).Id;

}

}

Entity AllTypes = new Entity(“new_alltypes”);

AllTypes.Attributes.Add(“new_name”, “Dup” + Name);

AllTypes.Attributes.Add(“ownerid”, new EntityReference(“systemuser”, OwnerID));

AllTypes.Attributes.Add(“new_text”, Text);

OptionSetValue option = new OptionSetValue(Convert.ToInt32(Picklist));

AllTypes.Attributes.Add(“new_picklist”, option);

AllTypes.Attributes.Add(“new_options”, Chk);

AllTypes.Attributes.Add(“new_number”, “” + Number);

AllTypes.Attributes.Add(“new_flotingnumber”, FloatNumber);

AllTypes.Attributes.Add(“new_decimalnumber”, DecimalNumber);

AllTypes.Attributes.Add(“new_currency”, Currency);

AllTypes.Attributes.Add(“new_date”, Date);

AllTypes.Attributes.Add(“new_description”, Description);

AllTypes.Attributes.Add(“new_acclookup”, new EntityReference(“account”, LookupID));

service.Create(AllTypes);

}

}

}

Advertisements

Passing parameters to JavaScript Web Resource function in CRM 2011.

Passing parameters to JavaScript Web Resource function in CRM 2011

If you want to use Generic Code in Javascript which will be Reusable in diff web resources pass the attribute value as Parameter in Event Source as mentioned below.

 In the calling Function need to Mention the” ExecutionContext” along with the parameter.

If you are not mention then it reads the parameters as “OBJECT”

 Note: If you want to pass more than one value then separate the attribute values with Semicolons

 Sample Javascript Web Resource for Account entity to get value of Account Name:

On load Code:

 

function test(ExecutionContext,Name){

 var name = Xrm.Page.data.entity.attributes.get(Name).getValue();

 // Or you can fetch the value using the following Way

var valuFromContext = ExecutionContext.getEventSource().controls.get(Name).getAttribute().getValue();

 }

 In Onload Function call , follow the below image.

 Cheers,

Happy Coding

Sequence Number/Auto Number for Custom Entity In MS CRM 2011

Generate Sequence Number/Auto Number for Custom Entity In MS CRM 2011

Create a Custom Entity:

Physical Name: Auto Number , Logical Name: new_autonumber

Create the folloing Attributes:

PhysicalName : EntityLogName,       Logical Name : new_EntityLogName DType :SingleLine

PhysicalName:StartNumber,                         Logical Name : new_ StartNumber        DType :INT

PhysicalName:LastAllocatedNumber,  Logical Name : new_LastAllocatedNumber DType :INT

PhysicalName:Prefix,                                    Logical Name : new_Prefix,     DType :Single Line

PhysicalName:Suffix,                                    Logical Name : new_Suffix      DType :Single Line

PhysicalName:Seperator,                             Logical Name : new_Seperator   DType :Single Line

PhysicalName:Attribute,          Logical Name : new_Attribute   DType :Single Line

Use the Below Plugin Code to Generate Sequence Number/Auto Number:

Write a plugin with this code and register on , for which entity you need Seq Number.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.Serialization;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Client;

using Microsoft.Xrm.Sdk.Query;

namespace SequenceNumber

{

publicclassSequenceNumber : IPlugin

{

publicvoid Execute(IServiceProvider serviceProvider)

{

IPluginExecutionContext context = (IPluginExecutionContext)                   serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

if (context.Depth == 1 && context.InputParameters.Contains(“Target”) && context.InputParameters[“Target”] isEntity)

{

Entity entity = (Entity)context.InputParameters[“Target”];

if (entity.LogicalName == “new_request”)

{

QueryExpression expression = newQueryExpression(“new_autonumber”);

expression.ColumnSet.AllColumns =true;

expression.Criteria.AddCondition(“new_name”, ConditionOperator.Equal,entity.LogicalName);

EntityCollection coll = service.RetrieveMultiple(expression);

foreach (Entity auto in coll.Entities)

{

if (coll != null && coll.Entities.Count > 0)

{

int startNumber = 0;

int number;

string prefix = string.Empty; ;

string suffix = string.Empty;

string seperator=string.Empty;

string attribute = string.Empty;

int lastAllocated;

string seqNumber=string.Empty;

string requestType = string.Empty;

int requestTypeValue;

DateTime today = DateTime.Now;

if (auto.Attributes.Contains(“new_startnumber”))

{

startNumber = (int)auto.Attributes[“new_startnumber”];

}

if (auto.Attributes.Contains(“new_lastallocatednumber”))

{

number = (int)auto.Attributes[“new_lastallocatednumber”];

lastAllocated = number;

lastAllocated++;

}

else

{

number = startNumber;

lastAllocated = number;

}

if (auto.Attributes.Contains(“new_prefix”))

{

prefix = auto.Attributes[“new_prefix”].ToString();

}

if (auto.Attributes.Contains(“new_suffix”))

{

suffix = auto.Attributes[“new_suffix”].ToString();

}

if (auto.Attributes.Contains(“new_seperator”))

{

seperator = auto.Attributes[“new_seperator”].ToString();

}

if (auto.Attributes.Contains(“new_startnumber”))

{

attribute = auto.Attributes[“new_attribute”].ToString();

}

if (attribute == “<FieldName From Autom Number Attribute Field>”)

{

seqNumber = prefix + seperator + lastAllocated.ToString();

entity.Attributes[attribute] = seqNumber;

}

if (attribute == “<FieldName From Autom Number Attribute Field>”)

{

seqNumber = prefix + seperator + lastAllocated.ToString() + seperator + suffix;

entity.Attributes[attribute] = seqNumber;

}

seqNumber = prefix + seperator + lastAllocated.ToString() + seperator + suffix;

auto.Attributes[“new_lastallocatednumber”] = lastAllocated;

service.Update(auto);

}

}

}

}

}

}

}

Happy Coding.

Retrieve The Values Using ODATA Restend Point Javascript in MS CRM 2011

function Onload() {

    var RecId = Xrm.Page.data.entity.getId();

    var userId = Xrm.Page.context.getUserId();

    var fieldname = Xrm.Page.getAttribute(<fieldname>);

    if (fieldname != null && !fieldname.getValue()) {

        var fwdFilter = “EntitySet?$select= <Retrieved field names>&$orderby=ModifiedOn desc&$filter=<Field Name>/Id eq guid'” + RecId + “‘ and <Field Name> eq false and

<Field Name>/Id eq guid'” + userId + “‘”;

        var fwdResult = ODataRetrieveMultiple(fwdFilter);

        if (fwdResult != null) {

            alert(“Not Yet Fieldnamenowledged this Request”);

            Xrm.Page.ui.close();

        }

    }

function ODataRetrieveMultiple(filter) {

    var serverUrl = Xrm.Page.context.getServerUrl();

    var oDataEndpointUrl = serverUrl + “/XRMServices/2011/OrganizationData.svc/”;

    oDataEndpointUrl += filter;

    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;

        }

    }

    returnnull;

}

 

function GetRequestObject() {

    if (window.XMLHttpRequest) {

        returnnew window.XMLHttpRequest;

    }

    else {

        try {

            returnnew ActiveXObject(“MSXML2.XMLHTTP.3.0”);

        }

        catch (ex) {

            returnnull;

        }

    }

}

Hope it will help you.

Cheers,

Show/Hide Tab or Section Based on Login User(Security Role)

Show Hide Tab or Section Based on Login User(Security Role)

Create WebResource And place the Below code then cal the function where you want to Need the Functionality

function ShowHideDispatchSection() {

    //Example Role: System Administrator

    if (UserHasRole(“Role”) || UserHasRole(“Role “)) {

        //  Tab Name or Guid of it

        Xrm.Page.ui.tabs.get(“1”).sections.get(“5”).setVisible(true);

}

else {

        Xrm.Page.ui.tabs.get(“1”).sections.get(“5”).setVisible(false);

    }

}

function UserHasRole(roleName) {

    var serverUrl = Xrm.Page.context.getServerUrl();

    var oDataEndpointUrl = serverUrl + “/XRMServices/2011/OrganizationData.svc/”;

    var org = Xrm.Page.context.getOrgUniqueName()

    var oDataEndpointUrl = “/” + org + “/XRMServices/2011/OrganizationData.svc/”;

    oDataEndpointUrl += “RoleSet?$top=1&$filter=Name eq ‘” + roleName + “‘”;

    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 role = requestResults.results[0];

            var id = role.RoleId;

            var currentUserRoles = Xrm.Page.context.getUserRoles();

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

                var userRole = currentUserRoles[i];

                if (GuidsAreEqual(userRole, id))

{
                    return true;
                }

           }

      }

    }

    return false;

}

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) {

    var isEqual = false;

    if (guid1 == null || guid2 == null) {

        isEqual = false;

    }

else {

        isEqual = guid1.replace(/[{}]/g, “”).toLowerCase() == guid2.replace(/[{}]/g, “”).toLowerCase();

}

    return isEqual;

}

 

Show MS CRM 2011 Optionset values in Dropdownlist in Asp.net

Sometime we have requirement to create MS CRM records through custom asp.net pages, and if we have optionset in that entity we might want to display optionset valeus in dropdownlist. So we can use below code to populate optionset values in dropdownlist.

public Dictionary<int, string> RetrieveOptionsetMetadata(IOrganizationService _iOgranizationService)

{

//Dictionary to store value and text

Dictionary<int,string> DropdownDatasource=newDictionary<int,string>();

//Create request to fetch optionset

RetrieveAttributeRequest _Request = new RetrieveAttributeRequest{

EntityLogicalName =“EntityName”,

LogicalName =“OptionsetFieldName”,

RetrieveAsIfPublished =true

};

// Execute the request

RetrieveAttributeResponse _Response =(RetrieveAttributeResponse)_iOgranizationService.Execute(_Request);

PicklistAttributeMetadata _PicklistAttributeMetadata = (PicklistAttributeMetadata)_Response.AttributeMetadata;

OptionMetadata[] optionList =_PicklistAttributeMetadata.OptionSet.Options.ToArray();

foreach (OptionMetadata _Optionset in optionList) {

_DropdownDatasource.Add(int.Parse(_Optionset.Value.ToString()), _Optionset.Label.UserLocalizedLabel.Label);

}

return _DropdownDatasource;

}

After that we can set datasource for dropdownlist like below

DropDownList1.DataSource = RetrieveOptionsetMetadata(_iOgranizationService);

DropDownList1.DataBind();

Hope Enjoyed Coding.

CRM 2011 Refresh Form after Subgrid Changes or Refresh

CRM 2011 Refresh Form after Subgrid Changes or Refresh

found on some articles that to be able to do this you need to attach an OnRefresh event to the element that then calls the function to load the parent window again:

var grid = document.getElementById(“MySubGrid”);

grid.attachEvent(“onrefresh”, ReLoadForm);
When I deployed to CRM 2011 Rollup 3, I found some issues that throw error like null object (document not ready) and in some IE versions the form keeps refreshing for eternity…

After spending some time investigating this annoying issue, I found out that we have to wait for the subgrid to finish loading its contents for this to work properly. The final javascript is as follows:

function Form_onload() {

setTimeout(“SubGridRefresh();”, 2500);

}

function SubGridRefresh() {

var grid = document.getElementById(“MySubGrid”);

if (grid) {

grid.attachEvent(“onrefresh”, ReLoadForm);

}

}

function ReLoadForm() {

window.location.reload(true);

}