### Getting Started with Tableau Migration SDK (Python) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/articles/index.md Example startup code for a simple migration application using the Tableau Migration SDK in Python. This snippet demonstrates basic initialization and usage patterns. ```python # This is a placeholder for the actual Python getting started code. # The content is included via a separate markdown include file. print("Python getting started code placeholder.") ``` -------------------------------- ### Getting Started with Tableau Migration SDK (C#) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/articles/index.md Example startup code for a simple migration application using the Tableau Migration SDK in C#. This snippet demonstrates basic initialization and usage patterns within the .NET Framework. ```csharp // This is a placeholder for the actual C# getting started code. // The content is included via a separate markdown include file. System.Console.WriteLine("C# getting started code placeholder."); ``` -------------------------------- ### Getting Started with Tableau Migration SDK in C# Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/api-csharp/index.md This code snippet demonstrates the basic setup for using the Tableau Migration SDK in a C# application. It serves as a starting point for developing migration tools and requires the Migration SDK to be installed and configured. ```csharp using Tableau.Migration; using Tableau.Migration.Api; using Tableau.Migration.Content; using Tableau.Migration.Engine; using Tableau.Migration.Engine.Pipelines; using Tableau.Migration.Engine.Services; using Tableau.Migration.Engine.Configuration; public class MigrationApp { public static async Task Main(string[] args) { // Create a migration pipeline builder var builder = new MigrationPipelineBuilder(); // Configure the pipeline (e.g., add sources, destinations, transformations) builder.ConfigurePipeline(config => { // Example: Add a source connection config.AddSourceConnection("SourceSite", "http://source.tableau.com", ""); // Example: Add a destination connection config.AddDestinationConnection("DestinationSite", "http://destination.tableau.com", ""); // Example: Add content types to migrate config.AddContentType(); config.AddContentType(); }); // Build the migration pipeline var pipeline = builder.Build(); // Execute the migration pipeline var result = await pipeline.ExecuteAsync(); // Handle the migration result if (result.Success) { Console.WriteLine("Migration completed successfully!"); } else { Console.WriteLine($"Migration failed: {result.Error?.Message}"); } } } ``` -------------------------------- ### Configuration File for Tableau Migration SDK Example Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/includes/python-getting-started.md This INI file contains configuration parameters for the Tableau Migration SDK example application. Values should not be quoted. It specifies settings like source and target Tableau site URLs and potentially other migration-related parameters. ```ini [General] SourceSiteURL = https://source.us-west-2b.online.tableau.com TargetSiteURL = https://target.us-west-2b.online.tableau.com [Credentials] SourceUsername = source_user SourcePassword = source_password TargetUsername = target_user TargetPassword = target_password [Migration] IncludeWorkbooks = true IncludeDataSources = true ``` -------------------------------- ### C# Startup Code for Tableau Migration Application Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/includes/csharp-getting-started.md This snippet illustrates the startup code for a custom Tableau migration application. It typically involves dependency injection setup and registering migration-specific services. This code is crucial for initializing the migration framework. ```csharp using Microsoft.Extensions.Hosting; namespace Csharp.ExampleApplication.Migration { public class MyMigrationApplication { public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices(MyMigrationApplication.ConfigureServices); public static void ConfigureServices(Microsoft.Extensions.DependencyInjection.IServiceCollection services) { // Add migration services here } } } ``` -------------------------------- ### Requirements File for Python Example Application Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/includes/python-getting-started.md This file lists the Python package dependencies required for the example application. It specifies versions for clarity and reproducibility. The example focuses on a specific version of the Tableau SDK and related libraries. ```text tableau-api-lib==0.4.0 requests==2.28.1 python-dotenv==0.21.0 ``` -------------------------------- ### Configure Dependency Injection for Schedule StartAt Transformer in C# Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/transformers/start_at_transformer.md This C# code demonstrates how to configure dependency injection for the `SimpleScheduleStartAtTransformer`. This setup allows the transformer to be correctly instantiated and provided with its required dependencies, such as the 'Start At' time. ```csharp using Microsoft.Extensions.DependencyInjection; using Tableau.Migration.ExampleApplication.Hooks.Transformers; // ... other using statements var serviceCollection = new ServiceCollection(); // ... other service registrations serviceCollection.AddTransient(provider => new SimpleScheduleStartAtTransformer(new DateTime(2023, 1, 1))); // ... rest of the DI configuration ``` -------------------------------- ### Install Tableau Migration SDK (Bash, .NET CLI, NuGet) Source: https://context7.com/tableau/tableau-migration-sdk/llms.txt Instructions for installing the Tableau Migration SDK using package managers for Python (pip) and C# (.NET CLI, NuGet Package Manager). ```bash # Python installation via pip pip install tableau_migration ``` ```bash # C# installation via .NET CLI dotnet add package Tableau.Migration ``` ```bash # C# installation via NuGet Package Manager Install-Package Tableau.Migration ``` -------------------------------- ### Install Tableau Migration SDK using PIP (Python) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/articles/index.md Installs the Tableau Migration SDK for Python using the PIP package installer. Ensure you have Python and PIP installed on your system. ```bash pip install tableau_migration ``` -------------------------------- ### Markdown Alert Examples Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/README.md Examples of how to create different types of alerts (Note, Tip, Important, Caution, Warning) in Markdown for DocFX rendering. ```markdown > [!NOTE] > This is a car. ``` ```markdown > [!TIP] > If the car does not move, put in in drive or park. ``` ```markdown > [!IMPORTANT] > Always change the engine oil on time. A new engine costs a lot more than a few oil changes. ``` ```markdown > [!CAUTION] > Check your surroundings when backing up. ``` ```markdown > [!WARNING] > Do not operate brake and accelerator pedals with two feet. ``` -------------------------------- ### Install Tableau Migration SDK using .NET CLI (C#) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/articles/index.md Installs the Tableau Migration SDK package for C# projects using the .NET command-line interface. This command adds the 'Tableau.Migration' NuGet package to your project. ```bash dotnet add package Tableau.Migration ``` -------------------------------- ### DocFX Relative Markdown Link Example Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/README.md Example of linking to another Markdown file within the documentation using a relative path. While functional, absolute paths are often preferred for clarity. ```markdown [API Reference](~/api-csharp/index.md) ``` -------------------------------- ### C# Program Entry Point for Tableau Migration SDK Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/includes/csharp-getting-started.md This snippet shows the main entry point for a C# application using the Tableau Migration SDK. It sets up the application's configuration and initiates the migration process. This code is essential for running migration tasks. ```csharp using System; namespace Csharp.ExampleApplication { internal class Program { private static void Main(string[] args) { Console.WriteLine("Hello World!"); } } } ``` -------------------------------- ### Python Main Module for Tableau Migration SDK Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/includes/python-getting-started.md This Python script serves as the main module for the Tableau Migration SDK example application. It demonstrates core functionalities and orchestrates the migration process. No specific dependencies are listed here, but it likely interacts with other SDK components. ```python import os import sys import logging from pathlib import Path # Add the parent directory to sys.path to allow importing from the root project_root = Path(__file__).resolve().parent.parent sys.path.append(str(project_root)) from Python.ExampleApplication.print_result import print_result logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def main(): logger.info("Starting Tableau Migration SDK Example Application...") # Example: Reading configuration from config.ini config_path = project_root / "examples/Python.ExampleApplication/config.ini" if config_path.exists(): logger.info(f"Reading configuration from: {config_path}") with open(config_path, 'r') as f: config_content = f.read() logger.info("Config content:\n%s", config_content) else: logger.warning("config.ini not found at expected path.") # Example: Simulating a migration task logger.info("Simulating migration task...") source_site_url = "http://source.tableau.com" target_site_url = "http://target.tableau.com" content_to_migrate = ["workbook1.twbx", "datasource1.tds"] logger.info("Migrating content from %s to %s", source_site_url, target_site_url) for item in content_to_migrate: logger.info("Processing: %s", item) # In a real scenario, SDK calls would happen here logger.info("Migration simulation complete.") # Example: Using the print_result helper function result_data = { "status": "success", "migrated_items": len(content_to_migrate), "errors": [] } print_result(result_data) logger.info("Tableau Migration SDK Example Application finished.") if __name__ == "__main__": main() ``` -------------------------------- ### DocFX Xref Link Example Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/README.md Example of creating an auto-generated content link using DocFX's xref syntax. It links to a specific type within the API. ```markdown [Tableau.Migration.Api.IApiClient](xref:Tableau.Migration.Api.IApiClient) ``` -------------------------------- ### Markdown Tab Group Example Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/README.md Example of creating a tab group in Markdown for DocFX. Each tab is defined by a heading with a specific anchor link. ```markdown ### [Tab 1 Name](#tab/tab1-id) Content in Tab 1 ### [Tab 2](#tab/tab2-id) Content in Tab 2 ### [Tab 3](#tab/tab3-id) Content in Tab 3 --- ``` -------------------------------- ### Run a Migration using Python SDK Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/api-python/index.md Provides a basic example of initiating a migration process using the Python wrapper for the Migration SDK. This typically involves setting up a plan and then executing it. ```python from tableau_migration_sdk.plan_builder import PlanBuilder from tableau_migration_sdk.migration_runner import MigrationRunner # 1. Configure the migration plan plan_builder = PlanBuilder() plan_builder.set_configuration_value("source_site_url", "https://source.example.com") plan_builder.set_configuration_value("target_site_url", "https://target.example.com") # ... add other configurations as needed ... plan = plan_builder.build() # 2. Initialize the migration runner runner = MigrationRunner(plan) # 3. Execute the migration try: runner.run_migration() print("Migration completed successfully.") except Exception as e: print(f"Migration failed: {e}") ``` -------------------------------- ### Python Migration Plan Builder Example Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/README.md This Python code snippet illustrates how to build a migration plan for Tableau Server to Cloud migration. It configures the source and destination details, authentication, and user mapping using a configuration file. ```python import configparser # configuration parser from tableau_migration import MigrationPlanBuilder, Migrator if __name__ == '__main__': config = configparser.ConfigParser() config.read('config.DEV.ini') # Build the plan plan_builder = MigrationPlanBuilder() plan_builder = plan_builder \ .from_source_tableau_server(config['SOURCE']['URL'], config['SOURCE']['SITE_CONTENT_URL'], config['SOURCE']['ACCESS_TOKEN_NAME'], config['SOURCE']['ACCESS_TOKEN']) \ .to_destination_tableau_cloud(config['DESTINATION']['URL'], config['DESTINATION']['SITE_CONTENT_URL'], config['DESTINATION']['ACCESS_TOKEN_NAME'], config['DESTINATION']['ACCESS_TOKEN']) \ .for_server_to_cloud() \ .with_tableau_id_authentication_type() \ .with_tableau_cloud_usernames(config['USERS']['EMAIL_DOMAIN']) ``` -------------------------------- ### Markdown Comment Example Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/README.md A workaround for adding comments in Markdown files using an empty link. ```markdown [//]: <> (This is a comment.) ``` -------------------------------- ### DocFX Xref Link with Anchor Example Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/README.md Example of creating an auto-generated content link with an anchor to a specific member of a type using DocFX's xref syntax. ```markdown [NetworkOptions.ExceptionsLoggingEnabled](xref:Tableau.Migration.Config.NetworkOptions#Tableau_Migration_Config_NetworkOptions_ExceptionsLoggingEnabled) ``` -------------------------------- ### JSON Configuration File for Tableau Migration SDK Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/includes/csharp-getting-started.md This JSON file demonstrates the structure for configuring source and destination Tableau environments. It includes server URLs, site details, and access tokens required for authentication. This configuration is read by the C# application to establish connections. ```json { "source": { "serverUrl": "http://server", "siteContentUrl": "", "accessTokenName": "my-server-token-name", "accessToken": "my-secret-server-pat" }, "destination": { "serverUrl": "https://pod.online.tableau.com", "siteContentUrl": "site-name", "accessTokenName": "my-cloud-token-name", "accessToken": "my-secret-cloud-pat" } } ``` -------------------------------- ### Register Schedule StartAt Transformer in Python Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/transformers/start_at_transformer.md This code snippet demonstrates how to register the `SimpleScheduleStartAtTransformer` with the `plan_builder` in Python. This is a crucial step to enable the transformer during the migration process. ```python plan_builder.transformers.add(SimpleScheduleStartAtTransformer) ``` -------------------------------- ### Implement Schedule StartAt Transformer in C# Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/transformers/start_at_transformer.md This C# transformer class adjusts the 'Start At' time for a Scheduled Task. It inherits from a base class that handles core migration logic. The code shows the class definition for the transformer. ```csharp using System; using Tableau.Migration.Api.Rest; using Tableau.Migration.Content; using Tableau.Migration.MigrationTableau.Hooks.Transformers; namespace Tableau.Migration.ExampleApplication.Hooks.Transformers { public class SimpleScheduleStartAtTransformer : MigrationHookTransformerBase { private readonly DateTime _startAt; public SimpleScheduleStartAtTransformer(DateTime startAt) { _startAt = startAt; } public override IMigrationTableauResponse TransformContentItem(ContentItemResponse contentItemResponse) { if (contentItemResponse.ContentItem is IScheduledTask scheduledTask) { scheduledTask.ScheduleStartTime = _startAt; } return contentItemResponse; } } } ``` -------------------------------- ### Register Schedule StartAt Transformer in C# Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/transformers/start_at_transformer.md This C# code snippet illustrates how to register the `SimpleScheduleStartAtTransformer` within the migration application. Proper registration ensures the transformer is utilized during the migration process. ```csharp public class MyMigrationApplication : IMigrationApplication { // ... other properties and methods public void Configure(IMigrationApplicationBuilder builder) { // ... other configurations builder.AddTransformer(new DateTime(2023, 1, 1)); } } ``` -------------------------------- ### Configure Content Types in Python using Environment Variables Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/articles/configuration.md Set batch sizes and types for content migration in Python via environment variables. The double underscore '__' is used as a delimiter, and variables start with 'MigrationSDK__'. Array indexes are used to group settings for specific content types. ```bash # User BatchSize is 201 MigrationSDK__ContentTypes__0__Type = User MigrationSDK__ContentTypes__0__BatchSize = 201 # Project BatchSize is 203 MigrationSDK__ContentTypes__1__Type = Project MigrationSDK__ContentTypes__1__BatchSize = 203 ``` -------------------------------- ### Dependency Injection Setup for Permissions Update Hook (C#) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/post-publish/update_permissions.md This C# code illustrates the dependency injection setup for the custom post-publish hook in the Tableau Migration SDK. It configures the application's service collection to recognize and provide the hook when needed. ```csharp using Microsoft.Extensions.DependencyInjection; using Tableau.Migration.Engine; using Csharp.ExampleApplication.Hooks.PostPublish; namespace Csharp.ExampleApplication { public class Program { public static void Main(string[] args) { var builder = Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { // Add the migration application and register the hook. services.AddTableauMigrationEngine(); services.AddSingleton(); }); builder.Build().Run(); } } } ``` -------------------------------- ### C# Email Domain Mapping Dependency Injection Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/mappings/username_email_mapping.md Illustrates how to configure dependency injection for the EmailDomainMapping in a C# application. This allows the mapping class and its options to be managed by the DI container. ```csharp using Csharp.ExampleApplication.Hooks.Mappings; using Microsoft.Extensions.DependencyInjection; using Tableau.Migration.Engine; // ... other using statements ... public static class Program { public static void Main(string[] args) { var services = new ServiceCollection(); services.AddTableauMigrationEngine(options => { options.AddHook(); }); services.AddSingleton(new EmailDomainMappingOptions { Domain = "example.com" }); // ... other service registrations ... var serviceProvider = services.BuildServiceProvider(); // ... rest of the application setup ... } } ``` -------------------------------- ### Register Project Rename Mapping (Python) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/mappings/rename_projects.md This Python snippet shows how to register a custom mapping class, such as `ProjectRenameMapping`, with the `plan_builder`. This ensures the mapping is included in the migration plan. ```Python plan_builder.mappings.add(ProjectRenameMapping) ``` -------------------------------- ### C# Email Domain Mapping Example Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/README.md This C# code snippet demonstrates how to map email domains for Tableau migration. It specifies the source and destination endpoints for the migration process. ```csharp public sealed class MyMigrationApplicationOptions { public EndpointOptions Source { get; set; } = new(); public EndpointOptions Destination { get; set; } = new(); } ``` -------------------------------- ### C# Configuration Classes for Tableau Migration SDK Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/includes/csharp-getting-started.md These C# classes define the structure for application configuration, specifically for migration options and endpoint details. They help in strongly typing configuration values loaded from sources like appsettings.json. Proper configuration is vital for successful migrations. ```csharp namespace Csharp.ExampleApplication.Config { public class MyMigrationApplicationOptions { public SourceOptions Source { get; set; } = new SourceOptions(); public DestinationOptions Destination { get; set; } = new DestinationOptions(); } public class SourceOptions { public string ServerUrl { get; set; } = ""; public string SiteContentUrl { get; set; } = ""; public string AccessTokenName { get; set; } = ""; public string AccessToken { get; set; } = ""; } public class DestinationOptions { public string ServerUrl { get; set; } = ""; public string SiteContentUrl { get; set; } = ""; public string AccessTokenName { get; set; } = ""; public string AccessToken { get; set; } = ""; } } ``` ```csharp namespace Csharp.ExampleApplication.Config { public class EndpointOptions { public string Url { get; set; } = ""; public string ApiKey { get; set; } = ""; } } ``` -------------------------------- ### C# Email Domain Mapping Class and Options Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/mappings/username_email_mapping.md Provides the C# implementation for EmailDomainMapping and its associated configuration options. This allows for custom mapping of email domains during Tableau Server to Tableau Cloud migrations. ```csharp using Tableau.Migration.Api.Hooks; namespace Csharp.ExampleApplication.Hooks.Mappings { public class EmailDomainMapping : IMigrationHook { private readonly EmailDomainMappingOptions _options; public EmailDomainMapping(EmailDomainMappingOptions options) { _options = options; } public Task ExecuteAsync(IMigrationHookExecutionContext executionContext) { // Implementation to map email domains return Task.CompletedTask; } } } ``` ```csharp namespace Csharp.ExampleApplication.Hooks.Mappings { public class EmailDomainMappingOptions { public string Domain { get; set; } = "example.com"; } } ``` -------------------------------- ### Implement Schedule StartAt Transformer in Python Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/transformers/start_at_transformer.md This Python transformer class is used to adjust the 'Start At' time of a Scheduled Task. It inherits from a base class providing core migration functionality. The code snippet shows the transformer class definition. ```python from datetime import datetime from tableau_migration.migration_transformer import MigrationTransformer from tableau_migration.migration_workbook import MigrationWorkbook class SimpleScheduleStartAtTransformer(MigrationTransformer): """Transformer that adjusts the 'Start At' of a schedule.""" def __init__(self, start_at: datetime): self.start_at = start_at def transform_workbook(self, workbook: MigrationWorkbook) -> None: """See base class.""" for schedule in workbook.schedules: schedule.schedule_start_time = self.start_at ``` -------------------------------- ### Define and Register Project Rename Mapping (C#) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/mappings/rename_projects.md This C# code defines a mapping class for renaming projects and demonstrates its registration within the migration application. It includes the class definition and how to add it to the migration process. ```C# using Tableau.Migration.Api.Hooks; using Tableau.Migration.Content; using Tableau.Migration.Content.Permissions; using Tableau.Migration.Engine.Hooks.Mappings; using Tableau.Migration.Engine.Pipelines; using System.Threading.Tasks; namespace Csharp.ExampleApplication.Hooks.Mappings { public class ProjectRenameMapping : IMigrationHook, IMigrationMapping { public string SourceProjectName { get; set; } = "Test"; public string DestinationProjectName { get; set; } = "Production"; public Task ExecuteAsync(IMigrationHookExecutionContext executionContext) { executionContext.Logger.LogInformation("Renaming project '{0}' to '{1}'.", SourceProjectName, DestinationProjectName); // In a real scenario, you would interact with the Tableau API here // to perform the actual rename operation. return Task.CompletedTask; } public IProject Map(IProject original, IMigrationHookExecutionContext executionContext) { if (original.Name == SourceProjectName) { return original.Rename(DestinationProjectName); } return original; } } } ``` ```C# public class MyMigrationApplication : IMigrationApplication { // ... other methods ... public void ConfigureMigrationPipeline(IMigrationPipelineBuilder pipelineBuilder) { // ... other configurations ... pipelineBuilder.WithMapping(new ProjectRenameMapping()); // ... other configurations ... } // ... other methods ... } ``` ```C# using Csharp.ExampleApplication.Hooks.Mappings; using Microsoft.Extensions.DependencyInjection; // ... other usings ... var serviceCollection = new ServiceCollection(); // ... other service registrations ... serviceCollection.AddTransient(); // Register the mapping class // ... rest of the service configuration ... var serviceProvider = serviceCollection.BuildServiceProvider(); // ... rest of the application setup ... ``` -------------------------------- ### C# Email Domain Mapping Registration Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/mappings/username_email_mapping.md Demonstrates how to register the EmailDomainMapping hook within a C# migration application. This step is crucial for enabling the custom username mapping during the migration process. ```csharp using Csharp.ExampleApplication.Hooks.Mappings; using Tableau.Migration.Engine.Builders; // ... other using statements ... public class MyMigrationApplication : IMigrationApplication { // ... other methods ... public void ConfigureMigrationPlan(IMigrationEngineBuilder migrationBuilder) { migrationBuilder .ConfigureMigrationPlan(planBuilder => planBuilder .WithTableauCloudUsernames(new EmailDomainMapping(new EmailDomainMappingOptions { Domain = "example.com" })) ); } } ``` -------------------------------- ### Dependency Injection for Migration Action Logging Hook in C# Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/migration-action-completed/log_migration_actions.md This C# code illustrates how to configure dependency injection for the migration action logging hook. It demonstrates registering the hook and its logger dependency within the service collection. This setup ensures the hook receives the necessary logger instance at runtime. ```csharp builder.Services.AddSingleton(); builder.Services.AddSingleton(provider => provider.GetRequiredService()); ``` -------------------------------- ### DocFX Code Snippet Inclusion (C#) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/README.md Markdown syntax to include a code snippet from an external C# file using regions. This is the preferred method for including code examples. ```markdown [!code-csharp[](../../../../examples/Csharp.ExampleApplication/MyMigrationApplication.cs#DefaultProjectsFilter-Registration)] ``` -------------------------------- ### Publish .NET Application Source: https://github.com/tableau/tableau-migration-sdk/blob/main/tools/Tableau.Migration.ManifestExplorer.Desktop/README.md Publishes the Manifest Explorer application using the .NET CLI. This command creates a self-contained deployment in the specified install folder for the net9.0 framework. It is necessary to run this command after every update to the application. ```bash dotnet publish -o -f net9.0 ``` -------------------------------- ### Python Email Domain Mapping Class Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/mappings/username_email_mapping.md Implements the EmailDomainMapping class in Python for scenarios where Tableau Server usernames are the same as the user part of the email. This class is used to supply the email domain during migration. ```python plan_builder = plan_builder \ .from_source_tableau_server( server_url=config['SOURCE']['URL'], site_content_url=config['SOURCE']['SITE_CONTENT_URL'], access_token_name=config['SOURCE']['ACCESS_TOKEN_NAME'], access_token=os.environ.get('TABLEAU_MIGRATION_SOURCE_TOKEN', config['SOURCE']['ACCESS_TOKEN'])) \ .to_destination_tableau_cloud( pod_url=config['DESTINATION']['URL'], site_content_url=config['DESTINATION']['SITE_CONTENT_URL'], access_token_name=config['DESTINATION']['ACCESS_TOKEN_NAME'], access_token=os.environ.get('TABLEAU_MIGRATION_DESTINATION_TOKEN', config['DESTINATION']['ACCESS_TOKEN'])) \ .for_server_to_cloud() \ .with_tableau_id_authentication_type() \ # You can add authentication type mappings here .with_tableau_cloud_usernames(EmailDomainMapping) ``` -------------------------------- ### Python Helper Module for Printing Results Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/includes/python-getting-started.md This Python script defines a helper function `print_result` used to display the outcome of migration tasks. It takes a dictionary as input and formats it for clear output. This module is a utility and has no external dependencies beyond standard Python libraries. ```python import json import logging logger = logging.getLogger(__name__) def print_result(result): """Prints the migration result in a formatted way. Args: result (dict): A dictionary containing the migration results. Expected keys: 'status', 'migrated_items', 'errors'. """ logger.info("--- Migration Result ---") if result.get("status") == "success": logger.info("Status: Success") migrated_count = result.get("migrated_items", 0) logger.info("Successfully migrated items: %d", migrated_count) else: logger.info("Status: Failed") errors = result.get("errors", []) if errors: logger.error("Errors encountered:") for error in errors: logger.error("- %s", error) else: logger.info("No specific errors reported, but status is not success.") # Optionally, print the full JSON for detailed inspection # logger.debug("Full result JSON: %s", json.dumps(result, indent=2)) logger.info("------------------------") ``` -------------------------------- ### Define Project Rename Mapping Class (Python) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/mappings/rename_projects.md This Python code defines a mapping class for renaming projects. It specifies the source and destination project names. This class is then added to the plan builder. ```Python from tableau_migration.migration_parameters import MigrationParameters from tableau_migration.migration_tasks import MigrationTask from tableau_migration.migration_plan_builder import MigrationPlanBuilder class ProjectRenameMapping: def __init__(self, source_project_name: str, destination_project_name: str): self.source_project_name = source_project_name self.destination_project_name = destination_project_name def execute(self, migration_parameters: MigrationParameters): print(f"Renaming project '{self.source_project_name}' to '{self.destination_project_name}'") # In a real scenario, you would interact with the Tableau API here # to perform the actual rename operation. pass # Example usage (within a migration context): # plan_builder = MigrationPlanBuilder() # plan_builder.mappings.add(ProjectRenameMapping(source_project_name="Test", destination_project_name="Production")) ``` -------------------------------- ### Serve Documentation Locally (PowerShell) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/README.md Command to generate and serve the documentation locally for development. Run from the repository root. ```powershell ./scripts/generate-docs.ps1 -serve ``` -------------------------------- ### Generate Documentation (PowerShell) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/README.md Command to generate static HTML documentation for the Tableau Migration SDK. Run from the repository root. ```powershell ./scripts/generate-docs.ps1 ``` -------------------------------- ### Register Bulk Logging Hook (C#) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/bulk-post-publish/bulk_logging.md This C# code demonstrates how to register the `BulkLoggingHook` with the migration plan. This registration step is crucial for the hook to be invoked during the migration process. ```csharp planBuilder.Hooks.Add(new BulkLoggingHook(loggerFactory.CreateLogger())); ``` -------------------------------- ### Configure Migration Plan with MigrationPlanBuilder (C#) Source: https://context7.com/tableau/tableau-migration-sdk/llms.txt Basic configuration of a migration plan using the MigrationPlanBuilder in C#, leveraging dependency injection. Sets up source and destination servers, migration type, and authentication. Includes validation and plan building. ```csharp // C#: Basic migration plan configuration with dependency injection using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Tableau.Migration; // Set up host with Migration SDK services using var host = Host.CreateDefaultBuilder(args) .ConfigureServices((ctx, services) => { services.AddTableauMigrationSdk(ctx.Configuration.GetSection("tableau:migrationSdk")); }) .Build(); // Get the plan builder from DI container var planBuilder = host.Services.GetRequiredService(); // Configure the migration plan planBuilder = planBuilder .FromSourceTableauServer( serverUrl: new Uri("http://my-tableau-server"), siteContentUrl: "", accessTokenName: "MyServerTokenName", accessToken: Environment.GetEnvironmentVariable("TABLEAU_MIGRATION_SOURCE_TOKEN") ?? "") .ToDestinationTableauCloud( podUrl: new Uri("https://10ax.online.tableau.com"), siteContentUrl: "my-cloud-site", accessTokenName: "MyCloudTokenName", accessToken: Environment.GetEnvironmentVariable("TABLEAU_MIGRATION_DESTINATION_TOKEN") ?? "") .ForServerToCloud() .WithTableauIdAuthenticationType(); // Validate and build var validationResult = planBuilder.Validate(); if (!validationResult.Success) { Console.WriteLine($"Validation errors: {string.Join(", ", validationResult.Errors)}"); return; } var plan = planBuilder.Build(); ``` -------------------------------- ### Initialize Tableau Migration SDK in Python Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Python/README.md This Python code snippet demonstrates how to import and initialize the Tableau Migration SDK. The import statement automatically initializes the .NET runtime required by the SDK. It then shows how to instantiate the PyMigrationPlanBuilder. ```python # This initializes the dotnet runtime on import import tableau_migration # Now just use the object from migration_migration_plan_builder import PyMigrationPlanBuilder planBuilder = PyMigrationPlanBuilder() ... ``` -------------------------------- ### Dependency Injection for Permission Transformer in C# Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/transformers/modify_permissions.md This C# code illustrates how to configure dependency injection for the ModifyPermissionsTransformer. This setup ensures that the transformer can be correctly instantiated and utilized by the migration framework. ```csharp builder.Services.AddSingleton(); ``` -------------------------------- ### Configure Content Types in C# using appsettings.json Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/articles/configuration.md Define content type configurations, including batch sizes, within the 'appsettings.json' file for C# applications. This JSON structure allows for granular control over migration batch sizes for different content types. ```json { "MigrationSdkOptions": { "contentType": [ { "type":"User", "batchSize": 201 }, { "type":"Project", "batchSize": 203 }, { "type":"ServerExtractRefreshTask", "batchSize": 200 } ], } } ``` -------------------------------- ### Implement Bulk Post-Publish Hook Class (C#) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/bulk-post-publish/bulk_logging.md This C# code defines the `BulkLoggingHook` class, which serves as a post-publish hook to log information about published content items. It utilizes dependency injection for the logger. ```csharp public class BulkLoggingHook : IPostPublishHook { private readonly ILogger _logger; public BulkLoggingHook(ILogger logger) { _logger = logger; } public Task ExecuteAsync(ContentItem[] contentItems, CancellationToken cancellationToken) { _logger.LogInformation("Received {Count} items for logging.", contentItems.Length); foreach (var item in contentItems) { _logger.LogInformation("Logging item: {Name} (Type: {Type})", item.Name, item.Type); } return Task.CompletedTask; } } ``` -------------------------------- ### Handle Migration Plan Validation Errors in C# Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/articles/plan_validation.md This example shows how to check the `Success` property of a `validationResult` object. If validation fails, it logs the errors, prompts the user to exit, and stops the application. ```csharp if (!validationResult.Success) { _logger.LogError($"Migration plan validation failed.", validationResult.Errors); Console.WriteLine("Press any key to exit"); Console.ReadKey(); _appLifetime.StopApplication(); } ``` -------------------------------- ### Configure Tableau Migration SDK with appsettings.json (C#) Source: https://context7.com/tableau/tableau-migration-sdk/llms.txt Configure the Migration SDK for C# applications using the appsettings.json file. This JSON structure allows for detailed settings related to source and destination servers, migration parallelism, batch sizes for different content types, network timeouts, file handling, and logging levels. ```json { "source": { "serverUrl": "http://my-tableau-server", "siteContentUrl": "", "accessTokenName": "my-server-token-name" }, "destination": { "serverUrl": "https://10ax.online.tableau.com", "siteContentUrl": "my-cloud-site", "accessTokenName": "my-cloud-token-name" }, "tableau": { "migrationSdk": { "migrationParallelism": 10, "contentTypes": [ { "type": "user", "batchSize": 50, "batchPublishingEnabled": true }, { "type": "group", "batchSize": 60 }, { "type": "project", "batchSize": 70 }, { "type": "datasource", "batchSize": 80 }, { "type": "workbook", "batchSize": 90 }, { "type": "serverextractrefreshtask", "batchSize": 100 } ], "network": { "fileTransferRequestTimeoutInterval": "01:00:00", "headerWaitTimeout": "00:05:00", "resilience": { "retryEnabled": true, "retryIntervals": ["00:00:01", "00:00:07", "00:00:31"], "perRequestTimeout": "00:02:00", "concurrentRequestsLimitEnabled": true, "maxConcurrentRequests": 4, "concurrentWaitInterval": "00:00:05", "clientThrottleEnabled": true, "maxReadRetries": 15 } }, "files": { "rootPath": "C:\\tableau-migration\\temp", "disableFileEncryption": false } }, "emailDomainMapping": { "emailDomain": "mycompany.com" } }, "Logging": { "LogLevel": { "Default": "Information", "System.Net.Http.HttpClient": "Warning", "Tableau.Migration": "Debug" } } } ``` -------------------------------- ### Configure Migration Plan with MigrationPlanBuilder (Python) Source: https://context7.com/tableau/tableau-migration-sdk/llms.txt Basic configuration of a migration plan using the MigrationPlanBuilder in Python. Sets up source and destination servers, migration type, and authentication. Includes validation and plan building. ```python # Python: Basic migration plan configuration import tableau_migration # Create a plan builder instance plan_builder = tableau_migration.MigrationPlanBuilder() # Configure source Tableau Server plan_builder = plan_builder \ .from_source_tableau_server( server_url="http://my-tableau-server", site_content_url="", # Empty string for default site access_token_name="MyServerTokenName", access_token="server-personal-access-token" ) \ .to_destination_tableau_cloud( pod_url="https://10ax.online.tableau.com", site_content_url="my-cloud-site", access_token_name="MyCloudTokenName", access_token="cloud-personal-access-token" ) \ .for_server_to_cloud() \ .with_tableau_id_authentication_type() \ .with_tableau_cloud_usernames("mycompany.com") # Validate the plan configuration validation_result = plan_builder.validate() if not validation_result.success: print(f"Validation errors: {validation_result.errors}") # Build the final migration plan plan = plan_builder.build() ``` -------------------------------- ### Add Default .NET Logging Provider Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/articles/logging.md Adds the default logging provider to the service collection when integrating the Tableau Migration SDK in a .NET application. This is a basic setup without specific provider configuration. ```csharp services .AddTableauMigrationSdk() .AddLogging(); ``` -------------------------------- ### Configure Dependency Injection for Bulk Logging Hook (C#) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/bulk-post-publish/bulk_logging.md This C# snippet shows how to configure dependency injection for the `BulkLoggingHook` within the application's `Program.cs`. It ensures that the hook can receive its required dependencies, such as the logger. ```csharp builder.Services.AddSingleton(); ``` -------------------------------- ### Register Bulk Post-Publish Hook (Python) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/bulk-post-publish/bulk_logging.md This Python snippet shows how to register the `BulkLoggingHookForDataSources` with the `plan_builder`. This ensures the hook is active during the migration process. ```python plan_builder.hooks.add(BulkLoggingHookForDataSources) ``` -------------------------------- ### Implement Bulk Post-Publish Hook for Logging (Python) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/bulk-post-publish/bulk_logging.md This Python code defines a class for a bulk post-publish hook that logs published items. It's designed to be registered with the plan builder to execute after publishing operations. ```python class BulkLoggingHookForDataSources: def __init__(self, logger): self.logger = logger def execute(self, content_items): self.logger.info(f"Received {len(content_items)} items for logging.") for item in content_items: self.logger.info(f"Logging item: {item.name} (Type: {item.type})") ``` -------------------------------- ### C# Dependency Injection for Tag Transformer Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/transformers/migrated_tag_transformer.md This C# code snippet illustrates how to configure dependency injection for the `MigratedTagTransformer`. This setup ensures that the transformer can be correctly instantiated and utilized within the migration application. ```csharp builder.Services.AddSingleton(); ``` -------------------------------- ### Filter Unlicensed Users (C#) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/filters/filter_users_by_site_role.md This C# code implements a filter to exclude unlicensed users from the migration. It leverages the Tableau Migration SDK and requires registration and potentially dependency injection setup. ```C# using Tableau.Migration.Api.Hooks.Filters; using Tableau.Migration.Content.Users; using Tableau.Migration.Engine.Hooks.Filters; using Tableau.Migration.Engine.Pipelines; using System.Threading.Tasks; namespace Csharp.ExampleApplication.Hooks.Filters { public class UnlicensedUsersFilter : UserFilter { public override Task FilterUserAsync(IUser user, IMigrationPipeline pipeline, System.Threading.CancellationToken cancel = default) { // Exclude users who do not have a site role assigned. return Task.FromResult(user.SiteRole != null); } } } ``` ```C# builder.Filters.Add(); ``` ```C# builder.Services.AddSingleton(); ``` -------------------------------- ### C#: Dependency Injection for Project Change Mappings Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/mappings/change_projects.md This C# code illustrates how to configure dependency injection for the project change mapping classes. This allows the migration framework to correctly instantiate and utilize the mapping logic. ```csharp builder.ConfigureServices(services => { services.AddSingleton(); }); ``` -------------------------------- ### Register Action URL XML Transformer in C# Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/transformers/action_url_xml_transformer.md This C# code snippet illustrates how to register the ActionUrlXmlTransformer within a Tableau migration application. Registration ensures that the transformer is utilized during the migration process. This example shows a typical registration pattern. ```csharp // Assuming 'planBuilder' is an instance of IContentPlanBuilder // planBuilder.Transformers.Add(new ActionUrlXmlTransformer()); ``` -------------------------------- ### C#: Map Workbooks and Data Sources to New Project Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/mappings/change_projects.md This C# code defines mapping classes to change the project of workbooks and data sources during migration. It inherits from base classes and specifies how to handle individual workbooks and data sources, targeting a new project. ```csharp using Tableau.Migration.Api.Hooks.Mappings; namespace Csharp.ExampleApplication.Hooks.Mappings { public class ChangeProjectMapping : IMigrationHookProvider, IMigrationHookProvider { public void Configure(IMigrationHookProviderContext context) { context.AddWorkbookMapping(); } public void Configure(IMigrationHookProviderContext context) { context.AddDataSourceMapping(); } } public class ChangeProjectWorkbookMapping : IWorkbookMapping { public string TargetProjectName => "Production"; } public class ChangeProjectDataSourceMapping : IDataSourceMapping { public string TargetProjectName => "Production"; } } ``` -------------------------------- ### Custom View File JSON Structure Example Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/articles/cv_file.md This JSON snippet illustrates the structure of a Custom View definition file downloaded by the Tableau Migration SDK. It highlights the 'tcv' field which holds the Base64 encoded custom view XML content. ```json [ ..... { "isSourceView": true, "viewName": "View 1", "tcv": "{base-64 custom view xml content with + signs replaced by -}" } ..... ] ``` -------------------------------- ### Load Environment Variables for Python SDK Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/articles/troubleshooting.md Demonstrates how to load environment variables from a .env file using the 'dotenv' library before initializing the Tableau Migration SDK in a Python application. This ensures that SDK configurations are correctly loaded. ```python # Used to load environment variables from dotenv import load_dotenv # Load the environment variables before importing tableau_migration load_dotenv() # first tableau_migration reference import tableau_migration # The SDK will not recognize the .env file values # Don't load the values here # load_dotenv() ``` -------------------------------- ### Pre-Migration Hooks (C#) Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/articles/hooks/custom_hooks.md Details on various pre-migration hooks available in the Tableau Migration SDK for C#, including their base classes, interfaces, and links to code samples. ```APIDOC ## Pre-Migration Hooks (C#) ### Description This section outlines the pre-migration hooks available for use with the Tableau Migration SDK in C#. These hooks allow for customization before the migration process begins. ### Endpoints #### Initialize Migration Hook ##### Description Hook for initializing the migration process. ##### Interface `IInitializeMigrationHook` ##### Code Samples [Code Samples/Initialize Migration](~/samples/initialize-migration/index.md) #### Filters Hook ##### Description Provides functionality to filter content during the migration process. ##### Base Class `ContentFilterBase` ##### Interface `IContentFilter` ##### Code Samples [Code Samples/Filters](~/samples/filters/index.md) #### Mappings Hook ##### Description Enables custom mapping of content during migration. ##### Base Class `ContentMappingBase` ##### Interface `IContentMapping` ##### Code Samples [Code Samples/Mappings](~/samples/mappings/index.md) #### Transformers Hook ##### Description Allows for transformation of content during the migration process. ##### Base Class `ContentTransformerBase` ##### Interface `IContentTransformer` ##### Code Samples [Code Samples/Transformers](~/samples/transformers/index.md) ``` -------------------------------- ### Configure Migration SDK with Python PlanBuilder Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/api-python/index.md Demonstrates how to provide basic configuration values to the Migration SDK using the PlanBuilder in Python. This is a foundational step for setting up migration plans. ```python from tableau_migration_sdk.plan_builder import PlanBuilder # Initialize PlanBuilder plan_builder = PlanBuilder() # Set configuration values (example) plan_builder.set_configuration_value("source_site_url", "https://source.example.com") plan_builder.set_configuration_value("target_site_url", "https://target.example.com") # Build the plan (further steps would follow) plan = plan_builder.build() print("Migration plan configured.") ``` -------------------------------- ### Register Migration Action Logging Hook in C# Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/migration-action-completed/log_migration_actions.md This C# code snippet shows how to register the migration action logging hook. It assumes the hook class is defined and available. Registration is typically done within the application's startup or configuration process. ```csharp planBuilder.Hooks.Add(); ``` -------------------------------- ### C#: Register Project Change Mappings Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/mappings/change_projects.md This C# snippet demonstrates how to register the custom mapping classes for workbooks and data sources within the migration application. This ensures that the defined project changes are applied during the migration process. ```csharp builder.ConfigureMigrationPlan(plan => { plan.Hooks.Add(); }); ``` -------------------------------- ### Register C# Migration Hooks with Dependency Injection Source: https://github.com/tableau/tableau-migration-sdk/blob/main/src/Documentation/samples/index.md Shows how to register a C# hook object using Dependency Injection (DI) and then add it to the plan builder's hook collection. DI allows for flexible object injection into hook constructors. ```csharp services.AddScoped(); _planBuilder.Filters.Add(); ``` -------------------------------- ### Configure Tableau Migration SDK with Environment Variables (Python) Source: https://context7.com/tableau/tableau-migration-sdk/llms.txt Configure the Migration SDK for Python applications using environment variables. Hierarchy is defined using double underscores. This method allows for dynamic configuration without modifying code files directly. ```bash # Python Environment Variables Configuration # Network parallelism - number of concurrent migrations export MigrationSDK__MigrationParallelism=10 # Content type batch sizes (array index ties settings together) export MigrationSDK__ContentTypes__0__Type=User export MigrationSDK__ContentTypes__0__BatchSize=50 export MigrationSDK__ContentTypes__0__BatchPublishingEnabled=true export MigrationSDK__ContentTypes__1__Type=Group export MigrationSDK__ContentTypes__1__BatchSize=60 export MigrationSDK__ContentTypes__2__Type=Project export MigrationSDK__ContentTypes__2__BatchSize=70 export MigrationSDK__ContentTypes__3__Type=DataSource export MigrationSDK__ContentTypes__3__BatchSize=80 export MigrationSDK__ContentTypes__4__Type=Workbook export MigrationSDK__ContentTypes__4__BatchSize=90 # File storage settings export MigrationSDK__Files__RootPath=/tmp/tableau-migration export MigrationSDK__Files__DisableFileEncryption=false # Network resilience settings export MigrationSDK__Network__Resilience__RetryEnabled=true export MigrationSDK__Network__Resilience__MaxConcurrentRequests=4 ``` ```python # Python: Reload configuration after changing environment variables import tableau_migration # Environment variables are evaluated at module import time # To reload after runtime changes: tableau_migration.reload_configuration() ```