Exemplo n.º 1
0
        public void TestPublishFilesImpersonateNoMachineName()
        {
            WNetCancelConnection2(TestSharePrivate, 0, true);
            using (var app = new VisualStudioApp()) {
                try {
                    var    project = app.OpenProject(@"TestData\HelloWorld.sln");
                    string subDir  = Guid.NewGuid().ToString();
                    project.Properties.Item("PublishUrl").Value = Path.Combine(TestSharePrivate, subDir);
                    app.OnDispose(() => project.Properties.Item("PublishUrl").Value = "");

                    app.OpenSolutionExplorer().SelectProject(project);

                    using (var creds = CredentialsDialog.PublishSelection(app)) {
                        creds.UserName = PrivateShareUserWithoutMachine;
                        creds.Password = PrivateSharePassword;
                        creds.OK();
                    }

                    System.Threading.Thread.Sleep(2000);

                    using (var helper = new NetUseHelper()) {
                        string dir   = Path.Combine(helper.Drive + "\\", subDir);
                        var    files = WaitForFiles(dir);
                        Assert.AreEqual(1, files.Length);
                        Assert.AreEqual("Program.py", Path.GetFileName(files[0]));

                        Directory.Delete(dir, true);
                    }
                } finally {
                    WNetCancelConnection2(TestSharePrivate, 0, true);
                }
            }
        }
Exemplo n.º 2
0
        private void setUserBtn_Click(object sender, EventArgs e)
        {
            CredentialsDialog dlg = new CredentialsDialog(EditorProperties.Resources.TaskSchedulerName);

            if (TargetServer != null)
            {
                dlg.Target = TargetServer;
            }
            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                SetUserText(dlg.UserName);
                string[] userParts = dlg.UserName.Split('\\');
                if (userParts.Length == 1)
                {
                    Domain = TargetServer;
                    User   = userParts[0];
                }
                else if (userParts.Length == 2)
                {
                    Domain = userParts[0];
                    User   = userParts[1];
                }
                Password = dlg.Password;
            }
        }
Exemplo n.º 3
0
        public void TestPublishFilesImpersonate(VisualStudioApp app)
        {
            WNetCancelConnection2(TestSharePrivate, 0, true);
            try {
                var    project = app.OpenProject(@"TestData\HelloWorld.sln");
                string subDir  = Guid.NewGuid().ToString();
                project.Properties.Item("PublishUrl").Value = Path.Combine(TestSharePrivate, subDir);
                app.OnDispose(() => project.Properties.Item("PublishUrl").Value = "");

                app.OpenSolutionExplorer().SelectProject(project);

                using (var creds = CredentialsDialog.PublishSelection(app)) {
                    creds.UserName = PrivateShareUserWithoutMachine;
                    creds.Password = PrivateSharePassword;
                    creds.OK();
                }

                string dir = Path.Combine(TestSharePrivate, subDir);

                var files = WaitForFiles(dir);

                Assert.IsNotNull(files, "Timed out waiting for files to publish");
                Assert.AreEqual(1, files.Length);
                Assert.AreEqual("Program.py", Path.GetFileName(files[0]));

                Directory.Delete(dir, true);
            } finally {
                WNetCancelConnection2(TestSharePrivate, 0, true);
            }
        }
Exemplo n.º 4
0
        private CredentialsDialog ShowDialog(
            string target,
            string username,
            string message,
            bool isNameReadonly)
        {
            CredentialsDialog dialog = new CredentialsDialog(target, "GitMind", message);

            dialog.SaveChecked = true;

            dialog.Name     = username;
            dialog.KeepName = isNameReadonly;

            // The credential dialog is only shown if there are no cached value for that user
            // The dialog contains a "save" check box, which when checked and credentials have been saved
            // will cache the credentials and thus skip showing the dialog the next time.
            // credentialDialog.AlwaysDisplay = true;
            if (dialog.Show(owner.Win32Window) == DialogResult.OK)
            {
                return(dialog);
            }

            Log.Debug($"User canceled {target}, {username}, {message}");
            return(null);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Ask for PSCredential from user
        /// </summary>
        /// <param name="caption">The caption for the message window.</param>
        /// <param name="message">The text of the message.</param>
        /// <param name="userName">The user name whose credential is to be prompted for. If this parameter set to null or an empty string, the function will prompt for the user name first.</param>
        /// <param name="targetName">The name of the target for which the credential is collected.</param>
        /// <param name="allowedCredentialTypes">A bitwise combination of the PSCredentialTypes enumeration values that identify the types of credentials that can be returned.</param>
        /// <param name="options">A bitwise combination of the PSCredentialUIOptions enumeration values that identify the UI behavior when it gathers the credentials.</param>
        /// <returns>A PSCredential object that contains the credentials for the target.</returns>
        public PSCredential GetPSCredential(string caption, string message, string userName,
                                            string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
        {
            PSCredential result = null;

            CredentialsDialog dialog = new CredentialsDialog(targetName, caption, message);

            dialog.Name = userName;

            switch (options)
            {
            case PSCredentialUIOptions.AlwaysPrompt:
                dialog.AlwaysDisplay = true;
                break;

            case PSCredentialUIOptions.ReadOnlyUserName:
                dialog.KeepName = true;
                break;

            case PSCredentialUIOptions.Default:
            case PSCredentialUIOptions.None:
                break;

            default:
                break;
            }

            if (dialog.Show() == DialogResult.OK)
            {
                result = new PSCredential(dialog.Name, dialog.Password);
            }

            return(result);
        }
Exemplo n.º 6
0
        private UserCredentials PromptForCredentials(string url)
        {
            UserCredentials   result = null;
            CredentialsDialog dialog = new CredentialsDialog("Kato - Jenkins Authentication : \r\n" + url);

            if (dialog.Show() == DialogResult.OK && (!String.IsNullOrWhiteSpace(dialog.Password) && !String.IsNullOrWhiteSpace(dialog.Name)))
            {
                var creds = new UserCredentials {
                    UserName = dialog.Name, Password = dialog.Password
                };

                if (!TryToAuthenticate(url, creds))
                {
                    return(null);
                }

                if (dialog.SaveChecked)
                {
                    dialog.Confirm(true);
                }
                result = creds;
            }

            return(result);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DownloadPanel"/> class.
        /// </summary>
        /// <param name="wizard">The wizard.</param>
        public DownloadPanel(IWizard wizard)
            : base(wizard)
        {
            this.Controls.AddRange(new Control[] { this.label1, this.downloadProgress, this.downloadStatus, this.overallStatus, this.overallProgress });

            Wizard.CancelRequest += new EventHandler(wizard_CancelRequest);
            this.LogDebug("Initializing Download Panel");
            installPath = Wizard.GetInstallPath( );
            this.LogDebug("Install path: {0}", installPath);
            SdkPath = Wizard.GetSdkPath( );
            this.LogDebug("SDK Path: {0}", SdkPath);

            CredentialsDialog = new CredentialsDialog( );
            var proxy    = HttpWebRequest.GetSystemWebProxy();
            var bypassed = proxy.IsBypassed(new Uri("http://google.com"));

            if (!bypassed)
            {
                var phost = proxy.GetProxy(new Uri("http://google.com"));
                this.LogDebug("Setting proxy info based on internet explorer");
                CredentialsDialog.ForceUI    = true;
                CredentialsDialog.Caption    = "Proxy Authentication";
                CredentialsDialog.TargetName = phost.Host;
            }
        }
Exemplo n.º 8
0
        private static NetworkCredential PromptImpl(IWin32Window owner, string realm, string path)
        {
            var credential = TryLoadFromFile(path);
            
            using (var dialog = new CredentialsDialog { Realm = realm })
            {
                if (credential != null)
                {
                    dialog.UserName = credential.UserName;
                    dialog.Password = credential.Password;
                    dialog.SavePassword = credential.Password.Length > 0;
                }

                if (dialog.ShowDialog(owner) != DialogResult.OK)
                    return null;

                if (dialog.UserName.Length == 0 || dialog.Password.Length == 0)
                    return null;

                credential = new NetworkCredential(dialog.UserName, dialog.Password);
                    
                if (dialog.SavePassword)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                    SaveToFile(path, credential);
                }
                else
                {
                    if (File.Exists(path))
                        File.Delete(path);
                }
            }

            return credential;
        }
Exemplo n.º 9
0
        private void CheckAuthentication()
        {
            if (username.Length == 0 || api_access_key.Length == 0)
            {
                CredentialsDialog credentialsDialog = new CredentialsDialog();
                System.Windows.Forms.DialogResult dialogResult = credentialsDialog.ShowDialog(this);

                if (dialogResult != DialogResult.OK) return;

                if (dialogResult == DialogResult.OK)
                {
                    username = credentialsDialog.Username;
                    api_access_key = credentialsDialog.ApiAccessKey;
                    deleteAllContainersButton.Enabled = true;
                }

                try
                {
                    Connection = new Connection(new UserCredentials(username, api_access_key));
                    RetrieveContainers();
                }
                catch
                {
                    MessageBox.Show("Authentication failed");
                    Form1_Load(this, new EventArgs());
                }
            }
        }
Exemplo n.º 10
0
        public static UserCredentials PromptForCredentials(string url, bool forceDisplay = false)
        {
            UserCredentials   result = null;
            CredentialsDialog dialog = new CredentialsDialog("Kato - Jenkins Authentication : \r\n" + url)
            {
                AlwaysDisplay = forceDisplay, SaveDisplayed = false
            };

            if (dialog.Show(saveChecked: true) == DialogResult.OK && (!string.IsNullOrWhiteSpace(dialog.Password) && !string.IsNullOrWhiteSpace(dialog.Name)))
            {
                var creds = new UserCredentials {
                    UserName = dialog.Name, Password = dialog.Password
                };

                if (!TryToAuthenticate(url, creds))
                {
                    return(null);
                }

                if (dialog.SaveChecked)
                {
                    dialog.Confirm(true);
                }

                result = creds;
            }

            return(result);
        }
Exemplo n.º 11
0
 public static void CredentialsDialog(Form parentForm)
 {
     using (var credentialsDialog1 = new CredentialsDialog())
     {
         var res = credentialsDialog1.ShowDialog(parentForm);
         AddTestResult(null, "Run", $"{res}: {credentialsDialog1.UserName}:{credentialsDialog1.Password}");
     }
 }
Exemplo n.º 12
0
        private void HandleAuthenticationRequiredMessage(AuthenticationRequiredMessage msg)
        {
            var model = new CredentialsModel {
                PromptMessage = msg.Message
            };
            var credentialsDialog = new CredentialsDialog(model);
            var dialogResult      = credentialsDialog.ShowDialog();

            msg.Callback(dialogResult, model.UserName, model.Password);
        }
Exemplo n.º 13
0
        public AuthenticationInfo?PromtForCredentials(string message)
        {
            var dlg = CredentialsDialog.CreateFromGladeFile(GetMainWindow(), GetWindowGroup());

            dlg.PromptText = message ?? "Authentication required";
            dlg.Run();
            if (dlg.Result)
            {
                return(dlg.Credentials);
            }
            return(null);
        }
Exemplo n.º 14
0
        internal static string InvokeCredentialDialog(string userName, IWin32Window owner)
        {
            CredentialsDialog dlg = new CredentialsDialog(EditorProperties.Resources.TaskSchedulerName,
                                                          EditorProperties.Resources.CredentialPromptMessage, userName);

            dlg.ValidatePassword = true;
            if (dlg.ShowDialog(owner) == DialogResult.OK)
            {
                return(dlg.Password);
            }
            return(null);
        }
        private string InvokeCredentialDialog(string userName)
        {
            CredentialsDialog dlg = new CredentialsDialog(EditorProperties.Resources.TaskSchedulerName,
                                                          EditorProperties.Resources.CredentialPromptMessage, userName);

            dlg.ValidatePassword = true;
            if (dlg.ShowDialog(ParentForm) == DialogResult.OK)
            {
                return(dlg.Password);
            }
            return(null);
        }
 public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
 {
     if (credentialType == CredentialType.RequestCredentials)
     {
         var dialog = new CredentialsDialog(uri.ToString(), "Connecting to " + uri.Host + "...", "Please provide credentials to connect to " + uri);
         if (dialog.Show() == DialogResult.OK)
         {
             return new NetworkCredential(dialog.Username, dialog.Password);
         }
     }
     return null;
 }
Exemplo n.º 17
0
        private bool Login()
        {
            using (CredentialsDialog dlgLogin = new CredentialsDialog())
            {
                dlgLogin.User    = Config.Get <string>("LastUser", string.Empty);
                dlgLogin.Caption = "CCOW Server";
                dlgLogin.Message = "Please provide an administrative user to access configuration settings.";
                while (true)
                {
                    if (dlgLogin.ShowDialog() == DialogResult.OK)
                    {
                        IntPtr token = IntPtr.Zero;

                        if (AuthenticationUtils.Login(dlgLogin.Domain, dlgLogin.User, dlgLogin.PasswordToString(), out token))
                        {
                            WindowsPrincipal principal = Thread.CurrentPrincipal as WindowsPrincipal;

                            if (AuthenticationUtils.IsAdmin(principal) || AuthenticationUtils.IsDomainAdmin(principal))
                            {
                                string saveUser = dlgLogin.User;

                                if (!string.IsNullOrEmpty(dlgLogin.Domain))
                                {
                                    saveUser = dlgLogin.Domain + "\\" + dlgLogin.User;
                                }

                                Config.Set <string>("LastUser", saveUser);
                                return(true);
                            }
                            else
                            {
                                MessageBox.Show(this, "User is not a member of Administrators group.", "Invalid User",
                                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }
                        }
                        else
                        {
                            Win32Exception e = new Win32Exception(Marshal.GetLastWin32Error());

                            MessageBox.Show(this, e.Message, "Authentication Error",
                                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return(false);
        }
Exemplo n.º 18
0
        public bool RequestCredential(CredentialRequest request, out System.Net.NetworkCredential credential)
        {
            credential = null;

            var dialog = new CredentialsDialog(request);

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                credential = dialog.GetCredential();
                return(true);
            }

            return(false);
        }
        /// <summary>
        /// Create a new NetManager object.
        /// </summary>
        public NetManager()
        {
            Log.AddEntry("Initialising network manager...");

            wiretapServer               = new Uri("http://wiretap.wwiionline.com"); // default server
            webClient                   = new MyWebClient();
            proxyCredDialog             = new CredentialsDialog("unused_target");
            proxyCredDialog.Persist     = true;
            proxyCredDialog.SaveChecked = true;
#if !SL
            IEProxy = WebRequest.DefaultWebProxy; // store for later
#endif
            Log.Okay();
        }
Exemplo n.º 20
0
 /// <summary>
 /// Gets the repository.
 /// </summary>
 /// <returns></returns>
 private XmlDocument GetRepository( )
 {
     try {
         XmlDocument    doc = new XmlDocument( );
         string         url = string.Format(URL_FORMAT, REPOSITORY);
         HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
         if (req.Proxy != null && ProxyCredentials != null)
         {
             req.Proxy.Credentials = ProxyCredentials;
         }
         req.UserAgent = string.Format(CultureInfo.InvariantCulture, Properties.Resources.UserAgent, this.GetType( ).Assembly.GetName( ).Version.ToString( ));
         using (HttpWebResponse resp = req.GetResponse( ) as HttpWebResponse) {
             using (Stream strm = resp.GetResponseStream( )) {
                 doc.Load(strm);
                 this.downloadProgress.SetValue(1);
             }
         }
         proxyRetryCount = 0;
         return(doc);
     } catch (WebException wex) {
         if (wex.Message.Contains(Properties.Resources.ProxyExceptionMessage) && proxyRetryCount < PROXY_RETRY_MAX)
         {
             //get credentials
             proxyRetryCount++;
             if (CredentialsDialog.ShowDialog(this.FindForm( ), true) == DialogResult.OK)
             {
                 if (string.IsNullOrEmpty(CredentialsDialog.Username) || string.IsNullOrEmpty(CredentialsDialog.Password))
                 {
                     throw;
                 }
                 else
                 {
                     ProxyCredentials = new NetworkCredential(CredentialsDialog.Username, CredentialsDialog.Password);
                 }
             }
             else
             {
                 throw;
             }
             return(GetRepository( ));
         }
         else
         {
             throw;
         }
     } catch (Exception ex) {
         throw;
     }
 }
Exemplo n.º 21
0
 public SelectDomainDialog(string domain, string username)
     : this()
 {
     if (bUseDefaultDomain)
     {
         rbDefaultDomain.Checked = true;
         tbDomain.Text = "";
     }
     else
     {
         sUsername = username;
         tbDomain.Text = domain;
         rbOtherDomain.Checked = true;
     }
     credsDialog = new CredentialsDialog(username);
 }
Exemplo n.º 22
0
        /// <summary>
        /// Downloads the platform tools.
        /// </summary>
        /// <returns></returns>
        private string DownloadPlatformTools( )
        {
            string tempFile = string.Empty;

            try {
                XmlElement ele = Repository.DocumentElement.SelectSingleNode(PlatformXpath, this.NSManager) as XmlElement;
                if (ele == null)
                {
                    throw new ArgumentException(Properties.Resources.PlatformUrlNotFoundMessage);
                }
                int size = 0;
                int.TryParse(ele.SelectSingleNode("sdk:size", NSManager).InnerText, out size);
                string file = ele.SelectSingleNode("sdk:url", NSManager).InnerText;
                tempFile = Path.Combine(Path.GetTempPath( ), file);
                string toolsUrl = string.Format(URL_FORMAT, file);

                DownloadFile(toolsUrl, tempFile, size);
            } catch (WebException wex) {
                if (wex.Message.Contains(Properties.Resources.ProxyExceptionMessage) && proxyRetryCount < PROXY_RETRY_MAX)
                {
                    //get credentials
                    proxyRetryCount++;
                    if (CredentialsDialog.ShowDialog(this.FindForm( ), true) == DialogResult.OK)
                    {
                        if (string.IsNullOrEmpty(CredentialsDialog.Username) || string.IsNullOrEmpty(CredentialsDialog.Password))
                        {
                            throw;
                        }
                        else
                        {
                            ProxyCredentials = new NetworkCredential(CredentialsDialog.Username, CredentialsDialog.Password);
                        }
                    }
                    else
                    {
                        throw;
                    }
                    return(DownloadSdkTools( ));
                }
                else
                {
                    throw;
                }
            }
            proxyRetryCount = 0;
            return(tempFile);
        }
Exemplo n.º 23
0
        private void Timewax_Load(object sender, RibbonUIEventArgs e)
        {
            bool hasCredentials = HasCredentials();

            if (!hasCredentials)
            {
                CredentialsDialog dialog = new CredentialsDialog(true);
                dialog.Controls["MainLabel"].Text = "Voordat je kan werken met de Timewax intergratie, \n moet je toegangsgegevens geven voor Timewax.";
                DialogResult result = dialog.ShowDialog();
            }

            Setup();

            SetupChangedRowListener();

            Globals.ThisWorkbook.Application.ScreenUpdating = true;
        }
Exemplo n.º 24
0
        private void AddProfileCommand()
        {
            var profileViewModel = new ProfileViewModel();

            var dialog = new CredentialsDialog(profileViewModel)
            {
                Owner = OptionsView.CurrentInstance,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };

            var result = dialog.ShowDialog();

            if (result == true)
            {
                Profiles.Add(profileViewModel);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        ///     Use the credentials dialog, this will show if there are not correct credentials.
        ///     If there are credentials, call the real login.
        /// </summary>
        /// <returns>Task</returns>
        public async Task LoginAsync(CancellationToken cancellationToken = default)
        {
            await LogoutAsync(cancellationToken);

            try
            {
                // Get the system name, so the user knows where to login to
                var credentialsDialog = new CredentialsDialog(_jiraConfiguration.Url)
                {
                    Name = null
                };
                while (credentialsDialog.Show(null, credentialsDialog.Name) == DialogResult.OK)
                {
                    if (await DoLoginAsync(credentialsDialog.Name, credentialsDialog.Password, cancellationToken))
                    {
                        if (credentialsDialog.SaveChecked)
                        {
                            credentialsDialog.Confirm(true);
                        }
                        IsLoggedIn    = true;
                        _loggedInTime = DateTime.Now;
                        return;
                    }
                    // Login failed, confirm this
                    try
                    {
                        credentialsDialog.Confirm(false);
                    }
                    catch (ApplicationException e)
                    {
                        // exception handling ...
                        Log.Error().WriteLine(e, "Problem using the credentials dialog");
                    }
                    // For every windows version after XP show an incorrect password baloon
                    credentialsDialog.IncorrectPassword = true;
                    // Make sure the dialog is display, the password was false!
                    credentialsDialog.AlwaysDisplay = true;
                }
            }
            catch (ApplicationException e)
            {
                // exception handling ...
                Log.Error().WriteLine(e, "Problem using the credentials dialog");
            }
        }
Exemplo n.º 26
0
        public static DialogResult ShowDialog(IWin32Window parent, ref string server, ref string username, ref string password)
        {
            CredentialsDialog frmInit = new CredentialsDialog
                                         {
                                             txtDbServer = { Text = server != string.Empty ? server : "localhost" },
                                             txtUsername = { Text = username },
                                             txtPassword = { Text = password }
                                         };

            DialogResult result = frmInit.ShowDialog(parent);
            if (result == DialogResult.OK)
            {
                username = frmInit.txtUsername.Text;
                password = frmInit.txtPassword.Text;
                server = frmInit.txtDbServer.Text;
            }
            return result;
        }
Exemplo n.º 27
0
        public virtual void GetCredentials(IScheduledResource scheduledResource)
        {
            var cancelled = false;

            while ((String.IsNullOrEmpty(AccountName) || String.IsNullOrEmpty(Password)) && !cancelled)
            {
                CredentialsDialog credentialsDialog = new CredentialsDialog {
                    UserName = scheduledResource.UserName, Options = CredentialsDialogOptions.GenericCredentials, ValidatePassword = true
                };
                var dialogResult = credentialsDialog.ShowDialog();
                if (dialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    cancelled = true;
                }
                AccountName = credentialsDialog.UserName;
                Password    = credentialsDialog.Password;
            }
        }
Exemplo n.º 28
0
        private void EditProfileCommand()
        {
            var tempProfile = JsonConvert.DeserializeObject <ProfileViewModel>(JsonConvert.SerializeObject(SelectedProfile));

            var dialog = new CredentialsDialog(tempProfile)
            {
                Owner = OptionsView.CurrentInstance,
                WindowStartupLocation = WindowStartupLocation.CenterOwner
            };

            var result = dialog.ShowDialog();

            if (result == true)
            {
                Profiles.Remove(SelectedProfile);
                Profiles.Add(tempProfile);
            }
        }
Exemplo n.º 29
0
 public void Login()
 {
     Logout();
     try
     {
         // Get the system name, so the user knows where to login to
         var systemName = _url.Replace(DEFAULT_POSTFIX1, "");
         systemName = systemName.Replace(DEFAULT_POSTFIX2, "");
         var dialog = new CredentialsDialog(systemName)
         {
             Name = null
         };
         while (dialog.Show(null, dialog.Name) == DialogResult.OK)
         {
             if (DoLogin(dialog.Name, dialog.Password))
             {
                 if (dialog.SaveChecked)
                 {
                     dialog.Confirm(true);
                 }
                 return;
             }
             try
             {
                 dialog.Confirm(false);
             }
             catch (ApplicationException e)
             {
                 // exception handling ...
                 Log.Error().WriteLine(e, "Problem using the credentials dialog");
             }
             // For every windows version after XP show an incorrect password baloon
             dialog.IncorrectPassword = true;
             // Make sure the dialog is display, the password was false!
             dialog.AlwaysDisplay = true;
         }
     }
     catch (ApplicationException e)
     {
         // exception handling ...
         Log.Error().WriteLine(e, "Problem using the credentials dialog");
     }
 }
Exemplo n.º 30
0
        public void TestPublishFilesImpersonate()
        {
            var project = DebugProject.OpenProject(@"Python.VS.TestData\HelloWorld.sln");

            try {
                string subDir = Guid.NewGuid().ToString();
                project.Properties.Item("PublishUrl").Value = Path.Combine(TestSharePrivate, subDir);
                string dir = Path.Combine(TestSharePrivate, subDir);
                var    app = new VisualStudioApp(VsIdeTestHostContext.Dte);

                app.OpenSolutionExplorer();
                var window = app.SolutionExplorerTreeView;

                // find Program.py, send copy & paste, verify copy of file is there
                var programPy = window.FindItem("Solution 'HelloWorld' (1 project)", "HelloWorld");

                programPy.SetFocus();

                ThreadPool.QueueUserWorkItem(x => VsIdeTestHostContext.Dte.ExecuteCommand("Build.PublishSelection"));

                var creds = new CredentialsDialog(app.WaitForDialog());
                creds.UserName = PrivateShareUser;
                creds.Password = PrivateSharePassword;
                creds.Ok();

                System.Threading.Thread.Sleep(2000);

                using (var impHelper = new ImpersonationHelper(new System.Net.NetworkCredential(PrivateShareUser.Split('\\')[1], PrivateSharePassword, PrivateShareUser.Split('\\')[0]))) {
                    for (int i = 0; i < 10 && !Directory.Exists(dir); i++)
                    {
                        System.Threading.Thread.Sleep(1000);
                    }

                    var files = Directory.GetFiles(dir);
                    Assert.AreEqual(files.Length, 1);
                    Assert.AreEqual(Path.GetFileName(files[0]), "Program.py");

                    Directory.Delete(dir, true);
                }
            } finally {
                project.Properties.Item("PublishUrl").Value = "";
            }
        }
 public static bool askUserForPassword(string name, string applicationName, Func<string,string,bool> credentialsOkCallback)
 {
     bool value = false;
     try
     {
         CredentialsDialog dialog = new CredentialsDialog(applicationName);
         if (name != null) 
         	dialog.AlwaysDisplay = true; // prevent an infinite loop
         if (dialog.Show(name) == DialogResult.OK)
         {
             if (credentialsOkCallback(dialog.Name, dialog.Password))
             {
                 value = true;
                 if (dialog.SaveChecked) 
                 {
                 	"saving".info();
                 	dialog.Confirm(true);
                 }
                 else                       
                 	"not saving".error();                        
             }
             else
             {
                 try
                 {
                 	"in dialog.Confirm(false)".error();
                     dialog.Confirm(false);
                 }
                 catch (ApplicationException applicationException)
                 {
                  	applicationException.log();
                 }
                 value = askUserForPassword(dialog.Name, applicationName,credentialsOkCallback); // need to find a way to display 'Logon unsuccessful'
             }
         }
     }
     catch (ApplicationException applicationException)
     {
     	applicationException.log();
         // exception handling ...
     }
     return value;
 }                
Exemplo n.º 32
0
        public void CredentialsDialogTest()
        {
            var cd = new CredentialsDialog("Caption", "Message", Environment.UserDomainName + "\\" + Environment.UserName);

            cd.EncryptPassword   = true;
            cd.ForcePreVistaUI   = true;
            cd.SaveChecked       = true;
            cd.ShowSaveCheckBox  = true;
            cd.Target            = "TestTarget";
            cd.ValidatePassword += CredDlgOnValidatePassword;
            cd.ShowDialog();
            Assert.That(MessageBox.Show("Confirm UI strings, old dlg and save chkbox", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes);
            cd.ConfirmCredentials(false);

            cd.Reset();
            Assert.That(cd.Caption, Is.Null);
            Assert.That(cd.SaveChecked, Is.False);

            cd.Caption           = "Caption";
            cd.UserName          = "******";
            cd.ValidatePassword += CredentialsDialog.StandardPasswordValidator;
            cd.ShowDialog();
            Assert.That(MessageBox.Show("Confirm new dlg and no save chkbox", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes);
            cd.ConfirmCredentials(true);

            CredentialsDialog.ParseUserName(cd.UserName, out string user, out string dom);

            void CredDlgOnValidatePassword(object sender, CredentialsDialog.PasswordValidatorEventArgs e)
            {
                Assert.That(ReferenceEquals(sender, cd));
                if (cd.EncryptPassword)
                {
                    Assert.That(e.Password, Is.Null);
                    Assert.That(e.SecurePassword, Is.Not.Null);
                }
                else
                {
                    Assert.That(e.Password, Is.Not.Null);
                    Assert.That(e.SecurePassword, Is.Null);
                }
            }
        }
Exemplo n.º 33
0
        public void TestPublishFilesImpersonateCancelCredentials()
        {
            WNetCancelConnection2(TestSharePrivate, 0, true);
            using (var app = new VisualStudioApp()) {
                try {
                    var    project = app.OpenProject(@"TestData\HelloWorld.sln");
                    string subDir  = Guid.NewGuid().ToString();
                    project.Properties.Item("PublishUrl").Value = Path.Combine(TestSharePrivate, subDir);
                    app.OnDispose(() => project.Properties.Item("PublishUrl").Value = "");
                    string dir = Path.Combine(TestSharePrivate, subDir);

                    app.OpenSolutionExplorer().SelectProject(project);

                    using (var creds = CredentialsDialog.PublishSelection(app)) {
                        creds.UserName = PrivateShareUser;
                        creds.Password = PrivateSharePasswordIncorrect;
                        creds.Cancel();
                    }

                    var          statusBar = app.GetService <IVsStatusbar>(typeof(SVsStatusbar));
                    string       text      = null;
                    const string expected  = "Publish failed: Access to the path";

                    for (int i = 0; i < 10; i++)
                    {
                        ErrorHandler.ThrowOnFailure(statusBar.GetText(out text));

                        if (text.StartsWith(expected))
                        {
                            break;
                        }
                        System.Threading.Thread.Sleep(1000);
                    }

                    Assert.IsTrue(text.StartsWith(expected), "Expected '{0}', got '{1}'", expected, text);
                } finally {
                    WNetCancelConnection2(TestSharePrivate, 0, true);
                }
            }
        }
Exemplo n.º 34
0
        private bool TryGet(
            string url,
            string username,
            string targetKey,
            string message,
            bool isNameReadonly,
            out IGitCredential gitCredential)
        {
            CredentialsDialog dialog = null;

            UiThread.Run(() => dialog = ShowDialog(targetKey, username, message, isNameReadonly));

            if (dialog != null)
            {
                gitCredential = new GitCredential(dialog, url);
                return(true);
            }

            Log.Debug("Credentials dialog canceled");
            gitCredential = null;
            return(false);
        }
Exemplo n.º 35
0
 public void login()
 {
     logout();
     try {
         // Get the system name, so the user knows where to login to
         string systemName = url.Replace(ConfluenceConfiguration.DEFAULT_POSTFIX1, "");
         systemName = url.Replace(ConfluenceConfiguration.DEFAULT_POSTFIX2, "");
         CredentialsDialog dialog = new CredentialsDialog(systemName);
         dialog.Name = null;
         while (dialog.Show(dialog.Name) == DialogResult.OK)
         {
             if (doLogin(dialog.Name, dialog.Password))
             {
                 if (dialog.SaveChecked)
                 {
                     dialog.Confirm(true);
                 }
                 return;
             }
             else
             {
                 try {
                     dialog.Confirm(false);
                 } catch (ApplicationException e) {
                     // exception handling ...
                     LOG.Error("Problem using the credentials dialog", e);
                 }
                 // For every windows version after XP show an incorrect password baloon
                 dialog.IncorrectPassword = true;
                 // Make sure the dialog is display, the password was false!
                 dialog.AlwaysDisplay = true;
             }
         }
     } catch (ApplicationException e) {
         // exception handling ...
         LOG.Error("Problem using the credentials dialog", e);
     }
 }
Exemplo n.º 36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DownloadPanel"/> class.
        /// </summary>
        /// <param name="wizard">The wizard.</param>
        public DownloadPanel( IWizard wizard )
            : base(wizard)
        {
            this.Controls.AddRange ( new Control[] { this.label1, this.downloadProgress, this.downloadStatus, this.overallStatus, this.overallProgress } );

            Wizard.CancelRequest += new EventHandler ( wizard_CancelRequest );
            this.LogDebug ( "Initializing Download Panel" );
            installPath = Wizard.GetInstallPath ( );
            this.LogDebug ( "Install path: {0}", installPath );
            SdkPath = Wizard.GetSdkPath ( );
            this.LogDebug ( "SDK Path: {0}", SdkPath );

            CredentialsDialog = new CredentialsDialog ( );
            var proxy = HttpWebRequest.GetSystemWebProxy();
                var bypassed = proxy.IsBypassed(new Uri("http://google.com"));
            if ( !bypassed ) {
                var phost = proxy.GetProxy ( new Uri ( "http://google.com" ) );
                this.LogDebug ( "Setting proxy info based on internet explorer" );
                CredentialsDialog.ForceUI = true;
                CredentialsDialog.Caption = "Proxy Authentication";
                CredentialsDialog.TargetName = phost.Host;
            }
        }
Exemplo n.º 37
0
 public static bool Login(string name)
 {
     
     bool value = false;
     try
     {
         dialog = new CredentialsDialog("InFlow Outlook Add-In");
         //dialog.Persist = true;
        
         if (name != null) dialog.AlwaysDisplay = true; // prevent an infinite loop
         if (dialog.Show(name) == DialogResult.OK)
         {
             if (Authenticate(dialog.Name, dialog.Password))
             {
                 value = true;
                 if (dialog.SaveChecked) dialog.Confirm(true);
             }
             else
             {
                 try
                 {
                     dialog.Confirm(false);
                 }
                 catch (ApplicationException applicationException)
                 {
                     // exception handling ...
                 }
                 value = Login(dialog.Name); // need to find a way to display 'Logon unsuccessful'
             }
         }
     }
     catch (ApplicationException applicationException)
     {
         // exception handling ...
     }
     return value;
 }
Exemplo n.º 38
0
        public void TestPublishFilesImpersonateCancelCredentials()
        {
            var project = DebugProject.OpenProject(@"Python.VS.TestData\HelloWorld.sln");

            try {
                string subDir = Guid.NewGuid().ToString();
                project.Properties.Item("PublishUrl").Value = Path.Combine(TestSharePrivate, subDir);
                string dir = Path.Combine(TestSharePrivate, subDir);
                var    app = new VisualStudioApp(VsIdeTestHostContext.Dte);

                app.OpenSolutionExplorer();
                var window = app.SolutionExplorerTreeView;

                // find Program.py, send copy & paste, verify copy of file is there
                var programPy = window.FindItem("Solution 'HelloWorld' (1 project)", "HelloWorld");

                programPy.SetFocus();

                ThreadPool.QueueUserWorkItem(x => VsIdeTestHostContext.Dte.ExecuteCommand("Build.PublishSelection"));

                var creds = new CredentialsDialog(app.WaitForDialog());
                creds.UserName = PrivateShareUser;
                creds.Password = PrivateSharePasswordIncorrect;
                creds.Cancel();

                System.Threading.Thread.Sleep(2000);

                var    statusBar = (IVsStatusbar)VsIdeTestHostContext.ServiceProvider.GetService(typeof(SVsStatusbar));
                string text;
                ErrorHandler.ThrowOnFailure(statusBar.GetText(out text));

                const string expected = "Publish failed: Access to the path '";
                Assert.IsTrue(text.StartsWith(expected), "Expected '{0}', got '{1}'", expected, text);
            } finally {
                project.Properties.Item("PublishUrl").Value = "";
            }
        }
		private string InvokeCredentialDialog(string userName)
		{
			CredentialsDialog dlg = new CredentialsDialog(EditorProperties.Resources.TaskSchedulerName,
				EditorProperties.Resources.CredentialPromptMessage, userName);
			dlg.Options |= CredentialsDialogOptions.Persist;
			dlg.ValidatePassword = true;
			if (dlg.ShowDialog(this.ParentForm) == DialogResult.OK)
				return dlg.Password;
			return null;
		}
 private void linkCreds_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     credsDialog = new CredentialsDialog(sUsername);
     credsDialog.ShowDialog(this);
 }
Exemplo n.º 41
0
    /// <summary>
    /// Method will be called when we try to connect to Host from the ADUC Plugin
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void cm_OnConnect(object sender, EventArgs e)
    {
        bool initialConnect = true;
        SelectDomainDialog domainDlg = null;

        while (true)
        {
            if (initialConnect)
            {
                domainDlg = new SelectDomainDialog(_hn.domainName, _hn.creds.UserName);
                if (domainDlg.ShowDialog() == DialogResult.OK)
                {
                    _hn.domainName = domainDlg.GetDomain();
                    _hn.domainControllerName = domainDlg.GetDomainControllerName();

                    if (!domainDlg.UseDefaultUserCreds())
                    {
                        _hn.creds.UserName = domainDlg.GetUsername();
                        _hn.creds.Password = domainDlg.GetPassword();
                    }
                }
                else
                {
                    if (!_hn.IsConnectionSuccess)
                        _hn.domainControllerName = _hn.domainName = _hn.creds.UserName = _hn.creds.Password = "";

                    break; // Connection dialog close on cancel
                }
            }

            if (!ConnectToDomain())
            {
                if (!domainDlg.UseDefaultUserCreds())
                {
                    CredentialsDialog credsDialog = new CredentialsDialog(_hn.creds.UserName);
                    if (credsDialog.ShowDialog(domainDlg) == DialogResult.OK)
                    {
                        _hn.creds.UserName = credsDialog.GetUsername();
                        _hn.creds.Password = credsDialog.GetPassword();

                        initialConnect = false;
                        continue;
                    }
                    else
                    {
                        _hn.domainControllerName = _hn.domainName = _hn.creds.UserName = _hn.creds.Password = "";
                        break; // Connection dialog close on cancel
                    }
                }
                else
                {
                    MessageBox.Show("Failed to connect to domain. Please use the alternate credentials",
                                    "Likewise Administrative Console", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                break;
            }
        }
    }
Exemplo n.º 42
0
		public void login() {
			logout();
			try {
				// Get the system name, so the user knows where to login to
				string systemName = url.Replace(ConfluenceConfiguration.DEFAULT_POSTFIX1,"");
                systemName = url.Replace(ConfluenceConfiguration.DEFAULT_POSTFIX2, "");
                CredentialsDialog dialog = new CredentialsDialog(systemName);
				dialog.Name = null;
				while (dialog.Show(dialog.Name) == DialogResult.OK) {
					if (doLogin(dialog.Name, dialog.Password)) {
						if (dialog.SaveChecked) {
							dialog.Confirm(true);
						}
						return;
					} else {
						try {
							dialog.Confirm(false);
						} catch (ApplicationException e) {
							// exception handling ...
							LOG.Error("Problem using the credentials dialog", e);
						}
						// For every windows version after XP show an incorrect password baloon
						dialog.IncorrectPassword = true;
						// Make sure the dialog is display, the password was false!
						dialog.AlwaysDisplay = true;
					}
				}
			} catch (ApplicationException e) {
				// exception handling ...
				LOG.Error("Problem using the credentials dialog", e);
			}
		}
Exemplo n.º 43
0
        public UpdateProject OpenProject(string projectPath)
        {
            UpdateProject project;
            try
            {
                project = UpdateProject.LoadProject(projectPath);
            }
            catch (Exception ex)
            {
                Popup.ShowPopup(this, SystemIcons.Error, "Error while reading the project.", ex,
                    PopupButtons.Ok);
                return null;
            }

            if (!project.SaveCredentials)
            {
                var credentialsDialog = new CredentialsDialog();
                if (credentialsDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        _ftpPassword =
                            AesManager.Decrypt(Convert.FromBase64String(project.FtpPassword),
                                credentialsDialog.Password.Trim(), credentialsDialog.Username.Trim());

                        if (project.Proxy != null)
                            _proxyPassword =
                                AesManager.Decrypt(Convert.FromBase64String(project.ProxyPassword),
                                    credentialsDialog.Password.Trim(), credentialsDialog.Username.Trim());

                        if (project.UseStatistics)
                            _sqlPassword =
                                AesManager.Decrypt(Convert.FromBase64String(project.SqlPassword),
                                    credentialsDialog.Password.Trim(), credentialsDialog.Username.Trim());
                    }
                    catch (CryptographicException)
                    {
                        Popup.ShowPopup(this, SystemIcons.Error, "Invalid credentials.",
                            "The entered credentials are invalid.", PopupButtons.Ok);
                        return null;
                    }
                    catch (Exception ex)
                    {
                        Popup.ShowPopup(this, SystemIcons.Error, "The decryption progress has failed.",
                            ex, PopupButtons.Ok);
                        return null;
                    }
                }
                else
                {
                    return null;
                }

                if (project.FtpUsername == credentialsDialog.Username)
                    return project;

                Popup.ShowPopup(this, SystemIcons.Error, "Invalid credentials.",
                    "The entered credentials are invalid.", PopupButtons.Ok);
                return null;
            }

            try
            {
                _ftpPassword =
                    AesManager.Decrypt(Convert.FromBase64String(project.FtpPassword),
                        Program.AesKeyPassword, Program.AesIvPassword);

                if (project.Proxy != null)
                    _proxyPassword =
                        AesManager.Decrypt(Convert.FromBase64String(project.ProxyPassword),
                            Program.AesKeyPassword, Program.AesIvPassword);

                if (project.UseStatistics)
                    _sqlPassword =
                        AesManager.Decrypt(Convert.FromBase64String(project.SqlPassword),
                            Program.AesKeyPassword, Program.AesIvPassword);
            }
            catch (Exception ex)
            {
                Popup.ShowPopup(this, SystemIcons.Error, "The decryption progress has failed.",
                    ex, PopupButtons.Ok);
                return null;
            }

            return project;
        }
 private void AddCredentials_OnClick(object sender, RoutedEventArgs e)
 {
     var credentialsDialogue = new CredentialsDialog();
     credentialsDialogue.Closing += CredentialsDialogue_Closing;
     
     credentialsDialogue.Launch();
 }
		private void setUserBtn_Click(object sender, EventArgs e)
		{
			CredentialsDialog dlg = new CredentialsDialog(EditorProperties.Resources.TaskSchedulerName);
			if (this.TargetServer != null)
				dlg.Target = this.TargetServer;
			if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
			{
				SetUserText(dlg.UserName);
				string[] userParts = dlg.UserName.Split('\\');
				if (userParts.Length == 1)
				{
					this.Domain = this.TargetServer;
					this.User = userParts[0];
				}
				else if (userParts.Length == 2)
				{
					this.Domain = userParts[0];
					this.User = userParts[1];
				}
				this.Password = dlg.Password;
			}
		}
		internal static string InvokeCredentialDialog(string userName, IWin32Window owner)
		{
			CredentialsDialog dlg = new CredentialsDialog(EditorProperties.Resources.TaskSchedulerName,
				EditorProperties.Resources.CredentialPromptMessage, userName);
			dlg.Options |= CredentialsDialogOptions.Persist;
			dlg.ValidatePassword = true;
			if (dlg.ShowDialog(owner) == DialogResult.OK)
				return dlg.Password;
			return null;
		}
Exemplo n.º 47
0
        private void cm_OnConnectToShare(object sender, EventArgs e)
        {
            WinError error = WinError.ERROR_SUCCESS;
            bool determinePath = true;
            bool initialConnect = false;
            bool showPathError = false;
            string username = null;
            string path = null;

            while (true)
            {
                if (determinePath)
                {
                    // Determine share path to connect to
                    ConnectToShareDialog connectDialog = new ConnectToShareDialog(path, showPathError);

                    if (connectDialog.ShowDialog() == DialogResult.OK)
                    {
                        showPathError = false;
                        determinePath = false;
                        path = connectDialog.GetPath();

                        if (connectDialog.UseAlternateUserCreds())
                        {
                            error = WinError.ERROR_ACCESS_DENIED;
                        }
                        else
                        {
                            initialConnect = true;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                if (initialConnect)
                {
                    Application.UseWaitCursor = true;
                    error = FileClient.FileClient.CreateConnection(path, null, null);
                    Application.UseWaitCursor = false;
                    initialConnect = false;
                }

                if (error == WinError.ERROR_SUCCESS)
                {
                    // Refresh RemoteShares list and exit
                    RemoteShares.Add(path);
                    break;
                }

                if (error == WinError.ERROR_BAD_NET_NAME)
                {
                    // Show share path connect dialog to allow the user to correct the bad path
                    //MessageBox.Show("The network path is unavailable", "File connection error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    showPathError = true;
                    determinePath = true;
                    continue;
                }

                if (error == WinError.ERROR_DOWNGRADE_DETECTED ||
                    error == WinError.ERROR_ACCESS_DENIED ||
                    error == WinError.ERROR_SESSION_CREDENTIAL_CONFLICT ||
                    error == WinError.ERROR_BAD_USERNAME ||
                    error == WinError.ERROR_INVALID_PASSWORD ||
                    error == WinError.ERROR_LOGON_TYPE_NOT_GRANTED)
                {
                    // Prompt for updated user credentials to access share
                    CredentialsDialog credDialog = new CredentialsDialog(username);

                    if (credDialog.ShowDialog() == DialogResult.OK)
                    {
                        if (credDialog.UseDefaultUserCreds())
                        {
                            initialConnect = true;
                            username = null;
                            continue;
                        }

                        username = credDialog.GetUsername();

                        Application.UseWaitCursor = true;
                        error = FileClient.FileClient.CreateConnection(path,
                                                                       username,
                                                                       credDialog.GetPassword());
                        Application.UseWaitCursor = false;
                        continue;
                    }
                    else
                    {
                        // Cancel Connect To attempt
                        break;
                    }
                }
                else
                {
                    // Encounter unexpected error
                    break;
                }
            }

            RefreshNetworkTreeNode();
            Application.UseWaitCursor = false;
        }
Exemplo n.º 48
0
        public virtual void GetCredentials(IScheduledResource scheduledResource)
        {
            var cancelled = false;
            while((String.IsNullOrEmpty(AccountName) || String.IsNullOrEmpty(Password)) && !cancelled)
            {

                CredentialsDialog credentialsDialog = new CredentialsDialog { UserName = scheduledResource.UserName, Options = CredentialsDialogOptions.GenericCredentials, ValidatePassword = true };
                var dialogResult = credentialsDialog.ShowDialog();
                if(dialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    cancelled = true;
                }
                AccountName = credentialsDialog.UserName;
                Password = credentialsDialog.Password;
            }
        }
Exemplo n.º 49
-1
        private void CheckAuthentication()
        {
            if (username.Length == 0 || api_access_key.Length == 0)
            {
                CredentialsDialog credentialsDialog = new CredentialsDialog();
                System.Windows.Forms.DialogResult dialogResult = credentialsDialog.ShowDialog(this);

                if (dialogResult != DialogResult.OK) return;

                if (dialogResult == DialogResult.OK)
                {
                    username = credentialsDialog.Username;
                    api_access_key = credentialsDialog.ApiAccessKey;
                    auth_endpoint = credentialsDialog.AuthEndpoint;

                    if (auth_endpoint.Length == 0)
                    {
                        auth_endpoint = "https://auth.api.rackspacecloud.com/v1.0";
                    }
                    deleteAllContainersButton.Enabled = true;

                }

                try
                {
                    Connection = new Connection(new UserCredentials(new System.Uri(auth_endpoint),username, api_access_key, null, null));
                    RetrieveContainers();
                }
                catch
                {
                    MessageBox.Show("Authentication failed");
                    Form1_Load(this, new EventArgs());
                }
            }
        }