### Install Useful Tips Service via Package Manager Console
Source: https://github.com/rws/studio-api-docs/blob/main/articles/hints_tips/UsefulTips/UsefulTipsApiArticle.md
Use this command in the Package Manager Console to install the RwsAppStore.UsefulTips.Service NuGet package.
```powershell
Install-Package RwsAppStore.UsefulTips.Service -Version 3.0.0.8
```
--------------------------------
### Initialize Preview Writer
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/enhancing_the_preview_file_writer.md
Initializes the StreamWriter for the preview output and writes the HTML start tag.
```csharp
// start the preview output
public void StartOfInput()
{
_preview = new StreamWriter(OutputProperties.OutputFilePath);
_preview.WriteLine(GetHTMLStart());
}
```
--------------------------------
### HTML Example with Inline Tags
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/processing_inline_tags.md
Demonstrates a segment containing bold inline tags.
```html
Open the dialog box.
```
--------------------------------
### XML Example of Translation Provider in Project File
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/translationmemory/storing_and_retrieving_the_plugin_settings.md
Shows how a translation provider and its settings are represented in an XML project or template file.
```xml
```
--------------------------------
### Hide Prompt Message
Source: https://github.com/rws/studio-api-docs/blob/main/articles/hints_tips/UsefulTips/UsefulTipsApiArticle.md
Allows getting or setting the 'HidePromptMessage' value, which controls whether users see a prompt to install useful tips.
```APIDOC
## HidePromptMessage
### Description
Gets or sets the 'HidePromptMessage' value for the plugin. Setting this to false prevents the user from receiving a prompt message to install useful tips.
### Method
GET, PUT
### Endpoint
/api/hidePromptMessage
### Request Body (for PUT)
- **HidePromptMessage** (bool) - Required - Set to true to show the prompt, false to hide it.
### Response (for GET)
#### Success Response (200)
- **HidePromptMessage** (bool) - The current value of the prompt message setting.
```
--------------------------------
### Get Initial Translation Units
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/translationmemory/looping_through_translation_memories.md
Fetches the first batch of translation units from the translation memory using an iterator. This is the starting point for looping through the TM.
```csharp
TranslationUnit[] tus = tm.LanguageDirection.GetTranslationUnits(ref tmIterator);
```
--------------------------------
### Run Prepare Task Sequence with Perfect Match Setup
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/perfect_match.md
This C# code demonstrates how to initialize a new project, add files, set up bilingual references for Perfect Match using files from a previous project, add master translation memories, and then run the Prepare task sequence.
```cs
public void RunPrepareWithPerfectMatch()
{
ProjectInfo info = this.GetProjectInfo();
//Create the project
FileBasedProject newProject = new FileBasedProject(info);
//Add project files
ProjectFile[] files=newProject.AddFiles(this.AddProjectFiles(@"c:\ProjectFiles\Documents\ar-AR"));
//Perfect Match Setup - Use the helper function to look for files in a previous project that match files in this project
newProject.AddBilingualReferenceFiles(GetBilingualFileMappings(info.TargetLanguages, files, @"c:\ProjectFiles\PreviousProjectFiles"));
//Add Translation memory
this.AddMasterTMs(newProject, @"c:\ProjectFiles\TMs\ar-AR");
//Run the prepare task sequence (Scan, ConvertToTranslatableFormat, WordCount, CopyToTargetLanguages, PerfectMatch, AnalyzeFiles, PreTranslateFiles, PopulateProjectTranslationMemories)
TaskSequence taskSequence = newProject.RunAutomaticTasks(files.GetIds(), TaskSequences.Prepare);
}
```
--------------------------------
### Prepare Project Files
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/running_tasks_on_project_files.md
Initializes the project with new files. This is a prerequisite for running subsequent tasks.
```CS
this.PrepareFiles(newProject);
```
--------------------------------
### Get Editor Controller in C#
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/integration/trados_studio_controllers.md
Obtain an instance of the EditorController to interact with the Trados Studio editor. This is a common starting point for many UI integrations.
```csharp
private EditorController GetEditorController()
{
return SdlTradosStudio.Application.GetController();
}
```
--------------------------------
### Example Usage of WindowsCredentialStore
Source: https://github.com/rws/studio-api-docs/blob/main/articles/hints_tips/Update_Plugins/how_to_update_plugins_to_trados_studio_2024_sr1.md
Demonstrates how to instantiate and use the WindowsCredentialStore to retrieve credentials for a given provider key. Handles cases where credentials may not be found.
```csharp
// Example usage
var credentialStore = new WindowsCredentialStore();
var credentials = credentialStore.GetCredential("your-provider-key");
if (credentials.HasValue) {
var username = credentials.Value.Username;
var password = credentials.Value.Password;
// Use credentials securely...
} else {
// Handle missing credentials scenario
}
```
--------------------------------
### Get Project Translation Memory Settings
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/translation_memory_settings.md
Retrieve the project's settings bundle and access the TranslationMemorySettings group to configure TM parameters. This is the starting point for modifying project-wide TM settings.
```C#
ISettingsBundle settings = project.GetSettings();
TranslationMemorySettings tmSettings = settings.GetSettingsGroup();
```
--------------------------------
### Start Preview Output in C#
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/implementing_the_preview_writer.md
This C# snippet demonstrates how to initialize the preview output stream and write the beginning of an HTML document within the StartOfInput method.
```C#
// start the preview output
public void StartOfInput()
{
_preview = new StreamWriter(OutputProperties.OutputFilePath);
_preview.WriteLine("");
}
```
--------------------------------
### SMSMessageTransmitter Example
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/core/extensions.md
An example of an SMSMessageTransmitter implementation.
```csharp
using Sdl.Core.PluginFramework;
namespace MyProject.Core.Extensions
{
[AutoInstall]
[Extension("SMSMessageTransmitter", "1.0.0.0")]
public class SMSMessageTransmitter : IMessageTransmitter
{
public void SendMessage(string message)
{
// Implementation details for sending SMS messages
Console.WriteLine($"Sending SMS: {message}");
}
}
}
```
--------------------------------
### Write Inline Start Tags in C#
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/implementing_the_file_writer.md
Writes the content of inline start tags to the target file. This method is called when an inline start tag is encountered.
```csharp
public override void InlineStartTag(IStartTagProperties tagInfo)
{
_targetFile.Write(tagInfo.TagContent);
}
```
--------------------------------
### C# InitializeSettings Method
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/implement_the_verification_logic_native.md
Initializes the verifier's settings by populating from a settings bundle. Requires the settings bundle object and a configuration ID.
```csharp
public void InitializeSettings(ISettingsBundle settingsBundle, string configurationId)
{
VerifierSettings _settings = new VerifierSettings();
_settings.PopulateFromSettingsBundle(settingsBundle, "Length Check XML v 1.0.0.0");
Enabled = _settings.Enable;
}
```
--------------------------------
### Simple Plugin Initializer Example
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/integration/trados_studio_application_initializers.md
This C# code demonstrates a basic plugin initializer that tracks application startup and closing times. It measures the elapsed time and prompts the user with a warning if the work time is less than a specified minimum before closing.
```csharp
using System;
using System.Windows.Forms;
using Sdl.Desktop.IntegrationApi;
using Sdl.Desktop.IntegrationApi.Extensions;
using Sdl.TranslationStudioAutomation.IntegrationApi;
namespace StudioInitializer.Sample
{
///
/// Implements an application initializer which will keep track of the application startup and closing time.
///
[ApplicationInitializer]
class PluginInitializer : IApplicationInitializer
{
private const int MinimumWorkTime = 4;
///
/// This method is executed when the application is starting.
///
public void Execute()
{
StudioTracking.Start();
// Setting up a check at the application closure verifying if the user has worked less then the minimum amount of time
// If the time passed since Studio opening and Studio closing is less than the MinimumWorkTime(4h) than
// request a confirmation from the user for the application closure otherwise just exit.
SdlTradosStudio.Application.Closing += (s, e) =>
{
TimeSpan elapsedTime = StudioTracking.Elapsed;
if (elapsedTime.Hours < MinimumWorkTime)
{
DialogResult dialogResult =
MessageBox.Show(
string.Format("You have been working for {0:dd\\.hh\\:mm\\:ss} and spending less than {1} hours. Are you sure you want to quit ?", StudioTracking.Elapsed, MinimumWorkTime)
, string.Format("Total work time is {0} minutes", elapsedTime.Minutes)
, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.No)
{
//Cancel the the application closing
e.Cancel = true;
return;
}
}
StudioTracking.Stop();
};
}
}
}
```
--------------------------------
### Example Comment in XML
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/extracting_comments.md
This is an example of a comment element within an XML structure, representing a comment associated with a segment.
```xml
This segment was translated using web translator.
```
--------------------------------
### Configure Generic External Preview Application
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/implementing_an_external_file_preview.md
Implement this method in your File Type Component Builder to define the external preview application. This example configures Notepad as the preview application.
```C#
public IAbstractPreviewApplication BuildPreviewApplication(string name)
{
if (name == "PreviewApplication_ExternalPreview")
{
Sdl.FileTypeSupport.Framework.PreviewControls.GenericExteralPreviewApplication genericExteralPreviewApplication = new Sdl.FileTypeSupport.Framework.PreviewControls.GenericExteralPreviewApplication();
genericExteralPreviewApplication.ApplicationPath = @"c:\\Windows\\System32\\notepad.exe";
return genericExteralPreviewApplication;
}
return null;
}
```
--------------------------------
### HTML Example of Standalone Placeholder Tag
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/processing_placeholder_tags.md
An example of an HTML document segment containing a standalone placeholder tag for an image.
```html
```
--------------------------------
### Create and Save a Return Package in C#
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/creating_a_return_package.md
This C# code demonstrates how to create a return package from project files, monitor its creation status, and save it to disk. Ensure the necessary project and language objects are initialized before use.
```csharp
public void CreatePackage(FileBasedProject project)
{
#region "FileIds"
Language targetLang = new Language(CultureInfo.GetCultureInfo("de-DE"));
ProjectFile[] files = project.GetTargetLanguageFiles(targetLang);
Guid[] fileIds = files.GetIds();
#endregion
#region "ReturnPackage"
ReturnPackageCreation returnPackage = project.CreateReturnPackage(fileIds, "Return Package Name", "Comment: Everything went fine");
#endregion
#region "PackageStatus"
bool packageIsCreated = false;
while (!packageIsCreated)
{
switch (returnPackage.Status)
{
case PackageStatus.Cancelling:
case PackageStatus.InProgress:
case PackageStatus.Scheduled:
case PackageStatus.NotStarted:
packageIsCreated = false;
break;
case PackageStatus.Cancelled:
case PackageStatus.Completed:
case PackageStatus.Failed:
case PackageStatus.Invalid:
packageIsCreated = true;
break;
default:
break;
}
}
if (returnPackage.Status != PackageStatus.Completed)
{
throw new Exception("A problem occurred during package creation.");
}
#endregion
#region "SavePackage"
project.SavePackageAs(returnPackage.PackageId, @"c\temp\return_package.sdlrpx");
#endregion
}
```
--------------------------------
### Example Text File Content
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/processing_native_formats_introduction.md
This is an example of a simple text file format that requires specific processing rules for localization.
```text
[Version=0]
[Element=text1]
Automatically re-open previously edited documents.
[Element=text2]
Prompt me to re-open previously edited documents. Opens a dialog box on start-up.
[Element=text3]
Do not automatically re-open previously edited couments. This is the default option.
[Element=text4]
Prd-Code NCC1504
```
--------------------------------
### HTML Image Tag Example
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/processing_placeholder_tags.md
An example of an HTML image tag. This is typically used for displaying images within web content.
```html
```
--------------------------------
### Complete Function to Open and Import a Package
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/importing_a_return_package.md
This function demonstrates the complete process of opening a project, importing a return package, and verifying its import status. It includes setup for event arguments and project initialization.
```csharp
public void OpenPackage(string projectFile, string returnPackageFile)
{
#region "EventArgs"
List taskStatusEventArgsList = new List();
List messageEventArgsList = new List();
#endregion
#region "OpenProject"
FileBasedProject project = new FileBasedProject(projectFile);
#endregion
#region "ImportPackage"
ReturnPackageImport import = project.ImportReturnPackage(returnPackageFile);
#endregion
#region "CheckImportStatus"
bool packageIsImported = false;
while (!packageIsImported)
{
switch (import.Status)
{
case PackageStatus.Cancelling:
case PackageStatus.InProgress:
case PackageStatus.Scheduled:
case PackageStatus.NotStarted:
packageIsImported = false;
break;
case PackageStatus.Cancelled:
case PackageStatus.Completed:
case PackageStatus.Failed:
case PackageStatus.Invalid:
packageIsImported = true;
break;
default:
break;
}
}
if (import.Status != PackageStatus.Completed)
{
throw new Exception("A problem occurred during package import.");
}
#endregion
}
```
--------------------------------
### Open New Project Wizard with Data
Source: https://github.com/rws/studio-api-docs/blob/main/articles/hints_tips/Better_Studio_interactivity/SR2ApiArticle.md
Use this snippet to programmatically open the New Project wizard and pre-set project details like name and content. Requires `IStudioEventAggregator`.
```cs
var wizardData = new ProjectWizardData()
{
ProjectName = "My Project",
Content = new List() { "C:\\MySample.doc" }
};
_eventAggregator.Publish(new OpenNewProjectWizardEvent(wizardData));
```
--------------------------------
### HTML Example of Leading Tag
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/handling_tags_during_segmentation.md
An example of an HTML segment with a leading IMG tag. This tag is not displayed by default in the editor view.
```html
Click the Open Dialog box button to open the dialog box.
```
--------------------------------
### Get Task Settings
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/automatic_tasks_and_task_settings.md
Retrieves the settings bundle for a project and then gets a specific settings group for the TranslateTaskSettings, optionally specifying a target language.
```C#
ISettingsBundle settings = project.GetSettings(trgLanguage);
TranslateTaskSettings pretranslateSettings = settings.GetSettingsGroup();
```
--------------------------------
### Add a New Useful Tip
Source: https://github.com/rws/studio-api-docs/blob/main/articles/hints_tips/UsefulTips/UsefulTipsApiArticle.md
This snippet demonstrates how to create an instance of TipsProvider and add a new tip for a single language (e.g., 'en'). It includes setting up tip details, language-specific information, and associated resource files.
```csharp
namespace RwsAppStore.Example.Services
{
public class UsefulTipsService
{
public void AddUsefulTips()
{
var pathInfo = new PathInfo("[Plugin Name]", "16");
var tipsProvider = new TipsProvider(pathInfo);
var imported = tipsProvider.ImportTips(GetImportTips(), true);
Console.WriteLine($"Imported {imported} useful tips.");
}
private static ImportTips GetImportTips()
{
var tipLanguage = new TipLanguage
{
LanguageId = "en",
Tips = new List
{
new Tip
{
Category = "[A category to group the tips]",
Context = "[The Id of the plugin View]",
Title = "My Tip",
Description = "This is an awesome Tip",
Icon = "[Relative path to the icon]",
DescriptionImage = "[Relative path to the image file]",
Content = "[Relative path to the markdown File]",
}
},
Resources = new List
{
new ResourceFile {FullPath = "[DescriptionImage Full Path]",
RelativePath = "[Relative Path]"},
new ResourceFile {FullPath = "[Content Full Path]",
RelativePath = "[Relative Path]"},
new ResourceFile {FullPath = "[Icon Full Path]",
RelativePath = "[Relative Path]"}
}
};
var importTips = new ImportTips
{
TipLanguages = new List { tipLanguage }
};
return importTips;
}
}
}
```
--------------------------------
### Open Project File
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/importing_a_return_package.md
Opens the project file using the FileBasedProject class. This is the initial step before importing a return package.
```C#
FileBasedProject project = new FileBasedProject(projectFile);
```
--------------------------------
### Get or Set the Plug-in Settings Value
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/batchtasks/adding_a_settings_ui_to_our_batch_tasks.md
Implement members to get or set the integer value that defines the confirmation level for plug-in settings.
```csharp
public int ConfirmationLevel { get; set; }
```
--------------------------------
### Publishing CreateReturnPackageEvent
Source: https://github.com/rws/studio-api-docs/blob/main/articles/hints_tips/Better_Studio_interactivity/SR2ApiArticle.md
This snippet shows how to create a SampleJob and publish a CreateReturnPackageEvent to initiate a return package creation process within Studio.
```cs
var sampleJob = new SampleJob() { JobName = "Sample" };
var project = SdlTradosStudio.Application.GetController().CurrentProject;
if (project != null)
{
var selectedProjectId = project.GetProjectInfo().Id.ToString();
eventAggregator.Publish(new CreateReturnPackageEvent(selectedProjectid, sampleJob));
}
```
--------------------------------
### Example TMX Translation Unit with Usage Count
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/translationmemory/importing_a_tmx_file.md
An example of a translation unit (TU) in TMX format, showing attributes like usage count and context.
```xml
0, 0
TM
Microsoft
The Check Spelling Command
Der Befehl Rechtschreibung
```
--------------------------------
### Implement ConvertReturnPackage Method
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/integration/process_custom_project_package_formats.md
This method is the entry point for converting a return package to a custom format. It handles opening the source package, creating the custom package, and ensuring cleanup.
```cs
public void ConvertReturnPackage(IConversionContext context, ExternalPackageConversionInfo externalPackageConversionInfo)
{
OnPackageConverted(0, "Beginning conversion");
try
{
var fromPackage = context.OpenPackage(externalPackageConversionInfo.FromPackagePath);
CreateCustomReturnPackage(fromPackage);
}
finally
{
Cleanup();
}
OnPackageConverted(100, "Conversion Completed");
}
```
--------------------------------
### Example Settings Bundle in .sdlproj File
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/loading_and_saving_the_settings_bil.md
This XML snippet shows the structure of a settings group stored within an .sdlproj file, including a setting for enabling a feature.
```xml
True
```
--------------------------------
### Apply Character Formatting to Start Tag
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/applying_character_formatting.md
Applies bold, italic, or underline formatting to a start tag based on the XML node name. Requires the 'Sdl.FileTypeSupport.Framework.Formatting' namespace.
```C#
// apply character formatting to the start tag
IFormattingGroup formattingGroup = PropertiesFactory.FormattingItemFactory.CreateFormatting();
startTag.Formatting = new FormattingGroup();
switch (item.Name)
{
case "b":
formattingGroup.Add(new Bold(true));
break;
case "i":
formattingGroup.Add(new Italic(true));
break;
case "u":
formattingGroup.Add(new Underline(true));
break;
default:
break;
}
```
--------------------------------
### TMX Translation Unit (TU) Example
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/translationmemory/importing_a_tmx_file.md
An example of a Translation Unit (TU) structure within a TMX file, showing properties like origin, confirmation level, and language segments.
```xml
TM
ApprovedTranslation
Microsoft
A dialog box will open.
Es öffnet sich ein Dialogfenster.
```
--------------------------------
### Complete Project Creation from Template
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/creating_proj_based_on_templates.md
Combines template reference and project information to create and save a new project. Ensure the GetInfoForTemplateProject method is accessible.
```csharp
public void CreateBasedOnTemplate()
{
#region "GetTemplate"
string templateFile = @"c:\temp\project_template.sdltpl";
ProjectTemplateReference template = new ProjectTemplateReference(templateFile);
#endregion
#region "TemplateBasedProject"
FileBasedProject newProject = new FileBasedProject(this.GetInfoForTemplateProject(), template);
newProject.Save();
#endregion
}
```
--------------------------------
### Get Project Reports List
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/working_with_project_reports.md
Use ProjectReportsOperations to get a list of all reports associated with a project. This method returns a list of report objects, each containing details like ID, name, and creation date.
```C#
var reports = new ProjectReportsOperations(fileBasedProject).GetProjectReports();
```
--------------------------------
### Return Project Package Options
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/creating_a_project_package.md
Returns the configured project package options.
```csharp
return options;
```
--------------------------------
### Create Return Package with Target Language Files
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/creating_a_return_package.md
This snippet demonstrates how to create a return package by selecting target language files. It assumes a single target language and retrieves all files associated with it.
```csharp
// Select the target language files to be included in the return package.
var targetLanguage = new CultureInfo("de-DE");
var targetFiles = project.GetTargetLanguageFiles(targetLanguage);
// Get the file IDs for the selected target language files.
var fileIds = targetFiles.Select(f => f.GetId()).ToArray();
```
--------------------------------
### BuildBilingualGenerator
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/the_filter_component_builder.md
Gets the bilingual writer components for this component, if any.
```APIDOC
## BuildBilingualGenerator
### Description
Gets the bilingual writer components for this component, if any.
### Method
`public virtual IBilingualDocumentGenerator BuildBilingualGenerator(string name)`
### Parameters
#### Path Parameters
- **name** (string) - not used here - Description not provided.
### Returns
- **IBilingualDocumentGenerator** - null if no bilingual generator is defined.
```
--------------------------------
### Import Tips
Source: https://github.com/rws/studio-api-docs/blob/main/articles/hints_tips/UsefulTips/UsefulTipsApiArticle.md
Imports a list of tips into the 'Useful Tips' collection in Trados Studio. Supports overwriting existing tips and running with administrator privileges.
```APIDOC
## ImportTips
### Description
Imports tips into the 'Useful Tips' collection in Trados Studio.
### Method
POST
### Endpoint
/api/importTips
### Parameters
#### Query Parameters
- **overwrite** (bool) - Required - Overwrite existing tips.
- **runasAdmin** (bool) - Optional - Elevate user rights to admin; default: true. If the app environment is not running with Admin rights, a UAC message will appear.
#### Request Body
- **importTips** (ImportTips) - Required - A list of Tips to add to the collection.
### Response
#### Success Response (200)
- **ImportTipsResult** (int) - The number of Tips added to the 'Useful Tips' collection.
```
--------------------------------
### Retrieve TranslationProvider URI
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/translationmemory/storing_and_retrieving_the_plugin_settings.md
Gets the current URI from the TranslationProviderUriBuilder.
```csharp
public Uri Uri
{
get
{
return _uriBuilder.Uri;
}
}
```
--------------------------------
### HostApplication Object Registry (C#)
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/core/extensions.md
This C# code snippet demonstrates the setup of the Object Registry within a HostApplication, which is crucial for managing extensions and custom objects.
```csharp
using System;
namespace HostApplication
{
public class HostApplication
{
public static void Main(string[] args)
{
ObjectRegistry.Register(new MyExtension());
ObjectRegistry.Register(new AnotherService());
Console.WriteLine("Extensions registered.");
}
}
public interface IExtension { }
public interface ISomeOtherService { }
public class MyExtension : IExtension
{
public MyExtension()
{
Console.WriteLine("MyExtension instantiated.");
}
}
public class AnotherService : ISomeOtherService
{
public AnotherService()
{
Console.WriteLine("AnotherService instantiated.");
}
}
public static class ObjectRegistry
{
public static void Register(T instance) where T : class
{
Console.WriteLine($"Registering instance of type {typeof(T).Name}");
}
}
}
```
--------------------------------
### BuildQuickTagsFactory
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/the_filter_component_builder.md
Gets the QuickTags object for this component, returning a QuickTags factory.
```APIDOC
## BuildQuickTagsFactory
### Description
Gets the QuickTags object for this component, returning a QuickTags factory.
### Method
`public virtual IQuickTagsFactory BuildQuickTagsFactory(string name)`
### Parameters
#### Path Parameters
- **name** (string) - not used here - Description not provided.
### Returns
- **IQuickTagsFactory** - a Quick tags factory.
```
--------------------------------
### Initialize Verifier Settings
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/implement_the_verification_logic_bil.md
Initializes verifier settings by populating them from a settings bundle.
```csharp
public void InitializeSettings(ISettingsBundle settingsBundle, string configurationId)
{
VerifierSettings _settings = new VerifierSettings();
_settings.PopulateFromSettingsBundle(settingsBundle, "Word 2007 v 2.0.0.0 WordArt Verifier");
CheckWordArt = _settings.CheckWordArt;
MaxWordCount = _settings.MaxWordCount;
}
```
--------------------------------
### Configure Pre-translate Task Settings
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/pre_translate_settings.md
A comprehensive example demonstrating how to retrieve, modify, and apply various pre-translation settings, including minimum match score, confirmation behavior for exact matches, and handling of no matches.
```C#
public void GetPretranslateTaskSettings(FileBasedProject project)
{
#region "PetranslateTaskSettings"
ISettingsBundle settings = project.GetSettings();
TranslateTaskSettings pretranslateSettings = settings.GetSettingsGroup();
#endregion
#region "MinimumScore"
pretranslateSettings.MinimumMatchScore.Value = 95;
#endregion
#region "ExactMatches"
pretranslateSettings.ConfirmAfterApplyingExactMatch.Value = true;
pretranslateSettings.LockExactMatchSegments.Value = false;
#endregion
#region "ContextMatches"
pretranslateSettings.ConfirmAfterApplyingInContextExactMatch.Value = true;
pretranslateSettings.LockContextMatchSegments.Value = true;
#endregion
#region "NoMatch"
pretranslateSettings.NoTranslationMemoryMatchFoundAction.Value = NoTranslationMemoryMatchFoundAction.CopySourceToTarget;
#endregion
#region "TranslationOverwrite"
pretranslateSettings.TranslationOverwriteMode.Value = TranslationUpdateMode.OverwriteExistingTranslation;
#endregion
#region "UpdateTaskSettings"
project.UpdateSettings(settings);
#endregion
}
```
--------------------------------
### Retrieve a Fields Template
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/translationmemory/tm_fields_templates.md
Get a server-based fields template by its name, including all its properties.
```csharp
ServerBasedFieldsTemplate template = tmServer.GetFieldsTemplate(templateName, FieldsTemplateProperties.All);
```
--------------------------------
### Set and Get Delimiter Parameter
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/translationmemory/storing_and_retrieving_the_plugin_settings.md
Manages the 'delimiter' string parameter for the plugin settings.
```csharp
public string Delimiter
{
get { return GetStringParameter("delimiter");}
set {SetStringParameter("delimiter", value);}
}
```
--------------------------------
### Connect to TM Server and Populate List (C#)
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/translationmemory/adding_the_server_tm_selection_form.md
Establishes a connection to the TM Server using provided credentials and populates a combo box with available TM names. Enables the OK button after a successful connection.
```csharp
// By clicking the Connect button you establish a connectionw with the TM
// Server. This will fill populate the dropdown list with the names of the
// server TMs and enable the list, which is by default disabled.
// Moreover, the OK button gets enabled.
private void btnConnect_Click(object sender, EventArgs e)
{
Connector connection = new Connector();
connection.Connect(this.txtServerUri.Text, this.txtUserName.Text,
this.txtPassword.Text, this.comboServerTMs);
this.btnOK.Enabled = true;
}
```
--------------------------------
### Get Container Properties
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/translationmemory/creating_a_server_translation_memory.md
A helper function to retrieve the properties required for selecting a container.
```csharp
private ContainerProperties GetContainerProperties()
{
return new ContainerProperties();
}
```
--------------------------------
### Open Package Wizard Customization Example
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/integration/customize_open_package_wizard.md
This C# code demonstrates how to publish an OpenProjectPackageEvent to customize the Open Package wizard. It shows how to provide initial and final wizard pages.
```csharp
var initialWizardSteps = new List
{
new FirstPage(),
new SecondPage()
};
var finalWizardSteps = new List
{
new LastPage()
};
_eventAggregator.Publish(
new OpenProjectPackageEvent(
packageFilePath: filePath,
job: null,
iconPath: null,
projectOrigin: null,
firstPages: initialWizardSteps,
lastPages: finalWizardSteps));
```
--------------------------------
### Initialize Settings for Bilingual File Writer
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/bilingual_file_writer.md
Sets up user settings by populating them from a settings bundle and configuration ID. This method is used to configure the file writer based on user preferences, such as whether to write a UTF-8 BOM.
```csharp
public void InitializeSettings(Sdl.Core.Settings.ISettingsBundle settingsBundle, string configurationId)
{
UserSettings _userSettings = new UserSettings();
_userSettings.PopulateFromSettingsBundle(settingsBundle, configurationId);
WriteUtf8Bom = _userSettings.WriteUtf8Bom;
}
```
--------------------------------
### BuildAbstractGenerator
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/the_filter_component_builder.md
Gets a native or bilingual document generator of the type defined for the specified name.
```APIDOC
## BuildAbstractGenerator
### Description
Gets a native or bilingual document generator of the type defined for the specified name.
### Method
`public virtual IAbstractGenerator BuildAbstractGenerator(string name)`
### Parameters
#### Path Parameters
- **name** (string) - Abstract generator name - Description not provided.
### Returns
- **IAbstractGenerator** - not generator for default preview. Returns null if the generator is not found.
```
--------------------------------
### Add Project Files and Bilingual Reference Files in C#
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/perfect_match.md
This snippet demonstrates adding project files and then associating them with bilingual reference files. It shows both using a helper method and manual assignment of mappings.
```C#
ProjectInfo info = this.GetProjectInfo();
ProjectFile[] files = project.AddFiles(this.AddProjectFiles(@"c:\ProjectFiles\Documents\ጃ"));
//Using a helper function to return an array of BilingualFileMappings which are added to the project
project.AddBilingualReferenceFiles(GetBilingualFileMappings(info.TargetLanguages, files, @"c:\ProjectFiles\PreviousProjectFiles"));
//Assigning one or more reference files manually
project.AddBilingualReferenceFiles(
new BilingualFileMapping[] {
new BilingualFileMapping(files[0].Id, new Language("fr-FE"), @"c:\ProjectFiles\PreviousProjectFiles\fr-FR\mydocument.docx.sdlxliff"),
new BilingualFileMapping(files[0].Id, new Language("de-DE"), @"c:\ProjectFiles\PreviousProjectFiles\de-DE\mydocument.docx.sdlxliff"),
new BilingualFileMapping(files[1].Id, new Language("fr-FE"), @"c:\ProjectFiles\PreviousProjectFiles\fr-FR\myotherdocument.docx.sdlxliff"),
});
```
--------------------------------
### C# Term Verifier Message Service
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/verification/implement_the_verification_logic.md
Example of a Term Verifier Message Service in C#.
```csharp
public class TermVerifierMessageService : IMessageReporter
{
// ... other members
}
```
--------------------------------
### BuildPreviewApplication
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/filetypesupport/the_filter_component_builder.md
Creates a new instance of the preview application with the specified name. Currently only allows building an external preview application.
```APIDOC
## BuildPreviewApplication
### Description
Creates a new instance of the preview application with the specified name. Currently only allows building an external preview application.
### Method
`public virtual IAbstractPreviewApplication BuildPreviewApplication(string name)`
### Parameters
#### Path Parameters
- **name** (string) - Preview application name - Description not provided.
### Returns
- **IAbstractPreviewApplication** - External preview application. Returns null if the specified name does not correspond to an external preview application. Throws NotImplementedException for 'PreviewApplication_ExternalPreview'.
```
--------------------------------
### Get Language Resources Template
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/translationmemory/language_resource_templates.md
Retrieves a language resources template from the server using its path.
```csharp
ServerBasedLanguageResourcesTemplate template = tmServer.GetLanguageResourcesTemplate(templatePath);
```
--------------------------------
### Execute Open Package Action (Legacy)
Source: https://github.com/rws/studio-api-docs/blob/main/articles/hints_tips/Better_Studio_interactivity/SR2ApiArticle.md
This is the older method to trigger the Open Package wizard. The new method uses event publishing for more options.
```cs
var app = new StudioApplication();
app.ExecuteAction();
```
--------------------------------
### Get Project Translation Memory Settings
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/project_tm_creation_settings.md
Retrieves the settings bundle and specifically the ProjectTranslationMemoryTaskSettings for a project.
```CS
ISettingsBundle settings = project.GetSettings();
ProjectTranslationMemoryTaskSettings projectTmSettings = settings.GetSettingsGroup();
```
--------------------------------
### Open New Server Project Local Copy (C#)
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/connecting_a_project_to_a_project_server.md
Use the OpenProject method in the ProjectServer class to open a server-based project when no local copy exists. This method creates a workspace and returns a FileBasedProject object. You need the project's unique ID and the desired local copy path.
```csharp
FileBasedProject SetupServerProjectLocalCopy(Guid projectId, string locationOfLocalCopy)
{
Uri serverAddress = new Uri("http://myServerAddress:80");
ProjectServer server = new ProjectServer(serverAddress, false, "MyUser", "MyPassword");
FileBasedProject project = server.OpenProject(projectId, locationOfLocalCopy);
return project;
}
```
--------------------------------
### Open Server Project from Existing Local Copy (C#)
Source: https://github.com/rws/studio-api-docs/blob/main/apiconcepts/projectautomation/connecting_a_project_to_a_project_server.md
Instantiate FileBasedProject using its constructor to open a server-based project when you already have a local copy. Provide the path to the local project file and authentication details.
```csharp
FileBasedProject project = new FileBasedProject(@"c:\MyProjectDirectory\MyProjectFile.sdlproj", false, "MyUserName", "MyPassword");
```