コード例 #1
0
ファイル: ScriptingExtensions.cs プロジェクト: jrlost/squidex
        public static async Task ExecuteCreateScriptAsync(this AssetOperation operation, CreateAsset create)
        {
            var script = operation.App.AssetScripts?.Create;

            if (string.IsNullOrWhiteSpace(script))
            {
                return;
            }

            var parentPath = await GetPathAsync(operation, create.ParentId);

            // Script vars are just wrappers over dictionaries for better performance.
            var vars = new AssetScriptVars
            {
                // Tags and metadata are mutable and can be changed from the scripts, but not replaced.
                Command = new AssetCommandScriptVars
                {
                    FileHash   = create.FileHash,
                    FileName   = create.File.FileName,
                    FileSlug   = create.File.FileName.Slugify(),
                    FileSize   = create.File.FileSize,
                    Metadata   = create.Metadata,
                    MimeType   = create.File.MimeType,
                    ParentId   = create.ParentId,
                    ParentPath = parentPath,
                    Tags       = create.Tags
                },
                Operation = "Create"
            };

            await ExecuteScriptAsync(operation, script, vars);
        }
コード例 #2
0
ファイル: AssetIdentifier.cs プロジェクト: OkashiKami/Odyssey
 public AssetIdentifier(string name, string path, string type, AssetOperation assetOperation = AssetOperation.None)
 {
     Name      = name;
     Path      = path;
     Type      = type;
     Operation = assetOperation;
 }
コード例 #3
0
        public static Task ExecuteUpdateScriptAsync(this AssetOperation operation, UpdateAsset update)
        {
            var script = operation.App.AssetScripts?.Update;

            if (string.IsNullOrWhiteSpace(script))
            {
                return(Task.CompletedTask);
            }

            // Tags and metadata are mutable and can be changed from the scripts, but not replaced.
            var vars = new ScriptVars
            {
                // Use a dictionary for better performance, because no reflection is involved.
                [ScriptKeys.Command] = new Dictionary <string, object?>
                {
                    [ScriptKeys.Metadata] = update.Metadata.Mutable(),
                    [ScriptKeys.FileHash] = update.FileHash,
                    [ScriptKeys.FileName] = update.File.FileName,
                    [ScriptKeys.FileSize] = update.File.FileSize,
                    [ScriptKeys.MimeType] = update.File.MimeType,
                    [ScriptKeys.Tags]     = update.Tags
                },
                [ScriptKeys.Operation] = "Update"
            };

            return(ExecuteScriptAsync(operation, script, vars));
        }
コード例 #4
0
ファイル: ScriptingExtensions.cs プロジェクト: jrlost/squidex
        public static Task ExecuteAnnotateScriptAsync(this AssetOperation operation, AnnotateAsset annotate)
        {
            var script = operation.App.AssetScripts?.Annotate;

            if (string.IsNullOrWhiteSpace(script))
            {
                return(Task.CompletedTask);
            }

            // Script vars are just wrappers over dictionaries for better performance.
            var vars = new AssetScriptVars
            {
                // Tags are mutable and can be changed from the scripts, but not replaced.
                Command = new AssetCommandScriptVars
                {
                    IsProtected = annotate.IsProtected,
                    Metadata    = annotate.Metadata,
                    FileName    = annotate.FileName,
                    FileSlug    = annotate.Slug,
                    Tags        = annotate.Tags
                },
                Operation = "Annotate"
            };

            return(ExecuteScriptAsync(operation, script, vars));
        }
コード例 #5
0
        private static async Task ExecuteScriptAsync(AssetOperation operation, string script, ScriptVars vars)
        {
            var snapshot = operation.Snapshot;

            var parentPath = await GetPathAsync(operation, snapshot.ParentId);

            // Use a dictionary for better performance, because no reflection is involved.
            var asset = new Dictionary <string, object?>
            {
                [ScriptKeys.Metadata]    = snapshot.ReadonlyMetadata(),
                [ScriptKeys.FileHash]    = snapshot.FileHash,
                [ScriptKeys.FileName]    = snapshot.FileName,
                [ScriptKeys.FileSize]    = snapshot.FileSize,
                [ScriptKeys.FileSlug]    = snapshot.Slug,
                [ScriptKeys.FileVersion] = snapshot.FileVersion,
                [ScriptKeys.IsProtected] = snapshot.IsProtected,
                [ScriptKeys.MimeType]    = snapshot.MimeType,
                [ScriptKeys.ParentId]    = snapshot.ParentId,
                [ScriptKeys.ParentPath]  = parentPath,
                [ScriptKeys.Tags]        = snapshot.ReadonlyTags()
            };

            vars[ScriptKeys.AppId]   = operation.App.Id;
            vars[ScriptKeys.AppName] = operation.App.Name;
            vars[ScriptKeys.AssetId] = operation.CommandId;
            vars[ScriptKeys.Asset]   = asset;
            vars[ScriptKeys.User]    = operation.User;

            var scriptEngine = operation.Resolve <IScriptEngine>();

            await scriptEngine.ExecuteAsync(vars, script, Options);
        }
コード例 #6
0
        public static async Task ExecuteCreateScriptAsync(this AssetOperation operation, CreateAsset create)
        {
            var script = operation.App.AssetScripts?.Create;

            if (string.IsNullOrWhiteSpace(script))
            {
                return;
            }

            var parentPath = await GetPathAsync(operation, create.ParentId);

            // Tags and metadata are mutable and can be changed from the scripts, but not replaced.
            var vars = new ScriptVars
            {
                // Use a dictionary for better performance, because no reflection is involved.
                [ScriptKeys.Command] = new Dictionary <string, object?>
                {
                    [ScriptKeys.Metadata]   = create.Metadata.Mutable(),
                    [ScriptKeys.FileHash]   = create.FileHash,
                    [ScriptKeys.FileName]   = create.File.FileName,
                    [ScriptKeys.FileSize]   = create.File.FileSize,
                    [ScriptKeys.FileSlug]   = create.File.FileName.Slugify(),
                    [ScriptKeys.MimeType]   = create.File.MimeType,
                    [ScriptKeys.ParentId]   = create.ParentId,
                    [ScriptKeys.ParentPath] = parentPath,
                    [ScriptKeys.Tags]       = create.Tags
                },
                [ScriptKeys.Operation] = "Create"
            };

            await ExecuteScriptAsync(operation, script, vars);
        }
コード例 #7
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the AssetServiceClient.
            AssetServiceClient assetService =
                client.GetService(Services.V6.AssetService);

            // Creates an image content.
            byte[] imageContent = MediaUtilities.GetAssetDataFromUrl(IMAGE_URL, client.Config);

            // Creates an image asset.
            ImageAsset imageAsset = new ImageAsset()
            {
                Data     = ByteString.CopyFrom(imageContent),
                FileSize = imageContent.Length,
                MimeType = MimeType.ImageJpeg,
                FullSize = new ImageDimension()
                {
                    HeightPixels = 315,
                    WidthPixels  = 600,
                    Url          = IMAGE_URL
                }
            };

            // Creates an asset.
            Asset asset = new Asset()
            {
                // Optional: Provide a unique friendly name to identify your asset.
                // If you specify the name field, then both the asset name and the image being
                // uploaded should be unique, and should not match another ACTIVE asset in this
                // customer account.
                // Name = 'Jupiter Trip #' + ExampleUtilities.GetRandomString(),
                Type       = AssetType.Image,
                ImageAsset = imageAsset
            };

            // Creates an asset operation.
            AssetOperation operation = new AssetOperation()
            {
                Create = asset
            };

            try
            {
                // Issues a mutate request to add the asset.
                MutateAssetsResponse response =
                    assetService.MutateAssets(customerId.ToString(), new[] { operation });

                // Displays the result.
                Console.WriteLine($"Image asset with resource name: " +
                                  $"'{response.Results.First().ResourceName}' is created.");
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
コード例 #8
0
        /// <summary>
        /// Adds an image to the Google Ads account.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The client customer ID.</param>
        /// <param name="imageUrl">The URL of the image.</param>
        /// <param name="assetName">The name of the asset.</param>
        /// <returns>The string resource name of the newly uploaded asset.</returns>
        private string uploadAsset(GoogleAdsClient client, long customerId,
                                   string imageUrl, string assetName)
        {
            // Creates the asset service client.
            AssetServiceClient assetServiceClient = client.GetService(Services.V6.AssetService);

            byte[] imageData = MediaUtilities.GetAssetDataFromUrl(imageUrl, client.Config);

            // Creates the image asset.
            Asset asset = new Asset()
            {
                Name       = assetName,
                Type       = AssetType.Image,
                ImageAsset = new ImageAsset()
                {
                    Data = ByteString.CopyFrom(imageData)
                }
            };

            // Creates the asset operation.
            AssetOperation operation = new AssetOperation()
            {
                Create = asset
            };

            // Adds the image asset.
            MutateAssetsResponse response = assetServiceClient.MutateAssets(customerId.ToString()
                                                                            , new[] { operation });
            string imageResourceName = response.Results.First().ResourceName;

            Console.WriteLine($"Created image asset with resource name '{imageResourceName}'.");
            return(imageResourceName);
        }
コード例 #9
0
        /// <summary>
        /// Uploads the image from the specified <paramref name="url"/>.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="url">The image URL.</param>
        /// <returns>ID of the uploaded image.</returns>
        private static long UploadImageAsset(AdWordsUser user, string url)
        {
            using (AssetService assetService =
                       (AssetService)user.GetService(AdWordsService.v201809.AssetService))
            {
                // Create the image asset.
                ImageAsset imageAsset = new ImageAsset()
                {
                    // Optional: Provide a unique friendly name to identify your asset. If you
                    // specify the assetName field, then both the asset name and the image being
                    // uploaded should be unique, and should not match another ACTIVE asset in this
                    // customer account.
                    // assetName = "Image asset " + ExampleUtilities.GetRandomString(),
                    imageData = MediaUtilities.GetAssetDataFromUrl(url, user.Config),
                };

                // Create the operation.
                AssetOperation operation = new AssetOperation()
                {
                    @operator = Operator.ADD,
                    operand   = imageAsset
                };

                // Create the asset and return the ID.
                return(assetService.mutate(new AssetOperation[]
                {
                    operation
                }).value[0].assetId);
            }
        }
コード例 #10
0
ファイル: ScriptingExtensions.cs プロジェクト: jrlost/squidex
        public static Task ExecuteUpdateScriptAsync(this AssetOperation operation, UpdateAsset update)
        {
            var script = operation.App.AssetScripts?.Update;

            if (string.IsNullOrWhiteSpace(script))
            {
                return(Task.CompletedTask);
            }

            // Script vars are just wrappers over dictionaries for better performance.
            var vars = new AssetScriptVars
            {
                // Tags and metadata are mutable and can be changed from the scripts, but not replaced.
                Command = new AssetCommandScriptVars
                {
                    Metadata = update.Metadata,
                    FileHash = update.FileHash,
                    FileName = update.File.FileName,
                    FileSize = update.File.FileSize,
                    MimeType = update.File.MimeType,
                    Tags     = update.Tags
                },
                Operation = "Update"
            };

            return(ExecuteScriptAsync(operation, script, vars));
        }
コード例 #11
0
ファイル: ScriptingExtensions.cs プロジェクト: jrlost/squidex
        private static async Task ExecuteScriptAsync(AssetOperation operation, string script, AssetScriptVars vars)
        {
            var snapshot = operation.Snapshot;

            var parentPath = await GetPathAsync(operation, snapshot.ParentId);

            // Script vars are just wrappers over dictionaries for better performance.
            var asset = new AssetEntityScriptVars
            {
                Metadata    = snapshot.Metadata,
                FileHash    = snapshot.FileHash,
                FileName    = snapshot.FileName,
                FileSize    = snapshot.FileSize,
                FileSlug    = snapshot.Slug,
                FileVersion = snapshot.FileVersion,
                IsProtected = snapshot.IsProtected,
                MimeType    = snapshot.MimeType,
                ParentId    = snapshot.ParentId,
                ParentPath  = parentPath,
                Tags        = snapshot.Tags
            };

            vars.AppId   = operation.App.Id;
            vars.AppName = operation.App.Name;
            vars.AssetId = operation.CommandId;
            vars.Asset   = asset;
            vars.User    = operation.User;

            var scriptEngine = operation.Resolve <IScriptEngine>();

            await scriptEngine.ExecuteAsync(vars, script, Options);
        }
コード例 #12
0
        public static async Task <HashSet <string> > NormalizeTags(this AssetOperation operation, HashSet <string> tags)
        {
            var tagService = operation.Resolve <ITagService>();

            var normalized = await tagService.NormalizeTagsAsync(operation.App.Id, TagGroups.Assets, tags, operation.Snapshot.Tags);

            return(new HashSet <string>(normalized.Values));
        }
コード例 #13
0
        public async Task <OperationResult> BuyAsset(int portfolioId, string ticket, int price, int amount,
                                                     int assetTypeId, DateTime date)
        {
            var portfolio = await _financeDataService.EfContext.Portfolios.FindAsync(portfolioId);

            var buyAction =
                await _financeDataService.EfContext.AssetActions.FirstOrDefaultAsync(a =>
                                                                                     a.Name == SeedFinanceData.BUY_ACTION);

            var assetType = await _financeDataService.EfContext.AssetTypes.FindAsync(assetTypeId);

            if (!CommonValidate(price, amount, assetType, portfolio, out var message))
            {
                return(new OperationResult
                {
                    IsSuccess = false,
                    Message = message
                });
            }

            var currentBalanceResult = await _balanceService.GetBalance(portfolioId, portfolio.UserId);

            if (price > currentBalanceResult.Result)
            {
                return(new OperationResult
                {
                    IsSuccess = false,
                    Message = "Недостаточно средств"
                });
            }

            var assetOperation = new AssetOperation
            {
                Portfolio     = portfolio,
                PortfolioId   = portfolioId,
                AssetAction   = buyAction,
                AssetActionId = buyAction.Id,
                AssetType     = assetType,
                AssetTypeId   = assetType.Id,
                Date          = date,
                PaymentPrice  = price,
                Ticket        = ticket,
                Amount        = amount
            };

            await _financeDataService.EfContext.AssetOperations.AddAsync(assetOperation);

            await _financeDataService.EfContext.SaveChangesAsync();

            GetPortfoliosData(portfolio.UserId, true);

            return(new OperationResult
            {
                IsSuccess = true,
                Message = "Актив куплен успешно"
            });
        }
コード例 #14
0
        public async Task <OperationResult> SellAsset(int portfolioId, string ticket, int price, int amount,
                                                      int assetTypeId, DateTime date)
        {
            var portfolio = await _financeDataService.EfContext.Portfolios.FindAsync(portfolioId);

            var sellAction =
                await _financeDataService.EfContext.AssetActions.FirstOrDefaultAsync(a =>
                                                                                     a.Name == SeedFinanceData.SELL_ACTION);

            var assetType = await _financeDataService.EfContext.AssetTypes.FindAsync(assetTypeId);

            if (!CommonValidate(price, amount, assetType, portfolio, out var message))
            {
                return(new OperationResult
                {
                    IsSuccess = false,
                    Message = message
                });
            }

            if (!HasAsset(portfolioId, amount, ticket, portfolio.UserId))
            {
                return(new OperationResult
                {
                    IsSuccess = false,
                    Message = "Такого количества активов нет в наличии"
                });
            }

            var assetOperation = new AssetOperation
            {
                Portfolio     = portfolio,
                PortfolioId   = portfolioId,
                AssetAction   = sellAction,
                AssetActionId = sellAction.Id,
                AssetType     = assetType,
                AssetTypeId   = assetType.Id,
                Date          = date,
                PaymentPrice  = price,
                Ticket        = ticket,
                Amount        = amount
            };

            await _financeDataService.EfContext.AssetOperations.AddAsync(assetOperation);

            await _financeDataService.EfContext.SaveChangesAsync();

            GetPortfoliosData(portfolio.UserId, true);

            return(new OperationResult
            {
                IsSuccess = true,
                Message = "Актив продан успешно"
            });
        }
コード例 #15
0
        // [END add_smart_display_ad_4]

        /// <summary>
        /// Uploads the image asset.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="imageUrl">The image URL.</param>
        /// <param name="width">The image width in pixels.</param>
        /// <param name="height">The image height in pixels.</param>
        /// <param name="imageName">Name of the image asset.</param>
        /// <returns>The resource name of the asset.</returns>
        // [START add_smart_display_ad_3]
        private static string UploadImageAsset(GoogleAdsClient client, long customerId,
                                               string imageUrl, long width, long height, string imageName)
        {
            // Get the AssetServiceClient.
            AssetServiceClient assetService =
                client.GetService(Services.V10.AssetService);

            // Creates an image content.
            byte[] imageContent = MediaUtilities.GetAssetDataFromUrl(imageUrl, client.Config);

            // Creates an image asset.
            ImageAsset imageAsset = new ImageAsset()
            {
                Data     = ByteString.CopyFrom(imageContent),
                FileSize = imageContent.Length,
                MimeType = MimeType.ImageJpeg,
                FullSize = new ImageDimension()
                {
                    HeightPixels = height,
                    WidthPixels  = width,
                    Url          = imageUrl
                }
            };

            // Creates an asset.
            Asset asset = new Asset()
            {
                // Optional: Provide a unique friendly name to identify your asset.
                // If you specify the name field, then both the asset name and the image being
                // uploaded should be unique, and should not match another ACTIVE asset in this
                // customer account.
                // Name = 'Jupiter Trip #' + ExampleUtilities.GetRandomString(),
                Type       = AssetType.Image,
                ImageAsset = imageAsset,
                Name       = imageName
            };

            // Creates an asset operation.
            AssetOperation operation = new AssetOperation()
            {
                Create = asset
            };

            // Issues a mutate request to add the asset.
            MutateAssetsResponse response =
                assetService.MutateAssets(customerId.ToString(), new[] { operation });

            string assetResourceName = response.Results.First().ResourceName;

            // Print out some information about the added asset.
            Console.WriteLine($"Added asset with resource name = '{assetResourceName}'.");

            return(assetResourceName);
        }
コード例 #16
0
        public static async Task CheckReferrersAsync(this AssetOperation operation)
        {
            var contentRepository = operation.Resolve <IContentRepository>();

            var hasReferrer = await contentRepository.HasReferrersAsync(operation.App.Id, operation.CommandId, SearchScope.All, default);

            if (hasReferrer)
            {
                throw new DomainException(T.Get("assets.referenced"), "OBJECT_REFERENCED");
            }
        }
コード例 #17
0
ファイル: ScriptingExtensions.cs プロジェクト: jrlost/squidex
        private static async Task <Array> GetPathAsync(AssetOperation operation, DomainId parentId)
        {
            if (parentId == default)
            {
                return(Array.Empty <object>());
            }

            var assetQuery = operation.Resolve <IAssetQueryService>();
            var assetPath  = await assetQuery.FindAssetFolderAsync(operation.App.Id, parentId);

            return(assetPath.Select(x => new { id = x.Id, folderName = x.FolderName }).ToArray());
        }
 /// <summary>Snippet for MutateAssets</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void MutateAssets()
 {
     // Create client
     AssetServiceClient assetServiceClient = AssetServiceClient.Create();
     // Initialize request argument(s)
     string customerId = "";
     IEnumerable <AssetOperation> operations = new AssetOperation[]
     {
         new AssetOperation(),
     };
     // Make the request
     MutateAssetsResponse response = assetServiceClient.MutateAssets(customerId, operations);
 }
コード例 #19
0
        /// <summary>
        /// 読み込み済み単体アセットの取得
        /// </summary>
        /// <param name="assetBundleName">取得したいアセットが含まれているアセットバンドル名</param>
        /// <param name="assetName">取得したいアセット名</param>
        public T GetLoadedAsset <T>(string assetBundleName, string assetName) where T : UnityEngine.Object
        {
            AssetOperation <T> assetOperation = null;

            if (this.CheckAssetLoaded <AssetOperation <T> >(assetBundleName, assetName, out assetOperation))
            {
                return(assetOperation.GetAsset());
            }
            else
            {
                return(null);
            }
        }
コード例 #20
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        public void Run(AdWordsUser user)
        {
            using (AssetService assetService =
                       (AssetService)user.GetService(AdWordsService.v201809.AssetService))
            {
                // Create the image asset.
                ImageAsset imageAsset = new ImageAsset()
                {
                    // Optional: Provide a unique friendly name to identify your asset. If you
                    // specify the assetName field, then both the asset name and the image being
                    // uploaded should be unique, and should not match another ACTIVE asset in this
                    // customer account.
                    // assetName = "Jupiter Trip " + ExampleUtilities.GetRandomString(),
                    imageData =
                        MediaUtilities.GetAssetDataFromUrl("https://goo.gl/3b9Wfh", user.Config),
                };

                // Create the operation.
                AssetOperation operation = new AssetOperation()
                {
                    @operator = Operator.ADD,
                    operand   = imageAsset
                };

                try
                {
                    // Create the asset.
                    AssetReturnValue result = assetService.mutate(new AssetOperation[]
                    {
                        operation
                    });

                    // Display the results.
                    if (result != null && result.value != null && result.value.Length > 0)
                    {
                        Asset newAsset = result.value[0];

                        Console.WriteLine("Image asset with id = '{0}' and name = {1} was created.",
                                          newAsset.assetId, newAsset.assetName);
                    }
                    else
                    {
                        Console.WriteLine("No image asset was created.");
                    }
                }
                catch (Exception e)
                {
                    throw new System.ApplicationException("Failed to create image asset.", e);
                }
            }
        }
コード例 #21
0
        private int ApplyAssetOperation(AssetOperation operation, int balance)
        {
            if (operation.AssetAction.Name == SeedFinanceData.BUY_ACTION)
            {
                balance -= operation.PaymentPrice;
            }

            if (operation.AssetAction.Name == SeedFinanceData.SELL_ACTION)
            {
                balance += operation.PaymentPrice;
            }

            return(balance);
        }
コード例 #22
0
        // [START add_asset]
        /// <summary>
        /// Creates an Asset to use in dynamic remarketing.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID.</param>
        /// <returns>The resource name of the newly created asset.</returns>
        private string CreateAsset(GoogleAdsClient client, long customerId)
        {
            AssetServiceClient assetService = client.GetService(Services.V10.AssetService);

            // Creates a DynamicEducationAsset.
            // See https://support.google.com/google-ads/answer/6053288?#zippy=%2Ceducation for a
            // detailed explanation of the field format.
            DynamicEducationAsset educationAsset = new DynamicEducationAsset()
            {
                // Defines meta-information about the school and program.
                SchoolName         = "The University of Unknown",
                Address            = "Building 1, New York, 12345, USA",
                ProgramName        = "BSc. Computer Science",
                Subject            = "Computer Science",
                ProgramDescription = "Slinging code for fun and profit!",
                // Sets up the program ID which is the ID that should be specified in
                // the tracking pixel.
                ProgramId = "bsc-cs-uofu",
                // Sets up the location ID which may additionally be specified in the
                // tracking pixel.
                LocationId     = "nyc",
                ImageUrl       = "https://gaagl.page.link/Eit5",
                AndroidAppLink = "android-app://com.example.android/http/example.com/gizmos?1234",
                IosAppLink     = "exampleApp://content/page",
                IosAppStoreId  = 123L
            };
            Asset asset = new Asset()
            {
                DynamicEducationAsset = educationAsset,
                // The final_urls list must not be empty
                FinalUrls = { "https://www.example.com" }
            };

            // Creates an operation to add the asset.
            AssetOperation operation = new AssetOperation()
            {
                Create = asset
            };

            // Sends the mutate request.
            MutateAssetsResponse response =
                assetService.MutateAssets(customerId.ToString(), new[] { operation });
            // Prints some information about the response.
            string resourceName = response.Results[0].ResourceName;

            Console.Write($"Created a dynamic education asset with resource name {resourceName}.");
            return(resourceName);
        }
コード例 #23
0
        public void RegisterOperation(AssetOperation operation)
        {
            if (operation.AssetAction.Name == SeedFinanceData.BUY_ACTION)
            {
                Amount      += operation.Amount;
                BoughtPrice += operation.PaymentPrice;
            }

            if (operation.AssetAction.Name == SeedFinanceData.SELL_ACTION)
            {
                Amount      -= operation.Amount;
                BoughtPrice -= operation.PaymentPrice;
            }

            Operations.Add(operation);
        }
コード例 #24
0
        /// <summary>Snippet for MutateAssetsAsync</summary>
        public async Task MutateAssetsAsync()
        {
            // Snippet: MutateAssetsAsync(string, IEnumerable<AssetOperation>, CallSettings)
            // Additional: MutateAssetsAsync(string, IEnumerable<AssetOperation>, CancellationToken)
            // Create client
            AssetServiceClient assetServiceClient = await AssetServiceClient.CreateAsync();

            // Initialize request argument(s)
            string customerId = "";
            IEnumerable <AssetOperation> operations = new AssetOperation[]
            {
                new AssetOperation(),
            };
            // Make the request
            MutateAssetsResponse response = await assetServiceClient.MutateAssetsAsync(customerId, operations);

            // End snippet
        }
コード例 #25
0
        private void RegisterOperation(List<AssetInfo> assets, AssetOperation operation)
        {
            if (operation.AssetType.Name == SeedFinanceData.STOCK_ASSET_TYPE)
            {
                var asset = assets.FirstOrDefault(a => a.Ticket == operation.Ticket);

                if (asset == null)
                {
                    var stockInfo = new StockInfo(_marketData, _financeDataService, operation.Ticket);
                    assets.Add(stockInfo);
                    asset = stockInfo;
                }
                
                asset.RegisterOperation(operation);
            }

            if (operation.AssetType.Name == SeedFinanceData.FOND_ASSET_TYPE)
            {
                var asset = assets.FirstOrDefault(a => a.Ticket == operation.Ticket);

                if (asset == null)
                {
                    var fondInfo = new FondInfo(_marketData, _financeDataService, operation.Ticket);
                    assets.Add(fondInfo);
                    asset = fondInfo;
                }

                asset.RegisterOperation(operation);
            }

            if (operation.AssetType.Name == SeedFinanceData.BOND_ASSET_TYPE)
            {
                var asset = assets.FirstOrDefault(a => a.Ticket == operation.Ticket);

                if (asset == null)
                {
                    var bondInfo = new BondInfo(_marketData, _financeDataService, operation.Ticket);
                    assets.Add(bondInfo);
                    asset = bondInfo;
                }

                asset.RegisterOperation(operation);
            }
        }
コード例 #26
0
        public static async Task MustMoveToValidFolder(this AssetOperation operation, DomainId parentId)
        {
            // If moved to root folder or not moved at all, we can just skip the validation.
            if (parentId == DomainId.Empty || parentId == operation.Snapshot.ParentId)
            {
                return;
            }

            var assetQuery = operation.Resolve <IAssetQueryService>();

            var path = await assetQuery.FindAssetFolderAsync(operation.App.Id, parentId);

            if (path.Count == 0)
            {
                operation.AddError(T.Get("assets.folderNotFound"), nameof(MoveAsset.ParentId)).ThrowOnErrors();
            }

            operation.ThrowOnErrors();
        }
コード例 #27
0
        public static Task ExecuteDeleteScriptAsync(this AssetOperation operation, DeleteAsset delete)
        {
            var script = operation.App.AssetScripts?.Delete;

            if (string.IsNullOrWhiteSpace(script))
            {
                return(Task.CompletedTask);
            }

            var vars = new ScriptVars
            {
                // Use a dictionary for better performance, because no reflection is involved.
                [ScriptKeys.Command] = new Dictionary <string, object?>
                {
                    [ScriptKeys.Permanent] = delete.Permanent
                },
                [ScriptKeys.Operation] = "Delete"
            };

            return(ExecuteScriptAsync(operation, script, vars));
        }
コード例 #28
0
ファイル: ScriptingExtensions.cs プロジェクト: jrlost/squidex
        public static Task ExecuteDeleteScriptAsync(this AssetOperation operation, DeleteAsset delete)
        {
            var script = operation.App.AssetScripts?.Delete;

            if (string.IsNullOrWhiteSpace(script))
            {
                return(Task.CompletedTask);
            }

            // Script vars are just wrappers over dictionaries for better performance.
            var vars = new AssetScriptVars
            {
                Command = new AssetCommandScriptVars
                {
                    Permanent = delete.Permanent
                },
                Operation = "Delete"
            };

            return(ExecuteScriptAsync(operation, script, vars));
        }
コード例 #29
0
        /// <summary>
        /// Creates a media bundle from the assets in a zip file. The zip file contains the
        /// HTML5 components.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <returns>The string resource name of the newly uploaded media bundle.</returns>
        private string CreateMediaBundleAsset(GoogleAdsClient client, long customerId)
        {
            // Gets the AssetService.
            AssetServiceClient assetServiceClient = client.GetService(Services.V10.AssetService);

            // The HTML5 zip file contains all the HTML, CSS, and images needed for the
            // HTML5 ad. For help on creating an HTML5 zip file, check out Google Web
            // Designer (https://www.google.com/webdesigner/).
            byte[] html5Zip = MediaUtilities.GetAssetDataFromUrl("https://gaagl.page.link/ib87",
                                                                 client.Config);

            // Creates the media bundle asset.
            Asset mediaBundleAsset = new Asset()
            {
                Type             = AssetTypeEnum.Types.AssetType.MediaBundle,
                MediaBundleAsset = new MediaBundleAsset()
                {
                    Data = ByteString.CopyFrom(html5Zip)
                },
                Name = "Ad Media Bundle"
            };

            // Creates the asset operation.
            AssetOperation operation = new AssetOperation()
            {
                Create = mediaBundleAsset
            };

            // Adds the asset to the client account.
            MutateAssetsResponse response = assetServiceClient.MutateAssets(customerId.ToString(),
                                                                            new[] { operation });

            // Displays the resulting resource name.
            string uploadedAssetResourceName = response.Results.First().ResourceName;

            Console.WriteLine($"Uploaded media bundle: {uploadedAssetResourceName}");

            return(uploadedAssetResourceName);
        }
コード例 #30
0
ファイル: ScriptingExtensions.cs プロジェクト: jrlost/squidex
        public static async Task ExecuteMoveScriptAsync(this AssetOperation operation, MoveAsset move)
        {
            var script = operation.App.AssetScripts?.Move;

            if (string.IsNullOrWhiteSpace(script))
            {
                return;
            }

            var parentPath = await GetPathAsync(operation, move.ParentId);

            // Script vars are just wrappers over dictionaries for better performance.
            var vars = new AssetScriptVars
            {
                Command = new AssetCommandScriptVars
                {
                    ParentId   = move.ParentId,
                    ParentPath = parentPath
                },
                Operation = "Move"
            };

            await ExecuteScriptAsync(operation, script, vars);
        }