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

The calling thread must be STA, because many UI components require this.

Using Thread: // Create a thread Thread newWindowThread = new Thread(new ThreadStart(() => { // You can use your code // Create and show the Window FaxImageLoad obj = new FaxImageLoad(destination); obj.Show(); // Start the Dispatcher Processing System.Windows.Threading.Dispatcher.Run(); })); // Set the apartment state newWindowThread.SetApartmentState(ApartmentState.STA); // Make the thread a background thread newWindowThread.IsBackground = true; // Start the thread newWindowThread.Start(); Using Task and Thread: // Creating Task Pool, Each task will work asyn and as an indivisual thread component Task[] tasks = new Task[3]; // Control drug data disc UI load optimize tasks[0] = Task.Run(() => { //This will handle the ui thread :The calling thread must be STA, because many U...

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

An error occurred while updating the entries. See the inner exception for details.

If you are using EF then you may get the error. This error is not specify where the error exactly occur in your table. To specify the error use this code & use debugger to see the exact error message. try { //Your code db = new FEDALIC_AGRI_DBEntities (); model.FarmerVillage = new Guid(village); model.FarmerThana = new Guid(thana); model.FarmerDistrict = new Guid(district); var _SET_FARMER_INFO = EMFermar.SetToModelObject(model); db.SET_FARMER_INFO.Add(_SET_FARMER_INFO); db.SaveChanges(); } catch (DbUpdateException e) { var innerEx = e.InnerException; while (innerEx.InnerException != null) innerEx = innerEx.InnerException; throw new Exception(innerEx.Message); } catch (DbEntityValidationException e...