How to get and set values in plugins?

 

How to get and set values in plugins? 

Ans.

 using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.IO;

using System.Linq;

using System.Net.NetworkInformation;

using System.Text;

using System.Threading.Tasks;

using System.Xml.Linq;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Messages;

using Microsoft.Xrm.Sdk.Metadata;


namespace DatatypesPlugin

{

    public class UpdateData : IPlugin

    {

        public void Execute(IServiceProvider serviceProvider)

        

        

        {

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

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

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

            ITracingService tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

           

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

            {

                try

                {

                    Entity primaryEntity = (Entity)context.InputParameters["Target"] as Entity;


                    //EntityReference lookupref = primaryEntity.ToEntityReference();

                    //string Acname = lookupref.Name;

                    //Guid lookupID = lookupref.Id;

                    //string logicalname = lookupref.LogicalName;


                    EntityReference lookup = primaryEntity.Contains("effizz_customjs") ? (EntityReference)primaryEntity["effizz_customjs"] : null;// by entity reference , 

                    if (lookup != null)

                    {

                        string name = lookup.Name;

                        tracing.Trace("lookup name:{0}", name);

                        Guid lookupID = lookup.Id;

                        tracing.Trace("lookup id:{0}", lookupID.ToString());

                        string logicalname = lookup.LogicalName;

                    }

                    //set lookup

                    EntityReference lookup1 = new EntityReference("effizz_customjs", new Guid("2fef6f61-166c-ee11-8178-000d3a0aabb1"));

                    primaryEntity["effizz_valueac"] =lookup1;


                    //SINGLE LINE TEXT GET

                    string localname = primaryEntity.Contains("effizz_name") ? (string)primaryEntity["effizz_name"] : null;

                    if (localname != null)

                    {

                        tracing.Trace(localname);

                    }


                    //SINGLE LINE TEXT SET

                    string Name = "kiran";

                    primaryEntity["effizz_name"]=Name;

                    tracing.Trace("the name is :{0}", Name.ToString());


                    //MULTI LINE TEXT GET

                    string byDescription  = primaryEntity.Contains("effizz_description") ? (string)primaryEntity["effizz_description"] : null;

                    if (byDescription != null)

                    {

                        tracing.Trace(byDescription);

                    }


                    //MULTI LINE TEXT SET

                    string descript = "Dynamics 365 is a portfolio of intelligent business applications that delivers superior operational efficiency and breakthrough customer experiences enabling businesses to become more agile and reduce complexity without increasing costs.\r\n\r\n Watch some d365 videos for an overview \r\n\r\n https://youtu.be/J5LdJXI9K1g?si=OenT-7JDffYJoh52";

                    primaryEntity["effizz_description"] = descript;

                    tracing.Trace("the Description is :{0}", descript.ToString());


                    // OPTION SET GET


                    OptionSetValue courses = primaryEntity.Contains("effizz_courses") ? (OptionSetValue)primaryEntity["effizz_courses"] : null;

                    if (courses != null)

                    {

                        tracing.Trace("courses is:{0}", courses.Value);

                    }

                    // OPTION SET SET

                    OptionSetValue courses1 = new OptionSetValue(684200001);

                    primaryEntity["effizz_courses"] = courses1;

                    tracing.Trace("courses1 is:{0} ", courses1.Value);



                    // MULTI SEELCT OPTION GET


                    OptionSetValueCollection collectSubjects = primaryEntity.Contains("effizz_subjects") ? (OptionSetValueCollection)primaryEntity["effizz_subjects"] : null;

                    if (collectSubjects != null)

                    {

                        OptionSetValueCollection sub = (OptionSetValueCollection)primaryEntity["effizz_subjects"];

                        foreach (var item in sub)

                        {

                            tracing.Trace("sub is{0}", item.Value);

                        }

                    }

                    // MULTI SELECT OPTION SET


                    int[] collectSubjects1 = { 684200002, 684200003, 684200001 };

                    OptionSetValueCollection sub1 = new OptionSetValueCollection();


                    foreach (var item in collectSubjects1)

                    {


                        sub1.Add(new OptionSetValue(item));

                        //tracing.Trace("no of sub1 :{0}", sub1.Count);

                    }

                    primaryEntity["effizz_subjects"] = sub1;

                    tracing.Trace("no of sub1 :{0}", sub1.Count);

                    //tracing.Trace("no of sub1 :{0}", sub1.Count);


                    string attributeName = "effizz_subjects";


                    if (primaryEntity.Attributes.Contains(attributeName))

                    {

                        // Retrieve the selected option set values.

                        OptionSetValueCollection selectedValues = primaryEntity.GetAttributeValue<OptionSetValueCollection>(attributeName);

                        RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest

                        {

                            EntityLogicalName = primaryEntity.LogicalName,

                            LogicalName = attributeName,

                            RetrieveAsIfPublished = true

                        };


                        RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);

                        MultiSelectPicklistAttributeMetadata optionSetMetadata = (MultiSelectPicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;


                        foreach (OptionSetValue selectedValue in selectedValues)

                        {

                            var option = optionSetMetadata.OptionSet.Options.FirstOrDefault(obj => obj.Value == selectedValue.Value);

                            if (option != null)

                            {

                                string label = option.Label.UserLocalizedLabel.Label;

                                tracing.Trace("The MultiOptions are {0}", label);


                            }

                        }


                    }


                    // TWO OPTION GET


                    bool extraclass = primaryEntity.Contains("effizz_extraclass") ? (bool)primaryEntity["effizz_extraclass"] : true;


                    if (extraclass != true)

                    {

                        tracing.Trace("The Extraclass is : {0}", extraclass.ToString());

                    }


                    // TWO OPTION SET


                    bool extraclass1 = new bool();

                    extraclass1 = true;

                    primaryEntity["effizz_extraclass"] = extraclass1;

                    tracing.Trace(" The Extraclass is :{0}", extraclass1);


                    // DECIMAL GET


                    decimal Content = primaryEntity.Contains("effizz_deccontent") ? (decimal)primaryEntity["effizz_deccontent"] : 0;

                    if (Content != 0)

                    {

                        tracing.Trace("you are{0}", Content.ToString());

                    }


                    // DECIMAL SET

                    

                    decimal ContentTo = new decimal();

                    ContentTo = -85;

                    primaryEntity["effizz_deccontent"] = ContentTo;

                    tracing.Trace("ranges is :{0} ", ContentTo);


                    //FLOAT GET


                    double Flow = primaryEntity.Contains("effizz_mildflow") ? (double)primaryEntity["effizz_mildflow"] : 0;


                    if (Flow != 0)

                    {

                        tracing.Trace("Flow is : {0}", Flow.ToString());

                    }


                    // FLOAT SET


                    double FlowBy = 88.24;

                    primaryEntity["effizz_mildflow"] = FlowBy;

                    tracing.Trace("your Age is : {0} ", FlowBy);


                    // SET CURRENCY


                    Money Total = primaryEntity.Contains("effizz_totalamt") ? (Money)primaryEntity["effizz_totalamt"] : null;

                    if (Total != null)

                    {

                        tracing.Trace("Total is : {0}", Total.Value);

                    }


                    // GET CURRENCY 


                    Money totalAmount = new Money(200);

                    primaryEntity["effizz_totalamt"] = totalAmount;

                    tracing.Trace("The totalAmount is : {0}", totalAmount.Value);




                    //Money discount = new Money(100);

                    //primaryEntity["effizz_discountamount"] = discount;

                    //tracing.Trace("The totalAmount is : {0}", discount.Value);


                    //Money detailed = new Money(50);

                    //primaryEntity["effizz_finalamount"] = detailed;

                    //tracing.Trace("The totalAmount is : {0}", detailed.Value);


                    // WHOLE NUMBER GET


                    int WholeAmount = primaryEntity.Contains("effizz_amount") ? (int)primaryEntity["effizz_amount"] : 0;


                    if (WholeAmount != 0)

                    {

                        tracing.Trace("Amount is : {0}", WholeAmount.ToString());

                    }


                    // WHOLE NUMBER SET


                    int amount = 234;

                    primaryEntity["effizz_amount"] = amount;

                    tracing.Trace("The Amount is : {0} ", amount);


                    // DATE AND TIME GET


                    DateTime dateofTime = primaryEntity.GetAttributeValue<DateTime>("effizz_datetime");

                    if (dateofTime != null)

                    {

                        tracing.Trace("dateofTime is : {0}", dateofTime.ToString());

                    }


                    // DATE AND TIME SET


                    DateTime dateTime = new DateTime();

                    dateTime = DateTime.UtcNow;

                    primaryEntity["effizz_datetime"] = dateTime.AddDays(2);

                    tracing.Trace("The DateTime is : {0} ", dateTime);


                    //string filenew = @"File.ReadAllText(path)";

                    //string[] fileData;


                    //if (primaryEntity.Contains("effizz_fileee")) // Replace "new_fileattribute" with your attribute name

                    //{

                    //    fileData = primaryEntity.GetAttributeValue<string[]>("effizz_fileee"); // Replace "new_fileattribute" with your attribute name

                    //    You can now work with the file data in the 'fileData' byte array.

                    //}


                    //Entity entity = new Entity("your_entity_logical_name"); // Replace with the logical name of your entity.


                    ////string path = @"c:\temp\MyTest.txt";

                    //string filenew = @"ErrorDetails (9)";

                    //// Open the file to read from.

                    //string rd = File.ReadAllText(filenew);

                    //string[] rdr = File.ReadAllLines(filenew);


                    //fileData = rdr;


                    //entity["effizz_fileee"] = fileData; // Replace "new_fileattribute" with your attribute name

                    //service.Create(entity); // Create or update the entity with the updated file attribute



                }

                catch (Exception ex)

                {

                    throw new InvalidPluginExecutionException(string.Format("Error occured in the PreUpdateAccount plugin: {0}", ex.Message));

                }


            }

            

        }

    }          

}


Comments

Popular posts from this blog

If any case created, then check for the same user how many cases are created with in 30 days, if more than 2 and less than 5 send a mail to team lead, if more than 5 and less than 9 then send a mail to manager using power automate.

Create approve & reject ribbon buttons, once click on approve it should change the status field to approve.If clicked on reject it should change to Reject. Based on status field change trigger work flow to send a email to stating request is approved/Rejected.