public async Task <int> SaveCampaignAsync(CampaignDto campaign) { using (_logger.BeginTimedOperation("CampaignsRepository.SaveCampaignAsync enters..")) { DynamicParameters parameters = new DynamicParameters(); parameters.Add("@Id", campaign.Id); parameters.Add("@ProductId", campaign.Product.Id); parameters.Add("@Name", campaign.Name); parameters.Add("@Start", campaign.Start); parameters.Add("@End", campaign.End); parameters.Add("@Active", true); int result = 0; try { using (var cn = _connectionManager.Connection) { cn.Open(); using (var tran = cn.BeginTransaction()) { CommandDefinition cmd = new CommandDefinition("Usp_Campaigns_Ins", parameters, tran, null, CommandType.StoredProcedure); result = await _connectionManager.Connection.ExecuteAsync(cmd); tran.Commit(); } } return(result); } catch { throw new CampaignsProductManagerException(System.Net.HttpStatusCode.InternalServerError, new Error(_configuration, ErrorItem.InternalServerError)); } } }
public ActionResult CreateCampaignWithGoal([FromBody] CampaignDto campaign) { var goalEntity = CreateGoal(campaign); var campaignEntity = CreateCampaign(campaign, goalEntity); return(Ok(_mapper.Map <Campaign, CampaignDto>(campaignEntity))); }
public async Task <IActionResult> CreateCampaign(CampaignDto campaign) { if (!ModelState.IsValid) { return(BadRequest()); } var newCampaign = new Campaign { Name = campaign.Name, From = campaign.From, To = campaign.To }; try { await _unitOfWork.Campaigns.AddAsync(newCampaign); await _unitOfWork.SaveChangesAsync(); return(CreatedAtAction( nameof(Get), new { id = campaign.Id }, campaign)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
private static Promotion GetMockedPromotionWithSettings(XDocument settingsXml) { var stream = new MemoryStream(); settingsXml.Save(stream); var settings = stream.ToArray(); var promotionDto = new PromotionDto(); var promotionTable = new PromotionDto.PromotionDataTable(); promotionDto.Tables.Add(promotionTable); var promotionRow = promotionTable.AddPromotionRow("", ApplicationGuid, "", DateTime.MinValue, DateTime.MaxValue, "", 0, 0, "", 0, "", 0, DateTime.MinValue, DateTime.MinValue, "", "", 0, 0, settings, 0, 0); var promotionLanguageTable = new PromotionDto.PromotionLanguageDataTable(); promotionDto.Tables.Add(promotionLanguageTable); var promotionLanguageRow = promotionLanguageTable.AddPromotionLanguageRow("", "en-US", promotionRow); var campaignDto = new CampaignDto(); var campaignTable = new CampaignDto.CampaignDataTable(); campaignDto.Tables.Add(campaignTable); var campaignRow = campaignTable.AddCampaignRow(ApplicationGuid, DateTime.MinValue, DateTime.MaxValue, "", DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, "", true, false, ""); return(new Promotion(promotionLanguageRow, promotionRow, campaignRow)); }
/// <summary> /// Gets the Campaign dto, checks permissions and caches results. /// </summary> /// <param name="campaignId">The campaign id.</param> /// <returns></returns> public static CampaignDto GetCampaignDto(int campaignId) { // Assign new cache key, specific for site guid and response groups requested // string cacheKey = MarketingCache.CreateCacheKey("Campaign", CampaignId.ToString()); CampaignDto dto = null; // check cache first //object cachedObject = MarketingCache.Get(cacheKey); //if (cachedObject != null) //dto = (CampaignDto)cachedObject; // Load the object if (dto == null) { CampaignAdmin campaign = new CampaignAdmin(); campaign.Load(campaignId); dto = campaign.CurrentDto; // Insert to the cache collection //MarketingCache.Insert(cacheKey, dto, MarketingConfiguration.CacheConfig.CampaignCollectionTimeout); } dto.AcceptChanges(); return(dto); }
/// <summary> /// Saves the campaign. /// </summary> /// <param name="dto">The dto.</param> public static void SaveCampaign(CampaignDto dto) { if (dto == null) { throw new ArgumentNullException("dto", String.Format("CampaignDto can not be null")); } //TODO: check concurrency when updating the records //TODO: need to check security roles here, // The procedure will be following: // 1. Retrieve the record from the database for each category that is about to be updated // 2. Check Write permissions (if failed generate the error and exit) // 3. Otherwise proceed to update // Continue with security checks and other operations /* * foreach (CampaignDto.CampaignRow row in dto.Campaign.Rows) * { * // Check Security * IDataReader reader = DataHelper.CreateDataReader(dto.CampaignSecurity, String.Format("CampaignId = -1 or CampaignId = {0}", row.CampaignId)); * PermissionRecordSet recordSet = new PermissionRecordSet(PermissionHelper.ConvertReaderToRecords(reader)); * if (!PermissionManager.CheckPermission(CampaignScope.Campaign, Permission.Read, recordSet)) * { * row.Delete(); * continue; * } * } * */ CampaignAdmin admin = new CampaignAdmin(dto); admin.Save(); }
public async Task <IActionResult> AddCampaign(CampaignDto model) { //check if model state is not valid if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //Create campaign object //Create facility object var programme = new Models.Campaign { Organization = model.Organization, Description = model.Description, Location = model.Location, EventDate = model.EventDate, CreatedDate = DateTime.Now }; //save facility to database _db.Campaigns.Add(programme); if (await _db.SaveChangesAsync() > 0) { // CampaignSms("Donor Trace", "0242229571"); return(Ok()); // save operation successful } return(BadRequest("Could not save campaign")); // save operation failed }
public string GetCampaignInfo(string[] commandArray) { try { var name = commandArray[1]; var campaign = _repository.FindByName(name); var campaignDto = new CampaignDto { Id = campaign.Id, Name = campaign.Name, Status = campaign.Active ? "Active" : "Ended", TargetSales = campaign.TargetSalesCount, TotalSales = campaign.TotalSales, Turnover = campaign.Turnover, AverageItemPrice = campaign.AverageItemPrice }; return ($"Campaign {campaignDto.Name} info; Status {campaignDto.Status}, Target Sales {campaignDto.TargetSales}, Total Sales {campaignDto.TotalSales}, Turnover {campaignDto.Turnover}, Average Item Price {campaignDto.TargetSales}"); } catch { return("get_campaign_info NAME"); } }
public void TestInitialize() { autoMapper.Reset(); autoMapper.Initialize(); product = new Product { Id = "ProductId", Name = "ProductName" }; productDto = new ProductDto { Id = "ProductId", Name = "ProductName" }; campaign = new Campaign { Id = "CampaignId", Name = "CampaignName", Start = DateTime.Now, End = DateTime.Now.AddMonths(1), Product = product }; campaignDto = new CampaignDto { Name = "CampaignName", Start = "01.02.2019", End = "01.03.2019", Product = productDto }; campaigns = new List <Campaign> { campaign }; }
public void CampaignSms(CampaignDto model) { // var phoneNumbers = from p in _db.Donors //select new { p.Phone }; string clientId = _config.GetValue <string>("Sms:ClientId"); string clientSecret = _config.GetValue <string>("Sms:ClientSecret"); StringBuilder builder = new StringBuilder(); builder.Append("Donor Trace Campaign"); builder.AppendLine(); builder.Append("Organization: " + " " + model.Organization); builder.AppendLine(); builder.Append("Description: " + " " + model.Description); builder.AppendLine(); builder.Append("Location: " + " " + model.Location); builder.AppendLine(); builder.Append("Date: " + " " + model.EventDate); var host = new ApiHost(new BasicAuth(clientId, clientSecret)); var messageApi = new MessagingApi(host); // foreach (var p in phoneNumbers) // { MessageResponse msg = messageApi.SendQuickMessage("Donor Trace", "0242229571", builder.ToString(), true); //} // return Ok(); }
public string Execute(params object[] parameters) { if (parameters.Length < 5) { return("Invalid parameters"); } var name = parameters[0].ToString(); var productCode = parameters[1].ToString(); var duration = int.Parse(parameters[2].ToString()); var priceManipulationLimit = int.Parse(parameters[3].ToString()); var targetSalesCount = int.Parse(parameters[4].ToString()); var data = new CampaignDto { Name = name, ProductCode = productCode, Duration = duration, PriceManipulationLimit = priceManipulationLimit, TargetSalesCount = targetSalesCount }; var response = _campaignService.Create(data); if (response.Success) { return ($"Campaign created; name {data.Name}, product {data.ProductCode}, duration {data.Duration}, limit {data.PriceManipulationLimit}, target sales count {data.TargetSalesCount}"); } return(string.Empty); }
public List <GameWithCampaignDto> CampaignMenuDelete(List <GameWithCampaignDto> gameList) { _gameService.PrintList(gameList); Console.WriteLine("Enter Campaign number that you want to delete:"); int campaignId = Convert.ToInt32(Console.ReadLine()); var campaignToBeDeleted = _campaignService.Get(gameList, campaignId); var deletedCampaign = _campaignService.Delete(campaignToBeDeleted); var deleteItem = new CampaignDto(); foreach (var gameItem in gameList) { foreach (var campaignItem in gameItem.campaignDtos) { if (campaignItem.Id == campaignId) { deleteItem = campaignItem; } } gameItem.campaignDtos.Remove(deleteItem); } return(gameList); }
/// <summary> /// Handles the SaveChanges event of the EditSaveControl control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void EditSaveControl_SaveChanges(object sender, SaveControl.SaveEventArgs e) { // Validate form if (!this.Page.IsValid) { e.RunScript = false; return; } CampaignDto campaign = (CampaignDto)Session[_CampaignDtoEditSessionKey]; //null; if (CampaignId > 0 && campaign == null) { campaign = CampaignManager.GetCampaignDto(CampaignId); //Int32.Parse(Parameters[_CampaignIdString].ToString())); } else if (CampaignId == 0) { campaign = new CampaignDto(); } IDictionary context = new ListDictionary(); context.Add(_CampaignDtoString, campaign); ViewControl.SaveChanges(context); if (campaign.HasChanges()) { CampaignManager.SaveCampaign(campaign); } // we don't need to store Dto in session any more Session.Remove(_CampaignDtoEditSessionKey); }
/// <summary> /// Loads the context. /// </summary> private void LoadContext() { if (CampaignId > 0) { CampaignDto campaign = null; if (!this.IsPostBack && (!this.Request.QueryString.ToString().Contains("Callback=yes"))) // load fresh on initial load { campaign = LoadFresh(); } else // load from session { campaign = (CampaignDto)Session[_CampaignDtoEditSessionKey]; if (campaign == null) { campaign = LoadFresh(); } } // Put a dictionary key that can be used by other tabs IDictionary dic = new ListDictionary(); dic.Add(_CampaignDtoString, campaign); // Call tabs load context ViewControl.LoadContext(dic); } }
public async Task <IActionResult> Edit(Guid id, [Bind("Id,Name")] CampaignDto campaignDto) { if (id != campaignDto.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(campaignDto); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CampaignDtoExists(campaignDto.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(campaignDto)); }
public List <GameWithCampaignDto> ListWithCampaign() { var gameList = List(); var campaignList = _campaignService.List(); var gameDtoList = new List <GameWithCampaignDto>(); foreach (var gameItem in gameList) { var gameDto = new GameWithCampaignDto(); gameDto.GameName = gameItem.GameName; gameDto.Id = gameItem.Id; gameDto.campaignDtos = new List <CampaignDto>(); foreach (var campaignItem in campaignList) { if (gameItem.Id == campaignItem.GameId) { var campaignDto = new CampaignDto(); campaignDto.Id = campaignItem.Id; campaignDto.GameId = campaignDto.GameId; campaignDto.DiscountRate = campaignItem.DiscountRate; campaignDto.CampaignName = campaignItem.CampaignName; gameDto.campaignDtos.Add(campaignDto); } } gameDtoList.Add(gameDto); } return(gameDtoList); }
public CampaignDto Update(CampaignDto campaign, string newCampaignName, int newDiscountRate) { campaign.CampaignName = newCampaignName; campaign.DiscountRate = newDiscountRate; Console.WriteLine(campaign.CampaignName + " was successfully updated"); return(campaign); }
/// <summary> /// Initializes a new instance of the <see cref="MarketingHelper"/> class. /// </summary> /// <param name="campaigns">The campaigns.</param> /// <param name="expressions">The expressions.</param> /// <param name="policies">The policies.</param> /// <param name="promotions">The promotions.</param> /// <param name="segments">The segments.</param> public MarketingHelper(CampaignDto campaigns, ExpressionDto expressions, PolicyDto policies, PromotionDto promotions, SegmentDto segments) { _Campaigns = campaigns; _Expressions = expressions; _Policies = policies; _Promotions = promotions; _Segments = segments; }
/// <summary> /// Loads the fresh. /// </summary> /// <returns></returns> private CampaignDto LoadFresh() { CampaignDto campaign = CampaignManager.GetCampaignDto(CampaignId); // persist in session Session[_CampaignDtoEditSessionKey] = campaign; return(campaign); }
public async Task <IActionResult> Create([Bind("Name,EmailId,EmailName,EmailContent,EmailObject,EmailExpeditor,ContactsEmailAdress")] CampaignDto campaignDto) { if (ModelState.IsValid) { int emailId = 0; if (!string.IsNullOrEmpty(campaignDto.EmailName)) { Email email = new Email() { Name = campaignDto.EmailName, Content = campaignDto.EmailContent, Object = campaignDto.EmailObject, Expeditor = campaignDto.EmailExpeditor }; _context.Email.Add(email); await _context.SaveChangesAsync(); var emailSaved = _context.Email.FirstOrDefault(e => e.Name.Equals(email.Name)); emailId = emailSaved.Id; } else { emailId = (int)campaignDto.EmailId; } Campaign campaign = new Campaign() { Name = campaignDto.Name, EmailId = emailId, }; var createdStatus = _context.CampaignStatus.FirstOrDefault(s => s.Name.Equals("Created")); campaign.CampaingStatusId = createdStatus.Id; _context.Campaign.Add(campaign); await _context.SaveChangesAsync(); foreach (var item in campaignDto.ContactsEmailAdress) { var contact = _context.Contact.FirstOrDefault(s => s.EmailAdress.Equals(item)); var campaignSaved = _context.Campaign.FirstOrDefault(c => c.Name.Equals(campaign.Name)); var campaignContact = new CampaignContact() { ContactId = contact.Id, CampaignId = campaignSaved.Id }; _context.CampaignContact.Add(campaignContact); } await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["EmailId"] = new SelectList(_context.Email, "Id", "Id", campaignDto.EmailId); return(View(campaignDto)); }
/// <summary> /// Saves the changes. /// </summary> /// <param name="context">The context.</param> public void SaveChanges(IDictionary context) { CampaignDto dto = (CampaignDto)context[_CampaignDtoString]; CampaignDto.CampaignRow row = null; if (dto.Campaign.Count > 0) { row = dto.Campaign[0]; row.Modified = DateTime.UtcNow; row.ModifiedBy = Page.User.Identity.Name; } else { row = dto.Campaign.NewCampaignRow(); row.ApplicationId = MarketingConfiguration.Instance.ApplicationId; row.Created = DateTime.UtcNow; row.ModifiedBy = Page.User.Identity.Name; } row.Name = CampaignName.Text; row.StartDate = this.AvailableFrom.Value.ToUniversalTime(); row.EndDate = this.ExpiresOn.Value.ToUniversalTime(); row.IsActive = IsActive.IsSelected; row.IsArchived = IsArchived.IsSelected; row.Comments = Comments.Text; if (row.RowState == DataRowState.Detached) { dto.Campaign.Rows.Add(row); } // Attach segments // Clear existing segments if (dto.CampaignSegment.Count > 0) { foreach (CampaignDto.CampaignSegmentRow segmentrow in dto.CampaignSegment.Rows) { segmentrow.Delete(); } } // Attach selected ones foreach (ListItem item in TargetSegments.Items) { if (!item.Selected) { continue; } CampaignDto.CampaignSegmentRow srow = dto.CampaignSegment.NewCampaignSegmentRow();; srow.CampaignId = row.CampaignId; srow.SegmentId = Int32.Parse(item.Value); dto.CampaignSegment.Rows.Add(srow); } }
public async Task <IActionResult> SaveCampaignAsync(CampaignDto campaign) { int res = await _campaignsLogic.SaveCampaignAsync(campaign); if (res > 0) { return(ReturnApiResponseSuccessWithResult("created", (int)HttpStatusCode.Created)); } return(ReturnApiResponseWithError(new Core.ResponseModel.ErrorModel((int)HttpStatusCode.InternalServerError))); }
private Goal CreateGoal(CampaignDto campaign) { var _goal = _goalService.Create( campaign.Goal.GoalStart, campaign.Goal.GoalEnd, campaign.Goal.MinAmount ); return(_goal.Entity); }
private Campaign CreateCampaign(CampaignDto campaign, Goal goal) { var _campaign = _campaignService.Create( campaign.CampaignName, campaign.CampaignDescription, campaign.CampaignUrl, goal ); return(_campaign.Entity); }
public async Task <IActionResult> Create([Bind("Id,Name")] CampaignDto campaignDto) { if (ModelState.IsValid) { campaignDto.Id = Guid.NewGuid(); _context.Add(campaignDto); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(campaignDto)); }
public async Task <IActionResult> CloseCampaignAsync([FromBody] CampaignDto campaignDto) { var campaign = await campaignService.GetCampaignAsync(campaignDto.Id); if (campaign == null) { return(NotFound()); } await campaignService.CloseCampaignAsync(campaign); return(Ok()); }
/// <summary> /// Loads the data and data bind. /// </summary> /// <param name="sortExpression">The sort expression.</param> private void LoadDataAndDataBind(string sortExpression) { CampaignDto dto = CampaignManager.GetCampaignDto(); if (dto.Campaign != null) { DataView view = dto.Campaign.DefaultView; view.Sort = sortExpression; MyListView.DataSource = view; } MyListView.CurrentListView.PrimaryKeyId = EcfListView.MakePrimaryKeyIdString("CampaignId"); MyListView.DataBind(); }
public IHttpActionResult PostCampaign(CampaignDto campaignDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } campaignDto.Id = Guid.NewGuid().ToString(); var campaign = Mapper.Map <CampaignDto, Campaign>(campaignDto); _campaignRepository.AddCampaign(campaign); return(CreatedAtRoute("DefaultApi", new { id = campaignDto.Id }, campaignDto)); }
private async Task <CampaignDto> CreateCampaignRequest(CampaignDto data) { var client = _factory.CreateAuthClient(); var json = JsonConvert.SerializeObject(data); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync("/campaign", content); response.EnsureSuccessStatusCode(); var stringResponse = await response.Content.ReadAsStringAsync(); _output.WriteLine(stringResponse); return(JsonConvert.DeserializeObject <CampaignDto>(stringResponse)); }
public static Campaign ToCampaign(this CampaignDto campaignDto) { if (campaignDto == null) { return(null); } return(new Campaign { Id = campaignDto.Id, Name = campaignDto.Name, Description = campaignDto.Description, IsActive = campaignDto.IsActive }); }
private int CreateCampaigns() { var dto = new CampaignDto(); var campaignRow = dto.Campaign.NewCampaignRow(); campaignRow.Name = "QuickSilver"; campaignRow.Created = DateTime.UtcNow; campaignRow.IsArchived = false; campaignRow.ApplicationId = AppContext.Current.ApplicationId; campaignRow.Modified = DateTime.UtcNow; campaignRow.IsActive = true; campaignRow.StartDate = DateTime.Today; campaignRow.EndDate = DateTime.Today.AddYears(1); dto.Campaign.AddCampaignRow(campaignRow); CampaignManager.SaveCampaign(dto); return dto.Campaign.First().CampaignId; }