EnVisageOnline/Main/Source/EnVisage/Code/Integration/CRM2016.cs

413 lines
19 KiB
C#

using EnVisage.Code.BLL;
using EnVisage.Controllers;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace EnVisage.Code.Integration
{
public class CRM2016 : CrmAccess
{
Logger _Logger = LogManager.GetCurrentClassLogger();
private string HostUrl { get; set; }
public CRM2016()
{
HostUrl = HttpContext.Current.Request.Url.Host;
}
private OrganizationService Connect()
{
_Logger.Log(NLog.LogLevel.Debug, "Connecting to crm system");
IntegrationManager man = new IntegrationManager(new EnVisageEntities());
var model = man.getCrmModel(HostUrl);
if (model == null)
return null;
string connectionString = "Url=" + model.CrmUrl + "; Username=" + model.CrmUserId + "; Password=" + model.DecodedPassword + ";";
_Logger.Log(NLog.LogLevel.Debug, "Connection info: " + connectionString.Replace(model.DecodedPassword, model.Password));
CrmConnection connection = CrmConnection.Parse(connectionString);
OrganizationService organisationservice = new OrganizationService(connection);
return organisationservice;
}
public override void Update(string CRMEntityName, string CRMAttrabuteName, object PrevuValue, Guid CRMEntityId)
{
try
{
OrganizationService organisationservice = Connect();
if (organisationservice != null)
{
var EntityToUpdate = organisationservice.Retrieve(CRMEntityName, CRMEntityId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
var orginalValue = EntityToUpdate.GetAttributeValue(CRMAttrabuteName);
if (orginalValue != PrevuValue)
{
EntityToUpdate.SetAttributeValue(CRMAttrabuteName, PrevuValue);
EntityToUpdate.SetAttributeValue("icmc_discoveryactualend", ((DateTime) PrevuValue).AddDays(100));
organisationservice.Update(EntityToUpdate);
}
}
else
{
_Logger.Log(NLog.LogLevel.Debug, "Failed to Connect to remote crm");
}
}
catch (Exception dd)
{
var sb = DateTime.Now.ToString() + ": " + dd.Message;
sb += Environment.NewLine + dd.ToString();
var logger = LogManager.GetCurrentClassLogger();
if (logger != null)
logger.Fatal(sb.ToString());
}
}
public override void Update(string CRMEntityName, Dictionary<string, object> Data, Guid CRMEntityId)
{
try
{
OrganizationService organisationservice = Connect();
if (organisationservice != null)
{
var EntityToUpdate = organisationservice.Retrieve(CRMEntityName, CRMEntityId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
foreach (string key in Data.Keys)
{
string CRMAttrabuteName = key;
object PrevuValue = Data[key];
var orginalValue = EntityToUpdate.GetAttributeValue(CRMAttrabuteName);
if (orginalValue != PrevuValue)
{
EntityToUpdate.SetAttributeValue(CRMAttrabuteName, PrevuValue);
}
}
organisationservice.Update(EntityToUpdate);
}
else
{
_Logger.Log(NLog.LogLevel.Debug, "Failed to Connect to remote crm");
}
}
catch (Exception dd)
{
var sb = DateTime.Now.ToString() + ": " + dd.Message;
sb += Environment.NewLine + dd.ToString();
var logger = LogManager.GetCurrentClassLogger();
if (logger != null)
logger.Fatal(sb.ToString());
}
}
public override void Update(Dictionary<string, Dictionary<string, object>> updateCollection, Guid CRMEntityId)
{
try
{
OrganizationService organisationservice = Connect();
if (organisationservice != null)
{
foreach (string key in updateCollection.Keys)
{
string CRMEntityName = key;
Dictionary<string, object> Data = updateCollection[key];
try
{
var EntityToUpdate = organisationservice.Retrieve(CRMEntityName, CRMEntityId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
foreach (string crmCol in Data.Keys)
{
string CRMAttrabuteName = crmCol;
object PrevuValue = Data[crmCol];
var orginalValue = EntityToUpdate.GetAttributeValue(CRMAttrabuteName);
if (orginalValue != PrevuValue)
{
EntityToUpdate.SetAttributeValue(CRMAttrabuteName, PrevuValue);
}
}
organisationservice.Update(EntityToUpdate);
}
catch (Exception dd)
{
var sb = DateTime.Now.ToString() + ": " + dd.Message;
sb += Environment.NewLine + dd.ToString();
var logger = LogManager.GetCurrentClassLogger();
if (logger != null)
logger.Fatal(sb.ToString());
}
}
}
else
{
_Logger.Log(NLog.LogLevel.Debug, "Failed to Connect to remote crm");
}
}
catch (Exception dd)
{
var sb = DateTime.Now.ToString() + ": " + dd.Message;
sb += Environment.NewLine + dd.ToString();
var logger = LogManager.GetCurrentClassLogger();
if (logger != null)
logger.Fatal(sb.ToString());
}
}
public override void create(Dictionary<string, Dictionary<string, object>> updateCollection)
{
try
{
OrganizationService organisationservice = Connect();
if (organisationservice != null)
{
foreach (string key in updateCollection.Keys)
{
string CRMEntityName = key;
Dictionary<string, object> Data = updateCollection[key];
try
{
var EntityToCreate = new Microsoft.Xrm.Sdk.Entity(CRMEntityName); //organisationservice.Retrieve(CRMEntityName, CRMEntityId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));
foreach (string crmCol in Data.Keys)
{
string CRMAttrabuteName = crmCol;
object PrevuValue = Data[crmCol];
KeyValuePair<string, object> attb = new KeyValuePair<string, object>(CRMAttrabuteName, PrevuValue);
EntityToCreate.Attributes.Add(attb);
}
organisationservice.Create(EntityToCreate);
}
catch (Exception dd)
{
var sb = DateTime.Now.ToString() + ": " + dd.Message;
sb += Environment.NewLine + dd.ToString();
var logger = LogManager.GetCurrentClassLogger();
if (logger != null)
logger.Fatal(sb.ToString());
}
}
}
else
{
_Logger.Log(NLog.LogLevel.Debug, "Failed to Connect to remote crm");
}
}
catch (Exception dd)
{
var sb = DateTime.Now.ToString() + ": " + dd.Message;
sb += Environment.NewLine + dd.ToString();
var logger = LogManager.GetCurrentClassLogger();
if (logger != null)
logger.Fatal(sb.ToString());
}
}
public override void RemoveResouceFromProject(string CRMEntityName,Guid CRMProjectNumber,string ResouceEmail)
{
_Logger.Log(NLog.LogLevel.Debug, "Removing resource Project number"+ CRMProjectNumber.ToString()+" Resource:"+ ResouceEmail);
try
{
OrganizationService organisationservice = Connect();
if (organisationservice != null)
{
Guid ResoueceId = GetContactID(ResouceEmail);
if (ResoueceId == Guid.Empty)
return;
Guid IdToDelete = GetProjectToResouceID(ResoueceId, CRMProjectNumber, CRMEntityName);
if (IdToDelete == Guid.Empty)
return;
organisationservice.Delete(CRMEntityName, IdToDelete);
}
else
{
_Logger.Log(NLog.LogLevel.Debug, "Failed to Connect to remote crm");
}
}
catch (Exception dd)
{
var sb = DateTime.Now.ToString() + ": " + dd.Message;
sb += Environment.NewLine + dd.ToString();
var logger = LogManager.GetCurrentClassLogger();
if (logger != null)
logger.Fatal(sb.ToString());
}
}
public override void addResourceToProject(string CRMEntityName, Dictionary<string, string> resourceData, Guid CRMParentEntityId)
{
try
{
OrganizationService organisationservice = Connect();
if (organisationservice != null)
{
try
{
var EntityToCreate = new Microsoft.Xrm.Sdk.Entity(CRMEntityName);
foreach (string crmCol in resourceData.Keys)
{
string CRMAttrabuteName = crmCol;
string PrevuValue = resourceData[crmCol];
KeyValuePair<string, object> attb;
if (CRMAttrabuteName.ToLower().Trim() == "icmc_stakeholder")
{
Guid GuidUserID = GetContactID(PrevuValue);
if (GuidUserID != Guid.Empty)
{
_Logger.Log(NLog.LogLevel.Debug, "Adding resource Project number" + CRMParentEntityId.ToString() + " Resource:" + PrevuValue + "/" + GuidUserID);
//attb = new KeyValuePair<string, object>(CRMAttrabuteName, GuidUserID);
var StakeHolderEf = new EntityReference("contact", GuidUserID);
EntityToCreate.SetAttributeValue(CRMAttrabuteName, StakeHolderEf);
//check to see if the resouce is already assigned to the project in client connect.
//if they are just return.
Guid IdToCreate = GetProjectToResouceID(GuidUserID, CRMParentEntityId, CRMEntityName);
if (IdToCreate != Guid.Empty)
{
_Logger.Log(NLog.LogLevel.Debug, "Resource record already exist for project");
return;
}
}
else
{
_Logger.Log(NLog.LogLevel.Debug, "Resource record not found in CRM for" + PrevuValue );
return;
}
}
else if (CRMAttrabuteName.ToLower().Trim() == "icmc_integratedteamrole")
{
OptionSetValue optionSet = new OptionSetValue();
optionSet.Value = getOptionSetValue(CRMEntityName,CRMAttrabuteName, PrevuValue); // 812420001;
EntityToCreate.SetAttributeValue(CRMAttrabuteName, optionSet);
}
}
var initiative = new EntityReference("new_project", CRMParentEntityId);
EntityToCreate.SetAttributeValue("icmc_initiative", initiative);
_Logger.Log(NLog.LogLevel.Debug, "Creating entity record");
organisationservice.Create(EntityToCreate);
}
catch (Exception dd)
{
var sb = DateTime.Now.ToString() + ": " + dd.Message;
sb += Environment.NewLine + dd.ToString();
var logger = LogManager.GetCurrentClassLogger();
if (logger != null)
logger.Fatal(sb.ToString());
}
}
else
{
_Logger.Log(NLog.LogLevel.Debug, "Failed to Connect to remote crm");
}
}
catch (Exception dd)
{
var sb = DateTime.Now.ToString() + ": " + dd.Message;
sb += Environment.NewLine + dd.ToString();
var logger = LogManager.GetCurrentClassLogger();
if (logger != null)
logger.Fatal(sb.ToString());
}
}
private Guid GetContactID(string emailAddress)
{
var userid = Guid.Empty;
OrganizationService organisationservice = Connect();
if (organisationservice != null)
{
QueryExpression query = new QueryExpression
{
EntityName = "contact",
ColumnSet = new ColumnSet("emailaddress1"),
Criteria = new FilterExpression
{
Filters ={
new FilterExpression{
Conditions ={
new ConditionExpression("emailaddress1", ConditionOperator.Equal, emailAddress)
}
}
}
}
};
var contactEntity=organisationservice.RetrieveMultiple(query).Entities.FirstOrDefault();
if (contactEntity != null)
userid = (Guid) contactEntity.GetAttributeValue("contactid");
else
userid = Guid.Empty;
}
return userid;
}
private Guid GetProjectToResouceID(Guid ResourceID,Guid ProjectId, string CRMEntityName)
{
var id = Guid.Empty;
OrganizationService organisationservice = Connect();
if (organisationservice != null)
{
QueryExpression query = new QueryExpression
{
EntityName = CRMEntityName,
ColumnSet = new ColumnSet(true),
Criteria = new FilterExpression
{
Filters ={
new FilterExpression{
Conditions ={
new ConditionExpression("icmc_stakeholder", ConditionOperator.Equal, ResourceID)
}
},
new FilterExpression{
Conditions ={
new ConditionExpression("icmc_initiative", ConditionOperator.Equal, ProjectId)
}
}
}
}
};
var P2Rs = organisationservice.RetrieveMultiple(query).Entities.FirstOrDefault();
if (P2Rs != null)
id = (Guid) P2Rs.Id;
else
id = Guid.Empty;
}
return id;
}
public int getOptionSetValue(string entityName, string attributeName, string optionsetText)
{
_Logger.Log(NLog.LogLevel.Debug, "Getting index value for "+ attributeName +" Value Text:"+ optionsetText);
int optionSetValue = 0;
OrganizationService organisationservice = Connect();
RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = entityName;
retrieveAttributeRequest.LogicalName = attributeName;
retrieveAttributeRequest.RetrieveAsIfPublished = true;
RetrieveAttributeResponse retrieveAttributeResponse =
(RetrieveAttributeResponse) organisationservice.Execute(retrieveAttributeRequest);
PicklistAttributeMetadata picklistAttributeMetadata =
(PicklistAttributeMetadata) retrieveAttributeResponse.AttributeMetadata;
OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;
foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
{
if (optionMetadata.Label.UserLocalizedLabel.Label.ToLower() == optionsetText.ToLower())
{
optionSetValue = optionMetadata.Value.Value;
return optionSetValue;
}
}
_Logger.Log(NLog.LogLevel.Debug, "Index not found value for " + attributeName + " Value Text:" + optionsetText);
return optionSetValue;
}
}
}