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.
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
Post a Comment