public NewsletterResponseObject GetSubscriber(string enccusId, ushort?position)
        {
            NewsletterResponseObject response = new NewsletterResponseObject();

            HarperLINQ.tbl_Customer        customer;
            HarperLINQ.AHT_MainDataContext dc;
            int cusId = 0;

            try
            {
                string strCusId = HarperCRYPTO.Cryptography.DeHash(enccusId, true);
                cusId = Int32.Parse(strCusId);
                response.PrimarySubscriber   = null;
                response.SecondarySubscriber = null;

                dc       = new HarperLINQ.AHT_MainDataContext(ConfigurationManager.ConnectionStrings["AHT_MainConnectionString"].ConnectionString);
                customer = dc.tbl_Customers.Where(c => c.cusID == cusId)
                           .Single();

                if (position.HasValue && position.Value != 1 && position.Value != 2)
                {
                    throw new ApplicationException("Position Value is invalid. Use 1 for Primary, 2 for Secondary.");
                }

                if (!position.HasValue || position.Value == 1)
                {
                    if (customer.cusStormPostPrimaryID.HasValue && customer.cusStormPostPrimaryID.Value > 0)
                    {
                        response.PrimarySubscriber = retrieveSubscriber(customer.cusStormPostPrimaryID.Value);
                        response.PrimarySubscriber.Primary_Email = true;
                        response.PrimarySubscriber.CusID         = cusId;
                    }
                }

                if (!position.HasValue || position.Value == 2)
                {
                    if (customer.cusStormPostSecondaryID.HasValue && customer.cusStormPostSecondaryID.Value > 0)
                    {
                        response.SecondarySubscriber       = retrieveSubscriber(customer.cusStormPostSecondaryID.Value);
                        response.SecondarySubscriber.CusID = cusId;
                    }
                }



                response.Success = true;
                return(response);
            }
            catch (Exception ex)
            {
                string argString = String.Format("enccusId: {0}; position: {1}", enccusId, position);
                new SupportClasses.Mailer().SendEmail(ConfigurationManager.AppSettings["mailserviceuser"],
                                                      ConfigurationManager.AppSettings["mailservicepwd"],
                                                      "NewsletterService ERROR - " + ex.GetType().Name,
                                                      "*****@*****.**",
                                                      ConfigurationManager.AppSettings["newsletter-erroremailto"],
                                                      "", "", argString + ex.ToString(), false,
                                                      ConfigurationManager.AppSettings["erroremailsmtpserver"]);
                throw;
            }
        }
        public NewsletterResponseObject GetSubscriber(string enccusId, ushort? position)
        {

            NewsletterResponseObject response = new NewsletterResponseObject();
            HarperLINQ.tbl_Customer customer;
            HarperLINQ.AHT_MainDataContext dc;
            int cusId = 0;

            try
            {
                string strCusId = HarperCRYPTO.Cryptography.DeHash(enccusId, true);
                cusId = Int32.Parse(strCusId);
                response.PrimarySubscriber = null;
                response.SecondarySubscriber = null;

                dc = new HarperLINQ.AHT_MainDataContext(ConfigurationManager.ConnectionStrings["AHT_MainConnectionString"].ConnectionString);
                customer = dc.tbl_Customers.Where(c => c.cusID == cusId)
                                           .Single();

                if (position.HasValue && position.Value != 1 && position.Value != 2)
                    throw new ApplicationException("Position Value is invalid. Use 1 for Primary, 2 for Secondary.");

                if (!position.HasValue || position.Value == 1)
                {
                    if (customer.cusStormPostPrimaryID.HasValue && customer.cusStormPostPrimaryID.Value > 0 )
                    {
                        response.PrimarySubscriber = retrieveSubscriber(customer.cusStormPostPrimaryID.Value);
                        response.PrimarySubscriber.Primary_Email = true;
                        response.PrimarySubscriber.CusID = cusId;
                    }
                }

                if (!position.HasValue || position.Value == 2)
                {
                    if (customer.cusStormPostSecondaryID.HasValue && customer.cusStormPostSecondaryID.Value > 0)
                    {
                        response.SecondarySubscriber = retrieveSubscriber(customer.cusStormPostSecondaryID.Value);
                        response.SecondarySubscriber.CusID = cusId;
                    }

                }



                response.Success = true;
                return response;
            }
            catch(Exception ex)
            {
                string argString = String.Format("enccusId: {0}; position: {1}", enccusId, position);
                new SupportClasses.Mailer().SendEmail(ConfigurationManager.AppSettings["mailserviceuser"],
                    ConfigurationManager.AppSettings["mailservicepwd"],
                    "NewsletterService ERROR - " + ex.GetType().Name,
                    "*****@*****.**",
                    ConfigurationManager.AppSettings["newsletter-erroremailto"],
                    "", "", argString + ex.ToString(), false,
                    ConfigurationManager.AppSettings["erroremailsmtpserver"]);
                throw;
            }
            
        }
        public NewsletterResponseObject CreateSubscriber(string encCusId, ushort position)
        {
            stormpost.api.SoapRequestProcessorService api;
            stormpost.api.Recipient           recipient, existing;
            HarperLINQ.AHT_MainDataContext    dc;
            HarperLINQ.tbl_Customer           customer;
            HarperLINQ.tbl_NetMembership      maxMembership;
            HarperLINQ.tbl_MembershipType     maxMembershipType;
            HarperLINQ.tbl_StormPostRecipient newRecipient;
            NewsletterResponseObject          response;
            int cusID = 0;

            try
            {
                cusID                      = Int32.Parse(HarperCRYPTO.Cryptography.DeHash(encCusId, true));
                api                        = new MemberServices.stormpost.api.SoapRequestProcessorService();
                dc                         = new HarperLINQ.AHT_MainDataContext(ConfigurationManager.ConnectionStrings["AHT_MainConnectionString"].ConnectionString);
                response                   = new NewsletterResponseObject();
                response.Success           = false;
                response.PrimarySubscriber = new NewsletterSubscriber();

                // Set the authentication on the SOAP object
                api.authenticationValue          = new MemberServices.stormpost.api.authentication();
                api.authenticationValue.username = ConfigurationManager.AppSettings["newsletter-api-username"];
                api.authenticationValue.password = ConfigurationManager.AppSettings["newsletter-api-password"];


                // Get the customer and his associated NetMembership record
                customer = dc.tbl_Customers.Where(c => c.cusID == cusID)
                           .Single();
                try
                {
                    maxMembership = dc.tbl_NetMemberships.Where(nm => nm.cusID == customer.cusID)
                                    .OrderByDescending(nm => nm.nmbDateEnd)
                                    .First();
                }
                catch
                {
                    maxMembership = null;
                }

                try
                {
                    maxMembershipType = dc.tbl_MembershipTypes.Where(mt => mt.mtyCode == maxMembership.mtyCode)
                                        .Single();
                }
                catch
                {
                    maxMembershipType = null;
                }


                // "Lazy" coding: look for an excuse not to do any work...
                if (position != 1 && position != 2)
                {
                    throw new ApplicationException("Postion specified is unsupported. Currently this operation only selects position 1 or 2.");
                }
                else if (position == 1 && customer.cusStormPostPrimaryID.HasValue && customer.cusStormPostPrimaryID > 0)
                {
                    throw new ApplicationException(String.Format("The customer selected already has a StormPulse account ({0})", customer.cusStormPostPrimaryID));
                }
                else if (position == 2 && customer.cusStormPostSecondaryID.HasValue && customer.cusStormPostSecondaryID > 0)
                {
                    throw new ApplicationException(String.Format("The customer selected already has a StormPulse account ({0})", customer.cusStormPostSecondaryID));
                }


                // Set up the recipient object
                recipient            = new MemberServices.stormpost.api.Recipient();
                recipient.dateJoined = DateTime.Now;
                recipient.externalID = customer.cusCustNum;
                recipient.SetDemographic("FirstName", customer.cusFirstName);
                recipient.SetDemographic("LastName", customer.cusLastName);
                recipient.SetDemographic("_Custom01", (maxMembershipType != null) ? maxMembershipType.mtyName : "");
                recipient.SetDemographic("_Custom02", customer.csoCode);
                recipient.SetDemographic("_Custom03", (maxMembership != null)  ? maxMembership.nmbDateEnd.ToShortDateString() : "");
                recipient.SetDemographic("_Custom04", position == 1 ? "True" : "False");
                if (position == 1)
                {
                    recipient.address = customer.cusEmail;
                }
                else if (position == 2)
                {
                    recipient.address = customer.cusSecondEmail;
                }


                // Check whether the recipient already exists at stormpost
                existing = null;
                try
                {
                    existing = api.getRecipientByAddress(recipient.address);
                }
                catch { }
                if (existing != null)
                {
                    if (!String.IsNullOrEmpty(existing.address) && existing.recipID.HasValue)
                    {
                        return(updateCustomerStormPostId(cusID, position, existing.recipID.Value));
                    }
                }

                // Make the createRecipient call, and update Nucleus with the new value
                response.PrimarySubscriber.UniqueID = api.createRecipientAndReturnRecipID(recipient);
                if (position == 1)
                {
                    customer.cusStormPostPrimaryID = response.PrimarySubscriber.UniqueID;
                }
                else if (position == 2)
                {
                    customer.cusStormPostSecondaryID = response.PrimarySubscriber.UniqueID;
                }

                // Create the StormPostRecipient object
                DateTime tmpDateTime = new DateTime();
                newRecipient = new HarperLINQ.tbl_StormPostRecipient()
                {
                    sprEmail        = recipient.address,
                    sprFirstName    = recipient.GetDemographics()["FirstName"],
                    sprLastName     = recipient.GetDemographics()["LastName"],
                    sprMemberType   = recipient.GetDemographics()["_Custom01"],
                    sprMemberSource = recipient.GetDemographics()["_Custom02"],
                    sprExpireDate   = (DateTime.TryParse(recipient.GetDemographics()["_Custom03"], out tmpDateTime) ? (DateTime?)tmpDateTime : (DateTime?)null),
                    sprPrimaryEmail = recipient.GetDemographics()["_Custom04"] == "True",
                    sprRecipId      = response.PrimarySubscriber.UniqueID,
                    timestmp        = DateTime.Now,
                    sprJoinDate     = DateTime.Now
                };
                dc.tbl_StormPostRecipients.InsertOnSubmit(newRecipient);
                dc.SubmitChanges();


                // Construct the response object
                response.PrimarySubscriber.CusID         = cusID;
                response.PrimarySubscriber.EmailAddress  = customer.cusEmail;
                response.PrimarySubscriber.Subscriptions = new List <Newsletter>();
                response.PrimarySubscriber.First_Name    = recipient.GetDemographics()["FirstName"];
                response.PrimarySubscriber.Last_Name     = recipient.GetDemographics()["LastName"];
                response.PrimarySubscriber.Member_Source = recipient.GetDemographics()["_Custom02"];
                response.PrimarySubscriber.Member_Type   = recipient.GetDemographics()["_Custom01"];
                response.PrimarySubscriber.Primary_Email = (recipient.GetDemographics()["_Custom04"] == "True");
                // Parse the Expire Date
                string   temp    = recipient.GetDemographics()["_Custom03"];
                DateTime tmpDate = new DateTime();
                response.PrimarySubscriber.Member_Expire_Date = (DateTime.TryParse(temp, out tmpDate)) ? (DateTime?)tmpDate : null;
                response.Success = true;
                return(response);
            }
            catch (Exception ex)
            {
                string argString = String.Format("cusId: {0}\r\n\r\n", cusID.ToString());
                new SupportClasses.Mailer().SendEmail(ConfigurationManager.AppSettings["mailserviceuser"],
                                                      ConfigurationManager.AppSettings["mailservicepwd"],
                                                      "NewsletterService ERROR - " + ex.GetType().Name,
                                                      "*****@*****.**",
                                                      ConfigurationManager.AppSettings["newsletter-erroremailto"],
                                                      "", "", argString + ex.ToString(), false,
                                                      ConfigurationManager.AppSettings["erroremailsmtpserver"]);
                throw;
            }
        }
        public NewsletterResponseObject CreateSubscriber(string encCusId, ushort position)
        {
            stormpost.api.SoapRequestProcessorService api;
            stormpost.api.Recipient recipient, existing;
            HarperLINQ.AHT_MainDataContext dc;
            HarperLINQ.tbl_Customer customer;
            HarperLINQ.tbl_NetMembership maxMembership;
            HarperLINQ.tbl_MembershipType maxMembershipType;
            HarperLINQ.tbl_StormPostRecipient newRecipient;
            NewsletterResponseObject response;
            int cusID = 0;

            try
            {
                cusID = Int32.Parse(HarperCRYPTO.Cryptography.DeHash(encCusId, true));
                api = new MemberServices.stormpost.api.SoapRequestProcessorService();
                dc = new HarperLINQ.AHT_MainDataContext(ConfigurationManager.ConnectionStrings["AHT_MainConnectionString"].ConnectionString);
                response = new NewsletterResponseObject();
                response.Success = false;
                response.PrimarySubscriber = new NewsletterSubscriber();

                // Set the authentication on the SOAP object
                api.authenticationValue = new MemberServices.stormpost.api.authentication();
                api.authenticationValue.username = ConfigurationManager.AppSettings["newsletter-api-username"];
                api.authenticationValue.password = ConfigurationManager.AppSettings["newsletter-api-password"];


                // Get the customer and his associated NetMembership record
                customer = dc.tbl_Customers.Where(c => c.cusID == cusID)
                                           .Single();
                try
                {
                    maxMembership = dc.tbl_NetMemberships.Where(nm => nm.cusID == customer.cusID)
                                                         .OrderByDescending(nm => nm.nmbDateEnd)
                                                         .First();
                }
                catch
                {
                    maxMembership = null;
                }

                try
                {
                    maxMembershipType = dc.tbl_MembershipTypes.Where(mt => mt.mtyCode == maxMembership.mtyCode)
                                          .Single();
                }
                catch
                {
                    maxMembershipType = null;
                }


                // "Lazy" coding: look for an excuse not to do any work...
                if (position != 1 && position != 2)
                    throw new ApplicationException("Postion specified is unsupported. Currently this operation only selects position 1 or 2.");
                else if (position == 1 && customer.cusStormPostPrimaryID.HasValue && customer.cusStormPostPrimaryID > 0)
                    throw new ApplicationException(String.Format("The customer selected already has a StormPulse account ({0})", customer.cusStormPostPrimaryID));
                else if (position == 2 && customer.cusStormPostSecondaryID.HasValue && customer.cusStormPostSecondaryID > 0)
                    throw new ApplicationException(String.Format("The customer selected already has a StormPulse account ({0})", customer.cusStormPostSecondaryID));
                

                // Set up the recipient object
                recipient = new MemberServices.stormpost.api.Recipient();
                recipient.dateJoined = DateTime.Now;
                recipient.externalID = customer.cusCustNum;
                recipient.SetDemographic("FirstName", customer.cusFirstName);
                recipient.SetDemographic("LastName", customer.cusLastName);
                recipient.SetDemographic("_Custom01", (maxMembershipType != null) ? maxMembershipType.mtyName : "");
                recipient.SetDemographic("_Custom02", customer.csoCode);
                recipient.SetDemographic("_Custom03", (maxMembership != null)  ? maxMembership.nmbDateEnd.ToShortDateString() : "");
                recipient.SetDemographic("_Custom04", position == 1 ? "True" : "False");
                if (position == 1)
                    recipient.address = customer.cusEmail;
                else if (position == 2)
                    recipient.address = customer.cusSecondEmail;


                // Check whether the recipient already exists at stormpost
                existing = null;
                try
                {
                    existing = api.getRecipientByAddress(recipient.address);
                }
                catch { }
                if (existing != null)
                {
                    if (!String.IsNullOrEmpty(existing.address) && existing.recipID.HasValue)
                    {
                        return updateCustomerStormPostId(cusID, position, existing.recipID.Value);
                    }
                }

                // Make the createRecipient call, and update Nucleus with the new value
                response.PrimarySubscriber.UniqueID = api.createRecipientAndReturnRecipID(recipient);
                if (position == 1)
                    customer.cusStormPostPrimaryID = response.PrimarySubscriber.UniqueID;
                else if (position == 2)
                    customer.cusStormPostSecondaryID = response.PrimarySubscriber.UniqueID;

                // Create the StormPostRecipient object
                DateTime tmpDateTime = new DateTime();
                newRecipient = new HarperLINQ.tbl_StormPostRecipient()
                {
                    sprEmail = recipient.address,
                    sprFirstName = recipient.GetDemographics()["FirstName"],
                    sprLastName = recipient.GetDemographics()["LastName"],
                    sprMemberType = recipient.GetDemographics()["_Custom01"],
                    sprMemberSource = recipient.GetDemographics()["_Custom02"],
                    sprExpireDate = (DateTime.TryParse(recipient.GetDemographics()["_Custom03"], out tmpDateTime) ? (DateTime?)tmpDateTime : (DateTime?)null),
                    sprPrimaryEmail = recipient.GetDemographics()["_Custom04"] == "True",
                    sprRecipId = response.PrimarySubscriber.UniqueID,
                    timestmp = DateTime.Now,
                    sprJoinDate = DateTime.Now
                };
                dc.tbl_StormPostRecipients.InsertOnSubmit(newRecipient);
                dc.SubmitChanges();


                // Construct the response object
                response.PrimarySubscriber.CusID = cusID;
                response.PrimarySubscriber.EmailAddress = customer.cusEmail;
                response.PrimarySubscriber.Subscriptions = new List<Newsletter>();
                response.PrimarySubscriber.First_Name = recipient.GetDemographics()["FirstName"];
                response.PrimarySubscriber.Last_Name = recipient.GetDemographics()["LastName"];
                response.PrimarySubscriber.Member_Source = recipient.GetDemographics()["_Custom02"];
                response.PrimarySubscriber.Member_Type = recipient.GetDemographics()["_Custom01"];
                response.PrimarySubscriber.Primary_Email = (recipient.GetDemographics()["_Custom04"] == "True");
                // Parse the Expire Date
                string temp = recipient.GetDemographics()["_Custom03"];
                DateTime tmpDate = new DateTime();
                response.PrimarySubscriber.Member_Expire_Date = (DateTime.TryParse(temp, out tmpDate)) ? (DateTime?)tmpDate : null;
                response.Success = true;
                return response;

            }
            catch(Exception ex)
            {
                string argString = String.Format("cusId: {0}\r\n\r\n", cusID.ToString());
                new SupportClasses.Mailer().SendEmail(ConfigurationManager.AppSettings["mailserviceuser"],
                    ConfigurationManager.AppSettings["mailservicepwd"],
                    "NewsletterService ERROR - " + ex.GetType().Name,
                    "*****@*****.**",
                    ConfigurationManager.AppSettings["newsletter-erroremailto"],
                    "", "", argString + ex.ToString(), false,
                    ConfigurationManager.AppSettings["erroremailsmtpserver"]);
                throw;
            }

        }