#region Help: Introduction to the script task
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
using System.Runtime.Serialization;
using Microsoft.Xrm.Sdk.Messages;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace ST_08e8b41493e841ac8d78a1347d3fce79
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
IOrganizationService organizationservice;
string crmurl, crmpass, crmuser, error, result, Enseigne, API, URL;
public OrganizationServiceProxy ConnectToCrm()
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(crmurl));
AuthenticationCredentials authCredentials = new AuthenticationCredentials();
authCredentials.ClientCredentials.UserName.UserName = crmuser;
authCredentials.ClientCredentials.UserName.Password = crmpass;
AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials);
OrganizationServiceProxy organizationProxy = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);
organizationProxy.EnableProxyTypes();
return organizationProxy;
SqlConnection cnx = (SqlConnection)(Dts.Connections["campagne"].AcquireConnection(Dts.Transaction) as SqlConnection);
crmurl = Dts.Variables["CRMURL"].Value.ToString();
crmpass = Dts.Variables["CRMPASS"].Value.ToString();
crmuser = Dts.Variables["CRMUSER"].Value.ToString();
Targets = Dts.Variables["User::Segment"].Value;
MessageBox.Show(e.Message.ToString());
OleDbDataAdapter Adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
Adapter.Fill(dt, Dts.Variables["User::Segment"].Value);
List<Segment> segments = new List<Segment>();
foreach (DataRow row in dt.Rows)
Segment s = new Segment();
object[] array = row.ItemArray;
Campagne = array[0].ToString(),
ContactId = array[1].ToString(),
Name = array[2].ToString(),
Customer = array[3].ToString()
var campagnes = segments.GroupBy(x => x.Campagne).Select(x => x.Key).ToList();
foreach (var c in campagnes)
var listContact = segments.Where(x => x.Campagne == c).Select(x => new { contactid = x.ContactId.ToUpper(), customer = x.Customer }).ToList();
var segmentname = segments.Where(x => x.Campagne == c).Select(x => x.Name).FirstOrDefault();
QueryExpression qx = new QueryExpression();
qx.EntityName = "msdyncrm_segment";
qx.Criteria.AddCondition("msdyncrm_segmentname", ConditionOperator.Like, "%" + segmentname + "_Fidélisation%");
Guid segmentid = Guid.Empty;
using (var organizationservice = ConnectToCrm())
EntityCollection coll = organizationservice.RetrieveMultiple(qx);
if (coll.Entities.Count < 1)
Entity segment = new Entity("msdyncrm_segment");
segment.Attributes["msdyncrm_segmentname"] = segmentname + "_Fidélisation";
segment.Attributes["msdyncrm_segmenttype"] = new OptionSetValue(192350001);
segment.Attributes["statuscode"] = new OptionSetValue(192350000);
segmentid = organizationservice.Create(segment);
segmentid = coll.Entities[0].Id;
var pageitemnumber = 100;
bool otheriteration = true;
var nbiteration = listContact.Count() / pageitemnumber;
while (iteration < nbiteration)
using (var organizationservice = ConnectToCrm())
var contactToAdd = listContact.Skip(iteration * pageitemnumber).Take(pageitemnumber).Where(x => x.contactid != "NULL").Select(a => a.contactid).ToArray();
var customerToAdd = listContact.Skip(iteration * pageitemnumber).Take(pageitemnumber).Where(x => x.customer != "NULL").Select(a => a.customer).ToArray();
OrganizationRequest req = new OrganizationRequest("msdyncrm_SegmentMembersUpdate");
req["msdyncrm_segmentid"] = segmentid.ToString();
req["msdyncrm_operation"] = "addByIds";
req["msdyncrm_memberids"] = Newtonsoft.Json.JsonConvert.SerializeObject(contactToAdd);
var result=organizationservice.Execute(req);
if (!string.IsNullOrEmpty(result["Errors"].ToString()))
MessageBox.Show(result["Errors"].ToString());
MessageBox.Show(ex.ToString() + " _Fidélisation");
MessageBox.Show(ex.Message + " _Fidélisation");
MessageBox.Show(e.Message.ToString());
Dts.TaskResult = (int)ScriptResults.Success;
#region ScriptResults declaration
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
public string Campagne { get; set; }
public string ContactId { get; set; }
public string Name { get; set; }
public string Customer { get; set; }