Beispiel #1
0
	private void ShowVideo()
	{
		if (videoAd != null)
		{
			videoAd.Start();
			videoAd = null;
		}
	}
Beispiel #2
0
	void Awake ()
	{
		// If this is the first instance, make it the singleton. If a singleton already exists and another reference is found, destroy it
		if (instance == null) {
			instance = this;
			DontDestroyOnLoad (this);
		} else {
			if (this != instance)
				Destroy (this.gameObject);
		}
	}
Beispiel #3
0
        public void CanInsertAd()
        {
            var item = new Ad()
            {
                Name = "Test Ad",
                Description = "Test Ad"
            };

            var result = _repo.Insert(item);
            var expected = _repo.Get(result.Id);
            Assert.AreEqual(result.Name, expected.Name);
            Assert.AreEqual(result.Description, expected.Name);
        }
Beispiel #4
0
        public void CanDeleteAd()
        {
            var item = new Ad()
            {
                Name = "To be deleted",
                Description = "To be deleted"
            };

            item = _repo.Insert(item);

            if (item == null)
                Assert.Fail("could not insert record to be deleted.");

            var result = _repo.Delete(item.Id);

            Assert.IsTrue(result);
        }
Beispiel #5
0
    } // End of the constructor

    #endregion

    #region Insert methods

    /// <summary>
    /// Add one ad
    /// </summary>
    /// <param name="post">A reference to a ad post</param>
    public static long Add(Ad post)
    {
        // Create the long to return
        long idOfInsert = 0;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "INSERT INTO dbo.ads (language_id, name, ad_slot, ad_code, inactive) "
            + "VALUES (@language_id, @name, @ad_slot, @ad_code, @inactive);SELECT SCOPE_IDENTITY();";

        // The using block is used to call dispose automatically even if there is a exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there is a exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@language_id", post.language_id);
                cmd.Parameters.AddWithValue("@name", post.name);
                cmd.Parameters.AddWithValue("@ad_slot", post.ad_slot);
                cmd.Parameters.AddWithValue("@ad_code", post.ad_code);
                cmd.Parameters.AddWithValue("@inactive", post.inactive);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection
                    cn.Open();

                    // Execute the insert
                    idOfInsert = Convert.ToInt64(cmd.ExecuteScalar());

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        // Return the id of the inserted item
        return idOfInsert;

    } // End of the Add method
Beispiel #6
0
        public void CanCallDelete()
        {
            var ad = new Ad()
            {
                Id = 40,
                Name = "40",
                Description = "40"
            };

            var mock = new Mock<IAdRepository>();
            mock.Setup(c => c.Delete(It.IsAny<int>())).Returns<Ad>(null);
            mock.Setup(c => c.Get(It.IsAny<int>())).Returns(ad);
            var controller = new AdsController(mock.Object);

            controller.Delete(ad.Id);

            mock.Verify(repo => repo.Delete(It.IsAny<int>()), Times.AtLeastOnce());
        }
Beispiel #7
0
        public void CanCallGet()
        {
            var ad = new Ad()
            {
                Id = 10,
                Name = "10",
                Description = "10"
            };

            var mock = new Mock<IAdRepository>();
            mock.Setup(c => c.Get(It.IsAny<int>())).Returns(ad);

            var controller = new AdsController(mock.Object);

            var result = controller.Get(10);

            Assert.IsTrue(result.Name == "10");
        }
Beispiel #8
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group that contains the ad.</param>
        /// <param name="adId">Id of the ad being removed.</param>
        public void Run(AdWordsUser user, long adGroupId, long adId)
        {
            // Get the AdGroupAdService.
            AdGroupAdService adGroupAdService = (AdGroupAdService)user.GetService(
                AdWordsService.v201509.AdGroupAdService);

            // Since we do not need to update any ad-specific fields, it is enough to
            // create the base type.
            Ad ad = new Ad();

            ad.id = adId;

            // Create the ad group ad.
            AdGroupAd adGroupAd = new AdGroupAd();

            adGroupAd.adGroupId = adGroupId;

            adGroupAd.ad = ad;

            // Create the operation.
            AdGroupAdOperation operation = new AdGroupAdOperation();

            operation.operand   = adGroupAd;
            operation.@operator = Operator.REMOVE;

            try {
                // Remove the ad.
                AdGroupAdReturnValue retVal = adGroupAdService.mutate(
                    new AdGroupAdOperation[] { operation });

                if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                {
                    AdGroupAd removedAdGroupAd = retVal.value[0];
                    Console.WriteLine("Ad with id = \"{0}\" and type = \"{1}\" was removed.",
                                      removedAdGroupAd.ad.id, removedAdGroupAd.ad.AdType);
                }
                else
                {
                    Console.WriteLine("No ads were removed.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to remove ad.", e);
            }
        }
        public async Task CreatePromotionOrderAsync_WithInvalidPromotionId_ShouldThrowAnArgumentException()
        {
            //Arrange
            var expectedErrorMessage = "Promotion with the given id doesn't exist!";

            var moqAdsService = new Mock <IAdsService>();
            var context       = InitializeContext.CreateContextForInMemory();

            promotionsService = new PromotionsService(context, moqAdsService.Object);

            var testingAd = new Ad
            {
                Id                = 1,
                Title             = "Iphone 6s",
                Description       = "PerfectCondition",
                ActiveFrom        = DateTime.UtcNow,
                ActiveTo          = DateTime.UtcNow.AddDays(30),
                AvailabilityCount = 1,
                Price             = 120,
                Condition         = new Condition {
                    Name = "Brand New"
                },
                Address = new Address
                {
                    Id           = 1,
                    Country      = "Bulgaria",
                    City         = "Sofia",
                    Street       = "Ivan Vazov",
                    District     = "Student city",
                    ZipCode      = 1000,
                    PhoneNumber  = "0895335532",
                    EmailAddress = "*****@*****.**"
                }
            };
            await context.Ads.AddAsync(testingAd);

            await context.SaveChangesAsync();

            //Act and assert
            var ex = await Assert.ThrowsAsync <ArgumentException>(() =>
                                                                  promotionsService.CreatePromotionOrderAsync(1, 1));

            Assert.Equal(expectedErrorMessage, ex.Message);
        }
Beispiel #10
0
        public void Insert(Ad ad)
        {
            var parameters = new List <SqlParameter>();

            parameters.Add(sqlHelper.CreateParameter("@AdName", ad.AdName, DbType.String));
            parameters.Add(sqlHelper.CreateParameter("@Info", ad.Info, DbType.String));
            parameters.Add(sqlHelper.CreateParameter("@CreateDate", ad.CreateDate, DbType.Date));
            parameters.Add(sqlHelper.CreateParameter("@PicPath", ad.PicPath, DbType.String));
            parameters.Add(sqlHelper.CreateParameter("@CategoryId", ad.CategoryId, DbType.Int32));
            parameters.Add(sqlHelper.CreateParameter("@AuthorName", ad.AuthorName, DbType.String));
            parameters.Add(sqlHelper.CreateParameter("@AuthorEmail", ad.AuthorEmail, DbType.String));
            parameters.Add(sqlHelper.CreateParameter("@AuthorPhone", ad.AuthorPhone, DbType.String));
            parameters.Add(sqlHelper.CreateParameter("@ProductPlacement", ad.ProductPlacement, DbType.String));
            parameters.Add(sqlHelper.CreateParameter("@ProductType", ad.ProductType, DbType.String));
            parameters.Add(sqlHelper.CreateParameter("@ProductState", ad.ProductState, DbType.String));
            parameters.Add(sqlHelper.CreateParameter("@UserId", ad.UserId, DbType.String));

            sqlHelper.Insert("Ad_Insert", CommandType.StoredProcedure, parameters.ToArray());
        }
Beispiel #11
0
        public async Task <JsonResult> Register(Ad AdJs)
        {
            HttpClient client = _api.Initial();

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));


            var jsonContent   = JsonConvert.SerializeObject(AdJs);
            var contentString = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            contentString.Headers.ContentType = new MediaTypeHeaderValue("application/json");


            HttpResponseMessage res = await client.PostAsync("api/Ad/Create", contentString);

            return(Json("ok"));
        }
Beispiel #12
0
 public virtual bool FillDetails(Ad ad)
 {
     if (_detailsSelector != null)
     {
         string content = WebHelper.GetStringFromUrl(ad.Url);
         var detailsMatches = _detailsSelector.Match(content).ToList();
         if (detailsMatches.Count == 1)
         {
             FillAdDetails(ad, detailsMatches[0]);
             return true;
         }
         else
         {
             Managers.LogEntriesManager.AddItem(SeverityLevel.Warning,
                 string.Format("{0} No matches found on details page {1}", this.GetType().Name, ad.Url), content);
         }
     }
     return false;
 }
Beispiel #13
0
        public void AddAd_HasCompany_ShouldWork()
        {
            int cId1 = 1, cId2 = 2;
            var c1 = new Company()
            {
                Id = cId1
            };
            var c2 = new Company()
            {
                Id = cId2
            };

            var a1 = new Ad()
            {
                Id = 1
            };
            var a2 = new Ad()
            {
                Id = 2
            };
            var a3 = new Ad()
            {
                Id = 3
            };

            PerformDbServiceActions((sut, db) => {
                sut.AddNewCompany(c1);
                sut.AddNewCompany(c2);

                sut.AddAd(a1, cId1);
                sut.AddAd(a2, cId1);
                sut.AddAd(a3, cId2); //other company

                var cnew = sut.GetCompany(cId1);

                Assert.NotNull(cnew.Ads);
                Assert.NotEmpty(cnew.Ads);
                Assert.Contains(a1.Id, cnew.Ads.Select(x => x.Id));
                Assert.Contains(a2.Id, cnew.Ads.Select(x => x.Id));
                Assert.DoesNotContain(a3.Id, cnew.Ads.Select(x => x.Id));
                db.DetachAll();
            });
        }
Beispiel #14
0
        public ActionResult PlaceAd()
        {
            string adText = TempData["adText"].ToString();

            if (!string.IsNullOrEmpty(adText))
            {
                var adToPlace           = new Ad(adText);
                var newspaperToGetNewAd = newspapers.FirstOrDefault(x => x.Id == Convert.ToInt32(TempData["newspaperId"].ToString()));

                if (newspaperToGetNewAd != null)
                {
                    //Persist New Ad in Database
                    newspaperToGetNewAd.PlaceAd(adToPlace);
                    writer.SaveNewAd(newspaperToGetNewAd.Id, adToPlace);
                }
            }

            return(RedirectToAction("Index"));
        }
Beispiel #15
0
 public static AdProductsModel MapToAdProductsModel(Ad ad)
 {
     return(new AdProductsModel()
     {
         id = ad.ID,
         name = ad.Name,
         price = ad.Price,
         salePrice = ad.Price,
         discount = 50,
         shortDetails = ad.AdDetail?.Description,
         description = ad.AdDetail?.Description,
         category = ad.Category?.Name,
         tags = new List <string> {
             ad.City?.Name
         },
         pictures = ad.AdDetail?.AdDetailPictures?.Select(x => x.File).ToList(),
         createdAt = ad.CreatedAt
     });
 }
Beispiel #16
0
        public static AdEditModel MapToAdEditModel(Ad entity)
        {
            var editModel = new AdEditModel();

            var mainPicture = entity.AdDetail?.MainPictureThumbnailFile;
            var description = entity.AdDetail?.Description;

            editModel.ID         = entity.ID;
            editModel.Name       = entity.Name;
            editModel.OwnerId    = entity.OwnerId;
            editModel.Price      = entity.Price;
            editModel.CategoryId = entity.CategoryID;
            editModel.CityId     = entity.CityID;
            editModel.AdDetail.AdDetailPictures = entity.AdDetail?.AdDetailPictures;
            editModel.MainPictureThumbnail      = mainPicture;
            editModel.Description = description;

            return(editModel);
        }
Beispiel #17
0
        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public PublicResult CreateAd(CreateAdDto dto)
        {
            using (var client = DbFactory.CreateClient())
            {
                var ad = new Ad
                {
                    AdPlaceId  = dto.AdPlaceId,
                    Title      = dto.Title,
                    ImagePath  = dto.ImagePath,
                    TargetUrl  = dto.TargetUrl,
                    OrderIndex = 0,
                    IsShow     = true
                };
                ad.Id = client.Insertable(ad).ExecuteReturnBigIdentity();

                _eventPublisher.EntityCreated(ad);
                return(Ok());
            }
        }
Beispiel #18
0
        public HttpResponseMessage GetAdDetails(HttpRequestMessage request, [FromBody] int adId)
        {
            return(GetHttpResponse(request, () =>
            {
                HttpResponseMessage response = null;

                Ad ad = adRepository.Get(adId);
                AdDetailsModel adDetails = new AdDetailsModel();
                List <string> adApplicantUserIds = new List <string>();

                adDetails.AdDetails = ad;

                adApplicantUserIds = adApplicationRespository.GetAdApplicant(ad.AdId);

                foreach (var adApplicant in adApplicantUserIds)
                {
                    Account account = UserManager.FindById(adApplicant);
                    if (account == null)
                    {
                        continue;
                    }

                    UserAccountModel userAccountModel = new UserAccountModel()
                    {
                        Email = account.Email,
                        FirstName = account.FirstName,
                        LastName = account.LastName,
                        UserName = account.UserName,
                        SubscriptionStatus = account.SubscriptionStatus,
                        PhoneNumber = account.PhoneNumber,
                        UserId = account.Id,
                        CurrentRating = account.CurrentRating,
                        NumberOfReviews = account.NumberOfReviews
                    };

                    adDetails.AdApplicantDetails.Add(userAccountModel);
                }

                response = request.CreateResponse(HttpStatusCode.OK, adDetails);

                return response;
            }));
        }
Beispiel #19
0
        private void CreateImageCreatives(Ad ad, JsonDynamicReader adGroupCreativesReader)
        {
            var imgCreative = GetImageCreative(adGroupCreativesReader);

            if (!string.IsNullOrEmpty(imgCreative.ImageUrl))
            {
                ad.Creatives.Add(imgCreative);
            }

            var bodyCreative = GetBodyCreative(adGroupCreativesReader);

            if (!string.IsNullOrEmpty(bodyCreative.Text))
            {
                ad.Creatives.Add(bodyCreative);
            }

            //bug creative type =9 story like
            ad.Creatives.Add(GetTextCreative(adGroupCreativesReader));
        }
        /// <summary>
        /// Uses OnAdUsidRequired to extract a usid for an ad, or ad.OriginalID if the function delegate is not defined.
        /// </summary>
        private string GetAdIdentity(Ad ad)
        {
            string val;

            if (this.OnAdUsidRequired != null)
            {
                val = this.OnAdUsidRequired(ad).ToString();
            }
            else if (String.IsNullOrEmpty(ad.OriginalID))
            {
                throw new Exception("Ad.OriginalID is required. If it is not available, provide a function for AdMetricsImportManager.OnAdUsidRequired that returns a unique value for this ad.");
            }
            else
            {
                val = ad.OriginalID.ToString();
            }

            return(val);
        }
Beispiel #21
0
        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public CreateAdResponse CreateAd(CreateAdRequest request)
        {
            using (var client = DbFactory.GetClient())
            {
                var ad = new Ad
                {
                    AdPlaceId  = request.AdPlaceId,
                    Title      = request.Title,
                    ImagePath  = request.ImagePath,
                    TargetUrl  = request.TargetUrl,
                    OrderIndex = 0,
                    IsShow     = true
                };
                ad.Id = client.Insertable(ad).ExecuteReturnBigIdentity();

                _eventPublisher.EntityCreated(ad);
                return(new CreateAdResponse());
            }
        }
Beispiel #22
0
        public override void Handle(Report report, RepoFacade repo)
        {
            if (report.Type == ReportTypes.Scam)
            {
                repo.FreezeAd(report.AdCategory, report.AdId);

                Ad ad = repo.GetAd(report.AdCategory, report.AdId);
                repo.BanUser(ad.UserId);

                User admin = repo.GetAdmin();

                string adminPopover  = $"<a data-toggle='popover' data-container='body' data-placement='top' data-html='true' data-content='Name: {admin.Name}<br>Email: {admin.Email}'>Admin</a>";
                string reportPopover = $"<a data-toggle='popover' data-container='body' data-placement='top' data-html='true' data-content='Type: {report.Type}<br>Comment: {report.Comment}'>reported</a>";
                string message       = $"Your ad <a href='/Home/Ad/?id={ad.Id}&category={ad.Category}'>{ad.Title}</a> was {reportPopover} and now is freezed and you are banned, contact {adminPopover} to solve this problem! <span class='notification-date'>[{DateTime.Now}]</span>";

                repo.NotifyUser(message, NotificationType.Report, ad.UserId);
            }
            Successor.Handle(report, repo);
        }
Beispiel #23
0
        public async Task CreateUpdateAdAsync_WithValidData_ShouldCreateUpdateAd()
        {
            //Arrange
            var expectedUpdateAdCount = 1;

            var context = InitializeContext.CreateContextForInMemory();

            updatesService = new UpdatesService(context);

            var testingAd = new Ad
            {
                Id                = 1,
                Title             = "Iphone 6s",
                Description       = "PerfectCondition",
                ActiveFrom        = DateTime.UtcNow,
                ActiveTo          = DateTime.UtcNow.AddDays(30),
                AvailabilityCount = 1,
                Price             = 120,
                Condition         = new Condition {
                    Name = "Brand New"
                },
                Address = new Address
                {
                    Country      = "Bulgaria",
                    City         = "Sofia",
                    Street       = "Ivan Vazov",
                    District     = "Student city",
                    ZipCode      = 1000,
                    PhoneNumber  = "0895335532",
                    EmailAddress = "*****@*****.**"
                }
            };

            await context.Ads.AddAsync(testingAd);

            await context.SaveChangesAsync();

            //Act
            await updatesService.CreateUpdateAdAsync(1);

            //Assert
            Assert.Equal(expectedUpdateAdCount, context.UpdateAds.Count());
        }
        public async Task <IActionResult> Update(CreateVM vm)
        {
            User u  = repo.GetUser(User.Identity.Name);
            Ad   ad = repo.GetAd(vm.Category, vm.Id);

            if (ad == null)
            {
                return(RedirectToAction("PageNotFound", "Error"));
            }
            if (ad.UserId != u.Id)
            {
                return(RedirectToAction("Forbidden", "Error"));
            }

            repo.UpdateAd(vm, (userId, message) => Notify(userId, "Price of observed item changed", message));
            await Notify(ad.UserId, "Price of observed item changed", "testing...");

            return(RedirectToAction("Ad", "Home", new { id = vm.Id, category = vm.Category }));
        }
        public IActionResult Ad(int id, string category)
        {
            Ad   targetAd = repo.GetAd(category, id);
            User user     = repo.GetUser(User.Identity.Name);

            if (targetAd == null)
            {
                return(RedirectToAction("PageNotFound", "Error"));
            }
            if (targetAd.IsFreezed == true && targetAd.UserId != user.Id)
            {
                return(RedirectToAction("Frozen", "Error"));
            }


            ViewBag.User = user;

            return(View(targetAd));
        }
        // GET: /Services/Edit/5
        public async Task <ActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Ad ad = await db.Ads.FindAsync(id);

            if (ad == null)
            {
                return(HttpNotFound());
            }
            ViewBag.Id       = new SelectList(db.AdsLocations, "Id", "exectLocation", ad.Id);
            ViewBag.Id       = new SelectList(db.LaptopAds, "Id", "color", ad.Id);
            ViewBag.Id       = new SelectList(db.MobileAds, "Id", "color", ad.Id);
            ViewBag.postedBy = new SelectList(db.AspNetUsers, "Id", "Email", ad.postedBy);
            ViewBag.Id       = new SelectList(db.CompanyAds, "adId", "rating", ad.Id);
            return(View(ad));
        }
Beispiel #27
0
        /// <summary>
        /// Updates the information from and ad, in the database.
        /// </summary>
        /// <param name="ad">Ad to be updated.</param>
        /// <param name="caseId">CaseId connected to the ad.</param>
        public void UpdateAd(Ad ad, int caseId)
        {
            int adId = ad.Id;

            SqlCommand cmd = new SqlCommand
            {
                CommandText = "UPDATE Ad SET CaseId = (@CaseId), Type = (@Type), StartDate = (@StartDate), EndDate = (@EndDate), Price = (@Price)" + "WHERE AdId = (@AdId)"
            };

            cmd.Parameters.Add("@AdId", SqlDbType.Int, 4, "AdId").Value = adId;

            cmd.Parameters.Add("@CaseId", SqlDbType.Int, 4, "CaseId").Value        = caseId;
            cmd.Parameters.Add("@Type", SqlDbType.Date, 8, "Type").Value           = ad.Type;
            cmd.Parameters.Add("@StartDate", SqlDbType.Date, 8, "StartDate").Value = ad.StartDate;
            cmd.Parameters.Add("@EndDate", SqlDbType.Date, 8, "EndDate").Value     = ad.EndDate;
            cmd.Parameters.Add("@Price", SqlDbType.Int, 4, "Price").Value          = ad.Price;

            DBConnectionMSSQL.Instance.ExecuteNonQuery(cmd);
        }
Beispiel #28
0
        // GET: RemoveBillboardFromAd
        public ActionResult RemoveBillboardFromAd(int?adId, int?billboardId)
        {
            if (adId == null || billboardId == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Ad        ad        = db.Ads.Find(adId);
            Billboard billboard = db.Billboards.Find(billboardId);

            if (ad == null || billboard == null)
            {
                return(HttpNotFound());
            }
            ad.Billboards.Remove(billboard);
            db.Entry(ad).State = EntityState.Modified;
            db.SaveChanges();
            logger.Log("Ads/RemoveBillboardFromAd/ - BillboardId:" + billboard.Id.ToString() + " from AdId: " + ad.Id.ToString());
            return(RedirectToAction("Details", new { id = adId }));
        }
Beispiel #29
0
        public IHttpActionResult CreateAd(CreateAdBindingModel model)
        {
            var userId = this.User.Identity.GetUserId();

            if (model == null)
            {
                return(this.BadRequest("Model cannot be null (no data in request)"));
            }

            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            var adType = this.Data.AdTypes
                         .FirstOrDefault(at => at.Name == model.Type);

            if (adType == null)
            {
                return(this.BadRequest("Type is invalid"));
            }

            var ad = new Ad()
            {
                Name        = model.Name,
                Description = model.Description,
                Price       = model.Price,
                Type        = adType,
                PostedOn    = DateTime.Now,
                Status      = AdStatus.Open,
                OwnerId     = this.User.Identity.GetUserId()
            };

            this.Data.Ads.Add(ad);
            this.Data.SaveChanges();

            var data = this.Data.Ads
                       .Where(a => a.Id == ad.Id)
                       .Select(AdViewModel.Create)
                       .FirstOrDefault();

            return(this.Ok(data));
        }
        private static bool IsFlatComplete(Ad ad)
        {
            if (!HasDescription(ad))
            {
                return(false);
            }

            if (!HaveAnyPicture(ad))
            {
                return(false);
            }

            if (!HasHouseSize(ad))
            {
                return(false);
            }

            return(true);
        }
Beispiel #31
0
        public async Task <IActionResult> PutAd(int id, Ad ad)
        {
            if (id != ad.Id)
            {
                return(BadRequest());
            }

            _context.Entry(ad).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                return(NotFound());
            }
            return(NoContent());
        }
Beispiel #32
0
        public IActionResult NewAd(Ad ad)
        {
            var db = new SimpleAdAuthDb(_connectionString);
            var vm = new NewAdViewModel()
            {
                IsAuthenticated = User.Identity.IsAuthenticated
            };

            if (User.Identity.IsAuthenticated)
            {
                var  email = User.Identity.Name;
                User user  = db.GetUserByEmail(email);
                ad.UserId      = user.Id;
                vm.CurrentUser = user;
                db.NewAd(ad);
            }

            return(Redirect("/Home/Index"));
        }
Beispiel #33
0
        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ServResult CreateAd(ServRequest <CreateAdDto> request)
        {
            using (var client = DbFactory.GetClient())
            {
                var ad = new Ad
                {
                    AdPlaceId  = request.Data.AdPlaceId,
                    Title      = request.Data.Title,
                    ImagePath  = request.Data.ImagePath,
                    TargetUrl  = request.Data.TargetUrl,
                    OrderIndex = 0,
                    IsShow     = true
                };
                ad.Id = client.Insertable(ad).ExecuteReturnBigIdentity();

                _eventPublisher.EntityCreated(ad);
                return(Ok());
            }
        }
Beispiel #34
0
        //[PrincipalPermission(SecurityAction.Demand, Role = SecurityValueObject.JonMtaaniAdminRole)]
        //[PrincipalPermission(SecurityAction.Demand, Name = SecurityValueObject.JonMtaaniUser)]
        public Ad UpdateAd(Ad ad, string loginEmail)
        {
            return(ExecuteFaultHandledOperation(() =>
            {
                IAdRepository adrepository = dataRepositoryFactory.GetDataRepository <IAdRepository>();

                Ad updatedEntity = null;

                if (ad.AdId == 0)
                {
                    updatedEntity = adrepository.Add(ad);
                }
                else
                {
                    updatedEntity = adrepository.Update(ad);
                }
                return updatedEntity;
            }));
        }
Beispiel #35
0
        public void GetMyAppointmentTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "Get_Appointment")
                          .Options;

            var user = new UserProfile {
                Id = "userId"
            };
            var ad = new Ad {
                Id = 2
            };
            var appointment = new Appointment
            {
                Id = 1,
                AgencyProfileId = "agencyId",
                AdId            = ad.Id,
                UserProfileId   = user.Id,
            };

            var agency = new AgencyProfile
            {
                Id       = "agencyId",
                Username = "******",
            };

            agency.Appointments.Add(appointment);
            agency.Ads.Add(ad);

            List <Appointment> apps;

            using (var db = new ApplicationDbContext(options))
            {
                db.Appointments.Add(appointment);
                db.AgenciesProfiles.Add(agency);
                db.SaveChanges();
                AppointmentService service = new AppointmentService(db);

                apps = service.GetMyAppointments(agency.Username).ToList();
            }

            Assert.Single(apps);
        }
Beispiel #36
0
        public ActionResult Create([Bind(Include = "Id,Title,Price,OwnerName,OwnerType,StartDate,EndDate,PinCode,CityId,CategoryId,RegionId,VillageId,Text,Phone,XLocation,YLocation,AgentId,ProfileId,VIP,Kupca,RoomId,BuildingTypeId,Mertebe,BinaMertebesi,Sahe,TorpaqSahesi,Email,Adress")] Ad ad)
        {
            if (ModelState.IsValid)
            {
                db.Ads.Add(ad);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.AgentId        = new SelectList(db.Agents, "Id", "Username", ad.AgentId);
            ViewBag.BuildingTypeId = new SelectList(db.BuildingTypes, "Id", "Name", ad.BuildingTypeId);
            ViewBag.CategoryId     = new SelectList(db.Categories, "Id", "Name", ad.CategoryId);
            ViewBag.CityId         = new SelectList(db.Cities, "Id", "Name", ad.CityId);
            ViewBag.ProfileId      = new SelectList(db.Profiles, "Id", "Email", ad.ProfileId);
            ViewBag.RegionId       = new SelectList(db.Regions, "Id", "Name", ad.RegionId);
            ViewBag.RoomId         = new SelectList(db.RoomCounts, "Id", "Name", ad.RoomId);
            ViewBag.VillageId      = new SelectList(db.Villages, "Id", "Name", ad.VillageId);
            return(View(ad));
        }
 public IHttpActionResult PostNew(Ad ad)
 {
     using (DyreportalenContext context = new DyreportalenContext())
     {
         context.Ads.Add(new Ad()
         {
             Ad_id    = ad.Ad_id,
             Created  = ad.Created,
             Title    = ad.Title,
             Text     = ad.Text,
             City     = ad.City,
             ImageUrl = ad.ImageUrl,
             Category = ad.Category,
             Race     = ad.Race,
             AdType   = ad.AdType
         });
         return(InjectTryCatch(context.SaveChanges));
     }
 }
        public void SubscribeOnPriceToggle(int adId, string category)
        {
            Ad   targetAd = repo.GetAd(category, adId);
            User u        = repo.GetUser(User.Identity.Name);

            if (targetAd == null)
            {
                return;
            }

            if (targetAd.Subscribers.Contains(u.Id))
            {
                repo.UnsubscribeFromAd(category, adId, u.Id);
            }
            else
            {
                repo.SubscribeOnAd(category, adId, u.Id);
            }
        }
Beispiel #39
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group that contains the ad.</param>
        /// <param name="adId">Id of the ad being removed.</param>
        public void Run(AdWordsUser user, long adGroupId, long adId)
        {
            // Get the AdGroupAdService.
              AdGroupAdService adGroupAdService = (AdGroupAdService) user.GetService(
              AdWordsService.v201601.AdGroupAdService);

              // Since we do not need to update any ad-specific fields, it is enough to
              // create the base type.
              Ad ad = new Ad();
              ad.id = adId;

              // Create the ad group ad.
              AdGroupAd adGroupAd = new AdGroupAd();
              adGroupAd.adGroupId = adGroupId;

              adGroupAd.ad = ad;

              // Create the operation.
              AdGroupAdOperation operation = new AdGroupAdOperation();
              operation.operand = adGroupAd;
              operation.@operator = Operator.REMOVE;

              try {
            // Remove the ad.
            AdGroupAdReturnValue retVal = adGroupAdService.mutate(
            new AdGroupAdOperation[] {operation});

            if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
              AdGroupAd removedAdGroupAd = retVal.value[0];
              Console.WriteLine("Ad with id = \"{0}\" and type = \"{1}\" was removed.",
              removedAdGroupAd.ad.id, removedAdGroupAd.ad.AdType);
            } else {
              Console.WriteLine("No ads were removed.");
            }
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to remove ad.", e);
              }
        }
 public AdHistoryViewModel(Ad ad)
 {
     _ad = ad;
 }
Beispiel #41
0
 protected virtual void FillAdDetails(Ad ad, Match match)
 {
 }
Beispiel #42
0
        /// <summary>
        /// Ads loader.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <returns>IEnumerable&lt;Ad&gt;.</returns>
        public static IEnumerable<Ad> AdsLoader(IDataReader reader)
        {
            var ads = new List<Ad>();

            while (reader.Read())
            {
                var adId = reader.Get<int>("ID");
                var lastMod = reader.Get<DateTime>("ModificationDate");
                var content = reader.Get<string>("Content");
                var counter = reader.Get<long>("Counter");
                var ad = new Ad
                {
                    AdID = adId,
                    LastModificationDate = lastMod,
                    Content = content,
                    TestCounter = counter
                };
                ads.Add(ad);

            }
            return ads;
        }
Beispiel #43
0
 public static Ad CreateAd(long id)
 {
     Ad ad = new Ad();
     ad.ID = id;
     return ad;
 }
Beispiel #44
0
        public void CanUpdateAd()
        {
            var item = _repo.Find(c => c.Description.ToLower().Contains("to be updated"));
            if (item == null)
            {
                var create = new Ad()
                {
                    Name = "Test Ad",
                    Description = "To be updated"
                };
                item = _repo.Insert(create);
            }

            var description = "to be updated " + DateTime.Now;
            item.Description = description;
            var expected = _repo.Update(item, item.Id);

            Assert.AreEqual(description, expected.Description);
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="service">An initialized Dfa Reporting service object
        /// </param>
        public override void Run(DfareportingService service)
        {
            long campaignId = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE"));
              long creativeId = long.Parse(_T("INSERT_CREATIVE_ID_HERE"));
              long placementId = long.Parse(_T("INSERT_PLACEMENT_ID_HERE"));
              long profileId = long.Parse(_T("INSERT_PROFILE_ID_HERE"));

              String adName = _T("INSERT_AD_NAME_HERE");

              // Retrieve the campaign.
              Campaign campaign = service.Campaigns.Get(profileId, campaignId).Execute();

              // Create a click-through URL.
              ClickThroughUrl clickThroughUrl = new ClickThroughUrl();
              clickThroughUrl.DefaultLandingPage = true;

              // Create a creative assignment.
              CreativeAssignment creativeAssignment = new CreativeAssignment();
              creativeAssignment.Active = true;
              creativeAssignment.CreativeId = creativeId;
              creativeAssignment.ClickThroughUrl = clickThroughUrl;

              // Create a placement assignment.
              PlacementAssignment placementAssignment = new PlacementAssignment();
              placementAssignment.Active = true;
              placementAssignment.PlacementId = placementId;

              // Create a creative rotation.
              CreativeRotation creativeRotation = new CreativeRotation();
              creativeRotation.CreativeAssignments = new List<CreativeAssignment>() {
              creativeAssignment
              };

              // Create a delivery schedule.
              DeliverySchedule deliverySchedule = new DeliverySchedule();
              deliverySchedule.ImpressionRatio = 1;
              deliverySchedule.Priority = "AD_PRIORITY_01";

              DateTime startDate = DateTime.Now;
              DateTime endDate = Convert.ToDateTime(campaign.EndDate);

              // Create a rotation group.
              Ad rotationGroup = new Ad();
              rotationGroup.Active = true;
              rotationGroup.CampaignId = campaignId;
              rotationGroup.CreativeRotation = creativeRotation;
              rotationGroup.DeliverySchedule = deliverySchedule;
              rotationGroup.StartTime = startDate;
              rotationGroup.EndTime = endDate;
              rotationGroup.Name = adName;
              rotationGroup.PlacementAssignments = new List<PlacementAssignment>() {
              placementAssignment
              };
              rotationGroup.Type = "AD_SERVING_STANDARD_AD";

              // Insert the rotation group.
              Ad result = service.Ads.Insert(rotationGroup, profileId).Execute();

              // Display the new ad ID.
              Console.WriteLine("Ad with ID {0} was created.", result.Id);
        }
Beispiel #46
0
 protected bool IsNewOrRepublishedAd(Ad ad, List<Ad> lastAds)
 {
     return !lastAds.Any(a => a.IsSameAd(ad) && (ad.PublishDate - a.PublishDate).Hours < 48/*if difference in time more than 48 hours we consider that this is republished ad*/);
 }
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                Service = new ServiceClient<ICampaignManagementService>(authorizationData);

                // Specify one or more campaigns.

                var campaign = new Campaign
                {
                    Name = "Women's Shoes" + DateTime.UtcNow,
                    Description = "Red shoes line.",
                    BudgetType = BudgetLimitType.MonthlyBudgetSpendUntilDepleted,
                    MonthlyBudget = 1000.00,
                    TimeZone = "PacificTimeUSCanadaTijuana",
                    DaylightSaving = true
                };

                // Specify one or more ad groups.

                var adGroup = new AdGroup
                {
                    Name = "Women's Red Shoe Sale",
                    AdDistribution = AdDistribution.Search,
                    BiddingModel = BiddingModel.Keyword,
                    PricingModel = PricingModel.Cpc,
                    StartDate = null,
                    EndDate = new Date { Month = 12, Day = 31, Year = 2015 },
                    ExactMatchBid = new Bid { Amount = 0.09 },
                    PhraseMatchBid = new Bid { Amount = 0.07 },
                    Language = "English"

                };

                // In this example only the second keyword should succeed. The Text of the first keyword exceeds the limit,
                // and the third keyword is a duplicate of the second keyword. 

                var keywords = new[] {
                    new Keyword
                    {
                        Bid = new Bid { Amount = 0.47 },
                        Param2 = "10% Off",
                        MatchType = MatchType.Broad,
                        Text = "Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes " +
                               "Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes " +
                               "Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes Brand-A Shoes"
                    },
                    new Keyword
                    {
                        Bid = new Bid { Amount = 0.47 },
                        Param2 = "10% Off",
                        MatchType = MatchType.Phrase,
                        Text = "Brand-A Shoes"
                    },
                    new Keyword
                    {
                        Bid = new Bid { Amount = 0.47 },
                        Param2 = "10% Off",
                        MatchType = MatchType.Phrase,
                        Text = "Brand-A Shoes"
                    }
                };

                // In this example only the second ad should succeed. The Title of the first ad is empty and not valid,
                // and the third ad is a duplicate of the second ad. 

                var ads = new Ad[] {
                    new TextAd 
                    {
                        DestinationUrl = "http://www.contoso.com/womenshoesale",
                        DisplayUrl = "Contoso.com",
                        Text = "Huge Savings on red shoes.",
                        Title = ""
                    },
                    new TextAd {
                        DestinationUrl = "http://www.contoso.com/womenshoesale",
                        DisplayUrl = "Contoso.com",
                        Text = "Huge Savings on red shoes.",
                        Title = "Women's Shoe Sale"
                    },
                    new TextAd {
                        DestinationUrl = "http://www.contoso.com/womenshoesale",
                        DisplayUrl = "Contoso.com",
                        Text = "Huge Savings on red shoes.",
                        Title = "Women's Shoe Sale"
                    }
                };

                // Add the campaign, ad group, keywords, and ads

                var campaignIds = (long[]) await AddCampaignsAsync(authorizationData.AccountId, new[] { campaign });
                var adGroupIds = (long[])await AddAdGroupsAsync(campaignIds[0], new[] { adGroup });

                AddKeywordsResponse addKeywordsResponse = await AddKeywordsAsync(adGroupIds[0], keywords);
                long?[] keywordIds = addKeywordsResponse.KeywordIds.ToArray();
                BatchError[] keywordErrors = addKeywordsResponse.PartialErrors.ToArray();

                AddAdsResponse addAdsResponse = await AddAdsAsync(adGroupIds[0], ads);
                long?[] adIds = addAdsResponse.AdIds.ToArray();
                BatchError[] adErrors = addAdsResponse.PartialErrors.ToArray();

                // Print the new assigned campaign and ad group identifiers

                PrintCampaignIdentifiers(campaignIds);
                PrintAdGroupIdentifiers(adGroupIds);

                // Print the new assigned keyword and ad identifiers, as well as any partial errors

                PrintKeywordResults(keywords, keywordIds, keywordErrors);
                PrintAdResults(ads, adIds, adErrors);


                // Delete the campaign, ad group, keyword, and ad that were previously added. 
                // You should remove this line if you want to view the added entities in the 
                // Bing Ads web application or another tool.

                DeleteCampaignsAsync(authorizationData.AccountId, new[] { campaignIds[0] });
                OutputStatusMessage(String.Format("Deleted CampaignId {0}\n", campaignIds[0]));
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Campaign Management service exceptions
            catch (FaultException<Microsoft.BingAds.CampaignManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.CampaignManagement.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.CampaignManagement.EditorialApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
Beispiel #48
0
	// -----------------------------------------------
	// NOTE: You can set up multiple platforms at once and the API will use the correct desc data for each
	// -----------------------------------------------
	void Start()
	{
		singleton = this;

		// bind button events
		RefreshButton.Select();
		RefreshButton.onClick.AddListener(refreshClicked);
		VisibilityButton.onClick.AddListener(visibilityClicked);
		BackButton.onClick.AddListener(backClicked);

		// make sure we don't init the same Ad twice
		if (created)
		{
			if (ad != null) ad.Visible = true;
			return;
		}
		created = true;

		// Ads - NOTE: You can pass in multiple "AdDesc" objects if you want more then one ad.
		var desc = new AdDesc();

		// global settings
		desc.Testing = true;// NOTE: To test ads on iOS, you must enable them in iTunes Connect.
		desc.Visible = true;
		desc.EventCallback = eventCallback;
		desc.UseClassicGUI = false;
		desc.GUIOverrideEnabled = false;
		desc.UnityUI_SortIndex = 1000;

		// Editor
		desc.Editor_AdAPI = AdAPIs.EditorTestAd;
		desc.Editor_AdGravity = AdGravity.BottomCenter;
		desc.Editor_AdScale = 1.5f;
		//desc.Editor_FixedWidthOverride = 250;
		//desc.Editor_FixedHeightOverride = 64;

		desc.Editor_MillennialMediaAdvertising_APID = "";
		desc.Editor_MillennialMediaAdvertising_AdGravity = AdGravity.BottomCenter;
		//desc.Editor_MillennialMediaAdvertising_RefreshRate = 120,

		// WinRT settings (Windows 8.0 & 8.1)
		desc.WinRT_AdAPI = AdAPIs.MicrosoftAdvertising;// NOTE: If building for WP 8.1 or Universal targets this value is used. All other WinRT values or used for Win8
		desc.WinRT_MicrosoftAdvertising_ApplicationID = "";
		desc.WinRT_MicrosoftAdvertising_UnitID = "";
		desc.WinRT_MicrosoftAdvertising_AdGravity = AdGravity.BottomCenter;
		desc.WinRT_MicrosoftAdvertising_AdSize = WinRT_MicrosoftAdvertising_AdSize.Wide_728x90;
		//desc.WinRT_MicrosoftAdvertising_UseBuiltInRefresh = false;
		//desc.WinRT_MicrosoftAdvertising_RefreshRate = 120;

		desc.WinRT_AdDuplex_ApplicationKey = "";
		desc.WinRT_AdDuplex_UnitID = "";
		desc.WinRT_AdDuplex_AdGravity = AdGravity.BottomCenter;
		desc.WinRT_AdDuplex_AdSize = WinRT_AdDuplex_AdSize.Wide_728x90;
		//desc.WinRT_AdDuplex_RefreshRate = 120;
			
		// WP8 settings (Windows Phone 8.0 & 8.1)
		desc.WP8_AdAPI = AdAPIs.MicrosoftAdvertising;// NOTE: If building for WP 8.1 or Universal targets this value is NOT used (Use the WinRT value instead). All other WP8 values are still used for WP 8.0, 8.1 and Universal.
		desc.WP8_MicrosoftAdvertising_ApplicationID = "";
		desc.WP8_MicrosoftAdvertising_UnitID = "";
		desc.WP8_MicrosoftAdvertising_AdGravity = AdGravity.BottomCenter;
		desc.WP8_MicrosoftAdvertising_AdSize = WP8_MicrosoftAdvertising_AdSize.Wide_480x80;
		//desc.WP8_MicrosoftAdvertising_UseBuiltInRefresh = false;
		//desc.WP8_MicrosoftAdvertising_RefreshRate = 120;

		desc.WP8_AdDuplex_ApplicationKey = "";
		desc.WP8_AdDuplex_UnitID = "";
		desc.WP8_AdDuplex_AdGravity = AdGravity.BottomCenter;
		//desc.WP8_AdDuplex_RefreshRate = 120;
			
		desc.WP8_AdMob_UnitID = "";// NOTE: You MUST have this even for Testing!
		desc.WP8_AdMob_AdGravity = AdGravity.BottomCenter;
		desc.WP8_AdMob_AdSize = Reign.WP8_AdMob_AdSize.Banner;
			
		// BB10 settings
		desc.BB10_AdAPI = AdAPIs.MillennialMediaAdvertising;
		desc.BB10_BlackBerryAdvertising_ZoneID = "";
		desc.BB10_BlackBerryAdvertising_AdGravity = AdGravity.BottomCenter;
		desc.BB10_BlackBerryAdvertising_AdSize = BB10_BlackBerryAdvertising_AdSize.Wide_320x53;

		desc.BB10_MillennialMediaAdvertising_APID = "";
		desc.BB10_MillennialMediaAdvertising_AdGravity = AdGravity.BottomCenter;
		//desc.BB10_MillennialMediaAdvertising_RefreshRate = 120;
		desc.BB10_AdScale = 1.5f;
			
		// iOS settings
		desc.iOS_AdAPI = AdAPIs.iAd;
		desc.iOS_iAd_AdGravity = AdGravity.BottomCenter;
			
		desc.iOS_AdMob_AdGravity = AdGravity.BottomCenter;
		desc.iOS_AdMob_UnitID = "";// NOTE: You can use legacy (PublisherID) too, You MUST have this even for Testing!
		desc.iOS_AdMob_AdSize = iOS_AdMob_AdSize.Banner_320x50;
			
		// Android settings
		#if AMAZON
		desc.Android_AdAPI = AdAPIs.Amazon;// Choose between AdMob or Amazon
		#else
		desc.Android_AdAPI = AdAPIs.AdMob;// Choose between AdMob or Amazon
		#endif
			
		desc.Android_AdMob_UnitID = "";// NOTE: You MUST have this even for Testing!
		desc.Android_AdMob_AdGravity = AdGravity.BottomCenter;
		desc.Android_AdMob_AdSize = Android_AdMob_AdSize.Banner_320x50;
			
		desc.Android_AmazonAds_ApplicationKey = "";
		desc.Android_AmazonAds_AdSize = Android_AmazonAds_AdSize.Wide_320x50;
		desc.Android_AmazonAds_AdGravity = AdGravity.BottomCenter;
		//desc.Android_AmazonAds_RefreshRate = 120;

		// create ad
		ad = AdManager.CreateAd(desc, adCreatedCallback);
	}
 public AdItemViewModel(Ad model)
 {
     _model = model;
 }
Beispiel #50
0
 public override bool FillDetails(Ad ad)
 {
     return false;
 }
Beispiel #51
0
        public void CanCallInsert()
        {
            var ad = new Ad()
            {
                Name = "20",
                Description = "20"
            };

            var newAd = new Ad()
            {
                Id = 20,
                Name = "20",
                Description = "20"
            };

            var mock = new Mock<IAdRepository>();
            mock.Setup(c => c.Insert(It.IsAny<Ad>())).Returns(newAd);

            var controller = new AdsController(mock.Object);
            controller.Request = new HttpRequestMessage
            {
                RequestUri = new Uri("http://localhost/api/ads")
            };
            controller.Configuration = new HttpConfiguration();
            controller.Configuration.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional });

            controller.RequestContext.RouteData = new HttpRouteData(
                    route: new HttpRoute(),
                    values: new HttpRouteValueDictionary { { "controller", "ads" } });

            var response = controller.Post(ad);
            var expectedUrl = "http://localhost/api/ads/" + newAd.Id;
            Assert.IsNotNull(response);
            Assert.AreEqual(expectedUrl, response.Headers.Location.AbsoluteUri);
        }
Beispiel #52
0
    } // End of the MasterPostExists method

    /// <summary>
    /// Get one ad based on id
    /// </summary>
    /// <param name="id">The id for the post</param>
    /// <returns>A reference to a ad post</returns>
    public static Ad GetOneById(Int32 id)
    {
        // Create the post to return
        Ad post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.ads WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", id);

                // Create a MySqlDataReader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new Ad(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method
Beispiel #53
0
	private void OnAdNotAvailable(AdFormat adFormat)
	{
		switch(adFormat)
		{
		case AdFormat.OFFER_WALL:
			ofwAd = null;
			break;
		case AdFormat.REWARDED_VIDEO:
			videoAd = null;
			break;
		case AdFormat.INTERSTITIAL:
			interstitialAd = null;
			break;
		default:
			break;
		}
	}
Beispiel #54
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            CheckPermission();

            if (pnlEditAd.Visible)
            {
                string subject = txtSubject.Text.Trim();
                string location = txtLocation.Text.Trim();
                string message = htmlEditor != null ? htmlEditor.Content.Trim() : ckeditor.Text.Trim();
                DateTime expirationDate = DateTime.Now.AddDays(Int32.Parse(ddExpiration.SelectedValue));

                #region validate fields

                if (ddCategories.SelectedValue == "-1")
                {
                    lblError.Text = "Please select category".Translate();
                    return;
                }

                if (subject.Length == 0)
                {
                    lblError.Text = "Please enter subject".Translate();
                    return;
                }

                if (location.Length == 0)
                {
                    lblError.Text = "Please enter location".Translate();
                    return;
                }

                if (message.Length == 0)
                {
                    lblError.Text = "Please enter message".Translate();
                    return;
                }

                #endregion

                Ad ad = null;
                int adID;
                if (!String.IsNullOrEmpty(Request.Params["aid"]) && Int32.TryParse(Request.Params["aid"], out adID))
                {
                    ad = Ad.Fetch(adID);
                }
                else 
                    ad = new Ad(Int32.Parse(ddSubcategories.SelectedValue), CurrentUserSession.Username)
                    {
                        Subject = subject,
                        Location = location,
                        Description = message,
                        ExpirationDate = expirationDate
                    };

                if (ad != null)
                {
                    if (CurrentUserSession.BillingPlanOptions.AutoApproveAds.Value
                                    || CurrentUserSession.Level != null && CurrentUserSession.Level.Restrictions.AutoApproveAds)
                    {
                        ad.Approved = true;
                    }
                    else
                    {
                        ad.Approved = false;
                    }

                    ad.CategoryID = Int32.Parse(ddSubcategories.SelectedValue);
                    ad.Subject = subject;
                    ad.Location = location;
                    ad.Description = message;
                    ad.ExpirationDate = expirationDate;
                    ad.Save();
                    AdID = ad.ID;

                    pnlEditAd.Visible = false;
                    pnlUploadAdPhotos.Visible = true;

                    loadPhotos(ad.ID);
                }
            }
            else
            {
                foreach (RepeaterItem item in rptAddPhoto.Items)
                {
                    TextBox txtAdPhotoDescription = (TextBox) item.FindControl("txtAdPhotoDescription");
                    FileUpload fuAdPhoto = (FileUpload)item.FindControl("fuAdPhoto");

                    if (fuAdPhoto.PostedFile.FileName.Length == 0) continue;

                    System.Drawing.Image image = null;
                    try
                    {
                        image = System.Drawing.Image.FromStream(fuAdPhoto.PostedFile.InputStream);
                    }
                    catch
                    {
                        lblError.Text = Lang.Trans("Invalid image!");
                        return;
                    }

                    Classes.AdPhoto photo = new Classes.AdPhoto(AdID.Value);
                    photo.Image = image;
                    photo.Description = txtAdPhotoDescription.Text.Trim();
                    photo.Save();

                    string cacheFileDir = Config.Directories.ImagesCacheDirectory + "/" + AdID % 10;
                    string cacheFileMask = String.Format("adID{0}_*.jpg", AdID);
                    foreach (string file in Directory.GetFiles(cacheFileDir, cacheFileMask))
                    {
                        File.Delete(file);
                    }
                }

                Response.Redirect("~/ShowAd.aspx?id=" + AdID);
            }
        }
Beispiel #55
0
	private void OnAdAvailable(Ad ad)
	{
		switch(ad.AdFormat)
		{
		case AdFormat.REWARDED_VIDEO:
			videoAd = ad;
			ShowVideo();
			break;
		case AdFormat.INTERSTITIAL:
			interstitialAd = ad;
			break;
		case AdFormat.OFFER_WALL:
			ofwAd = ad;
			break;
		default:
			break;
		}
	}
Beispiel #56
0
    } // End of the Add method

    #endregion

    #region Update methods

    /// <summary>
    /// Update a ad post
    /// </summary>
    /// <param name="post">A reference to a ad post</param>
    public static void Update(Ad post)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "UPDATE dbo.ads SET language_id = @language_id, name = @name, ad_slot = @ad_slot, "
            + "ad_code = @ad_code, inactive = @inactive WHERE id = @id;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The Using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@id", post.id);
                cmd.Parameters.AddWithValue("@language_id", post.language_id);
                cmd.Parameters.AddWithValue("@name", post.name);
                cmd.Parameters.AddWithValue("@ad_slot", post.ad_slot);
                cmd.Parameters.AddWithValue("@ad_code", post.ad_code);
                cmd.Parameters.AddWithValue("@inactive", post.inactive);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Execute the update
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Update method
        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                Service = new ServiceClient<ICampaignManagementService>(authorizationData);

                // Get a list of all Bing Merchant Center stores associated with your CustomerId

                IList<BMCStore> stores = await GetBMCStoresByCustomerIdAsync();
                if (stores == null)
                {
                    OutputStatusMessage(
                        String.Format("You do not have any BMC stores registered for CustomerId {0}.\n", authorizationData.CustomerId)
                    );
                    return;
                }

                #region ManageCampaign

                /* Add a new Bing Shopping campaign that will be associated with a ProductScope criterion.
                 *  - Set the CampaignType element of the Campaign to Shopping.
                 *  - Create a ShoppingSetting instance and set its Priority (0, 1, or 2), SalesCountryCode, and StoreId elements. 
                 *    Add this shopping setting to the Settings list of the Campaign.
                 */
                
                var campaign = new Campaign
                {
                    CampaignType = CampaignType.Shopping,
                    Settings = new[] { 
                        new ShoppingSetting() {
                            Priority = 0,
                            SalesCountryCode = "US",
                            StoreId = (int)stores[0].Id
                        }
                    },
                    Name = "Bing Shopping Campaign " + DateTime.UtcNow,
                    Description = "Bing Shopping Campaign Example.",
                    BudgetType = BudgetLimitType.MonthlyBudgetSpendUntilDepleted,
                    MonthlyBudget = 1000.00,
                    TimeZone = "PacificTimeUSCanadaTijuana",
                    DaylightSaving = true,
                };

                var campaignIds = await AddCampaignsAsync(authorizationData.AccountId, new[] { campaign });
                OutputCampaignIdentifiers(campaignIds);

                /* Optionally, you can create a ProductScope criterion that will be associated with your Bing Shopping campaign. 
                 * Use the product scope criterion to include a subset of your product catalog, for example a specific brand, 
                 * category, or product type. A campaign can only be associated with one ProductScope, which contains a list 
                 * of up to 7 ProductCondition. You'll also be able to specify more specific product conditions for each ad group.
                 */

                var campaignCriterions = new CampaignCriterion[] {
                    new CampaignCriterion() {
                        CampaignId = campaignIds[0],
                        BidAdjustment = null,  // Reserved for future use
                        Criterion = new ProductScope() {
                            Conditions = new ProductCondition[] {
                                new ProductCondition {
                                    Operand = "Condition",
                                    Attribute = "New"
                                },
                                new ProductCondition {
                                    Operand = "CustomLabel0",
                                    Attribute = "MerchantDefinedCustomLabel"
                                },
                            }
                        },
                    }                        
                };

                var addCampaignCriterionsResponse = await (AddCampaignCriterionsAsync(
                    campaignCriterions,
                    CampaignCriterionType.ProductScope)
                );

                #endregion ManageCampaign

                #region ManageAdGroup

                // Specify one or more ad groups.

                var adGroup = new AdGroup
                {
                    Name = "Product Categories",
                    AdDistribution = AdDistribution.Search,
                    BiddingModel = BiddingModel.Keyword,
                    PricingModel = PricingModel.Cpc,
                    StartDate = null,
                    EndDate = new Date { Month = 12, Day = 31, Year = 2016 },
                    Language = "English"
                };

                var adGroupIds = (long[])await AddAdGroupsAsync(campaignIds[0], new[] { adGroup });
                OutputAdGroupIdentifiers(adGroupIds);

                #region BidAllProducts

                var helper = new PartitionActionHelper(adGroupIds[0]);

                var root = helper.AddUnit(
                    null,
                    new ProductCondition { Operand = "All", Attribute = null },
                    0.35,
                    false
                );

                OutputStatusMessage("Applying only the root as a Unit with a bid . . . \n");
                var applyProductPartitionActionsResponse = await ApplyProductPartitionActionsAsync(helper.PartitionActions);

                var adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                );

                OutputStatusMessage("The ad group's product partition only has a tree root node: \n");
                OutputProductPartitions(adGroupCriterions);

                /*
                 * Let's update the bid of the root Unit we just added.
                 */

                BiddableAdGroupCriterion updatedRoot = new BiddableAdGroupCriterion
                {
                    Id = applyProductPartitionActionsResponse.AdGroupCriterionIds[0],
                    CriterionBid = new FixedBid
                    {
                        Bid = new Bid
                        {
                            Amount = 0.45
                        }
                    }
                };
                
                helper = new PartitionActionHelper(adGroupIds[0]);
                helper.UpdatePartition(updatedRoot);

                OutputStatusMessage("Updating the bid for the tree root node . . . \n");
                await ApplyProductPartitionActionsAsync(helper.PartitionActions);

                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                );

                OutputStatusMessage("Updated the bid for the tree root node: \n");
                OutputProductPartitions(adGroupCriterions);

                #endregion BidAllProducts

                #region InitializeTree

                /*
                 * Now we will overwrite any existing tree root, and build a product partition group tree structure in multiple steps. 
                 * You could build the entire tree in a single call since there are less than 5,000 nodes; however, 
                 * we will build it in steps to demonstrate how to use the results from ApplyProductPartitionActions to update the tree. 
                 * 
                 * For a list of validation rules, see the Bing Shopping Campaigns technical guide:
                 * https://msdn.microsoft.com/en-US/library/bing-ads-campaign-management-bing-shopping-campaigns.aspx
                 */

                helper = new PartitionActionHelper(adGroupIds[0]);

                /*
                 * Check whether a root node exists already.
                 */
                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                );
                var existingRoot = GetRootNode(adGroupCriterions);
                if (existingRoot != null)
                {
                    helper.DeletePartition(existingRoot);
                }

                root = helper.AddSubdivision(
                    null, 
                    new ProductCondition { Operand = "All", Attribute = null }
                );

                /*
                 * The direct children of any node must have the same Operand. 
                 * For this example we will use CategoryL1 nodes as children of the root. 
                 * For a list of valid CategoryL1 through CategoryL5 values, see the Bing Category Taxonomy:
                 * http://advertise.bingads.microsoft.com/en-us/WWDocs/user/search/en-us/Bing_Category_Taxonomy.txt
                 */
                var animalsSubdivision = helper.AddSubdivision(
                    root,
                    new ProductCondition { Operand = "CategoryL1", Attribute = "Animals & Pet Supplies" }
                );

                /*
                 * If you use a CategoryL2 node, it must be a descendant (child or later) of a CategoryL1 node. 
                 * In other words you cannot have a CategoryL2 node as parent of a CategoryL1 node. 
                 * For this example we will a CategoryL2 node as child of the CategoryL1 Animals & Pet Supplies node. 
                 */
                var petSuppliesSubdivision = helper.AddSubdivision(
                    animalsSubdivision,
                    new ProductCondition { Operand = "CategoryL2", Attribute = "Pet Supplies" }
                );

                var brandA = helper.AddUnit(
                    petSuppliesSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = "Brand A" },
                    0.35,
                    false
                );

                /*
                 * If you won't bid on Brand B, set the helper method's bidAmount to '0' and isNegative to true. 
                 * The helper method will create a NegativeAdGroupCriterion and apply the condition.
                 */
                var brandB = helper.AddUnit(
                    petSuppliesSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = "Brand B" },
                    0,
                    true
                );

                var otherBrands = helper.AddUnit(
                    petSuppliesSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = null },
                    0.35,
                    false
                );

                var otherPetSupplies = helper.AddUnit(
                    animalsSubdivision,
                    new ProductCondition { Operand = "CategoryL2", Attribute = null },
                    0.35,
                    false
                );

                var electronics = helper.AddUnit(
                    root,
                    new ProductCondition { Operand = "CategoryL1", Attribute = "Electronics" },
                    0.35,
                    false
                );

                var otherCategoryL1 = helper.AddUnit(
                    root,
                    new ProductCondition { Operand = "CategoryL1", Attribute = null },
                    0.35,
                    false
                );

                OutputStatusMessage("Applying product partitions to the ad group . . . \n");
                applyProductPartitionActionsResponse = await ApplyProductPartitionActionsAsync(helper.PartitionActions);

                // To retrieve product partitions after they have been applied, call GetAdGroupCriterionsByAdGroupId. 
                // The product partition with ParentCriterionId set to null is the root node.

                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                );

                /*
                 * The product partition group tree now has 9 nodes. 
                 
                   All other (Root Node)
                    |
                    +-- Animals & Pet Supplies (CategoryL1)
                    |    |
                    |    +-- Pet Supplies (CategoryL2)
                    |    |    |
                    |    |    +-- Brand A
                    |    |    |    
                    |    |    +-- Brand B
                    |    |    |    
                    |    |    +-- All other (Brand)
                    |    |         
                    |    +-- All other (CategoryL2)
                    |        
                    +-- Electronics (CategoryL1)
                    |   
                    +-- All other (CategoryL1)

                 */

                OutputStatusMessage("The product partition group tree now has 9 nodes: \n");
                OutputProductPartitions(adGroupCriterions);

                #endregion InitializeTree

                #region UpdateTree

                /*
                 * Let's replace the Electronics (CategoryL1) node created above with an Electronics (CategoryL1) node that 
                 * has children i.e. Brand C (Brand), Brand D (Brand), and All other (Brand) as follows: 
                 
                    Electronics (CategoryL1)
                    |
                    +-- Brand C (Brand)
                    |
                    +-- Brand D (Brand)
                    |
                    +-- All other (Brand)
           
                 */

                helper = new PartitionActionHelper(adGroupIds[0]);

                /*
                 * To replace a node we must know its Id and its ParentCriterionId. In this case the parent of the node 
                 * we are replacing is All other (Root Node), and was created at Index 1 of the previous ApplyProductPartitionActions call. 
                 * The node that we are replacing is Electronics (CategoryL1), and was created at Index 8. 
                 */
                var rootId = applyProductPartitionActionsResponse.AdGroupCriterionIds[1];
                electronics.Id = applyProductPartitionActionsResponse.AdGroupCriterionIds[8];
                helper.DeletePartition(electronics);

                var parent = new BiddableAdGroupCriterion() { Id = rootId };

                var electronicsSubdivision = helper.AddSubdivision(
                    parent,
                    new ProductCondition { Operand = "CategoryL1", Attribute = "Electronics" }
                );

                var brandC = helper.AddUnit(
                    electronicsSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = "Brand C" },
                    0.35,
                    false
                );

                var brandD = helper.AddUnit(
                    electronicsSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = "Brand D" },
                    0.35,
                    false
                );

                var otherElectronicsBrands = helper.AddUnit(
                    electronicsSubdivision,
                    new ProductCondition { Operand = "Brand", Attribute = null },
                    0.35,
                    false
                );

                OutputStatusMessage(
                    "Updating the product partition group to refine Electronics (CategoryL1) with 3 child nodes . . . \n"
                );
                applyProductPartitionActionsResponse = await ApplyProductPartitionActionsAsync(helper.PartitionActions);
                
                adGroupCriterions = await GetAdGroupCriterionsByAdGroupIdAsync(
                    adGroupIds[0],
                    CriterionType.ProductPartition
                );

                /*
                 * The product partition group tree now has 12 nodes, including the children of Electronics (CategoryL1):
                 
                   All other (Root Node)
                    |
                    +-- Animals & Pet Supplies (CategoryL1)
                    |    |
                    |    +-- Pet Supplies (CategoryL2)
                    |    |    |
                    |    |    +-- Brand A
                    |    |    |    
                    |    |    +-- Brand B
                    |    |    |    
                    |    |    +-- All other (Brand)
                    |    |         
                    |    +-- All other (CategoryL2)
                    |        
                    +-- Electronics (CategoryL1)
                    |    |
                    |    +-- Brand C (Brand)
                    |    |
                    |    +-- Brand D (Brand)
                    |    |
                    |    +-- All other (Brand)
                    |   
                    +-- All other (CategoryL1)
                 
                 */

                OutputStatusMessage(
                    "The product partition group tree now has 12 nodes, including the children of Electronics (CategoryL1): \n"
                );
                OutputProductPartitions(adGroupCriterions);

                #endregion UpdateTree

                #endregion ManageAdGroup

                #region ManageAds

                /*
                 * Create a product ad. You must add at least one ProductAd to the corresponding ad group. 
                 * A ProductAd is not used directly for delivered ad copy. Instead, the delivery engine generates 
                 * product ads from the product details that it finds in your Bing Merchant Center store's product catalog. 
                 * The primary purpose of the ProductAd object is to provide promotional text that the delivery engine 
                 * adds to the product ads that it generates. For example, if the promotional text is set to 
                 * “Free shipping on $99 purchases”, the delivery engine will set the product ad’s description to 
                 * “Free shipping on $99 purchases.”
                 */

                var ads = new Ad[] {
                    new ProductAd 
                    {
                        PromotionalText = "Free shipping on $99 purchases."
                    },
                };

                AddAdsResponse addAdsResponse = await AddAdsAsync(adGroupIds[0], ads);
                OutputAdResults(ads, addAdsResponse.AdIds, addAdsResponse.PartialErrors);

                #endregion ManageAds
                
                #region CleanUp

                /* Delete the campaign, ad group, criterion, and ad that were previously added. 
                 * You should remove this region if you want to view the added entities in the 
                 * Bing Ads web application or another tool.
                 */

                DeleteCampaignsAsync(authorizationData.AccountId, new[] { campaignIds[0] });
                OutputStatusMessage(String.Format("Deleted CampaignId {0}\n", campaignIds[0]));

                #endregion CleanUp
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Campaign Management service exceptions
            catch (FaultException<Microsoft.BingAds.CampaignManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.CampaignManagement.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.CampaignManagement.EditorialApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
Beispiel #58
0
 public void AddToAd(Ad ad)
 {
     base.AddObject("Ad", ad);
 }
Beispiel #59
0
        public ActionResult edit(FormCollection collection)
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get the return url
            string returnUrl = collection["returnUrl"];
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Get all the form values
            Int32 id = Convert.ToInt32(collection["txtId"]);
            Int32 language_id = Convert.ToInt32(collection["selectLanguage"]);
            string name = collection["txtName"];
            string url = collection["txtUrl"];
            string ad_slot = collection["selectAdSlot"];
            string ad_code = collection["txtDescription"];
            bool inactive = Convert.ToBoolean(collection["cbInactive"]);
            string keywords = collection["txtSearch"];
            Int32 currentPage = Convert.ToInt32(collection["hiddenPage"]);

            // Get the default admin language id
            Int32 adminLanguageId = currentDomain.back_end_language;

            // Get translated texts
            KeyStringList tt = StaticText.GetAll(adminLanguageId, "id", "ASC");

            // Get the ad
            Ad ad = Ad.GetOneById(id);
            bool postExists = true;

            // Check if the ad exists
            if (ad == null)
            {
                // Create an empty ad
                ad = new Ad();
                postExists = false;
            }

            // Update values
            ad.name = name;
            ad.language_id = language_id;
            ad.ad_slot = ad_slot;
            ad.ad_code = ad_code;
            ad.inactive = inactive;

            // Check if the user wants to do a search
            if (collection["btnSearch"] != null)
            {
                // Set form values
                ViewBag.Keywords = keywords;
                ViewBag.CurrentPage = currentPage;
                ViewBag.Ad = ad;
                ViewBag.TranslatedTexts = tt;
                ViewBag.ReturnUrl = returnUrl;

                // Return the edit view
                return View("edit");
            }

            // Check if the user wants to do a search
            if (collection["btnPreviousPage"] != null)
            {
                // Set form values
                ViewBag.Keywords = keywords;
                ViewBag.CurrentPage = currentPage - 1;
                ViewBag.Ad = ad;
                ViewBag.TranslatedTexts = tt;
                ViewBag.ReturnUrl = returnUrl;

                // Return the edit view
                return View("edit");
            }

            // Check if the user wants to do a search
            if (collection["btnNextPage"] != null)
            {
                // Set form values
                ViewBag.Keywords = keywords;
                ViewBag.CurrentPage = currentPage + 1;
                ViewBag.Ad = ad;
                ViewBag.TranslatedTexts = tt;
                ViewBag.ReturnUrl = returnUrl;

                // Return the edit view
                return View("edit");
            }

            // Create a error message
            string errorMessage = string.Empty;

            // Check for errors in the ad
            if (ad.language_id == 0)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_select_value"), tt.Get("language").ToLower()) + "<br/>";
            }
            if (ad.name.Length > 50)
            {
                errorMessage += "&#149; " + String.Format(tt.Get("error_field_length"), tt.Get("name"), "50") + "<br/>";
            }

            // Check if there is errors
            if (errorMessage == string.Empty)
            {
                // Check if we should add or update the ad
                if (postExists == false)
                {
                    // Add the ad
                    Ad.Add(ad);
                }
                else
                {
                    // Update the ad
                    Ad.Update(ad);
                }

                // Redirect the user to the list
                return Redirect(returnUrl);
            }
            else
            {
                // Set form values
                ViewBag.ErrorMessage = errorMessage;
                ViewBag.Keywords = keywords;
                ViewBag.CurrentPage = currentPage;
                ViewBag.TranslatedTexts = tt;
                ViewBag.Ad = ad;
                ViewBag.ReturnUrl = returnUrl;

                // Return the edit view
                return View("edit");
            }

        } // End of the edit method
Beispiel #60
0
	private void OnAdStarted(Ad ad)
	{
		// this is where you mute the sound and toggle buttons if necessary
		switch (ad.AdFormat)
		{
		case AdFormat.OFFER_WALL:
			ofwAd = null;
			break;
		case AdFormat.REWARDED_VIDEO:
			videoAd = null;
			break;
		case AdFormat.INTERSTITIAL:
			interstitialAd = null;
			break;
		default:
			break;
		}
	}