public ActionResult BillType()
        {
            //var model = new BillType();
            //{
            //    model.BillType1 = "Credit Card";
            //    model.Customers.Add(new Customer());
            //};

            using (var db = new SemplestModel.Semplest())
            {
                try
                {
                    if (db.BillTypes.Count() > 0)
                        return View(db.BillTypes.ToList());
                    else
                        return View();
                }
                catch
                {
                    return View();
                }
            }


            //return View();
        }
Beispiel #2
0
 public HomeModelChild()
 {
     using (var entities = new SemplestModel.Semplest())
         Configuration = entities.Configurations.FirstOrDefault();
     CampaignSetup = new CampaignSetupModel();
     CampaignSetup.AdModelProp.Addresses.FirstOrDefault().StateCodeFK = 0;
 }
        public ActionResult CampaignSetup(CampaignSetupModel cs, string command)
        {

            if (command == "") command = "";

            var logEnty = new LogEntry {ActivityId = Guid.NewGuid(), Message = "Loading CampaignSetup Controller"};
            Logger.Write(logEnty);
            //var logService = new LogService();
            //logService.AddToLog(1, "Campaign Setup Accessed", "CampaignSetup//CampaignSetup//CampaignSetup", 1);
            //var scw = new ServiceClientWrapper();
            //scw.SendEmail("subject", "*****@*****.**", "*****@*****.**", "test mail");

            //var campaignSetupModel = new CampaignSetupModel();
            Session["SiteLinks"] = null;
            Session["NegativeKeywords"] = null;
            Session["NegativeKeywordsText"] = null;
            Session["CampaignSetupModel"] = cs;
            Session["AllCategories"] = null;
            ViewBag.IsLaunched = false;
            ViewBag.IsCompleted = false;
            ViewBag.IsLaunchedAndCompleted = false;
            cs.AdModelProp.IsNew = true;
            var dbContext = new SemplestModel.Semplest();
            var userid =
                ((Credential)System.Web.HttpContext.Current.Session[SharedResources.SEMplestConstants.SESSION_USERID]).
                    UsersFK;
            cs.BillType = dbContext.Users.First(key => key.UserPK == userid).Customer.BillTypeFK;
            return View(cs);
        }
 public ActionResult LogIn(Semplest.SharedResources.Models.ProfileModel pm, string ReturnUrl)
 {
     using (SemplestEntities dbContext = new SemplestEntities())
     {
         Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] = 1;
         return RedirectToAction("CampaignSetup", "Campaign");
         var creds = dbContext.Credentials.Where(c => c.Username == pm.UserName && c.Password == pm.Password1);
         if (creds.Count() == 1)
         {
             Credential c = creds.First();
             Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] = c.UsersFK;
             if (c.User.UserRolesAssociations.First().RolesFK == 2)
                 //means this is an admin user
                 return RedirectToAction("Index", "Home");
             else if (c.User.IsRegistered)
                 //user is a regular core user
                 return RedirectToAction("CampaignSetup", "Campaign");
             else if (!string.IsNullOrEmpty(pm.SecurityAnswer) && !string.IsNullOrEmpty(pm.SecurityQuestion))
             {
                 //authenticated properly but hasn't registered yet
                 c.SecurityAnswer = pm.SecurityAnswer;
                 c.SecurityQuestion = pm.SecurityQuestion;
                 c.User.IsRegistered = true;
                 dbContext.SaveChanges();
                 return RedirectToAction("Index", "Home");
             }
             else
                 pm.IsRegistered = false;
         }
         return View(pm);
     }
 }
 public ActionResult Index(ReportIndexModel model)
 {
     Credential cred = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]));
     SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
     model.AdvertisingEngines = dbContext.AdvertisingEngines;
     model.ProductGroups = dbContext.Credentials.Where(x => x.UsersFK == cred.UsersFK).First().User.Customer.ProductGroups;
     return RedirectToAction("ReportDetails", model);
 }
 public ActionResult ReportDetails(ReportIndexModel model)
 {
     Credential cred = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]));
     SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
     model.AdvertisingEngines = dbContext.AdvertisingEngines;
     model.ProductGroups = dbContext.Credentials.Where(x => x.UsersFK == cred.UsersFK).First().User.Customer.ProductGroups;
     model.Detail = dbContext.vwPromotionCharts.Where(t => t.UserPK == cred.UsersFK).OrderBy(t => t.Keyword);
     model.Configuration = dbContext.Configurations.FirstOrDefault();
     return View(model);
 }
 public ActionResult Index(ReportIndexModel model)
 {
     var cred = ((Credential)(Session[SharedResources.SEMplestConstants.SESSION_USERID]));
     var dbContext = new SemplestModel.Semplest();
     model.AdvertisingEngines = dbContext.AdvertisingEngines;
     var credential = dbContext.Credentials.FirstOrDefault(x => x.UsersFK == cred.UsersFK);
     if (credential != null)
         model.ProductGroups = credential.User.Customer.ProductGroups;
     return RedirectToAction("ReportDetails", model);
 }
        //
        // GET: /Reporting/

        public ActionResult Index()
        {
            Credential cred = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]));
            SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
            IQueryable<Credential> cCred = dbContext.Credentials.Where(x => x.UsersFK == cred.UsersFK);
            ViewBag.Title = cCred.First().User.FirstName + " " + cCred.First().User.LastName + " - " + cCred.First().User.Customer.Name;
            ReportIndexModel rim = new ReportIndexModel();
            rim.AdvertisingEngines = dbContext.AdvertisingEngines;
            rim.ProductGroups = dbContext.Credentials.Where(x => x.UsersFK == cred.UsersFK).First().User.Customer.ProductGroups;
            return View(rim);
        }
Beispiel #9
0
        public ActionResult Index2()
        {
            SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
            Credential cred = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]));

            HomeModelChild child = new HomeModelChild();
            IQueryable<Credential> cCred = dbContext.Credentials.Where(x => x.UsersFK == cred.UsersFK);
            ViewBag.Title = cCred.First().User.FirstName + " " + cCred.First().User.LastName + " - " + cCred.First().User.Customer.Name;
            child.ProductGroups = cCred.First().User.Customer.ProductGroups;
            return View(child);
        }
Beispiel #10
0
 public ActionResult SchedulerView()
 {
     var dbContext = new SemplestModel.Semplest();
     var
     svmc  = new SchedulerViewModelCollection();
     foreach (SchedulerView svm in dbContext.SchedulerViews)
     {
         svmc.SVM.Add(new SchedulerViewModel{ CustomerName = svm.CustomerName, ExecutionStartTime = svm.ExecutionStartTime, Frequency = svm.Frequency, IsComplete = svm.IsComplete, IsEnabled = svm.IsEnabled, IsInactive = svm.IsInactive, IsSuccessful = svm.IsSuccessful, PromotionName = svm.PromotionName, ScheduleJobPK = svm.ScheduleJobPK, ScheduleName = svm.ScheduleName, SchedulePK = svm.SchedulePK});
     }
     svmc.Status = "All";
     return View(svmc);
 }
        //
        // GET: /CreateNewCustomerAccount/

        public ActionResult Index(string usersearch, string accountnumbersearch, string emailsearch, FormCollection form)
        {

            //ViewBag.Message = "Welcome to SEMPLEST ADMIN!";
            SemplestModel.Semplest dbcontext = new SemplestModel.Semplest();

            var viewModel =
                from u in dbcontext.Users
                join c in dbcontext.Customers on u.CustomerFK equals c.CustomerPK
                where ((c.Name.Contains(usersearch) || u.FirstName.Contains(usersearch) || u.LastName.Contains(usersearch)))
                select new HomeModel
                {
                    Customer = c.Name,
                    AccountNumber = c.CustomerPK,
                    FirstName = u.FirstName,
                    LastName = u.LastName,
                    Email = u.Email
                };

            var predicate = PredicateBuilder.True<HomeModel>();


            if (form["searchtype"] == "Customer" && usersearch != null && usersearch != "")
            {
                predicate = (p => p.Customer.ToLower().Contains(usersearch.ToLower()));
            }

            if (form["searchtype"] == "LastName" && usersearch != null && usersearch != "")
            {
                predicate = (p => p.LastName.ToLower().Contains(usersearch.ToLower()));
            }

            int accnumber;
            bool validaccountsearch = int.TryParse(accountnumbersearch, out accnumber);

            if (accountnumbersearch != null && accountnumbersearch != "" && validaccountsearch)
            {
                predicate = (p => p.AccountNumber == accnumber);
            }

            if (emailsearch != null && emailsearch != "")
            {
                predicate = (p => p.Email.ToLower().Contains(emailsearch.ToLower()));
            }


            //ordering by lastname, firstname
            viewModel = viewModel.OrderBy(p => p.Customer).ThenBy(p => p.LastName).ThenBy(p => p.FirstName);
            viewModel = viewModel.AsExpandable().Where(predicate);


            return View(viewModel);
        }
Beispiel #12
0
        public ActionResult Index2()
        {
            SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
            Credential cred = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]));

            HomeModelChild child = new HomeModelChild();
            IQueryable<Credential> cCred = dbContext.Credentials.Where(x => x.UsersFK == cred.UsersFK);
            var ps = dbContext.GetCustomerPromotionStatus(cCred.Single().User.CustomerFK).OrderBy(q => q.PromotionStatus).ThenBy(q => q.PromotionName).ToList();
            ViewBag.Title = cCred.First().User.FirstName + " " + cCred.First().User.LastName + " - " + cCred.First().User.Customer.Name;
            child.CustomerPromotions = ps;
            return View(child);
        }
Beispiel #13
0
    public PartialViewResult ErrorView(string ddl)
    {
        var dbContext = new SemplestModel.Semplest();
        List<ErrorModel> list = new List<ErrorModel>();
        DateTime reqDate = DateTime.Parse(ddl);
        foreach (Error er in dbContext.Errors.Where(x => x.CreatedDate.Month == reqDate.Month && x.CreatedDate.Day == reqDate.Day && x.CreatedDate.Year == reqDate.Year).OrderByDescending(x => x.CreatedDate))
        {
            var em = new ErrorModel();
            em.ErrorMessage = er.ErrorMessage;
            em.User = er.User != null ? er.User.Credentials.First().Username : "******";
            em.TimeStamp = er.CreatedDate;

            list.Add(em);
        }
        return PartialView("_ErrorView", list);
    }
Beispiel #14
0
 public ActionResult Create(BillType billtype)
 {
     try
     {
         using (var db = new SemplestModel.Semplest())
         {
             db.BillTypes.Add(billtype);
             db.SaveChanges();
         }
         return RedirectToAction("BillType");
     }
     catch
     {
         return View();
     }
 }
 public CampaignSetupModel()
 {
     ProductGroup = new ProductGroupModel();
     AdModelProp = new AdModel();
     BillingLaunch = new BillingLaunchModel();
     // for categories
     AllCategories = new List<CategoriesModel>();
     SelectedCategories = new List<CategoriesModel>();
     CategoryIds = new List<int>();
     // for keywords
     AllKeywords = new List<KeywordsModel>();
     AllKeywordProbabilityObjects = new List<KeywordProbabilityObject>();
     SelectedKeywords = new List<KeywordsModel>();
     KeywordIds = new List<int>();
     SiteLinks = new List<SiteLink>();
     Configuration = new SemplestModel.Semplest().Configurations.Single();
 }
        //
        // GET: /Reporting/

        public ActionResult Index()
        {
            var cred = ((Credential)(Session[SharedResources.SEMplestConstants.SESSION_USERID]));
            var dbContext = new SemplestModel.Semplest();
            IQueryable<Credential> cCred = dbContext.Credentials.Where(x => x.UsersFK == cred.UsersFK);
            ViewBag.Title = cCred.First().User.FirstName + " " + cCred.First().User.LastName + " - " + cCred.First().User.Customer.Name;
            var credential = dbContext.Credentials.FirstOrDefault(x => x.UsersFK == cred.UsersFK);
            if (credential != null)
            {
                var rim = new ReportIndexModel
                {
                    AdvertisingEngines = dbContext.AdvertisingEngines,
                    ProductGroups = credential.User.Customer.ProductGroups
                };
                return View(rim);
            }
            return View(new ReportIndexModel());
        }
 public ActionResult ReportSummaryGrid(string promotionFk, string advertisingEngineFk, DateTime? startDate, DateTime? endDate)
 {
     var dbContext = new SemplestModel.Semplest();
     var cred = ((Credential)(Session[SharedResources.SEMplestConstants.SESSION_USERID]));
     var promotionFks = Array.ConvertAll(promotionFk.Split(','), int.Parse);
     var adFks = Array.ConvertAll(advertisingEngineFk.Split(','), int.Parse);
     var grp = dbContext.vwPromotionCharts.Where(t => promotionFks.Contains(t.PromotionFK) && t.UserPK == cred.UsersFK && adFks.Contains(t.AdvertisingEngineFK) && t.TransactionDate >= startDate && t.TransactionDate <= endDate).OrderBy(t => t.Keyword).GroupBy(t => new { t.PromotionName });
     var reports = grp.Select(v => new vwPromotionChartModel
     {
         AmountSpent = v.Sum(t => t.NumberClick * t.AverageCPC),
         NumberImpressions = v.Sum(t => t.NumberImpressions),
         KeyWord = v.FirstOrDefault().PromotionName,
         NumberClick = v.Sum(t => t.NumberClick),
         SearchCTR = v.Sum(t => t.NumberClick / t.NumberImpressions),
         CPC = v.Sum(t => t.NumberClick) == 0 ? 0 : v.Sum(t => t.NumberClick * t.AverageCPC) / v.Sum(t => t.NumberClick),
         AveragePosition = v.Average(t => t.AveragePosition),
     }).ToList();
     return Json(reports, JsonRequestBehavior.AllowGet);
 }
Beispiel #18
0
 public ActionResult Index()
 {
     return RedirectToAction("Index2", "Home", new HomeModelChild());
     HomeModelParent hm = new HomeModelParent();
     SemplestModel.Semplest dbContext = new SemplestModel.Semplest();
     int userId = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID])).UsersFK;
     foreach (ProductGroup pg in dbContext.Users.Where(x => x.UserPK == userId).First().Customer.ProductGroups)
     {
         foreach (Promotion p in pg.Promotions)
         {
             if (p.IsLaunched)
                 hm.LaunchedCampaigns++;
             else
                 hm.StartedCampaignsNotLaunched++;
         }
     }
     hm.AdvertisingEngines = dbContext.AdvertisingEngines;
     return View(hm);
 }
 public ActionResult CampaignSetup(CampaignSetupModel cs)
 {
     Session["SiteLinks"] = null;
     Session["NegativeKeywords"] = null;
     Session["NegativeKeywordsText"] = null;
     Session["CampaignSetupModel"] = cs;
     Session["AllCategories"] = null;
     ViewBag.IsLaunched = false;
     ViewBag.IsCompleted = false;
     ViewBag.IsPending = false;
     ViewBag.IsLaunchedAndCompleted = false;
     cs.AdModelProp.IsNew = true;
     var dbContext = new SemplestModel.Semplest();
     var userid =
         ((Credential)System.Web.HttpContext.Current.Session[SharedResources.SEMplestConstants.SESSION_USERID]).
             UsersFK;
     cs.BillType = dbContext.Users.First(key => key.UserPK == userid).Customer.BillTypeFK;
     cs.ProductGroup.AllowAutoBid = dbContext.Users.Single(key => key.UserPK == userid).Customer.AllowAutobid;
     return View(cs);
 }
Beispiel #20
0
        public ActionResult ContactUs(SEMCustomerDetail model)
        {
            if (ModelState.IsValid && !(model.CallMe == false && model.EmailMe == false))
            {
                try
                {
                    model.CreatedDate = DateTime.Now;
                    using (var dbContext = new SemplestModel.Semplest())
                    {
                        string semEmail = dbContext.Configurations.Select(m => m.DefalutEmailContactMe).FirstOrDefault();

                        if (model.EmailMe == false)
                        {
                            model.email = "";
                        }
                        else if (model.CallMe == false)
                        {
                            model.Phone = "";
                        }
                        dbContext.SEMCustomerDetails.Add(model);
                        dbContext.SaveChanges();

                        // send email using smtp server
                        if (model.EmailMe == true)
                            SendMail(model, semEmail);
                    }
                }
                catch (Exception ex)
                {
                    string errMsg = "Error: " + ex.Message + "\r\n" + ex.StackTrace;
                    var errModel = new ErrorModel() { MsgToLog = errMsg, MsgToShow = "Error" };
                    return View("ErrorPage", errModel);
                }
                return RedirectToAction("ThankYou");
            }
            else
            {

                return View(model);
            }
        }
 public ActionResult ReportSummaryGrid()
 {
     var dbContext = new SemplestModel.Semplest();
     var grp = dbContext.vwPromotionCharts.Where(t => t.UserPK == 60).OrderBy(t => t.Keyword).GroupBy(t => new { t.PromotionName });
     List<vwPromotionChartModel> reports = new List<vwPromotionChartModel>();
     foreach (var v in grp)
     {
         reports.Add(new vwPromotionChartModel
         {
             AmountSpent = v.Sum(t => t.NumberClick * t.AverageCPC),
             NumberImpressions = v.Sum(t => t.NumberImpressions),
             KeyWord = v.FirstOrDefault().PromotionName,
             NumberClick = v.Sum(t => t.NumberClick),
             SearchCTR = v.Sum(t => t.NumberClick * 100 / t.NumberImpressions),
             CPC = v.Sum(t => t.NumberClick) == 0 ? 0 : v.Sum(t => t.NumberClick * t.AverageCPC) / v.Sum(t => t.NumberClick),
             AveragePosition = v.Sum(t => t.AveragePosition),
             IsActive = v.FirstOrDefault().IsActive ? "Live" : "Paused"
         });
     }
     return Json(reports, JsonRequestBehavior.AllowGet);
 }​​
Beispiel #22
0
        //
        // GET: /Error/

        public ActionResult Index()
        {
            var dbContext = new SemplestModel.Semplest();
//            SortedList<DateTime, ErrorModel> list = new SortedList<DateTime, ErrorModel>();
            List<ErrorModel> list = new List<ErrorModel>();
            List<DateTime> dt = new List<DateTime>();
            ErrorModel em = null;
            DateTime t = DateTime.Now.Date;
            //foreach (Error er in dbContext.Errors.Where(x=>x.CreatedDate>t).OrderByDescending(x => x.CreatedDate))
            foreach (Error er in dbContext.Errors.OrderByDescending(x => x.CreatedDate))
            {
                em = new ErrorModel();
                em.ErrorMessage = er.ErrorMessage;
                em.User = er.User != null ? er.User.Credentials.First().Username : "******";
                em.TimeStamp = er.CreatedDate;
                if (!dt.Contains(er.CreatedDate.Date))
                    dt.Add(er.CreatedDate.Date);
                ViewData["CreateDate"] = new SelectList(dt, "Date", "Date");
                list.Add(em);
            }
            return View(list);
        }
 public ActionResult ReportDetailsGrid()
 {
     var dbContext = new SemplestModel.Semplest();
     Credential cred = ((Credential)(Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]));
     var grp = dbContext.vwPromotionCharts.Where(t => t.UserPK == cred.UsersFK).OrderBy(t => t.Keyword).GroupBy(t => new { t.Keyword, t.PromotionName });
     List<vwPromotionChartModel> reports = new List<vwPromotionChartModel>();
     foreach (var v in grp)
     {
         reports.Add(new vwPromotionChartModel
         { 
                                 AmountSpent = v.Sum(t => t.NumberClick * t.AverageCPC) ,
                                 NumberImpressions = v.Sum(t => t.NumberImpressions),
                                 KeyWord = v.Key.Keyword,
                                 NumberClick = v.Sum(t => t.NumberClick), 
                                 SearchCTR = v.Sum(t => t.NumberClick * 100 / t.NumberImpressions),
                                 CPC = v.Sum(t => t.NumberClick) == 0 ? 0 : v.Sum(t => t.NumberClick * t.AverageCPC) / v.Sum(t => t.NumberClick),
                                 AveragePosition = v.Average(t => t.AveragePosition),
                                 IsActive = v.FirstOrDefault().IsActive ? "Live" : "Paused"
                                 }); 
         }
     return Json(reports, JsonRequestBehavior.AllowGet);
 }
        public ActionResult ReportGraph(string promotionFk, string advertisingEngineFk, DateTime? startDate, DateTime? endDate, string mode)
        {
            var dbContext = new SemplestModel.Semplest();
            var userid = ((Credential)(Session[SharedResources.SEMplestConstants.SESSION_USERID])).UsersFK;
            var promotionFks = Array.ConvertAll(promotionFk.Split(','), int.Parse);
            var adFks = Array.ConvertAll(advertisingEngineFk.Split(','), int.Parse);
            List<vwPromotionChart> promotionCharts;
            var reports = new List<ReportChartModel>();
            var reports1 = new List<ReportChartModel>();
            IEnumerable<IGrouping<DateTime, vwPromotionChart>> grp;
            IEnumerable<IGrouping<string, vwPromotionChart>> grpa;
            IEnumerable<IGrouping<string, ReportChartModel>> grp1;
            switch (mode)
            {
                case "1":
                    promotionCharts = dbContext.vwPromotionCharts.Where(t => promotionFks.Contains(t.PromotionFK) && adFks.Contains(t.AdvertisingEngineFK) && t.UserPK == userid && t.TransactionDate >= startDate && t.TransactionDate <= endDate).ToList();

                    grp = promotionCharts.GroupBy(t => t.TransactionDate);
                    foreach (var data in grp)
                    {
                        var count = data.Count();
                        reports.Add(new ReportChartModel { Clicks = data.Sum(t => t.NumberClick) / count, Impressions = data.Sum(t => t.NumberImpressions) / count, Date = data.Key.ToString("MM/dd"), AveragePosition = data.Sum(t => t.AveragePosition) / count, AverageCPC = data.Sum(t => t.AverageCPC) / count });
                    }
                    grp1 = reports.GroupBy(t => t.Date);
                    foreach (var data in grp1)
                    {
                        var count = data.Count();
                        reports1.Add(new ReportChartModel { Clicks = data.Sum(t => t.Clicks) / count, Impressions = data.Sum(t => t.Impressions) / count, Date = data.Key, AveragePosition = data.Sum(t => t.AveragePosition) / count, AverageCPC = data.Sum(t => t.AverageCPC) / count });
                    }
                    return Json(reports1, JsonRequestBehavior.AllowGet);
                case "2":
                    promotionCharts = dbContext.GetMondayChart(startDate, endDate).Where(t => promotionFks.Contains(t.PromotionFK) && adFks.Contains(t.AdvertisingEngineFK) && t.UserPK == userid).ToList();

                    grp = promotionCharts.GroupBy(t => t.TransactionDate);
                    foreach (var data in grp)
                    {
                        var count = data.Count();
                        reports.Add(new ReportChartModel { Clicks = data.Sum(t => t.NumberClick) / count, Impressions = data.Sum(t => t.NumberImpressions) / count, Date = data.Key.ToString("MM/dd"), AveragePosition = data.Sum(t => t.AveragePosition) / count, AverageCPC = data.Sum(t => t.AverageCPC) / count });
                    }
                    grp1 = reports.GroupBy(t => t.Date);
                    foreach (var data in grp1)
                    {
                        var count = data.Count();
                        reports1.Add(new ReportChartModel { Clicks = data.Sum(t => t.Clicks) / count, Impressions = data.Sum(t => t.Impressions) / count, Date = data.Key, AveragePosition = data.Sum(t => t.AveragePosition) / count, AverageCPC = data.Sum(t => t.AverageCPC) / count });
                    }
                    return Json(reports1, JsonRequestBehavior.AllowGet);


                  
                case "3":
                    promotionCharts = dbContext.vwPromotionCharts.Where(t => promotionFks.Contains(t.PromotionFK) && adFks.Contains(t.AdvertisingEngineFK) && t.UserPK == userid && t.TransactionDate >= startDate && t.TransactionDate <= endDate).ToList();

                    grpa = promotionCharts.GroupBy(t => (t.TransactionDate.Month) + "/" + (t.TransactionDate.Year));
                    foreach (var data in grpa)
                    {
                        var count = data.Count();
                        reports.Add(new ReportChartModel { Clicks = data.Sum(t => t.NumberClick) / count, Impressions = data.Sum(t => t.NumberImpressions) / count, Date = data.Key.ToString(), AveragePosition = data.Sum(t => t.AveragePosition) / count, AverageCPC = data.Sum(t => t.AverageCPC) / count });
                    }
                    grp1 = reports.GroupBy(t => t.Date);
                    foreach (var data in grp1)
                    {
                        var count = data.Count();
                        reports1.Add(new ReportChartModel { Clicks = data.Sum(t => t.Clicks) / count, Impressions = data.Sum(t => t.Impressions) / count, Date = data.Key, AveragePosition = data.Sum(t => t.AveragePosition) / count, AverageCPC = data.Sum(t => t.AverageCPC) / count });
                    }
                    return Json(reports1, JsonRequestBehavior.AllowGet);
                case "4":
                    promotionCharts = dbContext.vwPromotionCharts.Where(t => promotionFks.Contains(t.PromotionFK) && adFks.Contains(t.AdvertisingEngineFK) && t.UserPK == userid && t.TransactionDate >= startDate && t.TransactionDate <= endDate).ToList();

                    grpa = promotionCharts.GroupBy(t => t.TransactionDate.Year.ToString());
                    foreach (var data in grpa)
                    {
                        var count = data.Count();
                        reports.Add(new ReportChartModel { Clicks = data.Sum(t => t.NumberClick) / count, Impressions = data.Sum(t => t.NumberImpressions) / count, Date = data.Key.ToString(), AveragePosition = data.Sum(t => t.AveragePosition) / count, AverageCPC = data.Sum(t => t.AverageCPC) / count });
                    }
                    grp1 = reports.GroupBy(t => t.Date);
                    foreach (var data in grp1)
                    {
                        var count = data.Count();
                        reports1.Add(new ReportChartModel { Clicks = data.Sum(t => t.Clicks) / count, Impressions = data.Sum(t => t.Impressions) / count, Date = data.Key, AveragePosition = data.Sum(t => t.AveragePosition) / count, AverageCPC = data.Sum(t => t.AverageCPC) / count });
                    }
                    return Json(reports1, JsonRequestBehavior.AllowGet);
            }
            return Json(null, JsonRequestBehavior.AllowGet);

        }
        public void SaveKeywords(int promotionId, List<KeywordProbabilityObject> kpos, List<string> negativeKeywords,
                                 string productGroupName, string promotionName)
        {
            var stationIds = new DataTable();
            stationIds.Columns.Add("Keyword", typeof (string));
            stationIds.Columns.Add("IsActive", typeof (Boolean));
            stationIds.Columns.Add("IsDeleted", typeof (Boolean));
            stationIds.Columns.Add("IsNegative", typeof (Boolean));
            stationIds.Columns.Add("SemplestProbability", typeof (float));
            stationIds.Columns.Add("IsTargetMSN", typeof (Boolean));
            stationIds.Columns.Add("IsTargetGoogle", typeof (Boolean));
            var negativeKeywordsToBeInserted = new List<string>();
            if (negativeKeywords != null)
                negativeKeywordsToBeInserted.AddRange(negativeKeywords);
            foreach (var kpo in kpos)
            {
                if (!kpo.isDeleted)
                {
                    kpo.isDeleted = IsDeletedKeyword(kpo.keyword.Trim(), negativeKeywords);
                }

                var dr = stationIds.NewRow();
                dr["Keyword"] = kpo.keyword.Trim();
                dr["IsActive"] = "true";
                dr["IsDeleted"] = kpo.isDeleted;
                if (IsNegativeKeyword(kpo.keyword.Trim(), negativeKeywords))
                {
                    dr["IsNegative"] = true;
                    negativeKeywordsToBeInserted.Remove(kpo.keyword.Trim());
                }
                else
                    dr["IsNegative"] = false;
                dr["SemplestProbability"] = kpo.semplestProbability;
                dr["IsTargetMSN"] = kpo.isTargetMSN;
                dr["IsTargetGoogle"] = kpo.isTargetGoogle;
                stationIds.Rows.Add(dr);
                //System.Diagnostics.Debug.WriteLine("insert into @kwa (keyword,IsActive,IsDeleted,IsNegative,IsTargetGoogle,IsTargetMSN) values ('" + dr["Keyword"].ToString() + "',1,0,1,0,0)");
            }
            foreach (string s in negativeKeywordsToBeInserted)
            {
                var dr = stationIds.NewRow();
                dr["Keyword"] = s.Trim();
                dr["IsActive"] = "true";
                dr["IsNegative"] = true;
                dr["IsDeleted"] = false;
                dr["IsTargetMSN"] = 0;
                dr["IsTargetGoogle"] = 0;
                stationIds.Rows.Add(dr);
            }
            if (stationIds.Rows.Count > 0)
            {
                var parameter = new SqlParameter("kwa", stationIds)
                                    {SqlDbType = SqlDbType.Structured, TypeName = "PromotionKeywordTableType"};


                var parameter2 = new SqlParameter("@PromotionId", promotionId) {SqlDbType = SqlDbType.Int};

                var parameters = new object[] {parameter, parameter2};
                using (var dbcontext = new SemplestModel.Semplest())
                {
                    ((IObjectContextAdapter) dbcontext).ObjectContext.CommandTimeout = 100;
                    dbcontext.Database.ExecuteSqlCommand("exec sp_UpdateKeywords @kwa, @PromotionId", parameters);
                    _savedCampaign = true;
                    
                    //set keyword id's back in the model
                    int userid =
                        ((Credential)
                         System.Web.HttpContext.Current.Session[SharedResources.SEMplestConstants.SESSION_USERID]).
                            UsersFK;
                    var firstOrDefault = dbcontext.Users.FirstOrDefault(key => key.UserPK == userid);
                    if (firstOrDefault != null)
                    {
                        var promotion =
                            firstOrDefault.Customer.ProductGroups.First(key => key.ProductGroupName == productGroupName)
                                .Promotions.FirstOrDefault(key => key.PromotionName == promotionName);
                        if (promotion != null)
                        {
                            var pkas = promotion.PromotionKeywordAssociations;
                            foreach (PromotionKeywordAssociation pka in pkas)
                            {
                                PromotionKeywordAssociation pka1 = pka;
                                var qry = kpos.Where(key => key.keyword == pka1.Keyword.Keyword1).ToList();
                                if (qry.Any())
                                    qry.First().id = pka.Keyword.KeywordPK;
                            }
                        }
                    }
                }
            }
        }
 public void SaveSelectedCategories(int promotionId, IEnumerable<string> selectedCategories)
 {
     using (var dbcontext = new SemplestModel.Semplest())
     {
         var query = dbcontext.KeywordCategories.Where(c => c.PromotionFK == promotionId);
         if (!query.Any())
         {
             foreach (
                 var keyCategory in
                     selectedCategories.Select(
                         category => new KeywordCategory {PromotionFK = promotionId, KeywordCategory1 = category})
                 )
             {
                 dbcontext.KeywordCategories.Add(keyCategory);
             }
             dbcontext.SaveChanges();
         }
         else // categories exists so update them
         {
             // delete them first
             foreach (KeywordCategory kc in query)
             {
                 dbcontext.KeywordCategories.Remove(kc);
             }
             dbcontext.SaveChanges();
             // add them
             foreach (
                 var keyCategory in
                     selectedCategories.Select(
                         category => new KeywordCategory {PromotionFK = promotionId, KeywordCategory1 = category})
                 )
             {
                 dbcontext.KeywordCategories.Add(keyCategory);
             }
             dbcontext.SaveChanges();
         }
     }
 }
        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 int GetBudgetCycleId(string budgetCycleName)
 {
     using (var dbcontext = new SemplestModel.Semplest())
     {
         var queryBudgetCycle = dbcontext.BudgetCycles.Where(m => m.BudgetCycle1 == budgetCycleName);
         if (queryBudgetCycle.Any())
         {
             var budgetCycle = queryBudgetCycle.FirstOrDefault();
             if (budgetCycle != null)
                 return budgetCycle.BudgetCyclePK;
         }
     }
     return -1;
 }
        public List<ProductGroup> GetProductGroupsForUser(int userid)
        {
            using (var dbcontext = new SemplestModel.Semplest())
            {
                // get the customerfk from userid
                var queryCustFk = from c in dbcontext.Users where c.UserPK == userid select c.CustomerFK;
                var customerIdFk = queryCustFk.FirstOrDefault();
                if (customerIdFk != null)
                {
                    var custfk = (int) customerIdFk;

                    // get ProductGroup
                    var queryProdGrp = from c in dbcontext.ProductGroups
                                       where c.CustomerFK == custfk
                                       select c;
                    // get Promotion
                    if (queryProdGrp.Any())
                    {
                        return queryProdGrp.ToList();
                    }
                }
            }
            return null;

        }
 public IQueryable<vwProductPromotion> GetUserWithProductGroupAndPromotions(int userid)
 {
     var semplestEntities = new SemplestModel.Semplest();
     return semplestEntities.vwProductPromotions.Where(t => t.UserPK == userid);
 }