Exemplo n.º 1
0
		public updateDownloader(updateController instance, UpdateResult result) {
			_currentConfiguration = result.Configuration;
			_currentInstance = instance;
			_highestVersion = result.newUpdatePackages[result.newUpdatePackages.Count - 1].releaseInfo.Version;

			//WebClient initialisieren
			_wclDownload = new WebClient();

			_wclDownload.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);

			//Proxyeinstellungen setzen
			if (instance.proxyEnabled) {
				_wclDownload.Proxy = new WebProxy(new Uri(instance.proxyUrl + ":" + instance.proxyPort));
				if (!string.IsNullOrEmpty(instance.proxyUsername))
					_wclDownload.Proxy.Credentials = new NetworkCredential(instance.proxyUsername, instance.proxyPassword);
				else if (instance.proxyUseDefaultCredentials)
					_wclDownload.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
			}

			//Falls eine Authentifizierung erforderlich ist
			if (instance.authenticationMode == authenticationModes.Credentials) {
				_wclDownload.Credentials = new NetworkCredential(
					instance.authenticationUsername,
					instance.authenticationPassword);
			}

			//SSLFehler umleiten und ignorieren
			ServicePointManager.ServerCertificateValidationCallback += OnCheckSSLCert;

			//Urls erzeugen
			//updateInstaller 
			//UpdateInstaller - Manifest
			_urls = new List<string> {
										internalHelper.prepareUpdateLocation(instance.updateLocation) + "updateInstaller.zip",
										internalHelper.prepareUpdateLocation(instance.updateLocation) + "updateInstaller.xml"
									 };

			//Urls der Updatepakete erzeugen
			foreach (updatePackage package in result.newUpdatePackages)
				_urls.Add(internalHelper.prepareUpdateLocation(instance.updateLocation, "updates") + package.getFilename());

			_wclDownload.DownloadFileCompleted += _wclDownload_DownloadFileCompleted;
			_wclDownload.DownloadProgressChanged += _wclDownload_DownloadProgressChanged;

			//Temporäres Verzeichnis erstellen
			_tempDirectory = instance.internalSettings.downloadLocation;
			if (!Directory.Exists(_tempDirectory)) {
				Directory.CreateDirectory(_tempDirectory);
			}
		}
Exemplo n.º 2
0
        public object FindAndModifyAs(Type documentType, IMongoQuery query, IMongoSortBy sortBy, IMongoUpdate update, IMongoFields fields, bool returnNew, bool upsert, out UpdateResult result)
        {
            foreach (var document in QueryCompiler.Query(Documents, Documents2, query, sortBy, 0, 0))
            {
                // if old is needed then deep(!) clone before update //_131103_185751
                BsonDocument output = null;
                if (!returnNew)
                    output = document.DeepClone().AsBsonDocument;

                UpdateDocument(document, UpdateCompiler.GetFunction((IConvertibleToBsonDocument)update, null, false));

                if (returnNew)
                    output = document;

                // project
                if (fields != null)
                {
                    var project = FieldCompiler.GetFunction(fields);
                    output = project(output);
                }

                // if old is needed then return it as already deep cloned
                result = new SimpleUpdateResult(1, true);
                if (!returnNew && documentType == typeof(Dictionary))
                    return new Dictionary(output);
                else
                    // deserialize to required type
                    return BsonSerializer.Deserialize(output, documentType);
            }

            // not found, insert
            if (upsert)
            {
                var document = InsertNewDocument(query, update);

                result = new SimpleUpdateResult(1, false);
                return returnNew ? BsonSerializer.Deserialize(document, documentType) : null;
            }

            result = new SimpleUpdateResult(0, false);
            return null;
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ProposalLineItemService proposalLineItemService =
                       user.GetService <ProposalLineItemService>())
            {
                // Set the ID of the proposal line item to archive.
                long proposalLineItemId = long.Parse(_T("INSERT_PROPOSAL_LINE_ITEM_ID_HERE"));

                // Create statement to select a proposal line item by ID.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                    .AddValue("id", proposalLineItemId);

                // Set default for page.
                ProposalLineItemPage page = new ProposalLineItemPage();
                List <string>        proposalLineItemIds = new List <string>();

                try
                {
                    do
                    {
                        // Get proposal line items by statement.
                        page = proposalLineItemService.getProposalLineItemsByStatement(
                            statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            int i = page.startIndex;
                            foreach (ProposalLineItem proposalLineItem in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) Proposal line item with ID ='{1}' will be archived.", i++,
                                    proposalLineItem.id);
                                proposalLineItemIds.Add(proposalLineItem.id.ToString());
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                    Console.WriteLine("Number of proposal line items to be archived: {0}",
                                      proposalLineItemIds.Count);

                    if (proposalLineItemIds.Count > 0)
                    {
                        // Modify statement.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create action.
                        Google.Api.Ads.AdManager.v202108.ArchiveProposalLineItems action =
                            new Google.Api.Ads.AdManager.v202108.ArchiveProposalLineItems();

                        // Perform action.
                        UpdateResult result =
                            proposalLineItemService.performProposalLineItemAction(action,
                                                                                  statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine("Number of proposal line items archived: {0}",
                                              result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No proposal line items were archived.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Failed to archive proposal line items. Exception says \"{0}\"", e.Message);
                }
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user, long proposalId)
        {
            // Get the ProposalService.
            ProposalService proposalService =
                (ProposalService)user.GetService(DfpService.v201708.ProposalService);

            // Create statement to select the proposal.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :id")
                                                .OrderBy("id ASC")
                                                .Limit(1)
                                                .AddValue("id", proposalId);

            // Set default for page.
            ProposalPage  page        = new ProposalPage();
            List <string> proposalIds = new List <string>();
            int           i           = 0;

            try {
                do
                {
                    // Get proposals by statement.
                    page = proposalService.getProposalsByStatement(statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        foreach (Proposal proposal in page.results)
                        {
                            Console.WriteLine("{0}) Proposal with ID = '{1}', name = '{2}', and status ='{3}' " +
                                              "will be sent to Marketplace for buyer acceptance.",
                                              i++,
                                              proposal.id,
                                              proposal.name,
                                              proposal.status);
                            proposalIds.Add(proposal.id.ToString());
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of proposals to be sent to Marketplace: {0}", proposalIds.Count);

                if (proposalIds.Count > 0)
                {
                    // Modify statement for action.
                    statementBuilder.RemoveLimitAndOffset();

                    // Create action.
                    Google.Api.Ads.Dfp.v201708.RequestBuyerAcceptance action =
                        new Google.Api.Ads.Dfp.v201708.RequestBuyerAcceptance();

                    // Perform action.
                    UpdateResult result = proposalService.performProposalAction(action,
                                                                                statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of proposals that were sent to Marketplace: {0}",
                                          result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No proposals were sent to Marketplace.");
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to send proposals to Marketplace. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the ProposalService.
            ProposalService proposalService =
                (ProposalService)user.GetService(DfpService.v201511.ProposalService);

            // Set the ID of the proposal.
            long proposalId = long.Parse(_T("INSERT_PROPOSAL_ID_HERE"));

            // Create statement to select the proposal.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :id")
                                                .OrderBy("id ASC")
                                                .Limit(1)
                                                .AddValue("id", proposalId);

            // Set default for page.
            ProposalPage  page        = new ProposalPage();
            List <string> proposalIds = new List <string>();
            int           i           = 0;

            try {
                do
                {
                    // Get proposals by statement.
                    page = proposalService.getProposalsByStatement(statementBuilder.ToStatement());

                    if (page.results != null && page.results.Length > 0)
                    {
                        foreach (Proposal proposal in page.results)
                        {
                            Console.WriteLine("{0}) Proposal with ID = '{1}', name = '{2}', and status ='{3}' " +
                                              "will be approved.", i++, proposal.id, proposal.name, proposal.status);
                            proposalIds.Add(proposal.id.ToString());
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of proposals to be approved: {0}", proposalIds.Count);

                if (proposalIds.Count > 0)
                {
                    // Modify statement for action.
                    statementBuilder.RemoveLimitAndOffset();

                    // Create action.
                    SubmitProposalsForApproval action = new SubmitProposalsForApproval();

                    // Perform action.
                    UpdateResult result = proposalService.performProposalAction(action,
                                                                                statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of proposals approved: {0}", result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No proposals were approved.");
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to approve proposals. Exception says \"{0}\"",
                                  e.Message);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="dataTable">AppUserData.AppUserDataTable对象,该对象中应该有且只有一条记录。</param>
        /// <returns>修改操作结果</returns>
        public UpdateResult UpdateAppUser(AppUserData.AppUserDataTable dataTable)
        {
            UpdateResult updateResult = UpdateResult.Success;

            // 检查参数有效性
            if (dataTable == null || dataTable.Count == 0)
            {
                throw new ValidationException("更新用户时出错,传入参数为空或没有记录。");
            }

            // 执行修改
            OracleParameter[] paras = new OracleParameter[6];
            paras[0] = this.MakeInParam("p_user_id", OracleType.Char, 36, dataTable[0].ID.ToString());
            paras[1] = this.MakeInParam("p_username", OracleType.NVarChar, 50, dataTable[0].Username);
            paras[2] = this.MakeInParam("p_password", OracleType.NVarChar, 50, dataTable[0].Password);
            if (!dataTable[0].IsFullNameNull())
            {
                paras[3] = this.MakeInParam("p_fullname", OracleType.NVarChar, 200, dataTable[0].FullName);
            }
            else
            {
                paras[3] = this.MakeInParam("p_fullname", OracleType.NVarChar, 200, System.DBNull.Value);
            }

            if (!dataTable[0].IsEmailAddressNull())
            {
                paras[4] = this.MakeInParam("p_emailaddress", OracleType.NVarChar, 200, dataTable[0].EmailAddress);
            }
            else
            {
                paras[4] = this.MakeInParam("p_emailaddress", OracleType.NVarChar, 200, System.DBNull.Value);
            }

            paras[5] = MakeOutParam("p_result", OracleType.Int32, 4);

            this.ExecuteProc("Book_Update_User", paras);

            // 检查返回结果是否正常
            int outParam = int.Parse(paras[5].Value.ToString());

            if (outParam < 0 || outParam > 2)
            {
                throw new DbOperationException("存储过程UpdateAppUser返回参数值不可识别。");
            }

            // 变换返回值
            switch (outParam)
            {
            case 0:
                updateResult = UpdateResult.Success;
                break;

            case 1:
                updateResult = UpdateResult.Fail;
                break;

            case 2:
                updateResult = UpdateResult.ObeyUniqueConstraint;
                break;
            }

            return(updateResult);
        }
Exemplo n.º 7
0
 public object FindAndModifyAs(Type documentType, IMongoQuery query, IMongoSortBy sortBy, IMongoUpdate update, IMongoFields fields, bool returnNew, bool upsert, out UpdateResult result)
 {
     var r = _this.FindAndModify(query, sortBy, update, fields, returnNew, upsert);
     result = new FindAndModifyUpdateResult(r);
     return r.GetModifiedDocumentAs(documentType);
 }
        public UpdateResult<SubCategoryViewModel> UpdateSubCategory(SubCategoryViewModel subCategoryViewModel)
        {
            UpdateResult<SubCategoryViewModel> updateResult = new UpdateResult<SubCategoryViewModel>();

            if (subCategoryViewModel.SubCategoryId == Guid.Empty)
            {
                updateResult = CreateNewSubcategory(subCategoryViewModel);
            }
            else
            {

                bool success = AddUpdateCategorySubCategoryMapRepo(subCategoryViewModel);

                updateResult.Success = success;

            }

            return updateResult;
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user, long siteId)
        {
            using (SiteService siteService = user.GetService <SiteService>())
            {
                // Create statement to select the site.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(1)
                                                    .AddValue("id", siteId);

                // Set default for page.
                SitePage      page    = new SitePage();
                List <string> siteIds = new List <string>();
                int           i       = 0;

                try
                {
                    do
                    {
                        // Get sites by statement.
                        page = siteService.getSitesByStatement(
                            statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            foreach (Site site in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) Site with ID = '{1}', URL = '{2}', " +
                                    "and approval status = '{3}' will be submitted for approval.",
                                    i++, site.id, site.url, site.approvalStatus);
                                siteIds.Add(site.id.ToString());
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                    Console.WriteLine("Number of sites to be submitted for approval: {0}",
                                      siteIds.Count);

                    if (siteIds.Count > 0)
                    {
                        // Modify statement for action.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create action.
                        Google.Api.Ads.AdManager.v202108.SubmitSiteForApproval action =
                            new Google.Api.Ads.AdManager.v202108.SubmitSiteForApproval();

                        // Perform action.
                        UpdateResult result =
                            siteService.performSiteAction(action,
                                                          statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine(
                                "Number of sites that were submitted for approval: {0}",
                                result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No sites were submitted for approval.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Failed to send sites to Marketplace. Exception says \"{0}\"",
                        e.Message);
                }
            }
        }
Exemplo n.º 10
0
 private void DownloadFileCompleted(UpdateResult result)
 {
     _logger.Info("Downloading finished");
     UnPackZip(result);
 }
        public UpdateResult<ExternalOrderViewModel> UpdateExternalOrderShipped(ExternalOrderViewModel order)
        {
            UpdateResult<ExternalOrderViewModel> updateResult = new UpdateResult<ExternalOrderViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                DbSet<ExternalOrder> externalOrderSet = dbContext.ExternalOrderSet;

                ExternalOrder existingOrder = externalOrderSet.Where(x => x.StoreProviderOrderId == order.StoreProviderOrderId).FirstOrDefault();

                if (existingOrder != null)
                {
                    existingOrder.OrderStatus = (int)StoreOrderStatusEnum.Shipped;
                }

            }

            return updateResult;
        }
        public UpdateResult<ExternalActivity> UpdateExternalActivityDetails(ExternalActivityViewModel externalActivity)
        {
            UpdateResult<ExternalActivity> updateResult = new UpdateResult<ExternalActivity>() { Success = false };

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                DbSet<ExternalActivity> externalActivitySet = dbContext.ExternalActivitySet;

                ExternalActivity existingActivity = externalActivitySet.Where(x => x.StoreProviderType == (int)externalActivity.StoreProviderType
                                                                && x.ExternalActivityType == (int)externalActivity.ExternalActivityType).FirstOrDefault();

                if (existingActivity != null)
                {
                    Guid existingId = existingActivity.ActivityId;

                    existingActivity.ActivityStatus = (int)ExternalActivityStatus.Completed;
                    existingActivity.ExternalActivityType = (int)externalActivity.ExternalActivityType;
                    existingActivity.LastPerformedOn = externalActivity.LastPerformedOn;
                    existingActivity.StoreProviderType = (int)externalActivity.StoreProviderType;
                    externalActivity.UnshippedOrdersCount = externalActivity.UnshippedOrdersCount;

                    externalActivitySet.Attach(existingActivity);

                    dbContext.Entry(existingActivity).State = EntityState.Modified;

                }
                else
                {

                    existingActivity = existingActivity = new ExternalActivity()
                    {
                        ActivityId = Guid.NewGuid(),
                        ActivityStatus = (int)externalActivity.ActivityStatus,
                        ExternalActivityType = (int)externalActivity.ExternalActivityType,
                        LastPerformedOn = externalActivity.LastPerformedOn,
                        StoreProviderType = (int)externalActivity.StoreProviderType,
                    };

                    externalActivitySet.Add(existingActivity);
                }

                dbContext.SaveChanges();
                updateResult.Entity = existingActivity;

            }

            return updateResult;
        }
        public UpdateResult<ProductAttributeViewModel> UpdateProductAttribute(ProductAttributeViewModel productAttribute)
        {
            UpdateResult<ProductAttributeViewModel> updateResult = new UpdateResult<ProductAttributeViewModel>();

            updateResult.Entity = productAttribute;

            List<AttributeSubCategorySelection> selectedSubCategories = productAttribute.SubCategorySelections.Where(x => x.IsSelected).ToList();

            if (selectedSubCategories.Count == 0)
            {
                updateResult.Success = false;
                updateResult.ErrorMessage = "Please select at least one Sub Category";

                return updateResult;
            }

            if (string.IsNullOrEmpty(productAttribute.AttributeName))
            {
                updateResult.ErrorMessage = "Please enter a valid attribute name";
                return updateResult;
            }

            if (IsAttributeNameDuplicate(productAttribute))
            {
                updateResult.ErrorMessage = "Attribute Name already exist";

                return updateResult;
            }

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                using (DbContextTransaction trans = dbContext.Database.BeginTransaction())
                {

                    if (productAttribute.ProductAttributeId != Guid.Empty)
                    {

                        FindResult<SubCategoryAttributeMapViewModel> subCategoryAttributeMapVMResult = subCategoryAttributeMapRepository.FindBy(x => x.ProductAttributeId == productAttribute.ProductAttributeId);

                        List<Guid> existingSubCategoryIds = subCategoryAttributeMapVMResult.Entities.Select(x => x.SubCategoryId).ToList();

                        if (!subCategoryAttributeMapVMResult.Success)
                        {
                            updateResult.ErrorMessage = updateResult.ErrorMessage = string.Format("Can not retrieve existing mappings");
                            return updateResult;
                        }

                        if (subCategoryAttributeMapVMResult.Entities.Count > 0)
                        {
                            foreach (var item in subCategoryAttributeMapVMResult.Entities)
                            {
                                AttributeSubCategorySelection existingSelection = productAttribute.SubCategorySelections
                                        .FirstOrDefault(x => x.SubCategory.SubCategoryId == item.SubCategoryId && x.IsSelected == true);

                                if (existingSelection == null)
                                {
                                    EntityOperationResultBase deleteResult = subCategoryAttributeMapRepository.Delete(dbContext, item.SubCategoryAttributeMapId);

                                    if (deleteResult.Success == false)
                                    {
                                        updateResult.ErrorMessage = updateResult.ErrorMessage = string.Format("Mapping {0} Can not be deleted. Error: {1}", item.SubCategoryAttributeMapId, deleteResult.ErrorMessage);
                                    }
                                }
                            }
                        }

                        foreach (AttributeSubCategorySelection subCategorySelection in selectedSubCategories)
                        {

                            if (!existingSubCategoryIds.Contains(subCategorySelection.SubCategory.SubCategoryId))
                            {

                                SubCategoryAttributeMapViewModel newMapping = new SubCategoryAttributeMapViewModel
                                {
                                    ProductAttributeId = productAttribute.ProductAttributeId,
                                    SubCategoryId = subCategorySelection.SubCategory.SubCategoryId
                                };

                                UpdateResult<SubCategoryAttributeMapViewModel> updMappingResult = subCategoryAttributeMapRepository.Update(dbContext, newMapping);

                                if (!updMappingResult.Success)
                                {
                                    updateResult.Success = false;
                                    updateResult.ErrorMessage = updateResult.ErrorMessage = string.Format("Mapping with {0} Can not be saved", subCategorySelection.SubCategory.SubCategoryName); ;
                                    return updateResult;
                                }

                            }

                        }

                        updateResult = productAttributeRepository.Update(productAttribute);

                    }
                    else
                    {

                        updateResult = productAttributeRepository.Update(productAttribute);

                        if (!updateResult.Success)
                        {
                            return updateResult;
                        }

                        ProductAttributeViewModel updatedModel = updateResult.Entity;

                        foreach (var subCatSelection in selectedSubCategories)
                        {

                            SubCategoryAttributeMapViewModel newMapping = new SubCategoryAttributeMapViewModel
                            {
                                SubCategoryId = subCatSelection.SubCategory.SubCategoryId,
                                ProductAttributeId = updatedModel.ProductAttributeId
                            };

                            UpdateResult<SubCategoryAttributeMapViewModel> newMappingUpdateResult = subCategoryAttributeMapRepository.Update(newMapping);

                            if (!newMappingUpdateResult.Success)
                            {
                                trans.Rollback();
                                updateResult.Success = false;
                                updateResult.ErrorMessage = string.Format("Mapping with {0} Can not be saved", subCatSelection.SubCategory.SubCategoryName);
                                return updateResult;
                            }

                        }

                    }

                    trans.Commit();
                }

                if (updateResult.Success)
                {
                    updateResult.SuccessMessage = "Product Attribute saved successfully";
                }
                //if(findre)

            }

            return updateResult;
        }
Exemplo n.º 14
0
        public UpdateResult<ProductViewModel> SaveProduct(ProductViewModel productViewModel)
        {
            UpdateResult<ProductViewModel> result = new UpdateResult<ProductViewModel>() { Success = false };

            Guid categoryId = productViewModel.CategorySubCategoryMap.CategoryId;
            Guid subCategoryId = productViewModel.CategorySubCategoryMap.SubCategoryId;

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                try
                {

                    UpdateResult<ProductViewModel> updateResult = productRepository.Update(dbContext, productViewModel);

                    if (!updateResult.Success)
                    {
                        return updateResult;
                    }

                    foreach (ProductVariantViewModel prvm in productViewModel.ProductVariants)
                    {

                        prvm.ProductId = updateResult.Entity.ProductId;

                        ProductVariant pv = dbContext.ProductVariantSet.Where(x => x.ProductVariantId == prvm.ProductVariantId).FirstOrDefault();

                        if (pv == null)
                        {
                            prvm.ProductVariantId = Guid.Empty;
                        }

                        UpdateResult<ProductVariantViewModel> pvUpdateResult = productVariantRepository.Update(prvm);

                        if (!pvUpdateResult.Success)
                        {
                            result.Success = false;
                            result.ErrorMessage = pvUpdateResult.ErrorMessage;
                            return result;
                        }

                        List<ProductVariantAttributeValue> productVariantAttributeValueMaps = dbContext.ProductVariantAttributeValueSet
                                            .Where(x => x.ProductVariantId == prvm.ProductVariantId).ToList();

                        List<Guid> attributeSelectValueIds = new List<Guid>();

                        foreach (var item in prvm.ProductVariantAttributeValues)
                        {
                            if (item.ProductAttributeId != Guid.Empty)
                            {

                                if ((!item.AttributeValueListId.HasValue
                                     || item.AttributeValueListId.Value == Guid.Empty)
                                     && !string.IsNullOrEmpty(item.ProductAttributeValue))
                                {
                                    SubCategoryAttributeMap scAttrMap = dbContext.SubCategoryAttributeMapSet
                                        .Where(x => x.ProductAttributeId == item.ProductAttributeId && x.SubCategoryId == subCategoryId).FirstOrDefault();

                                    AttributeValueList avl = new AttributeValueList()
                                    {

                                        AttributeValueListId = Guid.NewGuid(),
                                        AttributeValue = item.ProductAttributeValue,
                                        CategoryId = categoryId,
                                        SubCategoryAttributeMapID = scAttrMap.SubCategoryAttributeMapId,
                                    };

                                    dbContext.AttributeValueListSet.Add(avl);

                                    item.AttributeValueListId = avl.AttributeValueListId;

                                    ProductVariantAttributeValue newPVAttrValue = new ProductVariantAttributeValue()
                                    {
                                        ProductVariantId = prvm.ProductVariantId,
                                        AttributeValueListId = item.AttributeValueListId.Value,
                                    };

                                    dbContext.ProductVariantAttributeValueSet.Add(newPVAttrValue);
                                    dbContext.SaveChanges();

                                }
                                else if (item.AttributeValueListId.HasValue && item.AttributeValueListId != Guid.Empty && !string.IsNullOrEmpty(item.ProductAttributeValue))
                                {
                                    ProductVariantAttributeValue pvAttrValue = productVariantAttributeValueMaps
                                                        .Where(x => x.AttributeValueListId == item.AttributeValueListId.Value)
                                                        .FirstOrDefault();

                                    if (pvAttrValue != null)
                                    {
                                        productVariantAttributeValueMaps.Remove(pvAttrValue);
                                    }
                                    else
                                    {
                                        ProductVariantAttributeValue newPVAttrValue = new ProductVariantAttributeValue()
                                        {
                                            ProductVariantId = prvm.ProductVariantId,
                                            AttributeValueListId = item.AttributeValueListId.Value,
                                        };

                                        dbContext.ProductVariantAttributeValueSet.Add(newPVAttrValue);
                                        dbContext.SaveChanges();

                                    }
                                }
                            }

                        }

                        if (productVariantAttributeValueMaps != null && productVariantAttributeValueMaps.Count > 0)
                        {
                            foreach (var pvavm in productVariantAttributeValueMaps)
                            {
                                dbContext.ProductVariantAttributeValueSet.Remove(pvavm);

                            }

                            dbContext.SaveChanges();
                        }
                    }

                    result.Success = true;
                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.ErrorMessage = ex.Message;
                }
            }

            return result;
        }
Exemplo n.º 15
0
        private static UpdateResult GetUpdateResult()
        {
            var updateResult = new UpdateResult();

            XmlTextReader reader = null;
            try
            {
                string url = BrowserHelper.Host + "/updatecheck.php?platform=pc&version=" + Application.ProductVersion;

            #if DEBUG
                //uncomment this if you want to check live site
                //url = "http://test.highlighthunter.com/updatecheck.php?platform=pc&version=1.2.0.0";
            #endif

                // Load the reader with the data file and ignore all white space nodes.
                reader = new XmlTextReader(url)
                             {
                                 WhitespaceHandling = WhitespaceHandling.None
                             };

                //logger.Info("Contents of update check: " + reader.ReadContentAsString());

                reader.ReadStartElement("updateResults");

                updateResult.IsUpdateAvailable = Boolean.Parse(reader.ReadElementString("isUpdateAvailable"));
                updateResult.LatestVersion = reader.ReadElementString("latestVersion");
                updateResult.WhatsNew = reader.ReadElementString("whatsNew");
                updateResult.DownloadPage = reader.ReadElementString("downloadPage");

                /*
                // Parse the file and display each of the nodes.
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            Console.WriteLine("<{0}>", reader.Name);
                            break;

                        case XmlNodeType.Text:
                            Console.WriteLine(reader.Value);
                            break;

                        case XmlNodeType.CDATA:
                            Console.WriteLine("<![CDATA[{0}]]>", reader.Value);
                            break;

                        case XmlNodeType.ProcessingInstruction:
                            Console.WriteLine("<?{0} {1}?>", reader.Name, reader.Value);
                            break;

                        case XmlNodeType.Comment:
                            Console.WriteLine("<!--{0}-->", reader.Value);
                            break;

                        case XmlNodeType.XmlDeclaration:
                            Console.WriteLine("<?xml version='1.0'?>");
                            break;

                        case XmlNodeType.Document:
                            break;

                        case XmlNodeType.DocumentType:
                            Console.WriteLine("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
                            break;

                        case XmlNodeType.EntityReference:
                            Console.WriteLine(reader.Name);
                            break;

                        case XmlNodeType.EndElement:
                            Console.WriteLine("</{0}>", reader.Name);
                            break;
                    }
                }
                 */
            }
            catch (Exception ex)
            {
                Logger.Error("Exception checking for update: " + ex.ToString());
            }

            finally
            {
                if (reader != null)
                    reader.Close();
            }

            return updateResult;
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201411.LineItemService);

            // Set the ID of the order to get line items from.
            long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

            // Create statement to select approved line items from a given order.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("orderId = :orderId and status = :status")
                                                .AddValue("orderId", orderId)
                                                .AddValue("status", ComputedStatus.INACTIVE.ToString());

            // Set default for page.
            LineItemPage  page        = new LineItemPage();
            List <string> lineItemIds = new List <string>();

            try {
                do
                {
                    // Get line items by statement.
                    page = lineItemService.getLineItemsByStatement(statementBuilder.ToStatement());

                    if (page.results != null && page.results.Length > 0)
                    {
                        int i = page.startIndex;
                        foreach (LineItemSummary lineItem in page.results)
                        {
                            // Archived line items cannot be activated.
                            if (!lineItem.isArchived)
                            {
                                Console.WriteLine("{0}) Line item with ID ='{1}', belonging to order ID ='{2}' " +
                                                  "and name ='{2}' will be activated.", i, lineItem.id, lineItem.orderId,
                                                  lineItem.name);
                                lineItemIds.Add(lineItem.id.ToString());
                                i++;
                            }
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);


                Console.WriteLine("Number of line items to be activated: {0}", lineItemIds.Count);

                if (lineItemIds.Count > 0)
                {
                    // Modify statement.
                    statementBuilder.RemoveLimitAndOffset();

                    // Create action.
                    ActivateLineItems action = new ActivateLineItems();

                    // Perform action.
                    UpdateResult result = lineItemService.performLineItemAction(action,
                                                                                statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of line items activated: {0}", result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No line items were activated.");
                    }
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to activate line items. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (WorkflowRequestService workflowRequestService =
                       (WorkflowRequestService)user.GetService(DfpService.v201711.WorkflowRequestService)) {
                // Set the ID of the proposal to approve workflow approval requests for.
                long proposalId = long.Parse(_T("INSERT_PROPOSAL_ID_HERE"));

                // Create a statement to select workflow approval requests for a proposal.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("WHERE entityId = :entityId and entityType = :entityType and type = :type")
                                                    .OrderBy("id ASC")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                    .AddValue("entityId", proposalId)
                                                    .AddValue("entityType", WorkflowEntityType.PROPOSAL.ToString())
                                                    .AddValue("type", WorkflowRequestType.WORKFLOW_APPROVAL_REQUEST.ToString());

                // Set default for page.
                WorkflowRequestPage page = new WorkflowRequestPage();
                List <long>         worflowRequestIds = new List <long>();

                try {
                    do
                    {
                        // Get workflow requests by statement.
                        page = workflowRequestService.getWorkflowRequestsByStatement(
                            statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            int i = page.startIndex;
                            foreach (WorkflowRequest workflowRequest in page.results)
                            {
                                Console.WriteLine("{0})  Workflow approval request with ID '{1}' will be " +
                                                  "approved.", i++, workflowRequest.id);
                                worflowRequestIds.Add(workflowRequest.id);
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                    Console.WriteLine("Number of workflow approval requests to be approved: {0}",
                                      worflowRequestIds.Count);

                    if (worflowRequestIds.Count > 0)
                    {
                        // Modify statement.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create action.
                        Google.Api.Ads.Dfp.v201711.ApproveWorkflowApprovalRequests action =
                            new Google.Api.Ads.Dfp.v201711.ApproveWorkflowApprovalRequests();

                        // Add a comment to the approval.
                        action.comment = "The proposal looks good to me. Approved.";

                        // Perform action.
                        UpdateResult result = workflowRequestService.performWorkflowRequestAction(action,
                                                                                                  statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine("Number of workflow requests approved: {0}", result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No workflow requests were approved.");
                        }
                    }
                } catch (Exception e) {
                    Console.WriteLine("Failed to archive workflow requests. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ProductPackageService productPackageService =
                       user.GetService <ProductPackageService>())
            {
                // Set the ID of the product package.
                long productPackageId = long.Parse(_T("INSERT_PRODUCT_PACKAGE_ID_HERE"));

                // Create statement to select the product package.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(1)
                                                    .AddValue("id", productPackageId);

                // Set default for page.
                ProductPackagePage page = new ProductPackagePage();
                List <string>      productPackageIds = new List <string>();
                int i = 0;

                try
                {
                    do
                    {
                        // Get product packages by statement.
                        page = productPackageService.getProductPackagesByStatement(
                            statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            foreach (ProductPackage productPackage in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) Product package with ID = '{1}', name = '{2}', and " +
                                    "status ='{3}' will be activated.", i++, productPackage.id,
                                    productPackage.name, productPackage.status);
                                productPackageIds.Add(productPackage.id.ToString());
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                    Console.WriteLine("Number of product packages to be activated: {0}",
                                      productPackageIds.Count);

                    if (productPackageIds.Count > 0)
                    {
                        // Modify statement for action.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create action.
                        ActivateProductPackages action = new ActivateProductPackages();

                        // Perform action.
                        UpdateResult result =
                            productPackageService.performProductPackageAction(action,
                                                                              statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine("Number of product packages activated: {0}",
                                              result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No product packages were activated.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to activate product packages. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (CreativeWrapperService creativeWrapperService =
                       user.GetService <CreativeWrapperService>())
            {
                long labelId = long.Parse(_T("INSERT_CREATIVE_WRAPPER_LABEL_ID_HERE"));

                try
                {
                    // Create a query to select the active creative wrapper for the given
                    // label.
                    StatementBuilder statementBuilder = new StatementBuilder()
                                                        .Where("labelId = :labelId AND status = :status").OrderBy("id ASC")
                                                        .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                        .AddValue("status", CreativeWrapperStatus.ACTIVE.ToString())
                                                        .AddValue("labelId", labelId);

                    // Set default for page.
                    CreativeWrapperPage page = new CreativeWrapperPage();

                    do
                    {
                        page = creativeWrapperService.getCreativeWrappersByStatement(
                            statementBuilder.ToStatement());
                        CreativeWrapper[] creativeWrappers = page.results;
                        if (creativeWrappers != null)
                        {
                            foreach (CreativeWrapper wrapper in creativeWrappers)
                            {
                                Console.WriteLine(
                                    "Creative wrapper with ID '{0}' applying to label " +
                                    "'{1}' with status '{2}' will be deactivated.", wrapper.id,
                                    wrapper.labelId, wrapper.status);
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                    Console.WriteLine("Number of creative wrappers to be deactivated: {0}",
                                      page.totalResultSetSize);

                    // Modify statement for action.
                    statementBuilder.RemoveLimitAndOffset();

                    // Perform action.
                    CreativeWrapperAction action = new DeactivateCreativeWrappers();
                    UpdateResult          result =
                        creativeWrapperService.performCreativeWrapperAction(action,
                                                                            statementBuilder.ToStatement());

                    // Display results.
                    if (result.numChanges > 0)
                    {
                        Console.WriteLine("Number of creative wrappers deactivated: {0}",
                                          result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No creative wrappers were deactivated.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to create creative wrappers. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user, long cmsMetadataKeyId)
        {
            using (CmsMetadataService cmsMetadataService = user.GetService <CmsMetadataService>())
            {
                // Create a statement to select CMS metadata values.
                int pageSize = StatementBuilder.SUGGESTED_PAGE_LIMIT;
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("cmsKeyId = :cmsMetadataKeyId and status = :status")
                                                    .OrderBy("id ASC")
                                                    .Limit(pageSize)
                                                    .AddValue("cmsMetadataKeyId", cmsMetadataKeyId)
                                                    .AddValue("status", CmsMetadataValueStatus.INACTIVE.ToString());

                // Retrieve a small amount of CMS metadata values at a time, paging through until
                // all CMS metadata values have been retrieved.
                int totalResultSetSize = 0;

                do
                {
                    CmsMetadataValuePage page = cmsMetadataService.getCmsMetadataValuesByStatement(
                        statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        totalResultSetSize = page.totalResultSetSize;
                        int i = page.startIndex;
                        foreach (CmsMetadataValue cmsMetadataValue in page.results)
                        {
                            Console.WriteLine(
                                "{0}) CMS metadata value with ID {1} will be activated",
                                i++, cmsMetadataValue.cmsMetadataValueId);
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(pageSize);
                } while (statementBuilder.GetOffset() < totalResultSetSize);

                Console.WriteLine("Number of CMS metadata values to be activated: {0}",
                                  totalResultSetSize);

                if (totalResultSetSize > 0)
                {
                    // Modify statement.
                    statementBuilder.RemoveLimitAndOffset();

                    // Create action.
                    Google.Api.Ads.AdManager.v202202.ActivateCmsMetadataValues action =
                        new Google.Api.Ads.AdManager.v202202.ActivateCmsMetadataValues();

                    // Perform action.
                    UpdateResult result = cmsMetadataService.performCmsMetadataValueAction(action,
                                                                                           statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of CMS metadata values activated: {0}",
                                          result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No CMS metadata values were activated.");
                    }
                }
            }
        }
Exemplo n.º 21
0
		internal updateFoundEventArgs(UpdateResult result) {
			Result = result;
		}
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="dfpUser">The DFP user object running the code example.</param>
        public override void Run(DfpUser dfpUser)
        {
            // Get the UserTeamAssociationService.
            UserTeamAssociationService userTeamAssociationService = (UserTeamAssociationService)
                                                                    dfpUser.GetService(DfpService.v201311.UserTeamAssociationService);

            // Set the user to remove from its teams.
            long userId = long.Parse(_T("INSERT_USER_ID_HERE"));

            // Create filter text to select user team associations by the user ID.
            String    statementText   = "WHERE userId = :userId LIMIT 500";
            Statement filterStatement = new StatementBuilder("").AddValue("userId", userId).
                                        ToStatement();

            // Set defaults for page and offset.
            UserTeamAssociationPage page = new UserTeamAssociationPage();
            int offset = 0;

            try {
                do
                {
                    // Create a statement to page through user team associations.
                    filterStatement.query = statementText + " OFFSET " + offset;

                    // Get user team associations by statement.
                    page = userTeamAssociationService.getUserTeamAssociationsByStatement(filterStatement);

                    if (page.results != null)
                    {
                        int i = page.startIndex;
                        foreach (UserTeamAssociation userTeamAssociation in page.results)
                        {
                            Console.WriteLine("{0}) User team association between user with ID \"{1}\" and " +
                                              "team with ID \"{2}\" will be deleted.", i, userTeamAssociation.userId,
                                              userTeamAssociation.teamId);
                            i++;
                        }
                    }

                    offset += 500;
                } while (offset < page.totalResultSetSize);

                Console.WriteLine("Number of teams that the user will be removed from: "
                                  + page.totalResultSetSize);

                if (page.totalResultSetSize > 0)
                {
                    // Modify statement for action.
                    filterStatement.query = "WHERE userId = :userId";

                    // Create action.
                    DeleteUserTeamAssociations action = new DeleteUserTeamAssociations();

                    // Perform action.
                    UpdateResult result =
                        userTeamAssociationService.performUserTeamAssociationAction(action, filterStatement);

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of teams that the user was removed from: "
                                          + result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No user team associations were deleted.");
                    }
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to delete user team associations. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
Exemplo n.º 23
0
        private void PromptUserForUpdate(UpdateResult updateResult)
        {
            var eventArgs = new CancelEventArgs();

            _isSafeToPromptHandler.Invoke(this, eventArgs);

            if (eventArgs.Cancel)
                return;

            try
            { // we should never crash app due to this
                if (MessageBox.Show("Here's what's new in Highlight Hunter " + updateResult.LatestVersion + ":" + Environment.NewLine + Environment.NewLine +
                    updateResult.WhatsNew + Environment.NewLine + Environment.NewLine +
                    "Download it now?",
                    "Update available!",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    BrowserHelper.LaunchBrowser(updateResult.DownloadPage, "updatecheck");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
Exemplo n.º 24
0
        public UpdateResult Update(FilterDefinition <TEntity> filterDefinition, UpdateDefinition <TEntity> updateDefinition)
        {
            UpdateResult result = this._collection.UpdateOne(filterDefinition, updateDefinition);

            return(result);
        }
Exemplo n.º 25
0
        public UpdateResult Update()
        {
            this.updateResult = UpdateResult.None;

            // Check for skipping.
            if ((DoomApplication.Instance.IWad == "doom2" ||
                 DoomApplication.Instance.IWad == "freedoom2" ||
                 DoomApplication.Instance.IWad == "plutonia" ||
                 DoomApplication.Instance.IWad == "tnt") &&
                this.count > 50)
            {
                int i;

                // Go on to the next level.
                for (i = 0; i < Player.MaxPlayerCount; i++)
                {
                    if (this.options.Players[i].Cmd.Buttons != 0)
                    {
                        break;
                    }
                }

                if (i < Player.MaxPlayerCount && this.stage != 2)
                {
                    if (this.options.Map == 30)
                    {
                        this.StartCast();
                    }
                    else
                    {
                        return(UpdateResult.Completed);
                    }
                }
            }

            // Advance animation.
            this.count++;

            if (this.stage == 2)
            {
                this.UpdateCast();

                return(this.updateResult);
            }

            if (DoomApplication.Instance.IWad == "doom2" ||
                DoomApplication.Instance.IWad == "freedoom2" ||
                DoomApplication.Instance.IWad == "plutonia" ||
                DoomApplication.Instance.IWad == "tnt")
            {
                return(this.updateResult);
            }

            if (this.stage == 0 && this.count > this.text.Length * Finale.TextSpeed + Finale.TextWait)
            {
                this.count        = 0;
                this.stage        = 1;
                this.updateResult = UpdateResult.NeedWipe;

                if (this.options.Episode == 3)
                {
                    this.options.Music.StartMusic(Bgm.BUNNY, true);
                }
            }

            if (this.stage == 1 && this.options.Episode == 3)
            {
                this.BunnyScroll();
            }

            return(this.updateResult);
        }
Exemplo n.º 26
0
 internal updateFoundEventArgs(UpdateResult result)
 {
     Result = result;
 }
Exemplo n.º 27
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public void Run(DfpUser user)
        {
            // Get the LineItemCreativeAssociationService.
            LineItemCreativeAssociationService licaService = (LineItemCreativeAssociationService)
                                                             user.GetService(DfpService.v201608.LineItemCreativeAssociationService);

            // Set the line item to get LICAs by.
            long lineItemId = long.Parse(_T("INSERT_LINE_ITEM_ID_HERE"));

            // Create a statement to page through active LICAs.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("lineItemId = :lineItemId")
                                                .OrderBy("lineItemId ASC, creativeId ASC")
                                                .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                .AddValue("lineItemId", lineItemId);

            // Set default for page.
            LineItemCreativeAssociationPage page = new LineItemCreativeAssociationPage();
            List <string> creativeIds            = new List <string>();

            try {
                do
                {
                    // Get LICAs by statement.
                    page = licaService.getLineItemCreativeAssociationsByStatement(
                        statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        int i = page.startIndex;
                        foreach (LineItemCreativeAssociation lica in page.results)
                        {
                            Console.WriteLine("{0}) LICA with line item ID = '{1}', creative ID ='{2}' and " +
                                              "status ='{3}' will be deactivated.", i, lica.lineItemId, lica.creativeId,
                                              lica.status);
                            i++;
                            creativeIds.Add(lica.creativeId.ToString());
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of LICAs to be deactivated: {0}", creativeIds.Count);

                if (creativeIds.Count > 0)
                {
                    // Modify statement for action.
                    statementBuilder.RemoveLimitAndOffset();

                    // Create action.
                    DeactivateLineItemCreativeAssociations action =
                        new DeactivateLineItemCreativeAssociations();

                    // Perform action.
                    UpdateResult result = licaService.performLineItemCreativeAssociationAction(action,
                                                                                               statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of LICAs deactivated: {0}", result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No LICAs were deactivated.");
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to deactivate LICAs. Exception says \"{0}\"", e.Message);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (UserService userService = user.GetService <UserService>())
            {
                // Set the ID of the user to deactivate
                long userId = long.Parse(_T("INSERT_USER_ID_HERE"));

                // Create statement text to select user by id.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :userId")
                                                    .OrderBy("id ASC")
                                                    .Limit(1)
                                                    .AddValue("userId", userId);

                // Sets default for page.
                UserPage      page    = new UserPage();
                List <string> userIds = new List <string>();

                try
                {
                    do
                    {
                        // Get users by statement.
                        page = userService.getUsersByStatement(statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            int i = page.startIndex;
                            foreach (User userResult in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) User with ID = '{1}', email = '{2}', and status = '{3}'" +
                                    " will be deactivated.", i, userResult.id, userResult.email,
                                    userResult.isActive ? "ACTIVE" : "INACTIVE");
                                userIds.Add(userResult.id.ToString());
                                i++;
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                    Console.WriteLine("Number of users to be deactivated: {0}",
                                      page.totalResultSetSize);

                    if (userIds.Count > 0)
                    {
                        // Modify statement for action.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create action.
                        DeactivateUsers action = new DeactivateUsers();

                        // Perform action.
                        UpdateResult result =
                            userService.performUserAction(action, statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine(
                                "Number of users deactivated: {0}" + result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No users were deactivated.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to deactivate users. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Exemplo n.º 29
0
        public Task <UpdateResult> UpdateAsync(UpdateRequest updateRequest, IManagedTemplatePackageProvider provider, CancellationToken cancellationToken)
        {
            _ = updateRequest ?? throw new ArgumentNullException(nameof(updateRequest));

            return(Task.FromResult(UpdateResult.CreateSuccess(updateRequest, updateRequest.TemplatePackage)));
        }
Exemplo n.º 30
0
 public object FindAndModifyAs(Type documentType, IMongoQuery query, IMongoSortBy sortBy, IMongoUpdate update, IMongoFields fields, bool returnNew, bool upsert, out UpdateResult result)
 {
     var args = new FindAndModifyArgs();
     args.Query = query;
     args.SortBy = sortBy;
     args.Update = update;
     args.Fields = fields;
     args.Upsert = upsert;
     args.VersionReturned = returnNew ? FindAndModifyDocumentVersion.Modified : FindAndModifyDocumentVersion.Original;
     var r = _this.FindAndModify(args);
     result = new FindAndModifyUpdateResult(r);
     return r.GetModifiedDocumentAs(documentType);
 }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the InventoryService.
            InventoryService inventoryService =
                (InventoryService)user.GetService(DfpService.v201403.InventoryService);

            // Set the ID of the ad unit to deactivate.
            int adUnitId = int.Parse(_T("INSERT_AD_UNIT_ID_HERE"));

            // Create a statement to select the ad unit.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :id")
                                                .OrderBy("id ASC")
                                                .Limit(1)
                                                .AddValue("id", adUnitId);

            // Set default for page.
            AdUnitPage    page      = new AdUnitPage();
            List <string> adUnitIds = new List <string>();

            try {
                do
                {
                    // Get ad units by Statement.
                    page = inventoryService.getAdUnitsByStatement(statementBuilder.ToStatement());

                    if (page.results != null && page.results.Length > 0)
                    {
                        int i = page.startIndex;
                        foreach (AdUnit adUnit in page.results)
                        {
                            Console.WriteLine("{0}) Ad unit with ID ='{1}', name = {2} and status = {3} will" +
                                              " be deactivated.", i, adUnit.id, adUnit.name, adUnit.status);
                            adUnitIds.Add(adUnit.id);
                            i++;
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of ad units to be deactivated: {0}", adUnitIds.Count);

                // Modify statement for action.
                statementBuilder.RemoveLimitAndOffset();

                // Create action.
                DeactivateAdUnits action = new DeactivateAdUnits();

                // Perform action.
                UpdateResult result = inventoryService.performAdUnitAction(action,
                                                                           statementBuilder.ToStatement());

                // Display results.
                if (result != null && result.numChanges > 0)
                {
                    Console.WriteLine("Number of ad units deactivated: {0}", result.numChanges);
                }
                else
                {
                    Console.WriteLine("No ad units were deactivated.");
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to deactivate ad units. Exception says \"{0}\"", ex.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (PlacementService placementService = user.GetService <PlacementService>())
            {
                // Create statement to select active placements.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("status = :status")
                                                    .OrderBy("id ASC")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                    .AddValue("status", InventoryStatus.ACTIVE.ToString());

                // Sets default for page.
                PlacementPage page         = new PlacementPage();
                List <string> placementIds = new List <string>();

                try
                {
                    do
                    {
                        // Get placements by statement.
                        page = placementService.getPlacementsByStatement(statementBuilder
                                                                         .ToStatement());

                        if (page.results != null)
                        {
                            int i = page.startIndex;
                            foreach (Placement placement in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) Placement with ID ='{1}', name ='{2}', and " +
                                    "status ='{3}' will be deactivated.",
                                    i, placement.id, placement.name, placement.status);
                                placementIds.Add(placement.id.ToString());
                                i++;
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                    Console.WriteLine("Number of placements to be deactivated: {0}",
                                      placementIds.Count);

                    if (placementIds.Count > 0)
                    {
                        // Modify statement for action.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create action.
                        DeactivatePlacements action = new DeactivatePlacements();

                        // Perform action.
                        UpdateResult result =
                            placementService.performPlacementAction(action,
                                                                    statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine("Number of placements deactivated: {0}",
                                              result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No placements were deactivated.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to deactivate placements. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (OrderService orderService = user.GetService <OrderService>())
            {
                // Set the ID of the order.
                long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

                // Create statement to select the order.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(1)
                                                    .AddValue("id", orderId);

                // Set default for page.
                OrderPage     page     = new OrderPage();
                List <string> orderIds = new List <string>();
                int           i        = 0;

                try
                {
                    do
                    {
                        // Get orders by statement.
                        page = orderService.getOrdersByStatement(statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            foreach (Order order in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) Order with ID = '{1}', name = '{2}', and status ='{3}' " +
                                    "will be approved.", i, order.id, order.name, order.status);
                                orderIds.Add(order.id.ToString());
                                i++;
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                    Console.WriteLine("Number of orders to be approved: {0}", orderIds.Count);

                    if (orderIds.Count > 0)
                    {
                        // Modify statement for action.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create action.
                        ApproveAndOverbookOrders action = new ApproveAndOverbookOrders();

                        // Perform action.
                        UpdateResult result =
                            orderService.performOrderAction(action, statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine("Number of orders approved: {0}", result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No orders were approved.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to approve orders. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the OrderService.
            OrderService orderService =
                (OrderService)user.GetService(DfpService.v201311.OrderService);

            // Create Statement text to select all draft orders.
            string statementText = "WHERE status IN (:status1, :status2) and endDateTime >= :today " +
                                   "AND isArchived = FALSE LIMIT 500";
            Statement statement = new StatementBuilder("").
                                  AddValue("status1", OrderStatus.DRAFT.ToString()).
                                  AddValue("status2", OrderStatus.PENDING_APPROVAL.ToString()).
                                  AddValue("today", System.DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")).ToStatement();

            // Set defaults for page and offset.
            OrderPage     page     = new OrderPage();
            int           i        = 0;
            int           offset   = 0;
            List <string> orderIds = new List <string>();

            try {
                do
                {
                    // Create a Statement to page through draft orders.
                    statement.query = string.Format("{0} OFFSET {1}", statementText, offset);
                    // Get orders by Statement.
                    page = orderService.getOrdersByStatement(statement);

                    if (page.results != null && page.results.Length > 0)
                    {
                        foreach (Order order in page.results)
                        {
                            Console.WriteLine("{0}) Order with ID = '{1}', name = '{2}', and status ='{3}' " +
                                              "will be approved.", i, order.id, order.name, order.status);
                            orderIds.Add(order.id.ToString());
                            i++;
                        }
                    }

                    offset += 500;
                } while (offset < page.totalResultSetSize);

                Console.WriteLine("Number of orders to be approved: {0}", orderIds.Count);

                if (orderIds.Count > 0)
                {
                    // Create action Statement.
                    statement = new StatementBuilder(
                        string.Format("WHERE id IN ({0})", string.Join(",", orderIds.ToArray()))).
                                ToStatement();

                    // Create action.
                    ApproveAndOverbookOrders action = new ApproveAndOverbookOrders();

                    // Perform action.
                    UpdateResult result = orderService.performOrderAction(action, statement);

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of orders approved: {0}", result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No orders were approved.");
                    }
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to approve orders. Exception says \"{0}\"",
                                  ex.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the ProductTemplateService.
            ProductTemplateService productTemplateService =
                (ProductTemplateService)user.GetService(DfpService.v201705.ProductTemplateService);

            // Set the ID of the product template to activate.
            long productTemplateId = long.Parse(_T("INSERT_PRODUCT_TEMPLATE_ID_HERE"));

            // Create statement to select a product template by ID.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :id")
                                                .OrderBy("id ASC")
                                                .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                .AddValue("id", productTemplateId);

            // Set default for page.
            ProductTemplatePage page = new ProductTemplatePage();
            List <string>       productTemplateIds = new List <string>();

            try {
                do
                {
                    // Get product templates by statement.
                    page = productTemplateService.getProductTemplatesByStatement(
                        statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        int i = page.startIndex;
                        foreach (ProductTemplate productTemplate in page.results)
                        {
                            Console.WriteLine("{0}) Product template with ID ='{1}' will be activated.",
                                              i++, productTemplate.id);
                            productTemplateIds.Add(productTemplate.id.ToString());
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of product templates to be activated: {0}",
                                  productTemplateIds.Count);

                if (productTemplateIds.Count > 0)
                {
                    // Modify statement.
                    statementBuilder.RemoveLimitAndOffset();

                    // Create action.
                    Google.Api.Ads.Dfp.v201705.ActivateProductTemplates action =
                        new Google.Api.Ads.Dfp.v201705.ActivateProductTemplates();

                    // Perform action.
                    UpdateResult result = productTemplateService.performProductTemplateAction(action,
                                                                                              statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of product templates activated: {0}", result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No product templates were activated.");
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to activate product templates. Exception says \"{0}\"",
                                  e.Message);
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the WorkflowRequestService.
            WorkflowRequestService proposalLineItemService =
                (WorkflowRequestService)user.GetService(DfpService.v201708.WorkflowRequestService);

            // Set the ID of the proposal to trigger workflow external conditions for.c
            long proposalId = long.Parse(_T("INSERT_PROPOSAL_ID_HERE"));

            // Create a statement to select workflow external condition requests for a proposal.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("entityId = :entityId and entityType = :entityType and type = :type")
                                                .OrderBy("id ASC")
                                                .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                .AddValue("entityId", proposalId)
                                                .AddValue("entityType", WorkflowEntityType.PROPOSAL.ToString())
                                                .AddValue("type", WorkflowRequestType.WORKFLOW_EXTERNAL_CONDITION_REQUEST.ToString());

            // Set default for page.
            WorkflowRequestPage page = new WorkflowRequestPage();
            List <long>         workflowRequestIds = new List <long>();

            try {
                do
                {
                    // Get workflow requests by statement.
                    page = proposalLineItemService.getWorkflowRequestsByStatement(
                        statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        int i = page.startIndex;
                        foreach (WorkflowRequest workflowRequest in page.results)
                        {
                            Console.WriteLine("{0}) Workflow external condition request with ID '{1}'" +
                                              " for {2} with ID '{3}' will be triggered.", i++, workflowRequest.id,
                                              workflowRequest.entityType.ToString(), workflowRequest.entityId);
                            workflowRequestIds.Add(workflowRequest.id);
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of workflow external condition requests to be triggered: {0}",
                                  workflowRequestIds.Count);

                if (workflowRequestIds.Count > 0)
                {
                    // Modify statement.
                    statementBuilder.RemoveLimitAndOffset();

                    // Create action.
                    Google.Api.Ads.Dfp.v201708.TriggerWorkflowExternalConditionRequests action =
                        new Google.Api.Ads.Dfp.v201708.TriggerWorkflowExternalConditionRequests();

                    // Perform action.
                    UpdateResult result = proposalLineItemService.performWorkflowRequestAction(action,
                                                                                               statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of workflow external condition requests triggered: {0}",
                                          result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No workflow external condition requests were triggered.");
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to tirgger workflow external condition requests. Exception " +
                                  "says \"{0}\"", e.Message);
            }
        }
Exemplo n.º 37
0
        public static async Task <UpdateResult> UpdateAllFiles(PluginInformation pInformation, string modPath)
        {
            var updateUrl = await PluginRegistryService.Instance.GetModuleUpdateUrl(pInformation);

            string onlineSerializedInformation = await ReadOnlineModuleJson(updateUrl);

            if (onlineSerializedInformation is null)
            {
                //Debugger.Error($"Failed to update plugin: {pInformation.Name}!");
                return(UpdateResult.Failed);
            }

            PluginInformation onlineInformation = JsonConvert.DeserializeObject <PluginInformation>(onlineSerializedInformation);

            if (!IsVersionOk(onlineInformation.Update.MinimumVersion))
            {
                Debugger.Warn($"Newest version of {pInformation.Name} requires HunterPie v{onlineInformation.Update.MinimumVersion}!");
                return(UpdateResult.Skipped);
            }

            UpdateResult result = UpdateResult.UpToDate;

            foreach (string filePath in onlineInformation.Update.FileHashes.Keys)
            {
                string onlineHash = onlineInformation.Update.FileHashes[filePath];

                if (onlineHash.ToLower() == "installonly" && File.Exists(Path.Combine(modPath, filePath)))
                {
                    continue;
                }

                if (pInformation.Update.FileHashes.ContainsKey(filePath))
                {
                    string localHash = pInformation.Update.FileHashes[filePath];

                    if (onlineHash.ToLower() != localHash.ToLower() || !File.Exists(Path.Combine(modPath, filePath)))
                    {
                        string outputPath = Path.Combine(modPath, filePath);
                        if (!(await DownloadFileAsync($"{updateUrl}/{filePath}", outputPath, filePath)))
                        {
                            return(UpdateResult.Failed);
                        }

                        result = UpdateResult.Updated;
                    }
                }
                else
                {
                    string outputPath = Path.Combine(modPath, filePath);
                    if (!(await DownloadFileAsync($"{updateUrl}/{filePath}", outputPath, filePath)))
                    {
                        return(UpdateResult.Failed);
                    }
                    result = UpdateResult.Updated;
                }
            }

            return(await DownloadFileAsync($"{updateUrl}/module.json", Path.Combine(modPath, "module.json"), "module.json")
                ? result
                : UpdateResult.Failed);
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the CustomFieldService.
            CustomFieldService customFieldService = (CustomFieldService)user.GetService(
                DfpService.v201405.CustomFieldService);

            // Set the ID of the custom field to update.
            int customFieldId = int.Parse(_T("INSERT_CUSTOM_FIELD_ID_HERE"));

            // Create statement to select only active custom fields that apply to
            // line items.
            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Where("id = :id")
                                                .OrderBy("id ASC")
                                                .Limit(1)
                                                .AddValue("id", customFieldId);

            // Set default for page.
            CustomFieldPage page           = new CustomFieldPage();
            int             i              = 0;
            List <string>   customFieldIds = new List <string>();

            try {
                do
                {
                    // Get custom fields by statement.
                    page = customFieldService.getCustomFieldsByStatement(statementBuilder.ToStatement());

                    if (page.results != null)
                    {
                        foreach (CustomField customField in page.results)
                        {
                            Console.WriteLine("{0}) Custom field with ID \"{1}\" and name \"{2}\" will be " +
                                              "deactivated.", i, customField.id, customField.name);
                            customFieldIds.Add(customField.id.ToString());
                            i++;
                        }
                    }
                    statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                Console.WriteLine("Number of custom fields to be deactivated: " + customFieldIds.Count);

                if (customFieldIds.Count > 0)
                {
                    // Remove limit and offset from statement.
                    statementBuilder.RemoveLimitAndOffset();

                    // Create action.
                    Google.Api.Ads.Dfp.v201405.DeactivateCustomFields action =
                        new Google.Api.Ads.Dfp.v201405.DeactivateCustomFields();

                    // Perform action.
                    UpdateResult result = customFieldService.performCustomFieldAction(action,
                                                                                      statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of custom fields deactivated: " + result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No custom fields were deactivated.");
                    }
                }
            } catch (Exception ex) {
                Console.WriteLine("Failed to deactivate custom fields. Exception says \"{0}\"", ex.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (LabelService labelService = user.GetService <LabelService>())
            {
                // Set the ID of the label to deactivate.
                int labelId = int.Parse(_T("INSERT_LABEL_ID_HERE"));

                // Create statement text to select the label.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(1)
                                                    .AddValue("id", labelId);

                // Set default for page.
                LabelPage page = new LabelPage();

                try
                {
                    do
                    {
                        // Get labels by statement.
                        page = labelService.getLabelsByStatement(statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            int i = page.startIndex;
                            foreach (Label label in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) Label with ID '{1}', name '{2}' will be deactivated.", i,
                                    label.id, label.name);
                                i++;
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                    Console.WriteLine("Number of labels to be deactivated: " +
                                      page.totalResultSetSize);

                    // Modify statement for action.
                    statementBuilder.RemoveLimitAndOffset();

                    // Create action.
                    DeactivateLabels action = new DeactivateLabels();

                    // Perform action.
                    UpdateResult result =
                        labelService.performLabelAction(action, statementBuilder.ToStatement());

                    // Display results.
                    if (result != null && result.numChanges > 0)
                    {
                        Console.WriteLine("Number of labels deactivated: " + result.numChanges);
                    }
                    else
                    {
                        Console.WriteLine("No labels were deactivated.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to deactivate labels. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Exemplo n.º 40
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="dfpUser">The DFP user object running the code example.</param>
        public void Run(DfpUser dfpUser)
        {
            using (UserTeamAssociationService userTeamAssociationService =
                       (UserTeamAssociationService)dfpUser.GetService(DfpService.v201805
                                                                      .UserTeamAssociationService))
            {
                // Set the user to remove from its teams.
                long userId = long.Parse(_T("INSERT_USER_ID_HERE"));

                // Create filter text to select user team associations by the user ID.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("userId = :userId")
                                                    .OrderBy("userId ASC, teamId ASC")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                    .AddValue("userId", userId);

                // Set default for page.
                UserTeamAssociationPage page = new UserTeamAssociationPage();

                try
                {
                    do
                    {
                        // Get user team associations by statement.
                        page = userTeamAssociationService.getUserTeamAssociationsByStatement(
                            statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            int i = page.startIndex;
                            foreach (UserTeamAssociation userTeamAssociation in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) User team association between user with ID \"{1}\" and " +
                                    "team with ID \"{2}\" will be deleted.", i,
                                    userTeamAssociation.userId, userTeamAssociation.teamId);
                                i++;
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                    Console.WriteLine("Number of teams that the user will be removed from: " +
                                      page.totalResultSetSize);

                    if (page.totalResultSetSize > 0)
                    {
                        // Modify statement for action.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create action.
                        DeleteUserTeamAssociations action = new DeleteUserTeamAssociations();

                        // Perform action.
                        UpdateResult result =
                            userTeamAssociationService.performUserTeamAssociationAction(action,
                                                                                        statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine("Number of teams that the user was removed from: " +
                                              result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No user team associations were deleted.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Failed to delete user team associations. Exception says \"{0}\"",
                        e.Message);
                }
            }
        }
        private UpdateResult<SubCategoryViewModel> CreateNewSubcategory(SubCategoryViewModel subCategoryViewModel)
        {
            UpdateResult<SubCategoryViewModel> updateResult = new UpdateResult<SubCategoryViewModel>();

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                updateResult = subCategoryRepository.Update(subCategoryViewModel);

                if (updateResult.Success)
                {
                    AddCategorySubCategoryMap(dbContext, subCategoryViewModel);
                }

                updateResult.Success = true;
                updateResult.ErrorMessage = string.Empty;
            }

            return updateResult;
        }
Exemplo n.º 42
0
        public async Task <UpdateResult> UpdateAsync(Expression <Func <T, bool> > where, UpdateDefinition <T> update, UpdateOptions options, CancellationToken cancellationToken)
        {
            UpdateResult updateResult = await this.Collection.UpdateOneAsync(where, update, options, cancellationToken);

            return(updateResult);
        }
        public UpdateResult<PurchaseOrderViewModel> SavePurchaseOrder(PurchaseOrderViewModel purchaseOrder)
        {
            UpdateResult<PurchaseOrderViewModel> updateResult = new UpdateResult<PurchaseOrderViewModel>();

            bool isNewOrder = purchaseOrder.PurchaseOrderId == Guid.Empty ? true : false;

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {

                using (DbContextTransaction tran = dbContext.Database.BeginTransaction())
                {

                    try
                    {
                        updateResult = purchaseOrderRepository.Update(dbContext, purchaseOrder);

                        if (!updateResult.Success || updateResult.Entity == null)
                        {
                            return updateResult;
                        }

                        Dictionary<Guid, PurchaseOrderItemViewModel> existingPurchaseOrderItems = new Dictionary<Guid, PurchaseOrderItemViewModel>();

                        List<Guid> soItemIds = new List<Guid>();

                        if (!isNewOrder)
                        {
                            FindResult<PurchaseOrderItemViewModel> existingSOItemsResult = purchaseOrderItemRepository.FindBy(dbContext, x => x.PurchaseOrderId == purchaseOrder.PurchaseOrderId);

                            if (existingSOItemsResult.Success)
                            {
                                existingPurchaseOrderItems = existingSOItemsResult.Entities.ToDictionary(x => x.PurchaseOrderItemId, y => y);

                                soItemIds = existingPurchaseOrderItems.Keys.ToList();
                            }

                        }

                        purchaseOrder.PurchaseOrderId = updateResult.Entity.PurchaseOrderId;

                        foreach (PurchaseOrderItemViewModel sItem in purchaseOrder.PurchaseOrderItems)
                        {

                            sItem.PurchaseOrderId = purchaseOrder.PurchaseOrderId;

                            decimal quantityToUpdate = sItem.Quantity;

                            if (!soItemIds.Contains(sItem.PurchaseOrderItemId))
                            {

                                sItem.PurchaseOrderItemId = Guid.Empty;

                            }
                            else
                            {

                                quantityToUpdate -= existingPurchaseOrderItems[sItem.PurchaseOrderItemId].Quantity;
                                existingPurchaseOrderItems.Remove(sItem.PurchaseOrderItemId);

                            }

                            UpdateResult<PurchaseOrderItemViewModel> soItemUpdResult = purchaseOrderItemRepository.Update(dbContext, sItem);

                            if (soItemUpdResult.Success)
                            {
                                sItem.PurchaseOrderItemId = soItemUpdResult.Entity.PurchaseOrderId;

                                ProductVariant pv = dbContext.ProductVariantSet.Where(x => x.ProductVariantId == sItem.ProductVariantId).FirstOrDefault();

                                if (pv != null)
                                {
                                    pv.TransactionQuantity += sItem.Quantity;
                                    pv.LastPurchasePrice = sItem.Price;

                                    dbContext.ProductVariantSet.Attach(pv);
                                    dbContext.Entry(pv).State = EntityState.Modified;
                                    dbContext.SaveChanges();
                                }

                            }

                        }//For Each sItem in purchaseOrder.PurchaseOrderItems

                        foreach (Guid key in existingPurchaseOrderItems.Keys)
                        {
                            purchaseOrderItemRepository.Delete(dbContext, key);

                            PurchaseOrderItemViewModel pvItem = existingPurchaseOrderItems[key];

                            ProductVariant pv = dbContext.ProductVariantSet.Where(x => x.ProductVariantId == pvItem.ProductVariantId).FirstOrDefault();

                            if(pv != null)
                            {
                                pv.TransactionQuantity -= pvItem.Quantity;

                                dbContext.ProductVariantSet.Attach(pv);
                                dbContext.Entry(pv).State = EntityState.Modified;
                                dbContext.SaveChanges();
                            }

                        }

                        tran.Commit();
                        updateResult.Success = true;

                    }//Try
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        updateResult.Success = false;
                        updateResult.ErrorMessage = ex.Message;

                    }

                }//Using Transaction

            }// Using DBContext

            return updateResult;
        }
Exemplo n.º 44
0
        public async Task <UpdateResult> UpdateAsync(FilterDefinition <T> query, UpdateDefinition <T> update, UpdateOptions options, CancellationToken cancellationToken)
        {
            UpdateResult updateResult = await this.Collection.UpdateOneAsync(query, update, options, cancellationToken);

            return(updateResult);
        }
 private void UpdateEbootResult(UpdateResult result)
 {
     if (this.InvokeRequired)
     {
         BeginInvoke(new UpdateEbootResultDeleg(UpdateEbootResult), new object[] { result });
         return;
     }
     //add to list
     Debug.WriteLine(String.Format("Update eboot {0}", result));
     MessageBox.Show(String.Format("Update eboot {0}", result));
 }
Exemplo n.º 46
0
        public UpdateResult<ProductViewModel> SaveProduct(ProductViewModel productViewModel)
        {
            UpdateResult<ProductViewModel> result = new UpdateResult<ProductViewModel>() { Success = false };

            Guid categoryId = productViewModel.CategorySubCategoryMap.CategoryId;
            Guid subCategoryId = productViewModel.CategorySubCategoryMap.SubCategoryId;

            using (InnoventoryDBContext dbContext = new InnoventoryDBContext())
            {
                try
                {
                    string categoryCode = categoryRepository.GetCategoryCode(categoryId);

                    string subCategoryCode = subCategoryRepository.GetSubCategoryCode(subCategoryId);

                    string productName = Utility.GetNormalizedString(productViewModel.ProductName);

                    string firstTwo = productName.Substring(0, 2).ToUpper();

                    //string strSeed = DateTime.Now.ToString("MMddyyHHmm");

                    //int numberSeed = 0;

                    //if(!int.TryParse(strSeed, out numberSeed))
                    //{
                    //    numberSeed = int.MaxValue;
                    //}

                    //int seed = int.Parse(strSeed);

                    UpdateResult<ProductViewModel> updateResult = productRepository.Update(dbContext, productViewModel);

                    if (!updateResult.Success)
                    {
                        return updateResult;
                    }

                    foreach (ProductVariantViewModel prvm in productViewModel.ProductVariants)
                    {

                        prvm.ProductId = updateResult.Entity.ProductId;

                        ProductVariant pv = dbContext.ProductVariantSet.Where(x => x.ProductVariantId == prvm.ProductVariantId).FirstOrDefault();

                        if (pv == null)
                        {
                            prvm.ProductVariantId = Guid.Empty;
                            Random random = new Random();

                            string randomNumber = random.Next(999999).ToString().PadLeft(10, "0"[0]);

                            string skuCode = string.Format("ST-{0}{1}{2}{3}", categoryCode, subCategoryCode, firstTwo, randomNumber);

                            prvm.SKUCode = skuCode;
                        }

                        UpdateResult<ProductVariantViewModel> pvUpdateResult = productVariantRepository.Update(prvm);

                        if (!pvUpdateResult.Success)
                        {
                            result.Success = false;
                            result.ErrorMessage = pvUpdateResult.ErrorMessage;
                            return result;
                        }

                        List<ProductVariantAttributeValue> productVariantAttributeValueMaps = dbContext.ProductVariantAttributeValueSet
                                            .Where(x => x.ProductVariantId == prvm.ProductVariantId).ToList();

                        List<Guid> attributeSelectValueIds = new List<Guid>();

                        foreach (var item in prvm.ProductVariantAttributeValues)
                        {
                            if (item.ProductAttributeId != Guid.Empty)
                            {

                                if ((!item.AttributeValueListId.HasValue
                                     || item.AttributeValueListId.Value == Guid.Empty)
                                     && !string.IsNullOrEmpty(item.ProductAttributeValue))
                                {
                                    SubCategoryAttributeMap scAttrMap = dbContext.SubCategoryAttributeMapSet
                                        .Where(x => x.ProductAttributeId == item.ProductAttributeId && x.SubCategoryId == subCategoryId).FirstOrDefault();

                                    AttributeValueList avl = new AttributeValueList()
                                    {

                                        AttributeValueListId = Guid.NewGuid(),
                                        AttributeValue = item.ProductAttributeValue,
                                        CategoryId = categoryId,
                                        SubCategoryAttributeMapID = scAttrMap.SubCategoryAttributeMapId,
                                    };

                                    dbContext.AttributeValueListSet.Add(avl);

                                    item.AttributeValueListId = avl.AttributeValueListId;

                                    ProductVariantAttributeValue newPVAttrValue = new ProductVariantAttributeValue()
                                    {
                                        ProductVariantId = prvm.ProductVariantId,
                                        AttributeValueListId = item.AttributeValueListId.Value,
                                    };

                                    dbContext.ProductVariantAttributeValueSet.Add(newPVAttrValue);
                                    dbContext.SaveChanges();

                                }
                                else if (item.AttributeValueListId.HasValue && item.AttributeValueListId != Guid.Empty && !string.IsNullOrEmpty(item.ProductAttributeValue))
                                {
                                    ProductVariantAttributeValue pvAttrValue = productVariantAttributeValueMaps
                                                        .Where(x => x.AttributeValueListId == item.AttributeValueListId.Value)
                                                        .FirstOrDefault();

                                    if (pvAttrValue != null)
                                    {
                                        productVariantAttributeValueMaps.Remove(pvAttrValue);
                                    }
                                    else
                                    {
                                        ProductVariantAttributeValue newPVAttrValue = new ProductVariantAttributeValue()
                                        {
                                            ProductVariantId = prvm.ProductVariantId,
                                            AttributeValueListId = item.AttributeValueListId.Value,
                                        };

                                        dbContext.ProductVariantAttributeValueSet.Add(newPVAttrValue);
                                        dbContext.SaveChanges();

                                    }
                                }
                            }

                        }

                        if (productVariantAttributeValueMaps != null && productVariantAttributeValueMaps.Count > 0)
                        {
                            foreach (var pvavm in productVariantAttributeValueMaps)
                            {
                                dbContext.ProductVariantAttributeValueSet.Remove(pvavm);

                            }

                            dbContext.SaveChanges();
                        }
                    }

                    result.Success = true;
                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.ErrorMessage = ex.Message;
                }
            }

            return result;
        }