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

WPF datagrid cell textbox change event

Entity/Class: public class FeesDetails : INotifyPropertyChanged { public int Id { get; set; } public string FeesName { get; set;} public string FeesDetailsName { get; set; } public int? PaidAmount { get; set; } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(System.String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } public int feesAmount { get; set; } public int FeesAmount { get { return this.feesAmount; } set { if (value != this.feesAmount) { this.feesAmount = value; NotifyPropertyChanged("FeesAmount"); } } } } XAML: <DataGrid AutoGenerateColumns="False" Height="21...

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...

mvvm double click event in listview

If you want to get the double click event on a listview item you can try with this code; <ListView Grid.Row="0" Grid.RowSpan="3" Grid.Column="0" Width="250" Height="200" HorizontalAlignment="Stretch" VerticalAlignment="Top" AlternationCount="2" BorderBrush="#FFA8CC7B" ItemContainerStyle="{StaticResource alternatingStyle}" ItemsSource="{Binding FromPayerNameList}" SelectedItem="{Binding SelectedFromPayer, Mode=TwoWay}"> <ListView.ItemTemplate> <DataTemplate> <TextBlock Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}" Text=...