### Video Upload Parameters Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/03-upload-api.md Demonstrates how to set up parameters for uploading a video file, including eager transformations. ```csharp var videoParams = new VideoUploadParams() { File = new FileDescription(@"C:\video.mp4"), PublicId = "my_video", EagerTransforms = new List() { new Transformation() .Format("mp4") .VideoCodec("h264") .Quality("auto"), new Transformation() .Format("webm") .VideoCodec("vp9") .Quality("auto") } }; var result = cloudinary.Upload(videoParams); ``` -------------------------------- ### Raw File Upload Parameters Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/03-upload-api.md Shows how to configure parameters for uploading a raw file, such as a PDF document. ```csharp var rawParams = new RawUploadParams() { File = new FileDescription(@"C:\document.pdf"), PublicId = "my_pdf", Type = "upload" }; var result = cloudinary.Upload(rawParams, "auto"); ``` -------------------------------- ### Cloudinary Initialization Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Demonstrates how to initialize the Cloudinary SDK with configuration settings. This is the first step before using any Cloudinary functionalities. ```csharp var cloudinary = new Cloudinary(new Account("my_cloud_name", "my_api_key", "my_api_secret")); ``` -------------------------------- ### Dependency Injection Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Shows how to integrate the Cloudinary SDK with a dependency injection container. This promotes modularity and testability. ```csharp // Example using Microsoft.Extensions.DependencyInjection services.AddSingleton(provider => { var config = new CloudinaryConfiguration { CloudName = "my_cloud_name", ApiKey = "my_api_key", ApiSecret = "my_api_secret" }; return new Cloudinary(config); }); ``` -------------------------------- ### Install CloudinaryDotNet NuGet Package Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/README.md Use this command in the Package Manager Console to install the CloudinaryDotNet NuGet package. ```csharp PM> Install-Package CloudinaryDotNet ``` -------------------------------- ### Dependency Injection Setup Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/10-configuration.md Set up Cloudinary as a singleton service in your .NET application using dependency injection. This example shows how to retrieve configuration from appsettings.json. ```csharp public class Startup { public void ConfigureServices(IServiceCollection services) { var cloudinaryConfig = Configuration.GetSection("Cloudinary"); var account = new Account( cloudinaryConfig["CloudName"], cloudinaryConfig["ApiKey"], cloudinaryConfig["ApiSecret"] ); services.AddSingleton(_ => new Cloudinary(account) { Api = { UsePrivateCdn = bool.Parse(cloudinaryConfig["UsePrivateCdn"]) } }); } } ``` -------------------------------- ### Authentication Token Generation Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Shows how to generate signed URLs or tokens for authenticated access to private assets. This is crucial for security. ```csharp var token = cloudinary.Auth.SignedPrivateDownload("my_private_asset_id", 3600); // Expires in 1 hour ``` -------------------------------- ### Complete Metadata Field Workflow Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/07-metadata-fields.md This comprehensive example covers the entire lifecycle of metadata fields: creating multiple fields (string, enum), listing all fields, retrieving a specific field, updating a field, and finally deleting it. ```csharp // 1. Create metadata fields var skuField = new MetadataFieldCreateParams() { ExternalId = "sku", Label = "SKU", Type = "string", Required = true, Restrictions = new StringRestrictions() { MaxLength = 50 } }; var categoryField = new MetadataFieldCreateParams() { ExternalId = "category", Label = "Category", Type = "enum", Restrictions = new EnumRestrictions() { Values = new[] { "Electronics", "Apparel", "Home" } } }; cloudinary.AddMetadataField(skuField); cloudinary.AddMetadataField(categoryField); // 2. List all fields var allFields = cloudinary.ListMetadataFields(); Console.WriteLine($"Defined {allFields.MetadataFields.Count()} fields"); // 3. Get specific field var sku = cloudinary.GetMetadataField("sku"); Console.WriteLine($"SKU field: {sku.MetadataField.Label}"); // 4. Update field var updateParams = new MetadataFieldUpdateParams() { Required = false }; cloudinary.UpdateMetadataField("sku", updateParams); // 5. Delete field cloudinary.DeleteMetadataField("sku"); ``` -------------------------------- ### Video Upload Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Demonstrates how to upload a video file to Cloudinary. This is used for managing video assets. ```csharp var uploadParams = new VideoUploadParams { File = new FileDescription("sample.mp4", System.IO.File.OpenRead("path/to/local/video.mp4")), }; var uploadResult = cloudinary.Upload(uploadParams); ``` -------------------------------- ### Run the ASP.NET Core Application Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/samples/README.md Start the Cloudinary sample application. The application will be accessible via a web browser at the specified local address. ```bash dotnet run ``` -------------------------------- ### Async/Await Support Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/README.md Shows how to perform asynchronous operations like uploading and listing resources using await. Ensure your methods are marked async. ```csharp var result = await cloudinary.UploadAsync(uploadParams); var resources = await cloudinary.ListResourcesAsync(listParams); ``` -------------------------------- ### Transformation Preset Application Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Shows how to apply a pre-defined transformation preset to an asset when generating its URL. This promotes consistency in transformations. ```csharp var url = cloudinary.Api.UrlImgUpld("sample.jpg").Transform(new Transformation().Preset("my_preset_name")); ``` -------------------------------- ### Batch Upload with Progress Tracking Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Illustrates a pattern for uploading multiple assets in a batch, including progress tracking. This is useful for large uploads. ```csharp // Example assumes a method to handle batch uploads and progress updates // See 12-advanced-patterns.md for full details on this pattern. ``` -------------------------------- ### Transformation Chaining Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/README.md Demonstrates fluent chaining of transformation methods on a Transformation instance. Use this for building complex image transformations. ```csharp new Transformation() .Width(800) .Height(600) .Crop("fill") .Quality("auto") .Format("webp") ``` -------------------------------- ### URL Generation Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Shows how to generate Cloudinary URLs for assets. This includes basic URL construction and applying transformations. ```csharp var url = cloudinary.Api.UrlImgUpld("sample.jpg").Transform(new Transformation().Width(100).Height(100).Crop("fill")); ``` -------------------------------- ### Image Upload Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Provides an example of uploading an image to Cloudinary. This method is used for adding new image assets to your account. ```csharp var uploadParams = new ImageUploadParams { File = new FileDescription("sample.jpg", System.IO.File.OpenRead("path/to/local/image.jpg")), }; var uploadResult = cloudinary.Upload(uploadParams); ``` -------------------------------- ### Search Assets Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Demonstrates how to search for assets based on various criteria. This is useful for finding specific assets within your Cloudinary account. ```csharp var searchParams = new SearchParams() .Query("tags=nature") .MaxResults(10); var searchResult = cloudinary.Search().Search(searchParams).Execute(); ``` -------------------------------- ### Metadata Field Creation Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Demonstrates how to create custom metadata fields for categorizing and organizing assets. This enhances asset management capabilities. ```csharp var createParams = new MetadataFieldCreateParams { ExternalId = "my_custom_field", Label = "My Custom Field", Type = "string" }; var result = cloudinary.Admin.CreateMetadataField(createParams); ``` -------------------------------- ### Applying Radius Transformation Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/11-types-enums.md Example of how to apply a radius transformation using the Radius class with a list of integer values. ```csharp new Transformation().Radius(new Radius { Values = new List { 10 } }) ``` -------------------------------- ### URL Builder Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/README.md Demonstrates using the fluent interface of the URL builder to construct a signed image delivery URL. Set Signed(true) for authenticated URLs. ```csharp cloudinary.Api.UrlImgUp .Transform(transformation) .Signed(true) .BuildUrl("public_id") ``` -------------------------------- ### URL-Based Authentication Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/05-authentication.md Demonstrates how to use a generated AuthToken with the Cloudinary URL builder to create a secure, authenticated URL. ```APIDOC ## URL-Based Authentication ### Description Use tokens in Url builder to create authenticated URLs. ### Example ```csharp var token = new AuthToken(authKey) .Duration(3600) .Acl("/image/authenticated/*") .Generate(); var url = cloudinary.Api.UrlImgAuth .AuthToken(token) .BuildUrl("my_authenticated_image.jpg"); // Returns authenticated URL with token as query parameter or cookie ``` ``` -------------------------------- ### Public IDs starting with a prefix and excluding a format Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/06-search-api.md Finds assets whose public IDs start with 'profile/' and are not in 'gif' format, sorted by upload date. This demonstrates prefix matching and exclusion. ```csharp // Public IDs starting with prefix var prefixParams = new SearchParams() { Expression = "public_id ^ \"profile/\" AND format != \"gif\"", Sort = "uploaded_at desc" }; var prefixed = cloudinary.Search(prefixParams); ``` -------------------------------- ### Raw File Upload Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Shows how to upload raw files (e.g., documents, archives) to Cloudinary. This is useful for storing non-media assets. ```csharp var uploadParams = new RawUploadParams { File = new FileDescription("sample.txt", System.IO.File.OpenRead("path/to/local/file.txt")), }; var uploadResult = cloudinary.Upload(uploadParams); ``` -------------------------------- ### Batch Delete with Validation Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Demonstrates a pattern for deleting multiple assets in a batch, including validation steps. This ensures safe and controlled deletion of assets. ```csharp // Example assumes a method to handle batch deletions with validation. // See 12-advanced-patterns.md for full details on this pattern. ``` -------------------------------- ### Error Handling Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Illustrates how to handle potential errors during Cloudinary operations. This ensures robust application behavior. ```csharp try { // Cloudinary operation that might fail var result = cloudinary.Upload(new ImageUploadParams { File = new FileDescription("nonexistent.jpg", null) }); } catch (CloudinaryException ex) { // Handle the Cloudinary-specific exception Console.WriteLine($"Cloudinary Error: {ex.Message}"); } catch (Exception ex) { // Handle other general exceptions Console.WriteLine($"General Error: {ex.Message}"); } ``` -------------------------------- ### Upload with Error Handling Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/03-upload-api.md Demonstrates how to handle potential errors during an image upload operation using a try-catch block and checking the upload result. ```csharp try { var uploadParams = new ImageUploadParams() { File = new FileDescription(@"C:\image.jpg"), PublicId = "my_image" }; var uploadResult = await cloudinary.UploadAsync(uploadParams); if (uploadResult.Error != null) { Console.WriteLine($"Upload error: {uploadResult.Error.Message}"); } else { Console.WriteLine($"Upload successful: {uploadResult.SecureUrl}"); } } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message}"); } ``` -------------------------------- ### URL Signing with Transformations Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/10-configuration.md Enable URL signing for secure asset delivery and apply transformations directly within the URL generation process. This example includes a width transformation. ```csharp // Enable signature on URL var signedUrl = cloudinary.Api.UrlImgUp .Signed(true) .Transform(new Transformation().Width(300)) .BuildUrl("image.jpg"); // Use long (SHA-256) signatures CloudinaryConfiguration.LongUrlSignature = true; ``` -------------------------------- ### Advanced Query Examples Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/06-search-api.md Illustrates advanced search capabilities, including finding responsive images based on dimensions and aspect ratio, and finding tagged products with specific metadata fields. ```APIDOC ## Advanced Query Examples ### Description Provides examples for advanced search queries, such as filtering images based on dimensions and aspect ratio, and searching for products with specific tags and metadata. ### Method `cloudinary.Search(SearchParams searchParams)` ### Parameters #### Request Body - **searchParams** (SearchParams) - Required - An object containing advanced search criteria, including Expression, Sort, MaxResults, and WithField. ### Request Example: Find Responsive Images ```csharp var responsiveParams = new SearchParams() { Expression = "width > 600 AND aspect_ratio > 0.75 AND aspect_ratio < 1.5", Sort = "bytes asc", MaxResults = 50 }; var responsive = cloudinary.Search(responsiveParams); ``` ### Request Example: Find Tagged Products with Metadata ```csharp var productParams = new SearchParams() { Expression = "tags : \"product\" AND exif = true AND format = \"jpg\"", WithField = new[] { "exif", "colors", "custom_coordinates" }, Sort = "created_at desc" }; var products = cloudinary.Search(productParams); ``` ### Response #### Success Response (200) - **Resources** (List) - Array of matching resources that satisfy the advanced query criteria. #### Response Example (Responsive Images) ```json { "resources": [ { "public_id": "responsive_image_1", "width": 1200, "height": 900, "aspect_ratio": 1.33, "bytes": 204800, "url": "http://res.cloudinary.com/demo/image/upload/responsive_image_1.jpg" } ] } ``` #### Response Example (Tagged Products with Metadata) ```json { "resources": [ { "public_id": "product_1", "tags": ["product"], "exif": {}, "colors": [["red", 0.8]], "custom_coordinates": {}, "url": "http://res.cloudinary.com/demo/image/upload/product_1.jpg" } ] } ``` ``` -------------------------------- ### Attach Metadata to Resources Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/07-metadata-fields.md This example demonstrates how to define a metadata field and then update a resource's context with metadata values. It involves creating a field and then using UpdateResourceContext with PublicIds and a Context dictionary. ```csharp // Define a field var field = new MetadataFieldCreateParams() { ExternalId = "photographer", Label = "Photographer Name", Type = "string" }; cloudinary.AddMetadataField(field); // Update resource with metadata in context var updateParams = new ContextParams() { PublicIds = new[] { "my_photo" }, Context = new Dictionary() { { "photographer", "John Smith" } } }; cloudinary.UpdateResourceContext(updateParams); ``` -------------------------------- ### Advanced Patterns and Workflows Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Documentation on advanced usage patterns and real-world workflow examples for the Cloudinary .NET SDK, including optimization, batch operations, and search. ```APIDOC ## Advanced Patterns and Workflows ### Description This section covers advanced usage patterns and real-world workflow examples for the Cloudinary .NET SDK, demonstrating how to leverage its features for complex tasks. ### Patterns Covered - Responsive image optimization - Multi-device image generation - Batch upload with progress tracking - Batch delete with validation - Transformation preset library usage - Hierarchical tag management - Schema-based metadata management - Complex search query builders - Pagination helpers - Advanced retry strategies - Lazy loading for large collections - URL caching strategies - Real-world workflow examples ### Related Documentation - Search query syntax guide - Authentication patterns - Retry logic examples ``` -------------------------------- ### Asynchronous Search for Images Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/06-search-api.md Perform an asynchronous search for image resources, filtering by format and sorting by creation date. This example iterates through the returned resources and prints their details. ```csharp public async Task SearchImagesAsync() { var searchParams = new SearchParams() { Expression = "resource_type = \"image\" AND format = \"jpg\"", Sort = "created_at desc", MaxResults = 25 }; try { var results = await cloudinary.SearchAsync(searchParams); foreach (var resource in results.Resources) { Console.WriteLine($"ID: {resource.PublicId}"); Console.WriteLine($"Size: {resource.Bytes} bytes"); Console.WriteLine($"Dimensions: {resource.Width}x{resource.Height}"); Console.WriteLine($"URL: {resource.SecureUrl}"); Console.WriteLine("---"); } Console.WriteLine($"Total results: {results.TotalCount}"); if (!string.IsNullOrEmpty(results.NextCursor)) { Console.WriteLine($"Next page cursor: {results.NextCursor}"); } } catch (Exception ex) { Console.WriteLine($"Search error: {ex.Message}"); } } ``` -------------------------------- ### Define and Manage Metadata Schemas Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/12-advanced-patterns.md Initializes product-related metadata fields including SKU, price, category, and stock status. This setup is crucial for structured data management on Cloudinary resources. ```csharp public class MetadataSchemaService { private readonly Cloudinary _cloudinary; public MetadataSchemaService(Cloudinary cloudinary) { _cloudinary = cloudinary; } public async Task InitializeProductSchemaAsync() { // SKU field await _cloudinary.AddMetadataFieldAsync( new MetadataFieldCreateParams() { ExternalId = "product_sku", Label = "Product SKU", Type = "string", Required = true, Restrictions = new StringRestrictions() { MinLength = 3, MaxLength = 20 } }); // Price field await _cloudinary.AddMetadataFieldAsync( new MetadataFieldCreateParams() { ExternalId = "product_price", Label = "Price (cents)", Type = "integer", Restrictions = new IntegerRestrictions() { Min = 0, Max = 999999 } }); // Category field await _cloudinary.AddMetadataFieldAsync( new MetadataFieldCreateParams() { ExternalId = "product_category", Label = "Category", Type = "enum", Required = true, Restrictions = new EnumRestrictions() { Values = new[] { "Electronics", "Clothing", "Books", "Home", "Sports" } } }); // In stock field await _cloudinary.AddMetadataFieldAsync( new MetadataFieldCreateParams() { ExternalId = "in_stock", Label = "In Stock", Type = "string", DefaultValue = "true" }); } public async Task UpdateProductMetadataAsync( string publicId, Product product) { var context = new Dictionary() { { "product_sku", product.Sku }, { "product_price", product.PriceCents.ToString() }, { "product_category", product.Category }, { "in_stock", product.IsInStock ? "true" : "false" } }; var contextParams = new ContextParams() { PublicIds = new[] { publicId }, Context = context }; await _cloudinary.UpdateResourceContextAsync(contextParams); } public class Product { public string Sku { get; set; } public int PriceCents { get; set; } public string Category { get; set; } public bool IsInStock { get; set; } } } ``` -------------------------------- ### Chaining Transformations Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/02-url-building.md Demonstrates how to chain multiple transformation methods to create complex image manipulations. The `Chain()` method starts a new nested transformation. ```APIDOC ## Chain() ### Description Creates a new nested transformation for chaining multiple effects. ### Method `Chain` ### Returns A new `Transformation` instance that is chained. ### Example ```csharp var transform = new Transformation() .Width(400) .Height(300) .Crop("fill") .Chain() .Overlay("logo") .Gravity("south_east") .X(10) .Y(10); ``` ``` -------------------------------- ### Handle Cloudinary SDK Configuration Errors Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/08-error-handling.md Catch 'ArgumentException' when initializing the Cloudinary SDK to handle invalid configuration parameters. This ensures proper setup before making API calls. ```csharp try { var cloudinary = new Cloudinary(account); } catch (ArgumentException ex) { // Invalid configuration Console.WriteLine($"Configuration error: {ex.Message}"); } ``` -------------------------------- ### Cloudinary .NET SDK Initialization, URL Building, Upload, and Search Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/README.md Demonstrates initializing the Cloudinary SDK, building an optimized image URL with transformations, uploading an image with specific parameters, and searching for assets based on tags and dimensions. Ensure Cloudinary credentials and file paths are correctly configured. ```csharp // Initialize var cloudinary = new Cloudinary("cloudinary://key:secret@cloud"); // Build optimized URL var url = cloudinary.Api.UrlImgUp .Transform(new Transformation() .Width(800) .Height(600) .Crop("fill") .Quality("auto") .Format("webp")) .BuildUrl("photo.jpg"); // Upload image var result = await cloudinary.UploadAsync(new ImageUploadParams() { File = new FileDescription(@"C:\\photo.jpg"), PublicId = "my_photo", Tags = new[] { "profile", "featured" } }); // Search assets var results = await cloudinary.SearchAsync(new SearchParams() { Expression = "tags : \"featured\" AND width > 800", Sort = "created_at desc" }); ``` -------------------------------- ### Get Metadata Field Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/07-metadata-fields.md Retrieves a specific metadata field by its external ID. ```APIDOC ## Get Metadata Field ### Description Retrieves a specific metadata field by its external ID. ### Method GET (Implied by `GetMetadataField`) ### Endpoint /admin/metadata_fields/{external_id} ### Parameters #### Path Parameters - **external_id** (string) - Required - The external ID of the metadata field to retrieve. ### Response #### Success Response (200) - **MetadataField** (MetadataField) - The definition of the requested metadata field. - **Error** (Error) - Error information if operation failed. ### MetadataField Properties - **ExternalId** (string) - Field external ID. - **Label** (string) - Field label. - **Type** (string) - Field type. - **Required** (bool) - Whether field is required. - **DefaultValue** (object) - Default value. - **Restrictions** (object) - Field restrictions. - **DataType** (string) - Data type for the field. ``` -------------------------------- ### Initialize Cloudinary SDK Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/INDEX.md Demonstrates three ways to initialize the Cloudinary SDK: using the CLOUDINARY_URL environment variable, a direct string URL, or an Account object with explicit credentials. ```csharp using CloudinaryDotNet; // Via environment variable CLOUDINARY_URL var cloudinary = new Cloudinary(); // Or via string URL var cloudinary = new Cloudinary("cloudinary://key:secret@cloud"); // Or via Account object var account = new Account("cloud", "key", "secret"); var cloudinary = new Cloudinary(account); ``` -------------------------------- ### Metadata Fields Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Guide to managing custom metadata fields, including creation, retrieval, updates, and deletion. ```APIDOC ## Metadata Fields ### Description This section covers the management of custom metadata fields within Cloudinary. It details methods for creating (`AddMetadataField()`), retrieving (`GetMetadataField()`), updating (`UpdateMetadataField()`), deleting (`DeleteMetadataField()`), and listing (`ListMetadataFields()`) metadata fields. Supported field types, restrictions, defaults, and complete workflow examples are provided. ### Methods - **AddMetadataField()**: Creates a new custom metadata field. - **GetMetadataField()**: Retrieves a specific metadata field. - **UpdateMetadataField()**: Modifies an existing metadata field. - **DeleteMetadataField()**: Removes a metadata field. - **ListMetadataFields()**: Enumerates all custom metadata fields. - **Field types**: Supports string, integer, date, enum, and set types. - **Field restrictions and defaults**: Configuring constraints and default values for fields. - **Complete workflow examples**: Demonstrates practical usage scenarios. ``` -------------------------------- ### Initialize Cloudinary SDK Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/README.md Instantiate the Cloudinary object to begin using the SDK. Ensure you have your Cloudinary account credentials configured. ```csharp using CloudinaryDotNet; using CloudinaryDotNet.Actions; var cloudinary = new Cloudinary(); ``` -------------------------------- ### Get Streaming Profile Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/04-admin-api.md Retrieves a specific streaming profile by its name. Use this to view the configuration of an existing profile. ```csharp public StreamingProfileResult GetStreamingProfile(string name) public Task GetStreamingProfileAsync(string name, CancellationToken? cancellationToken = null) ``` -------------------------------- ### StartTime Method Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/05-authentication.md Sets the UNIX timestamp for when the authentication token becomes valid. This allows for delayed activation of the token. ```APIDOC ## StartTime Method ### Description Sets the time from which the token is valid. ### Method ```csharp public AuthToken StartTime(long startTime) ``` ### Parameters #### Path Parameters - **startTime** (long) - Required - UNIX timestamp (seconds since epoch). ### Returns The AuthToken instance for method chaining. ### Example ```csharp var token = new AuthToken(key) .StartTime(Utils.UnixTimeNowSeconds() + 300); // Valid in 5 minutes ``` ``` -------------------------------- ### Asset Deletion Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Illustrates how to delete an asset from Cloudinary using its public ID. This operation permanently removes the asset. ```csharp var result = cloudinary.Delete("my_public_id"); ``` -------------------------------- ### Initialize Cloudinary with String URL Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/10-configuration.md Initialize the Cloudinary SDK by passing the Cloudinary URL directly as a string. Suitable for simple configurations or managing multiple accounts. ```csharp var cloudinary = new Cloudinary("cloudinary://key:secret@mycloud"); ``` -------------------------------- ### Initialize Cloudinary with Environment Variable Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/10-configuration.md Initialize the Cloudinary SDK by setting the CLOUDINARY_URL environment variable. Recommended for production environments. ```bash CLOUDINARY_URL=cloudinary://api_key:api_secret@cloud_name ``` ```csharp var cloudinary = new Cloudinary(); ``` -------------------------------- ### Asynchronous Search Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/06-search-api.md Provides an example of performing a search asynchronously using the `SearchAsync` method. This is useful for non-blocking operations in applications. ```APIDOC ## Asynchronous Search ### Description Performs a search for resources asynchronously, allowing for non-blocking operations. ### Method `await cloudinary.SearchAsync(SearchParams searchParams)` ### Parameters #### Request Body - **searchParams** (SearchParams) - Required - An object containing search criteria. ### Request Example ```csharp public async Task SearchImagesAsync() { var searchParams = new SearchParams() { Expression = "resource_type = \"image\" AND format = \"jpg\"", Sort = "created_at desc", MaxResults = 25 }; try { var results = await cloudinary.SearchAsync(searchParams); foreach (var resource in results.Resources) { Console.WriteLine($"ID: {resource.PublicId}"); Console.WriteLine($"Size: {resource.Bytes} bytes"); Console.WriteLine($"Dimensions: {resource.Width}x{resource.Height}"); Console.WriteLine($"URL: {resource.SecureUrl}"); Console.WriteLine("---"); } Console.WriteLine($"Total results: {results.TotalCount}"); if (!string.IsNullOrEmpty(results.NextCursor)) { Console.WriteLine($"Next page cursor: {results.NextCursor}"); } } catch (Exception ex) { Console.WriteLine($"Search error: {ex.Message}"); } } ``` ### Response #### Success Response (200) - **Resources** (List) - Array of matching resources. - **TotalCount** (int) - Total number of matching resources. - **NextCursor** (string) - Pagination cursor for the next page, if available. #### Response Example ```json { "resources": [ { "public_id": "sample_image_async_1", "bytes": 5120, "width": 1024, "height": 768, "secure_url": "https://res.cloudinary.com/demo/image/upload/sample_image_async_1.jpg" } ], "total_count": 50, "next_cursor": "async_cursor_string" } ``` ``` -------------------------------- ### Initialize Cloudinary Instance Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/01-cloudinary-core.md Demonstrates different ways to initialize the Cloudinary class, either by using environment variables, an explicit Cloudinary URL, or an Account object. ```csharp using CloudinaryDotNet; var cloudinary = new Cloudinary(); ``` ```csharp var cloudinary = new Cloudinary("cloudinary://key:secret@mycloud"); ``` ```csharp var account = new Account("mycloud", "key", "secret"); var cloudinary = new Cloudinary(account); ``` -------------------------------- ### List Streaming Profiles Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/04-admin-api.md Lists all available streaming profiles in your Cloudinary account. Useful for getting an overview of configured profiles. ```csharp public StreamingProfileListResult ListStreamingProfiles() public Task ListStreamingProfilesAsync( CancellationToken? cancellationToken = null) ``` -------------------------------- ### Clone and Set Up Remote Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/CONTRIBUTING.md Clone the Cloudinary .NET repository and set up the upstream remote for tracking changes. ```git git clone https://github.com/cloudinary/CloudinaryDotNet.git cd CloudinaryDotNet git remote add upstream https://github.com/cloudinary/CloudinaryDotNet.git ``` -------------------------------- ### Error Handling Example Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/README.md Illustrates how to check for errors in the result object after an operation. All results contain an Error property that may be populated. ```csharp if (result.Error != null) { Console.WriteLine(result.Error.Message); } ``` -------------------------------- ### Configuration Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/MANIFEST.txt Details on initializing the Cloudinary SDK and configuring various settings. ```APIDOC ## Configuration ### Description This section outlines the various ways to initialize and configure the Cloudinary .NET SDK. It covers four primary initialization methods: using URL, Account details, environment variables, or OAuth. It details the global `CloudinaryConfiguration` object and its properties, including options for URL building, upload settings, search parameters, and API configuration. Integration with .NET configuration systems like `appsettings.json` and dependency injection setup are also explained. ### Initialization Methods - **URL initialization**: Configuring via a Cloudinary URL. - **Account initialization**: Using Cloud Name, API Key, and API Secret. - **Environment variable initialization**: Reading configuration from environment variables. - **OAuth initialization**: Using OAuth for authentication. ### Configuration Options - **Global CloudinaryConfiguration**: Centralized settings management. - **URL builder configuration**: Options for customizing URL generation. - **Upload configuration**: Settings related to file uploads. - **Search parameters**: Default parameters for search queries. - **API configuration properties**: SDK-level API settings. - **Environment variables**: Supported environment variables for configuration. - **.NET configuration integration**: Using `appsettings.json`. - **Dependency injection setup**: Configuring the SDK for DI containers. ``` -------------------------------- ### Create an Upload Preset for Unsigned Uploads Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/10-configuration.md Configure and create an upload preset for unsigned (client-side) uploads, specifying allowed formats, file size limits, and folder structure. ```csharp var presetParams = new UploadPresetParams() { Name = "my_preset", Unsigned = true, Folder = "preset_uploads/", AllowedFormats = new[] { "jpg", "png", "gif" }, MaxFileSize = 10485760, // 10 MB Tags = "preset" }; var result = cloudinary.CreateUploadPreset(presetParams); ``` -------------------------------- ### Building Image URLs with Transformations Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/09-transformation-reference.md Shows how to build image URLs and image tags using a Transformation object. ```csharp var transform = new Transformation() .Width(600) .Height(400) .Crop("fill") .Quality("auto") .Format("webp"); var url = cloudinary.Api.UrlImgUp .Transform(transform) .BuildUrl("photo.jpg"); // Use in image tag var tag = cloudinary.Api.UrlImgUp .Transform(transform) .BuildImageTag("photo.jpg", new { alt = "My Photo" }); ``` -------------------------------- ### Get Specific Metadata Field Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/07-metadata-fields.md Retrieves a specific metadata field definition by its external ID. Use this to inspect a field's configuration. ```csharp var field = cloudinary.GetMetadataField("product_sku"); Console.WriteLine($"Label: {field.MetadataField.Label}"); ``` -------------------------------- ### Initialize Cloudinary from Environment Variable Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/05-authentication.md Initializes the Cloudinary client by reading authentication details from the CLOUDINARY_URL environment variable. This is a convenient way to manage credentials. ```csharp var cloudinary = new Cloudinary(); ``` -------------------------------- ### Default Responsive Settings Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/02-url-building.md Configure default device pixel ratio and responsive image settings for your transformations. ```csharp public static object DefaultDpr { get; set; } ``` ```csharp public static bool DefaultIsResponsive { get; set; } ``` -------------------------------- ### Get Usage Statistics Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/04-admin-api.md Retrieves current usage statistics and quotas for your Cloudinary account. Useful for monitoring resource consumption and API request limits. ```csharp public UsageResult GetUsage() public Task GetUsageAsync(CancellationToken? cancellationToken = null) ``` ```csharp var usage = cloudinary.GetUsage(); Console.WriteLine($"Storage: {usage.Bytes} bytes"); Console.WriteLine($"Resources: {usage.Resources}"); ``` -------------------------------- ### Image Delivery URL Generation Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/10-configuration.md Examples of generating different types of image delivery URLs using the Cloudinary SDK, including authenticated and private delivery. ```csharp // Image delivery var imageUrl = cloudinary.Api.UrlImgUp; // Authenticated image delivery var authUrl = cloudinary.Api.UrlImgAuth; // Video delivery var videoUrl = cloudinary.Api.UrlVideoUpAuth; // Private image delivery var privateUrl = cloudinary.Api.UrlImgPrivate; ``` -------------------------------- ### Complete Cloudinary Configuration in C# Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/10-configuration.md This snippet shows how to initialize and configure the Cloudinary client using application settings. It covers account details, API settings like CDN usage and URL shortening, and global defaults. ```csharp public class CloudinaryService { private readonly Cloudinary _cloudinary; public CloudinaryService(IConfiguration configuration) { var cloudConfig = configuration.GetSection("Cloudinary"); var account = new Account( cloudConfig["CloudName"], cloudConfig["ApiKey"], cloudConfig["ApiSecret"] ); _cloudinary = new Cloudinary(account) { Api = { UsePrivateCdn = bool.Parse(cloudConfig["UsePrivateCdn"] ?? "false"), PrivateCdn = cloudConfig["PrivateCdn"], ShortenUrl = bool.Parse(cloudConfig["ShortenUrl"] ?? "false"), CSubDomain = bool.Parse(cloudConfig["CSubDomain"] ?? "false") } }; // Set global defaults CloudinaryConfiguration.CloudName = account.Cloud; CloudinaryConfiguration.LongUrlSignature = true; } public Url GetImageUrl() { return _cloudinary.Api.UrlImgUp; } public Url GetSecureUrl() { return _cloudinary.Api.UrlImgUp.Secure(true); } public async Task UploadImageAsync(IFormFile file) { var uploadParams = new ImageUploadParams() { File = new FileDescription(file.FileName, file.OpenReadStream()), Folder = "web_uploads", Overwrite = false, UniqueFilename = true }; return await _cloudinary.UploadAsync(uploadParams); } } ``` -------------------------------- ### Default Responsive Settings Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/02-url-building.md Static properties to configure default responsive behavior. ```APIDOC ## DefaultDpr ### Description Default Device Pixel Ratio for responsive images. ### Property `DefaultDpr` ### Type `object` ``` ```APIDOC ## DefaultIsResponsive ### Description Enables or disables default responsive image generation. ### Property `DefaultIsResponsive` ### Type `bool` ``` -------------------------------- ### Basic Search with Pagination Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/06-search-api.md Demonstrates how to perform a basic search for images and retrieve results with pagination. It shows how to set search parameters like expression and max results, and how to fetch the next page of results using the NextCursor. ```APIDOC ## Search Images with Pagination ### Description Performs a search for images and retrieves results, including support for pagination to fetch subsequent pages of results. ### Method `cloudinary.Search(SearchParams searchParams)` ### Parameters #### Request Body - **searchParams** (SearchParams) - Required - An object containing search criteria, including Expression, MaxResults, Sort, and optionally NextCursor for pagination. ### Request Example ```csharp var searchParams = new SearchParams() { Expression = "resource_type = \"image\"", MaxResults = 10 }; var results = cloudinary.Search(searchParams); Console.WriteLine($"Found {results.TotalCount} results"); Console.WriteLine($"Returned {results.Resources.Count} results"); // Get next page if available if (!string.IsNullOrEmpty(results.NextCursor)) { var nextParams = new SearchParams() { Expression = searchParams.Expression, Sort = searchParams.Sort, MaxResults = searchParams.MaxResults, NextCursor = results.NextCursor }; var nextResults = cloudinary.Search(nextParams); } ``` ### Response #### Success Response (200) - **TotalCount** (int) - Total number of matching resources. - **Resources** (List) - Array of matching resources. - **NextCursor** (string) - Pagination cursor for the next page, if available. #### Response Example ```json { "total_count": 100, "resources": [ { "public_id": "sample_image_1", "format": "jpg", "bytes": 10240, "width": 800, "height": 600, "url": "http://res.cloudinary.com/demo/image/upload/sample_image_1.jpg", "secure_url": "https://res.cloudinary.com/demo/image/upload/sample_image_1.jpg" } ], "next_cursor": "some_cursor_string" } ``` ``` -------------------------------- ### Get Specific Resource Metadata Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/04-admin-api.md Retrieves metadata for a specific resource using its public ID and optional resource type. Use this to fetch details about an individual asset. ```csharp public GetResourceResult GetResource(GetResourceParams parameters) public Task GetResourceAsync(GetResourceParams parameters, CancellationToken? cancellationToken = null) ``` ```csharp var resourceParams = new GetResourceParams() { PublicId = "my_image", ResourceType = "image" }; var resource = cloudinary.GetResource(resourceParams); Console.WriteLine($"URL: {resource.SecureUrl}"); Console.WriteLine($"Created: {resource.CreatedAt}"); ``` -------------------------------- ### Initialize Cloudinary with Account Credentials Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/05-authentication.md Initializes the Cloudinary client using your cloud name, API key, and API secret for basic authentication. ```csharp var account = new Account("mycloud", "api_key", "api_secret"); var cloudinary = new Cloudinary(account); ``` -------------------------------- ### AuthToken Constructor Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/05-authentication.md Initializes a new AuthToken instance. Use the constructor with a key for authenticated access. ```csharp public AuthToken() public AuthToken(string key) ``` -------------------------------- ### Cloudinary Class Constructors Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/01-cloudinary-core.md Initialize the Cloudinary client using different methods: default constructor (reads from environment variable), explicit Cloudinary URL, or an Account object. ```APIDOC ## Cloudinary Class Constructors ### Description Initializes the main Cloudinary client. You can initialize it using the default constructor which reads credentials from the `CLOUDINARY_URL` environment variable, by providing an explicit Cloudinary URL string, or by passing an `Account` object containing your credentials. ### Constructors - `public Cloudinary()` - `public Cloudinary(string cloudinaryUrl)` - `public Cloudinary(Account account)` ### Parameters #### `Cloudinary(string cloudinaryUrl)` - **cloudinaryUrl** (string) - Required - Cloudinary URL in format `cloudinary://key:secret@cloud_name`. If not provided, uses `CLOUDINARY_URL` environment variable. #### `Cloudinary(Account account)` - **account** (Account) - Required - Cloudinary account object with credentials. ### Usage Examples ```csharp // Using environment variable CLOUDINARY_URL using CloudinaryDotNet; var cloudinary = new Cloudinary(); // Using explicit URL var cloudinary = new Cloudinary("cloudinary://key:secret@mycloud"); // Using Account object var account = new Account("mycloud", "key", "secret"); var cloudinary = new Cloudinary(account); ``` ``` -------------------------------- ### Get Cloudinary Account Configuration Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/04-admin-api.md Retrieves Cloudinary account configuration details, including cloud name and storage quotas. This is useful for verifying account settings or displaying information to users. ```csharp public ConfigResult GetConfig(ConfigParams configParams = null) public Task GetConfigAsync(ConfigParams configParams = null, CancellationToken? cancellationToken = null) ``` ```csharp var config = cloudinary.GetConfig(); Console.WriteLine($"Cloud name: {config.CloudName}"); Console.WriteLine($"Total storage: {config.MaxfileSize} bytes"); ``` -------------------------------- ### Upload Preset Management Methods Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/03-upload-api.md Provides methods for creating, retrieving, deleting, and listing upload presets. Use these to manage preset configurations for uploads. ```csharp public UploadPresetResult CreateUploadPreset(UploadPresetParams parameters) public Task CreateUploadPresetAsync(UploadPresetParams parameters) public UploadPresetResult GetUploadPreset(string name) public Task GetUploadPresetAsync(string name) public DeleteUploadPresetResult DeleteUploadPreset(string name) public Task DeleteUploadPresetAsync(string name) public ListUploadPresetsResult ListUploadPresets() public Task ListUploadPresetsAsync() ``` -------------------------------- ### Build URL with Per-URL Configuration Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/10-configuration.md Construct a specific image URL with custom configurations for security, CDN usage, transformations, and other URL properties. ```csharp var url = cloudinary.Api.UrlImgUp .Secure(true) .UsePrivateCdn(true) .PrivateCdn("custom-cdn.example.com") .ShortenUrl(true) .UseSubDomain(true) .CName("mycdn.example.com") .Transform(new Transformation().Width(300)) .BuildUrl("image.jpg"); ``` -------------------------------- ### List Resources by Tag Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/04-admin-api.md Lists all resources associated with a specific tag, with options for resource type and maximum results. Use this to find all assets tagged with a particular keyword. ```csharp public ListResourcesResult ListResourcesByTag(ListResourcesByTagParams parameters) public Task ListResourcesByTagAsync(ListResourcesByTagParams parameters, CancellationToken? cancellationToken = null) ``` ```csharp var tagParams = new ListResourcesByTagParams() { Tag = "profile", ResourceType = "image" }; var resources = cloudinary.ListResourcesByTag(tagParams); ``` -------------------------------- ### Building URLs with Transformations Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/09-transformation-reference.md Shows how to build image URLs and HTML image tags by applying a `Transformation` object to an image asset. ```APIDOC ## Building URLs with Transformations ### Description Construct image URLs and HTML image tags by applying a `Transformation` object to an asset. ### Example ```csharp var transform = new Transformation() .Width(600) .Height(400) .Crop("fill") .Quality("auto") .Format("webp"); var url = cloudinary.Api.UrlImgUp .Transform(transform) .BuildUrl("photo.jpg"); // Use in image tag var tag = cloudinary.Api.UrlImgUp .Transform(transform) .BuildImageTag("photo.jpg", new { alt = "My Photo" }); ``` ``` -------------------------------- ### FileDescription Class Constructors Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/01-cloudinary-core.md Create a FileDescription object to represent a file for upload, providing the file path, display name, stream, or byte array. ```APIDOC ## FileDescription Class Constructors ### Description Represents a file to be uploaded to Cloudinary. Use these constructors to create a `FileDescription` object, specifying the file by its path, display name and stream, or display name and byte array. ### Constructors - `public FileDescription(string path)` - `public FileDescription(string displayName, Stream stream)` - `public FileDescription(string displayName, byte[] bytes)` ### Parameters #### `FileDescription(string path)` - **path** (string) - Required - File path on disk. #### `FileDescription(string displayName, Stream stream)` - **displayName** (string) - Required - Display name for the file (used in API). - **stream** (Stream) - Required - Stream containing file data. #### `FileDescription(string displayName, byte[] bytes)` - **displayName** (string) - Required - Display name for the file (used in API). - **bytes** (byte[]) - Required - Byte array containing file data. ``` -------------------------------- ### AuthToken StartTime Method Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/05-authentication.md Sets the UNIX timestamp when the token becomes valid. Useful for pre-scheduled access. The AuthToken instance is returned for method chaining. ```csharp var token = new AuthToken(key) .StartTime(Utils.UnixTimeNowSeconds() + 300); // Valid in 5 minutes ``` -------------------------------- ### Add and Apply Custom Metadata to Resources Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/INDEX.md Defines a custom metadata field (e.g., 'product_sku') and then applies a value to that field for specific resources. ```csharp // Define field cloudinary.AddMetadataField(new MetadataFieldCreateParams() { ExternalId = "product_sku", Label = "Product SKU", Type = "string" }); // Apply to resource cloudinary.UpdateResourceContext(new ContextParams() { PublicIds = new[] { "product_photo" }, Context = new Dictionary() { { "product_sku", "SKU12345" } } }); ``` -------------------------------- ### ICloudinaryAdminApi Interface Methods Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/11-types-enums.md Provides methods for administrative tasks such as pinging the service, retrieving configuration, fetching and deleting resources, and listing resources. ```csharp public interface ICloudinaryAdminApi { PingResult Ping(); Task PingAsync(CancellationToken? cancellationToken = null); ConfigResult GetConfig(ConfigParams configParams = null); Task GetConfigAsync(ConfigParams configParams = null, CancellationToken? cancellationToken = null); GetResourceResult GetResource(GetResourceParams parameters); ListResourcesResult ListResources(ListResourcesParams parameters = null); DelResResult DeleteResources(DelResParams parameters); // ... additional methods } ``` -------------------------------- ### Upload with Eager Transformations Source: https://github.com/cloudinary/cloudinarydotnet/blob/master/_autodocs/INDEX.md Uploads an image and immediately generates multiple eager transformations (thumbnails) as specified in the EagerTransforms list. ```csharp var uploadParams = new ImageUploadParams() { File = new FileDescription(@"C:\photo.jpg"), EagerTransforms = new List() { new Transformation().Width(200).Height(200).Crop("thumb"), new Transformation().Width(500).Height(500).Crop("fill") } }; var result = cloudinary.Upload(uploadParams); // Transformations generated immediately, not lazily ```