Showing posts with label CRM 2011. Show all posts
Showing posts with label CRM 2011. Show all posts

Thursday, August 21, 2014

Check Entity and Attribute Exist in CRM or not?

   private bool DoesAttributeExist(string entityName,string attributeName, IOrganizationService service)
        {
            RetrieveEntityRequest request = new RetrieveEntityRequest
            {
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes,
                LogicalName = entityName
            };
            RetrieveEntityResponse response
              = (RetrieveEntityResponse)service.Execute(request);

            return response.EntityMetadata.Attributes.FirstOrDefault(element => element.LogicalName == attributeName && element.AttributeType.Value == AttributeTypeCode.DateTime) != null;
        }

        private bool DoesEntityExist(string entityName, IOrganizationService _service)
        {
            RetrieveAllEntitiesRequest allEntitiesRequest = new RetrieveAllEntitiesRequest();
            // Retrieve only the currently published changes, ignoring the changes that have
            // not been published.
            allEntitiesRequest.RetrieveAsIfPublished = false;
            //allEntitiesRequest.MetadataItems = MetadataItems.EntitiesOnly;

            // Execute the request
            RetrieveAllEntitiesResponse allEntitiesResponse = (RetrieveAllEntitiesResponse)_service.Execute(allEntitiesRequest);

            // Iterate through the retrieved entities
            foreach (EntityMetadata entity in allEntitiesResponse.EntityMetadata)
            {
                if (entity.LogicalName == entityName)
                    return true;
            }
            return false;
        }

Thursday, April 24, 2014

How to use ExecuteMultipleRequest with ServiceContext and Linq

The following code is retrieving all the contacts where parent customer id is C6CB814A-BA75-E011-8720-00155DA5304E and updating their phone number.
var ServiceContext = new OrganizationServiceContext(service);
Guid accountid = new Guid("C6CB814A-BA75-E011-8720-00155DA5304E");

// Create an ExecuteMultipleRequest object.
ExecuteMultipleRequest requestWithResults = new ExecuteMultipleRequest()
{
    // Assign settings that define execution behavior: continue on error, don't return responses. 
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        ReturnResponses = false
    }, 
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
};
               
requestWithResults.Requests.AddRange(from c in ServiceContext.CreateQuery("contact")
                                    where c["parentcustomerid"].Equals(accountid)
                                    select new UpdateRequest()
                                    {
                                        Target = new Entity("contact")
                                        {
                                            Id = c.Id,
                                            Attributes = { new KeyValuePair<string,object>("telephone1", "+61402234212") }
                                        }
                                    });

// Excute the requests
ExecuteMultipleResponse Response = (ExecuteMultipleResponse)service.Execute(requestWithResults);

Monday, May 27, 2013

Opening Forms using the Xrm.Utility.openEntityForm



Using the openEntityForm

Opening a New Form

To simply open a form for creating a new record you can use the following line of code. Simply replace account with the entity of your choice.

Xrm.Utility.openEntityForm("account");

Open a Form with an Existing Record

If you want to open a specific record you just add the guid for that record like this:

Xrm.Utility.openEntityForm("account","A85C0252-DF8B-E111-997C-00155D8A8410″);

Disable / Enable fields, sections, tabs and the whole Form in MS CRM 2011


When working with the MS CRM form , Your requirement will be to enable (set to read/write) or disable (set to read / only) selected fields, sections, tabs and the Whole form.

Please have a glance below code for these functionalities to work out.

1)     Enable / Disable a field

Xrm.Page.getControl(“fieldname”).setDisabled(false);

2)    Enable / Disable a Section

function sectiondisable (sectionname, disablestatus)

{

var ctrlName = Xrm.Page.ui.controls.get();

for(var i in ctrlName) {

var ctrl = ctrlName[i];

var ctrlSection = ctrl.getParent().getName();

if (ctrlSection == sectionname) {

ctrl.setDisabled(disablestatus);

}

}

}  // sectiondisable

3)    Enable / Disable a Tab

function tabdisable (tabname, disablestatus)
{
 var tab = Xrm.Page.ui.tabs.get(tabname);
 if (tab == null) alert("Error: The tab: " + tabname + " is not on the form");
 else {
     var tabsections =  tab.sections.get();
     for (var i in tabsections) {
         var secname = tabsections[i].getName();
         sectiondisable(secname, disablestatus);
     }
  }
}   // tabdisable


4)    Enable / Disable a Form

function formdisable(disablestatus)
{
    var allAttributes = Xrm.Page.data.entity.attributes.get();
    for (var i in allAttributes) {
           var myattribute = Xrm.Page.data.entity.attributes.get(allAttributes[i].getName());
           var myname = myattribute.getName();        
           Xrm.Page.getControl(myname).setDisabled(disablestatus);
    }
} // formdisable

5)     Enable / Disable All Controls in the TAB

function DisableAllControlsInTab(tabControlNo)
{
var tabControl = Xrm.Page.ui.tabs.get(tabControlNo);
    if (tabControl != null)
{  
      Xrm.Page.ui.controls.forEach
(
     function (control, index)
{        
if (control.getParent().getParent() == tabControl && control.getControlType() != "subgrid")
{              control.setDisabled(true);
        }    
});
      }
 }
function EnableAllControlsInTab(tabControlNo)
 {    
var tabControl = Xrm.Page.ui.tabs.get(tabControlNo);    
if (tabControl != null)
{      
 Xrm.Page.ui.controls.forEach
(    
function (control, index)
{        
if (control.getParent().getParent() == tabControl && control.getControlType() != "subgrid")
{            
control.setDisabled(false);
        }
    });
    }
 }
 Hope this will help.

Regards,

Friday, May 24, 2013

Get Required Attendee(Activity Party) value from Appointment.


Guid Id = new Guid("D77839B3-CBC2-E211-8DC3-B4B52F6714CA");
            XrmServiceContext _context = new XrmServiceContext(_service);
            Appointment appointment = _context.AppointmentSet.Where(p=>p.ActivityId==Id).SingleOrDefault();
            if (appointment != null)
            {
               
                EntityCollection receipt = new EntityCollection();
                receipt = appointment.GetAttributeValue<EntityCollection>("requiredattendees");
                for (int i = 0; i < receipt.Entities.Count; i++)
                {
                    ActivityParty ap = receipt[i].ToEntity<ActivityParty>();

                    string id,name;

                    if (ap.PartyId.LogicalName == "account")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                    if (ap.PartyId.LogicalName == "contact")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                    if (ap.PartyId.LogicalName == "systemuser")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                }
            }

Thursday, May 23, 2013

Find the day of the week.


 var startday = Xrm.Page.getAttribute("new_quotestart").getValue().getDay();

Find the Number of Days between two Days.



function CalculateDaysOpen()
{
        var FormType = Xrm.Page.ui.getFormType();
        if (FormType != null && FormType==2)
{
                  var currentDate=new Date();
 var createdDate=Xrm.Page.data.entity.attributes.get("createdon").getValue();
                  cycletime = Math.abs(currentDate- createdDate)
          alert(Math.round(cycletime / 86400000));
         }
}

Get Current User's Teams in crm 2011 using javascript.


function GetCurrentUserTeams() {

  var user = Xrm.Page.context.getUserId();
  var userId = user.substring(1,37);

    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>team</q1:EntityName>" +
    " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
    " <q1:Attributes>" +
    " <q1:Attribute>name</q1:Attribute>" +
    " </q1:Attributes>" +
    " </q1:ColumnSet>" +
    " <q1:Distinct>false</q1:Distinct>" +
    " <q1:LinkEntities>" +
    " <q1:LinkEntity>" +
    " <q1:LinkFromAttributeName>teamid</q1:LinkFromAttributeName>" +
    " <q1:LinkFromEntityName>team</q1:LinkFromEntityName>" +
    " <q1:LinkToEntityName>teammembership</q1:LinkToEntityName>" +
    " <q1:LinkToAttributeName>teamid</q1:LinkToAttributeName>" +
    " <q1:JoinOperator>Inner</q1:JoinOperator>" +
    " <q1:LinkCriteria>" +
    " <q1:FilterOperator>And</q1:FilterOperator>" +
    " <q1:Conditions>" +
    " <q1:Condition>" +
    " <q1:AttributeName>systemuserid</q1:AttributeName>" +
    " <q1:Operator>Equal</q1:Operator>" +
    "<q1:Values>" +
    //code to get the owner
    "<q1:Value xsi:type=\"xsd:string\">" + userId + "</q1:Value>" +
    "</q1:Values>" +

    " </q1:Condition>" +
    " </q1:Conditions>" +
    " </q1:LinkCriteria>" +
    " </q1:LinkEntity>" +
    " </q1:LinkEntities>" +
    " </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 resultXml = xmlHttpRequest.responseXML;
    //alert(resultXml.xml);

    // Save all entity nodes in an array.
    var entityNodes = resultXml.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

    var teamnames = new Array();
    var teamids = new Array();

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

        var entityNode = entityNodes[i];
        var teamidNode = entityNode.selectSingleNode("q1:teamid");
        var teamNode = entityNode.selectSingleNode("q1:name");
        var teamid = (teamidNode == null) ? null : teamidNode.text;
        var team = (teamNode == null) ? null : teamNode.text;

        teamnames[i] = team;
        teamids[i] = teamid;
    }

    alert(teamnames);
}


Above script will not work in CRM 2013. For CRM 2013,the script is as below

function GetCurrentUserTeams()
{
    var teamName="Communities Team";
if (teamName != null && teamName != "") {
// build endpoint URL
var serverUrl = Xrm.Page.context.getServerUrl();
var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
// query to get the teams that match the name
oDataEndpointUrl += "TeamSet?$select=Name,TeamId&$filter=Name eq '" + teamName + "'";
var service = GetRequestObject();
if (service != null) {
// execute the request
service.open("GET", oDataEndpointUrl, false);
service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
service.setRequestHeader("Accept", "application/json,text/javascript, */*");
service.send(null);
// parse the results
var requestResults = eval('(' + service.responseText + ')').d;
if (requestResults != null && requestResults.results.length > 0) {
var teamCounter;
// iterate through all of the matching teams, checking to see if the current user has a membership
for (teamCounter = 0; teamCounter < requestResults.results.length; teamCounter++) {
var team = requestResults.results[teamCounter];
var teamId = team.TeamId;
// get current user teams
var currentUserTeams = getUserTeams(teamId);
// Check whether current user teams matches the target team
if (currentUserTeams != null) {
for (var i = 0; i < currentUserTeams.length; i++) {
var userTeam = currentUserTeams[i];
// check to see if the team guid matches the user team membership id
if (GuidsAreEqual(userTeam.TeamId, teamId)) {
return true;
}
}
}
else {
return false;
}
}
}
else {
alert("Team with name '" + teamName + "' not found");
return false;
}
return false;
}
 }
 else {
 alert("No team name passed");
 return false;
 }
}
function getUserTeams(teamToCheckId) {
 // gets the current users team membership
 var userId = Xrm.Page.context.getUserId().substr(1, 36);
 var serverUrl = Xrm.Page.context.getServerUrl();
 var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
 oDataEndpointUrl += "TeamMembershipSet?$filter=SystemUserId eq guid' " + userId + " ' and TeamId eq guid' " + teamToCheckId + " '";
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;
 }
 }
}
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) {
 // compares two guids
 var isEqual = false;
 if (guid1 == null || guid2 == null) {
 isEqual = false;
 } else {
 isEqual = (guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase());
 }
 return isEqual;
}

Sunday, May 12, 2013

How to add Month in given date using Jscript.


 var startdate=Xrm.Page.data.entity.attributes.get(startingdate).getValue();
 var duration=Xrm.Page.data.entity.attributes.get(nodays).getValue();
  var endwarrantydate=Xrm.Page.data.entity.attributes.get(endingdate);
  if(startdate!=null && duration!=null)
  {            
var enddate= startdate.setMonth(startdate.getMonth() + duration);
        endwarrantydate.setValue(enddate);
  }

Wednesday, April 24, 2013

How to access Parent Form Attribute in CRM form.


you can access the property using window.top.opener

Lets i have to access the property of parent lookup form and set into it.then you can use the following code

var previous = window.top.opener.Xrm.Page.getAttribute("customerid").getValue();
previous[0].name = Xrm.Page.getAttribute("firstname").getValue() + " " +  Xrm.Page.getAttribute("lastname").getValue();
window.top.opener.Xrm.Page.getAttribute("customerid").setValue(previous);


same way if i want to get the value from parent form then

var previous = window.top.opener.Xrm.Page.getAttribute("firstname").getValue();

This is unsupportive way.


Execute workflow using javascript in CRM 2011




function RunWorkflow() {
    var _return = window.confirm('Are you want to execute workflow.');
    if (_return) {
        var url = Xrm.Page.context.getServerUrl();
        var entityId = Xrm.Page.data.entity.getId();
        var workflowId = '437DDF9B-EE32-4E88-91CF-544B49179F58';
        var OrgServicePath = "/XRMServices/2011/Organization.svc/";
        url = url + OrgServicePath;
  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\">" +
    Xrm.Page.context.getAuthenticationHeader() +
    "<soap:Body>" +
    "<Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
    "<Request xsi:type=\"ExecuteWorkflowRequest\">" +
    "<EntityId>" + entityId + "</EntityId>" +
    "<WorkflowId>" + workflowId+ "</WorkflowId>" +
    "</Request>" +
    "</Execute>" +
    "</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/Execute");
  xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
  xmlHttpRequest.send(xml);
 }
}

Tuesday, April 23, 2013

Create Early-Bound Entity Classes with the Code Generation Tool (CrmSvcUtil.exe) in CRM 2011


You can find the utility in the SDK download package in the SDK\Bin folder.The classes created by the code generation tool are designed to be built into a class library that can be referenced by projects that use Microsoft Dynamics CRM. After you have generated the classes using the tool, you should add the file that contains the classes to your Visual Studio project or solution

Assemblies Need to Include
Microsoft.Crm.Sdk.Proxy.dll
Microsoft.Xrm.Sdk.dll

Run the Code Generation Utility
Run this utility from the SDK\Bin folder. If you run the utility from another location, the Microsoft.Xrm.Sdk.dll assembly, located in the SDK\Bin folder, must be located in the same folder

Format for running the utility from the command line
CrmSvcUtil.exe /url:http://<servername>/<organizationname>
/XRMServices/2011/Organization.svc /out:<outputfilename>.cs /username:<username> /password:<password> /domain:<domainname> /namespace:<outputnamespace> /serviceContextName:<service context name>


Open Visual command Prompt and then Go to the path sdk/bin in CRM sdk and then write below commnad if you are using the
CRM online

CrmSvcUtil.exe /url:https://org.api.crm5.dynamics.com/XRMServices/2011/Organization.svc /out:GeneratedCode.cs /username:"myname@mubnam.onmicrosoft.com" /password:"password" /deviceid:"23pq434ldg5nqps9h4ivlngbfv" /devicepassword:"J-n60IPL7h;Ga`b5##SsIHJM"


Examples to use the code generation utility from the command line for each deployment type
Claims Authentication Active Directory
CrmSvcUtil.exe /url:http://CRM2011:5555/Org/XRMServices/2011/Organization.svc /out:GeneratedCode.cs /username:administrator /password:password"


Claims Authentication - IFD
CrmSvcUtil.exe /url:https://org.crm.com:5555/XRMServices/2011/Organization.svc /out:GeneratedCode.cs /username:administrator /password:p@ssword!

Monday, April 15, 2013

Write a common plugin for Create/Update/Delete events in Dynamics CRM 2011

If you want to write a common plugin for Create/Update/Delete events in Dynamics CRM 2011 then only you need to take care of “context.InputParameters["Target"]“. In case of Create/Update event “context.InputParameters["Target"] is Entity” and in case of Delete event “context.InputParameters["Target"] is EntityReference”. Below is the sample code for the same:


public void Execute(IServiceProvider serviceProvider)
{
     // Obtain the execution context from the service provider.
     IPluginExecutionContext context = (IPluginExecutionContext)
     serviceProvider.GetService(typeof(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 (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
     {
          if (context.MessageName == "Create")
          {
               //Code to be executed during Create event of an entity
          }
          else if (context.MessageName == "Update")
          {
               //Code to be executed during Update event of an entity
          }
      }
      else if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
      {
          if (context.MessageName == "Delete")
          {
              //Code to be executed during Delete event of an entity
          }
      }
}

Monday, November 5, 2012

Open Silverlight application on click of custom ribbon button in CRM 2011


First Create a Silverlight application and upload on Webresource in CRM.
Then second step create a HTML web Page like below.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
 
<head>
    <title>ExpenseNote</title>
    <style type="text/css">
    html, body {
        height: 100%;
        overflow: auto;
    }
    body {
        padding: 0;
        margin: 0;
    }
    #silverlightControlHost {
        height: 100%;
        text-align:center;
    }
    </style>
    <script type="text/jscript" src="../../ClientGlobalContext.js.aspx"></script>
   1:  
   2:     <script type="text/javascript" src="../JavaScripts/Silverlight.js">
   1: </script>
   2:     <script type="text/javascript">
   3:       function onSilverlightError(sender, args) {
   4:         
   5:             var appSource = "";
   6:             if (sender != null && sender != 0) {
   7:               appSource = sender.getHost().Source;
   8:             }
   9:             
  10:             var errorType = args.ErrorType;
  11:             var iErrorCode = args.ErrorCode;
  12:  
  13:             if (errorType == "ImageError" || errorType == "MediaError") {
  14:               return;
  15:             }
  16:  
  17:             var errMsg = "Unhandled Error in Silverlight Application " +  appSource + "\n" ;
  18:  
  19:             errMsg += "Code: "+ iErrorCode + "    \n";
  20:             errMsg += "Category: " + errorType + "       \n";
  21:             errMsg += "Message: " + args.ErrorMessage + "     \n";
  22:  
  23:             if (errorType == "ParserError") {
  24:                 errMsg += "File: " + args.xamlFile + "     \n";
  25:                 errMsg += "Line: " + args.lineNumber + "     \n";
  26:                 errMsg += "Position: " + args.charPosition + "     \n";
  27:             }
  28:             else if (errorType == "RuntimeError") {           
  29:                 if (args.lineNumber != 0) {
  30:                     errMsg += "Line: " + args.lineNumber + "     \n";
  31:                     errMsg += "Position: " +  args.charPosition + "     \n";
  32:                 }
  33:                 errMsg += "MethodName: " + args.methodName + "     \n";
  34:             }
  35:  
  36:             throw new Error(errMsg);
  37:         }
  38:     
</script>
</head>
<body>
    <form id="form1" runat="server" style="height:100%">
    <div id="silverlightControlHost">
      <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
          <param name="source" value="../XAP/Treeview.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="4.0.50826.0" />
          <param name="autoUpgrade" value="true" />
          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
               <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
          </a>
        </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
    </form>
</body>
</html>




Note:

1) In the source parameter specify the path of your xap webresource correctly.
Here name of the webresource is ink_/XAP/Treeview.xap and so the value for source is "../XAP/Treeview.xap", a relative path.

2) Also add the SilverLight.js file as a webresource. You can find the Silverlight.js file in sdk in the Silverlight example projects.

Now create a webresource and upload this html file. We have named this html webresource as Treeview.html.

Now we need to open this html file on click of a button.

For this we will create a button. You can create button using the Visual Ribbon editor. To use Visual Ribbon Editor refer this link
http://microsoftcrmkartik.blogspot.in/2012/10/create-mark-complete-function-button-in.html

In Action you can either directly specify a URL which will be accessed on button click or you can specify a javascript function which is defined within a webresource of type javascript file. In this example we would be using a javascript function defined within a webresource.

Here OpenSilverLightControl is the function that contains code to open the Treeview.html file.



function OpenSilverLightControl()
 {
var serverUrl = Xrm.Page.context.getServerUrl();         
window.showModalDialog(serverUrl+'/WebResources/ink_/html/Treeview.html', " ","dialogWidth:800px ; dialogHeight:600px; center:yes;resizable:yes");
}

how to get (ScriptObject)HtmlPage.Window.GetProperty(“Xrm”) in Silverlight Application when it embedded to HTML Page in CRM


dynamic xrmnew = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
if (xrmnew == null)
{
    HtmlWindow parentWindow = HtmlPage.Window.GetProperty("parent") as HtmlWindow;
    xrmnew = (ScriptObject)parentWindow.GetProperty("Xrm");
}
Guid Id = new Guid(xrmnew.Page.data.entity.getId());

Tuesday, October 30, 2012

How to add button to CRM 2011 form?

I am not talking about Ribbon but but if you want to create button on Form Then Refrer below link

http://thecrmworld.wordpress.com/2011/04/27/how-to-add-button-to-crm-2011-form/

Refreshing a Web Resource on a form - CRM 2011


How I refresh a html web resource is as follows in a form's OnChange event is as follows.
var someOnchangeEvent = function(){
    var wrControl = Xrm.Page.ui.controls.get("nameofwebresoucecontrol");
    wrControl.setSrc(wrControl.getSrc());
}

Monday, October 29, 2012

How to Publish Webresource using coding/InPlug


 PublishXmlRequest request = new PublishXmlRequest()
 {
                           ParameterXml = String.Format(@"<importexportxml><webresources><webresource>{0}</webresource></webresources></importexportxml>", webResource.WebResourceId)
 };

 service.Execute(request);


webResource.WebResourceId=This is the Guid of Webresource


Please make sure that if you are using this code in PlugIn then you should register the PlugIn in Asynchnronous mode.

if you want to Publish all customization then


PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
service.Execute(publishRequest);

Friday, October 5, 2012

Create Mark Complete Function Button in Custom Entity.


I have one requirement that i have to create same functionality that we have in Phone call Activity like Mark Complete.

Please Follow the Below steps to create Mark Complete Functionality.

1.First Go to Settings->Customization->Select Entity->Field->open Status Reason Field->Select In Active Dropdown->Add new ->Completed and save and publish.

2.Now Go to We Resource and Add PNG File for Mark Complete Button with name new_imgComplete.

3.Go to Setting->Solution(Under Customization)->Then Create a New Solution->Save and Close.

4.Open the Newly Created Solution->Add Existing->Entity and select the Entity to which you want to Add the Mark Complete Button.->Save and Close.

5.Now select the Solution and Export(Unmanaged) the Solution.

6.Open customizations.xml File.

7. under <RibbonDiffXml>.......</RibbonDiffXml> paste the Following line

<RibbonDiffXml>
 <CustomActions>
          <CustomAction Id="Form.CustomAction" Location="Mscrm.Form.hov_meeting.MainTab.Save.Controls._children" Sequence="1">
            <CommandUIDefinition>
              <Button Id="Form.Button.CompleteMeeting" Command="Form.CommandDef" LabelText="$LocLabels:Lable.Text" ToolTipTitle="$LocLabels:Lable.ToolTip" ToolTipDescription="$LocLabels:Lable.ToolTip" TemplateAlias="o1" Image32by32="$webresource:new_imgComplete" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>
        <Templates>
          <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
        </Templates>
        <CommandDefinitions>
          <CommandDefinition Id="Form.CommandDef">
            <EnableRules>
              <EnableRule Id="EnableRule.NotNew" />
              <EnableRule Id="EnableRule.WebClient" />
              <EnableRule Id="EnableRule.CustomButton" />
            </EnableRules>
            <DisplayRules>
              <DisplayRule Id="DisplayRule.FormStateNotNew" />
              <DisplayRule Id="DisplayRule.WebClient" />
            </DisplayRules>
            <Actions>
              <JavaScriptFunction Library="$webresource:new_MeetingFunctions" FunctionName="MarkComplete" />
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>
        <RuleDefinitions>
          <TabDisplayRules />
          <DisplayRules>
            <DisplayRule Id="DisplayRule.FormStateNotNew">
              <FormStateRule State="Create" InvertResult="true" />
            </DisplayRule>
            <DisplayRule Id="DisplayRule.WebClient">
              <CrmClientTypeRule Type="Web" />
            </DisplayRule>
          </DisplayRules>
          <EnableRules>
            <EnableRule Id="EnableRule.CustomButton">
              <CustomRule Library="$webresource:new_MeetingFunctions" FunctionName="test" />
            </EnableRule>
            <EnableRule Id="EnableRule.NotNew">
              <FormStateRule State="Create" InvertResult="true" />
            </EnableRule>
            <EnableRule Id="EnableRule.WebClient">
              <CrmClientTypeRule Type="Web" />
            </EnableRule>
          </EnableRules>
        </RuleDefinitions>
        <LocLabels>
          <LocLabel Id="Lable.Text">
            <Titles>
              <Title languagecode="1033" description="Mark Complete" />
            </Titles>
          </LocLabel>
          <LocLabel Id="Lable.ToolTip">
            <Titles>
              <Title languagecode="1033" description="Mark Complete" />
            </Titles>
          </LocLabel>
        </LocLabels>
</RibbonDiffXml>

8.Now Zip the all File again with the same name that you export the solution and import again in solution.

9.Now create one .js file with name new_MeetingFunctions and Add the script in WebResource.be sure that if you give the another name then you have to change it in Customizations.xml file under

<Actions>
         <JavaScriptFunction Library="$webresource:new_MeetingFunctions" FunctionName="MarkComplete" />
</Actions>

10.Now paste the Following lines in .js File

function MarkComplete()
{
   alert(Xrm.Page.context.getServerUrl());
    //SetStateRequest(Entity Name, Xrm.Page.data.entity.getId(), 1,100000000);
    SetStateRequest("hov_meeting", Xrm.Page.data.entity.getId(), 1,100000000);
    window.location.reload(true);
}

function RetrieveOptionsetLabel(entityLogicalName ,RetrieveAttributeName,optionValue,AssignAttributeName,Id  )
{
    // Calling Metadata service to get Optionset Label
    SDK.MetaData.RetrieveEntityAsync(SDK.MetaData.EntityFilters.Attributes, entityLogicalName, null, false, function (entityMetadata) { successRetrieveEntity(entityLogicalName, entityMetadata, RetrieveAttributeName, optionValue,AssignAttributeName,Id); }, errorDisplay);

}

function successRetrieveEntity(logicalName, entityMetadata, RetrieveAttributeName, OptionValue,AssignAttributeName,Id)
{

    var success = false;
    for (var i = 0; i < entityMetadata.Attributes.length; i++) {
        var AttributeMetadata = entityMetadata.Attributes[i];
        if (success) break;
        if (AttributeMetadata.SchemaName.toLowerCase() == RetrieveAttributeName.toLowerCase()) {
            for (var o = 0; o < AttributeMetadata.OptionSet.Options.length; o++) {
                var option = AttributeMetadata.OptionSet.Options[o];
                if (option.OptionMetadata.Value == OptionValue)
                {

                    //Xrm.Page.getAttribute(AssignAttributeName).setValue(option.OptionMetadata.Label.UserLocalizedLabel.Label);
   var serverUrl = location.protocol + '//' + location.host + '/' + Xrm.Page.context.getOrgUniqueName(); //Xrm.Page.context.getServerUrl();

var meetinglink = "<a href='javascript: void(0);' onclick=\"window.open(\'" + serverUrl + "/main.aspx?etn=hov_meeting&pagetype=entityrecord&id={" + Id + "}\', \'windowname1\', \'resizable=1, scrollbars=1\');  return false;\" style='color:blue;text-decoration:underline !important'>" + option.OptionMetadata.Label.UserLocalizedLabel.Label + "</a>";

                    document.getElementById("header_" + AssignAttributeName + "_d").childNodes[0].innerHTML=meetinglink;
                    success = true;
                    break;
                }
            }
        }
    }
}



function SetStateRequest(_entityname, entityid, _state, _status)
{
    var requestMain = ""
    requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    requestMain += "  <s:Body>";
    requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    requestMain += "      <request i:type=\"b:SetStateRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
    requestMain += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>EntityMoniker</c:key>";
    requestMain += "            <c:value i:type=\"a:EntityReference\">";
    requestMain += "              <a:Id>" + entityid + "</a:Id>";
    requestMain += "              <a:LogicalName>" + _entityname + "</a:LogicalName>";
    requestMain += "              <a:Name i:nil=\"true\" />";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>State</c:key>";
    requestMain += "            <c:value i:type=\"a:OptionSetValue\">";
    requestMain += "              <a:Value>" + _state + "</a:Value>";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <c:key>Status</c:key>";
    requestMain += "            <c:value i:type=\"a:OptionSetValue\">";
    requestMain += "              <a:Value>" + _status + "</a:Value>";
    requestMain += "            </c:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "        </a:Parameters>";
    requestMain += "        <a:RequestId i:nil=\"true\" />";
    requestMain += "        <a:RequestName>SetState</a:RequestName>";
    requestMain += "      </request>";
    requestMain += "    </Execute>";
    requestMain += "  </s:Body>";
    requestMain += "</s:Envelope>";
    var req = new XMLHttpRequest();
    req.open("POST", _getServerUrl(), false)  
    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");
    var successCallback = null;
    var errorCallback = null;
    req.onreadystatechange = function () { SetStateResponse(req, successCallback, errorCallback); };
    req.send(requestMain);
}

function SetStateResponse(req, successCallback, errorCallback)
{

    if (req.readyState == 4)
    {
        if (req.status == 200)
        {
            if (successCallback != null)
            { successCallback(); }
        }
        else
        {
            _getError(req.responseXML);
        }
    }
}

function successCallback()
{
alert('test');
}

function _getServerUrl()
{
    var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
    var serverUrl = "";
    if (typeof GetGlobalContext == "function")
    {
        var context = GetGlobalContext();
        serverUrl = context.getServerUrl();
    }
    else
    {
        if (typeof Xrm.Page.context == "object")
        {
            serverUrl = location.protocol + '//' + location.host+ '/' + Xrm.Page.context.getOrgUniqueName();
           //If you are using the Trail vesrion of CRM means CRM Online then
           // serverUrl = location.protocol + '//' + location.host;
        }
        else
        { throw new Error("Unable to access the server URL"); }
    }
    if (serverUrl.match(/\/$/))
    {
        serverUrl = serverUrl.substring(0, serverUrl.length - 1);
    }
    return serverUrl + OrgServicePath;
}

function _getError(faultXml)
{
    var errorMessage = "Unknown Error (Unable to parse the fault)";
    if (typeof faultXml == "object")
    {
        try
        {
            var bodyNode = faultXml.firstChild.firstChild;
            //Retrieve the fault node
            for (var i = 0; i < bodyNode.childNodes.length; i++)
            {
                var node = bodyNode.childNodes[i];
                if ("s:Fault" == node.nodeName)
                {
                    for (var j = 0; j < node.childNodes.length; j++)
                    {
                        var faultStringNode = node.childNodes[j];
                        if ("faultstring" == faultStringNode.nodeName)
                        {
                            errorMessage = faultStringNode.text;
                            break;
                        }
                    }
                    break;
                }
            }
        }
        catch (e) { };
    }
    return new Error(errorMessage);
}

function GetOptionsetLabel(entityLogicalName ,RetrieveAttributeName,optionValue,AssignAttributeName)
{
    // Calling Metadata service to get Optionset Label
    SDK.MetaData.RetrieveEntityAsync(SDK.MetaData.EntityFilters.Attributes, entityLogicalName, null, false, function (entityMetadata) { successGetEntity(entityLogicalName, entityMetadata, RetrieveAttributeName, optionValue,AssignAttributeName); }, errorDisplay);

}

function successGetEntity(logicalName, entityMetadata, RetrieveAttributeName, OptionValue,AssignAttributeName)
{
    var success = false;
    for (var i = 0; i < entityMetadata.Attributes.length; i++) {
        var AttributeMetadata = entityMetadata.Attributes[i];
        if (success) break;
        if (AttributeMetadata.SchemaName.toLowerCase() == RetrieveAttributeName.toLowerCase()) {
            for (var o = 0; o < AttributeMetadata.OptionSet.Options.length; o++) {
                var option = AttributeMetadata.OptionSet.Options[o];
                if (option.OptionMetadata.Value == OptionValue)
                {
                    Xrm.Page.getAttribute(AssignAttributeName).setValue(option.OptionMetadata.Label.UserLocalizedLabel.Label);  
                    success = true;
                    break;
                }
            }
        }
    }
}

function GetRequestObject()
{
    if (window.XMLHttpRequest)
        return new window.XMLHttpRequest;
    else
    {
        try
        {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch (ex)
        {
            return null;
        }
    }
}

function errorDisplay(XmlHttpRequest, textStatus, errorThrown)
{
     alert(errorThrown);
}

function trim(str)
{
    if(!str || typeof str != 'string')
        return null;

    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}

11.Now Open the Form and Add Javascript Library  from Web Resource. and Save it and publish the Form.

12.Thats it and just check now.Create the Record from and Save and Close.and again open the Record and Click on Mark Complete Button.