Tuesday, 19 November 2013

Retrieve records associate contact email address in CRM 2011 using C#

Here i retrieve email id in the "to" field of email activity.

Entity entity = context.InputParameters["Target"] as Entity;
                   
                    if (entity.LogicalName != "email")
                        return;
                    Email email = entity.ToEntity<Email>();                  
                    string to = string.Empty;

                    ColumnSet col = new ColumnSet("to");
                    entity = service.Retrieve(entity.LogicalName, entity.Id, col);
                    Guid partyId = new Guid();
                    EntityCollection Recipients = entity.GetAttributeValue<EntityCollection>("to");
                    foreach (var party in Recipients.Entities)
                    {                      
                        partyId = party.GetAttributeValue<EntityReference>("partyid").Id;
                    }

                    ColumnSet column = new ColumnSet("emailaddress1");
                    Entity toRecipent= service.Retrieve("contact", partyId, column);

                    Contact contact = toRecipent.ToEntity<Contact>();
                    to = contact.EMailAddress1;

How to use Access teams in CRM 2013.

Monday, 18 November 2013

Enable/Disable Autosave options in CRM 2013

Autosave can be enabled/disabled by navigating to Settings > Administration > System Settings > General Tab.


Friday, 15 November 2013

Get Option set text value from CRM 2011 using C#.

public string getOptionSetText(string entityName, string attributeName, int optionsetValue)
   {
       string optionsetText = string.Empty;
       RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
       retrieveAttributeRequest.EntityLogicalName = entityName;
       retrieveAttributeRequest.LogicalName = attributeName;
       retrieveAttributeRequest.RetrieveAsIfPublished = true;

       RetrieveAttributeResponse retrieveAttributeResponse = 
         (RetrieveAttributeResponse)OrganizationService.Execute(retrieveAttributeRequest);
       PicklistAttributeMetadata picklistAttributeMetadata = 
         (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

       OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;

       foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
       {
            if (optionMetadata.Value == optionsetValue)
             {
                optionsetText = optionMetadata.Label.UserLocalizedLabel.Label;
                 return optionsetText;
             }

       }
       return optionsetText;
  }

Get Option set values in CRM 2011 using C#.

string optionSetText="Advertisement"
OptionSetValue leadSource = new OptionSetValue(getOptionSetValue(lead.LogicalName, "fieldAttribute", optionSetText));
newLead["leadsourcecode"] = leadSource;

public int getOptionSetValue(string logicalName, string attributeName, string optionsetText)
        {
            int optionSetValue=0;
            RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
            retrieveAttributeRequest.EntityLogicalName = "lead";
            retrieveAttributeRequest.LogicalName = attributeName;
            retrieveAttributeRequest.RetrieveAsIfPublished = true;

            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
            PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

            OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;

            foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
            {
                if (optionMetadata.Label.UserLocalizedLabel.Label.ToLower() == optionsetText.ToLower())
                {
                    optionSetValue = optionMetadata.Value.Value;
                    return optionSetValue;
                }

            }
            return optionSetValue;
        }

Wednesday, 13 November 2013

Plugin to Create record in the creation of email activity in CRM 2011 and 2013

In my scenario i have to create new lead in creation of email. The email contain one Xml attachment named enquiry. That attachment have some standard tags. I have to read the xml tag and its values.Based on the values i have to create a new lead record. I did this scenario using the following code:

using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Xrm;
using System.Xml;
using System.IO;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;

namespace OPS.Lead.Create
{  
    public class GenerateLead : IPlugin
    {
        XmlDocument doc = new XmlDocument();
        IOrganizationService service;
        public void Execute(IServiceProvider serviceProvider)
        {          
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            try
            {
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                service = serviceFactory.CreateOrganizationService(context.UserId);
             
                if (context.InputParameters.ContainsKey("Target") && context.InputParameters["Target"] is Entity)
                {                  
                    Entity entity = context.InputParameters["Target"] as Entity;
                 
                    if (entity.LogicalName != "email")
                        return;
                    Email email = entity.ToEntity<Email>();                  
                    string to = string.Empty;

                    ColumnSet col = new ColumnSet("to", "from");
                    entity = service.Retrieve(entity.LogicalName, entity.Id, col);
                    Guid partyId = new Guid();
                    EntityCollection Recipients = entity.GetAttributeValue<EntityCollection>("to");
                    foreach (var party in Recipients.Entities)
                    {                      
                        partyId = party.GetAttributeValue<EntityReference>("partyid").Id;
                    }

                    ColumnSet column = new ColumnSet("internalemailaddress");
                    Entity toRecipent = service.Retrieve(SystemUser.EntityLogicalName, partyId, column);

                    SystemUser contact = toRecipent.ToEntity<SystemUser>();
                    to = contact.InternalEMailAddress;

                    if (!(to == "enquiry@xyz.com"))
                        return;

                    try
                    {
                        //Retrieve all attachments associated with the email activity.
                        QueryExpression _attachmentQuery = new QueryExpression
                        {
                            EntityName = ActivityMimeAttachment.EntityLogicalName,
                            ColumnSet = new ColumnSet("activitymimeattachmentid"),
                            Criteria = new FilterExpression
                            {
                                FilterOperator = LogicalOperator.And,
                                Conditions =
                        {
                            new ConditionExpression
                            {
                                AttributeName = "objectid",
                                Operator = ConditionOperator.Equal,
                                Values = {entity.Id}
                            },
                            new ConditionExpression
                            {
                                AttributeName = "objecttypecode",
                                Operator = ConditionOperator.Equal,
                                Values = {Email.EntityLogicalName}
                            }
                        }
                            }
                        };

                        EntityCollection results = service.RetrieveMultiple(_attachmentQuery);

                        if (results.Entities.Count == 0)
                            return;
                        string filename=string.Empty;
                        foreach (Entity ent in results.Entities)
                        {

                            ColumnSet colset = new ColumnSet();
                            colset.AllColumns = true;
                            ActivityMimeAttachment emailAttachment = (ActivityMimeAttachment)service.Retrieve("activitymimeattachment", ent.Id, colset);
                            filename= emailAttachment.FileName;
                            if (filename.Equals("enquiry"))
                            {
                                byte[] fileContent = Convert.FromBase64String(emailAttachment.Body);
                                using (MemoryStream ms = new MemoryStream(fileContent))
                                {
                                    doc.Load(ms);
                                }
                            }
                        }

                        if (filename.Equals("enquiry"))
                        {
                            Entity newLead = new Entity("lead");

                            newLead["subject"] = entity.GetAttributeValue<string>("subject");
                            newLead["firstname"] = GetTagValue("Firstname");
                            newLead["lastname"] = GetTagValue("LastName");
                            newLead["emailaddress1"] = GetTagValue("EmailAddress");
                            newLead["companyname"] = GetTagValue("Companyname");
                            newLead["jobtitle"] = GetTagValue("Title");
                            newLead["mobilephone"] = GetTagValue("MobileNo");
                            newLead["address1_country"] = GetTagValue("Country");

                            string numberOfUsers = GetTagValue("Crmusers");
                            OptionSetValue crmUsers = new OptionSetValue(getOptionSetValue("ln_crmusers", numberOfUsers));
                            newLead["ln_crmusers"] = crmUsers;

                            string source = GetTagValue("Channel");
                            OptionSetValue leadSource = new OptionSetValue(getOptionSetValue("leadsourcecode", source));
                            newLead["leadsourcecode"] = leadSource;

                            string NoOfProduct = GetTagValue("ProductImplemented");
                            OptionSetValue productImplemented = new OptionSetValue(getOptionSetValue("ln_productimplemented", NoOfProduct));
                            newLead["ln_productimplemented"] = productImplemented;

                            string durationToBuy = GetTagValue("BuyPeriod");
                            OptionSetValue buyPeriod = new OptionSetValue(getOptionSetValue("ln_buyplan", durationToBuy));
                            newLead["ln_buyplan"] = buyPeriod;

                            string wantDemo = GetTagValue("Demo");
                            bool demo = false;
                            if (wantDemo.Equals("true"))
                                demo = true;
                            newLead["ln_demo"] = demo;

                            string broucher = GetTagValue("Brochure");
                            bool ln_broucher = false;
                            if (broucher.Equals("true"))
                                ln_broucher = true;
                            newLead["ln_brochure"] = ln_broucher;

                            newLead["description"] = GetTagValue("Comments");
                            newLead["ownerid"] = new EntityReference(SystemUser.EntityLogicalName, context.UserId);

                            service.Create(newLead);
                        }
                        else
                            return;
                    }
                    catch (FaultException<OrganizationServiceFault> ex)
                    {
                        tracingService.Trace("1"+ex.Message);
                    }
                    catch (Exception e)
                    {
                        tracingService.Trace("2"+e.Message);
                    }
                }
            }          
            catch (Exception exp)
            {
                tracingService.Trace("3"+exp.Message);
            }
        }

        public string GetTagValue(string element)
        {          
            string values = "";
            foreach (XmlNode node in doc.GetElementsByTagName(element))
                values = node.InnerText;
            return values;
        }

        public int getOptionSetValue(string attributeName, string optionsetText)
        {
            int optionSetValue = 0;
            RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
            retrieveAttributeRequest.EntityLogicalName = "lead";
            retrieveAttributeRequest.LogicalName = attributeName;
            retrieveAttributeRequest.RetrieveAsIfPublished = true;

            RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
            PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

            OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;

            foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
            {
                if (optionMetadata.Label.UserLocalizedLabel.Label.ToLower() == optionsetText.ToLower())
                {
                    optionSetValue = optionMetadata.Value.Value;
                    return optionSetValue;
                }

            }
            return optionSetValue;
        }
    }
}
 

Friday, 15 March 2013

Trigger workflow from button using JavaScript in CRM 2011


function CallWorkflow(entityId, workflowId) {
  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, 12 March 2013

Disable all fields in CRM 2011 based on Statuscode using Javascript


function DisableFields() {
    if (Xrm.Page.data.entity.attributes.get("statuscode").getValue() != 1) {
        disableFormFields(true);
    }
}
function doesControlHaveAttribute(control) {
    var controlType = control.getControlType();
    return controlType != "iframe" && controlType != "webresource" && controlType != "subgrid";
}
function disableFormFields(onOff) {
    Xrm.Page.ui.controls.forEach(function (control, index) {
        if (doesControlHaveAttribute(control)) {
            control.setDisabled(onOff);
        }
    });
}

Save this code on webResources and call DisableFields method on page OnLoad.

Thursday, 7 March 2013

Thursday, 28 February 2013

Disable View of Look Up Record dialog


function SupplierLookup() {
    document.getElementById("customerid").setAttribute("lookuptypes", "1");
    document.getElementById("customerid").setAttribute("defaulttype", "1");
    Xrm.Page.getControl("customerid").setDefaultView("36C01218-C55F-E211-BACF-00155D000B45"); // View Id
    document.getElementById("customerid").setAttribute("disableViewPicker", "1");
}

Thursday, 21 February 2013

Access restriction: The type Krb5LoginModule is not accessible due to restriction on required library C:\Program Files\Java\jre7\lib\rt.jar

In eclipse go to: Window > Preferences > Java > Compiler > Errors/Warnings > Deprecated and restricted API > Forbidden reference (access rules) > set it to ‘Warnings’ 

Wednesday, 13 February 2013

Set Opportunity status to Won in crm 2011


WinOpportunityRequest winRequest = new WinOpportunityRequest
                    {
                        OpportunityClose = new OpportunityClose
                        {
                            OpportunityId = new EntityReference
                            {
                                LogicalName = "opportunity",
                                Id = order.OpportunityId.Id
                            },
                        },
                        Status = new OptionSetValue(3)
                    };
                    service.Execute(winRequest);

Friday, 8 February 2013

Create Users in Domino Administrator



The purpose of this document is to create Lotus Notes user using Domino Administrator in Domino Server. Once the user is created successfully in Domino Server it can be configured in Lotus Notes.

Prerequisites:
·         Lotus Domino Administrator should  be installed and configured

Steps:
1.   Open Lotus Domino Administrator
2.   Select “People” under the Domino server directory



3.       Right side panel, click “People”. In that click “Register…” as shown below.



4.   It will prompt below dialog, click “Certifier ID…” and choose the “cert.id” file from “C:\Program Files\IBM\Lotus\Domino\data” path. 



5.   Then click “OK” button in the above dialog.
6.   It will prompt for Lotus Notes certifier password as shown below. In that enter certifier password and click “OK” button. 



7.   Finally after the validation it will open the user creation dialog as shown below. in that dialog enter the required details as shown below. 



8.   Click “Password Options…” and set the options as shown below and click “OK” button.




9.   Then to set the email address for the newly created user, Check the “Advanced” option and set the email address as shown below. 



10.                Once all the above steps are completed, click the green color tick symbole in the above dialog and click the “Register” button to regiter the user in the domino server. 



11.                Once the user registered successfully in the domino server, it will show the below confirmation dialog.




These are all the steps to be done to create a user in domino server.

Thursday, 7 February 2013

Run Reports of a particular record in CRM 2011 using javacript



Open particular record and Click run report and select which report you want to run.




Copy the URL on the report window. Use that url on the given code.

function openreport(id) { //  Get Current record Id

    var errorMessage = "Context is not available.";
    var context;
    if (typeof GetGlobalContext != "undefined") {
        context = GetGlobalContext();
    }
    else {
        if (typeof Xrm != "undefined") {

            context = Xrm.Page.context;
        }
        else {
            alert(errorMessage);
            return;
        }
    }

    var orgUrl = context.getServerUrl();

    var reportUrl = orgUrl + "/crmreports/viewer/viewer.aspx?action=run&context=records&helpID=OrderAcknowledgement.rdl&id=%7b20a4c6e9-8f6f-e211-957a-00155d000b45%7d&records=" + encodeURIComponent(id) + "&recordstype=10006";

    window.open(reportUrl);

}

Add the Code on CRM webresources and call this method on your ribbon custom button.

Wednesday, 6 February 2013

Remove pending email warning notification on CRM 2011


If you are using on-premise and use a URL like so:
http://crmserver/{Organization Name}

use the following instead:
http://crmserver/{Organization Name}/main.aspx?skipNotification=1

If you are claims-based (IFD) and use a URL like so:
https://{Organization Name}.crmserver.com

use the following instead:
https://{Organization Name}.crmserver.com/main.aspx?skipNotification=1

For on-line customers using a url like:
https://{Organization Name}.crm5.dynamics.com

use the following instead:
https://{Organization Name}.crm5.dynamics.com/main.aspx?skipNotification=1


Save it to your bookmark and stop growling (if you're like me) every time you open up CRM!

Wednesday, 30 January 2013

Count Sub-grid records in entity in CRM 2011 using javascript



function requisitionproducts() {
//Get Current record Id
    var Guid = Xrm.Page.data.entity.getId();
    var fetchXml =
    "<fetch mapping='logical'>" +
       "<entity name='quotedetail'>" + //SubGrid entity name
    //Condition to Check the subGrid record is associated with current record      
          "<filter>" +  
             "<condition attribute='quoteid' operator='eq' value='" + Guid + "' />" +
          "</filter>" +
       "</entity>" +
    "</fetch>";
   
    var fetchedRecord = XrmServiceToolkit.Soap.Fetch(fetchXml)
    if (fetchedRecord.length > 0) {
        return true;
    }
}


After adding this web-resource you need to add the following files to your form page Libraries:

  1. Json
  2. jquery
  3. xrmservicetoolkit


Monday, 21 January 2013

Get Current user business unit in CRM 2011 using javascript


function GetBusinessUnit() {  
        var request = "<request i:type='b:WhoAmIRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts' xmlns:b='http://schemas.microsoft.com/crm/2011/Contracts'>" +
                            "<a:Parameters xmlns:c='http://schemas.datacontract.org/2004/07/System.Collections.Generic' />" +
                            "<a:RequestId i:nil='true' />" +
                            "<a:RequestName>WhoAmI</a:RequestName>" +
                          "</request>";
        var resultXml = XrmServiceToolkit.Soap.Execute(request);
        var buid = resultXml.getElementsByTagName("a:Results")[0].childNodes[1].childNodes[1].text;
        var cols = ["name"];
        var retrievedContact = XrmServiceToolkit.Soap.Retrieve("businessunit", buid, cols);
        var businessUnitName = retrievedContact.attributes['name'].value;
       alert(businessUnitName);
    }
After that you need to add the following files to the Form Libraries.

  1. Jquery
  2. Json2
  3. XrmServiceToolkit
Download these files from the following link: XrmServiceToolkit

Get Partylist/Lookup field id in CRM 2011 using Javascript


var lookup = new Array();
        lookup = Xrm.Page.getAttribute("to").getValue();
        for (var indxAttendees = 0; indxAttendees < lookup.length; indxAttendees++) {
        var lookupId = lookup[indxAttendees].id;
        var lookupName=lookup[indxAttendees].name;
        var lookupType=lookup[indxAttendees].entityType;
}

Tuesday, 8 January 2013

Hide section/field based on related entity/records in CRM 2011 using javascript


function retrieveworkorder() {

    var ordernumber = Xrm.Page.data.entity.getId();
    if (ordernumber != null) {
        var fetchXml =
                    "<fetch mapping='logical'>" +
                       "<entity name='jmh_workorder'>" +
                          "<attribute name='jmh_workordernumber' />" +
                          "<filter>" +
                             "<condition attribute='jmh_bespokeorderid' operator='eq' value='" + ordernumber + "' />" +
                          "</filter>" +
                       "</entity>" +
                    "</fetch>";

        var retrievedOrder = XrmServiceToolkit.Soap.Fetch(fetchXml);
//        alert(retrievedOrder.length);
        if (retrievedOrder.length > 0) {
            Xrm.Page.ui.tabs.get("general").sections.get("workorder").setVisible(false);
        }
    }

}

Reference: http://xrmservicetoolkit.codeplex.com/wikipage?title=Soap%20Functions 

Monday, 7 January 2013

Get Business Unit in CRM 2011 using javascript

  • Add the following script to your web resources:
function GetBusinessUnit() {
    var currentstore = Xrm.Page.getAttribute('jmh_store').getValue();
    if (currentstore == null) {
        var request = "<request i:type='b:WhoAmIRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts' xmlns:b='http://schemas.microsoft.com/crm/2011/Contracts'>" +
                            "<a:Parameters xmlns:c='http://schemas.datacontract.org/2004/07/System.Collections.Generic' />" +
                            "<a:RequestId i:nil='true' />" +
                            "<a:RequestName>WhoAmI</a:RequestName>" +
                          "</request>";
        var resultXml = XrmServiceToolkit.Soap.Execute(request);
        var buid = resultXml.getElementsByTagName("a:Results")[0].childNodes[1].childNodes[1].text;
        var cols = ["name"];
        var retrievedContact = XrmServiceToolkit.Soap.Retrieve("businessunit", buid, cols);
        var buName = retrievedContact.attributes['name'].value;
        SetLookupValue('jmh_store', buid, buName, 'businessunit');
    }

    function SetLookupValue(fieldName, id, name, entityType) {
        if (fieldName != null) {
            var lookupValue = new Array();
            lookupValue[0] = new Object();
            lookupValue[0].id = id;
            lookupValue[0].name = name;
            lookupValue[0].entityType = entityType;
            Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
        }
    }
}


Note : Add XrmServiceToolkit in the page library
Reference: http://xrmservicetoolkit.codeplex.com/wikipage?title=Soap%20Functions