Example #1
0
        public void AddKeyWordsToAdGroup()
        {
            CampaignLo campaignDto = new CampaignLo
            {
                Name      = DateTime.Now.ToString(),
                StartDate = DateTime.Now,
                EndDate   = DateTime.Now.AddYears(1),
                Budget    = new BudgetLo
                {
                    Name        = DateTime.Now.ToString(),
                    MicroAmount = 5000000
                }
            };
            var campaign = Campaigns.CreateCampaign(new AdWordsUser(), campaignDto);

            AdGroupLo adGroupDotLo = new AdGroupLo
            {
                CampaignId = campaign.value[0].id,
                Name       = DateTime.Now.ToString(),
                KeyWords   = "hej, med dig"
            };
            var addedAdGroup = AdGroupAdwords.CreateAdGroup(new AdWordsUser(), adGroupDotLo);

            // Act
            var result = AdWordsKeyword.AddKeyWordsToAdGroup(new AdWordsUser(), addedAdGroup.value[0].id, adGroupDotLo.KeyWords);

            // Assert
            Assert.AreEqual(2, result.value.Length);
        }
Example #2
0
    private void GoToNextCampaign()
    {
        switch (currentCamp)
        {
        case Campaigns.CateringToTheRich:
            currentCamp = Campaigns.MysteriousEntity;
            GameManager.instance.ChangeInGameState(InGameStates.JobSelect);
            break;

        case Campaigns.MysteriousEntity:
            currentCamp = Campaigns.FinalTest;
            GameManager.instance.ChangeInGameState(InGameStates.JobSelect);
            break;

        case Campaigns.FinalTest:
            GameManager.instance.ChangeInGameState(InGameStates.MoneyEnding);     // go to ending
            break;

        default:
            Debug.LogError("Current Campaign " + currentCamp + " not setup.");
            return;
        }

        GameObject.FindGameObjectWithTag("powercore").gameObject.GetComponent <RoomStats>().UpgradePower();

        SaveCampaignData();
    }
Example #3
0
        public void CreateAdGroupTest()
        {
            // Assert
            CampaignLo campaignDto = new CampaignLo
            {
                Name      = DateTime.Now.ToString(),
                StartDate = DateTime.Now,
                EndDate   = DateTime.Now.AddYears(1),
                Budget    = new BudgetLo
                {
                    Name        = DateTime.Now.ToString(),
                    MicroAmount = 5000000
                }
            };
            var campaign = Campaigns.CreateCampaign(new AdWordsUser(), campaignDto);

            AdGroupLo adGroupDto = new AdGroupLo
            {
                CampaignId = campaign.value[0].id,
                Name       = DateTime.Now.ToString(),
                KeyWords   = "hej, med dig"
            };

            // Act
            var result = AdGroupAdwords.CreateAdGroup(new AdWordsUser(), adGroupDto);

            // Assert
            Assert.AreEqual(adGroupDto.CampaignId, result.value[0].campaignId);
            Assert.AreEqual(2, (int)result.value[0].status);
        }
Example #4
0
        public void GetAll()
        {
            // Arrange
            var limit  = 2;
            var offset = 0;

            var mockRepository = new MockRepository(MockBehavior.Strict);
            var mockClient     = mockRepository.Create <IClient>();

            mockClient
            .Setup(c => c.GetAsync($"{ENDPOINT}?limit={limit}&offset={offset}", It.IsAny <CancellationToken>()))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(MULTIPLE_CAMPAIGNS_JSON)
            })
            .Verifiable();

            var campaigns = new Campaigns(mockClient.Object, ENDPOINT);

            // Act
            var result = campaigns.GetAllAsync(limit, offset, CancellationToken.None).Result;

            // Assert
            result.ShouldNotBeNull();
            result.Length.ShouldBe(2);
        }
Example #5
0
        public ActionResult RejectCampaign(Campaigns model)
        {
            object i = model.id;

            Models.MongoDBHelper.MongoDBUpdateCampaign(i, "Rejected");
            return(RedirectToAction("ViewRequests", new { Message = ManageMessageId.UpdatedRequestSuccess }));
        }
Example #6
0
 /// <summary>
 /// Adds another LoaderInfo to the current result set.
 /// </summary>
 /// <param name="info">Additional LoaderInfo</param>
 public void AddRange(LoaderInfo info)
 {
     Campaigns.AddRange(info.Campaigns);
     Errors.AddRange(info.Errors);
     Levels.AddRange(info.Levels);
     Players.AddRange(info.Players);
 }
Example #7
0
        public void SendNow()
        {
            // Arrange
            var campaignId = 986724;

            var apiResponse = @"{
				'id': 986724,
				'status': 'Scheduled'
			}"            ;

            var mockRepository = new MockRepository(MockBehavior.Strict);
            var mockClient     = mockRepository.Create <IClient>();

            mockClient
            .Setup(c => c.PostAsync($"{ENDPOINT}/{campaignId}/schedules/now", (JObject)null, It.IsAny <CancellationToken>()))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(apiResponse)
            })
            .Verifiable();

            var campaigns = new Campaigns(mockClient.Object, ENDPOINT);

            // Act
            campaigns.SendNowAsync(campaignId, CancellationToken.None).Wait();

            // Assert
        }
Example #8
0
 public void AddCampaign(Campaign campaign)
 {
     if (Campaigns.Find(x => x.Id == campaign.Id) == null)
     {
         Campaigns.Add(campaign);
     }
 }
Example #9
0
        private string RemovePromocode(Log log, Campaigns campaigns, SendSMS sendSMS)
        {
            var db = new WebSMSEntities1();

            if (!campaigns.MessageText.Contains('#'))
            {
                return("Ok");
            }
            int    length    = campaigns.MessageText.Count(x => x == '#');
            string promocode = sendSMS.MessageText.Substring(campaigns.MessageText.IndexOf('#'), length);

            if (db.PromoCodes.Any(
                    x =>
                    x.IdCampaign == campaigns.IdCampaign && x.IdClient == campaigns.IdClient &&
                    x.PromoCode == promocode && x.IsUsed))
            {
                var promoCodeRecord =
                    db.PromoCodes.First(
                        x =>
                        x.IdCampaign == campaigns.IdCampaign && x.IdClient == campaigns.IdClient &&
                        x.PromoCode == promocode && x.IsUsed);

                promoCodeRecord.IsUsed = false;
                db.SaveChanges();
                return("Ok");
            }
            return("Ok");
        }
Example #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CakeMailRestClient"/> class.
        /// </summary>
        /// <param name="apiKey">The API Key received from CakeMail</param>
        /// <param name="host">The host where the API is hosted. The default is api.wbsrvc.com</param>
        /// <param name="httpClient">Allows you to inject your own HttpClient. This is useful, for example, to setup the HtppClient with a proxy</param>
        public CakeMailRestClient(string apiKey, string host = DEFAULT_HOST, HttpClient httpClient = null)
        {
            _mustDisposeHttpClient = httpClient == null;
            _httpClient            = httpClient;

            ApiKey    = apiKey;
            BaseUrl   = new Uri($"https://{host.TrimEnd('/')}/");
            Version   = typeof(CakeMailRestClient).GetTypeInfo().Assembly.GetName().Version.ToString();
            UserAgent = $"CakeMail .NET REST Client/{Version} (+https://github.com/Jericho/CakeMail.RestClient)";

            _fluentClient = new FluentClient(this.BaseUrl, httpClient)
                            .SetUserAgent(this.UserAgent);

            _fluentClient.BaseClient.DefaultRequestHeaders.Add("apikey", this.ApiKey);

            _fluentClient.Filters.Remove <DefaultErrorFilter>();
            _fluentClient.Filters.Add(new DiagnosticHandler());
            _fluentClient.Filters.Add(new CakeMailErrorHandler());

            Campaigns        = new Campaigns(_fluentClient);
            Clients          = new Clients(_fluentClient);
            Countries        = new Countries(_fluentClient);
            Permissions      = new Permissions(_fluentClient);
            Lists            = new Lists(_fluentClient);
            Timezones        = new Timezones(_fluentClient);
            Mailings         = new Mailings(_fluentClient);
            Relays           = new Relays(_fluentClient);
            Segments         = new Segments(_fluentClient);
            Users            = new Users(_fluentClient);
            SuppressionLists = new SuppressionLists(_fluentClient);
            Templates        = new Templates(_fluentClient);
            Triggers         = new Triggers(_fluentClient);
        }
Example #11
0
        private Client(string apiKey, string username, string password, string baseUri, string apiVersion, HttpClient httpClient)
        {
            _mustDisposeHttpClient = httpClient == null;
            _httpClient            = httpClient;

#if DEBUG
            Version = "DEBUG";
#else
            var assemblyVersion = typeof(Client).GetTypeInfo().Assembly.GetName().Version;
            Version = $"{assemblyVersion.Major}.{assemblyVersion.Minor}.{assemblyVersion.Build}";
#endif

            _fluentClient = new FluentClient(new Uri($"{baseUri.TrimEnd('/')}/{apiVersion.TrimStart('/')}"), httpClient)
                            .SetUserAgent($"StrongGrid/{Version} (+https://github.com/Jericho/StrongGrid)")
                            .SetRequestCoordinator(new SendGridRetryStrategy());

            _fluentClient.Filters.Remove <DefaultErrorFilter>();
            _fluentClient.Filters.Add(new DiagnosticHandler());
            _fluentClient.Filters.Add(new SendGridErrorHandler());

            if (!string.IsNullOrEmpty(apiKey))
            {
                _fluentClient.SetBearerAuthentication(apiKey);
            }
            if (!string.IsNullOrEmpty(username))
            {
                _fluentClient.SetBasicAuthentication(username, password);
            }

            AccessManagement   = new AccessManagement(_fluentClient);
            Alerts             = new Alerts(_fluentClient);
            ApiKeys            = new ApiKeys(_fluentClient);
            Batches            = new Batches(_fluentClient);
            Blocks             = new Blocks(_fluentClient);
            Bounces            = new Bounces(_fluentClient);
            Campaigns          = new Campaigns(_fluentClient);
            Categories         = new Categories(_fluentClient);
            Contacts           = new Contacts(_fluentClient);
            CustomFields       = new CustomFields(_fluentClient);
            GlobalSuppressions = new GlobalSuppressions(_fluentClient);
            InvalidEmails      = new InvalidEmails(_fluentClient);
            IpAddresses        = new IpAddresses(_fluentClient);
            IpPools            = new IpPools(_fluentClient);
            Lists             = new Lists(_fluentClient);
            Mail              = new Mail(_fluentClient);
            Segments          = new Segments(_fluentClient);
            SenderIdentities  = new SenderIdentities(_fluentClient);
            Settings          = new Settings(_fluentClient);
            SpamReports       = new SpamReports(_fluentClient);
            Statistics        = new Statistics(_fluentClient);
            Subusers          = new Subusers(_fluentClient);
            Suppressions      = new Suppressions(_fluentClient);
            Teammates         = new Teammates(_fluentClient);
            Templates         = new Templates(_fluentClient);
            UnsubscribeGroups = new UnsubscribeGroups(_fluentClient);
            User              = new User(_fluentClient);
            WebhookSettings   = new WebhookSettings(_fluentClient);
            WebhookStats      = new WebhookStats(_fluentClient);
            Whitelabel        = new Whitelabel(_fluentClient);
        }
        public static string Description(Campaigns campaign)
        {
            switch (campaign)
            {
            case Campaigns.Growth:
                return("Increases the growth of the weakest pet who takes part. The growth gain is higher with higher growth of the other pets.");

            case Campaigns.Divinity:
                return("You can earn divinity with this campaign. The higher the stats of the pets who take part, the more you will receive.");

            case Campaigns.Food:
                return("You can find pet food here. Anything from puny food to mighty food. \nThe stats of your pets don't matter here.");

            case Campaigns.Item:
                return("Search for pet stones. The higher the stats of the pets who take part, the more you will receive. You also have a chance to find rare items like godly liquid, chakra pill or a lucky draw!");

            case Campaigns.Level:
                return("If your pets are bored of fighting clones, this is the right campaign for them. You will gain levels. The higher the growth and stats of the pets, the more levels you gain.");

            case Campaigns.Multiplier:
                return("Increases the pet multiplier and even the cap of the pet rebirth multiplier.");

            case Campaigns.GodPower:
                return("Your pets have a chance to find one or more god power. The higher the total stats of the pets, the higher the chance to find it.");

            default:
                return(string.Empty);
            }
        }
Example #13
0
        public async Task UpdateAsync()
        {
            // Arrange
            var campaignId         = 986724;
            var title              = "March Newsletter";
            var suppressionGroupId = 42;
            var senderId           = 124451;

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(new HttpMethod("PATCH"), Utils.GetSendGridApiUri(ENDPOINT, campaignId)).Respond("application/json", SINGLE_CAMPAIGN_JSON);

            var client    = Utils.GetFluentClient(mockHttp);
            var campaigns = new Campaigns(client);

            // Act
            var result = await campaigns.UpdateAsync(campaignId, title, suppressionGroupId, null, null, null, null, null, null, senderId, null, null, null, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            result.ShouldNotBeNull();
            result.Id.ShouldBe(986724);
            result.Title.ShouldBe(title);
        }
Example #14
0
        public async Task RescheduleAsync()
        {
            // Arrange
            var campaignId = 986724;
            var sendOn     = DateTime.UtcNow.AddHours(15);

            var apiResponse = @"{
				'id': 986724,
				'send_at': 1489451436,
				'status': 'Scheduled'
			}"            ;

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(new HttpMethod("PATCH"), Utils.GetSendGridApiUri(ENDPOINT, campaignId, "schedules")).Respond("application/json", apiResponse);

            var client    = Utils.GetFluentClient(mockHttp);
            var campaigns = new Campaigns(client);

            // Act
            await campaigns.RescheduleAsync(campaignId, sendOn, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
        /// <summary>
        /// Verifies that all mission and global variable
        /// references point to valid missions and global variables.
        /// </summary>
        private void SanityCheckCampaigns()
        {
            Campaigns.ForEach(c => c.Missions.ForEach(m =>
            {
                if (Missions.Exists(otherMission => otherMission.InternalName == m.InternalName))
                {
                    throw new CampaignConfigException("Mission named " + m.InternalName + " exists more than once!");
                }

                Missions.Add(m);
            }));

            foreach (var campaign in Campaigns)
            {
                foreach (var mission in campaign.Missions)
                {
                    // I'm starting to feel a bit like a functional programmer

                    Array.ForEach(mission.UnlockMissions, VerifyMissionExists);
                    Array.ForEach(mission.UsedGlobalVariables, VerifyGlobalVariableExists);
                    Array.ForEach(mission.UnlockGlobalVariables, VerifyGlobalVariableExists);

                    mission.ConditionalMissionUnlocks.ForEach(conditionalMissionUnlock =>
                    {
                        VerifyMissionExists(conditionalMissionUnlock.UnlockMissionName);
                        conditionalMissionUnlock.PrerequisiteGlobalVariableStates.ForEach(gvc => VerifyGlobalVariableExists(gvc.GlobalVariableName));
                    });
                }
            }
        }
Example #16
0
        private string AddPromocode(Log log, Campaigns campaigns, SendSMS sendSMS)
        {
            var db = new WebSMSEntities1();

            if (!campaigns.MessageText.Contains('#'))
            {
                return("Ok");
            }
            if (
                db.PromoCodes.Any(
                    x => x.IdCampaign == campaigns.IdCampaign && x.IdClient == campaigns.IdClient && !x.IsUsed))
            {
                var promoCodeRecord =
                    db.PromoCodes.First(
                        x => x.IdCampaign == campaigns.IdCampaign && x.IdClient == campaigns.IdClient && !x.IsUsed);
                if (promoCodeRecord.PromoCode.Length != campaigns.MessageText.Count(x => x == '#'))
                {
                    log.Status = 16;
                    db.Log.Add(log);
                    db.SaveChanges();
                    return("Wrong promocode");
                }
                promoCodeRecord.IsUsed = true;
                string hash = new string('#', promoCodeRecord.PromoCode.Length);
                sendSMS.MessageText = campaigns.MessageText.Replace(hash, promoCodeRecord.PromoCode);
                db.SaveChanges();
                return("Ok");
            }
            log.Status = 17;
            db.Log.Add(log);
            db.SaveChanges();
            return("Promocodes have ended");
        }
        public SiteResponse <object> Add(Campaign cam)
        {
            //kampanya ekleme
            var response = new SiteResponse <object>();

            response.Status = cam == null;
            if (response.Status)
            {
                response.Message = "Kampanya tanımsız";
                return(response);
            }
            var newCampaign = new Campaigns();

            newCampaign.AddedDate       = DateTime.Now;
            newCampaign.CompanyName     = cam.CompanyName;
            newCampaign.Companies_Id    = cam.Companies_Id;
            db.Entry(newCampaign).State = EntityState.Added;
            db.SaveChanges();
            response.Status = newCampaign.Id != 0;
            if (response.Status)
            {
                response.Message = "Kampanya eklendi";
                return(response);
            }
            else
            {
                response.Message = "Kampanya id tanımsız";
                return(response);
            }
        }
Example #18
0
        public void GetScheduledDate()
        {
            // Arrange
            var campaignId  = 986724;
            var apiResponse = @"{
				'send_at': 1489771528
			}"            ;

            var mockRepository = new MockRepository(MockBehavior.Strict);
            var mockClient     = mockRepository.Create <IClient>();

            mockClient
            .Setup(c => c.GetAsync($"{ENDPOINT}/{campaignId}/schedules", It.IsAny <CancellationToken>()))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(apiResponse)
            })
            .Verifiable();

            var campaigns = new Campaigns(mockClient.Object, ENDPOINT);

            // Act
            var result = campaigns.GetScheduledDateAsync(campaignId, CancellationToken.None).Result;

            // Assert
            result.ShouldNotBeNull();
            result.HasValue.ShouldBeTrue();
        }
Example #19
0
        public void Reschedule()
        {
            // Arrange
            var campaignId = 986724;
            var sendOn     = DateTime.UtcNow.AddHours(15);

            var apiResponse = @"{
				'id': 986724,
				'send_at': 1489451436,
				'status': 'Scheduled'
			}"            ;

            var mockRepository = new MockRepository(MockBehavior.Strict);
            var mockClient     = mockRepository.Create <IClient>();

            mockClient
            .Setup(c => c.PatchAsync($"{ENDPOINT}/{campaignId}/schedules", It.IsAny <JObject>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(apiResponse)
            })
            .Verifiable();

            var campaigns = new Campaigns(mockClient.Object, ENDPOINT);

            // Act
            campaigns.RescheduleAsync(campaignId, sendOn, CancellationToken.None).Wait();

            // Assert
        }
        /// <summary>
        /// get campaigns from mailer queue
        /// </summary>
        /// <returns></returns>
        private List <Campaigns> getCampaigns()
        {
            //List<Campaigns>
            campaigns = new List <Campaigns>();
            DataSet ds = new DataSet();

            ds            = campaignChecker();
            CampaignCount = ds.Tables[0].Rows.Count;
            if (ds.Tables[0].Rows.Count > 0)
            {
                Campaigns camp = null;
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    camp                    = new Campaigns();
                    camp.CampaignID         = (int)row["CampaignID"];
                    camp.IdentifierCampaign = row["IdentifierCampaign"].ToString();
                    campaigns.Add(camp);
                }
                return(campaigns);
            }
            else
            {
                return(null);
            }
        }
Example #21
0
        public void Update()
        {
            // Arrange
            var campaignId         = 986724;
            var title              = "March Newsletter";
            var suppressionGroupId = 42;
            var senderId           = 124451;

            var mockRepository = new MockRepository(MockBehavior.Strict);
            var mockClient     = mockRepository.Create <IClient>();

            mockClient
            .Setup(c => c.PatchAsync($"{ENDPOINT}/{campaignId}", It.IsAny <JObject>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(SINGLE_CAMPAIGN_JSON)
            })
            .Verifiable();

            var campaigns = new Campaigns(mockClient.Object, ENDPOINT);

            // Act
            var result = campaigns.UpdateAsync(campaignId, title, suppressionGroupId, null, null, null, null, null, null, senderId, null, null, CancellationToken.None).Result;

            // Assert
            result.ShouldNotBeNull();
            result.Id.ShouldBe(986724);
            result.Title.ShouldBe(title);
        }
Example #22
0
        public void GetAdGroups()
        {
            // Assert
            CampaignLo campaignDto = new CampaignLo
            {
                Name      = DateTime.Now.ToString(),
                StartDate = DateTime.Now,
                EndDate   = DateTime.Now.AddYears(1),
                Budget    = new BudgetLo
                {
                    Name        = DateTime.Now.ToString(),
                    MicroAmount = 5000000
                }
            };
            var campaign = Campaigns.CreateCampaign(new AdWordsUser(), campaignDto);

            AdGroupLo adGroupDtoLo = new AdGroupLo
            {
                CampaignId = campaign.value[0].id,
                Name       = DateTime.Now.ToString(),
                KeyWords   = "hej, med dig"
            };

            // Act
            var adGroup = AdGroupAdwords.CreateAdGroup(new AdWordsUser(), adGroupDtoLo);
            var result  = AdGroupAdwords.GetAdGroups(new AdWordsUser(), campaign.value[0].id);

            // Assert
            Assert.AreNotEqual(0, result.Count);
            Assert.AreEqual(adGroup.value[0].name, result.ElementAt(0).name);
        }
Example #23
0
        public async Task ScheduleAsync()
        {
            // Arrange
            var campaignId = 986724;
            var sendOn     = DateTime.UtcNow.AddHours(5);

            var apiResponse = @"{
				""id"": 986724,
				""send_at"": 1489771528,
				""status"": ""Scheduled""
			}"            ;

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Post, Utils.GetSendGridApiUri(ENDPOINT, campaignId, "schedules")).Respond("application/json", apiResponse);

            var client    = Utils.GetFluentClient(mockHttp);
            var campaigns = new Campaigns(client);

            // Act
            await campaigns.ScheduleAsync(campaignId, sendOn, CancellationToken.None).ConfigureAwait(false);

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
Example #24
0
        /// <summary>
        ///     Create a client that connects to the SendGrid Web API
        /// </summary>
        /// <param name="apiKey">Your SendGrid API Key</param>
        /// <param name="baseUri">Base SendGrid API Uri</param>
        public Client(string apiKey, string baseUri = "https://api.sendgrid.com", string apiVersion = "v3", HttpClient httpClient = null)
        {
            _baseUri = new Uri(string.Format("{0}/{1}", baseUri, apiVersion));
            _apiKey  = apiKey;

            Alerts             = new Alerts(this);
            ApiKeys            = new ApiKeys(this);
            Blocks             = new Blocks(this);
            Campaigns          = new Campaigns(this);
            Categories         = new Categories(this);
            Contacts           = new Contacts(this);
            CustomFields       = new CustomFields(this);
            GlobalSuppressions = new GlobalSuppressions(this);
            Lists             = new Lists(this);
            Mail              = new Mail(this);
            Segments          = new Segments(this);
            SenderIdentities  = new SenderIdentities(this);
            Settings          = new Settings(this);
            Statistics        = new Statistics(this);
            Suppressions      = new Suppressions(this);
            Templates         = new Templates(this);
            UnsubscribeGroups = new UnsubscribeGroups(this);
            User              = new User(this);
            Version           = typeof(Client).GetTypeInfo().Assembly.GetName().Version.ToString();

            _mustDisposeHttpClient  = (httpClient == null);
            _httpClient             = httpClient ?? new HttpClient();
            _httpClient.BaseAddress = _baseUri;
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MEDIA_TYPE));
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
            _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", string.Format("StrongGrid/{0}", Version));
        }
Example #25
0
 public void Seed(Model model)
 {
     if (model.Categories != null)
     {
         Categories.AddRange(model.Categories);
     }
     if (model.Products != null)
     {
         Products.AddRange(model.Products);
     }
     if (model.Regions != null)
     {
         Regions.AddRange(model.Regions);
     }
     if (model.Shops != null)
     {
         Shops.AddRange(model.Shops);
     }
     if (model.Customers != null)
     {
         Customers.AddRange(model.Customers);
     }
     if (model.Campaigns != null)
     {
         Campaigns.AddRange(model.Campaigns);
     }
     if (model.Sales != null)
     {
         Sales.AddRange(model.Sales);
     }
     if (model.LeadStates != null)
     {
         LeadStates.AddRange(model.LeadStates);
     }
     if (model.LeadHistory != null)
     {
         LeadHistory.AddRange(model.LeadHistory);
     }
     if (model.Budget != null)
     {
         Budget.AddRange(model.Budget);
     }
     if (model.RegionWiseSales != null)
     {
         RegionWiseSales.AddRange(model.RegionWiseSales);
     }
     if (model.Opportunities != null)
     {
         Opportunities.AddRange(model.Opportunities);
     }
     if (model.ProfitAndSales != null)
     {
         ProfitAndSales.AddRange(model.ProfitAndSales);
     }
     if (model.RegionSales != null)
     {
         RegionSales.AddRange(model.RegionSales);
     }
     SaveChanges();
 }
Example #26
0
        public void GetCampaignsTest()
        {
            // Arrange
            CampaignLo campaignDto = new CampaignLo
            {
                Name      = DateTime.Now.ToString(),
                StartDate = DateTime.Now,
                EndDate   = DateTime.Now.AddYears(1),
                Budget    = new BudgetLo
                {
                    Name        = DateTime.Now.ToString(),
                    MicroAmount = 5000000
                }
            };


            // Act
            var             campaign  = Campaigns.CreateCampaign(new AdWordsUser(), campaignDto);
            List <Campaign> campaigns = Campaigns.GetCampaigns(new AdWordsUser(), true);

            Campaign[] camp = campaigns.Where(campa => campa.name == campaignDto.Name).ToArray();

            // Assert
            Assert.AreNotEqual(0, campaigns.Count);
            Assert.AreEqual(campaign.value[0].id, camp[0].id);
        }
Example #27
0
        public void CreateCampaignTest()
        {
            // Arrange
            CampaignLo campaignDto = new CampaignLo
            {
                Name      = DateTime.Now.ToString(),
                StartDate = DateTime.Now,
                EndDate   = DateTime.Now.AddYears(1),
                Budget    = new BudgetLo
                {
                    Name        = DateTime.Now.ToString(),
                    MicroAmount = 5000000
                }
            };

            // Act
            CampaignReturnValue campaign = Campaigns.CreateCampaign(new AdWordsUser(), campaignDto);

            // Assert
            Assert.AreEqual(DateTime.Now.ToString("yyyyMMdd"), campaign.value[0].startDate);
            Assert.AreEqual(DateTime.Now.AddYears(1).ToString("yyyyMMdd"), campaign.value[0].endDate);
            Assert.AreEqual(1, (int)campaign.value[0].status);
            Assert.AreEqual(true, campaign.value[0].networkSetting.targetGoogleSearch);
            Assert.AreEqual(false, campaign.value[0].networkSetting.targetPartnerSearchNetwork);
        }
        private void btn_show_battle_Click(object sender, RoutedEventArgs e)
        {
            _response = _client.GetAsync("").Result;

            if (_response.IsSuccessStatusCode)
            {
                var campaignsString = _response.Content.ReadAsStringAsync().Result; // ReadAsA sync<IEnumerable<Employee>>().Result;

                var objects = JObject.Parse(campaignsString);                       // parse as array
                _campaings = objects.ToObject <Campaigns>();

                _battleId = Int32.Parse(txtbx_battle_id.Text);
                _currentBattles.Add(_battleId);
                var chosenBattle = _campaings.Battles.Values.Where(x => x.Id == _battleId);
                var battlesList  = _campaings.Battles.Values.Where(x => _currentBattles.Contains(x.Id)).ToList();
                tabControlBattles.ItemsSource = battlesList;

                //var tabItemNew = new TabItem { Header = _battleId.ToString()};
                //var tabItemNewIndex = tabControlBattles.Items.Add(tabItemNew);
                //tabItemNew.Focus();
            }
            else
            {
                MessageBox.Show("Error Code" + _response.StatusCode + " : Message - " + _response.ReasonPhrase);
            }
        }
Example #29
0
        private Client(string apiKey, string username, string password, HttpClient httpClient, bool disposeClient, StrongGridClientOptions options)
        {
            _mustDisposeHttpClient = disposeClient;
            _httpClient            = httpClient;
            _options = options ?? GetDefaultOptions();

            _fluentClient = new FluentClient(new Uri(SENDGRID_V3_BASE_URI), httpClient)
                            .SetUserAgent(Client.UserAgent)
                            .SetRequestCoordinator(new SendGridRetryStrategy());

            _fluentClient.Filters.Remove <DefaultErrorFilter>();

            // Order is important: DiagnosticHandler must be first.
            // Also, the list of filters must be kept in sync with the filters in Utils.GetFluentClient in the unit testing project.
            _fluentClient.Filters.Add(new DiagnosticHandler(_options.LogLevelSuccessfulCalls, _options.LogLevelFailedCalls));
            _fluentClient.Filters.Add(new SendGridErrorHandler());

            if (!string.IsNullOrEmpty(apiKey))
            {
                _fluentClient.SetBearerAuthentication(apiKey);
            }
            if (!string.IsNullOrEmpty(username))
            {
                _fluentClient.SetBasicAuthentication(username, password);
            }

            AccessManagement   = new AccessManagement(_fluentClient);
            Alerts             = new Alerts(_fluentClient);
            ApiKeys            = new ApiKeys(_fluentClient);
            Batches            = new Batches(_fluentClient);
            Blocks             = new Blocks(_fluentClient);
            Bounces            = new Bounces(_fluentClient);
            Campaigns          = new Campaigns(_fluentClient);
            Categories         = new Categories(_fluentClient);
            Contacts           = new Contacts(_fluentClient);
            CustomFields       = new CustomFields(_fluentClient);
            Designs            = new Designs(_fluentClient);
            EmailActivities    = new EmailActivities(_fluentClient);
            EmailValidation    = new EmailValidation(_fluentClient);
            GlobalSuppressions = new GlobalSuppressions(_fluentClient);
            InvalidEmails      = new InvalidEmails(_fluentClient);
            IpAddresses        = new IpAddresses(_fluentClient);
            IpPools            = new IpPools(_fluentClient);
            Lists                = new Lists(_fluentClient);
            Mail                 = new Mail(_fluentClient);
            Segments             = new Segments(_fluentClient);
            SenderIdentities     = new SenderIdentities(_fluentClient);
            Settings             = new Settings(_fluentClient);
            SpamReports          = new SpamReports(_fluentClient);
            Statistics           = new Statistics(_fluentClient);
            Subusers             = new Subusers(_fluentClient);
            Suppressions         = new Suppressions(_fluentClient);
            Teammates            = new Teammates(_fluentClient);
            Templates            = new Templates(_fluentClient);
            UnsubscribeGroups    = new UnsubscribeGroups(_fluentClient);
            User                 = new User(_fluentClient);
            WebhookSettings      = new WebhookSettings(_fluentClient);
            WebhookStats         = new WebhookStats(_fluentClient);
            SenderAuthentication = new SenderAuthentication(_fluentClient);
        }
Example #30
0
        public void Schedule()
        {
            // Arrange
            var campaignId = 986724;
            var sendOn     = DateTime.UtcNow.AddHours(5);

            var apiResponse = @"{
				'id': 986724,
				'send_at': 1489771528,
				'status': 'Scheduled'
			}"            ;

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect(HttpMethod.Post, Utils.GetSendGridApiUri(ENDPOINT, campaignId, "schedules")).Respond("application/json", apiResponse);

            var client    = Utils.GetFluentClient(mockHttp);
            var campaigns = new Campaigns(client);

            // Act
            campaigns.ScheduleAsync(campaignId, sendOn, CancellationToken.None).Wait();

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
Example #31
0
 private AttributeValueViewModel PrepareAttributeValueViewModel(Campaigns.Model.AttributeValue attributeValue)
 {
     return new AttributeValueViewModel
     {
         AttributeId = attributeValue.AttributeId,
         Value = attributeValue.Value,
     };
 }
Example #32
0
 private CharacterViewModel PrepareCharacterViewModel(Campaigns.Model.Character character)
 {
     return new CharacterViewModel
     {
         Id = character.Id,
         Name = character.Name,
         Description = character.Description,
         LatestSheetId = character.SheetId,
         AttributeValues = character.Sheet.AttributeValues.Select(PrepareAttributeValueViewModel)
     };
 }
Example #33
0
 public void AddAttribute(Campaigns.Model.Attribute attrib)
 {
     if (_attributes.Values.Any(a => a.Id == attrib.Id))
     {
         throw new Exception(
             String.Format("Attribute calculation assertion failure: attribute already exists with ID {0} ({1})", attrib.Id, attrib.Name));
     }
     // var attrib = new Attribute { Id = AllocId(), Name = name, Category = category };
     _attributes.Add(AttributeKey(attrib.Name, attrib.Category), attrib);
     GetContributionsByAttribute(attrib);
     GetContributionsForAttribute(attrib);
 }
Example #34
0
 public void InsertCampaign()
 {
     var campaigns = new Campaigns();
     var campaign = new Campaign
                        {
                            Name = "Test",
                            Description = "Test"
                        };
     campaign = campaigns.Insert(campaign);
     Assert.AreNotEqual(0, campaign.Id);
     Assert.AreEqual("N", campaign.IsClosed);
 }
Example #35
0
 public bool IsAttributeContributing(Campaigns.Model.Attribute source)
 {
     return _memDb.Attributes.Any(a => a.Id == source.Id);
 }
 public static void AssertNoAttrib(this CalculationResult result, Campaigns.Model.Attribute attrib)
 {
     var count = result.AttributeValues.Count(val => val.Attribute == attrib);
     Assert.AreEqual(0, count);
 }
 public static void AssertAttribContributionFrom(this CalculationResult result, Campaigns.Model.Attribute attrib, Campaigns.Model.Attribute contributingAttrib)
 {
     var values = result.AttributeValues.Where(val => val.Attribute == attrib);
     Assert.IsTrue(values.Count() == 1);
 }
Example #38
0
 private int CompletePendingCalculation(Campaigns.Model.Attribute target)
 {
     var value = GetOrAddPendingValue(target);
     var contribsToTarget = GetRelevantContributionsTo(target).ToList();
     foreach (var contribution in contribsToTarget)
     {
         var source = contribution.Source;
         var sourceValue = null == source ? 0 : _completedValues[source.Id].Value;
         value.Value += contribution.Formula(sourceValue);
     }
     return SetCompleted(value);
 }
Example #39
0
 public ICollection<AttributeContribution> ContributionsTo(Campaigns.Model.Attribute target)
 {
     if (null == target)
         throw new ArgumentNullException("target");
     return _contributionsForAttributeId[target.Id];
 }
Example #40
0
 public IEnumerable<AttributeContribution> AllContributionsFrom(Campaigns.Model.Attribute source)
 {
     return _contributionsDb.ContributionsFrom(source);
 }
Example #41
0
        /// <summary>
        /// Populates the fields for multiple objects from the columns found in an open reader.
        /// </summary>
        ///
        /// <param name="rdr" type="IDataReader">An object that implements the IDataReader interface</param>
        ///
        /// <returns>Object of Campaigns</returns>
        ///
        /// <remarks>
        ///
        /// <RevisionHistory>
        /// Author				Date			Description
        /// DLGenerator			6/25/2012 02:05:58 PM		Created function
        /// 
        /// </RevisionHistory>
        ///
        /// </remarks>
        ///
        internal static Campaigns PopulateObjectsFromReaderWithCheckingReader(IDataReader rdr, DatabaseHelper oDatabaseHelper, string ConnectionString)
        {
            Campaigns list = new Campaigns();

            if (rdr.Read())
            {
                Campaign obj = new Campaign(ConnectionString);
                PopulateObjectFromReader(obj, rdr);
                list.Add(obj);
                while (rdr.Read())
                {
                    obj = new Campaign(ConnectionString);
                    PopulateObjectFromReader(obj, rdr);
                    list.Add(obj);
                }
                oDatabaseHelper.Dispose();
                return list;
            }
            else
            {
                oDatabaseHelper.Dispose();
                return null;
            }
        }
Example #42
0
 public bool IsAttributeContributing(Campaigns.Model.Attribute source)
 {
     return _contributingAttributes.Contains(source);
 }
Example #43
0
 public IEnumerable<AttributeContribution> AllContributionsTo(Campaigns.Model.Attribute target)
 {
     return _contributionsDb.ContributionsTo(target);
 }
Example #44
0
 private IEnumerable<AttributeContribution> GetRelevantContributionsTo(Campaigns.Model.Attribute target)
 {
     // direct contributions and contributions that are relevant to this calculation
     return _context.AllContributionsTo(target)
         .Where(contrib => null == contrib.Source || _context.IsAttributeContributing(contrib.Source));
 }
Example #45
0
 private IEnumerable<AttributeContribution> GetPendingContributionsTo(Campaigns.Model.Attribute target)
 {
     return from contrib in _context.AllContributionsTo(target)
            let dependency = contrib.Source
            where null != dependency &&
                  _context.IsAttributeContributing(dependency) &&
                  !_completedValues.ContainsKey(dependency.Id)
            select contrib;
 }
Example #46
0
        private AttributeValue GetOrAddPendingValue(Campaigns.Model.Attribute target)
        {
            AttributeValue result;
            if (!_pendingValues.TryGetValue(target.Id, out result))
            {
                result = new AttributeValue
                {
                    Attribute = target,
                    Value = 0,
                };
                AddValueAsPending(result);

            }
            return result;
        }
Example #47
0
 public static IEnumerable<Campaigns.Model.AttributeContribution> ContributionsTo(this ICalculationRules ctx, Campaigns.Model.Attribute target)
 {
     return ctx.AllContributionsTo(target)
         .Where(c => null == c.Source || ctx.IsAttributeContributing(c.Source));
 }
Example #48
0
 public ICollection<AttributeContribution> ContributionsFrom(Campaigns.Model.Attribute source)
 {
     if (null == source)
         throw new ArgumentNullException("source");
     return _contributionsByAttributeId[source.Id];
 }
Example #49
0
 public static IEnumerable<Campaigns.Model.AttributeContribution> ContributionsBy(this ICalculationRules ctx, Campaigns.Model.Attribute source)
 {
     return ctx.AllContributionsFrom(source)
         .Where(c => ctx.IsAttributeContributing(c.Target));
 }
 public static Campaigns CreateCampaigns(global::System.Guid campaignId, string campaignName, int cost, int costPerClick, int costPerDay, int costBase, bool isActive, global::System.DateTime startDate, global::System.DateTime endDate, string data)
 {
     Campaigns campaigns = new Campaigns();
     campaigns.CampaignId = campaignId;
     campaigns.CampaignName = campaignName;
     campaigns.Cost = cost;
     campaigns.CostPerClick = costPerClick;
     campaigns.CostPerDay = costPerDay;
     campaigns.CostBase = costBase;
     campaigns.IsActive = isActive;
     campaigns.StartDate = startDate;
     campaigns.EndDate = endDate;
     campaigns.Data = data;
     return campaigns;
 }
Example #51
0
        /// <summary>
        /// Populates the fields for multiple objects from the columns found in an open reader.
        /// </summary>
        ///
        /// <param name="rdr" type="IDataReader">An object that implements the IDataReader interface</param>
        ///
        /// <returns>Object of Campaigns</returns>
        ///
        /// <remarks>
        ///
        /// <RevisionHistory>
        /// Author				Date			Description
        /// DLGenerator			6/25/2012 02:05:58 PM		Created function
        /// 
        /// </RevisionHistory>
        ///
        /// </remarks>
        ///
        internal static Campaigns PopulateObjectsFromReader(IDataReader rdr, string ConnectionString)
        {
            Campaigns list = new Campaigns();

            while (rdr.Read())
            {
                Campaign obj = new Campaign(ConnectionString);
                PopulateObjectFromReader(obj,rdr);
                list.Add(obj);
            }
            return list;
        }
Example #52
0
        public static AttributeViewModel CreateViewModel(this IEntityStore<Campaigns.Model.AttributeContribution> db, Campaigns.Model.Attribute attribute)
        {
            if (null == attribute)
                return null;

            Mapper.CreateMap<Campaigns.Model.Attribute, AttributeViewModel>();
            Mapper.CreateMap<Campaigns.Model.AttributeContribution, AttributeContributionViewModel>();

            var viewModel = Mapper.Map<AttributeViewModel>(attribute);
            viewModel.ContributionsFrom = db.GetContributionsFromAttribute(attribute.Id).Select(Mapper.Map<AttributeContributionViewModel>);
            viewModel.ContributionsTo = db.GetContributionsToAttribute(attribute.Id).Select(Mapper.Map<AttributeContributionViewModel>);

            return viewModel;
        }
Example #53
0
 private IList<AttributeContribution> GetContributionsByAttribute(Campaigns.Model.Attribute attrib)
 {
     if (null == attrib)
         throw new ArgumentNullException("attrib");
     IList<AttributeContribution> contribs;
     if (!_contributionsByAttributeId.TryGetValue(attrib.Id, out contribs))
     {
         contribs = new List<AttributeContribution>();
         _contributionsByAttributeId.Add(attrib.Id, contribs);
     }
     return contribs;
 }
 public static void AssertAttribValue(this CalculationResult result, Campaigns.Model.Attribute attrib, int value)
 {
     var values = result.AttributeValues.Where(val => val.Attribute == attrib);
     Assert.IsTrue(values.Count() == 1);
     Assert.AreEqual(value, values.First().Value);
 }
Example #55
0
 public static IQueryable<Campaigns.Model.AttributeContribution> ContributionsFrom(this IEntityStore<AttributeContribution> db, Campaigns.Model.Attribute source)
 {
     return db.AsQueryable.Where(c => c.SourceId == source.Id);
 }
Example #56
0
 public void SetInitialValue(Campaigns.Model.Attribute attribute, int value)
 {
     _contributionsDb.Add(attribute.ConstantContributionFrom(null, value));
     _contributingAttributes.Add(attribute);
 }
 public void AddToCampaigns(Campaigns campaigns)
 {
     base.AddObject("Campaigns", campaigns);
 }
Example #58
0
 public static IQueryable<Campaigns.Model.AttributeContribution> ContributionsTo(this IEntityStore<AttributeContribution> db, Campaigns.Model.Attribute target)
 {
     return db.AsQueryable.Where(c => c.TargetId == target.Id);
 }