Esempio n. 1
0
        public CampaignSetupModel GetCategories(CampaignSetupModel model)
        {
            var scw = new ServiceClientWrapper();

            // create AdCopy array

            // get categories or classifications
            var categories = scw.GetCategories(null, model.ProductGroup.ProductPromotionName,
                                               model.ProductGroup.Words,
                                               model.AdModelProp.Ads.Select(
                                                   pad => pad.AdTitle + " " + pad.AdTextLine1 + " " + pad.AdTextLine2).
                                                   ToArray(), model.AdModelProp.LandingUrl);

            // create categories list that will be displayed in a multiselect list box
            if (categories != null && categories.Count > 0)
            {
                for (var i = 0; i < categories.Count; i++)
                {
                    var cm = new CampaignSetupModel.CategoriesModel {Id = i, Name = categories[i]};
                    model.AllCategories.Add(cm);
                }
            }
            else
            {
                var logEnty = new LogEntry
                                  {ActivityId = Guid.NewGuid(), Message = "Could not get Categories from web service"};
                Logger.Write(logEnty);
            }
            return model;
            // save this some how while getting the keywords this is becoming null
        }
        public ReturnState ChargeCreditCard(CustomerObject co, Promotion promo, int payTypeFk, decimal budget)
        {
            var sw = new ServiceClientWrapper();
            var gr = sw.CreateProfile(co);
            if (gr != null && gr.isGood && !gr.isError)
            {
                var refNum = gr.CustomerRefNum;
                gr = sw.AuthorizeAndCapture(refNum, double.Parse(budget.ToString()));
                if (gr != null && gr.isApproved && !gr.isError && gr.ResponseCode == "00")
                {
                    var tr = new TransactionRepository(_dbcontext);
                    var amount = decimal.Parse(gr.amountRedeemedNoDecimal);
                    var cp =
                        _dbcontext.CreditCardProfiles.Add(new CreditCardProfile
                                                              {
                                                                  CustomerRefNum = refNum,
                                                                  CustomerFK = promo.ProductGroup.CustomerFK
                                                              });
                    var tran = _dbcontext.Transactions.Add(new Transaction
                                                               {
                                                                   CreatedDate = DateTime.Now,
                                                                   Amount = amount,
                                                                   CreditCardProfileFK = cp.CreditCardProfilePK,
                                                                   AuthCode = gr.AuthCode,
                                                                   TxRefNum = gr.TxRefNum
                                                               });
                    tran.SemplestTransactions.Add(new SemplestTransaction
                                                      {
                                                          CreatedDate = DateTime.Now,
                                                          Amount = amount,
                                                          TransactionTypeFK = tr.GetTransactionTypeCode("MediaSpend")
                                                      });
                    promo.RemainingBudgetInCycle += amount;
                    promo.StartBudgetInCycle += amount;
                    promo.CreditCardProfileFK = cp.CreditCardProfilePK;
                    _dbcontext.PromotionBudgets.Add(new PromotionBudget
                                                        {
                                                            TransactionsFK = tran.TransactionsPK,
                                                            PromotionFK = promo.PromotionPK,
                                                            BudgetCarryOverAmount = 0,
                                                            BudgetToAddAmount = amount,
                                                            BudgetToAddDate = DateTime.Now,
                                                            CreatedDate = DateTime.Now,
                                                            IsValid = true,
                                                            IsAppliedToPromotion = true
                                                        });
                    return new ReturnState(false, false, string.Empty, null);
                }
                return gr == null
                           ? new ReturnState(true, false, "Server Exception", null)
                           : new ReturnState(true, true, gr.Message, null);
            }

            return gr == null
                       ? new ReturnState(true, false, "Server Exception", null)
                       : new ReturnState(true, true, "Card Declined", null);
        }
Esempio n. 3
0
        public CampaignSetupModel GetKeyWords(CampaignSetupModel model, int promoId)
        {
            if (model.AllCategories.Count == 0)
            {
                //model.AllCategories = (List<CampaignSetupModel.CategoriesModel>)Session["AllCategories"];
            }

            var catList = new List<string>();

            foreach (var cat in model.AllCategories)
            {
                catList.AddRange(from t in model.CategoryIds where cat.Id == t select cat.Name);
            }

            var scw = new ServiceClientWrapper();
            // create AdCopy array


            // get keywords from the web service
            //List<string> keywords = scw.GetKeywords(catList, null, "coffee machine", null, null, "http://www.wholelattelove.com", null);
            var keywords = scw.GetKeywords(catList, null, SerializeAdEnginesSelectedToStringArray(model).ToArray(),
                                           model.ProductGroup.ProductPromotionName,
                                           model.ProductGroup.Words,
                                           model.AdModelProp.Ads.Select(
                                               pad => pad.AdTitle + " " + pad.AdTextLine1 + " " + pad.AdTextLine2).
                                               ToArray(), model.AdModelProp.LandingUrl,
                                           SerializeToGeoTargetObjectArray(model).ToArray());


            if (keywords != null && keywords.Length > 0)
            {

                model.AllKeywordProbabilityObjects.AddRange(keywords);
                SaveKeywords(promoId, model.AllKeywordProbabilityObjects, model.AdModelProp.NegativeKeywords,
                             model.ProductGroup.ProductGroupName, model.ProductGroup.ProductPromotionName);
                foreach (
                    var kwm in
                        model.AllKeywordProbabilityObjects.Where(key => key.isDeleted == false).Select(
                            key => new CampaignSetupModel.KeywordsModel {Name = key.keyword, Id = key.id}))
                {
                    model.AllKeywords.Add(kwm);
                }
            }
            else
            {
                var logEnty = new LogEntry
                                  {ActivityId = Guid.NewGuid(), Message = "Could not get Keywords from web service"};
                Logger.Write(logEnty);
            }
            return model;
        }
Esempio n. 4
0
        public CampaignSetupModel GetKeyWords(CampaignSetupModel model)
        {
            if (model.AllCategories.Count == 0)
            {
                //model.AllCategories = (List<CampaignSetupModel.CategoriesModel>)Session["AllCategories"];
            }

            var catList = new List<string>();

            foreach (var cat in model.AllCategories)
            {
                catList.AddRange(from t in model.CategoryIds where cat.Id == t select cat.Name);
            }

            var scw = new ServiceClientWrapper();
            // create AdCopy array
            List<string> adtitletextList = new List<string>();
            foreach (SemplestModel.PromotionAd pad in model.AdModelProp.Ads)
            {
                adtitletextList.Add(pad.AdTitle + " " + pad.AdText);
            }

            // get keywords from the web service
            //List<string> keywords = scw.GetKeywords(catList, null, "coffee machine", null, null, "http://www.wholelattelove.com", null);
            var keywords = scw.GetKeywords(catList, null, model.ProductGroup.ProductPromotionName,
                                            model.ProductGroup.Words, adtitletextList.ToArray(), model.AdModelProp.Url, null);
            if (keywords != null && keywords.Count > 0)
            {
                foreach (var kwm in keywords.Select(key => new CampaignSetupModel.KeywordsModel { Name = key }))
                {
                    model.AllKeywords.Add(kwm);
                }
            }
            else
            {
                var logEnty = new LogEntry { ActivityId = Guid.NewGuid(), Message = "Could not get Keywords from web service" };
                Logger.Write(logEnty);
            }
            return model;
        }
Esempio n. 5
0
        public List<CampaignSetupModel.KeywordsModel> SaveNegativeKeywords(CampaignSetupModel model, int customerFk)
        {
            if (model.AdModelProp.NegativeKeywords.Any())
            {
                GoogleViolation[] gv = ValidateGoogleNegativeKeywords(model.AdModelProp.NegativeKeywords);
                if (gv.Length > 0)
                    throw new Exception(gv.First().shortFieldPath + ": " + gv.First().errorMessage);
            }
            using (var dbcontext = new SemplestModel.Semplest())
            {
                var promo = GetPromoitionFromCampaign(dbcontext, customerFk, model);
                if (!promo.IsLaunched)
                { RefreshKeywords(model, promo); }
                else
                {
                    var addKiops = new List<KeywordIdRemoveOppositePair>();
                    var addNewKiops = new List<string>();
                    var addDeletedKiops = new List<int>();
                    var qpka = promo.PromotionKeywordAssociations.ToList();
                    //check negative keywords that have been added to the gui
                    if (model.AdModelProp.NegativeKeywords != null)
                    {
                        foreach (string negativeKeyword in model.AdModelProp.NegativeKeywords)
                        {
                            var kiop = new KeywordIdRemoveOppositePair();
                            var pka = qpka.SingleOrDefault(key => key.Keyword.Keyword1 == negativeKeyword);
                            if (pka != null)
                            {
                                //means if the keyword existied and was positive it needs to be removed and added as a negative. 
                                //if the keyword is already negative then do nothing because we've already added it
                                kiop.keywordId = pka.KeywordFK;
                                if (!pka.IsNegative)
                                {
                                    kiop.removeOpposite = true;
                                    addKiops.Add(kiop);
                                }
                            }
                            else
                            {
                                var kw = dbcontext.Keywords.SingleOrDefault(key => key.Keyword1 == negativeKeyword);
                                if (kw != null)
                                {
                                    kiop.keywordId = kw.KeywordPK;
                                    kiop.removeOpposite = false;
                                    addKiops.Add(kiop);
                                }
                                else//this keyword doesn't exist in the database so when we call the stored proc get the id so it can be sent to the api
                                    addNewKiops.Add(negativeKeyword);
                            }
                        }
                    }

                    //check for negative keywords that have been removed from the gui
                    foreach (PromotionKeywordAssociation k in qpka.Where(key => key.IsNegative == true).ToList())
                    {
                        if (!model.AdModelProp.NegativeKeywords.Contains(k.Keyword.Keyword1))
                            addDeletedKiops.Add(k.Keyword.KeywordPK);
                    }

                    List<int> deletedKeywords = new List<int>();
                    var op = new System.Data.Objects.ObjectParameter("NegativeKeywordID", typeof(int));
                    var op2 = new System.Data.Objects.ObjectParameter("Exists", typeof(int));
                    foreach (string kw in model.AdModelProp.NegativeKeywords)
                    {
                        //keywords that need to be deleted
                        var snr = dbcontext.SetNegativeKeyword(kw, promo.PromotionPK, op, op2).ToList();
                        if (snr.Any())
                        {
                            deletedKeywords.AddRange(snr.Select(ids => ids.KeywordPK));
                        }

                        if (!string.IsNullOrEmpty(op.Value.ToString()))
                        {
                            var kop = new KeywordIdRemoveOppositePair { keywordId = int.Parse(op.Value.ToString()), removeOpposite = bool.Parse(op2.Value.ToString()) };
                            addKiops.Add(kop);
                        }
                    }
                    foreach (int dk in addDeletedKiops)
                        promo.PromotionKeywordAssociations.Single(kw => kw.KeywordFK == dk).IsDeleted=true;
                    dbcontext.SaveChanges();
                    _savedCampaign = true;
                    var sw = new ServiceClientWrapper();
                    var adEngines = new List<string>();
                    adEngines.AddRange(
                        promo.PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1));
                    if (addDeletedKiops.Any())
                        sw.DeleteNegativeKeywords(promo.PromotionPK, addDeletedKiops, adEngines);
                    if (addKiops.Any())
                        sw.AddNegativeKeywords(promo.PromotionPK, addKiops, adEngines);
                    if (deletedKeywords.Any())
                        sw.DeleteKeywords(promo.PromotionPK, deletedKeywords, adEngines);
                }
                model.AllKeywords.Clear();
                model.AllKeywords.AddRange(
                    promo.PromotionKeywordAssociations.Where(key => !key.IsDeleted && !key.IsNegative).Select(
                        key =>
                        new CampaignSetupModel.KeywordsModel { Name = key.Keyword.Keyword1, Id = key.Keyword.KeywordPK }));
            }
            return model.AllKeywords;
        }
Esempio n. 6
0
        public ActionResult LaunchAdProduct(CampaignSetupModel model)
        {
            ServiceClientWrapper sw = new ServiceClientWrapper();
            List<string> adEngines = new List<string>();
            if (ModelState.IsValid)
            {
                model = (CampaignSetupModel)Session["CampaignSetupModel"];
                //SemplestDataService ds = new SemplestDataService();
                //ds.SaveAd(model);
            }
            var dbContext = new SemplestModel.Semplest();
            //ProductGroup pg = dbContext.ProductGroups.Where(x => x.ProductGroupName == model.ProductGroup.ProductGroupName).First();
            //Promotion pm = dbContext.ProductGroups.Where(x => x.ProductGroupName==model.ProductGroup.ProductGroupName).First().Promotions.Where(p => p.PromotionName == model.ProductGroup.ProductPromotionName).First();
            var userid = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID])).UsersFK;
            int customerFk = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID])).User.CustomerFK.Value;
            var pm =
                dbContext.Users.First(x => x.UserPK == userid).Customer.ProductGroups.First(
                    x => x.ProductGroupName == model.ProductGroup.ProductGroupName).Promotions.First(
                    p => p.PromotionName == model.ProductGroup.ProductPromotionName);
            foreach (PromotionAdEngineSelected pades in pm.PromotionAdEngineSelecteds)
                adEngines.Add(pades.AdvertisingEngine.AdvertisingEngine1);
            try
            {
                pm.IsLaunched = sw.scheduleAddPromotionToAdEngine(customerFk, pm.ProductGroupFK, pm.PromotionPK, adEngines.ToArray()); ;
            }
            catch (Exception ex)
            {
                var logEnty = new LogEntry { ActivityId = Guid.NewGuid(), Message = ex.Message };
                Logger.Write(logEnty);
                pm.IsLaunched = true;
            }
            dbContext.SaveChanges();
            //return PartialView("KeyWords", model);

            //return View();
            //return Json("Congratulations, Your Product has Launched!!!");
            // now we are showing the image with wait window so we don't to show this in message box
            return Json("");
            //return Json("LaunchAdProduct");

        }
Esempio n. 7
0
        public ActionResult AddNewCard(FormCollection fc)
        {
            try
            {
                Credential c = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]));

                

                #region handle form data here....
                //handle form data
                if (fc["ExpirationDate"].ToString().Split(',')[0] == "-Select Month-" )
                { 
                    //no exp month has been selected
                }
                if (fc["ExpirationDate"].ToString().Split(',')[1] == "-Select Year-")
                { 
                    //no exp year has been selected
                }
                if (fc["CardNumber"].ToString() == "")
                {
                    //no card number entered
                }
                if (fc["FirstName"].ToString() == "")
                {
                    //no FirstName  entered
                }
                if (fc["LastName"].ToString() == "")
                {
                    //no LastName entered
                }
                if (fc["Address"].ToString() == "")
                {
                    //no Address entered
                }
                if (fc["City"].ToString() == "")
                {
                    //no City entered
                }
                if (fc["zip"].ToString() == "")
                {
                    //no zip entered
                }
                if (fc["phone"].ToString() == "")
                {
                    //no zip entered
                }
                if (fc["email"].ToString() == "")
                {
                    //no zip entered
                }

                #endregion

                //make api call 
                CustomerObject co = new CustomerObject() {  ExpireDateMMYY = fc["ExpirationDate"].ToString().Split(',')[0].ToString() + fc["ExpirationDate"].ToString().Split(',')[1],
                                                            creditCardNumber = fc["CardNumber"],
                                                            FirstName = fc["FirstName"].ToString(),
                                                            LastName = fc["FirstName"].ToString(),
                                                            Address1 = fc["Address"].ToString(),
                                                            City = fc["City"].ToString(),
                                                            ZipCode = fc["zip"].ToString(),
                                                            Phone = fc["phone"].ToString(),
                                                            Email = fc["email"].ToString(),
                                                             StateAbbr=fc["state"].ToString()};

                ServiceClientWrapper scw=new ServiceClientWrapper();
                GatewayReturnObject myret = scw.CreateProfile(co);
                if (myret.Message != "Profile Request Processed") throw new Exception();
                if (myret.isGood != true) throw new Exception();


                string customerreferencenumber = myret.CustomerRefNum.ToString();
                var dbContext = new SemplestModel.Semplest();
                var custid = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID])).User.Customer.CustomerPK;
                var trans = dbContext.CreditCardProfiles.Add(new CreditCardProfile() { CustomerFK = custid, CustomerRefNum = customerreferencenumber });
                
                //to do: add nickname for dropdown so that we can avoid calling the cc api everytime we are on the billinglaunch page
                //save nickname to creditcardprofiles
                

                //return to billinglaunch,
                //update the card drop down, select the last one added





                /////////////////////////////////////////////////////
                //info: to charge card call AuthorizeAndCapture below
                //double amountToCharge=2.0;
                //GatewayReturnObject myret3 = scw.AuthorizeAndCapture(myret.CustomerRefNum, amountToCharge);

               



            }
            catch (Exception ex)
            {

            }

            return View();


        }
Esempio n. 8
0
        public string SaveGeoTargetingAds(int customerFK, CampaignSetupModel model, CampaignSetupModel oldModel)
        {
            var rString = new System.Text.StringBuilder();
            using (var dbcontext = new SemplestModel.Semplest())
            {
                var queryProd = (from c in dbcontext.ProductGroups
                                 where
                                     c.CustomerFK == customerFK &&
                                     c.ProductGroupName == model.ProductGroup.ProductGroupName
                                 select c).Single();
                var promo = GetPromotionFromProductGroup(queryProd, model.ProductGroup.ProductPromotionName);

                List<PromotionAd> addAds;
                List<int> updateAds;
                List<int> deleteAds;
                GoogleViolation[] gv;
                PromoAdTableType at;
                var shouldscheduleAds = AddPromotionAdsToPromotion(promo, model, customerFK, oldModel,
                                                   out addAds, out updateAds, out deleteAds, out at);
                if (shouldscheduleAds)
                {
                    List<GoogleAddAdRequest> verifyAds =
                      model.AdModelProp.Ads.Where(t => !t.Delete).Select(pad => new GoogleAddAdRequest
                      {
                          promotionAdID = promo.PromotionPK,
                          headline = pad.AdTitle,
                          description1 =
                              pad.AdTextLine1,
                          description2 =
                              pad.AdTextLine2
                      }).ToList();
                    gv = ValidateAds(model.AdModelProp.LandingUrl,
                                                                           model.AdModelProp.DisplayUrl, verifyAds);
                    if (gv.Length > 0)
                        throw new Exception(gv.First().shortFieldPath + ": " + gv.First().errorMessage);
                }
                GeoTargetTableType gt;
                int addressCode =-1;
                var st = dbcontext.AddressTypes.SingleOrDefault(pt => pt.AddressType1 == model.AdModelProp.PromotionAddressType);
                if (st != null)
                    addressCode = st.AddressTypePK;
                var shouldUpdateGeoTargeting = AddGeoTargetingToPromotion(promo, model, customerFK, oldModel, out gt);
                if (shouldUpdateGeoTargeting)
                {
                    var gtos = SerializeToGeoTargetObjectArray(model);
                    if (gtos.Any())
                    {
                        gv = ValidateGeotargeting(gtos);
                        if (gv.Length > 0)
                            throw new Exception(gv.First().shortFieldPath + ": " + gv.First().errorMessage);
                    }
                }

                var parameter = new SqlParameter("PromotionPK", promo.PromotionPK) { SqlDbType = SqlDbType.Int };
                var parameter2 = new SqlParameter("LandingUrl", model.AdModelProp.LandingUrl.Trim()) { SqlDbType = SqlDbType.NVarChar };
                var parameter3 = new SqlParameter("DisplayUrl", model.AdModelProp.DisplayUrl.Trim()) { SqlDbType = SqlDbType.NVarChar };
                var parameter4 = new SqlParameter("AddressTypeFK", addressCode) { SqlDbType = SqlDbType.Int };
                var parameter5 = new SqlParameter("GeoTVP", gt) { SqlDbType = SqlDbType.Structured, TypeName = "GeoTargetTableType" };
                var parameter6 = new SqlParameter("AdTVP", at) { SqlDbType = SqlDbType.Structured, TypeName = "PromoAdTableType" };
                var parameters = new object[] {parameter, parameter2, parameter3, parameter4, parameter5, parameter6};
                var results = ((IObjectContextAdapter)dbcontext).ObjectContext.ExecuteStoreQuery<RVal>("exec UpdateGeoTargetingPromoAds @PromotionPK, @LandingUrl, @DisplayUrl, @AddressTypeFK, @GeoTVP, @AdTVP", parameters);
                _savedCampaign = true;
                foreach (var r in results)
                {
                    rString.Append(r.UID);
                    rString.Append("=");
                    rString.Append(r.PKEY);
                    rString.Append(",");
                }
                    
                if (promo.IsLaunched)
                {
                    var sw = new ServiceClientWrapper();
                    var adEngines = new List<string>();
                    adEngines.AddRange(
                            promo.PromotionAdEngineSelecteds.Select(
                                pades => pades.AdvertisingEngine.AdvertisingEngine1));
                    if (shouldscheduleAds)
                    {
                        if (addAds.Any())
                        {
                            var addAdsIds =
                                addAds.Select(
                                    promoAd =>
                                    dbcontext.PromotionAds.Single(
                                        row =>
                                        row.AdTextLine1 == promoAd.AdTextLine1 && row.AdTextLine2 == promoAd.AdTextLine2 &&
                                        row.AdTitle == promoAd.AdTitle && row.PromotionFK == promo.PromotionPK).
                                        PromotionAdsPK).ToList();
                            sw.scheduleAds(promo.PromotionPK, addAdsIds, adEngines,
                                           SEMplestConstants.PromotionAdAction.Add);
                        }
                        if (updateAds.Any())
                            sw.scheduleAds(promo.PromotionPK, updateAds, adEngines,
                                           SEMplestConstants.PromotionAdAction.Update);
                        if (deleteAds.Any())
                            sw.scheduleAds(promo.PromotionPK, deleteAds, adEngines,
                                           SEMplestConstants.PromotionAdAction.Delete);
                    }
                    if (shouldUpdateGeoTargeting)
                        sw.scheduleUpdateGeoTargeting(promo.PromotionPK, adEngines);
                }
            }
            return string.IsNullOrEmpty(rString.ToString()) ? String.Empty : rString.ToString().Substring(0, rString.ToString().Length - 1);
        }
Esempio n. 9
0
        public ActionResult GetCategories(SearchKeywordsModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var scw = new ServiceClientWrapper();
                    var addcopies = new[] { model.AdCopy };
                    List<string> categories = scw.GetCategories(null, model.Product, model.Description, addcopies,
                                                                model.LandingPage);
                    if (categories != null && categories.Count > 0)
                    {
                        int i = 0;
                        foreach (string cate in categories)
                        {
                            var cm = new SearchKeywordsModel.CategoriesModel { Id = i, Name = cate };
                            i++;
                            model.AllCategories.Add(cm);
                        }
                    }
                    else
                    {
                        CreateDummyModel(model);
                    }

                    // save this some how while getting the keywords this is becoming null
                    Session.Add("AllCategories", model.AllCategories);
                }
                return View(model);
            }
            catch (Exception ex)
            {
                string err = ex.Message + "\\r\\n" + ex.StackTrace;
                //CreateDummyModel(model);
                //ViewBag.AllCategories = model.AllCategories;
                //Session.Add("AllCategories", model.AllCategories);
                return View(model);
            }
        }
Esempio n. 10
0
 private GoogleViolation[] ValidateGeotargeting(List<GeoTargetObject> gto)
 {
     var sw = new ServiceClientWrapper();
     return sw.ValidateGoogleGeoTargets(gto);
 }
Esempio n. 11
0
 private GoogleViolation[] ValidateGoogleNegativeKeywords(List<string> negativeKeywords)
 {
     var sw = new ServiceClientWrapper();
     return sw.ValidateGoogleNegativeKeywords(negativeKeywords);
 }
Esempio n. 12
0
        public ActionResult Preview(int promotionId)
        {
            var scw = new ServiceClientWrapper();
            scw.SendEmail("subject", "*****@*****.**", "*****@*****.**", "test mail");

            var campaignSetupModel = _campaignRepository.GetCampaignSetupModelForPromotionId(promotionId);
            //set sitelinks in session
            //if (!string.IsNullOrEmpty(campaignSetupModel.ProductGroup.StartDate))
            //    campaignSetupModel.ProductGroup.StartDate =
            //        Convert.ToDateTime(campaignSetupModel.ProductGroup.StartDate).ToString("MM/dd/yyyy");
            //if (!string.IsNullOrEmpty(campaignSetupModel.ProductGroup.EndDate))
            //    campaignSetupModel.ProductGroup.EndDate =
            //        Convert.ToDateTime(campaignSetupModel.ProductGroup.EndDate).ToString("MM/dd/yyyy");
            Session.Add("AddsStoreModel", new AddsStoreModel { Ads = campaignSetupModel.AdModelProp.Ads.ToList() });

            // set negative keywords in session
            Session["NegativeKeywords"] = campaignSetupModel.AdModelProp.NegativeKeywords;
            Session["NegativeKeywordsText"] = campaignSetupModel.AdModelProp.NegativeKeywordsText;

            campaignSetupModel.ProductGroup.IsEdit = true;
            return PartialView(campaignSetupModel);
        }
Esempio n. 13
0
        public void SaveGeoTargetingAds(int customerFK, CampaignSetupModel model, CampaignSetupModel oldModel)
        {
            using (var dbcontext = new SemplestModel.Semplest())
            {
                var queryProd = (from c in dbcontext.ProductGroups
                                 where
                                     c.CustomerFK == customerFK &&
                                     c.ProductGroupName == model.ProductGroup.ProductGroupName
                                 select c).Single();
                var promo = GetPromotionFromProductGroup(queryProd, model.ProductGroup.ProductPromotionName);

                List<PromotionAd> addAds;
                List<int> updateAds;
                List<int> deleteAds;
                GoogleViolation[] gv;
                var shouldscheduleAds = AddPromotionAdsToPromotion(promo, model, customerFK, oldModel,
                                                   out addAds, out updateAds, out deleteAds);
                if (shouldscheduleAds)
                {
                    List<GoogleAddAdRequest> verifyAds =
                      model.AdModelProp.Ads.Where(t => !t.Delete).Select(pad => new GoogleAddAdRequest
                      {
                          promotionAdID = promo.PromotionPK,
                          headline = pad.AdTitle,
                          description1 =
                              pad.AdTextLine1,
                          description2 =
                              pad.AdTextLine2
                      }).ToList();
                    gv = ValidateAds(model.AdModelProp.LandingUrl,
                                                                           model.AdModelProp.DisplayUrl, verifyAds);
                    if (gv.Length > 0)
                        throw new Exception(gv.First().shortFieldPath + ": " + gv.First().errorMessage);
                }
                var shouldUpdateGeoTargeting = AddGeoTargetingToPromotion(promo, model, customerFK, oldModel,
           ((IObjectContextAdapter)dbcontext).ObjectContext);
                if (shouldUpdateGeoTargeting)
                {
                    var gtos = SerializeToGeoTargetObjectArray(model);
                    if (gtos.Any())
                    {
                        gv = ValidateGeotargeting(gtos);
                        if (gv.Length > 0)
                            throw new Exception(gv.First().shortFieldPath + ": " + gv.First().errorMessage);
                        var op = new System.Data.Objects.ObjectParameter("totalSize", typeof(int));
                        string valueDelimiter = ",";
                        string listDelimiter = ";";
                        dbcontext.GetMSNGeoLocation(null, SerializeToCommaDlimitedString(model.AdModelProp.Addresses, valueDelimiter, listDelimiter), valueDelimiter, listDelimiter, op);
                        if ((int)op.Value > 250)
                            throw new Exception("geotarget limit");
                    }
                }
                promo.LandingPageURL = model.AdModelProp.LandingUrl.Trim();
                promo.DisplayURL = model.AdModelProp.DisplayUrl.Trim();
                dbcontext.SaveChanges();
                _savedCampaign = true;

                if (promo.IsLaunched)
                {
                    var sw = new ServiceClientWrapper();
                    var adEngines = new List<string>();
                    adEngines.AddRange(
                            promo.PromotionAdEngineSelecteds.Select(
                                pades => pades.AdvertisingEngine.AdvertisingEngine1));
                    if (shouldscheduleAds)
                    {
                        if (addAds.Any())
                        {
                            var addAdsIds =
                                addAds.Select(
                                    promoAd =>
                                    dbcontext.PromotionAds.Single(
                                        row =>
                                        row.AdTextLine1 == promoAd.AdTextLine1 && row.AdTextLine2 == promoAd.AdTextLine2 &&
                                        row.AdTitle == promoAd.AdTitle && row.PromotionFK == promo.PromotionPK).
                                        PromotionAdsPK).ToList();
                            sw.scheduleAds(promo.PromotionPK, addAdsIds, adEngines,
                                           SEMplestConstants.PromotionAdAction.Add);
                        }
                        if (updateAds.Any())
                            sw.scheduleAds(promo.PromotionPK, updateAds, adEngines,
                                           SEMplestConstants.PromotionAdAction.Update);
                        if (deleteAds.Any())
                            sw.scheduleAds(promo.PromotionPK, deleteAds, adEngines,
                                           SEMplestConstants.PromotionAdAction.Delete);
                    }
                    if (shouldUpdateGeoTargeting)
                        sw.scheduleUpdateGeoTargeting(promo.PromotionPK, adEngines);
                }
            }
        }
Esempio n. 14
0
 private bool SendAccountActivationEmail(int userId)
 {
     var scw = new ServiceClientWrapper();
     return scw.SendAccountActivationEmail(userId);
 }
Esempio n. 15
0
 public bool ValidateAccountActivationToken(string token)
 {
     var scw = new ServiceClientWrapper();
     return scw.ValidateAccountActivationToken(token);
 }
Esempio n. 16
0
 public ActionResult EndPromotion(int promotionIdE)
 {
     try
     {
         ServiceClientWrapper sw = new ServiceClientWrapper();
         SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
         List<string> adEngines = new List<string>();
         Promotion p = dbContext.Promotions.Where(x => x.PromotionPK == promotionIdE).First();
         int customerId = ((Credential)Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).User.CustomerFK.Value;
         foreach (PromotionAdEngineSelected pades in p.PromotionAdEngineSelecteds)
             adEngines.Add(pades.AdvertisingEngine.AdvertisingEngine1);
         p.IsCompleted = sw.schedulePromotion(promotionIdE, adEngines.ToArray(), SEMplestConstants.SchedulePromotionType.End);
         dbContext.SaveChanges();
     }
     catch (Exception ex) { Semplest.SharedResources.Helpers.ExceptionHelper.LogException(ex); }
     return RedirectToAction("Index2");
 }
Esempio n. 17
0
 public ActionResult RemovePromotion(int promotionId)
 {
     try
     {
         ServiceClientWrapper sw = new ServiceClientWrapper();
         SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
         int customerId = ((Credential)Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).User.CustomerFK.Value;
         dbContext.Promotions.First(x => x.PromotionPK == promotionId).IsDeleted = sw.schedulePromotion(promotionId, dbContext.Promotions.First(x => x.PromotionPK == promotionId).PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1).ToArray(), SEMplestConstants.SchedulePromotionType.Delete);
         dbContext.SaveChanges();
     }
     catch (Exception ex) { Semplest.SharedResources.Helpers.ExceptionHelper.LogException(ex); }
     return RedirectToAction("Index2");
 }
Esempio n. 18
0
        public ActionResult GetKeywords(SearchKeywordsModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    model.StatusMessage = "Please wait while getting the Keywords";
                    //SemplestWebApp.Helpers.ServiceHelper.CallSemplestTestGetMethod();
                    if (model.AllCategories.Count == 0)
                    {
                        model.AllCategories = (List<SearchKeywordsModel.CategoriesModel>)Session["AllCategories"];
                    }

                    if (model.AllCategories.Count <= 0)
                    {
                    }

                    var catList = new List<string>();

                    foreach (SearchKeywordsModel.CategoriesModel cat in model.AllCategories)
                    {
                        for (int i = 0; i < model.ItemIds.Length; i++)
                        {
                            if (cat.Id == model.ItemIds[i])
                            {
                                catList.Add(cat.Name);
                            }
                        }
                    }


                    var scw = new ServiceClientWrapper();
                    //var query = from c in model.AllCategories
                    //            let i = c.Id
                    //            where model.ItemIds.Contains(i)
                    //            select  c.Name ;
                    //List<string> catList = model.AllCategories.Select(m => m.Name).Where(
                    //List<string> keywords = scw.GetKeywords(catList, null, "coffee machine", null, null, "http://www.wholelattelove.com", null);
                    var addcopies = new[] { model.AdCopy };
                    //List<string> keywords = scw.GetKeywords(catList, null, model.Product, model.Description, addcopies,
                    //                                        model.LandingPage, null);
                    //if (keywords != null && keywords.Count > 0)
                    //{
                    //    int i = 0;
                    //    foreach (string key in keywords)
                    //    {
                    //        var kwm = new SearchKeywordsModel.KeywordsModel();
                    //        kwm.Name = key;
                    //        model.AllKeywords.Add(kwm);
                    //    }
                    //}
                    //else
                    //{
                        CreateDummyModel(model);
                    //}
                }

                return View(model);
            }
            catch (Exception ex)
            {
                string err = ex.Message + "\\r\\n" + ex.StackTrace;
                //CreateDummyModel(model);
                return View(model);
            }
        }
Esempio n. 19
0
 public void SetKeywordsDeleted(List<int> keywordIds, int promoId)
 {
     using (var dbcontext = new SemplestModel.Semplest())
     {
         foreach (int keywordId in keywordIds)
             dbcontext.PromotionKeywordAssociations.Where(key => key.KeywordFK == keywordId).First(
                 key => key.PromotionFK == promoId).IsDeleted = true;
         dbcontext.SaveChanges();
         _savedCampaign = true;
         var adEngines = new List<string>();
         var promo = dbcontext.Promotions.Single(row => row.PromotionPK == promoId);
         if (promo.IsLaunched)
         {
             var sw = new ServiceClientWrapper();
             adEngines.AddRange(
                     promo.PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1));
             sw.DeleteKeywords(promoId, keywordIds, adEngines);
         }
     }
 }
Esempio n. 20
0
 public void SaveSiteLinks(CampaignSetupModel model, int customerFk, CampaignSetupModel oldModel)
 {
     bool shouldRefreshSiteLinks = false;
     using (var dbcontext = new SemplestModel.Semplest())
     {
         var queryProd = (from c in dbcontext.ProductGroups
                          where
                              c.CustomerFK == customerFk &&
                              c.ProductGroupName == model.ProductGroup.ProductGroupName
                          select c).Single();
         var promo = GetPromotionFromProductGroup(queryProd, model.ProductGroup.ProductPromotionName);
         List<GoogleSiteLink> sl =
                                   model.SiteLinks.Where(t => !t.Delete).Select(row => new GoogleSiteLink
                                   {
                                       LinkText = row.LinkText,
                                       LinkURL = row.LinkURL
                                   }).ToList();
         if (sl.Any())
         {
             GoogleViolation[] gv = ValidateSiteLinks(sl);
             if (gv.Length > 0)
                 throw new Exception(gv.First().shortFieldPath + ": " + gv.First().errorMessage);
         }
         shouldRefreshSiteLinks = AddSiteLinksToPromotion(promo, model, customerFk, ((IObjectContextAdapter)dbcontext).ObjectContext, oldModel);
         dbcontext.SaveChanges();
         _savedCampaign = true;
         try
         {
             var adEngines = new List<string>();
             if (promo.IsLaunched && shouldRefreshSiteLinks)
             {
                 adEngines.AddRange(
                     promo.PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1));
                 var sw = new ServiceClientWrapper();
                 sw.scheduleRefreshSiteLinks(promo.PromotionPK, adEngines);
             }
         }
         catch (Exception ex)
         {
             SharedResources.Helpers.ExceptionHelper.LogException(ex);
         }
     }
 }
Esempio n. 21
0
 private GoogleViolation[] ValidateSiteLinks(List<GoogleSiteLink> sl)
 {
     var sw = new ServiceClientWrapper();
     return sw.ValidateGoogleRefreshSiteLinks(sl);
 }
Esempio n. 22
0
 public void AddSiteLinksToPromotion(Promotion promo, CampaignSetupModel model, int customerFk)
 {
     if (model.SiteLinks != null)
         foreach (var sitelink in model.SiteLinks)
         {
             var slink = new SiteLink
             {
                 LinkText = sitelink.LinkText,
                 LinkURL = sitelink.LinkURL,
                 PromotionFK = promo.PromotionPK
             };
             promo.SiteLinks.Add(slink);
             try
             {
                 var sw = new ServiceClientWrapper();
                 var adEngines = new List<string>();
                 if (promo.IsLaunched)
                 {
                     adEngines.AddRange(promo.PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1));
                     sw.scheduleRefreshSiteLinksForAd(customerFk, promo.PromotionPK, adEngines);
                 }
             }
             catch (Exception ex) { SharedResources.Helpers.ExceptionHelper.LogException(ex.ToString()); }
         }
 }
Esempio n. 23
0
 private GoogleViolation[] ValidateAds(String landingPageURL, String displayURL, List<GoogleAddAdRequest> ads)
 {
     var sw = new ServiceClientWrapper();
     return sw.ValidateGoogleAd(landingPageURL, displayURL, ads);
 }
Esempio n. 24
0
        public void AddGeoTargetingToPromotion(Promotion promo, CampaignSetupModel model, int customerFk)
        {
            if (model.AdModelProp.Addresses != null)
            {
                foreach (GeoTargeting geo in model.AdModelProp.Addresses)
                {
                    // this is check should be removed once we fix the logic in partialview and model
                    if (!String.IsNullOrEmpty(geo.Zip) || (!String.IsNullOrEmpty(geo.City) && geo.StateCodeFK > 0))
                    {
                        if (geo.StateCodeFK < 0)
                            geo.StateCodeFK = null;

                        var geotarget = new GeoTargeting
                        {
                            Address = geo.Address,
                            City = geo.City,
                            StateCodeFK = geo.StateCodeFK,
                            Zip = geo.Zip,
                            ProximityRadius = geo.ProximityRadius,
                            Latitude = geo.Latitude,
                            Longitude = geo.Longitude
                        };
                        promo.GeoTargetings.Add(geotarget);
                        try
                        {
                            var sw = new ServiceClientWrapper();
                            var adEngines = new List<string>();
                            if (promo.IsLaunched)
                            {
                                adEngines.AddRange(promo.PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1));
                                sw.scheduleUpdateGeoTargeting(customerFk, promo.PromotionPK, adEngines);
                            }
                        }
                        catch (Exception ex) { SharedResources.Helpers.ExceptionHelper.LogException(ex.ToString()); }
                    }
                }
            }
        }
Esempio n. 25
0
 public void SaveProductPromotion(int customerFk, CampaignSetupModel model, CampaignSetupModel oldModel)
 {
     using (var dbcontext = new SemplestModel.Semplest())
     {
         var queryProdGrp = from c in dbcontext.ProductGroups
                            where
                                c.CustomerFK == customerFk &&
                                c.ProductGroupName == model.ProductGroup.ProductGroupName
                            select c;
         if (!queryProdGrp.Any())
         {
             //create new productgroup and promotion
             var prodgroup = new ProductGroup
             {
                 ProductGroupName = model.ProductGroup.ProductGroupName,
                 IsActive = true,
                 CustomerFK = customerFk,
                 StartDate =
                     Convert.ToDateTime(model.ProductGroup.StartDate,
                                        new CultureInfo("en-Us")),
                 EndDate =
                     String.IsNullOrEmpty(model.ProductGroup.EndDate)
                         ? (DateTime?)null
                         : Convert.ToDateTime(model.ProductGroup.EndDate)
             };
             var promo = CreatePromotionFromModel(model,
                                                     dbcontext.Configurations.First().
                                                         CustomerDefaultPerCampaignFlatFeeAmount);
             dbcontext.ProductGroups.Add(prodgroup);
             dbcontext.Promotions.Add(promo);
             SavePromotionAdEngineSelected(promo,model, dbcontext);
             dbcontext.SaveChanges();
             _savedCampaign = true;
         }
         else
         {//productgroupexists
             var updateProdGrp = queryProdGrp.Single();
             var updatePromotion = GetPromotionFromProductGroup(updateProdGrp,
                                                                model.ProductGroup.ProductPromotionName);
             // if this is null means promotion name changed so create a new promotion
             if (updatePromotion == null)
             {
                 // create new promotion
                 updatePromotion = CreatePromotionFromModel(model,
                                                            dbcontext.Configurations.First().
                                                                CustomerDefaultPerCampaignFlatFeeAmount);
                 updatePromotion.ProductGroupFK = updateProdGrp.ProductGroupPK;
                 dbcontext.Promotions.Add(updatePromotion);
                 SavePromotionAdEngineSelected(updatePromotion, model, dbcontext);
             }
             else
             {
                 // update promotion
                 UpdatePromotionFromModel(updatePromotion, model, dbcontext.Configurations.First().CustomerDefaultPerCampaignFlatFeeAmount);
                 if (updatePromotion.IsLaunched)
                 {
                     var sw = new ServiceClientWrapper();
                     var adEngines = new List<string>();
                     adEngines.AddRange(
                         updatePromotion.PromotionAdEngineSelecteds.Select(
                             pades => pades.AdvertisingEngine.AdvertisingEngine1));
                     if (model.ProductGroup.Budget != oldModel.ProductGroup.Budget)
                         sw.scheduleUpdateBudget(updatePromotion.PromotionPK, model.ProductGroup.Budget,
                                                 adEngines);
                     if (Convert.ToDateTime(model.ProductGroup.StartDate) != Convert.ToDateTime(oldModel.ProductGroup.StartDate))
                         sw.scheduleChangePromotionStartDate(updatePromotion.PromotionPK,
                                                             updatePromotion.PromotionStartDate, adEngines);
                 }
                 SavePromotionAdEngineSelected(updatePromotion, model, dbcontext);
             }
         }
         dbcontext.SaveChanges();
         // we need to set this because the _dbcontext is  and campaign is updated so reflect changes we need to create new context
         _savedCampaign = true;
     }
 }
        public ActionResult Add(CustomerAccountWithEmployeeModel m, string command, FormCollection fc )
        {
            
            if (command.ToLower() == "cancel") return RedirectToAction("Index");


            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();

            


            //check if userid has been taken by other users

            var userIDSs = from c in dbcontext.Credentials
                        where c.Username.Equals(m.CustomerAccount.UserID) 
                        select c;
            if (userIDSs.Count() > 0)
                      ModelState.AddModelError("CustomerAccount.UserID", "This UserID is already taken!!");

               
                  if (!ModelState.IsValid)
                  {
                      //repopulate 
                   #region needs to repopulate lists to get the same view again

                      var roles = (from r in dbcontext.Roles select r).ToList().OrderBy(r => r.RoleName);

                      m.Roles = roles.Select(r => new SelectListItem
                      {
                          Value = r.RolePK.ToString(),
                          Text = r.RoleName.ToString()
                      });




                      //repopualte

                      var allreps = from e in dbcontext.Employees
                                    //join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK
                                    join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
                                    join u in dbcontext.Users on e.UsersFK equals u.UserPK
                                    where (et.EmployeeType1 == "Rep" && u.IsActive.Equals(true))
                                    select new EmployeeCustomerAssociaitionModel
                                    {
                                        //AccountNumber = eca.CustomerFK,
                                        employeePK = e.EmployeePK,
                                        EmployeeType = et.EmployeeType1,
                                        EmployeeUserPK = u.UserPK,
                                        FirstName = u.FirstName,
                                        MiddleInitial = u.MiddleInitial,
                                        LastName = u.LastName
                                    };



                      /////////////////////////////////////////////////////////////////////////////////
                      //for sales dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var allsalespersons = from e in dbcontext.Employees
                                            //join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK
                                            join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID
                                            join u in dbcontext.Users on e.UsersFK equals u.UserPK
                                            where (et.EmployeeType1 == "Sales" && u.IsActive.Equals(true))
                                            select new EmployeeCustomerAssociaitionModel
                                            {
                                                //AccountNumber = eca.CustomerFK,
                                                employeePK = e.EmployeePK,
                                                EmployeeType = et.EmployeeType1,
                                                EmployeeUserPK = u.UserPK,
                                                FirstName = u.FirstName,
                                                MiddleInitial = u.MiddleInitial,
                                                LastName = u.LastName
                                            };


                      var allparents =
              from c in dbcontext.Customers
              join chi in dbcontext.CustomerHierarchies.Where(p => p.CustomerParentFK == null) on c.CustomerPK equals chi.CustomerFK
              select c;

                      List<SelectListItem> sli = new List<SelectListItem>();


                      sli.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Parent »»" });
                      sli.Add(new SelectListItem { Value = (0).ToString(), Text = "«« Single User   »»" });

                      //x.SelectedParentID = -1;

                      m.Parents = allparents.ToList().Select(r => new SelectListItem
                      {
                          Value = r.CustomerPK.ToString(),
                          Text = r.Name.ToString()
                      }).Union(sli);



                      /////////////////////////////////////////////////////////////////////////////////
                      //for billtype dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var allbilltypes = (from a in dbcontext.BillTypes select a).ToList();

                      
                      m.BillTypes = allbilltypes.Select(r => new SelectListItem
                      {
                          Value = r.BillTypePK.ToString(),
                          Text = r.BillType1.ToString()
                      });




                      //for state dropdown
                      /////////////////////////////////////////////////////////////////////////////////
                      var allstates = (from sc in dbcontext.StateCodes select sc).ToList();
                      
                      m.States = allstates.Select(r => new SelectListItem
                      {
                          Value = r.StateAbbrPK.ToString(),
                          Text = r.StateAbbr.ToString()
                      });


                      List<SelectListItem> slina = new List<SelectListItem>();
                      slina.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Not Assigned »»" });



                      List<EmployeeCustomerAssociaitionModel> ll1 = allreps.OrderBy(r => r.LastName).ThenBy(r => r.FirstName).ToList(); ;
                      List<SelectListItem> sl1 = new List<SelectListItem>();
                      foreach (EmployeeCustomerAssociaitionModel s in ll1)
                      {
                          SelectListItem mylistitem = new SelectListItem();
                          mylistitem.Text = s.FirstName + " " + s.LastName;
                          mylistitem.Value = s.employeePK.ToString();
                          sl1.Add(mylistitem);
                      }
                      m.Reps = sl1.Union(slina);


                      List<EmployeeCustomerAssociaitionModel> ll2 = allsalespersons.OrderBy(r => r.LastName).ThenBy(r => r.FirstName).ToList();
                      List<SelectListItem> sl2 = new List<SelectListItem>();
                      foreach (EmployeeCustomerAssociaitionModel s in ll2)
                      {
                          SelectListItem mylistitem = new SelectListItem();
                          mylistitem.Text = s.FirstName + " " + s.LastName;
                          mylistitem.Value = s.employeePK.ToString();
                          sl2.Add(mylistitem);
                      }
                      m.SalesPersons = sl2.Union(slina);
                      return View(m);     
   #endregion
                  }

             

            try
            {
                


                //BillType bt = dbcontext.BillTypes.First(p => p.BillType1 == "Flat Fee"); // --- feees --- !!!
                //revisit 
                ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30");

                var c = new Customer
                            { 
                                Name = m.CustomerAccount.Customer,
                                BillTypeFK = m.SelectedBillTypeID,
                                ProductGroupCycleType = pgct,
                                 PercentOfMedia=m.CustomerAccount.PercentMedia,
                                 ServiceFee= m.CustomerAccount.ServiceFee,
                                  InternalCustomerId= m.CustomerAccount.internalID,
                                PromotionFeeAmount = m.CustomerAccount.PromotionFeeAmount,
                                CreditLimit=m.CustomerAccount.CreditLimit,
                                PromotionFeeOverride=m.CustomerAccount.PromotionFeeOverride 
                            };

                dbcontext.Customers.Add(c);

                var u = new User
                            {
                                Customer = c,
                                Email = m.CustomerAccount.Email,
                                FirstName = m.CustomerAccount.FirstName,
                                LastName = m.CustomerAccount.LastName,
                                MiddleInitial = m.CustomerAccount.MiddleInitial,
                                IsActive = m.CustomerAccount.isActive
                            };
                dbcontext.Users.Add(u);

                var r = dbcontext.Roles.First(p => p.RolePK == m.SelectedRoleID);
                var ura = new UserRolesAssociation { Role = r, User = u };
                dbcontext.UserRolesAssociations.Add(ura);


                //
                var cr = new Credential
                             { 
                                 User = u,
                                 UsersFK = u.UserPK,
                                 Username = m.CustomerAccount.UserID,
                                 Password = m.CustomerAccount.UserPassword
                             };
                dbcontext.Credentials.Add(cr);


                PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!!
                var ph = new Phone {Phone1 = m.CustomerAccount.Phone, PhoneType = pt};
                dbcontext.Phones.Add(ph);

                var cpa = new CustomerPhoneAssociation {Customer = c, Phone = ph};
                dbcontext.CustomerPhoneAssociations.Add(cpa);

                var sc = dbcontext.StateCodes.First(p => p.StateAbbrPK == m.SelectedStateID);
                var at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!!

                var a = new Address
                            {
                                Address1 = m.CustomerAccount.Address1,
                                Address2 = m.CustomerAccount.Address2,
                                City = m.CustomerAccount.City,
                                ZipCode = m.CustomerAccount.Zip,
                                StateCode = sc
                            };
                dbcontext.Addresses.Add(a);

                var caa = new CustomerAddressAssociation {Address = a, Customer = c, AddressType = at};
                dbcontext.CustomerAddressAssociations.Add(caa);

                var cn = new CustomerNote {Customer = c, Note = m.CustomerAccount.CustomerNote};
                dbcontext.CustomerNotes.Add(cn);

                
                //don't add if not assigned
                if (m.SelectedRepID != -1)
                {
                    var addrep = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedRepID };
                    dbcontext.EmployeeCustomerAssociations.Add(addrep);
                }
                
                //don't add if not assigned
                if (m.SelectedSalesPersonID != -1)
                {
                    var addsales = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedSalesPersonID };
                    dbcontext.EmployeeCustomerAssociations.Add(addsales);
                }

                CustomerHierarchy ch = null;
                if (m.SelectedParentID == -1) //set parent
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = null};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                else if (m.SelectedParentID == 0) //set self -- single user
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = c.CustomerPK};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                else //assign a parent
                {
                    ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = m.SelectedParentID};
                    dbcontext.CustomerHierarchies.Add(ch);
                }
                dbcontext.SaveChanges();

                /////////////////////////////////////////////////////////////////////////////
                ///// sending of emails
                AesEncyrption ae = AesEncyrption.getInstance();
                string encryptedToken = ae.GenerateToken(ch.CustomerParentFK.Value.ToString(), DateTime.Now.ToString(), cr.Username, cr.Password);
                string emailUrl = System.Configuration.ConfigurationManager.AppSettings["VerificationUrl"].ToString() + encryptedToken;
                if (fc["sendcustomeremail"] != null)
                {
                    string from, to, body, subject;

                    //send email to child customers
                    //if  child customer
                    if (m.SelectedParentID >0)
                    {
                        var emailtemplate = (
                                            from et in dbcontext.EmailTemplates
                                            join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK
                                            where ey.EmailType1.Equals("WelcomeEmailChild")
                                            select et).FirstOrDefault();

                        var parentdetails = from usr in dbcontext.Users
                                            join cus in dbcontext.Customers on usr.CustomerFK equals cus.CustomerPK
                                            where usr.CustomerFK == m.SelectedParentID
                                            select new { usr.CustomerFK, usr.Email, cus.Name };

                        //send mail //revisit
                        from = "*****@*****.**";
                        to = u.Email;
                        body = emailtemplate.EmailBody;
                        //parent name in subject line
                        subject = parentdetails.FirstOrDefault().Name + " " +emailtemplate.EmailSubject;
                        body = body.Replace("[ChildCustomerFirstLast]", u.FirstName.ToString() + " " + u.LastName.ToString());
                        body = body.Replace("[ParentCustomerName]", parentdetails.FirstOrDefault().Name.ToString());
                        body = body.Replace("[FAQs]", "http://faq");
                        body = body.Replace("[ChildCustomerUserID]", cr.Username.ToString());
                        body = body.Replace("[ChildCustomerPassword]", cr.Password.ToString());
                        body = body.Replace("[INSERT LINK]", emailUrl);
                        bool sent = false;
                        ServiceClientWrapper scw = new ServiceClientWrapper();
                        sent = scw.SendEmail(subject, from, to, body);
                    }


                    if (m.SelectedParentID == -1) ///set parent
                    {
                        var emailtemplate = (
                                            from et in dbcontext.EmailTemplates
                                            join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK
                                            where ey.EmailType1.Equals("WelcomeEmailParent")
                                            select et).FirstOrDefault();

                        
                        //send mail //revisit
                        from = "*****@*****.**";
                        to = u.Email;
                        body = emailtemplate.EmailBody;
                        subject = emailtemplate.EmailSubject;
                        

                        
                        body = body.Replace("[ParentCustomerName]", c.Name.FirstOrDefault().ToString());
                        body = body.Replace("[ParentCustomerUserID]", cr.Username.ToString());
                        body = body.Replace("[ParentCustomerPassword]", cr.Password.ToString());
                        body = body.Replace("[INSERT LINK]", emailUrl);
                        body = body.Replace("[DefaultEmailContactUS]", dbcontext.Configurations.First().DefaultEmailContactUs.ToString());
                        bool sent = false;
                        ServiceClientWrapper scw = new ServiceClientWrapper();
                        sent = scw.SendEmail(subject, from, to, body);
                    }



                    
                    if (m.SelectedParentID ==0) // non child parent customer - self
                    {

                        var emailtemplate = (
                                                from et in dbcontext.EmailTemplates
                                                join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK
                                                where ey.EmailType1.Equals("WelcomeEmailNonParentUser")
                                                select et).FirstOrDefault();

                        //send mail //revisit
                        from = "*****@*****.**";
                        to = u.Email;
                        body = emailtemplate.EmailBody;
                        subject = emailtemplate.EmailSubject;
                        body = body.Replace("[NonParentCustomer]", u.FirstName.ToString() + " " + u.LastName.ToString());
                        body = body.Replace("[NonParentCustomerUserID]", cr.Username.ToString());
                        body = body.Replace("[NonParentCustomerPassword]", cr.Password.ToString());
                        body = body.Replace("[INSERT LINK]", emailUrl);
                        bool sent = false;
                        ServiceClientWrapper scw = new ServiceClientWrapper();
                        sent = scw.SendEmail(subject, from, to, body);
                    }
                    //SendEmail


                }

            }
            catch (Exception ex)
            {
                Semplest.SharedResources.Helpers.ExceptionHelper.LogException(ex);
            }


            return RedirectToAction("Index");
        }
        public ActionResult Upload(HttpPostedFileBase uploadFile, CustomerImport imp, FormCollection fc)
        {
            string importstatus;
            importstatus  = "The import was the successful..";
            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();
            

            {

                StringBuilder strValidations = new StringBuilder(string.Empty);
                try
                {
                    if (uploadFile.ContentLength > 0)
                    {
                        string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
                        Path.GetFileName(uploadFile.FileName));
                        uploadFile.SaveAs(filePath);
                        FileHelperEngine engine = new FileHelperEngine(typeof(CustomerImportData));
                        engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue;

                        CustomerImportData[] customersimported = (CustomerImportData[])engine.ReadFile(filePath);


                        if (engine.ErrorManager.HasErrors)
                            foreach (ErrorInfo err in engine.ErrorManager.Errors)
                            {
                                string s;
                                s = err.LineNumber + " / " + err.RecordString + " / " + err.ExceptionInfo.ToString();

                                //Console.WriteLine(err.LineNumber);    
                                //Console.WriteLine(err.RecordString);   
                                //Console.WriteLine(err.ExceptionInfo.ToString());
                            }

                        if (customersimported.Count() < 1) throw new Exception("No customers could be imported from csv file");
                        ///////////
                        ///////////


                        foreach (CustomerImportData cust in customersimported)
                        {

                            CustomerAccount m = new CustomerAccount();


                            #region
                            //cust.ContactCompanyName;
                            //cust.ContactEmail;
                            //cust.ContactFirstName;
                            //cust.ContactLastName;
                            //cust.ContactMiddleInitial;
                            //cust.ContactPhoneNumber;
                            //cust.ContactAddressLine1;
                            //cust.ContactAddressLine2;
                            //cust.ContactCity;
                            //cust.ContactState;
                            //cust.ContactStatus;
                            //cust.ContactZip;
                            //cust.FixedMonthlybudget;
                            //cust.InternalCustomerID;
                            ///////
                            //cust.LocalTargetAddress1;
                            //cust.LocalTargetAddress2;
                            //cust.LocalTargetAddress3;
                            //cust.LocalTargetProximity1;
                            //cust.LocalTargetProximity1;
                            //cust.LocalTargetProximity2;
                            //cust.LocalTargetProximity3;
                            //cust.ParentCompanyName;

                            //ca.Address1;
                            //ca.Address2;
                            //ca.City;
                            //ca.Customer;
                            //ca.Email;
                            //ca.FirstName;
                            //ca.MiddleInitial;
                            //ca.Phone;
                            //ca.State;
                            //ca.UserID;
                            //ca.UserPassword;
                            //ca.Zip;
                            //ca.isActive;
                            #endregion

                            /*
                        //cust.ContactStatus;
                        cust.FixedMonthlybudget;
                        //cust.InternalCustomerID;
                        /////
                        cust.LocalTargetAddress1;
                        cust.LocalTargetAddress2;
                        cust.LocalTargetAddress3;
                        cust.LocalTargetProximity1;
                        cust.LocalTargetProximity2;
                        cust.LocalTargetProximity3;
                        cust.ParentCompanyName;
                        /////
                        */

                            m.internalID = cust.InternalCustomerID;
                            m.Address1 = cust.ContactAddressLine1;
                            m.Address2 = cust.ContactAddressLine2;
                            m.City = cust.ContactCity;
                            m.Customer = cust.ContactCompanyName;
                            m.Email = cust.ContactEmail;
                            m.FirstName = cust.ContactFirstName;
                            m.MiddleInitial = cust.ContactMiddleInitial;
                            m.LastName = cust.ContactLastName;
                            m.Phone = cust.ContactPhoneNumber;
                            m.State = cust.ContactState;
                            m.UserID = cust.ContactEmail;
                            m.UserPassword = Semplest.SharedResources.Helpers.RandomPassword.Generate(8, 10);
                            m.Zip = cust.ContactZip;
                            m.isActive = true;


                            var emailtemplate = (from et in dbcontext.EmailTemplates
                                                 where et.EmailTemplatePK.Equals(13)
                                                 select et).FirstOrDefault();
                                                        
                            try
                            {
                                var existing = (from ex in dbcontext.Customers
                                                where ex.InternalCustomerId.Equals(cust.InternalCustomerID) && ex.Name.Equals(m.Customer)
                                                select ex).ToList();

                                if (existing.Count() > 0) throw new Exception();


                                ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30");

                                //Customer c = dbcontext.Customers.Add(new Customer { Name = m.Customer, BillTypeFK = imp.SelectedBillTypeID, ProductGroupCycleType = pgct, InternalCustomerId = cust.InternalCustomerID });
                                var c = new Customer { Name = m.Customer, BillTypeFK = imp.SelectedBillTypeID, ProductGroupCycleType = pgct, InternalCustomerId = cust.InternalCustomerID };
                                dbcontext.Customers.Add(c);
                                var u = new User
                                {
                                    Customer = c,
                                    Email = m.Email,
                                    FirstName = m.FirstName,
                                    LastName = m.LastName,
                                    MiddleInitial = m.MiddleInitial,
                                    IsActive = m.isActive
                                };
                                dbcontext.Users.Add(u);

                                var cr = new Credential { User = u, UsersFK = u.UserPK, Username = m.UserID, Password = m.UserPassword };
                                dbcontext.Credentials.Add(cr);


                                PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!!
                                Phone ph = new Phone { Phone1 = m.Phone, PhoneType = pt };
                                dbcontext.Phones.Add(ph);
                                
                                var cpa = new CustomerPhoneAssociation { Customer = c, Phone = ph };
                                dbcontext.CustomerPhoneAssociations.Add(cpa);

                                StateCode sc = dbcontext.StateCodes.First(p => p.StateAbbr == m.State);
                                AddressType at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!!
                                var a = new Address { Address1 = m.Address1, Address2 = m.Address2, City = m.City, ZipCode = m.Zip, StateCode = sc };
                                dbcontext.Addresses.Add(a);
                                var caa = new CustomerAddressAssociation { Address = a, Customer = c, AddressType = at };
                                dbcontext.CustomerAddressAssociations.Add(caa);

                                var cn = new CustomerNote { Customer = c, Note = m.CustomerNote };
                                dbcontext.CustomerNotes.Add(cn);

                                var r = dbcontext.Roles.First(p => p.RolePK == imp.SelectedRoleID);
                                var ura = new UserRolesAssociation { Role = r, User = u };
                                dbcontext.UserRolesAssociations.Add(ura);

                                //default to the parent's rep and salesperson

                                var parentrepandsales = (from prs in dbcontext.EmployeeCustomerAssociations
                                                         where prs.CustomerFK.Equals(imp.ParentID)
                                                         select prs).ToList();
                                foreach (EmployeeCustomerAssociation eca in parentrepandsales)
                                {
                                    var addrepandsales = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = eca.EmployeeFK };
                                    dbcontext.EmployeeCustomerAssociations.Add(addrepandsales);
                                }

                                //add child to parent in customerhierarchy
                                var ch = new CustomerHierarchy { CustomerFK = c.CustomerPK, CustomerParentFK = imp.ParentID };
                                dbcontext.CustomerHierarchies.Add(ch);
                                dbcontext.SaveChanges();

                                if (fc["sendcustomeremail"] != null)
                                {

                                    ///////////////////////////////////////////////////////////////
                                    //FOR SENDING OUT EMAILS to child customers
                                    /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ///

                                    var parentdetails = from usr in dbcontext.Users
                                                        join cus in dbcontext.Customers on usr.CustomerFK equals cus.CustomerPK
                                                        where usr.CustomerFK == imp.ParentID
                                                        select new { usr.CustomerFK, usr.Email, cus.Name };

                                    //send mail //revisit
                                    string from = "*****@*****.**";
                                    string to = u.Email;
                                    string body = emailtemplate.EmailBody;
                                    string subject = emailtemplate.EmailSubject;
                                    body = body.Replace("[ChildCustomerFirstLast]", u.FirstName.ToString() + " " + u.LastName.ToString());
                                    body = body.Replace("[ParentCustomerName]", parentdetails.FirstOrDefault().Name.ToString());
                                    body = body.Replace("[FAQs]", "http://faq");
                                    body = body.Replace("[ChildCustomerUserID]", cr.Username.ToString());
                                    body = body.Replace("[ChildCustomerPassword]", cr.Password.ToString());
                                    body = body.Replace("[INSERT LINK]", "http://encrypto");

                                    //SendEmail
                                    bool sent = false;
                                    ServiceClientWrapper scw = new ServiceClientWrapper();
                                    sent = scw.SendEmail(subject, from, to, body);
                                }
                                                            
                            }
                            catch (Exception ex)
                            {
                                //Console.WriteLine(ex.TargetSite);
                                SemplestModel.Semplest _dbContext = new SemplestModel.Semplest();
                                SemplestModel.Error er = new SemplestModel.Error();
                                er.ErrorMessage = ex.Message+"  \r\n "+ex.InnerException  +"  \r\n "+ex.StackTrace +"  \r\n "+ex.Source+"  \r\n "+ex.TargetSite;
                                //filterContext.RequestContext.HttpContext.Session
                                //if (HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] == null)
                                //    er.UsersFK = 1;
                                //else
                                //    er.UsersFK = ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]) == null ? 1 : ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).UsersFK;
                                er.CreatedDate = DateTime.Now;
                                _dbContext.Errors.Add(er);
                                _dbContext.SaveChanges();
                                
                                var scw = new ServiceClientWrapper();
                                scw.SendEmail("WebSite Error Message", "*****@*****.**", _dbContext.Configurations.First().OnErrorEmail, er.ErrorMessage);
                            }
                        }//endforeach

                    }
                    else throw new Exception();

                }
                catch (Exception ex)
                {
                    importstatus = "An error has occured. Please check the file for errors and try again..";
                    //Console.WriteLine(ex.TargetSite);
                    SemplestModel.Semplest _dbContext = new SemplestModel.Semplest();
                    SemplestModel.Error er = new SemplestModel.Error();
                    er.ErrorMessage = ex.Message + "  \r\n " + ex.InnerException + "  \r\n " + ex.StackTrace + "  \r\n " + ex.Source + "  \r\n " + ex.TargetSite;
                    //filterContext.RequestContext.HttpContext.Session
                    //if (HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] == null)
                    //    er.UsersFK = 1;
                    //else
                    //    er.UsersFK = ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]) == null ? 1 : ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).UsersFK;
                    er.CreatedDate = DateTime.Now;
                    _dbContext.Errors.Add(er);
                    _dbContext.SaveChanges();
                    var scw = new ServiceClientWrapper();
                    scw.SendEmail("WebSite Error Message", "*****@*****.**", _dbContext.Configurations.First().OnErrorEmail, er.ErrorMessage);

                }


                /*
                 
                 *   public Boolean SendEmail(String subject, String from, String recipient, String msgTxt)
        {
            var jsonHash = new Dictionary<string, string>();
            jsonHash.Add("subject", subject);
            jsonHash.Add("from", from);
            jsonHash.Add("recipient", recipient);
            jsonHash.Add("msgTxt", msgTxt);
            string jsonstr = JsonConvert.SerializeObject(jsonHash);
            string returnData = runMethod(_baseURLTest, MAILSERVICEOFFERED, "SendEmail", jsonstr, timeoutMS);
            var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(returnData);
            string boolResult = dict.Values.First();
            return Convert.ToBoolean(boolResult);
        }
                 
                 */



                //scope.Complete();
            }

            //return View(m);

            ImportResultModel res = new ImportResultModel();
            res.Importresult = importstatus;
            return RedirectToAction("CustomerImportResult", "AccountService",   res );
        }
Esempio n. 28
0
        public void AddPromotionAdsToPromotion(Promotion promo, CampaignSetupModel model, int customerFk)
        {
            foreach (PromotionAd pad in model.AdModelProp.Ads.Where(t => !t.Delete))
            {
                var cad = new PromotionAd { AdTextLine1 = pad.AdTextLine1, AdTextLine2 = pad.AdTextLine2, AdTitle = pad.AdTitle };

                //if (pad.SiteLinks != null)
                //{
                //    // add sitelinks
                //    foreach (SiteLink slink in pad.SiteLinks)
                //    {
                //        // this is check should be removed once we fix the logic in partialview and model
                //        if (!String.IsNullOrEmpty(slink.LinkText) && !String.IsNullOrEmpty(slink.LinkURL))
                //        {
                //            var slinkobj = new SiteLink { LinkText = slink.LinkText, LinkURL = slink.LinkURL };
                //            cad.SiteLinks.Add(slinkobj);
                //        }
                //    }
                //}

                promo.PromotionAds.Add(cad);
                try
                {
                    var sw = new ServiceClientWrapper();
                    var adEngines = new List<string>();
                    var promoAds = new List<int>();
                    if (promo.IsLaunched)
                    {
                        adEngines.AddRange(promo.PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1));
                        promoAds.AddRange(promo.PromotionAds.Select(pa => pa.PromotionAdsPK));
                        sw.scheduleAds(customerFk, promo.PromotionPK, promoAds, adEngines, true);
                    }
                }
                catch (Exception ex) { SharedResources.Helpers.ExceptionHelper.LogException(ex.ToString()); }
            }
        }
Esempio n. 29
0
        public string SaveSiteLinks(CampaignSetupModel model, int customerFk, CampaignSetupModel oldModel)
        {
            bool shouldRefreshSiteLinks = false;
            var rString = new System.Text.StringBuilder();
            using (var dbcontext = new SemplestModel.Semplest())
            {
                var queryProd = (from c in dbcontext.ProductGroups
                                 where
                                     c.CustomerFK == customerFk &&
                                     c.ProductGroupName == model.ProductGroup.ProductGroupName
                                 select c).Single();
                var promo = GetPromotionFromProductGroup(queryProd, model.ProductGroup.ProductPromotionName);
                List<GoogleSiteLink> sl =
                                          model.SiteLinks.Where(t => !t.Delete).Select(row => new GoogleSiteLink
                                          {
                                              LinkText = row.LinkText,
                                              LinkURL = row.LinkURL
                                          }).ToList();
                if (sl.Any())
                {
                    GoogleViolation[] gv = ValidateSiteLinks(sl);
                    if (gv.Length > 0)
                        throw new Exception(gv.First().shortFieldPath + ": " + gv.First().errorMessage);
                }
                SiteLinksTableType st;
                shouldRefreshSiteLinks = AddSiteLinksToPromotion(promo, model, customerFk, ((IObjectContextAdapter)dbcontext).ObjectContext, oldModel, out st);

                var parameter = new SqlParameter("PromotionPK", promo.PromotionPK) { SqlDbType = SqlDbType.Int };
                var parameter2 = new SqlParameter("SlTVP", st) { SqlDbType = SqlDbType.Structured, TypeName = "SiteLinksTableType" };
                var parameters = new object[] { parameter, parameter2 };
                var results = ((IObjectContextAdapter)dbcontext).ObjectContext.ExecuteStoreQuery<RVal>("exec UpdateSiteLinks @PromotionPK, @SlTVP", parameters);
                _savedCampaign = true;
                foreach (var r in results)
                {
                    rString.Append(r.UID);
                    rString.Append("=");
                    rString.Append(r.PKEY);
                    rString.Append(",");
                }
                _savedCampaign = true;
                try
                {
                    var adEngines = new List<string>();
                    if (promo.IsLaunched && shouldRefreshSiteLinks)
                    {
                        adEngines.AddRange(
                            promo.PromotionAdEngineSelecteds.Select(pades => pades.AdvertisingEngine.AdvertisingEngine1));
                        var sw = new ServiceClientWrapper();
                        sw.scheduleRefreshSiteLinks(promo.PromotionPK, adEngines);
                    }
                }
                catch (Exception ex)
                {
                    SharedResources.Helpers.ExceptionHelper.LogException(ex);
                }
            }
            return string.IsNullOrEmpty(rString.ToString()) ? String.Empty : rString.ToString().Substring(0, rString.ToString().Length - 1);
        }
        public ActionResult RestartPromotions(int id)
        {
            SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
            ServiceClientWrapper sw = new ServiceClientWrapper();
            foreach (ProductGroup pg in dbContext.Customers.Where(key => key.CustomerPK == id).First().ProductGroups)
            {
                foreach (Promotion p in pg.Promotions)
                {
                    if (p.IsLaunched && p.IsPaused && (!p.IsCompleted))
                    {
                        List<string> adEngines = new List<string>();
                        foreach (PromotionAdEngineSelected pades in p.PromotionAdEngineSelecteds)
                            adEngines.Add(pades.AdvertisingEngine.AdvertisingEngine1);
                        p.IsPaused = !sw.schedulePromotion(id, p.PromotionPK, adEngines.ToArray(), true);
                    }
                }
            }

            dbContext.SaveChanges();
            Dictionary<string, object> d = new Dictionary<string, object>();
            d.Add("id", id);
            return RedirectToAction("Index", new System.Web.Routing.RouteValueDictionary(d));
        }