Skip to main content

Dynamic 365 CRUD Operation with non relational entity from Plugin

By default in to plugin a entity we can access entity and its relational entity.
If we want to access a non relational entity we need to use XrmServiceContext.




 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.ServiceModel;  
 using Microsoft.Xrm.Sdk;  
 using Microsoft.Xrm.Sdk.Query;  
 namespace TotalBudget.Plugins  
 {  
   /// <summary>  
   /// In order to generate Early Bounded Class, dont need to pass any credential for Active directoy authentication  
   /// CrmSvcUtil.exe /url:http://yourdonain/XRMServices/2011/Organization.svc /domain:yourdomain /out:"EarlyBoundedEntities.cs" /namespace:TotalBudget.Plugins /servicecontextname:XrmServiceContext  
   /// </summary>  
   public class TotalBudgetCalculation : IPlugin  
   {  
     // Global variable  
     Guid _AccountId;  
     int _currencyTypeId;  
     int _year;  
     decimal _gesumBudget;  
     List<TotalBudgetCurrency> _TotalBudgetCurrencyList = new List<TotalBudgetCurrency>();  
     public class TotalBudgetCurrency {  
       public int Year { get; set; }  
       public int YearValue { get; set; }  
     }  
     public void Execute(IServiceProvider serviceProvider)  
     {  
       // Obtain the tracing service  
       ITracingService tracingService =  
       (ITracingService)serviceProvider.GetService(typeof(ITracingService));  
       IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));  
       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)  
       {  
         // Obtain the target entity from the input parameters.   
         var entity_planungeinkauf = ((Entity)context.InputParameters["Target"] as Entity).ToEntity<tmg_planungeinkauf>();  
         try  
         {  
           // Read data according to attribute  
           var accountId = ((EntityReference)(entity_planungeinkauf.Attributes["tmg_agentur"])).Id;  
           var currency = (entity_planungeinkauf.GetAttributeValue<OptionSetValue>("tmg_waehrung")).Value;  
           var year = (entity_planungeinkauf.GetAttributeValue<DateTime>("tmg_auftrageingang"));  
           var gesumBudget = (entity_planungeinkauf.GetAttributeValue<decimal>("tmg_gesamtbudgetnnfreigabe"));  
           // if date field tmg_auftrageingang has no value then will retun.  
           if (year == DateTime.MinValue)  
             return;  
           // set value in to global variable  
           _AccountId = accountId;  
           _currencyTypeId = currency;  
           _year = year.Year;  
           _gesumBudget = gesumBudget;  
           #region Retrieve data from Planungeinkauf  
           // Load currency List  
           LoadTotalBudgetCurrencyList();  
           // Get all tmg_planungeinkauf data with account id, year and currency type  
           var quer_tmg_planungeinkauf = Query_tmg_planungeinkauf(entity_planungeinkauf);  
           DataCollection<Entity> entityCollection = service.RetrieveMultiple(quer_tmg_planungeinkauf).Entities;  
           List<tmg_planungeinkauf> tmg_planungeinkaufList = new List<tmg_planungeinkauf>();  
           foreach (tmg_planungeinkauf planungeinkauf in entityCollection)  
           {  
             tmg_planungeinkaufList.Add(planungeinkauf);  
           }  
           decimal totalBudget = 0;  
           totalBudget = tmg_planungeinkaufList.Sum(x => Convert.ToDecimal(x.tmg_gesamtbudgetnnfreigabe));  
           #endregion  
           # region Retrieve data from Gesumpt Budget  
           // Update new_arch_geamtbudgetSet entity with account Id, year and currency id  
                          // Non relational entity   
           using (var xrmServiceContext = new XrmServiceContext(service))  
           {  
             TotalBudgetCurrency TotalBudgetCurrency = _TotalBudgetCurrencyList.First(x => x.Year == _year);  
             // Get filtered record from geamtbudget using proxy context  
             new_arch_geamtbudget filtered_geamtbudget = xrmServiceContext.new_arch_geamtbudgetSet.Where(v =>v.new_arch_Firma.Id == _AccountId  
                                    && v.new_arch_Wahrung.Value == _currencyTypeId  
                                    && v.new_arch_Jahr.Value == TotalBudgetCurrency.YearValue).FirstOrDefault();  
             // Check Any geamtbudget Data Exist or not  
             if (filtered_geamtbudget == null)  
             {  
               // If data not exist new record will insert in to TotalBudget  
               var filtered_geamtbudget_new = new new_arch_geamtbudget  
               {  
                 new_arch_Firma = new EntityReference { Id = _AccountId },  
                 new_arch_Jahr = new OptionSetValue(TotalBudgetCurrency.YearValue),  
                 new_arch_Wahrung = new OptionSetValue(_currencyTypeId),  
                 new_arch_GesamtbudgetRollUp = _gesumBudget  
               };  
               xrmServiceContext.AddObject(filtered_geamtbudget_new);  
               xrmServiceContext.SaveChanges();  
             }  
             else  
             {  
               // If record exist with AccountId, year and currency Id then it will calculate  
               // Total tmg_gesamtbudgetnnfreigabe for this account from tmg_planungeinkauf entity  
               filtered_geamtbudget.new_arch_GesamtbudgetRollUp = totalBudget;  
               xrmServiceContext.UpdateObject(filtered_geamtbudget);  
               xrmServiceContext.SaveChanges();  
             }  
           }  
           #endregion  
         }  
         catch (FaultException<OrganizationServiceFault> ex)  
         {  
           throw new InvalidPluginExecutionException("An error occurred in FollowUpPlugin.", ex);  
         }  
         catch (Exception ex)  
         {  
           tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());  
           throw;  
         }  
       }  
     }  
     // From date field tmg_auftrageingang it will set option set value of year  
     // Load zear and option set value year 2017 to 2025  
     private void LoadTotalBudgetCurrencyList()  
     {  
       _TotalBudgetCurrencyList = new List<TotalBudgetCurrency>();  
       TotalBudgetCurrency TotalBudget = new TotalBudgetCurrency();  
       TotalBudget.Year = 2017;  
       TotalBudget.YearValue = 100000000;  
       _TotalBudgetCurrencyList.Add(TotalBudget);  
       TotalBudget = new TotalBudgetCurrency();  
       TotalBudget.Year = 2018;  
       TotalBudget.YearValue = 100000001;  
       _TotalBudgetCurrencyList.Add(TotalBudget);  
       TotalBudget = new TotalBudgetCurrency();  
       TotalBudget.Year = 2019;  
       TotalBudget.YearValue = 100000002;  
       _TotalBudgetCurrencyList.Add(TotalBudget);  
     }  
     // Querz in to tmg_planungeinkauf entitz that will return all data with AccountId, Currency and year parameter  
     public QueryBase Query_tmg_planungeinkauf(Entity entity)  
     {  
       // Build query expression  
       QueryExpression query = new QueryExpression()  
       {  
         Distinct = false,  
         EntityName = entity.LogicalName,  
         ColumnSet = new ColumnSet("tmg_auftrageingang", "tmg_gesamtbudgetnnfreigabe", "tmg_waehrung", "tmg_auftrageingang"),  
         Criteria =  
         {  
           Filters =  
           {  
             new FilterExpression  
             {  
               FilterOperator = LogicalOperator.And,  
               Conditions =  
               {  
                 new ConditionExpression("tmg_agentur", ConditionOperator.Equal, _AccountId),  
                 new ConditionExpression("tmg_waehrung", ConditionOperator.Equal, _currencyTypeId),  
                 new ConditionExpression("tmg_gesamtbudgetnnfreigabe", ConditionOperator.NotNull),  
                 new ConditionExpression("tmg_auftrageingang", ConditionOperator.Equal, _year)  
               },  
             }  
           }  
         }  
       };  
       return query;  
     }  
   }  
 }  

Comments

Popular posts from this blog

C# run powershell script as administrator

Recently I was fetching a problem that I need to run a PowerShell script that will change TFS user Display name and SID. I was trying to run that script from C# that was not working due to TFS security update and TLS certificate. Using this code block I resolve the Issue. var newProcessInfo = new System.Diagnostics.ProcessStartInfo(); newProcessInfo.FileName = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe"; newProcessInfo.Verb = "runas"; // Define Run as administrator newProcessInfo.Arguments = script; //Define your powershell script newProcessInfo.UseShellExecute = false; newProcessInfo.RedirectStandardOutput = true; // This will enable to read Powershell run output newProcessInfo.RedirectStandardError = true; Process proces = System.Diagnostics.Process.Start(newProcessInfo); proces.WaitForExit(); // I want to read the output string from powershell window StringBuilder output = new StringBuilder(); output.Append("Started"); while (!proces.St

ASP.NET MVC razor SAP Crystal report

Crete a new project: Add a aspx Master Page Create a new folder Reports and 2 sub folder crystal & crystalviewer Now add a web form page in crystalviewer  folder. Add the master page namespace in your web form page. MasterPageFile ="~/Views/Shared/ReportSite.Master" Replace your web form by this code < asp : Content ID ="Content1" ContentPlaceHolderID ="ContentPlaceHolder1" runat ="server">      </ asp : Content > Now go to design mode of your web form drag & drop the crystal report viewer in your web form. After that your page will be look look like this. Replace the code: < CR : CrystalReportViewer ID ="EmployeeList" runat ="server"   HasCrystalLogo ="False"     AutoDataBind ="True"   Height ="50px"   EnableParameterPrompt ="false" EnableDatabaseLogonPrompt

mvc razor textboxfor change event change another textboxfor value

Based on value of Weight, Rate , CNF & AWB it will change the value of Freight , TTLCNF anfd TTLFright . Freight= Weight*Rate; TTLCNF  = Weight*CNF; TTLFright=  Freight+ TTLCNF  + AWB; @Html.TextBoxFor(model => model.Weight, new { onChange="return GetWight(this);"}) @Html.TextBoxFor(model => model.Rate, new { onChange="return GetWight(this);"})/Kg @Html.TextBoxFor(model => model.Freight, new {disabled = "disabled" , @readonly = "readonly" ,onChange="return GetTTLFright(this);"}) @Html.TextBoxFor(model => model.CNFPK, new { onChange="return GetCNFPK(this);"}) @Html.TextBoxFor(model => model.TTLCNF, new {disabled = "disabled" , @readonly = "readonly",onChange="return GetTTLFright(this);" }) @Html.TextBoxFor(model => model.AWB, new { onChange="return GetTTLFright(this);"}) and script <script> function GetW