Exemplo n.º 1
0
        public override void PreCreate(Entity entity, ConnectionHelper helper)
        {
            try
            {
                if (entity.Contains("listname") && entity["listname"] != null)
                {
                    #region check config params
                    string apikey = Common.GetParamValue(helper.OrganizationService, "ApiKey");
                    string userid = Common.GetParamValue(helper.OrganizationService, "UserId");
                    string nmList = Common.GetParamValue(helper.OrganizationService, "Default List");

                    if (apikey == null || userid == null || nmList == null)
                    {
                        Common.LogToCRM(helper.OrganizationService, $"Creating new segment for {(string)entity["listname"]}: missing configuration parameters",
                                        "-");
                        return;
                    }
                    #endregion

                    NewsmanAPI api       = new NewsmanAPI(apikey, userid);
                    string     segmentId = api.CreateSegment(nmList, (string)entity["listname"]);
                    entity["nmc_newsmansegmentid"] = segmentId;

                    Common.LogToCRM(helper.OrganizationService, $"Created segment for {(string)entity["listname"]}", $"Segment id: {segmentId}");
                }
            }
            catch (Exception ex)
            {
                Common.LogToCRM(helper.OrganizationService, $"Error creating segment for {(string)entity["listname"]}", $"Error message:{ex.Message}, stack trace: {ex.StackTrace}");
            }
        }
Exemplo n.º 2
0
        private void SendMemberToNewsman(MarketingListInfo listInfo, Guid member, IOrganizationService service)
        {
            //get member email and information
            Subscriber subscriber = Common.CreateSubscriber(service, member, listInfo.ListTargetType);

            if (subscriber != null)
            {
                #region check config params
                string apikey = Common.GetParamValue(service, "ApiKey");
                string userid = Common.GetParamValue(service, "UserId");
                string nmList = Common.GetParamValue(service, "Default List");

                if (apikey == null || userid == null || nmList == null)
                {
                    return;
                }
                #endregion
                using (NewsmanAPI api = new NewsmanAPI(apikey, userid))
                {
                    var resp = api.ImportSubscribers(nmList, listInfo.NewsmanSegmentId, subscriber);
                    Common.LogToCRM(service, $"Importing [{subscriber.Email}] for [{listInfo.ListName}] list", $"Import id: {resp.Replace("\"","")}");
                }
            }
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            #region test timestamp
            string mm = "1.";
            try
            {
                string connstring = ConfigurationManager.AppSettings["ConnString"];
                //Console.WriteLine("CONNSTRING: "+ connstring);


                CrmServiceClient conn = new CrmServiceClient(connstring);



                IOrganizationService service = conn.OrganizationWebProxyClient != null ?
                                               (IOrganizationService)conn.OrganizationWebProxyClient :
                                               (IOrganizationService)conn.OrganizationServiceProxy;

                mm += "2.";
                QueryExpression qry = new QueryExpression("nmc_newsmanhistory");
                qry.ColumnSet = new ColumnSet("nmc_timestamp");
                qry.Orders.Add(new OrderExpression("nmc_timestamp", OrderType.Ascending));
                qry.NoLock   = true;
                qry.TopCount = 1;
                mm          += "3.";

                if (service == null)
                {
                    Console.WriteLine($"SERVICE E NULL!");
                }

                EntityCollection results = service.RetrieveMultiple(qry);

                Entity last = results.Entities.FirstOrDefault();
                mm += "4.";

                Console.WriteLine($"CONECTAT LA CRM SI CITIT TIMESTAMP");
                mm += "5.";
                if (last != null && last.Contains("nmc_timestamp"))
                {
                    Console.WriteLine($"TIMESTAMP CRM {last["nmc_timestamp"].ToString()}");
                }

                Console.ReadKey();
            }
            catch (Exception e)
            {
                Console.WriteLine($"Eroare la conexiunea CRM: {e.Message}; PAS: {mm}");
            }
            return;

            #endregion


            using (NewsmanAPI api = new NewsmanAPI(apikey, userid))
            {
                #region commented
                //var lists = api.RetrieveLists();
                //var segments = api.RetrieveSegments(defaultList);

                //var newSegment = api.CreateSegment(defaultList, "segment din consola");

                List <Subscriber> subscribers = new List <Subscriber>();
                subscribers.Add(new Subscriber {
                    Email = "*****@*****.**", Firstname = "abf", Lastname = "cr"
                });
                subscribers.Add(new Subscriber {
                    Email = "*****@*****.**", Firstname = "bcf", Lastname = "dr"
                });
                subscribers.Add(new Subscriber {
                    Email = "*****@*****.**", Firstname = "george", Lastname = "calinescu"
                });
                //var resp = api.ImportSubscribers(defaultList, "65399", subscribers);

                //var status = api.ImportStatus(resp.Replace("\"", ""));
                //DateTimeOffset.UtcNow.Ticks.ToString()
                #endregion

                TimeSpan ts = DateTime.Now.Subtract(DateTime.Now.AddMinutes(-2));

                History(api);
            }
        }
Exemplo n.º 4
0
        static void History(NewsmanAPI api)
        {
            int pageSize = 1000;

            //crm connection
            CrmServiceClient conn = new CrmServiceClient("connection string");

            // Cast the proxy client to the IOrganizationService interface.
            IOrganizationService service = conn.OrganizationWebProxyClient != null ?
                                           (IOrganizationService)conn.OrganizationWebProxyClient :
                                           (IOrganizationService)conn.OrganizationServiceProxy;

            Entity nmHistoryRec = new Entity("nmc_newsmanhistory");

            nmHistoryRec.Attributes["nmc_action"]  = "click";
            nmHistoryRec.Attributes["nmc_linkurl"] = "www.google.com";
            service.Create(nmHistoryRec);

            //initialize duplicate detection collection
            EntityCollection crtRecords = RetrieveAllCurrentHistory(service);

            double             dblTimestamp = 1504127167.2155;
            double             crtTimestamp = 0;
            List <ListHistory> list         = api.RetrieveListHistory(defaultList, pageSize, "0");

            List <string> contactslist        = new List <string>();
            DateTime      startProcessingTime = DateTime.Now;
            double        failTimestamps      = 0;

            while (true)
            {
                if (list.Count > 0)
                {
                    crtTimestamp = Convert.ToDouble(list[list.Count - 1].timestamp);
                }
                else
                {
                    failTimestamps = crtTimestamp;
                    break;
                }

                for (int i = list.Count - 1; i >= 0; i--)
                {
                    var record = list[i];

                    if (Convert.ToDouble(record.timestamp) >= dblTimestamp)
                    {
                        if (RecordExists(crtRecords, record))
                        {
                            continue;
                        }

                        contactslist.Add(record.email);
                        //save checkpoint for the next history retrieval
                        crtTimestamp = Convert.ToDouble(list[i].timestamp);
                    }
                }

                if (dblTimestamp != 0 && crtTimestamp < dblTimestamp)
                {
                    break;
                }

                list = api.RetrieveListHistory(defaultList, pageSize, crtTimestamp.ToString());
            }

            var original = contactslist.Count;

            contactslist.ForEach(Concatenate);
            expand += "//";
            var duplicates = contactslist.Distinct().Count();
        }
Exemplo n.º 5
0
        private void ResetConfigurationParameters(ConnectionHelper helper, string name, string value)
        {
            try
            {
                #region check config params
                string apikey      = null;
                string userid      = null;
                Entity nmLists     = Common.GetParamEntity(helper.OrganizationService, "Newsman Lists");
                Entity defaultList = Common.GetParamEntity(helper.OrganizationService, "Default List");

                if (name == "ApiKey")
                {
                    apikey = value;
                    userid = Common.GetParamValue(helper.OrganizationService, "UserId");
                }

                if (name == "UserId")
                {
                    userid = value;
                    apikey = Common.GetParamValue(helper.OrganizationService, "ApiKey");
                }

                if (apikey == null || userid == null)
                {
                    return;
                }
                #endregion

                //create newsman api instance
                NewsmanAPI nmapi           = new NewsmanAPI(apikey, userid);
                string     listInformation = null;

                helper.TracingService.Trace("Retrieving lists");
                try
                {
                    listInformation = nmapi.RetrieveListsJson();
                }
                catch (Exception e)
                {
                    Common.LogToCRM(helper.OrganizationService, $"Exception when retrieving Newsman lists",
                                    $"Message: {e.Message} // Stack trace: {e.StackTrace}");
                }
                helper.TracingService.Trace("Retrieved");

                if (nmLists == null)
                {
                    //create lists config param
                    Entity listsParam = new Entity("nmc_newsmanconfig");
                    listsParam.Attributes["nmc_name"]  = "Newsman Lists";
                    listsParam.Attributes["nmc_value"] = listInformation;

                    helper.TracingService.Trace("Create params");
                    helper.OrganizationService.Create(listsParam);

                    if (listInformation != null)
                    {
                        Common.LogToCRM(helper.OrganizationService, $"Created Newsman Config parameter for retrieved lists",
                                        listsParam.Attributes["nmc_value"].ToString());
                    }
                }
                else
                {
                    //update lists config param
                    nmLists.Attributes["nmc_value"] = listInformation;

                    helper.TracingService.Trace("Update params");
                    helper.OrganizationService.Update(nmLists);

                    if (listInformation != null)
                    {
                        Common.LogToCRM(helper.OrganizationService, $"Updated Newsman Config parameter for retrieved lists",
                                        nmLists.Attributes["nmc_value"].ToString());
                    }
                }

                //reset Default List when modifying apikey
                if (listInformation == null && defaultList != null)
                {
                    defaultList.Attributes["nmc_value"] = null;
                    helper.OrganizationService.Update(defaultList);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 6
0
        public override void PostUpdate(Entity entity, ConnectionHelper helper)
        {
            DateTime startProcessingTime = DateTime.Now;
            Entity   image = helper.PluginExecutionContext.PostEntityImages.Contains("Image") ?
                             helper.PluginExecutionContext.PostEntityImages["Image"] : entity;
            string name = (string)image.GetValue("nmc_name", image);

            #region Retrieve history
            if (entity.Contains("nmc_nextrunon") && name == "ApiKey")
            {
                //initialization
                int  totalSeconds    = 100;
                int  nmcPageCount    = 100;
                Guid LastTimestampID = InitializeTimestamp(helper.OrganizationService);

                #region check config params
                string apikey      = Common.GetParamValue(helper.OrganizationService, "ApiKey");
                string userid      = Common.GetParamValue(helper.OrganizationService, "UserId");
                string defaultList = Common.GetParamValue(helper.OrganizationService, "Default List");

                if (apikey == null || userid == null || defaultList == null)
                {
                    Common.LogToCRM(helper.OrganizationService, "History retrieve attempt failed. Missing configuration parameters", "");
                    return;
                }
                #endregion

                //create newsman api instance
                NewsmanAPI nmapi = new NewsmanAPI(apikey, userid);

                //retrieve last history timestamp
                string lastTimestamp = RetrieveLastTimestamp(helper.OrganizationService, LastTimestampID);
                Common.LogToCRM(helper.OrganizationService, $"Attempting history retrieve with list_id {defaultList}, count {nmcPageCount} and timestamp {lastTimestamp}",
                                $"Current last timestamp is {lastTimestamp}");

                //initialize duplicate detection collection
                EntityCollection crtCRMRecords = RetrieveAllCurrentHistory(helper.OrganizationService);
                IEnumerable <DuplicateSubscriber> crtRecords = crtCRMRecords.Entities.Where(i => i.Contains("nmc_subscriberid") && i.Contains("nmc_action") && i.Contains("nmc_timestamp")).
                                                               Select(s => new DuplicateSubscriber()
                {
                    Subscriber = (string)s["nmc_subscriberid"],
                    Action     = (string)s["nmc_action"],
                    Timestamp  = (string)s["nmc_timestamp"]
                });

                ICollection <DuplicateSubscriber> crtColl = crtRecords.ToList();

                try
                {
                    //first page
                    var    history      = nmapi.RetrieveListHistory(defaultList, nmcPageCount, lastTimestamp).ToArray();
                    string crtTimestamp = string.Empty;

                    while (true)
                    {
                        //break loop when no other records are returned
                        if (history.Length == 0)
                        {
                            //reset  timestamp
                            ResetTimestamp(helper.OrganizationService, LastTimestampID);

                            break;
                        }

                        //save checkpoint for the next history retrieval
                        crtTimestamp = history.Min(h => h.timestamp);

                        #region Check timer
                        //break loop before CRM plugin times out
                        if (DateTime.Now.Subtract(startProcessingTime).TotalSeconds > totalSeconds)
                        {
                            Common.LogToCRM(helper.OrganizationService, "History records creating loop break caused by forced timeout", null);
                            break;
                        }
                        #endregion

                        for (int i = 0; i < history.Length; i++)
                        {
                            //get next record
                            var record = history[i];
                            if (RecordExists(crtColl, record))
                            {
                                continue;
                            }

                            #region Newsletter information
                            EntityReference newsletter = GetEntityReference(helper.OrganizationService, record.newsletter_id, "nmc_newsmannewsletter");
                            if (newsletter == null)
                            {
                                //create newsletter record
                                Entity nl = new Entity("nmc_newsmannewsletter");
                                nl.Attributes.Add("nmc_subject", record.newsletter_subject);
                                nl.Attributes.Add("nmc_newsletterid", record.newsletter_id);
                                nl.Attributes.Add("nmc_newsletterlink", NewsmanDefaults.NewsletterLink(defaultList, record.newsletter_id));
                                Guid nlId = helper.OrganizationService.Create(nl);

                                newsletter = new EntityReference("nmc_newsmannewsletter", nlId);
                            }
                            #endregion

                            #region Create history
                            Entity nmHistoryRec = new Entity("nmc_newsmanhistory");
                            nmHistoryRec.Attributes["nmc_date"]         = record.date;
                            nmHistoryRec.Attributes["nmc_action"]       = record.action;
                            nmHistoryRec.Attributes["nmc_subscriberid"] = record.subscriber_id;
                            nmHistoryRec.Attributes["nmc_timestamp"]    = record.timestamp;
                            nmHistoryRec.Attributes["nmc_linkurl"]      = record.url;
                            nmHistoryRec.Attributes["nmc_datetime"]     = DatetimeFromTimestamp(record.timestamp);
                            nmHistoryRec.Attributes["nmc_emailused"]    = record.email;
                            nmHistoryRec.Attributes["nmc_customerid"]   = GetEntityReference(helper.OrganizationService, record.email);
                            nmHistoryRec.Attributes["nmc_newsletterid"] = newsletter;

                            helper.OrganizationService.Create(nmHistoryRec);
                            #endregion

                            //extend the collection
                            crtColl.Add(new DuplicateSubscriber()
                            {
                                Action = record.action, Subscriber = record.subscriber_id, Timestamp = record.timestamp
                            });
                        }

                        UpdateLastTimestamp(helper.OrganizationService, LastTimestampID, crtTimestamp);

                        #region Check timer
                        //break loop before CRM plugin times out
                        if (DateTime.Now.Subtract(startProcessingTime).TotalSeconds > totalSeconds)
                        {
                            Common.LogToCRM(helper.OrganizationService, "History records creating loop break caused by forced timeout", null);
                            break;
                        }
                        #endregion

                        //next page
                        history = nmapi.RetrieveListHistory(defaultList, nmcPageCount, crtTimestamp).ToArray();
                    }
                }
                catch (Exception e)
                {
                    Common.LogToCRM(helper.OrganizationService, "Exception creating history records", e.ToString());
                }
            }
            #endregion
        }
Exemplo n.º 7
0
        public override void PostUpdate(Entity entity, ConnectionHelper helper)
        {
            Entity image = helper.PluginExecutionContext.PostEntityImages["Image"];

            if (entity.Contains("nmc_syncmembers") &&
                entity["nmc_syncmembers"] != null &&
                (bool)entity["nmc_syncmembers"])
            {
                Common.LogToCRM(helper.OrganizationService, $"Marketing list sync triggered: {entity.Id.ToString()}", "Update triggered on marketing list record");

                try
                {
                    #region check config params
                    string apikey = Common.GetParamValue(helper.OrganizationService, "ApiKey");
                    string userid = Common.GetParamValue(helper.OrganizationService, "UserId");
                    string nmList = Common.GetParamValue(helper.OrganizationService, "Default List");

                    if (apikey == null || userid == null || nmList == null)
                    {
                        Common.LogToCRM(helper.OrganizationService, $"Marketing list sync ignored: {entity.Id.ToString()}", "Missing Newsman API configuration!");
                        return;
                    }
                    #endregion

                    using (NewsmanAPI api = new NewsmanAPI(apikey, userid))
                    {
                        #region Generate query criteria
                        int             memberTypeCode = image.GetOptionSetValue("createdfromcode");
                        string          memberType     = memberTypeCode == 1 ? "account" : (memberTypeCode == 2 ? "contact" : "lead");
                        QueryExpression qry            = new QueryExpression(memberType);
                        ColumnSet       cols           = null;
                        switch (memberType)
                        {
                        case "account":
                            cols = new ColumnSet("name", "emailaddress1", "emailaddress2", "emailaddress3");
                            break;

                        case "contact":
                        case "lead":
                            cols = new ColumnSet("firstname", "lastname", "emailaddress1", "emailaddress2", "emailaddress3");
                            break;

                        default:
                            cols = new ColumnSet(false);
                            break;
                        }
                        qry.ColumnSet = cols;
                        LinkEntity listMember = qry.AddLink("listmember", memberType + "id", "entityid", JoinOperator.Inner);
                        LinkEntity list       = listMember.AddLink("list", "listid", "listid");
                        list.LinkCriteria.AddCondition("listid", ConditionOperator.Equal, entity.Id);
                        #endregion

                        #region Send to Newsman
                        StringBuilder importIDs = new StringBuilder();

                        int    totalRecordCount = 0;
                        string segment          = (string)image.GetValue("nmc_newsmansegmentid");
                        qry.PageInfo                        = new PagingInfo();
                        qry.PageInfo.Count                  = 5000;
                        qry.PageInfo.PageNumber             = 1;
                        qry.PageInfo.PagingCookie           = null;
                        qry.PageInfo.ReturnTotalRecordCount = true;
                        EntityCollection members = helper.OrganizationService.RetrieveMultiple(qry);
                        Common.LogToCRM(helper.OrganizationService, $"Started synchronization for {(string)image["listname"]}", $"First page has {members.TotalRecordCount.ToString("N0")} record(s)");
                        totalRecordCount += members.TotalRecordCount;

                        //first batch
                        string importId = api.ImportSubscribers(nmList, segment, Common.CreateSubscribers(members));
                        importIDs.Append($"{importId};");

                        //rest of the batches
                        while (members.MoreRecords)
                        {
                            members  = helper.OrganizationService.RetrieveMultiple(qry);
                            importId = api.ImportSubscribers(nmList, segment, Common.CreateSubscribers(members));
                            importIDs.Append($"{importId};");
                            qry.PageInfo.PageNumber++;
                            qry.PageInfo.PagingCookie = members.PagingCookie;
                            totalRecordCount         += members.TotalRecordCount;
                        }
                        ;
                        Common.LogToCRM(helper.OrganizationService, $"Finished synchronization for {(string)image["listname"]}", $"Total number of records is: {totalRecordCount.ToString("N0")}. List of generated Newsman import ids: {importIDs.ToString()}");
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    Common.LogToCRM(helper.OrganizationService, $"Error syncing list members for {(string)image["listname"]}", $"Error message:{ex.Message}, stack trace: {ex.StackTrace}");
                }
                finally
                {
                    Entity resetList = new Entity(entity.LogicalName, entity.Id);
                    resetList.Attributes["nmc_syncmembers"] = false;
                    helper.OrganizationService.Update(resetList);
                }
            }
        }