/// <summary>
        /// If the plug-in settings can be changed by the user,
        /// SDL Trados Studio will display a Settings button.
        /// By clicking this button, users raise the plug-in user interface,
        /// in which they can modify any applicable settings, in our implementation
        /// the delimiter character and the list file name.
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="translationProvider"></param>
        /// <param name="languagePairs"></param>
        /// <param name="credentialStore"></param>
        /// <returns></returns>
        #region "Edit"
        public bool Edit(IWin32Window owner, ITranslationProvider translationProvider, LanguagePair[] languagePairs, ITranslationProviderCredentialStore credentialStore)
        {
            var editProvider = translationProvider as MtTranslationProvider;

            if (editProvider == null)
            {
                return(false);
            }

            //get saved key if there is one and put it into options
            //get google credentials
            var getCredGt = GetMyCredentials(credentialStore, "mtenhancedprovidergt:///");

            if (getCredGt != null)
            {
                editProvider.Options.ApiKey           = getCredGt.Credential;
                editProvider.Options.PersistGoogleKey = getCredGt.Persist;
            }

            //get microsoft credentials
            var getCredMt = GetMyCredentials(credentialStore, "mtenhancedprovidermst:///");

            if (getCredMt != null)
            {
                try
                {
                    var creds = new GenericCredentials(getCredMt.Credential); //parse credential into username and password
                    editProvider.Options.ClientId              = creds.UserName;
                    editProvider.Options.ClientSecret          = creds.Password;
                    editProvider.Options.PersistMicrosoftCreds = getCredMt.Persist;
                }
                catch { }//swallow b/c it will just fail to fill in instead of crashing the whole program
            }

            var dialog = new MtProviderConfDialog(editProvider.Options, credentialStore);

            //we are letting user delete creds but after testing it seems that it's ok if the individual credentials are null, b/c our method will re-add them to the credstore based on the uri
            if (dialog.ShowDialog(owner) == DialogResult.OK)
            {
                editProvider.Options = dialog.Options;

                var apiKey = editProvider.Options.ApiKey;

                //we are setting credentials selectively based on the chosen provider to avoid saving the other if it is blank
                if (dialog.Options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    //set google credential
                    SetGoogleCredentials(credentialStore, apiKey, dialog.Options.PersistGoogleKey);
                }
                else if (dialog.Options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    //set mst cred
                    var creds2 = new GenericCredentials(dialog.Options.ClientId, dialog.Options.ClientSecret);
                    SetMstCredentials(credentialStore, creds2, dialog.Options.PersistMicrosoftCreds);
                }
                return(true);
            }

            return(false);
        }
        private void PopulateCredentials()
        {
            var uri = GetUri();

            if (uri == null)
            {
                return;
            }

            // Populate the login field if they've opted to persist the credentials
            var credentials = credentialStore.GetCredential(uri);

            if (credentials != null && credentials.Persist)
            {
                // Keep credentials persisting checked
                SaveCredentialsOption.Checked = true;

                // Populate the related textboxes with the saved credentials
                var gCredentials = new GenericCredentials(credentials.Credential);
                UsernameField.Text = gCredentials.UserName;
                PasswordField.Text = gCredentials.Password;
                APIKeyField.Text   = gCredentials["API-Key"];
                BasicAuthenticationOption.Checked = gCredentials["UseApiKey"] != "true";
                APIKeyOption.Checked = !BasicAuthenticationOption.Checked;

                DelayedLPPopulation();
            }
        }
Esempio n. 3
0
        public ITranslationProvider CreateTranslationProvider(
            Uri translationProviderUri,
            string translationProviderState,
            ITranslationProviderCredentialStore credentialStore)
        {
            Log.Logger.Info("Attempting to create a new translation provider with URI: {0}", translationProviderUri);

            if (!SupportsTranslationProviderUri(translationProviderUri))
            {
                Log.Logger.Error("Cannot handle URI {0}.", translationProviderUri);
                throw new Exception("Cannot handle URI.");
            }

            var credentials = credentialStore.GetCredential(translationProviderUri);

            if (credentials == null)
            {
                //Throw TranslationProviderAuthenticationException, which will cause Studio to call GetCredentialsFromUser
                throw new TranslationProviderAuthenticationException();
            }

            var options            = JsonConvert.DeserializeObject <TranslationOptions>(translationProviderState);
            var genericCredentials = new GenericCredentials(credentials.Credential);

            if (options.UseBasicAuthentication)
            {
                options.ApiToken = ETSApi.ETSTranslatorHelper.GetAuthToken(options, genericCredentials);
            }
            else
            {
                options.ApiToken = genericCredentials["API-Key"];
                ETSApi.ETSTranslatorHelper.VerifyBasicAPIToken(options, genericCredentials);
            }
            return(new TranslationProvider(options));
        }
        /// <summary>
        /// Verifies that the API Key passed by the user is a valid API key.
        /// </summary>
        /// <param name="options"></param>
        /// <param name="credentials"></param>
        public static void VerifyBasicAPIToken(TranslationOptions options, GenericCredentials credentials)
        {
            _logger.Trace("");
            if (options == null)
            {
                throw new ArgumentNullException("Options is null");
            }
            var oldAPIKey = options.ApiToken;

            options.ApiToken = credentials["API-Key"];
            options.UseBasicAuthentication = credentials["UseApiKey"] != "true";

            try
            {
                // Make a request to the API using whatever path desired.
                ContactMtEdgeServer(MtEdgeGet, options, "language-pairs");
            }
            catch (AggregateException e)
            {
                _logger.Error($"{Constants.VerifyBasicAPIToken}: {e.Message}\n {e.StackTrace}");
                throw TranslateAggregateException(e);
            }
            catch (SocketException e)
            {
                _logger.Error($"{Constants.VerifyBasicAPIToken}: {e.Message}\n {e.StackTrace}");
                throw TranslateAggregateException(e);
            }
            finally
            {
                options.ApiToken = oldAPIKey;
            }
        }
Esempio n. 5
0
        public ITranslationProvider[] Browse(IWin32Window owner, LanguagePair[] languagePairs, ITranslationProviderCredentialStore credentialStore)
        {
            //construct options to send to form
            var loadOptions = new MtTranslationOptions();
            //get saved key if there is one and put it into options
            //get google credentials
            var getCredGt = GetMyCredentials(credentialStore, "mtenhancedprovidergt:///");

            if (getCredGt != null)
            {
                loadOptions.ApiKey           = getCredGt.Credential;
                loadOptions.PersistGoogleKey = getCredGt.Persist;
            }

            //get microsoft credentials
            var getCredMt = GetMyCredentials(credentialStore, "mtenhancedprovidermst:///");

            if (getCredMt != null)
            {
                try
                {
                    var creds = new GenericCredentials(getCredMt.Credential); //parse credential into username and password
                    loadOptions.ClientId              = creds.UserName;
                    loadOptions.ClientSecret          = creds.Password;
                    loadOptions.PersistMicrosoftCreds = getCredMt.Persist;
                }
                catch { } //swallow b/c it will just fail to fill in instead of crashing the whole program
            }

            var apiConnecter           = new ApiConnecter(loadOptions);
            var allSupportedLanguages  = ApiConnecter.SupportedLangs;
            var correspondingLanguages = languagePairs.Where(lp => allSupportedLanguages.Contains(lp.TargetCultureName.Substring(0, 2))).ToList();

            //loadOptions.LanguagesSupported = correspLanguages.ToDictionary(lp => lp.TargetCultureName, lp=>"MS Translator");
            //construct form
            var dialog = new MtProviderConfDialog(loadOptions, credentialStore, correspondingLanguages);

            //we are letting user delete creds but after testing it seems that it's ok if the individual credentials are null, b/c our method will re-add them to the credstore based on the uri
            if (dialog.ShowDialog(owner) == DialogResult.OK)
            {
                var testProvider = new MtTranslationProvider(dialog.Options);
                var apiKey       = dialog.Options.ApiKey;

                //we are setting credentials selectively based on the chosen provider to avoid saving the other if it is blank
                if (dialog.Options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    //set google credential
                    SetGoogleCredentials(credentialStore, apiKey, dialog.Options.PersistGoogleKey);
                }
                else if (dialog.Options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    //set mst cred
                    var creds2 = new GenericCredentials(dialog.Options.ClientId, dialog.Options.ClientSecret);
                    SetMstCredentials(credentialStore, creds2, dialog.Options.PersistMicrosoftCreds);
                }

                return(new ITranslationProvider[] { testProvider });
            }
            return(null);
        }
Esempio n. 6
0
        public ITranslationProvider CreateTranslationProvider(Uri translationProviderUri, string translationProviderState, ITranslationProviderCredentialStore credentialStore)
        {
            #region "CheckHandlesUri"
            if (!SupportsTranslationProviderUri(translationProviderUri))
            {
                throw new Exception(PluginResources.UriNotSupportedMessage);
            }
            #endregion
            //create options class based on URI passed to the method
            var loadOptions = new MtTranslationOptions(translationProviderUri);

            var myUri = new Uri("amazontranslateprovider:///");
            if (credentialStore.GetCredential(myUri) != null && credentialStore.GetCredential(myUri).Credential != String.Empty)
            {
                var credPersists = credentialStore.GetCredential(myUri).Persist;
                var cred         = new TranslationProviderCredential("", credPersists); //will this work??
                cred = credentialStore.GetCredential(myUri);                            //if credential is there then just get it

                var cred2 = new GenericCredentials(cred.Credential);                    //convert to generic credentials
                //add creds to options
                loadOptions.AccessKey = cred2.UserName;
                loadOptions.SecretKey = cred2.Password;
            }
            else if (loadOptions.SelectedAuthType == MtTranslationOptions.AWSAuthType.AccessKeys)
            {
                throw new TranslationProviderAuthenticationException();
            }
            //construct new provider with options..these options are going to include the cred.credential and the cred.persists
            var tp = new MtTranslationProvider(loadOptions);

            return(tp);
        }
        public ITranslationProvider CreateTranslationProvider(Uri translationProviderUri, string translationProviderState, ITranslationProviderCredentialStore credentialStore)
        {
            #region "CheckHandlesUri"
            if (!SupportsTranslationProviderUri(translationProviderUri))
            {
                throw new Exception(PluginResources.UriNotSupportedMessage);
            }
            #endregion

            //create options class based on URI passed to the method
            var loadOptions = new MtTranslationOptions(translationProviderUri);

            //start with MT...check if we are using MT
            if (loadOptions.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
            {
                var myUri = new Uri("mtenhancedprovidermst:///");
                if (credentialStore.GetCredential(myUri) != null)
                {
                    var credPersists = credentialStore.GetCredential(myUri).Persist;
                    var cred = new TranslationProviderCredential("", credPersists); //will this work??

                    cred = credentialStore.GetCredential(myUri); //if credential is there then just get it

                    var cred2 = new GenericCredentials(cred.Credential);//convert to generic credentials
                    //add creds to options
                    loadOptions.ClientId = cred2.UserName;
                    loadOptions.ClientSecret = cred2.Password;
                }
                else
                {
                    throw new TranslationProviderAuthenticationException();
                }
            }
            else //if we are using Google as the provider need to get API key
            {
                var myUri = new Uri("mtenhancedprovidergt:///");
                if (credentialStore.GetCredential(myUri) != null)
                {
                    var credPersists = credentialStore.GetCredential(myUri).Persist;
                    var cred = new TranslationProviderCredential("", credPersists); //will this work??

                    cred = credentialStore.GetCredential(myUri); //if credential is there then just get it
                    //add gt key to options
                    loadOptions.ApiKey = cred.Credential;
                }
                else
                {
                    throw new TranslationProviderAuthenticationException(); 
                    //throwing this exception ends up causing Studio to call MtTranslationProviderWinFormsUI.GetCredentialsFromUser();
                    //which we use to prompt the user to enter credentials
                }
            }
            
            //construct new provider with options..these options are going to include the cred.credential and the cred.persists
            var tp = new MtTranslationProvider(loadOptions);

            return tp;
        }
        public ITranslationProvider CreateTranslationProvider(Uri translationProviderUri, string translationProviderState, ITranslationProviderCredentialStore credentialStore)
        {
            #region "CheckHandlesUri"
            if (!SupportsTranslationProviderUri(translationProviderUri))
            {
                throw new Exception(PluginResources.UriNotSupportedMessage);
            }
            #endregion

            //create options class based on URI passed to the method
            MtTranslationOptions loadOptions = new MtTranslationOptions(translationProviderUri);

            //start with MT...check if we are using MT
            if (loadOptions.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
            {
                Uri myUri = new Uri("mtenhancedprovidermst:///");
                if (credentialStore.GetCredential(myUri) != null)
                {
                    bool credPersists = credentialStore.GetCredential(myUri).Persist;
                    TranslationProviderCredential cred = new TranslationProviderCredential("", credPersists); //will this work??

                    cred = credentialStore.GetCredential(myUri); //if credential is there then just get it

                    GenericCredentials cred2 = new GenericCredentials(cred.Credential);//convert to generic credentials
                    //add creds to options
                    loadOptions.ClientID = cred2.UserName;
                    loadOptions.ClientSecret = cred2.Password;
                }
                else
                {
                    throw new TranslationProviderAuthenticationException();
                }
            }
            else //if we are using Google as the provider need to get API key
            {
                Uri myUri = new Uri("mtenhancedprovidergt:///");
                if (credentialStore.GetCredential(myUri) != null)
                {
                    bool credPersists = credentialStore.GetCredential(myUri).Persist;
                    TranslationProviderCredential cred = new TranslationProviderCredential("", credPersists); //will this work??

                    cred = credentialStore.GetCredential(myUri); //if credential is there then just get it
                    //add gt key to options
                    loadOptions.apiKey = cred.Credential;
                }
                else
                {
                    throw new TranslationProviderAuthenticationException();
                    //throwing this exception ends up causing Studio to call MtTranslationProviderWinFormsUI.GetCredentialsFromUser();
                    //which we use to prompt the user to enter credentials
                }
            }

            //construct new provider with options..these options are going to include the cred.credential and the cred.persists
            MtTranslationProvider tp = new MtTranslationProvider(loadOptions);

            return tp;
        }
        private bool AuthenticateCredentials(GenericCredentials credentials, bool showAlertOnFailure = true)
        {
            // Expire the old LPs in case we've changed the host and reset the API version
            SDLMTEdgeTranslatorHelper.ExpireLanguagePairs();
            Options.ApiVersion = APIVersion.Unknown;

            string token;

            try
            {
                if (Options.UseBasicAuthentication)
                {
                    token = SDLMTEdgeTranslatorHelper.GetAuthToken(Options, credentials);
                }
                else
                {
                    token = APIKeyField.Text;
                    SDLMTEdgeTranslatorHelper.VerifyBasicAPIToken(Options, credentials);
                }
            }
            catch (Exception e)
            {
                _logger.Error($"{Constants.AuthenticateCredentials}: {e.Message}\n {e.StackTrace}");
                if (showAlertOnFailure)
                {
                    DialogResult = DialogResult.None;
                    MessageBox.Show(e.Message, PluginResources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return(false);
            }
            Options.ApiToken = token;

            if (tabControl != null)
            {
                try
                {
                    //avoiding to do binding when the window will be closed. Because removing and adding the tab will do the bind again.
                    inRemoveLanguagesPreferencesTab = true;
                    tabControl.Controls.RemoveByKey("LPTab");
                    if (Options?.ApiVersion == APIVersion.v2)
                    {
                        tabControl.Invoke(new Action(() =>
                        {
                            if (LPTab != null)
                            {
                                tabControl.Controls.Add(LPTab);
                            }
                        }));
                    }
                }
                finally
                {
                    inRemoveLanguagesPreferencesTab = false;
                }
            }

            return(true);
        }
        public ETSHelperTests()
        {
            apiKeyTranslationOptions = new TranslationOptions(new Uri(StringResource.ApiUrl));
            apiKeyTranslationOptions.UseBasicAuthentication = false;
            apiKeyTranslationOptions.ApiToken = StringResource.ApiKey;

            basicAuthTranslationOptions = new TranslationOptions(new Uri(StringResource.ApiUrl));
            basicAuthTranslationOptions.UseBasicAuthentication = true;
            userCredentials = new GenericCredentials(StringResource.Username, StringResource.Password);
        }
        private GenericCredentials GetCredentials()
        {
            var userName    = UsernameField.Text;
            var password    = PasswordField.Text;
            var credentials = new GenericCredentials(userName, password);

            credentials["API-Key"]   = APIKeyField.Text;
            credentials["UseApiKey"] = BasicAuthenticationOption.Checked ? "false" : "true";
            return(credentials);
        }
        public ITranslationProvider[] Browse(IWin32Window owner, LanguagePair[] languagePairs, ITranslationProviderCredentialStore credentialStore)
        {
            //construct options to send to form
            MtTranslationOptions loadOptions = new MtTranslationOptions();
            //get saved key if there is one and put it into options
            //get google credentials
            TranslationProviderCredential getCredGt = GetMyCredentials(credentialStore, "mtenhancedprovidergt:///");

            if (getCredGt != null)
            {
                loadOptions.apiKey           = getCredGt.Credential;
                loadOptions.persistGoogleKey = getCredGt.Persist;
            }

            //get microsoft credentials
            TranslationProviderCredential getCredMt = GetMyCredentials(credentialStore, "mtenhancedprovidermst:///");

            if (getCredMt != null)
            {
                try
                {
                    GenericCredentials creds = new GenericCredentials(getCredMt.Credential); //parse credential into username and password
                    loadOptions.ClientID              = creds.UserName;
                    loadOptions.ClientSecret          = creds.Password;
                    loadOptions.persistMicrosoftCreds = getCredMt.Persist;
                }
                catch { } //swallow b/c it will just fail to fill in instead of crashing the whole program
            }

            //construct form
            MtProviderConfDialog dialog = new MtProviderConfDialog(loadOptions, credentialStore);

            //we are letting user delete creds but after testing it seems that it's ok if the individual credentials are null, b/c our method will re-add them to the credstore based on the uri
            if (dialog.ShowDialog(owner) == DialogResult.OK)
            {
                MtTranslationProvider testProvider = new MtTranslationProvider(dialog.Options);
                string apiKey = dialog.Options.apiKey;

                //we are setting credentials selectively based on the chosen provider to avoid saving the other if it is blank
                if (dialog.Options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    //set google credential
                    SetGoogleCredentials(credentialStore, apiKey, dialog.Options.persistGoogleKey);
                }
                else if (dialog.Options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    //set mst cred
                    GenericCredentials creds2 = new GenericCredentials(dialog.Options.ClientID, dialog.Options.ClientSecret);
                    SetMstCredentials(credentialStore, creds2, dialog.Options.persistMicrosoftCreds);
                }

                return(new ITranslationProvider[] { testProvider });
            }
            return(null);
        }
        public ITranslationProvider[] Browse(IWin32Window owner, LanguagePair[] languagePairs, ITranslationProviderCredentialStore credentialStore)
        {
            //construct options to send to form
            MtTranslationOptions loadOptions = new MtTranslationOptions();
            //get saved key if there is one and put it into options
            //get google credentials
            TranslationProviderCredential getCredGt = GetMyCredentials(credentialStore, "mtenhancedprovidergt:///");
            if (getCredGt != null)
            {
                loadOptions.apiKey = getCredGt.Credential;
                loadOptions.persistGoogleKey = getCredGt.Persist;
            }

            //get microsoft credentials
            TranslationProviderCredential getCredMt = GetMyCredentials(credentialStore, "mtenhancedprovidermst:///");
            if (getCredMt != null)
            {
                try
                {
                    GenericCredentials creds = new GenericCredentials(getCredMt.Credential); //parse credential into username and password
                    loadOptions.ClientID = creds.UserName;
                    loadOptions.ClientSecret = creds.Password;
                    loadOptions.persistMicrosoftCreds = getCredMt.Persist;
                }
                catch { } //swallow b/c it will just fail to fill in instead of crashing the whole program
            }

            //construct form
            MtProviderConfDialog dialog = new MtProviderConfDialog(loadOptions, credentialStore);
            //we are letting user delete creds but after testing it seems that it's ok if the individual credentials are null, b/c our method will re-add them to the credstore based on the uri
            if (dialog.ShowDialog(owner) == DialogResult.OK)
            {
                MtTranslationProvider testProvider = new MtTranslationProvider(dialog.Options);
                string apiKey = dialog.Options.apiKey;

                //we are setting credentials selectively based on the chosen provider to avoid saving the other if it is blank
                if (dialog.Options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    //set google credential
                    SetGoogleCredentials(credentialStore, apiKey, dialog.Options.persistGoogleKey);
                }
                else if (dialog.Options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    //set mst cred
                    GenericCredentials creds2 = new GenericCredentials(dialog.Options.ClientID, dialog.Options.ClientSecret);
                    SetMstCredentials(credentialStore, creds2, dialog.Options.persistMicrosoftCreds);
                }

                return new ITranslationProvider[] { testProvider };
            }
            return null;
        }
        private bool AuthenticateCredentials(GenericCredentials credentials, bool showAlertOnFailure = true)
        {
            // Expire the old LPs in case we've changed the host and reset the API version
            SDLMTEdgeTranslatorHelper.ExpireLanguagePairs();
            Options.ApiVersion = APIVersion.Unknown;

            string token;

            try
            {
                if (Options.UseBasicAuthentication)
                {
                    token = SDLMTEdgeTranslatorHelper.GetAuthToken(Options, credentials);
                }
                else
                {
                    token = APIKeyField.Text;
                    SDLMTEdgeTranslatorHelper.VerifyBasicAPIToken(Options, credentials);
                }
            }
            catch (Exception e)
            {
                Log.Logger.Error($"{Constants.AuthenticateCredentials}: {e.Message}\n {e.StackTrace}");
                if (showAlertOnFailure)
                {
                    DialogResult = DialogResult.None;
                    if (Environment.UserInteractive)
                    {
                        MessageBox.Show(e.Message, @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                return(false);
            }
            Options.ApiToken = token;

            if (tabControl != null)
            {
                tabControl.Controls.RemoveByKey("LPTab");
                if (Options?.ApiVersion == APIVersion.v2)
                {
                    tabControl.Invoke(new Action(() =>
                    {
                        if (LPTab != null)
                        {
                            tabControl.Controls.Add(LPTab);
                        }
                    }));
                }
            }

            return(true);
        }
        private GenericCredentials GetCredentials()
        {
            var userName    = UsernameField.Text;
            var password    = PasswordField.Text;
            var credentials = new GenericCredentials(userName, password)
            {
                ["API-Key"]   = APIKeyField.Text,
                ["UseApiKey"] = BasicAuthenticationOption.Checked ? "false" : "true",
                ["RequiresSecureProtocol"] = ConnectionBox.Checked ? "true" : "false"
            };

            return(credentials);
        }
        public void ETSApi_VerifyAPIKey_NoExceptionThrown()
        {
            var credentials = new GenericCredentials(null, null);

            credentials["API-Key"]   = apiKeyTranslationOptions.ApiToken;
            credentials["UseApiKey"] = "true";
            try
            {
                ETSTranslatorHelper.VerifyBasicAPIToken(apiKeyTranslationOptions, credentials);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception, but got: " + ex.Message);
            }
        }
Esempio n. 17
0
        private void PopulateLanguagePairs()
        {
            if (LanguagePairs == null || LanguagePairs.Length == 0)
            {
                return;
            }

            GenericCredentials credentials = GetCredentials();

            if (!AuthenticateCredentials(credentials, false))
            {
                return;
            }

            if (Options.APIVersion != ETSApi.APIVersion.v2)
            {
                return;
            }

            var languagePairChoices = Options.SetPreferredLanguages(LanguagePairs);

            // Since this is run on a separate thread, use invoke to communicate with the master thread.
            TradosLPs.Invoke(new Action(() =>
            {
                // This gets called multiple times, so let's clear out the old contents
                TradosLPs.Columns.Clear();
                TradosLPs.AutoGenerateColumns = false;

                DataGridViewTextBoxColumn targetColumn = new DataGridViewTextBoxColumn();
                targetColumn.Name             = "Target Language";
                targetColumn.DataPropertyName = "TradosCulture";
                targetColumn.ReadOnly         = true;

                DataGridViewComboBoxColumn lpChoicesColumn = new DataGridViewComboBoxColumn();
                lpChoicesColumn.Name      = "SDL ETS Language Pair";
                lpChoicesColumn.FlatStyle = FlatStyle.Flat;

                TradosLPs.Columns.AddRange(new DataGridViewColumn[] { targetColumn, lpChoicesColumn });
                // Handler for populating combobox
                TradosLPs.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(TradosLPs_DataBindingComplete);

                TradosLPs.DataSource = languagePairChoices;

                // Handlers for when the combobox changes
                TradosLPs.CellValueChanged             += new DataGridViewCellEventHandler(TradosLPs_CellValueChanged);
                TradosLPs.CurrentCellDirtyStateChanged += new EventHandler(TradosLPs_CurrentCellDirtyStateChanged);
            }));
        }
        /// <summary>
        /// This gets called when a TranslationProviderAuthenticationException is thrown
        /// Since SDL Studio doesn't pass the provider instance here and even if we do a workaround...
        /// any new options set in the form that comes up are never saved to the project XML...
        /// so there is no way to change any options, only to provide the credentials
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="translationProviderUri"></param>
        /// <param name="translationProviderState"></param>
        /// <param name="credentialStore"></param>
        /// <returns></returns>

        public bool GetCredentialsFromUser(IWin32Window owner, Uri translationProviderUri, string translationProviderState, ITranslationProviderCredentialStore credentialStore)
        {
            var options = new MtTranslationOptions(translationProviderUri);
            var caption = "Credentials"; //default in case any problem retrieving localized resource below

            caption = PluginResources.PromptForCredentialsCaption;

            var dialog = new MtProviderConfDialog(options, caption, credentialStore);

            dialog.DisableForCredentialsOnly(); //only show controls for setting credentials, as that is the only thing that will end up getting saved

            if (dialog.ShowDialog(owner) == DialogResult.OK)
            {
                //set mst cred
                var creds2 = new GenericCredentials(dialog.Options.AccessKey, dialog.Options.SecretKey);
                SetCredentials(credentialStore, creds2, dialog.Options.PersistAWSCreds);
                return(true);
            }
            return(false);
        }
        public ITranslationProvider[] Browse(IWin32Window owner, LanguagePair[] languagePairs, ITranslationProviderCredentialStore credentialStore)
        {
            //construct options to send to form
            var loadOptions = new MtTranslationOptions();
            //get saved key if there is one and put it into options

            //get credentials
            var getCredAmz = GetMyCredentials(credentialStore, "amazontranslateprovider:///");

            if (getCredAmz != null)
            {
                try
                {
                    var creds = new GenericCredentials(getCredAmz.Credential); //parse credential into username and password
                    loadOptions.AccessKey = creds.UserName;
                    loadOptions.SecretKey = creds.Password;

                    loadOptions.PersistAWSCreds = getCredAmz.Persist;
                    loadOptions.RegionName      = GetRegionName();
                }
                catch { } //swallow b/c it will just fail to fill in instead of crashing the whole program
            }

            //construct form
            var dialog = new MtProviderConfDialog(loadOptions, credentialStore);

            //we are letting user delete creds but after testing it seems that it's ok if the individual credentials are null, b/c our method will re-add them to the credstore based on the uri
            if (dialog.ShowDialog(owner) == DialogResult.OK)
            {
                var testProvider = new MtTranslationProvider(dialog.Options);

                //set credentials
                var creds2 = new GenericCredentials(dialog.Options.AccessKey, dialog.Options.SecretKey);
                SetCredentials(credentialStore, creds2, dialog.Options.PersistAWSCreds);
                SetRegionName(dialog.Options.RegionName);

                SetSupportedLanguages(languagePairs, loadOptions);
                return(new ITranslationProvider[] { testProvider });
            }
            return(null);
        }
Esempio n. 20
0
        private void OKClicked(object sender, EventArgs e)
        {
            int?port = GetPort();

            if (!port.HasValue)
            {
                DialogResult = DialogResult.None;
                string error = string.Format("The port must be a valid port between {0} and {1}.", IPEndPoint.MinPort, IPEndPoint.MaxPort);
                MessageBox.Show(error, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            GenericCredentials credentials = GetCredentials();

            if (!AuthenticateCredentials(credentials))
            {
                return;
            }

            var creds = new TranslationProviderCredential(credentials.ToCredentialString(), Options.PersistCredentials);

            credentialStore.AddCredential(Options.Uri, creds);

            if (setDefaultTM.Checked)
            {
                PluginConfiguration.CurrentInstance.DefaultConnection = new Connection(
                    host: Options.Host,
                    port: Options.Port
                    );
                PluginConfiguration.CurrentInstance.SaveToFile();
            }
            else if (!setDefaultTM.Checked &&
                     PluginConfiguration.CurrentInstance.DefaultConnection.HasValue &&
                     PluginConfiguration.CurrentInstance.DefaultConnection.Value.Host == Options.Host &&
                     PluginConfiguration.CurrentInstance.DefaultConnection.Value.Port == Options.Port)
            {
                PluginConfiguration.CurrentInstance.DefaultConnection = null;
                PluginConfiguration.CurrentInstance.SaveToFile();
            }
        }
        /// <summary>
        /// If the plug-in settings can be changed by the user,
        /// SDL Trados Studio will display a Settings button.
        /// By clicking this button, users raise the plug-in user interface,
        /// in which they can modify any applicable settings, in our implementation
        /// the delimiter character and the list file name.
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="translationProvider"></param>
        /// <param name="languagePairs"></param>
        /// <param name="credentialStore"></param>
        /// <returns></returns>

        public bool Edit(IWin32Window owner, ITranslationProvider translationProvider, LanguagePair[] languagePairs, ITranslationProviderCredentialStore credentialStore)
        {
            var editProvider = translationProvider as MtTranslationProvider;

            if (editProvider == null)
            {
                return(false);
            }

            //get credentials
            var getCredAmz = GetMyCredentials(credentialStore, "amazontranslateprovider:///");

            if (getCredAmz != null)
            {
                try
                {
                    var creds = new GenericCredentials(getCredAmz.Credential); //parse credential into username and password
                    editProvider.Options.AccessKey       = creds.UserName;
                    editProvider.Options.SecretKey       = creds.Password;
                    editProvider.Options.PersistAWSCreds = getCredAmz.Persist;
                }
                catch { }//swallow b/c it will just fail to fill in instead of crashing the whole program
            }

            var dialog = new MtProviderConfDialog(editProvider.Options, credentialStore);

            //we are letting user delete creds but after testing it seems that it's ok if the individual credentials are null, b/c our method will re-add them to the credstore based on the uri
            if (dialog.ShowDialog(owner) == DialogResult.OK)
            {
                editProvider.Options = dialog.Options;
                SetSupportedLanguages(languagePairs, editProvider.Options);
                //set mst cred
                var creds2 = new GenericCredentials(dialog.Options.AccessKey, dialog.Options.SecretKey);
                SetCredentials(credentialStore, creds2, dialog.Options.PersistAWSCreds);
                return(true);
            }

            return(false);
        }
Esempio n. 22
0
        /// <summary>
        /// This gets called when a TranslationProviderAuthenticationException is thrown
        /// Since SDL Studio doesn't pass the provider instance here and even if we do a workaround...
        /// any new options set in the form that comes up are never saved to the project XML...
        /// so there is no way to change any options, only to provide the credentials
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="translationProviderUri"></param>
        /// <param name="translationProviderState"></param>
        /// <param name="credentialStore"></param>
        /// <returns></returns>
        #region "GetCredentialsFromUser"
        public bool GetCredentialsFromUser(IWin32Window owner, Uri translationProviderUri, string translationProviderState, ITranslationProviderCredentialStore credentialStore)
        {
            var options = new MtTranslationOptions(translationProviderUri);
            var caption = "Credentials"; //default in case any problem retrieving localized resource below

            if (options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
            {
                caption = PluginResources.PromptForCredentialsCaption_Google;
            }
            else if (options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
            {
                caption = PluginResources.PromptForCredentialsCaption_Microsoft;
            }

            var dialog = new MtProviderConfDialog(options, caption, credentialStore);

            dialog.DisableForCredentialsOnly(); //only show controls for setting credentials, as that is the only thing that will end up getting saved

            if (dialog.ShowDialog(owner) == DialogResult.OK)
            {
                var apiKey = dialog.Options.ApiKey;

                if (options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    //set google credential
                    SetGoogleCredentials(credentialStore, apiKey, dialog.Options.PersistGoogleKey);
                }
                else if (options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    //set mst cred
                    var creds2 = new GenericCredentials(dialog.Options.ClientId, dialog.Options.ClientSecret);
                    SetMstCredentials(credentialStore, creds2, dialog.Options.PersistMicrosoftCreds);
                }
                return(true);
            }
            return(false);
        }
        /// <summary>
        /// Using the username and password passed in via credentials, obtain the authentication token that will be
        /// later used to validate API calls.
        /// </summary>
        /// <param name="options"></param>
        /// <param name="credentials"></param>
        /// <param name="useHTTP"></param>
        /// <returns></returns>
        public static string GetAuthToken(
            TranslationOptions options,
            GenericCredentials credentials,
            bool useHTTP = false)
        {
            _logger.Trace("");

            lock (optionsLock)
            {
                if (options.ApiVersion == APIVersion.Unknown)
                {
                    SetMtEdgeApiVersion(options);
                }
            }

            ServicePointManager.Expect100Continue      = true;
            ServicePointManager.DefaultConnectionLimit = 9999;
            ServicePointManager.SecurityProtocol       = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

            using (var httpClient = new HttpClient())
            {
                // Build the URI for querying the token
                var builder = new UriBuilder(options.Uri);
                builder.Path = string.Format("/api/{0}/auth", options.ApiVersionString);

                // Pass in the username and password as parameters to retrieve the auth token
                var queryString = HttpUtility.ParseQueryString(string.Empty);
                queryString["username"] = credentials.UserName;
                queryString["password"] = credentials.Password;
                builder.Query           = queryString.ToString();
                builder.Scheme          = useHTTP ? Uri.UriSchemeHttp : Uri.UriSchemeHttps;

                // Users may be hosting the service locally and therefore not sign their certificates. If so,
                // we'll want to accept all certificates. Otherwise, this would throw an exception.
                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

                try
                {
                    var httpResponse = httpClient.PostAsync(builder.Uri, null).Result;
                    if (httpResponse.Content != null && httpResponse.StatusCode == HttpStatusCode.OK)
                    {
                        return(httpResponse.Content.ReadAsStringAsync().Result);
                    }
                    else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized || httpResponse.StatusCode == HttpStatusCode.BadRequest)
                    {
                        throw new UnauthorizedAccessException("The credentials provided are not authorized.");
                    }
                    throw new Exception("No response from the URI provided");
                }
                catch (Exception e)
                {
                    while (e.InnerException != null)
                    {
                        e = e.InnerException;
                    }

                    if (!useHTTP && e.HResult == (int)ErrorHResult.HandshakeFailure)
                    {
                        return(GetAuthToken(options, credentials, true));
                    }
                    _logger.Error($"{Constants.AuthToken}: {e.Message}\n {e.StackTrace}");
                    throw TranslateAggregateException(e);
                }
            }
        }
        /// <summary>
        /// Using the username and password passed in via credentials, obtain the authentication token that will be
        /// later used to validate API calls.
        /// </summary>
        public static string GetAuthToken(
            TranslationOptions options,
            GenericCredentials credentials,
            bool useHTTP = false)
        {
            lock (optionsLock)
            {
                if (options.ApiVersion == APIVersion.Unknown)
                {
                    SetMtEdgeApiVersion(options);
                }
            }

            ServicePointManager.Expect100Continue      = true;
            ServicePointManager.DefaultConnectionLimit = 9999;

            using (var httpClient = new HttpClient())
            {
                // Build the URI for querying the token
                var builder = new UriBuilder(options.Uri)
                {
                    Path = $"/api/{options.ApiVersionString}/auth"
                };

                // Pass in the username and password as parameters to retrieve the auth token
                var queryString = HttpUtility.ParseQueryString(string.Empty);
                queryString["username"] = credentials.UserName;
                queryString["password"] = credentials.Password;
                builder.Query           = queryString.ToString();
                builder.Scheme          = useHTTP ? Uri.UriSchemeHttp : Uri.UriSchemeHttps;


                try
                {
                    var httpResponse = httpClient.PostAsync(builder.Uri, null).Result;
                    if (httpResponse.Content != null && httpResponse.StatusCode == HttpStatusCode.OK)
                    {
                        return(httpResponse.Content.ReadAsStringAsync().Result);
                    }
                    else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized || httpResponse.StatusCode == HttpStatusCode.BadRequest)
                    {
                        throw new UnauthorizedAccessException("The credentials provided are not authorized.");
                    }
                    throw new Exception("No response from the URI provided");
                }
                catch (Exception e)
                {
                    while (e.InnerException != null)
                    {
                        e = e.InnerException;
                    }

                    if (!useHTTP && e.HResult == (int)ErrorHResult.HandshakeFailure)
                    {
                        return(GetAuthToken(options, credentials, true));
                    }
                    _logger.Error($"{Constants.AuthToken}: {e.Message}\n {e.StackTrace}");
                    throw TranslateAggregateException(e);
                }
            }
        }
        private void SetMstCredentials(ITranslationProviderCredentialStore credentialStore, GenericCredentials creds, bool persistCred)
        {
            //used to set credentials
            // we are only setting and getting credentials for the uri with no parameters...kind of like a master credential
            Uri myUri = new Uri("mtenhancedprovidermst:///");

            TranslationProviderCredential cred = new TranslationProviderCredential(creds.ToCredentialString(), persistCred);
            credentialStore.RemoveCredential(myUri);
            credentialStore.AddCredential(myUri, cred);
        }
        public bool GetCredentialsFromUser(IWin32Window owner, Uri translationProviderUri, string translationProviderState, ITranslationProviderCredentialStore credentialStore)
        {
            MtTranslationOptions options = new MtTranslationOptions(translationProviderUri);
            string caption = "Credentials"; //default in case any problem retrieving localized resource below
            if (options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                caption = PluginResources.PromptForCredentialsCaption_Google;
            else if (options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                caption = PluginResources.PromptForCredentialsCaption_Microsoft;

            MtProviderConfDialog dialog = new MtProviderConfDialog(options, caption, credentialStore);
            dialog.DisableForCredentialsOnly(); //only show controls for setting credentials, as that is the only thing that will end up getting saved

            if (dialog.ShowDialog(owner) == DialogResult.OK)
            {
                string apiKey = dialog.Options.apiKey;

                if (options.SelectedProvider == MtTranslationOptions.ProviderType.GoogleTranslate)
                {
                    //set google credential
                    SetGoogleCredentials(credentialStore, apiKey, dialog.Options.persistGoogleKey);
                }
                else if (options.SelectedProvider == MtTranslationOptions.ProviderType.MicrosoftTranslator)
                {
                    //set mst cred
                    GenericCredentials creds2 = new GenericCredentials(dialog.Options.ClientID, dialog.Options.ClientSecret);
                    SetMstCredentials(credentialStore, creds2, dialog.Options.persistMicrosoftCreds);
                }
                return true;
            }
            return false;
        }
Esempio n. 27
0
        private void SetMstCredentials(ITranslationProviderCredentialStore credentialStore, GenericCredentials creds, bool persistCred)
        { //used to set credentials
            // we are only setting and getting credentials for the uri with no parameters...kind of like a master credential
            var myUri = new Uri("mtenhancedprovidermst:///");

            var cred = new TranslationProviderCredential(creds.ToCredentialString(), persistCred);

            credentialStore.RemoveCredential(myUri);
            credentialStore.AddCredential(myUri, cred);
        }