Sam's Microsoft Dynamics 365 Blog

Wednesday, 24 May 2017

C# Plugin Code



Assembly


using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using System.Collections.Generic;


Connection To On-Premise CRM

ClientCredentials credentials = new ClientCredentials();
credentials.UserName.UserName = @"CAWOWX\Akhilesh.Gandhi";
credentials.UserName.Password = "t2Z6sGnD";
Uri serviceUri = new Uri("https://crm-train.cmg.asia/CMGD365DEVM3/
XRMServices/2011/Organization.svc");
OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri,
 null, credentials, null);
proxy.EnableProxyTypes();
IOrganizationService organizationService = (IOrganizationService)proxy;





Connection To On-Line CRM

App.config  :-
<add name="CRMConnectionString" connectionString="Url=https://mys1.crm8.
dynamics.com/; Username=imtiyaz@mys1.onmicrosoft.com; Password=1!qQjafri;"
 />

C#   :-
CrmConnection connection = CrmConnection.Parse(ConfigurationManager.ConnectionStrings["CRMConnectionString"].ConnectionString);
IOrganizationService service = new OrganizationService(connection);
OrganizationServiceContext context = new OrganizationServiceContext(service);
Get And Post attribute Value
Option Set:-

Get : - 

OptionSetValue opProductType = new OptionSetValue();
opProductType = (OptionSetValue)item.Attributes[attributeName];
var optionValue = opProductType.Value;


Get Formatted Value :-

var StatusString = TermAndCon.FormattedValues["status"].ToString(); 


Post :  -
newSalesOrder[attributeName] = new OptionSetValue(Convert.ToInt32(optionValue));


Lookup:-

Get : -

EntityReference enfcur = (EntityReference)item.Attributes[attributeName];
 var LookupId = enfcur.Id;
 var logicalName = enfcur.LogicalName;

Post :  -
newSalesOrder[attributeName] = new EntityReference(logicalName, LookupId);
Money:-
Get : -

var totalValue = ((Money)item.Attributes[attributeName]).Value;

Post :  -

newSalesOrder[attributeName] = new Money((decimal)totalValue);
Others:-

Get : -

newSalesOrder[attributeName] = item.Attributes[attributeName];
Post :  -
newSalesOrder[attributeName] = item.Attributes[attributeName];
Get Single Record Corresponding to Guid


Guid contactguid = new Guid("{F0843D42-633D-E711-80CB-005056030F25}");
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "contactid";
condition1.Operator = ConditionOperator.Equal;
condition1.Values.Add(contactguid);

FilterExpression contactfilter = new FilterExpression();
contactfilter.Conditions.Add(condition1);
QueryExpression contactQuery = new QueryExpression("contact");
contactQuery.ColumnSet = new ColumnSet(true);
contactQuery.Criteria.AddFilter(contactfilter);
 
EntityCollection contactRecord = organizationService.RetrieveMultiple(contactQuery);
   foreach (var _Contact in contactRecord.Entities)
   {
       if (_Contact.Attributes.Contains("vtv_remainingpoints"))
      {
        var  customerPoints = _Contact.Attributes["vtv_remainingpoints"].ToString();
      }
 
    }





Retrieve Records Using Fetch XML

var fetchingTC = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                          "<entity name='vtv_termsandconditionsmain'>" +
                          "<attribute name='vtv_termsandconditionsmainid'/>" +
                           "<attribute name='vtv_name'/>" +
                           "<attribute name='createdon'/>" +
                            "<order attribute='vtv_name' descending='false'/>" +
                            "<filter type='and'>" +
                          "<filter type='and'>" +
                           "<filter type='and'>" +
                             "<filter type='or'>" +
                              "<condition attribute='vtv_city' operator='eq' value=''/>" +
                              "<condition attribute='vtv_club' operator='eq'  value='4152e494-ec18-e711-b068-00155d08642c'/>" +
                               "<condition attribute='vtv_district' operator='eq' value=''/>" +
                               "<condition attribute='vtv_region' operator='eq' value=''/>" +
                               "</filter>" +
                             "<condition attribute='vtv_contracttype' operator='eq' value='100000000'/>" +
                                     "<condition attribute='vtv_promotionprogram' operator='eq' value=''/>" +
                                 "</filter>" +
                                  "</filter>" + 
                                  "</filter>" +
                                "</entity>" +
                              "</fetch>";
 
          var TCLlistReq = new RetrieveMultipleRequest()
          {
              Query = new FetchExpression(fetchingTC)
          };
          //Get all 
          EntityCollection TandCTempEntities = ((RetrieveMultipleResponse)organizationService.Execute(TCLlistReq)).EntityCollection;
         

Retrieve Associate Record
 
Guid myGuid = new Guid("{F0843D42-633D-E711-80CB-005056030F25}");
Guid productGuid1 = new Guid("{E3AE34A8-EF2B-E711-80D6-00505603100A}");
   QueryExpression qesalesorder2 = new QueryExpression();
 //Query on reated entity records 
  qesalesorder2.EntityName = "product";
 //Retrieve the all attributes of the related record
qesalesorder2.ColumnSet = new ColumnSet(true);
 
 //create the relationship object
   Relationship relationship = new Relationship();
//add the condition where you can retrieve only the users related to Sales Order 
qesalesorder2.Criteria = new FilterExpression();
 // name of relationship between user & Sales Order
relationship.SchemaName = "vtv_contact_product_rd";
//create relationshipQueryCollection Object
 RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
 //Add the your relation and query to the RelationshipQueryCollection
 relatedEntity.Add(relationship, qesalesorder2);
 //create the retrieve request object
 RetrieveRequest request = new RetrieveRequest();
//add the relatedentities query
request.RelatedEntitiesQuery = relatedEntity;
 //set column to and the condition for the SalesOrder
ColumnSet salesorderColumns1 = new ColumnSet(true);
request.ColumnSet = salesorderColumns1;
request.Target = new EntityReference { Id = myGuid, LogicalName = "contact" };
 //execute the request
 RetrieveResponse response = (RetrieveResponse)organizationService.Execute(request);
ICollection<EntityCollection> rst = response.Entity.RelatedEntities.Values;
 List<EntityCollection> temp = new List<EntityCollection>(rst);
//get systemusers from N to N relationship
 EntityCollection SystemUserData = temp[0];
Associate a Record  
(Associate Products to Contact. Contact is a primary Entity)
 Guid contact_Id = new Guid("{F0843D42-633D-E711-80CB-005056030F25}");
 Guid productGuid = new Guid("{E3AE34A8-EF2B-E711-80D6-00505603100A}");

 EntityReference contact = new EntityReference("contact", contact_Id);
 EntityReference product = new EntityReference("product", product.Id);

 // Creating EntityReferenceCollection for the Contact
  EntityReferenceCollection relatedEntities = new EntityReferenceCollection();

 relatedEntities.Add(product);

Relationship relationship1 = new Relationship("vtv_contact_product_rd");

organizationService.Associate(contact.LogicalName, contact.Id, relationship1, relatedEntities);

Deassociate a Record  
foreach (var item in SystemUserData.Entities)
{
       
 EntityReference contact = new EntityReference("contact", myGuid); EntityReference product = new EntityReference("product", item.Id); // Creating EntityReferenceCollection for the Contact EntityReferenceCollection relatedEntities1 = new EntityReferenceCollection();
 // Add the related entity contact
relatedEntities1.Add(contact);
// Add the Account Contact relationship schema name
 Relationship relationship2 = new Relationship("vtv_contact_product_rd");
// Disassociate the contact record to Account
 organizationService.Disassociate(product.LogicalName, product.Id, relationship2, relatedEntities1);
}


Throw a message in CRM using Plugins
throw new InvalidPluginExecutionException("Maximum limit exceeded...!");


Create a Task Entity Record

//define task entity
Entity task = new Entity("task");
task["subject"] = "New member change request has been ";
task["description"] = "hello test"
Guid taskid= organizationService.Create(task);

Assign a Task to user

AssignRequest assign = new AssignRequest
{
     Assignee = new EntityReference("systemuser", _userGuid),
     Target = new EntityReference("task", taskid)
};
 
 // Execute the Request
organizationService.Execute(assign);

Create a activityparty Entity Record
(Email)

//create activityparty
Entity Fromparty = new Entity("activityparty");
Entity Toparty = new Entity("activityparty");
//set partyid 
Fromparty["partyid"] = new EntityReference("systemuser", _userId);
 
//system user guid
Guid _userGuid = sendEmail.userGuid;
//Email reciver
Toparty["partyid"] = new EntityReference("systemuser", _userGuid);
//create email  and set attributes
Entity _Email = new Entity("email");
_Email["from"] = new Entity[] { Fromparty };
_Email["to"] = new Entity[] { Toparty };
_Email["subject"] = "New Price List has been ";
_Email["description"] = "https://crm-train.cmg.asia/main.aspx?etn=";
_Email["directioncode"] = true;
 Guid EmailID = organizationService.Create(_Email);



Get Entity Field Schema Name On Form
(function(){var frm=(window.Xrm&&window.Xrm.Page&&window.Xrm.Page.ui&&window)||(frames[1]&&frames[1].Xrm&&frames[1].Xrm.Page.ui&&frames[1])||frames[0];var Xrm=frm.Xrm;if(!Xrm||!Xrm.Page||!Xrm.Page.ui){alert('Unable to find CRM form');return;}Xrm.Page.ui.tabs.forEach(function(tab){tab.setVisible(true);tab.sections.forEach(function(section){section.setVisible(true);});});var $=frm.jQuery||(frm.CEI&&frm.CEI.$);if(!$){var head=frm.document.getElementsByTagName('head').item(0);var s=frm.document.createElement('script');s.setAttribute('type','text/javascript');s.setAttribute('src','https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js');s.async=false;head.appendChild(s);waitForJQ();}else{setLabels();}function waitForJQ(){if(frm.jQuery){$=frm.jQuery.noConflict(true);setLabels();}else{setTimeout(waitForJQ,1000);}}function setLabels(){Xrm.Page.data.entity.attributes.forEach(function(a){a.controls.forEach(function(c){var lblText=c.getLabel();c.setVisible(true);var attr=a.getName();var lbl=$('#'+c.getName()+'_c').html('');lbl.css('text-align','left');if(lbl.is('td')){lbl.closest('table').children('colgroup').children('col:even').attr('width','400');}$('<input/>').width(200).val(attr).appendTo(lbl).focus(function(){$(this).select()});$('<span></span>').text(lblText).appendTo(lbl);});});}})();


Custom Workflow

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Activities;
using System.Text.RegularExpressions;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Workflow;


namespace CustomWorkflow
{
    public class CustomWorkflowClass : CodeActivity
    {
        protected override void Execute(CodeActivityContext context)
        {
            IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
            // Use the context service to create an instance of IOrganizationService.
            IOrganizationService _orgService = serviceFactory.CreateOrganizationService(workflowContext.InitiatingUserId);

            Entity ent = new Entity("contact");
            ent.Attributes["firstname"] = "wwww";
            ent.Attributes["lastname"] = "fff";
           Guid guid= _orgService.Create(ent);
            //ITracingService tracer = context.GetExtension<ITracingService>();
            //Entity email = (Entity)workflowContext.InputParameters["Target"];
           
        }

    }
}

Plugin sample Code

using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Plugin_Sample
{
    public class PluginClass1 : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);
            IOrganizationService service1 = (IOrganizationService)serviceProvider.GetService(typeof(IOrganizationService));
            if (context.InputParameters != null)
            {
                Entity ent = new Entity(context.PrimaryEntityName);
                ent.Attributes["firstname"] = "aaa";
                ent.Attributes["lastname"] = "bbb";
                Guid guid = service.Create(ent);

            }
        }
    }
}

No comments:

Post a Comment

Web Resource vs PCF vs Canvas App - which of the one is used?

While started working on specific Business Requirements related to custom layout, there is a always common question that "where to star...