using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Win32;
namespace Microsoft.Crm {
public class ServiceActivityClosedHandler :IPlugin {
/// <summary>
/// Deze methode zal een crmservice aamaken.
/// Ik moet het via deze methode doen, omdat Icrmservice niet toegelaten wordt
/// in de child pipeline.
/// </summary>
/// <param name="context">De context dat de plugin gekregen heeft.</param>
/// <param name="flag">Met welke gebruiker moet de service aangemaakt worden.</param>
/// <returns>De aangemaakte service.</returns>
private CrmService CreateCrmService(IPluginExecutionContext context, Boolean flag) {
var authToken = new CrmAuthenticationToken { AuthenticationType = 0, OrganizationName = context.OrganizationName, CallerId = (flag ? context.UserId : context.InitiatingUserId) };
var corToken = new CorrelationToken { CorrelationId = context.CorrelationId, CorrelationUpdatedTime = context.CorrelationUpdatedTime, Depth = context.Depth };
var regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM", false);
var service = new CrmService {
CrmAuthenticationTokenValue = authToken,
UseDefaultCredentials = true,
Url = String.Concat(regkey.GetValue("ServerUrl").ToString(), "/2007/crmservice.asmx"),
CorrelationTokenValue = corToken
};
return service;
}
/// <summary>
/// Via deze methode haal je alle info op vanuit een service activiteit.
/// </summary>
/// <param name="ActvId">De ID van de service activiteit dat je wil ophalen.</param>
/// <param name="service">De service die een connectie naar databank mogelijk maakt.</param>
/// <returns></returns>
private DynamicEntity RetrieveActivity(Guid ActvId , CrmService service) {
// Filter instellen
ConditionExpression con = new ConditionExpression();
con.AttributeName = "activityid";
con.Operator = ConditionOperator.Equal;
con.Values = new string[] { ActvId.ToString() };
// Filter toevoegen
FilterExpression filter = new FilterExpression();
filter.FilterOperator = LogicalOperator.And;
filter.AddCondition(con);
// Query maken
QueryExpression query = new QueryExpression();
query.EntityName = "serviceappointment";
query.ColumnSet = new AllColumns();
query.Criteria = filter;
// Databank bevragen
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
retrieve.ReturnDynamicEntities = true;
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)service.Execute(retrieve);
// Terug geven
if (retrieved.BusinessEntityCollection.BusinessEntities.Count == 1) {
return (DynamicEntity)retrieved.BusinessEntityCollection.BusinessEntities[0];
} else {
return null;
}
}
/// <summary>
/// Als je een serviceactiviteit beëindigd, dan moet hij een nieuw
/// tijdregistratie aanmaken met de gegevens uit serviceactiviteit.
/// </summary>
/// <param name="context">de meegegeven properties van het formulier</param>
public void Execute(IPluginExecutionContext context) {
// Variable serviceappointment
DynamicEntity entity = null;
// Check whether the input parameters property bag contains a target
// of the create operation and that target is of type DynamicEntity.
if (context.InputParameters.Properties.Contains("Target") &&
context.InputParameters.Properties["Target"] is DynamicEntity) {
// Obtain the target business entity from the input parmameters.
entity = (DynamicEntity)context.InputParameters.Properties["Target"];
// Verify that the entity represents an serviceappointment.
if (entity.Name != EntityName.serviceappointment.ToString()) { return; }
// Kijken of de serviceappointment gecomplete wordt.
if (!entity.Properties.Contains("statuscode")) { return; }
if (((Status)entity.Properties["statuscode"]).Value != 8) { return; }
} else { return; }
// Checken of state gelijk is aan
try {
// aanmaken nieuwe entiteit tijdregistratiebestand
DynamicEntity new_tijd = new DynamicEntity();
// Naam van entiteit
new_tijd.Name = "new_timeregistration";
// Properties toevoegen
new_tijd.Properties = new PropertyCollection();
// Activiteit ophalen
DynamicEntity actv = RetrieveActivity(new Guid(((Key)entity.Properties["activityid"]).Value.ToString()), CreateCrmService(context, true));
// Begintijd
new_tijd.Properties.Add(new CrmDateTimeProperty("new_regstart", (CrmDateTime)actv.Properties["scheduledstart"]));
// Eindtijd
new_tijd.Properties.Add(new CrmDateTimeProperty("new_regend", (CrmDateTime)actv.Properties["scheduledend"]));
// Verplaatsing
new_tijd.Properties.Add(new CrmBooleanProperty("new_transportation", new CrmBoolean(true)));
// Klant
if (actv.Properties.Contains("customers")) {
Lookup lo = new Lookup();
DynamicEntity[] ctms = (DynamicEntity[])(actv.Properties["customers"]);
lo.Value = ((Lookup)ctms[0].Properties["partyid"]).Value;
lo.type = EntityName.account.ToString();
new_tijd.Properties.Add(new LookupProperty("new_accountid", lo));
}
// Factureren tijd
double facturatie = 100.0;
new_tijd.Properties.Add(new CrmFloatProperty("new_invoicetime", new CrmFloat(facturatie)));
// Beschrijving
new_tijd.Properties.Add(new StringProperty("new_desc", "Aangemaakt via crm plugin."));
// adhv Dynamic class kan ik deze entiteit toevoegen
TargetCreateDynamic targetCreate = new TargetCreateDynamic();
targetCreate.Entity = new_tijd;
// Create the request object.
CreateRequest create = new CreateRequest();
create.Target = targetCreate;
// Execute the request.
CrmService service = CreateCrmService(context, true);
CreateResponse created = (CreateResponse)service.Execute(create);
} catch (System.Web.Services.Protocols.SoapException) {
//Exception handling
throw;
} catch (Exception) {
//Exception handling
throw;
}
}
}
}