/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="businessId">The AdWords Express business id.</param> /// <param name="promotionId">The promotion id.</param> public void Run(AdWordsUser user, long businessId, long promotionId) { // Get the ExpressBusinessService. ExpressBusinessService businessService = (ExpressBusinessService) user.GetService(AdWordsService.v201509.ExpressBusinessService); // Get the PromotionService PromotionService promotionService = (PromotionService) user.GetService(AdWordsService.v201509.PromotionService); // Set the business ID to the service. promotionService.RequestHeader.expressBusinessId = businessId; // Update the budget for the promotion Promotion promotion = new Promotion(); promotion.id = promotionId; Money newBudget = new Money(); newBudget.microAmount = 2000000; promotion.budget = newBudget; PromotionOperation operation = new PromotionOperation(); operation.@operator = Operator.SET; operation.operand = promotion; try { Promotion[] updatedPromotions = promotionService.mutate( new PromotionOperation[] { operation }); Console.WriteLine("Promotion ID {0} for business ID {1} now has budget micro " + "amount {2}.", promotionId, businessId, updatedPromotions[0].budget.microAmount); } catch (Exception e) { throw new System.ApplicationException("Failed to update promotions.", e); } }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="businessId">The AdWords Express business id.</param> public void Run(AdWordsUser user, long businessId) { // Get the PromotionService PromotionService promotionService = (PromotionService) user.GetService(AdWordsService.v201601.PromotionService); // Set the business ID to the service. promotionService.RequestHeader.expressBusinessId = businessId; // First promotion Promotion marsTourPromotion = new Promotion(); Money budget = new Money(); budget.microAmount = 1000000L; marsTourPromotion.name = "Mars Tour Promotion " + ExampleUtilities.GetShortRandomString(); marsTourPromotion.status = PromotionStatus.PAUSED; marsTourPromotion.destinationUrl = "http://www.example.com"; marsTourPromotion.budget = budget; marsTourPromotion.callTrackingEnabled = true; // Criteria // Criterion - Travel Agency product service ProductService productService = new ProductService(); productService.text = "Travel Agency"; // Criterion - English language // The ID can be found in the documentation: // https://developers.google.com/adwords/api/docs/appendix/languagecodes Language language = new Language(); language.id = 1000L; // Criterion - State of California Location location = new Location(); location.id = 21137L; marsTourPromotion.criteria = new Criterion[] { productService, language, location }; // Creative Creative creative = new Creative(); creative.headline = "Standard Mars Trip"; creative.line1 = "Fly coach to Mars"; creative.line2 = "Free in-flight pretzels"; marsTourPromotion.creatives = new Creative[] { creative }; PromotionOperation operation = new PromotionOperation(); operation.@operator = Operator.ADD; operation.operand = marsTourPromotion; try { Promotion[] addedPromotions = promotionService.mutate( new PromotionOperation[] { operation }); Console.WriteLine("Added promotion ID {0} with name {1} to business ID {2}.", addedPromotions[0].id, addedPromotions[0].name, businessId); } catch (Exception e) { throw new System.ApplicationException("Failed to add promotions.", e); } }
public void Enable(Promotion promotion) { if (promotion.MarkEnable()) { _db.SaveChanges(); Event.Raise(new PromotionEnabled(promotion)); } }
public bool Create(Promotion promotion) { if (promotion.RequireCouponCode && IsCouponAlreadyTaken(promotion.CouponCode, promotion.Id)) { throw new InvalidOperationException("Coupon code has been taken."); } return _db.GetRepository<Promotion>().Insert(promotion); }
public bool Update(Promotion promotion) { if (promotion.RequireCouponCode && IsCouponAlreadyTaken(promotion.CouponCode, promotion.Id)) { throw new InvalidOperationException("Coupon code has been taken."); } return _db.GetRepository<Promotion>().Update(promotion, k => new object[] { k.Id }); }
public Promotion CreatePromotion(Promotion promotion) { var entity = promotion.ToDataModel(); coreModel.Promotion retVal = null; using (var repository = _repositoryFactory()) { repository.Add(entity); CommitChanges(repository); } retVal = GetPromotionById(entity.Id); return retVal; }
public Promotion CreatePromotion(Promotion promotion) { var entity = promotion.ToDataModel(); coreModel.Promotion retVal = null; using (var repository = _repositoryFactory()) { repository.Add(entity); CommitChanges(repository); } retVal = GetPromotionById(entity.Id); _cacheManager.ClearRegion("MarketingModuleRegion"); return retVal; }
public long insert(Promotion entity) { try { entity.CreatedAt = DateTime.Now; db.Promotions.Add(entity); db.SaveChanges(); return entity.id; } catch { return -1; } }
public bool update(Promotion entity) { try { Promotion p = db.Promotions.Find(entity.id); p.Content = entity.Content; p.Deadline = entity.Deadline; p.ModifieAt = DateTime.Now; p.Status = entity.Status; p.Title = entity.Title; db.SaveChanges(); return true; } catch { return false; } }
public bool Insert(string UPICode, string Title, string Content, DateTime StartDate, DateTime EndDate, int AdminId) { try { Promotion o = new Promotion(); o.UpiCode = UPICode; o.Title = Title; o.Content = Content; o.StartDate = StartDate; o.EndDate = EndDate; o.AdministratorId = AdminId; db.Promotions.InsertOnSubmit(o); db.SubmitChanges(); return true; } catch { return false; } }
public void UpdatePromotions(Promotion[] promotions) { using (var repository = _repositoryFactory()) using (var changeTracker = base.GetChangeTracker(repository)) { foreach (var promotion in promotions) { var sourceEntity = promotion.ToDataModel(); var targetEntity = repository.GetPromotionById(promotion.Id); if (targetEntity == null) { repository.Add(sourceEntity); } else { changeTracker.Attach(targetEntity); sourceEntity.Patch(targetEntity); } } CommitChanges(repository); } }
partial void UpdatePromotion(Promotion instance);
decimal CalculateTotalPromoted(Receipt receipt, Promotion[] promotions) { string[] barcodes = promotions.Where(p => p.Type == "BUY_ONE_HUNDRED_CUT_FIFTY") .Select(p => p.BarCode) .ToArray(); decimal totalAfterPromoted = receipt.ReceiptItems.Where(r => barcodes.Contains(r.Product.Barcode)) .Select(r => (r.Total - r.Promoted)).Sum(); return (int)(totalAfterPromoted/100)*50; }
public static IEnumerable<Promotion> GetAllPromotionList() { var promotions = new List<Promotion>(); using (var connection = new SqlConnection(GetConnection())) { const string sql = @"SELECT * FROM [dbo].[promotion]"; var cmd = new SqlCommand(sql, connection); connection.Open(); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var promotion = new Promotion { CodeId = reader.GetString(0), Rate = reader.GetInt32(1), Price = reader.GetSqlMoney(2).ToDouble(), Hidden = reader.GetBoolean(3) }; promotions.Add(promotion); } } return promotions; } }
public void Save(Promotion promotion) { m_session.Save(promotion); m_session.Flush(); }
protected void btnAssignPromotion_Click(object sender, EventArgs e) { clearMsgPanel(); PromotionAssigment promotionAssigment = new PromotionAssigment(); if (vaidateInputAndFillData(promotionAssigment)) { PromotionManager promotionAssigmentManager = new PromotionManager(promotionAssigment); TransactionResponse response = promotionAssigmentManager.addNewPromotionAssignment(); if (response.isSuccessful()) { msgPanel.Visible = true; SucessDIV.Visible = true; lblSuccessMessage.Text = response.getMessage(); AssignPromotionPanel.Visible = true; btnAssignNew.Visible = true; btnAssignPromotion.Visible = false; //REGISTER NOTIFICATION ABOUT THIS ASSIGNMENT TO HR OFFICER //HERE THE CIRRENT USER (i.e., HR Manager) IS THE SENDER AND HR OFFICERs ARE THE RECEIVERS NotificationManager notificationManager = new NotificationManager(promotionAssigment); TransactionResponse notificationResponse = notificationManager.addNotificationForPromotioAssignement(Membership.GetUser()); if (!notificationResponse.isSuccessful()) { msgPanel.Visible = true; WarnDIV.Visible = true; lblWarningMsg.Text = notificationResponse.getMessage() + notificationResponse.getErrorCode(); } //REMOVE THIS TASK FROM HR_MANGERS MAIL BOX TransactionResponse delteResponse = notificationManager.deleteNotificationForAssignedPromotion(Membership.GetUser()); if (!delteResponse.isSuccessful()) { //check if Warning Message is already logged, if so just add on it if (WarnDIV.Visible) { msgPanel.Visible = true; lblWarningMsg.Text = lblWarningMsg.Text + " and " + delteResponse.getMessage() + delteResponse.getErrorCode(); } else { msgPanel.Visible = true; WarnDIV.Visible = true; lblWarningMsg.Text = delteResponse.getMessage() + delteResponse.getErrorCode(); } } Promotion promotion = new Promotion(); promotion.MinuteNo = promotionAssigment.MinuteNo; PromotionManager promotionManager = new PromotionManager(promotion); TransactionResponse promotionResponse = promotionManager.updatePromotionStatus(promotion, PromotionConstants.PROMOTION_ASSIGNED); if (!promotionResponse.isSuccessful()) { msgPanel.Visible = true; ErroroDIV.Visible = true; lblErrorMsg.Text = "Error occured while update promotion status. Please contact your system administrator."; return; } } else { msgPanel.Visible = true; WarnDIV.Visible = true; lblWarningMsg.Text = response.getMessage() + response.getErrorCode(); } } }
private void detach_Promotions(Promotion entity) { this.SendPropertyChanging(); entity.Administrator = null; }
private DBOperationsUtil getDBOperationToUpdatePromotionStatus4Assignment(IDictionary<string, object> parameters, Promotion promotion, string promoStatus) { DBOperationsUtil dpOperation = null; //Pass Stored Procedure Name and parameter list. parameters.Add("@Emp_ID", 0); parameters.Add("@Minute_No", promotion.MinuteNo); parameters.Add("@vacancy_No", 0); parameters.Add("@forAssOrAnnounce", promoStatus); dpOperation = new DBOperationsUtil(DbAccessConstants.spUpdatePromotionStatus, parameters); return dpOperation; }
public ActionResult Edit(int id) { Promotion Promotion = _db.Promotions.Find(id); return(View(Promotion)); }
private void Dispatch(Message completeMessage) { if (completeMessage.type != MessageType.Ping && completeMessage.type != MessageType.Pong) { Debug.Log($"Recieved message of type {completeMessage.type}"); } Action action = completeMessage.type switch { MessageType.Connect when !isHost => () => { string hostName = Encoding.UTF8.GetString(completeMessage.data); host = new Player(string.IsNullOrEmpty(hostName) ? "Host" : hostName, Team.White, true); string localName = PlayerPrefs.GetString("PlayerName", "GUEST"); player = new Player(localName, Team.Black, false); mainThreadActions.Enqueue(() => { LoadLobby(Lobby.Type.Client); lobby?.UpdatePlayerName(host); }); SendMessage(new Message(MessageType.UpdateName, System.Text.Encoding.UTF8.GetBytes(localName))); }, MessageType.Disconnect when isHost => PlayerDisconnected, MessageType.Disconnect when !isHost => lobby == null ? (Action)Disconnect : (Action)Shutdown, MessageType.Ping => () => SendMessage(new Message(MessageType.Pong)), MessageType.Pong => ReceivePong, MessageType.ProposeTeamChange => ReceiveTeamChangeProposal, MessageType.ApproveTeamChange => () => mainThreadActions.Enqueue(SwapTeams), MessageType.Ready => Ready, MessageType.Unready => Unready, MessageType.HandicapOverlayOn when lobby => () => lobby?.ToggleHandicapOverlay(true), MessageType.HandicapOverlayOff when lobby => () => lobby?.ToggleHandicapOverlay(false), MessageType.StartMatch when !isHost => () => StartMatch(GameParams.Deserialize(completeMessage.data)), MessageType.Surrender when multiplayer => () => multiplayer.Surrender( surrenderingTeam: isHost?player.Value.team: host.team, timestamp: JsonConvert.DeserializeObject <float>(Encoding.ASCII.GetString(completeMessage.data)) ), MessageType.BoardState when multiplayer => () => multiplayer.ReceiveBoard(BoardState.Deserialize(completeMessage.data)), MessageType.Promotion when multiplayer => () => multiplayer.ReceivePromotion(Promotion.Deserialize(completeMessage.data)), MessageType.OfferDraw when multiplayer => () => mainThreadActions.Enqueue(() => GameObject.FindObjectOfType <OfferDrawPanel>()?.Open()), MessageType.AcceptDraw when multiplayer => () => multiplayer.Draw(JsonConvert.DeserializeObject <float>(Encoding.ASCII.GetString(completeMessage.data))), MessageType.UpdateName when isHost => () => UpdateClientName(completeMessage), MessageType.UpdateName when !isHost => () => UpdateHostName(completeMessage), MessageType.FlagFall when multiplayer => () => multiplayer.ReceiveFlagfall(Flagfall.Deserialize(completeMessage.data)), MessageType.Checkmate when multiplayer => () => multiplayer.ReceiveCheckmate(BitConverter.ToSingle(completeMessage.data, 0)), MessageType.Stalemate when multiplayer => () => multiplayer.ReceiveStalemate(BitConverter.ToSingle(completeMessage.data, 0)), MessageType.OpponentSearching when lobby&& !isHost => lobby.OpponentSearching, MessageType.OpponentFound when lobby&& !isHost => () => mainThreadActions.Enqueue(() => lobby.OpponentFound(host)), _ => () => Debug.LogWarning($"Ignoring unhandled message {completeMessage.type}"), }; action?.Invoke(); }
private JsonResult ToJson(Promotion model) { var viewModel = new PromotionUi(); viewModel.DrugCatalogList = h.GetCatalogList().Select(x => new TextValue { Text = x.Text, Value = x.Value }).ToList(); viewModel.RegionGlobalList = DB.Regions().Select(x => new TextValue(x)).ToList(); viewModel.Id = model.Id; viewModel.Name = model.Name; viewModel.Annotation = model.Annotation; if (model.MediaFile != null) { viewModel.PromotionFileId = model.MediaFile.Id; viewModel.PromotionFileName = model.MediaFile.ImageName; viewModel.PromotionFileUrl = Url.Action("GetFile", "MediaFiles", new { model.MediaFile.Id }); } if (model.Id == 0) { viewModel.Title = "Новая промоакция"; } else { viewModel.Title = "Редактирование промоакции: " + model.Name; } viewModel.PromotionFileId = model.MediaFile?.Id; if (model.Begin < DateTime.Now) { viewModel.Begin = DateTime.Now.ToString("dd.MM.yyyy"); } else { viewModel.Begin = model.Begin.ToString("dd.MM.yyyy"); } if (model.End < DateTime.Now) { viewModel.End = DateTime.Now.ToString("dd.MM.yyyy"); } else { viewModel.End = model.End.ToString("dd.MM.yyyy"); } viewModel.DrugList = model.PromotionToDrug.ToList().Select(x => x.DrugId.ToString()).ToList(); var regions = DB.Regions((ulong)model.RegionMask); viewModel.RegionList = regions.Select(x => x.Id.ToString()).ToList(); if (model.AllSuppliers) { viewModel.SuppierRegions = new List <string>() { "0" } } ; else { viewModel.SuppierRegions = model.PromotionsToSupplier.Select(x => x.SupplierId.ToString()).ToList(); } viewModel.SuppierRegionsList = h.GetSupplierList(regions.Select(x => x.Id).ToList()) .Select(x => new TextValue { Text = x.Text, Value = x.Value }) .ToList(); viewModel.SuppierRegionsList.Add(new TextValue() { Text = "Все поставщики из выбранных регионов", Value = "0" }); return(Json(viewModel, JsonRequestBehavior.AllowGet)); }
public IActionResult Post([FromBody] AddPromotionViewModel promotionToAdd) { if (!IsMerchant()) { return(BadRequest(new { error = "De voorziene token voldoet niet aan de eisen." })); } //modelstate werkt niet op lijsten :-D if (promotionToAdd.Images == null || !promotionToAdd.Images.Any()) { return(BadRequest(new { error = "Geen afbeelding(en) meegeven." })); } if (!ContainsJpgs(promotionToAdd.Images)) { return(BadRequest(new { error = "Geen jpg afbeelding(en) gevonden" })); } if (promotionToAdd.StartDate == null) { return(BadRequest(new { error = "Geen start datum meegeven." })); } if (promotionToAdd.EndDate == null) { return(BadRequest(new { error = "Geen eind datum meegeven." })); } if (ModelState.IsValid) { Establishment establishmentFromDb = _establishmentRepository.getById(promotionToAdd.EstablishmentId ?? 0); if (establishmentFromDb == null) { return(BadRequest(new { error = "Vestiging niet gevonden." })); } if (!_establishmentRepository.isOwnerOfEstablishment(int.Parse(User.FindFirst("userId")?.Value), establishmentFromDb.EstablishmentId)) { return(BadRequest(new { error = "Vestiging behoord niet tot uw vestigingen." })); } Promotion newPromotion = new Promotion { Name = promotionToAdd.Name, Message = promotionToAdd.Message, StartDate = (DateTime)promotionToAdd.StartDate, EndDate = (DateTime)promotionToAdd.EndDate }; _promotionRepository.addPromotion(promotionToAdd.EstablishmentId ?? 0, newPromotion); //we hebben id nodig voor img path dus erna newPromotion.Images = ConvertFileViewModelToImages(promotionToAdd.Images, newPromotion.PromotionId); newPromotion.Attachments = ConvertFileViewModelToAttachments(promotionToAdd.Attachments, newPromotion.PromotionId); _promotionRepository.SaveChanges(); return(Ok(new { bericht = "De promotie werd succesvol toegevoegd." })); } //Als we hier zijn is is modelstate niet voldaan dus stuur error 400, slechte aanvraag string errorMsg = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)); return(BadRequest(new { error = errorMsg })); }
public IActionResult Put(int id, [FromBody] ModifyPromotionViewModel editedPromotion) { if (ModelState.IsValid) { if (!IsMerchant()) { return(BadRequest(new { error = "De voorziene token voldoet niet aan de eisen." })); } Promotion promotion = _promotionRepository.getById(id); if (promotion == null) { return(BadRequest(new { error = "Promotie niet gevonden" })); } if (!_promotionRepository.isOwnerOfPromotion(int.Parse(User.FindFirst("userId")?.Value), id)) { return(BadRequest(new { error = "Promotie behoord niet tot uw promoties" })); } if (!string.IsNullOrEmpty(editedPromotion.Name)) { promotion.Name = editedPromotion.Name; } if (!string.IsNullOrEmpty(editedPromotion.Message)) { promotion.Message = editedPromotion.Message; } if (editedPromotion.StartDate != null) { promotion.StartDate = (DateTime)editedPromotion.StartDate; } if (editedPromotion.EndDate != null) { promotion.EndDate = (DateTime)editedPromotion.EndDate; } if (editedPromotion.Attachments != null && editedPromotion.Attachments.Any()) { var attachments = ConvertFileViewModelToAttachments(editedPromotion.Attachments, id); if (attachments.Any()) { promotion.Attachments = attachments; } } if (editedPromotion.Images != null && editedPromotion.Images.Any()) { var images = ConvertFileViewModelToImages(editedPromotion.Images, id); if (images.Any()) { promotion.Images = images; } } _promotionRepository.SaveChanges(); return(Ok(new { bericht = "De promotie werd succesvol bijgewerkt." })); } //Als we hier zijn is is modelstate niet voldaan dus stuur error 400, slechte aanvraag string errorMsg = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)); return(BadRequest(new { error = errorMsg })); }
private void LvPromotionsItem_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e) { Promotion promotion = (Promotion)((Grid)sender).DataContext; ((Window.Current.Content as Frame)?.Content as MainPage)?.contentFrame.Navigate(typeof(PromotionDetail), new EditPromotionPassThroughElement(promotion, new CompanyManager().FindCompanyById(promotion.CompanyId), (int)AddPromotionPassThroughElement.IDENTIFIERS.PROMOTION)); }
protected void btnRegister_Click(object sender, EventArgs e) { clearLabelMsg(); Vacancy vacancy = new Vacancy(); if (!validateAllData(vacancy) && isGeneralOrGSpecific != 0) { return; } VacancyRegistrationAndEvaluationManager manager = new VacancyRegistrationAndEvaluationManager(vacancy); TransactionResponse response = manager.addNewVacancy(); if (response.isSuccessful()) { //update promotion table for the specified minute number Promotion promotion = new Promotion(); if (vacancy.VacancyOpenedFor == "2") { if (DropDPromMinNumb.SelectedValue != "-1") { string[] splitter = new string[] { PageConstants.GREATER_GREATER_THAN }; MinNumInfo = (DropDPromMinNumb.SelectedValue).Split(splitter, StringSplitOptions.RemoveEmptyEntries); applicantEID = MinNumInfo[0].Trim(); MinNumber = MinNumInfo[1].Trim(); promotion.EmpID = applicantEID; promotion.MinuteNo = MinNumber; PromotionManager promotionManager = new PromotionManager(promotion); TransactionResponse promotionResponse = promotionManager.updatePromotion(promotion, vacancy.VacancyNo); if (!promotionResponse.isSuccessful()) { clearLabelMsg(); msgPanel.Visible = true; ErroroDIV.Visible = true; lblErrorMsg.Text = promotionResponse.getMessage(); return; } } else { lblvacForPromotion.Visible = true; lblvacForPromotion.Text = "You can't register vacancy for promotion now. If you want to register vacancy for promotion please first register promotion."+ "Or if promotion is already registered please contact you manager to assign promotion to you."; } } clearLabelMsg(); msgPanel.Visible = true; SucessDIV.Visible = true; lblSuccessMessage.Text = response.getMessage(); btnRegister.Visible = false; btnCancel.Visible = true; PromotionAssigment promotionAssigment = new PromotionAssigment(); promotionAssigment.MinuteNo = MinNumber; if (isVacncyForPromotion) { //REMOVE THIS TASK FROM HR_MANGERS MAIL BOX NotificationManager notificationManager = new NotificationManager(promotion); TransactionResponse delteResponse = notificationManager.deleteNotificationForAssignedPromotionforSpecificHROfficer(Membership.GetUser()); if (!delteResponse.isSuccessful()) { //check if Warning Message is already logged, if so just add on it if (WarnDIV.Visible) { msgPanel.Visible = true; ErroroDIV.Visible = true; lblWarningMsg.Text = lblWarningMsg.Text + " and " + delteResponse.getMessage() + delteResponse.getErrorCode(); } else { msgPanel.Visible = true; ErroroDIV.Visible = true; lblWarningMsg.Text = delteResponse.getMessage() + delteResponse.getErrorCode(); } } } } else { msgPanel.Visible = true; ErroroDIV.Visible = true; lblErrorMsg.Text = response.getMessage() + response.getErrorCode(); } }
private void btnInsert_Click(object sender, EventArgs e) { bool create = db.Authorities.Single(x => x.AccountID == getAccount && x.NameOfAuthority == "Manage Promotion").Create; if (create == true) { string tmp = null; if (v.Required(txtPrice) || v.Required(txtContent) || v.RegularNumberExpression(txtPrice)) { if (v.Required(txtPrice)) { tmp += "Price can't empty \n"; } if (v.Required(txtContent)) { tmp += "Content can't empty \n"; } if (!v.Required(txtPrice) && v.RegularNumberExpression(txtPrice)) { tmp += "Price must be numbers \n"; } MessageBox.Show(tmp); } else { string id = txtID.Text; float price = float.Parse(txtPrice.Text.ToString()); DateTime start = dtDateStart.Value; DateTime end = dtpEndDate.Value; string content = txtContent.Text; string productID = (string)cboProduct.SelectedValue; Product product = db.Products.SingleOrDefault(x => x.ProductID == productID); var tam = txtImage.Text; string image = null; if (tam != string.Empty) { image = product.Name + Path.GetExtension(txtImage.Text); } else { image = ""; } Promotion promote = db.Promotions.FirstOrDefault(x => x.ProductID == productID); if (promote == null) { if (start >= DateTime.Today && end.Date >= start.Date) { if (Bus_Promotion.Insert(id, price, start, end, content, image, productID) == true) { MessageBox.Show("Create Sucessfully!"); GUI_Promote_Load(null, null); txtContent.Text = txtPrice.Text = txtImage.Text = ""; } else { MessageBox.Show("Create Unsuccessfully!"); } } else { MessageBox.Show("Start Date or End Date is not valid!"); } } else { MessageBox.Show("Promotion is existed"); } } } else { MessageBox.Show("Your account do not have the authority to create Promotion!"); } }
private void SetActiveCouponDetails(ApplicationDbContext dbContext, Dashboard model, Promotion activePromo) { model.ActivePromoName = activePromo.Title; model.ActivePromoDiscount = activePromo.Discount; model.ActivePromoEndDate = activePromo.DisplayEndDate; model.ActivePromoWarningMessage = GetActivePromoWarningMessage(activePromo.EndDate); model.ActivePromoId = activePromo.Id; model.ActivePromoType = Common.PromoType_Coupon; PromotionStats stats = (from x in dbContext.PromotionStats where x.Promotion.Id == activePromo.Id select x).FirstOrDefault(); model.ActivePromoClaimedEntries = stats != null ? stats.TimesClaimed : 0; model.ActivePromoViews = stats != null ? stats.TimesViewed : 0; }
//DB Get Promotion List public void DBGetPromotionList(string mobile) { try { string CMSPlayerID = ServerSide.DBGetCMSPlayerID(mobile); DataSet ds = new DataSet(); List <SqlParameter> spParams = new List <SqlParameter>(); spParams.Add(new SqlParameter("@CMSPlayerID", CMSPlayerID)); ds = DataAcess.ExecuteQuerySP("PEC.PROMOTIONS_GetPromotionList_ByCMSPlayerID", spParams); if (ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { Promotion newPromo = new Promotion(); newPromo.PromotionID = Convert.ToInt32(ds.Tables[0].Rows[i][""].ToString()); newPromo.PromoVersionID = Convert.ToInt32(ds.Tables[0].Rows[i][""].ToString()); newPromo.GameID = Convert.ToInt32(ds.Tables[0].Rows[i][""].ToString()); newPromo.PromotionName = ds.Tables[0].Rows[i][""].ToString(); newPromo.StartDate = Convert.ToDateTime(ds.Tables[0].Rows[i][""].ToString()); newPromo.EndDate = Convert.ToDateTime(ds.Tables[0].Rows[i][""].ToString()); newPromo.Enrolled = Convert.ToBoolean(ds.Tables[0].Rows[i][""].ToString()); newPromo.CouponsAvaliable = Convert.ToBoolean(ds.Tables[0].Rows[i][""].ToString()); newPromo.NextDrawingDate = Convert.ToDateTime(ds.Tables[0].Rows[i][""].ToString()); newPromo.CheckInAvaliable = Convert.ToBoolean(ds.Tables[0].Rows[i][""].ToString()); newPromo.CheckInStatusMessage = ds.Tables[0].Rows[i][""].ToString(); newPromo.FreeEntryAvaliable = Convert.ToBoolean(ds.Tables[0].Rows[i][""].ToString()); newPromo.RemoteEntryAvaliable = Convert.ToBoolean(ds.Tables[0].Rows[i][""].ToString()); newPromo.PointsToDate = Convert.ToInt32(ds.Tables[0].Rows[i][""].ToString()); newPromo.EntriesToDate = Convert.ToInt32(ds.Tables[0].Rows[i][""].ToString()); newPromo.PointsPerEntry = Convert.ToInt32(ds.Tables[0].Rows[i][""].ToString()); newPromo.TodaysPoint = Convert.ToInt32(ds.Tables[0].Rows[i][""].ToString()); newPromo.DailyEntryLImit = Convert.ToInt32(ds.Tables[0].Rows[i][""].ToString()); newPromo.ThresholdType = ds.Tables[0].Rows[i][""].ToString(); newPromo.ThresholdPoints = Convert.ToInt32(ds.Tables[0].Rows[i][""].ToString()); newPromo.PrizeName = ds.Tables[0].Rows[i][""].ToString(); newPromo.ThresholdReached = Convert.ToBoolean(ds.Tables[0].Rows[i][""].ToString()); newPromo.PrizeClaimed = Convert.ToBoolean(ds.Tables[0].Rows[i][""].ToString()); newPromo.GameAvaliable = Convert.ToBoolean(ds.Tables[0].Rows[i][""].ToString()); newPromo.RaffleAvaliable = Convert.ToBoolean(ds.Tables[0].Rows[i][""].ToString()); DataSet raffleDS = new DataSet(); List <SqlParameter> raffleParams = new List <SqlParameter>(); raffleParams.Add(new SqlParameter("@CMSPlayerID", CMSPlayerID)); raffleDS = DataAcess.ExecuteQuerySP("PEC.PROMOTIONS_GetPromotionRaffleTickets", raffleParams); if (raffleDS.Tables[0].Rows.Count > 0) { for (int j = 0; j < raffleDS.Tables[0].Rows.Count; j++) { RaffleTicketList newRaffleTicket = new RaffleTicketList(); newRaffleTicket.RaffleTicket = raffleDS.Tables[0].Rows[j][""].ToString(); newPromo.RaffleTickets.Add(newRaffleTicket); } } else { newPromo.RaffleTickets = null; } DataSet imageDS = new DataSet(); List <SqlParameter> imageParams = new List <SqlParameter>(); imageParams.Add(new SqlParameter("@CMSPlayerID", CMSPlayerID)); imageDS = DataAcess.ExecuteQuerySP("PEC.PROMOTIONS_GetPromotionImage", imageParams); if (imageDS.Tables[0].Rows.Count > 0) { MemoryStream ms = new MemoryStream((byte[])imageDS.Tables[0].Rows[0]["Image"]); byte[] bytes = ms.ToArray(); newPromo.PromotionImage = bytes; } else { newPromo.PromotionImage = null; } Promotions.Add(newPromo); } } else { RemoveData(); } } catch (SqlException ex) { string errorMessage = ex.Message; RemoveData(); } }
private DBOperationsUtil getDBOperationToUpdatePromotionStatus(IDictionary<string, object> parameters, Promotion promotion, string vacNo) { DBOperationsUtil dpOperation = null; //Pass Stored Procedure Name and parameter list. parameters.Add("@Emp_ID", promotion.EmpID); parameters.Add("@Minute_No", promotion.MinuteNo); parameters.Add("@vacancy_No", vacNo); parameters.Add("@forAssOrAnnounce", PromotionConstants.VACANCY_ANNOUNCED_FOR_PROMOTION); dpOperation = new DBOperationsUtil(DbAccessConstants.spUpdatePromotionStatus, parameters); return dpOperation; }
public XmlParam(string pFunc_id, string pAction_id, string pRequest, XmlCallBack pcallBack, Promotion pbook, string pPageID) { func_id = pFunc_id; action_id = pAction_id; request = pRequest; callBack = pcallBack; book = pbook; PageID = pPageID; }
private Promotion.Serial.QuaySoBook ConvertSerialToQuaysoBook(Promotion.Serial.SerialBook oSerialBook) { if (oSerialBook != null) { Promotion.Serial.QuaySoBook oBook = new Promotion.Serial.QuaySoBook(); oBook.ACCOUNT_NUMBER = oSerialBook.ACCOUNT_NUMBER; oBook.Book_Number = oSerialBook.Book_Number; oBook.BookType = oSerialBook.BookType; oBook.CMTND = oSerialBook.CMTND; oBook.CO_CODE = oSerialBook.CO_CODE; oBook.Currency = oSerialBook.Currency; oBook.Customer_Id = oSerialBook.Customer_Id; oBook.Customer_Name = oSerialBook.Customer_Name; oBook.MaturityDate = oSerialBook.MaturityDate; oBook.ValueDate = oSerialBook.ValueDate; oBook.Period = oSerialBook.Period; oBook.Sector = oSerialBook.Sector; oBook.Telephone = oSerialBook.Telephone; oBook.TERM = oSerialBook.TERM; oBook.TotalAmount = oSerialBook.TotalAmount; return oBook; } return null; }
public void Init(XmlParam param) { string xmlStr = param.xmlStr; Camera.main.GetComponent <MsgCenter_h>().TestText.text += "\nInit(XmlParam param)"; if (xmlStr != null && xmlStr != string.Empty && xmlStr != "") { Debug.Log("Init : " + param.xmlStr); List <Promotion> pros = new List <Promotion>(); XmlElement xmlRoot = GetXmlElement(param.xmlStr); BookCover cover; Promotion pro = null; maxCode = 0; int tmp = 0; XmlNode xmlNode = null; //Camera.main.GetComponent<MsgCenter_h>().TestText.text += param.xmlStr + "\n"; if (xmlRoot["brochure_list"] != null) { //Debug.Log("if"); foreach (XmlNode node in xmlRoot["brochure_list"].ChildNodes) { pro = null; cover = null; if (node.Attributes["brochure_code"] != null) { tmp = int.Parse(node.Attributes["brochure_code"].Value); } else { tmp = -1; } try { pro = new Promotion(node.Attributes["brochure_id"].Value, node.Attributes["brochure_templet_id"].Value); cover = new BookCover(node.Attributes["brochure_file_url"].Value); } catch (Exception exc) { Debug.Log(exc.Message); //throw; } finally { if (tmp > maxCode) { maxCode = tmp; } if (pro != null) { pros.Add(pro); if (cover != null) { pro.SelfCover = cover; } else { pro.SelfCover = new BookCover(); } } if (xmlNode == null) { xmlNode = node; } } } //Debug.Log("if_after"); } else { Camera.main.GetComponent <MsgCenter_h>().TestText.text += "\nerr : xmlRoot[\"brochure_list\"] == null !\n"; Debug.Log("err : xmlRoot[\"brochure_list\"] == null"); } Debug.Log("---------------->>>>>>>>>>>>>>>>>>>>" + maxCode); if (!string.IsNullOrEmpty(Bookrack.Instance.GetAttribute(xmlNode))) { _book = pros; Camera.main.GetComponent <MsgCenter_h>().TestText.text += "\nbook.Count = " + _book.Count.ToString() + "\n"; XmlParam xmlParam; //Camera.main.GetComponent<MsgCenter_h>().TestText.text += " _book.Count" + _book.Count;// //Debug.Log(_book.Count); for (int i = 0; i < _book.Count; i++) { xmlParam = new XmlParam("3D404767", "page", "brochure_id=\"" + _book[i].ID + "\" " + "layout_kind = \"1\"", AnalysisCoverLeyout, _book[i]); GetTarXml(xmlParam); } } } Camera.main.GetComponent <MsgCenter_h>().TestText.text += "\nOverInit(XmlParam param)"; }
public void EditPromotion(Promotion promotion) { promotion.PromotionName = TextProcessor.ToTitleCase(promotion.PromotionName); _repo.EditPromotion(promotion); }
public async Task <IActionResult> PostPromotion([FromBody] Promotion promotion) { await _promotionService.AddPromotion(promotion); return(CreatedAtAction("GetPromotion", new { id = promotion.promotionid }, promotion)); }
protected void btnConfirmComplete_Click(object sender, EventArgs e) { PromotionAssigment promotionAssigment = new PromotionAssigment(); string minNo = DropDownLMinuteNo.SelectedItem.Text; if (minNo != "-1") { lblminNo.Visible = false; string[] splitVacancyDetail = minNo.Split(new string[] { PageConstants.GREATER_GREATER_THAN }, StringSplitOptions.None); promotionAssigment.MinuteNo = splitVacancyDetail[1].Trim(); } else { resetAllControl(); lblminNo.Visible = true; return; } Promotion promotion = new Promotion(); promotion.MinuteNo = promotionAssigment.MinuteNo; PromotionManager promotionManager = new PromotionManager(promotion); TransactionResponse promotionResponse = promotionManager.updatePromotionStatus(promotion, PromotionConstants.PROMOTION_NOT_NEED_VACANCY_CANT_POSTED_BY_DISTRICT); if (!promotionResponse.isSuccessful()) { msgPanel.Visible = true; ErroroDIV.Visible = true; lblErrorMsg.Text = "Error occured while update promotion status. Please contact your system administrator."; return; } //REMOVE THIS TASK FROM HR_MANGERS MAIL BOX NotificationManager notificationManager = new NotificationManager(promotionAssigment); TransactionResponse delteResponse = notificationManager.deleteNotificationForAssignedPromotion(Membership.GetUser()); if (!delteResponse.isSuccessful()) { //check if Warning Message is already logged, if so just add on it if (WarnDIV.Visible) { msgPanel.Visible = true; lblWarningMsg.Text = lblWarningMsg.Text + " and " + delteResponse.getMessage() + delteResponse.getErrorCode(); } else { msgPanel.Visible = true; WarnDIV.Visible = true; lblWarningMsg.Text = delteResponse.getMessage() + delteResponse.getErrorCode(); } } else { PanelConfirmVacancyComplete.Visible = false; msgPanel.Visible = true; SucessDIV.Visible = true; lblSuccessMessage.Text = "Operation Success!"; btnAssignNew.Visible = false; btnAssignPromotion.Visible = true; populateAssignedPromotion(); AssignPromotionPanel.Visible = true; } }
public int Post([FromBody] Promotion value) { return(_promotionRepository.Create(value)); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="businessId">The AdWords Express business id.</param> public void Run(AdWordsUser user, long businessId) { // Get the ExpressBusinessService. ExpressBusinessService businessService = (ExpressBusinessService) user.GetService(AdWordsService.v201509.ExpressBusinessService); // Get the PromotionService PromotionService promotionService = (PromotionService) user.GetService(AdWordsService.v201509.PromotionService); // Get the business for the businessId. We will need its geo point to // create a Proximity criterion for the new Promotion. Selector businessSelector = new Selector() { fields = new string[] { ExpressBusiness.Fields.Id, ExpressBusiness.Fields.GeoPoint }, predicates = new Predicate[] { Predicate.Equals(ExpressBusiness.Fields.Id, businessId.ToString()) } }; ExpressBusinessPage businessPage = businessService.get(businessSelector); if (businessPage == null || businessPage.entries == null || businessPage.entries.Length == 0) { Console.WriteLine("No business was found."); return; } // Set the business ID to the service. promotionService.RequestHeader.expressBusinessId = businessId; // First promotion Promotion marsTourPromotion = new Promotion(); Money budget = new Money(); budget.microAmount = 1000000L; marsTourPromotion.name = "Mars Tour Promotion " + ExampleUtilities.GetShortRandomString(); marsTourPromotion.status = PromotionStatus.PAUSED; marsTourPromotion.destinationUrl = "http://www.example.com"; marsTourPromotion.budget = budget; marsTourPromotion.callTrackingEnabled = true; // Criteria // Criterion - Travel Agency product service ProductService productService = new ProductService(); productService.text = "Travel Agency"; // Criterion - English language // The ID can be found in the documentation: // https://developers.google.com/adwords/api/docs/appendix/languagecodes Language language = new Language(); language.id = 1000L; // Criterion - Within 15 miles Proximity proximity = new Proximity(); proximity.geoPoint = businessPage.entries[0].geoPoint; proximity.radiusDistanceUnits = ProximityDistanceUnits.MILES; proximity.radiusInUnits = 15; marsTourPromotion.criteria = new Criterion[] { productService, language, proximity }; // Creative Creative creative = new Creative(); creative.headline = "Standard Mars Trip"; creative.line1 = "Fly coach to Mars"; creative.line2 = "Free in-flight pretzels"; marsTourPromotion.creatives = new Creative[] { creative }; PromotionOperation operation = new PromotionOperation(); operation.@operator = Operator.ADD; operation.operand = marsTourPromotion; try { Promotion[] addedPromotions = promotionService.mutate( new PromotionOperation[] { operation }); Console.WriteLine("Added promotion ID {0} with name {1} to business ID {2}.", addedPromotions[0].id, addedPromotions[0].name, businessId); } catch (Exception e) { throw new System.ApplicationException("Failed to add promotions.", e); } }
public bool Put(int id, [FromBody] Promotion value) { return(_promotionRepository.Modify(id, value)); }
protected virtual SmartTargetPromotion CreatePromotionEntity(Promotion promotion, string viewName, string regionName, Localization localization) { // TODO TSI-901: Create SmartTargetExperiment (subclass of SmartTargetPromotion) if promotion is Experiment. return new SmartTargetPromotion { MvcData = new MvcData(viewName), XpmMetadata = new Dictionary<string, string> { {"PromotionID", promotion.PromotionId}, {"RegionID", regionName} }, Title = promotion.Title, Slogan = promotion.Slogan, // Create SmartTargetItem objects for visible ST Items. Items = promotion.Items.Where(item => item.Visible).Select(item => CreateSmartTargetItem(item, localization)).ToList() }; }
private bool SaveEditor(Promotion p, IPromotionAction a) { switch (a.TypeId.ToString().ToUpper()) { case PromotionActionBase.TypeIdProductPriceAdjustment: decimal adjustmentTemp = ((ProductPriceAdjustment)a).Amount; decimal parsedAdjustment = 0; if (decimal.TryParse(this.AmountField.Text, out parsedAdjustment)) { adjustmentTemp = parsedAdjustment; } ((ProductPriceAdjustment)a).Amount = adjustmentTemp; if (this.lstAdjustmentType.SelectedValue == "1") { ((ProductPriceAdjustment)a).AdjustmentType = AmountTypes.Percent; } else { ((ProductPriceAdjustment)a).AdjustmentType = AmountTypes.MonetaryAmount; } return(MyPage.MTApp.MarketingServices.Promotions.Update(p)); case PromotionActionBase.TypeIdOrderTotalAdjustment: decimal adjustmentTemp2 = ((OrderTotalAdjustment)a).Amount; decimal parsedAdjustment2 = 0; if (decimal.TryParse(this.OrderTotalAmountField.Text, out parsedAdjustment2)) { adjustmentTemp2 = parsedAdjustment2; } ((OrderTotalAdjustment)a).Amount = adjustmentTemp2; if (this.lstOrderTotalAdjustmentType.SelectedValue == "1") { ((OrderTotalAdjustment)a).AdjustmentType = AmountTypes.Percent; } else { ((OrderTotalAdjustment)a).AdjustmentType = AmountTypes.MonetaryAmount; } return(MyPage.MTApp.MarketingServices.Promotions.Update(p)); case PromotionActionBase.TypeIdOrderShippingAdjustment: decimal adjustmentOrderShipping = ((OrderShippingAdjustment)a).Amount; decimal parsedAdjustmentOrderShipping = 0; if (decimal.TryParse(this.OrderShippingAdjustmentAmount.Text, out parsedAdjustmentOrderShipping)) { adjustmentOrderShipping = parsedAdjustmentOrderShipping; } ((OrderShippingAdjustment)a).Amount = adjustmentOrderShipping; if (this.lstOrderShippingAdjustmentType.SelectedValue == "1") { ((OrderShippingAdjustment)a).AdjustmentType = AmountTypes.Percent; } else { ((OrderShippingAdjustment)a).AdjustmentType = AmountTypes.MonetaryAmount; } return(MyPage.MTApp.MarketingServices.Promotions.Update(p)); } return(false); }
partial void InsertPromotion(Promotion instance);
public void AddPromotion(Promotion promo) => promotions.Add(promo);
partial void DeletePromotion(Promotion instance);
public Promotion Delete(Promotion entity) { return(_promotion.Delete(entity)); }
public Promotion Update(Promotion entity, List <Expression <Func <Promotion, object> > > update = null, List <Expression <Func <Promotion, object> > > exclude = null) { return(_promotion.Update(entity, update, exclude)); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="businessId">The AdWords Express business id.</param> public void Run(AdWordsUser user, long businessId) { // Get the ExpressBusinessService. ExpressBusinessService businessService = (ExpressBusinessService) user.GetService(AdWordsService.v201406.ExpressBusinessService); // Get the PromotionService PromotionService promotionService = (PromotionService) user.GetService(AdWordsService.v201406.PromotionService); // Get the business for the businessId. We will need its geo point to // create a Proximity criterion for the new Promotion. Selector businessSelector = new Selector(); Predicate predicate = new Predicate(); predicate.field = "Id"; predicate.@operator = PredicateOperator.EQUALS; predicate.values = new string[] { businessId.ToString() }; businessSelector.predicates = new Predicate[] { predicate }; businessSelector.fields = new string[] { "Id", "GeoPoint" }; ExpressBusinessPage businessPage = businessService.get(businessSelector); if (businessPage == null || businessPage.entries == null || businessPage.entries.Length == 0) { Console.WriteLine("No business was found."); return; } // Set the business ID to the service. promotionService.RequestHeader.expressBusinessId = businessId; // First promotion Promotion marsTourPromotion = new Promotion(); Money budget = new Money(); budget.microAmount = 1000000L; marsTourPromotion.name = "Mars Tour Promotion " + ExampleUtilities.GetShortRandomString(); marsTourPromotion.status = PromotionStatus.PAUSED; marsTourPromotion.destinationUrl = "http://www.example.com"; marsTourPromotion.budget = budget; marsTourPromotion.callTrackingEnabled = true; // Criteria // Criterion - Travel Agency product service ProductService productService = new ProductService(); productService.text = "Travel Agency"; // Criterion - English language // The ID can be found in the documentation: // https://developers.google.com/adwords/api/docs/appendix/languagecodes Language language = new Language(); language.id = 1000L; // Criterion - Within 15 miles Proximity proximity = new Proximity(); proximity.geoPoint = businessPage.entries[0].geoPoint; proximity.radiusDistanceUnits = ProximityDistanceUnits.MILES; proximity.radiusInUnits = 15; marsTourPromotion.criteria = new Criterion[] { productService, language, proximity }; // Creative Creative creative = new Creative(); creative.headline = "Standard Mars Trip"; creative.line1 = "Fly coach to Mars"; creative.line2 = "Free in-flight pretzels"; marsTourPromotion.creatives = new Creative[] { creative }; PromotionOperation operation = new PromotionOperation(); operation.@operator = Operator.ADD; operation.operand = marsTourPromotion; try { Promotion[] addedPromotions = promotionService.mutate( new PromotionOperation[] { operation }); Console.WriteLine("Added promotion ID {0} with name {1} to business ID {2}.", addedPromotions[0].id, addedPromotions[0].name, businessId); } catch (Exception ex) { throw new System.ApplicationException("Failed to add promotions.", ex); } }
public IResult Open(Promotion promotion) { return(new DialogResult(new DocModel <Promotion>(promotion.Id), resizable: true)); }
public static void Init() { //Database stuff ApplicationDbContext db = new ApplicationDbContext(); //Xml stuff XmlDocument xmlDoc = new XmlDocument(); XmlNodeList elemList; //check if tables are empty using (db) { if (!db.Categories.Any()) { // The table is empty xmlDoc.Load("https://supermaco.starwave.nl/api/categories"); elemList = xmlDoc.GetElementsByTagName("Categories"); foreach (XmlNode Category in elemList[0].ChildNodes) { Category c = new Category(); c.Name = Category.ChildNodes[0].InnerXml; c.ParentId = null; c.Type = "Category"; db.Categories.Add(c); foreach (XmlNode SubCategory in Category.SelectNodes("Subcategory")) { Category sc = new Category(); sc.Name = SubCategory.ChildNodes[0].InnerXml; sc.Parent = c; sc.Type = "SubCategory"; db.Categories.Add(sc); foreach (XmlNode SubSubCategory in SubCategory.SelectNodes("Subsubcategory")) { Category ssc = new Category(); ssc.Name = SubSubCategory.ChildNodes[0].InnerXml; ssc.Parent = sc; ssc.Type = "SubSubCategory"; db.Categories.Add(ssc); } } } db.SaveChanges(); } if (!db.Deliveryslots.Any()) { // THe table is empty xmlDoc.Load("https://supermaco.starwave.nl/api/deliveryslots"); elemList = xmlDoc.GetElementsByTagName("Deliveryslots"); foreach (XmlNode DeliverySlot in elemList[0].ChildNodes) { Deliveryslots Deliveryslot = new Deliveryslots(); Deliveryslot.DateSlot = DateTime.ParseExact(DeliverySlot.ChildNodes[0].InnerXml, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); foreach (XmlNode Timestamp in DeliverySlot.SelectNodes("Timeslots/Timeslot")) { Deliveryslots Slot2 = new Deliveryslots(); Slot2.DateSlot = Deliveryslot.DateSlot; Slot2.StartTime = Timestamp.SelectSingleNode("StartTime").InnerXml; Slot2.EndTime = Timestamp.SelectSingleNode("EndTime").InnerXml; Slot2.Price = decimal.Parse(Timestamp.SelectSingleNode("Price").InnerXml) / 100; db.Deliveryslots.Add(Slot2); } } db.SaveChanges(); } if (!db.Products.Any()) { // The table is empty xmlDoc.Load("https://supermaco.starwave.nl/api/products"); elemList = xmlDoc.GetElementsByTagName("Products"); foreach (XmlNode CurrProduct in elemList[0].ChildNodes) { Product product = new Product(); product.ApiId = Int32.Parse(CurrProduct.Attributes["Id"].InnerXml); product.EAN = long.Parse(CurrProduct.SelectSingleNode("EAN").InnerXml); product.Title = CurrProduct.SelectSingleNode("Title").InnerXml.Trim(); product.Brand = CurrProduct.SelectSingleNode("Brand").InnerXml; product.ShortDescription = CurrProduct.SelectSingleNode("Shortdescription").InnerXml; product.FullDescription = CurrProduct.SelectSingleNode("Fulldescription").InnerXml; product.Image = CurrProduct.SelectSingleNode("Image").InnerXml; product.Weight = CurrProduct.SelectSingleNode("Weight").InnerXml; product.Price = Decimal.Parse(CurrProduct.SelectSingleNode("Price").InnerXml) / 100; var SSC = CurrProduct.SelectSingleNode("Subsubcategory").InnerXml; var query = (from c in db.Categories where c.Name == SSC select new { c.Id }).FirstOrDefault(); product.CategoryId = query.Id; db.Products.Add(product); } db.SaveChanges(); } if (!db.Promotions.Any()) { // The table is empty xmlDoc.Load("https://supermaco.starwave.nl/api/promotions"); elemList = xmlDoc.GetElementsByTagName("Promotion"); var Title = elemList[0].SelectSingleNode("Title").InnerXml; foreach (XmlNode CurrDisc in xmlDoc.GetElementsByTagName("Discount")) { Promotion promo = new Promotion(); promo.Title = Title; promo.ProductEAN = long.Parse(CurrDisc.SelectSingleNode("EAN").InnerXml); promo.DiscountPrice = decimal.Parse(CurrDisc.SelectSingleNode("DiscountPrice").InnerXml) / 100; var c**t = CurrDisc.SelectSingleNode("ValidUntil").InnerXml; promo.ValidUntil = DateTime.ParseExact(CurrDisc.SelectSingleNode("ValidUntil").InnerXml, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); db.Promotions.Add(promo); } db.SaveChanges(); } } }
public abstract void Update(Promotion promotion, ShoppingMall shoppingMall);
public static String CreateJSONPromotion(Promotion promotion, String userID) { StringWriter stringWriter = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(stringWriter); writer.WriteStartObject(); writer.WritePropertyName("id"); writer.WriteValue(userID + promotion.Name); writer.WritePropertyName("ownerId"); writer.WriteValue(userID); writer.WritePropertyName("name"); writer.WriteValue(promotion.Name); writer.WritePropertyName("style"); writer.WriteValue(promotion.Type); writer.WritePropertyName("region"); writer.WriteValue(promotion.Region); writer.WritePropertyName("history"); writer.WriteStartArray(); //Ensure that at least one item is written var historyItems = promotion.History.Split('~'); if (historyItems.Length > 0) { foreach (String item in promotion.History.Split('~')) { writer.WriteValue(item); } } else { writer.WriteValue(String.Empty); } writer.WriteEndArray(); writer.WritePropertyName("details"); writer.WriteStartArray(); //Ensure that at least one item is written if (promotion.MatchDetails.Count > 0) { foreach (String detail in promotion.MatchDetails) { writer.WriteValue(detail); } } else { writer.WriteValue(String.Empty); } writer.WriteEndArray(); writer.WritePropertyName("matchCount"); writer.WriteValue(promotion.MatchCount); writer.WritePropertyName("averageRating"); writer.WriteValue(promotion.AverageRating); writer.WritePropertyName("rosterCount"); writer.WriteValue(promotion.EmployeeList.Count); writer.WriteEndObject(); return(stringWriter.ToString()); }
public TransactionResponse updatePromotionStatus(Promotion promotion, string promoStatus) { TransactionResponse response = new TransactionResponse(); try { //Add List of Arguments for new employee IDictionary<string, object> parameters = new Dictionary<string, object>(); DBOperationsUtil dpOperation = getDBOperationToUpdatePromotionStatus4Assignment(parameters, promotion, promoStatus); dpOperation.updateRecord(); response.setMessageType(TransactionResponse.SeverityLevel.SUCESS); response.setSuccess(true); } catch (SqlException ex) { //Other SqlException is catched response.setMessageType(TransactionResponse.SeverityLevel.ERROR); response.setMessage(DBOperationErrorConstants.M_UNKNOWN_ERROR_UPDATE_VACANCY); response.setErrorCode(DBOperationErrorConstants.E_UNKNOWN_ERROR_AT_DB_OOPERATION); response.setSuccess(false); } //CATCH ANY OTHER EXCEPTION, dont let user see any kind of unexpected error catch (Exception ex) { //Write this exception to file for investigation of the issue later. logException(ex); LoggerManager.upDateWithGenericErrorMessage(response); } return response; }
public void OrderCalculator_TestBugWithFreeShipping_12738() { //InitBasicStubs(); var app = CreateHccAppInMemory(); // Create taxes var tax1 = new TaxSchedule { Name = "Tax1" }; var tax2 = new TaxSchedule { Name = "Tax2" }; app.OrderServices.TaxSchedules.Create(tax1); app.OrderServices.TaxSchedules.Create(tax2); var taxrate1 = new Tax { Rate = 10, ShippingRate = 5, CountryIsoAlpha3 = "USA", ApplyToShipping = true, TaxScheduleId = tax1.Id }; var taxrate2 = new Tax { Rate = 10, ShippingRate = 10, CountryIsoAlpha3 = "USA", ApplyToShipping = true, TaxScheduleId = tax2.Id }; app.OrderServices.Taxes.Create(taxrate1); app.OrderServices.Taxes.Create(taxrate2); // Prepare products var catA = new Category { Name = "Category A" }; var catB = new Category { Name = "Category B" }; var prod1 = new Product { ProductName = "Product 1", SitePrice = 100, TaxSchedule = tax1.Id }; var prod2 = new Product { ProductName = "Product 2", SitePrice = 50, TaxSchedule = tax2.Id }; app.CatalogServices.Categories.Create(catA); app.CatalogServices.Categories.Create(catB); app.CatalogServices.Products.Create(prod1); app.CatalogServices.Products.Create(prod2); app.CatalogServices.CategoriesXProducts.AddProductToCategory(prod1.Bvin, catA.Bvin); app.CatalogServices.CategoriesXProducts.AddProductToCategory(prod2.Bvin, catB.Bvin); // Prepare promotion var promFreeShipping = new Promotion { Mode = PromotionType.OfferForLineItems, Name = "FREE SHIPPING", IsEnabled = true }; promFreeShipping.AddQualification(new LineItemCategory(catA.Bvin)); promFreeShipping.AddAction(new LineItemFreeShipping()); app.MarketingServices.Promotions.Create(promFreeShipping); var o = new Order { StoreId = app.CurrentStore.Id }; var li1 = prod1.ConvertToLineItem(app, 1); var li2 = prod2.ConvertToLineItem(app, 1); o.Items.Add(li1); o.Items.Add(li2); // Create Shipping Method var sm = new ShippingMethod(); var flatRatePerOrder = new FlatRatePerOrder(); flatRatePerOrder.Settings.Amount = 2m; sm.Bvin = Guid.NewGuid().ToString(); sm.ShippingProviderId = flatRatePerOrder.Id; sm.Settings = flatRatePerOrder.Settings; sm.Adjustment = 0m; sm.Name = "Flat Rate Per Item"; sm.ZoneId = -100; // US All Zone app.OrderServices.ShippingMethods.Create(sm); app.OrderServices.EnsureDefaultZones(app.CurrentStore.Id); o.ShippingAddress.City = "Richmond"; o.ShippingAddress.CountryBvin = Country.UnitedStatesCountryBvin; o.ShippingAddress.Line1 = "124 Anywhere St."; o.ShippingAddress.PostalCode = "23233"; o.ShippingAddress.RegionBvin = "VA"; o.ShippingMethodId = sm.Bvin; o.ShippingProviderId = sm.ShippingProviderId; app.CalculateOrder(o); Assert.IsTrue(li1.IsMarkedForFreeShipping); Assert.IsFalse(li2.IsMarkedForFreeShipping); Assert.AreEqual(1.33m, li1.ShippingPortion); Assert.AreEqual(0.67m, li2.ShippingPortion); Assert.AreEqual(10m, li1.TaxPortion); Assert.AreEqual(5m, li2.TaxPortion); Assert.AreEqual(2m, o.TotalShippingBeforeDiscounts); Assert.AreEqual(2m, o.TotalShippingAfterDiscounts); Assert.AreEqual(15m, o.ItemsTax); Assert.AreEqual(0.14m, o.ShippingTax); Assert.AreEqual(15.14m, o.TotalTax); }
public PromotionManager(Promotion promotion) { this.promotion = promotion; }
private static void ApprovePromotion(CommercePipelineExecutionContext context, Promotion promotion) { promotion.SetComponent(new ApprovalComponent(context.GetPolicy <ApprovalStatusPolicy>().Approved)); }
protected virtual SmartTargetPromotion CreatePromotionEntity(Promotion promotion, string viewName, string regionName, Localization localization, ExperimentDimensions experimentDimensions) { // In ST 2014 SP1 the ResultSet.FilterPromotions API represents Experiments as type Promotion, so we're not testing on type Experiment here. SmartTargetPromotion result = (experimentDimensions != null) ? new SmartTargetExperiment(experimentDimensions) : new SmartTargetPromotion(); result.MvcData = new MvcData(viewName); result.XpmMetadata = new Dictionary<string, object> { {"PromotionID", promotion.PromotionId}, {"RegionID", regionName} }; result.Title = promotion.Title; result.Slogan = promotion.Slogan; // Create SmartTargetItem objects for visible ST Items. result.Items = promotion.Items.Where(item => item.Visible).Select(item => CreateSmartTargetItem(item, localization)).ToList(); return result; }
public override async Task <CreateCouponsArgument> Run( CreateCouponsArgument arg, CommercePipelineExecutionContext context) { await this._getManagedListCommand.PerformTransaction(context.CommerceContext, async() => { var policy = context.CommerceContext.GetPolicy <LoyaltyPointsPolicy>(); LoyaltyPointsEntity loyaltyPointsEntity = await _findEntityCommand.Process(context.CommerceContext, typeof(LoyaltyPointsEntity), Constants.EntityId, shouldCreate: true) as LoyaltyPointsEntity; if (loyaltyPointsEntity == null) { await context.AbortWithError("Unable to access or create LoyaltyPointsEntity {0}", "LoyaltyPointsEntityNotReturned", Constants.EntityId); return; } // Prevent simultaneous updates, in case multiple minion instances. Since these might be on scaled servers, mutex lock uses database field. // Lock is read before count is checked, so that when first process finishes and releases row, counts will be replenished. // Notes: // 1. If this pipeline aborts, the lock should be rolled back. // 2. Assuming transactions are enabled, the second process should never see IsLocked=true, as the read won't return until the lock is released. However, // this syntax should work on a non-transactional environment, and makes the intent of the code clearer. if (loyaltyPointsEntity.IsLocked) { await context.AbortWithError("{0} is locked. If this condition persists, unset this value through the database.", "EntityLocked", Constants.EntityId); return; } var list = await EnsureList(context, Constants.AvailableCouponsList); if (list == null) { await context.AbortWithError("Unable to create list {0}", "UnableToCreateList", Constants.AvailableCouponsList); return; } long count = await _getListCountCommand.Process(context.CommerceContext, Constants.AvailableCouponsList); context.Logger.LogDebug($"{this.Name}: List {Constants.AvailableCouponsList} has {count} items."); if (count <= policy.ReprovisionTriggerCount) { loyaltyPointsEntity.IsLocked = true; await _persistEntityCommand.Process(context.CommerceContext, loyaltyPointsEntity); context.Logger.LogDebug($"{this.Name}: List {Constants.AvailableCouponsList} is at or under reprovision count of {policy.ReprovisionTriggerCount}."); loyaltyPointsEntity.SequenceNumber++; string suffix = loyaltyPointsEntity.SequenceNumber.ToString(); string promotionName = string.Format(Constants.GeneratedPromotion, suffix); Promotion promotion = await GeneratePromotion(context, promotionName); if (promotion == null) { await context.AbortWithError("Unable to generate promotion {0}.", "PromotionNotFound", promotionName); return; } await AddCoupons(context, promotion, suffix); if (context.IsNullOrHasErrors()) { return; } await AllocateCoupons(context, promotion, suffix); if (context.IsNullOrHasErrors()) { return; } ApprovePromotion(context, promotion); await CopyCouponsToList(context, loyaltyPointsEntity, list); if (context.IsNullOrHasErrors()) { return; } loyaltyPointsEntity.IsLocked = false; await _persistEntityCommand.Process(context.CommerceContext, list); await _persistEntityCommand.Process(context.CommerceContext, promotion); await _persistEntityCommand.Process(context.CommerceContext, loyaltyPointsEntity); } }); return(arg); }
private long SaveNewPromotion(PromotionUi model) { var file = SaveFile(model.File); var regionMask = model.RegionList.Select(x => (ulong)Convert.ToInt64(x)).Aggregate((y, z) => y | z); if (file == null) { if (model.PromotionFileId != null) { file = DB2.MediaFiles.Find(model.PromotionFileId.Value); } } var promotion = new Promotion(CurrentUser) { Name = model.Name, Annotation = model.Annotation, Begin = Convert.ToDateTime(model.Begin), End = Convert.ToDateTime(model.End), Author = DB2.Users.Find(CurrentUser.Id), MediaFile = file, RegionMask = (long)regionMask, }; DB2.Promotions.Add(promotion); DB2.SaveChanges(); foreach (var item in model.DrugList) { var promotionToDrug = new PromotionToDrug() { DrugId = Convert.ToInt64(item), PromotionId = promotion.Id }; DB2.PromotionToDrugs.Add(promotionToDrug); } if (model.SuppierRegions.Contains("0")) { model.SuppierRegions = h.GetSupplierList(model.SuppierRegions.ToList().Select(x => (ulong)Convert.ToInt64(x)).ToList()).ToList().Select(x => x.Value).ToList(); promotion.AllSuppliers = true; } else { promotion.AllSuppliers = false; } foreach (var item in model.SuppierRegions) { var X = new PromotionsToSupplier() { PromotionId = promotion.Id, SupplierId = Convert.ToInt64(item) }; DB2.PromotionsToSuppliers.Add(X); } DB2.PromotionHistory.Add(new PromotionSnapshot(CurrentUser, promotion, DB, DB2) { SnapshotName = "Добавление промоакции", }); DB2.SaveChanges(); Mails.PromotionNotification(MailType.CreatePromotion, promotion); return(promotion.Id); }
public string GetEditorVirtualPath(Promotion promotion) { return "~/Areas/" + Strings.AreaName + "/Views/Config.cshtml"; }
/// <summary> /// Coupons must be in allocated to be usable by customers. /// </summary> private async Task AllocateCoupons(CommercePipelineExecutionContext context, Promotion promotion, string suffix) { var policy = context.GetPolicy <LoyaltyPointsPolicy>(); string privateCouponGroupId = $"{CommerceEntity.IdPrefix<PrivateCouponGroup>()}{policy.CouponPrefix}-{suffix}"; var privateCouponGroup = await _findEntityCommand.Process(context.CommerceContext, typeof(PrivateCouponGroup), privateCouponGroupId) as PrivateCouponGroup; if (privateCouponGroup == null) { await context.AbortWithError("Unable to find PrivateCouponGroup { 0}.", "PrivateCouponGroupNotFound", privateCouponGroupId); return; } await _newCouponAllocationCommand.Process(context.CommerceContext, promotion, privateCouponGroup, policy.CouponBlockSize); }
public JsonResult Get(int id) { Promotion result = ApiHelper <Promotion> .HttpGetAsync($"{Helper.ApiUrl}api/promotions/getbyid/{id}"); return(Json(new { result })); }