Beispiel #1
0
 /// <summary> Retrieves the related entity of type 'CampaignEntity', using a relation of type 'n:1'</summary>
 /// <param name="forceFetch">if true, it will discard any changes currently in the currently loaded related entity and will refetch the entity from the persistent storage</param>
 /// <returns>A fetched entity of type 'CampaignEntity' which is related to this entity.</returns>
 public virtual CampaignEntity GetSingleCampaign(bool forceFetch)
 {
     if ((!_alreadyFetchedCampaign || forceFetch || _alwaysFetchCampaign) && !this.IsSerializing && !this.IsDeserializing && !this.InDesignMode)
     {
         bool           performLazyLoading = this.CheckIfLazyLoadingShouldOccur(Relations.CampaignEntityUsingCampaignId) && (EntityBase.EnableLazyLoading || forceFetch);
         CampaignEntity newEntity          = new CampaignEntity();
         bool           fetchResult        = false;
         if (performLazyLoading)
         {
             AddToTransactionIfNecessary(newEntity);
             fetchResult = newEntity.FetchUsingPK(this.CampaignId);
         }
         if (fetchResult)
         {
             newEntity = (CampaignEntity)GetFromActiveContext(newEntity);
         }
         else
         {
             if (!_campaignReturnsNewIfNotFound)
             {
                 RemoveFromTransactionIfNecessary(newEntity);
                 newEntity = null;
             }
         }
         this.Campaign           = newEntity;
         _alreadyFetchedCampaign = fetchResult;
     }
     return(_campaign);
 }
        public async Task <ActionResult <CampaignEntityDTO> > Post(CampaignEntityDTO entity)
        {
            var faction = (await _context.Locations.Include(p => p.Faction).FirstOrDefaultAsync(p => p.Id == entity.LocationId)).Faction;
            var _entity = new CampaignEntity {
                Campaign    = await _context.Campaigns.FirstOrDefaultAsync(p => p.Id == entity.CampaignId),
                Entity      = await _context.Entities.FirstOrDefaultAsync(p => p.Id == entity.EntityId),
                Faction     = faction,
                Location    = await _context.Locations.FirstOrDefaultAsync(p => p.Id == entity.LocationId),
                AvailableAt = (await _context.Campaigns.FirstOrDefaultAsync(p => p.Id == entity.CampaignId)).StartDate,
                Count       = entity.Count,
                Status      = entity.Status
            };

            var unitCost = (await _context.CampaignEntityCosts
                            .Include(p => p.Campaign)
                            .Include(p => p.Entity)
                            .FirstOrDefaultAsync(p => p.Entity.Id == entity.EntityId && p.Campaign.Id == entity.CampaignId))?.Cost ??
                           (await _context.Entities.FirstOrDefaultAsync(p => p.Id == entity.EntityId)).DefaultCost;

            if (unitCost * entity.Count > faction.Budget)
            {
                return(BadRequest());
            }

            faction.Budget -= unitCost * entity.Count;

            await _context.CampaignEntities.AddAsync(_entity);

            _context.Factions.Update(faction);
            await _context.SaveChangesAsync();

            return(CreatedAtAction(nameof(Get), new { id = _entity.Id }, entity));
        }
        public OrderEntity Create(ProductEntity product, int quantity, CampaignEntity campaign, int currentTime)
        {
            if (product.Stock < quantity)
            {
                throw new InsufficientStockException();
            }

            OrderEntity order;

            if (campaign != null)
            {
                var sellingPrice = _productPriceService.CalculateDiscountedPrice(campaign, product.Price, currentTime);

                order = new OrderEntity(product.ProductCode, quantity, sellingPrice, campaign.Id);

                campaign.NotifyOrderCreation(quantity, order.Price);
            }
            else
            {
                order = new OrderEntity(product.ProductCode, quantity, product.Price);
            }

            product.DecreaseStock(quantity);

            return(order);
        }
        public async Task AddReferralStakeReleasedAsync(ReferralStakeDto referralStake)
        {
            using (var context = _contextFactory.CreateDataContext())
            {
                var historyEntity = TransactionHistoryEntity.CreateForReferralStakeTokensRelease(referralStake);
                var releasedReferralStakeEntity = ReleasedReferralStakeEntity.Create(referralStake);

                var campaign = await context.Campaigns.FindAsync(referralStake.CampaignId);

                if (campaign != null && campaign.CampaignName != referralStake.CampaignName)
                {
                    campaign.CampaignName = referralStake.CampaignName;
                }

                if (campaign == null)
                {
                    campaign = CampaignEntity.Create(referralStake.CampaignId, referralStake.CampaignName);
                }

                releasedReferralStakeEntity.Campaign = campaign;

                context.ReleasedReferralStakes.Add(releasedReferralStakeEntity);
                context.TransactionHistories.Add(historyEntity);

                await context.SaveChangesAsync();
            }
        }
Beispiel #5
0
        public async Task AddAsync(BonusCashInDto bonusCashIn)
        {
            using (var context = _contextFactory.CreateDataContext())
            {
                var historyEntity = TransactionHistoryEntity.Create(bonusCashIn);
                var bonusEntity   = BonusCashInEntity.Create(bonusCashIn);

                var campaign = await context.Campaigns.FindAsync(bonusCashIn.CampaignId);

                if (campaign != null && campaign.CampaignName != bonusCashIn.CampaignName)
                {
                    campaign.CampaignName = bonusCashIn.CampaignName;
                }

                if (campaign == null)
                {
                    campaign = CampaignEntity.Create(bonusCashIn.CampaignId, bonusCashIn.CampaignName);
                }

                bonusEntity.Campaign = campaign;

                context.BonusCashIns.Add(bonusEntity);
                context.TransactionHistories.Add(historyEntity);

                await context.SaveChangesAsync();
            }
        }
Beispiel #6
0
        private void FillSaveParameters(CampaignEntity campaign, IDbCommand sqlCommand)
        {
            IDbDataParameter parameter;

            parameter = dataAccess.GetNewDataParameter("@description", DbType.String);

            parameter.Value = campaign.Description;
            if (String.IsNullOrEmpty(campaign.Description))
            {
                parameter.Value = DBNull.Value;
            }

            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@name", DbType.String);

            parameter.Value = campaign.Name;
            if (String.IsNullOrEmpty(campaign.Name))
            {
                parameter.Value = DBNull.Value;
            }

            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@startDate", DbType.DateTime);

            parameter.Value = campaign.StartDate;
            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@stopDate", DbType.DateTime);

            parameter.Value = campaign.StopDate;
            sqlCommand.Parameters.Add(parameter);
            parameter = dataAccess.GetNewDataParameter("@idUser", DbType.Int32);

            parameter.Value = campaign.IdUser;
            sqlCommand.Parameters.Add(parameter);
        }
Beispiel #7
0
        /// <summary>
        /// Function to delete a CampaignEntity from database.
        /// </summary>
        /// <param name="campaignEntity">CampaignEntity to delete</param>
        /// <param name="session">User's session identifier.</param>
        /// <returns>null if the CampaignEntity was deleted successfully, the same CampaignEntity otherwise</returns>
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="campaignEntity"/> is null.
        /// </exception>
        /// <exception cref="UtnEmallBusinessLogicException">
        /// If an UtnEmallDataAccessException occurs in DataModel.
        /// </exception>
        public CampaignEntity Delete(CampaignEntity campaignEntity, string session)
        {
            bool permited = ValidationService.Instance.ValidatePermission(session, "delete", "Campaign");

            if (!permited)
            {
                ExceptionDetail detail = new ExceptionDetail(new UtnEmall.Server.BusinessLogic.UtnEmallPermissionException("The user hasn't permissions to delete an entity"));
                throw new FaultException <ExceptionDetail>(detail);
            }

            if (campaignEntity == null)
            {
                throw new ArgumentException("The argument can not be null or be empty");
            }
            try
            {
                // Delete campaignEntity using data access object
                campaignDataAccess.Delete(campaignEntity);
                return(null);
            }
            catch (UtnEmallDataAccessException utnEmallDataAccessException)
            {
                throw new UtnEmall.Server.BusinessLogic.UtnEmallBusinessLogicException(utnEmallDataAccessException.Message, utnEmallDataAccessException);
            }
        }
Beispiel #8
0
        /// <summary>
        /// Function to save a CampaignEntity to the database.
        /// </summary>
        /// <param name="campaignEntity">CampaignEntity to save</param>
        /// <param name="session">User's session identifier.</param>
        /// <returns>null if the CampaignEntity was saved successfully, the same CampaignEntity otherwise</returns>
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="campaignEntity"/> is null.
        /// </exception>
        /// <exception cref="UtnEmallBusinessLogicException">
        /// If an UtnEmallDataAccessException occurs in DataModel.
        /// </exception>
        public CampaignEntity Save(CampaignEntity campaignEntity, string session)
        {
            bool permited = ValidationService.Instance.ValidatePermission(session, "save", "Campaign");

            if (!permited)
            {
                ExceptionDetail detail = new ExceptionDetail(new UtnEmall.Server.BusinessLogic.UtnEmallPermissionException("The user hasn't permissions to save an entity"));
                throw new FaultException <ExceptionDetail>(detail);
            }

            if (!Validate(campaignEntity))
            {
                return(campaignEntity);
            }
            try
            {
                // Save campaignEntity using data access object
                campaignDataAccess.Save(campaignEntity);
                return(null);
            }
            catch (UtnEmallDataAccessException utnEmallDataAccessException)
            {
                throw new UtnEmall.Server.BusinessLogic.UtnEmallBusinessLogicException(utnEmallDataAccessException.Message, utnEmallDataAccessException);
            }
        }
Beispiel #9
0
        public async Task <CreateCampaignResponse> Handle(CreateCampaignCommand request, CancellationToken cancellationToken)
        {
            var productIsExists = await _productRepository.AnyAsync(x => x.ProductCode == request.ProductCode);

            if (!productIsExists)
            {
                throw new ProductNotFoundException();
            }

            var productCampaigns = await _campaignRepository.FindAsync(x => x.ProductCode == request.ProductCode);

            var isAnyActiveCampaign = productCampaigns.Any(x => x.IsActive(_timeService.CurrentTime));

            if (isAnyActiveCampaign)
            {
                throw new AlreadyActiveCampaignForProductException(request.ProductCode);
            }

            var isCampaignExists = await _campaignRepository.AnyAsync((x => x.Name == request.CampaignName));

            if (isCampaignExists)
            {
                throw new CampaignAlreadyExistsException(request.CampaignName);
            }

            var campaign = new CampaignEntity(request.CampaignName, request.ProductCode, request.Duration, request.PriceManipulationLimit, request.TargetSalesCount, _timeService.CurrentTime);

            var result = await _campaignRepository.AddAsync(campaign);

            return(new CreateCampaignResponse(result));
        }
Beispiel #10
0
 /// <summary>
 /// Constructor de clase
 /// </summary>
 public CampaignEditor()
 {
     this.InitializeComponent();
     this.StartDatePicker.Fill(2000, DateTime.Today.Year + 5);
     this.StopDatePicker.Fill(2000, DateTime.Today.Year + 6);
     campaign = new CampaignEntity();
 }
        internal PointTrackResult ShareCampaignToAppMessage(CampaignEntity campaign, Guid?memberId, string openId)
        {
            PointTrackResult result = new PointTrackResult();

            if (campaign == null || campaign.Status != EnumCampaignStatus.Ongoing)
            {
                return(result);
            }

            if (campaign.ShareAppMessagePoint <= 0)
            {
                return(result);
            }

            #region 判断有没有分享过

            ShareLogEntity log = ShareManager.GetShareLog(campaign.Id, openId);
            if (log == null)
            {
                log                 = new ShareLogEntity();
                log.Member          = memberId;
                log.OpenId          = openId;
                log.PageId          = campaign.Id;
                log.ShareAppMessage = true;
                ShareManager.Create(log);
            }
            else
            {
                if (log.ShareAppMessage && log.Member.HasValue)
                {
                    return(result);
                }

                if (log.ShareAppMessage && memberId.HasValue == false)
                {
                    return(result);
                }

                log.Member          = memberId;
                log.ShareAppMessage = true;
                ShareManager.Update(log);
            }

            #endregion

            if (memberId.HasValue)
            {
                PointTrackArgs args = new PointTrackArgs();
                args.DomainId = campaign.Domain;
                args.MemberId = memberId.Value;
                args.Quantity = campaign.ShareAppMessagePoint;
                args.Type     = MemberPointTrackType.Campaign;
                args.TagName  = campaign.Name;
                args.TagId    = campaign.Id;
                result        = MemberManager.PointTrack(args);
            }

            return(result);
        }
Beispiel #12
0
        public void When_Campaign_Create_IsActive_Return_True()
        {
            var campaign = new CampaignEntity("C1", "P1", 10, 10, 10, 0);

            var isActive = campaign.IsActive(4);

            Assert.True(isActive);
        }
Beispiel #13
0
        /// <summary>Creates a new, empty CampaignEntity object.</summary>
        /// <returns>A new, empty CampaignEntity object.</returns>
        public override IEntity Create()
        {
            IEntity toReturn = new CampaignEntity();

            // __LLBLGENPRO_USER_CODE_REGION_START CreateNewCampaign
            // __LLBLGENPRO_USER_CODE_REGION_END
            return(toReturn);
        }
Beispiel #14
0
        public void When_Campaign_Expired_IsActive_Must_Be_Return_False()
        {
            var campaign = new CampaignEntity("C1", "P1", 10, 10, 10, 0);

            var isActive = campaign.IsActive(10);

            Assert.False(isActive);
        }
        public async Task CreateAsync(CreateCampaignRequest request)
        {
            var entity = new CampaignEntity
            {
                Name = request.Name
            };

            await(await _container).CreateItemAsync(await _entityMutator.CreateMetadataAsync(entity, request.SharedWith));
        }
Beispiel #16
0
 /// <summary> setups the sync logic for member _campaign</summary>
 /// <param name="relatedEntity">Instance to set as the related entity of type entityType</param>
 private void SetupSyncCampaign(IEntityCore relatedEntity)
 {
     if (_campaign != relatedEntity)
     {
         DesetupSyncCampaign(true, true);
         _campaign = (CampaignEntity)relatedEntity;
         this.PerformSetupSyncRelatedEntity(_campaign, new PropertyChangedEventHandler(OnCampaignPropertyChanged), "Campaign", Mecca.CMT.DAL.RelationClasses.StaticCampaignOwnerRelations.CampaignEntityUsingCampaignIdStatic, true, ref _alreadyFetchedCampaign, new string[] {  });
     }
 }
Beispiel #17
0
        private static void CheckForDelete(CampaignEntity entity)
        {
            ServiceCampaignDataAccess varServiceCampaignDataAccess = new ServiceCampaignDataAccess();

            if (varServiceCampaignDataAccess.LoadWhere(ServiceCampaignEntity.DBIdCampaign, entity.Id, false, OperatorType.Equal).Count > 0)
            {
                throw new UtnEmallDataAccessException("There are services associated to this campaign.");
            }
        }
 /// <summary> setups the sync logic for member _campaign</summary>
 /// <param name="relatedEntity">Instance to set as the related entity of type entityType</param>
 private void SetupSyncCampaign(IEntity2 relatedEntity)
 {
     if (_campaign != relatedEntity)
     {
         DesetupSyncCampaign(true, true);
         _campaign = (CampaignEntity)relatedEntity;
         base.PerformSetupSyncRelatedEntity(_campaign, new PropertyChangedEventHandler(OnCampaignPropertyChanged), "Campaign", CampaignAssignmentEntity.Relations.CampaignEntityUsingCampaignId, true, new string[] {  });
     }
 }
        /// <summary> Initializes the class members</summary>
        protected virtual void InitClassMembers()
        {
            _campaign             = null;
            _organizationRoleUser = null;

            PerformDependencyInjection();

            // __LLBLGENPRO_USER_CODE_REGION_START InitClassMembers
            // __LLBLGENPRO_USER_CODE_REGION_END
            OnInitClassMembersComplete();
        }
Beispiel #20
0
 /// <summary>
 /// Salva uma campanha na base de dados
 /// </summary>
 /// <param name="newEntity"></param>
 /// <returns></returns>
 public CampaignEntity CreateCampaign(CampaignEntity newEntity)
 {
     using (ModelContext context = new ModelContext())
     {
         newEntity.LastUpdate = DateTime.UtcNow;
         context.Campaigns.Attach(newEntity);
         context.Entry(newEntity).State = System.Data.Entity.EntityState.Added;
         context.SaveChanges();
     }
     return(newEntity);
 }
Beispiel #21
0
        public void Campaign_Should_CalculateCorrectly_AverageItemPrice_And_Turnover()
        {
            var campaign = new CampaignEntity("C1", "P1", 10, 10, 10, 0);

            campaign.NotifyOrderCreation(10, 25.5M);
            campaign.NotifyOrderCreation(5, 50);
            campaign.NotifyOrderCreation(40, 60);

            Assert.Equal(52, campaign.AverageItemPrice);
            Assert.Equal(2905, campaign.Turnover);
        }
Beispiel #22
0
        /// <summary>
        /// carga el contenido del formulario en el objeto de entidad
        /// </summary>
        private void Load()
        {
            if (mode == EditionMode.Add)
            {
                campaign = new CampaignEntity();
            }

            campaign.Name        = TxtName.Text.Trim();
            campaign.Description = TxtDescription.Text.Trim();
            campaign.StartDate   = StartDatePicker.Date;
            campaign.StopDate    = StopDatePicker.Date;
        }
 public Campaign ToCampaign(CampaignEntity campaign)
 {
     if (campaign == null)
     {
         return(null);
     }
     return(new Campaign
     {
         Id = campaign.Id,
         Name = campaign.Name
     });
 }
Beispiel #24
0
        /// <summary>
        /// Function to Load the relation User from database.
        /// </summary>
        /// <param name="campaign">CampaignEntity parent</param>
        /// <exception cref="ArgumentNullException">
        /// if <paramref name="campaign"/> is not a <c>CampaignEntity</c>.
        /// </exception>
        public void LoadRelationUser(CampaignEntity campaign, Dictionary <string, IEntity> scope)
        {
            if (campaign == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            bool closeConnection = false;

            try
            {
                // Create a new connection if needed
                if (dbConnection == null || dbConnection.State.CompareTo(ConnectionState.Closed) == 0)
                {
                    closeConnection = true;
                    dbConnection    = dataAccess.GetNewConnection();
                    dbConnection.Open();
                }
                // Create a command

                string           cmdText    = "SELECT idUser FROM [Campaign] WHERE idCampaign = @idCampaign";
                IDbCommand       sqlCommand = dataAccess.GetNewCommand(cmdText, dbConnection, dbTransaction);
                IDbDataParameter parameter  = dataAccess.GetNewDataParameter("@idCampaign", DbType.Int32);
                // Set command parameters values

                parameter.Value = campaign.Id;
                sqlCommand.Parameters.Add(parameter);
                // Execute commands

                object idRelation = sqlCommand.ExecuteScalar();
                if (idRelation != null && ((int)idRelation) > 0)
                {
                    // Create data access objects and set connection objects
                    UserDataAccess userDataAccess = new UserDataAccess();
                    userDataAccess.SetConnectionObjects(dbConnection, dbTransaction);
                    // Load related object

                    campaign.User = userDataAccess.Load(((int)idRelation), true, scope);
                }
            }
            catch (DbException dbException)
            {
                // Catch and rethrow as custom exception
                throw new UtnEmallDataAccessException(dbException.Message, dbException);
            }
            finally
            {
                // Close connection if initiated by me
                if (closeConnection)
                {
                    dbConnection.Close();
                }
            }
        }
Beispiel #25
0
        /// <summary>
        /// Atualiza uma campanha
        /// </summary>
        /// <param name="updatedEntity"></param>
        /// <returns></returns>
        public CampaignEntity UpdateCampaign(CampaignEntity updatedEntity)
        {
            using (ModelContext context = new ModelContext())
            {
                updatedEntity.LastUpdate = DateTime.UtcNow;
                context.Campaigns.Attach(updatedEntity);
                context.Entry(updatedEntity).State = System.Data.Entity.EntityState.Modified;
                context.SaveChanges();
            }

            return(updatedEntity);
        }
        public ActionResult PictureVoteUpload()
        {
            string strCampaignId = Request.QueryString["campaignId"];

            if (String.IsNullOrEmpty(strCampaignId))
            {
                return(RespondResult(false, "参数无效。"));
            }

            Guid campaignId = Guid.Parse(strCampaignId);

            CampaignEntity             campaign    = _campaignManager.GetCampaign(campaignId);
            Campaign_PictureVoteEntity pictureVote = _campaignManager.PictureVote.GetPictureVote(campaignId);

            if (campaign == null || pictureVote == null)
            {
                //重定向到错误页面
                return(new RedirectResult(String.Format(
                                              "~/Home/ErrorView/?message={0}", "td8")));
            }

            //判断当前用户上传量是否已达限制,达到限制则直接跳转到查看页面
            List <Campaign_PictureVoteItemEntity> uploadList =
                _campaignManager.PictureVote.GetMemberPictureVoteItemList(campaignId, MemberContext.Member.Id);

            if (uploadList.Count >= pictureVote.MaxPublishTimes)
            {
                return(RedirectToAction("PictureVoteItemDetail",
                                        new { domainId = DomainContext.Domain.Id, itemId = uploadList[0].Id, campaignId = strCampaignId }));

                //return RedirectToRoute(new
                //{
                //    controller = "Campaign",
                //    action = "PictureVoteItemDetail",
                //    domainId = DomainContext.Domain.Id,
                //    id = uploadList[0].Id,
                //    campaignId = strCampaignId
                //});
                //return Redirect(String.Format("~/Campaign/PictureVoteItemDetail/{0}?campaignId={1}&id={2}",
                //    DomainContext.Domain.Id, uploadList[0].Id, strCampaignId));
            }

            PictureVoteUploadViewModel model = new PictureVoteUploadViewModel();

            model.Campaign    = campaign;
            model.JsApiConfig = DomainContext.GetJsApiConfig(HttpContext.Request.Url.ToString());
            model.JsApiConfig.JsApiList.Add("chooseImage");
            model.JsApiConfig.JsApiList.Add("previewImage");
            model.JsApiConfig.JsApiList.Add("uploadImage");
            model.JsApiConfig.JsApiList.Add("downloadImage");
            return(View(model));
        }
Beispiel #27
0
        public void Update(CampaignEntity campaign, Campaign_ShakingLotteryEntity shakingLottery)
        {
            if (campaign == null || shakingLottery == null)
            {
                Debug.Assert(false, "campaign == null || shakingLottery ==null");
                return;
            }

            shakingLottery.CampaignId = campaign.Id;
            shakingLottery.Domain     = campaign.Domain;

            _campaignManager.DataBase.UpdateList(campaign, shakingLottery);
        }
        public void UpdateLuckyTicket(CampaignEntity campaign, Campaign_LuckyTicketEntity luckyTicket)
        {
            if (campaign == null || luckyTicket == null)
            {
                Debug.Assert(false, "campaign == null || luckyTicket ==null");
                return;
            }

            luckyTicket.CampaignId = campaign.Id;
            luckyTicket.Domain     = campaign.Domain;

            _campaignManager.DataBase.UpdateList(campaign, luckyTicket);
        }
        public void UpdateDonation(CampaignEntity campaign, Campaign_DonationEntity donation)
        {
            if (campaign == null || donation == null)
            {
                Debug.Assert(false, "campaign == null || donation ==null");
                return;
            }

            donation.CampaignId = campaign.Id;
            donation.Domain     = campaign.Domain;

            _campaignManager.DataBase.UpdateList(campaign, donation);
        }
        public void UpdateLottery(CampaignEntity campaign, Campaign_LotteryEntity lottery)
        {
            if (campaign == null || lottery == null)
            {
                Debug.Assert(false, "campaign == null || lottery ==null");
                return;
            }

            lottery.CampaignId = campaign.Id;
            lottery.Domain     = campaign.Domain;

            _campaignManager.DataBase.UpdateList(campaign, lottery);
        }