/// <summary>
        /// Downloads some favicons.
        /// </summary>
        /// <param name="entries">The entries.</param>
        private void downloadSomeFavicons(KeePassLib.Collections.PwObjectList<PwEntry> entries)
        {
            StatusProgressForm progressForm = new StatusProgressForm();

            progressForm.InitEx("Downloading Favicons", true, false, m_host.MainWindow);
            progressForm.Show();
            progressForm.SetProgress(0);

            float progress = 0;
            float outputLength = (float)entries.UCount;
            int downloadsCompleted = 0;
            string errorMessage = "";
            int errorCount = 0;

            foreach (PwEntry pwe in entries)
            {
                string message = "";
                downloadOneFavicon(pwe, ref message);
                if (message != "")
                {
                    errorMessage = message;
                    errorCount++;
                }

                downloadsCompleted++;
                progress = (downloadsCompleted / outputLength) * 100;
                progressForm.SetProgress((uint)Math.Floor(progress));
                System.Threading.Thread.Sleep(100);
                if (progressForm.UserCancelled)
                    break;
            }

            progressForm.Hide();
            progressForm.Close();

            if (errorMessage != "")
            {
                if (errorCount == 1)
                    MessageBox.Show(errorMessage, "Download error");
                else
                    MessageBox.Show(errorCount + " errors occurred. The last error message is shown here. To see the other messages, select a smaller group of entries and use the right click menu to start the download. " + errorMessage, "Download errors");
            }

            m_host.MainWindow.UpdateUI(false, null, false, null,
                true, null, true);
            m_host.MainWindow.UpdateTrayIcon();
        }
		/// <summary>
		/// The main routine, called when import is selected
		/// </summary>
		/// <param name="pwStorage"></param>
		/// <param name="sInput"></param>
		/// <param name="slLogger"></param>
		public override void Import(PwDatabase pwStorage, System.IO.Stream sInput, KeePassLib.Interfaces.IStatusLogger slLogger)
		{
            try
            {
                Form1 form = new Form1();

                form.Initialise(pwStorage);

                if (form.ShowDialog() == DialogResult.OK)
                {

                    // return;
                    bool overwritePassword = form.Overwrite;
                    bool searchWeb = form.GetTitles;
                    bool checkMatches = form.Merge;
                    string masterPassword = form.Password;

                    bool addAutoType = form.AddAutoType;
                    PwIcon iconId = (PwIcon)Enum.Parse(typeof(PwIcon), form.IconName);

                    string profilePath = form.ProfilePath;

                    if (String.IsNullOrEmpty(profilePath))
                    {
                        MessageBox.Show("No Profile Selected. Use Load More Profiles", "Profile Required", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Import(pwStorage, sInput, slLogger); // bit of a hack!
                        return;
                    }

                    PwGroup group = form.Group;

                    if (group == null)
                        group = pwStorage.RootGroup;

                    //     return;

                    try
                    {
                        InternetAccessor internetAccessor = new InternetAccessor();

                        slLogger.StartLogging("Importing Firefox Passwords", false);

                        slLogger.SetText("Logging In", LogStatusType.Info);

                        FirefoxProfile profile = new FirefoxProfile(profilePath);

                        profile.Login(masterPassword);

                        slLogger.SetText("Reading Signon file", LogStatusType.Info);


                        FirefoxSignonsFile signonsFile = profile.GetSignonsFile(masterPassword);


                        slLogger.SetText("Processing Passwords", LogStatusType.Info);

                        int count = signonsFile.SignonSites.Count;
                        int pos = 0;

                        //  return;

                        // Loop each entry and add it to KeePass
                        foreach (FirefoxSignonSite signonSite in signonsFile.SignonSites)
                        {
                            // keep the user informed of progress
                            pos++;

                            foreach (FirefoxSignon signon in signonSite.Signons)
                            {
                                if (!slLogger.ContinueWork()) // Check if process has been cancelled by the user
                                    break;


                                slLogger.SetProgress((uint)(100 * ((double)pos) / ((double)count)));


                                string notes = String.Empty;

                                if (form.IncludeImportNotes)
                                {
                                    notes += "Imported from FireFox by the Web Site Advantage FireFox to KeePass Importer" + Environment.NewLine;
                                }

                                // gather the data to import

                                string title = signonSite.Site;
                                string url = signonSite.Site;

                                if (!String.IsNullOrEmpty(signon.LoginFormDomain))
                                {
                                    title = signon.LoginFormDomain;
                                    url = signon.LoginFormDomain;
                                }

                                string host = url;
                                try
                                {
                                    Uri uri = new Uri(url);
                                    host = uri.Host;
                                }
                                catch { }

                                slLogger.SetText(title, LogStatusType.Info);


                                string username = signon.UserName;

                                bool newEntry = true;

                                PwEntry pe = null;

                                if (checkMatches)
                                    pe = KeePassHelper.FindMatchingEntry(pwStorage.RootGroup, url, username);

                                if (pe == null)
                                {
                                    // create a new entry

                                    pe = new PwEntry(true, true);
                                    group.AddEntry(pe, true);
                                    slLogger.SetText("Created new entry", LogStatusType.AdditionalInfo);
                                }
                                else
                                {
                                    newEntry = false;
                                    slLogger.SetText("Found matching entry", LogStatusType.AdditionalInfo);
                                }

                                if (newEntry || overwritePassword)
                                {
                                    // set the password
                                    pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pwStorage.MemoryProtection.ProtectPassword, signon.Password));
                                }

                                if (newEntry)
                                {
                                    // set all fields
                                    pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pwStorage.MemoryProtection.ProtectTitle, title));
                                    pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pwStorage.MemoryProtection.ProtectUserName, username));
                                    pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pwStorage.MemoryProtection.ProtectUrl, url));
                                    if (!String.IsNullOrEmpty(notes))
                                        pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pwStorage.MemoryProtection.ProtectNotes, notes));
                                    pe.Expires = false;
                                    pe.IconId = iconId;

                                    // Gatter any extra information... 

                                    if (!String.IsNullOrEmpty(signon.UserNameField))
                                        pe.Strings.Set("UserNameField", new ProtectedString(false, signon.UserNameField));

                                    if (!String.IsNullOrEmpty(signon.PasswordField))
                                        pe.Strings.Set("PasswordField", new ProtectedString(false, signon.PasswordField));

                                    if (!String.IsNullOrEmpty(signon.LoginFormDomain))
                                        pe.Strings.Set("LoginFormDomain", new ProtectedString(false, signon.LoginFormDomain));

                                }

                                string webTitle = null;

                                // if new or the title is the same as the url then we should try and get the title
                                if (searchWeb)
                                {
                                    // test if new or entry has url as title
                                    if ((newEntry || pe.Strings.Get(PwDefs.TitleField).ReadString() == pe.Strings.Get(PwDefs.UrlField).ReadString()))
                                    {
                                        // get the pages title
                                        slLogger.SetText("Accessing website for title", LogStatusType.AdditionalInfo);

                                        webTitle = internetAccessor.ScrapeTitle(url);

                                        if (!String.IsNullOrEmpty(webTitle))
                                        {
                                            slLogger.SetText("Title set from internet to " + webTitle, LogStatusType.AdditionalInfo);


                                            pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pwStorage.MemoryProtection.ProtectTitle, webTitle));
                                        }
                                    }
                                    //else
                                    //{
                                    //    // Entry has a good title, keep it incase there are other ones for this site
                                    //    title = pe.Strings.Get(PwDefs.TitleField).ReadString();
                                    //}
                                }
                                // return;


                                if (addAutoType)
                                    KeePassHelper.InsertAutoType(pe, "*" + host + "*", KeePassUtilities.AutoTypeSequence());

                                // return;

                                if (webTitle != null && addAutoType)
                                    KeePassHelper.InsertAutoType(pe, KeePassUtilities.AutoTypeWindow(webTitle), KeePassUtilities.AutoTypeSequence());

                            }
                        }
                    }
                    finally
                    {
                        slLogger.EndLogging();
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessage.ShowErrorMessage("Importer", "Import Failed", ex);
            }
		}
 public bool SetText(string strNewText, KeePassLib.Interfaces.LogStatusType lsType)
 {
     return true;
 }
		/// <summary>
		/// The main routine, called when import is selected
		/// </summary>
		/// <param name="pwStorage"></param>
		/// <param name="sInput"></param>
		/// <param name="slLogger"></param>
		public override void Import(PwDatabase pwStorage, System.IO.Stream sInput, KeePassLib.Interfaces.IStatusLogger slLogger)
		{

			FormXml form = new FormXml();

			form.Initialise(pwStorage);

		//	form.GroupName = pwStorage.RootGroup.Name;

			//if (pwStorage.LastSelectedGroup != null)
			//{
			//    form.GroupName = pwStorage.RootGroup.FindGroup(pwStorage.LastSelectedGroup, true).Name;
			//}

			if (form.ShowDialog() == DialogResult.OK)
			{
				bool overwritePassword = form.Overwrite;
				bool searchWeb = form.GetTitles;
				bool checkMatches = form.Merge;

				bool addAutoType = form.AddAutoType;

				PwIcon iconId = (PwIcon)Enum.Parse(typeof(PwIcon), form.IconName);

				PwGroup group = form.Group;

				if (group==null)
					group = pwStorage.RootGroup;

				try
				{
					InternetAccessor internetAccessor = new InternetAccessor();

					slLogger.StartLogging("Importing Firefox File", false);

					slLogger.SetText("Reading File", LogStatusType.Info);

					// Load in the supplied xml document
					XmlDocument fireFoxDocument = new XmlDocument();
					XmlReaderSettings settings = new XmlReaderSettings();
					settings.CheckCharacters = false;
					settings.ValidationType = ValidationType.None;

					XmlReader reader = XmlTextReader.Create(sInput, settings);
					try
					{
						fireFoxDocument.Load(reader);
					}
					catch (Exception ex)
					{
						throw new Exception("Failed to load the password file. " + Environment.NewLine +
							"This may be due to the presence of foreign characters in the data. " + Environment.NewLine +
							"Please check the website for help" + Environment.NewLine + Environment.NewLine + ex.Message, ex);
					}
					finally
					{
						reader.Close();
					}

					// Get a collection of nodes that represent each password
					XmlNodeList fireFoxEntryNodes = fireFoxDocument.SelectNodes("xml/entries/entry");

					int count = fireFoxEntryNodes.Count;
					int pos = 0;

					// Loop each entry and add it to KeePass
					foreach (XmlElement fireFoxEntryElement in fireFoxEntryNodes)
					{
						if (!slLogger.ContinueWork()) // Check if process has been cancelled by the user
							break;

						// keep the user informed of progress
						pos++;
						slLogger.SetProgress((uint)(100 * ((double)pos) / ((double)count)));

						// gather the data to import
						string title = fireFoxEntryElement.SelectSingleNode("@host").InnerText;

						slLogger.SetText(title, LogStatusType.Info);


                        string notes = String.Empty;

                        if (form.IncludeImportNotes)
                        {
                            notes += "Imported from FireFox by the Web Site Advantage FireFox to KeePass Importer" + Environment.NewLine;
                        }

						string url = fireFoxEntryElement.SelectSingleNode("@host").InnerText;
						string formSubmitURL = fireFoxEntryElement.SelectSingleNode("@formSubmitURL").InnerText;

						if (!String.IsNullOrEmpty(formSubmitURL))
							url = formSubmitURL;

                        string host = url;
                        try
                        {
                            Uri uri = new Uri(url);
                            host = uri.Host;
                        }
                        catch { }

						string username = fireFoxEntryElement.SelectSingleNode("@user").InnerText;

						bool newEntry = true;

						PwEntry pe = null;

						if (checkMatches)
							pe = KeePassHelper.FindMatchingEntry(pwStorage.RootGroup, url, username);

						if (pe == null)
						{
							// create a new entry
							pe = new PwEntry(true, true);
							group.AddEntry(pe,true);
							slLogger.SetText("Created new entry", LogStatusType.AdditionalInfo);
						}
						else
						{
							newEntry = false;
							slLogger.SetText("Found matching entry", LogStatusType.AdditionalInfo);
						}

						if (newEntry || overwritePassword)
						{
							// set the password
							pe.Strings.Set(PwDefs.PasswordField, new ProtectedString(pwStorage.MemoryProtection.ProtectPassword, fireFoxEntryElement.SelectSingleNode("@password").InnerText));
						}

						if (newEntry)
						{
							// set all fields
							pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pwStorage.MemoryProtection.ProtectTitle, title));
							pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(pwStorage.MemoryProtection.ProtectUserName, username));
							pe.Strings.Set(PwDefs.UrlField, new ProtectedString(pwStorage.MemoryProtection.ProtectUrl, url));
                            if (!String.IsNullOrEmpty(notes))
							    pe.Strings.Set(PwDefs.NotesField, new ProtectedString(pwStorage.MemoryProtection.ProtectNotes, notes));
							pe.Expires = false;
							pe.IconId = iconId;

							// Gatter any extra information... 

							if (fireFoxEntryElement.HasAttribute("userFieldName") && fireFoxEntryElement.GetAttribute("userFieldName").Length > 0)
								pe.Strings.Set("UserNameField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("userFieldName")));

							if (fireFoxEntryElement.HasAttribute("usernameField") && fireFoxEntryElement.GetAttribute("usernameField").Length > 0)
								pe.Strings.Set("UserNameField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("usernameField")));

							if (fireFoxEntryElement.HasAttribute("passFieldName") && fireFoxEntryElement.GetAttribute("passFieldName").Length > 0)
								pe.Strings.Set("PasswordField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("passFieldName")));

							if (fireFoxEntryElement.HasAttribute("passwordField") && fireFoxEntryElement.GetAttribute("passwordField").Length > 0)
								pe.Strings.Set("PasswordField", new ProtectedString(false, fireFoxEntryElement.GetAttribute("passwordField")));

							if (fireFoxEntryElement.HasAttribute("httpRealm") && fireFoxEntryElement.GetAttribute("httpRealm").Length > 0)
								pe.Strings.Set("HttpRealm", new ProtectedString(false, fireFoxEntryElement.GetAttribute("httpRealm")));

							if (fireFoxEntryElement.HasAttribute("formSubmitURL") && fireFoxEntryElement.GetAttribute("formSubmitURL").Length > 0)
								pe.Strings.Set("LoginFormDomain", new ProtectedString(false, fireFoxEntryElement.GetAttribute("formSubmitURL")));

						}

						string webTitle = null;
						// if new or the title is the same as the url then we should try and get the title
						if (searchWeb)
						{

							// test if new or entry has url as title
							if ((newEntry || pe.Strings.Get(PwDefs.TitleField).ReadString() == pe.Strings.Get(PwDefs.UrlField).ReadString()))
							{
								// get the pages title
								slLogger.SetText("Accessing website for title", LogStatusType.AdditionalInfo);

								webTitle = internetAccessor.ScrapeTitle(url);

								if (!String.IsNullOrEmpty(webTitle))
								{
									slLogger.SetText("Title set from internet to " + webTitle, LogStatusType.AdditionalInfo);

									pe.Strings.Set(PwDefs.TitleField, new ProtectedString(pwStorage.MemoryProtection.ProtectTitle, webTitle));
								}
							}
						}

                        if (addAutoType)
                            KeePassHelper.InsertAutoType(pe, "*" + host + "*", KeePassUtilities.AutoTypeSequence());

						if (webTitle!=null && addAutoType)
                            KeePassHelper.InsertAutoType(pe, KeePassUtilities.AutoTypeWindow(webTitle), KeePassUtilities.AutoTypeSequence());
					}
				}
				finally
				{
					slLogger.EndLogging();
				}
			}
		}
 public override string GetCellData(string columnName, KeePassLib.PwEntry entry)
 {
     switch (columnName) {
     case sshKeyStatusColumnName:
       var agentModeAgent = ext.agent as Agent;
       if (agentModeAgent != null && agentModeAgent.IsLocked) {
     return "Agent Locked";
       }
       try {
     var key = entry.GetSshKey();
     if (key == null)
       return "N/A";
     if (ext.agent.GetAllKeys().Get(key.Version, key.GetPublicKeyBlob()) != null)
       return "Loaded";
       } catch (PpkFormatterException) {
     return "Error";
       } catch (Exception ex) {
     Debug.Fail(ex.Message);
     return "*Error";
       }
       return "Not Loaded";
       }
       Debug.Fail(string.Format("Unknown column name: {0}", columnName));
       return string.Empty;
 }
 public override void PerformCellAction(string columnName, KeePassLib.PwEntry entry)
 {
     switch (columnName) {
     case sshKeyStatusColumnName:
       try {
     var key = entry.GetSshKey();
     if (key == null)
       break;
     var agentKey = ext.agent.GetAllKeys().Get(key.Version, key.GetPublicKeyBlob());
     if (agentKey == null)
       ext.AddEntry(entry, null);
     else
       ext.agent.RemoveKey(agentKey);
       } catch (Exception ex) {
     Debug.Fail(ex.Message);
       }
       break;
     default:
       Debug.Fail(string.Format("Unsupported column: {0}", columnName));
       break;
       }
 }
 /// <summary>
 /// Retrieves a OneDrive Refresh Token from the provided KeePass database
 /// </summary>
 /// <param name="keePassDatabase">KeePass database instance to get the Refresh Token from</param>
 /// <returns>OneDrive Refresh Token if available or NULL if no Refresh Token found for the provided database</returns>
 public static string GetRefreshTokenFromKeePassDatabase(KeePassLib.PwDatabase keePassDatabase)
 {
     var refreshToken = keePassDatabase.CustomData.Get("KoenZomers.KeePass.OneDriveSync.RefreshToken");
     return refreshToken;
 }
 /// <summary>
 /// Saves the provided OneDrive Refresh Token in the provided KeePass database
 /// </summary>
 /// <param name="keePassDatabase">KeePass database instance to store the Refresh Token in</param>
 /// <param name="refreshToken">The OneDrive Refresh Token to store securely in the KeePass database</param>
 public static void SaveRefreshTokenInKeePassDatabase(KeePassLib.PwDatabase keePassDatabase, string refreshToken)
 {
     keePassDatabase.CustomData.Set("KoenZomers.KeePass.OneDriveSync.RefreshToken", refreshToken);
 }