private void OnBtnOK(object sender, EventArgs e)
        {
            m_pwDatabase.SettingsChanged = DateTime.UtcNow;

            if (m_tbDbName.Text != m_pwDatabase.Name)
            {
                m_pwDatabase.Name        = m_tbDbName.Text;
                m_pwDatabase.NameChanged = DateTime.UtcNow;
            }

            string strNew    = m_tbDbDesc.Text;
            string strOrgFlt = StrUtil.NormalizeNewLines(m_pwDatabase.Description, false);
            string strNewFlt = StrUtil.NormalizeNewLines(strNew, false);

            if (strNewFlt != strOrgFlt)
            {
                m_pwDatabase.Description        = strNew;
                m_pwDatabase.DescriptionChanged = DateTime.UtcNow;
            }

            if (m_tbDefaultUser.Text != m_pwDatabase.DefaultUserName)
            {
                m_pwDatabase.DefaultUserName        = m_tbDefaultUser.Text;
                m_pwDatabase.DefaultUserNameChanged = DateTime.UtcNow;
            }

            if (!m_cbColor.Checked)
            {
                m_pwDatabase.Color = Color.Empty;
            }
            else
            {
                m_pwDatabase.Color = m_clr;
            }

            int nCipher = CipherPool.GlobalPool.GetCipherIndex(m_cmbEncAlgo.Text);

            Debug.Assert(nCipher >= 0);
            if (nCipher >= 0)
            {
                m_pwDatabase.DataCipherUuid = CipherPool.GlobalPool[nCipher].CipherUuid;
            }
            else
            {
                m_pwDatabase.DataCipherUuid = StandardAesEngine.AesUuid;
            }

            // m_pwDatabase.KeyEncryptionRounds = (ulong)m_numKdfIt.Value;
            KdfParameters pKdf = GetKdfParameters(true);

            if (pKdf != null)
            {
                m_pwDatabase.KdfParameters = pKdf;
            }
            // No assert, plugins may assign KDF parameters

            if (m_rbNone.Checked)
            {
                m_pwDatabase.Compression = PwCompressionAlgorithm.None;
            }
            else if (m_rbGZip.Checked)
            {
                m_pwDatabase.Compression = PwCompressionAlgorithm.GZip;
            }
            else
            {
                Debug.Assert(false);
            }

            // m_pwDatabase.MemoryProtection.ProtectTitle = UpdateMemoryProtection(0,
            //	m_pwDatabase.MemoryProtection.ProtectTitle, PwDefs.TitleField);
            // m_pwDatabase.MemoryProtection.ProtectUserName = UpdateMemoryProtection(1,
            //	m_pwDatabase.MemoryProtection.ProtectUserName, PwDefs.UserNameField);
            // m_pwDatabase.MemoryProtection.ProtectPassword = UpdateMemoryProtection(2,
            //	m_pwDatabase.MemoryProtection.ProtectPassword, PwDefs.PasswordField);
            // m_pwDatabase.MemoryProtection.ProtectUrl = UpdateMemoryProtection(3,
            //	m_pwDatabase.MemoryProtection.ProtectUrl, PwDefs.UrlField);
            // m_pwDatabase.MemoryProtection.ProtectNotes = UpdateMemoryProtection(4,
            //	m_pwDatabase.MemoryProtection.ProtectNotes, PwDefs.NotesField);

            // m_pwDatabase.MemoryProtection.AutoEnableVisualHiding = m_cbAutoEnableHiding.Checked;

            if (m_cbRecycleBin.Checked != m_pwDatabase.RecycleBinEnabled)
            {
                m_pwDatabase.RecycleBinEnabled = m_cbRecycleBin.Checked;
                m_pwDatabase.RecycleBinChanged = DateTime.UtcNow;
            }
            int iRecBinSel = m_cmbRecycleBin.SelectedIndex;

            if (m_dictRecycleBinGroups.ContainsKey(iRecBinSel))
            {
                if (!m_dictRecycleBinGroups[iRecBinSel].Equals(m_pwDatabase.RecycleBinUuid))
                {
                    m_pwDatabase.RecycleBinUuid    = m_dictRecycleBinGroups[iRecBinSel];
                    m_pwDatabase.RecycleBinChanged = DateTime.UtcNow;
                }
            }
            else
            {
                Debug.Assert(false);
                if (!PwUuid.Zero.Equals(m_pwDatabase.RecycleBinUuid))
                {
                    m_pwDatabase.RecycleBinUuid    = PwUuid.Zero;
                    m_pwDatabase.RecycleBinChanged = DateTime.UtcNow;
                }
            }

            int iTemplSel = m_cmbEntryTemplates.SelectedIndex;

            if (m_dictEntryTemplateGroups.ContainsKey(iTemplSel))
            {
                if (!m_dictEntryTemplateGroups[iTemplSel].Equals(m_pwDatabase.EntryTemplatesGroup))
                {
                    m_pwDatabase.EntryTemplatesGroup        = m_dictEntryTemplateGroups[iTemplSel];
                    m_pwDatabase.EntryTemplatesGroupChanged = DateTime.UtcNow;
                }
            }
            else
            {
                Debug.Assert(false);
                if (!PwUuid.Zero.Equals(m_pwDatabase.EntryTemplatesGroup))
                {
                    m_pwDatabase.EntryTemplatesGroup        = PwUuid.Zero;
                    m_pwDatabase.EntryTemplatesGroupChanged = DateTime.UtcNow;
                }
            }

            if (!m_cbHistoryMaxItems.Checked)
            {
                m_pwDatabase.HistoryMaxItems = -1;
            }
            else
            {
                m_pwDatabase.HistoryMaxItems = (int)m_numHistoryMaxItems.Value;
            }

            if (!m_cbHistoryMaxSize.Checked)
            {
                m_pwDatabase.HistoryMaxSize = -1;
            }
            else
            {
                m_pwDatabase.HistoryMaxSize = (long)m_numHistoryMaxSize.Value * 1024 * 1024;
            }

            m_pwDatabase.MaintainBackups();             // Apply new history settings

            if (!m_cbKeyRec.Checked)
            {
                m_pwDatabase.MasterKeyChangeRec = -1;
            }
            else
            {
                m_pwDatabase.MasterKeyChangeRec = (long)m_numKeyRecDays.Value;
            }

            if (!m_cbKeyForce.Checked)
            {
                m_pwDatabase.MasterKeyChangeForce = -1;
            }
            else
            {
                m_pwDatabase.MasterKeyChangeForce = (long)m_numKeyForceDays.Value;
            }

            m_pwDatabase.MasterKeyChangeForceOnce = m_cbKeyForceOnce.Checked;
        }
        private ProtectedBinary ReadProtectedBinary(XmlReader xr)
        {
            if (xr.MoveToAttribute(AttrRef))
            {
                string strRef = xr.Value;
                if (!string.IsNullOrEmpty(strRef))
                {
                    int iRef;
                    if (StrUtil.TryParseIntInvariant(strRef, out iRef))
                    {
                        ProtectedBinary pb = m_pbsBinaries.Get(iRef);
                        if (pb != null)
                        {
                            // https://sourceforge.net/p/keepass/feature-requests/2023/
                            xr.MoveToElement();
#if DEBUG
                            string strInner = ReadStringRaw(xr);
                            Debug.Assert(string.IsNullOrEmpty(strInner));
#else
                            ReadStringRaw(xr);
#endif

                            return(pb);
                        }
                        else
                        {
                            Debug.Assert(false);
                        }
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            bool bCompressed = false;
            if (xr.MoveToAttribute(AttrCompressed))
            {
                bCompressed = (xr.Value == ValTrue);
            }

            XorredBuffer xb = ProcessNode(xr);
            if (xb != null)
            {
                Debug.Assert(!bCompressed);                 // See SubWriteValue(ProtectedBinary value)
                return(new ProtectedBinary(true, xb));
            }

            string strValue = ReadString(xr);
            if (strValue.Length == 0)
            {
                return(new ProtectedBinary());
            }

            byte[] pbData = Convert.FromBase64String(strValue);
            if (bCompressed)
            {
                pbData = MemUtil.Decompress(pbData);
            }
            return(new ProtectedBinary(false, pbData));
        }
Exemple #3
0
        private static byte[] OpenExternal(string strName, byte[] pbData,
                                           BinaryDataOpenOptions opt)
        {
            byte[] pbResult = null;

            try
            {
                string strBaseTempDir = UrlUtil.EnsureTerminatingSeparator(
                    UrlUtil.GetTempPath(), false);

                string strTempID, strTempDir;
                while (true)
                {
                    byte[] pbRandomID = CryptoRandom.Instance.GetRandomBytes(8);
                    strTempID = Convert.ToBase64String(pbRandomID);
                    strTempID = StrUtil.AlphaNumericOnly(strTempID);
                    if (strTempID.Length == 0)
                    {
                        Debug.Assert(false); continue;
                    }

                    strTempDir = strBaseTempDir + strTempID;
                    if (!Directory.Exists(strTempDir))
                    {
                        Directory.CreateDirectory(strTempDir);

                        strTempDir = UrlUtil.EnsureTerminatingSeparator(
                            strTempDir, false);

                        // Mark directory as encrypted, such that new files
                        // are encrypted automatically; there exists no
                        // Directory.Encrypt method, but we can use File.Encrypt,
                        // because this internally uses the EncryptFile API
                        // function, which works with directories
                        try { File.Encrypt(strTempDir); }
                        catch (Exception) { Debug.Assert(false); }

                        break;
                    }
                }

                string strFile = strTempDir + strName;
                File.WriteAllBytes(strFile, pbData);

                // Encrypt again, in case the directory encryption above failed
                try { File.Encrypt(strFile); }
                catch (Exception) { Debug.Assert(false); }

                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName         = strFile;
                psi.UseShellExecute  = true;
                psi.WorkingDirectory = strTempDir;

                ParameterizedThreadStart pts = new ParameterizedThreadStart(
                    BinaryDataUtil.ShellOpenFn);
                Thread th = new Thread(pts);
                th.Start(psi);

                string strMsgMain = KPRes.AttachExtOpened + MessageService.NewParagraph +
                                    KPRes.AttachExtOpenedPost + ":";
                string strMsgImp        = KPRes.Import;
                string strMsgImpDesc    = KPRes.AttachExtImportDesc;
                string strMsgCancel     = KPRes.DiscardChangesCmd;
                string strMsgCancelDesc = KPRes.AttachExtDiscardDesc;

                VistaTaskDialog vtd = new VistaTaskDialog();
                vtd.CommandLinks    = true;
                vtd.Content         = strMsgMain;
                vtd.MainInstruction = strName;
                vtd.WindowTitle     = PwDefs.ShortProductName;
                vtd.SetIcon(VtdCustomIcon.Question);

                vtd.AddButton((int)DialogResult.OK, strMsgImp, strMsgImpDesc);
                vtd.AddButton((int)DialogResult.Cancel, strMsgCancel, strMsgCancelDesc);

                vtd.FooterText = KPRes.AttachExtSecDel;
                vtd.SetFooterIcon(VtdIcon.Information);

                bool bImport;
                if (vtd.ShowDialog())
                {
                    bImport = ((vtd.Result == (int)DialogResult.OK) ||
                               (vtd.Result == (int)DialogResult.Yes));
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine(strName);
                    sb.AppendLine();
                    sb.AppendLine(strMsgMain);
                    sb.AppendLine();
                    sb.AppendLine("[" + KPRes.Yes + "]:");
                    sb.AppendLine(StrUtil.RemoveAccelerator(strMsgImp) +
                                  " - " + strMsgImpDesc);
                    sb.AppendLine();
                    sb.AppendLine("[" + KPRes.No + "]:");
                    sb.AppendLine(StrUtil.RemoveAccelerator(strMsgCancel) +
                                  " - " + strMsgCancelDesc);
                    sb.AppendLine();
                    sb.AppendLine(KPRes.AttachExtSecDel);

                    bImport = MessageService.AskYesNo(sb.ToString(),
                                                      PwDefs.ShortProductName);
                }

                if (bImport && !opt.ReadOnly)
                {
                    while (true)
                    {
                        try
                        {
                            pbResult = File.ReadAllBytes(strFile);
                            break;
                        }
                        catch (Exception exRead)
                        {
                            if (!AskForRetry(strFile, exRead.Message))
                            {
                                break;
                            }
                        }
                    }
                }

                string strReportObj = null;
                while (true)
                {
                    try
                    {
                        strReportObj = strFile;
                        if (File.Exists(strFile))
                        {
                            FileInfo fiTemp = new FileInfo(strFile);
                            long     cb     = fiTemp.Length;
                            if (cb > 0)
                            {
                                byte[] pbOvr = new byte[cb];
                                Program.GlobalRandom.NextBytes(pbOvr);
                                File.WriteAllBytes(strFile, pbOvr);
                            }

                            File.Delete(strFile);
                        }

                        strReportObj = strTempDir;
                        if (Directory.Exists(strTempDir))
                        {
                            Directory.Delete(strTempDir, true);
                        }

                        break;
                    }
                    catch (Exception exDel)
                    {
                        if (!AskForRetry(strReportObj, exDel.Message))
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageService.ShowWarning(ex.Message);
            }

            return(pbResult);
        }
Exemple #4
0
        private static void CreateFromDirectory(string strDirPath)
        {
            string strPlgx = strDirPath + "." + PlgxExtension;

            PlgxPluginInfo plgx = new PlgxPluginInfo(false, true, true);

            PlgxCsprojLoader.LoadDefault(strDirPath, plgx);

            FileStream fs = new FileStream(strPlgx, FileMode.Create,
                                           FileAccess.Write, FileShare.None);
            BinaryWriter bw = new BinaryWriter(fs);

            bw.Write(PlgxSignature1);
            bw.Write(PlgxSignature2);
            bw.Write(PlgxVersion);
            WriteObject(bw, PlgxFileUuid, (new PwUuid(true)).UuidBytes);
            WriteObject(bw, PlgxBaseFileName, StrUtil.Utf8.GetBytes(
                            plgx.BaseFileName));
            WriteObject(bw, PlgxCreationTime, StrUtil.Utf8.GetBytes(
                            TimeUtil.SerializeUtc(DateTime.Now)));
            WriteObject(bw, PlgxGeneratorName, StrUtil.Utf8.GetBytes(
                            PwDefs.ShortProductName));
            WriteObject(bw, PlgxGeneratorVersion, MemUtil.UInt64ToBytes(
                            PwDefs.FileVersion64));

            string strKP = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqKP];

            if (!string.IsNullOrEmpty(strKP))
            {
                ulong uKP = StrUtil.ParseVersion(strKP);
                if (uKP != 0)
                {
                    WriteObject(bw, PlgxPrereqKP, MemUtil.UInt64ToBytes(uKP));
                }
            }

            string strNet = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqNet];

            if (!string.IsNullOrEmpty(strNet))
            {
                ulong uNet = StrUtil.ParseVersion(strNet);
                if (uNet != 0)
                {
                    WriteObject(bw, PlgxPrereqNet, MemUtil.UInt64ToBytes(uNet));
                }
            }

            string strOS = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqOS];

            if (!string.IsNullOrEmpty(strOS))
            {
                WriteObject(bw, PlgxPrereqOS, StrUtil.Utf8.GetBytes(strOS));
            }

            string strPtr = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqPtr];

            if (!string.IsNullOrEmpty(strPtr))
            {
                uint uPtr;
                if (uint.TryParse(strPtr, out uPtr))
                {
                    WriteObject(bw, PlgxPrereqPtr, MemUtil.UInt32ToBytes(uPtr));
                }
            }

            string strBuildPre = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxBuildPre];

            if (!string.IsNullOrEmpty(strBuildPre))
            {
                WriteObject(bw, PlgxBuildPre, StrUtil.Utf8.GetBytes(strBuildPre));
            }

            string strBuildPost = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxBuildPost];

            if (!string.IsNullOrEmpty(strBuildPost))
            {
                WriteObject(bw, PlgxBuildPost, StrUtil.Utf8.GetBytes(strBuildPost));
            }

            WriteObject(bw, PlgxBeginContent, null);

            RecursiveFileAdd(bw, strDirPath, new DirectoryInfo(strDirPath));

            WriteObject(bw, PlgxEndContent, null);
            WriteObject(bw, PlgxEOF, null);

            bw.Close();
            fs.Close();

            // Test loading not possible, because MainForm not available
            // PlgxPlugin.Load(strPlgx);
        }
Exemple #5
0
        public static CompositeKey KeyFromCommandLine(CommandLineArgs args)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            CompositeKey cmpKey           = new CompositeKey();
            string       strPassword      = args[AppDefs.CommandLineOptions.Password];
            string       strPasswordEnc   = args[AppDefs.CommandLineOptions.PasswordEncrypted];
            string       strPasswordStdIn = args[AppDefs.CommandLineOptions.PasswordStdIn];
            string       strKeyFile       = args[AppDefs.CommandLineOptions.KeyFile];
            string       strUserAcc       = args[AppDefs.CommandLineOptions.UserAccount];

            if (strPassword != null)
            {
                cmpKey.AddUserKey(new KcpPassword(strPassword));
            }
            else if (strPasswordEnc != null)
            {
                cmpKey.AddUserKey(new KcpPassword(StrUtil.DecryptString(strPasswordEnc)));
            }
            else if (strPasswordStdIn != null)
            {
                KcpPassword kcpPw = ReadPasswordStdIn(true);
                if (kcpPw != null)
                {
                    cmpKey.AddUserKey(kcpPw);
                }
            }

            if (strKeyFile != null)
            {
                if (Program.KeyProviderPool.IsKeyProvider(strKeyFile))
                {
                    KeyProviderQueryContext ctxKP = new KeyProviderQueryContext(
                        IOConnectionInfo.FromPath(args.FileName), false, false);

                    bool   bPerformHash;
                    byte[] pbProvKey = Program.KeyProviderPool.GetKey(strKeyFile, ctxKP,
                                                                      out bPerformHash);
                    if ((pbProvKey != null) && (pbProvKey.Length > 0))
                    {
                        try { cmpKey.AddUserKey(new KcpCustomKey(strKeyFile, pbProvKey, bPerformHash)); }
                        catch (Exception exCKP)
                        {
                            MessageService.ShowWarning(exCKP);
                            return(null);
                        }

                        Array.Clear(pbProvKey, 0, pbProvKey.Length);
                    }
                    else
                    {
                        return(null);                     // Provider has shown error message
                    }
                }
                else                 // Key file
                {
                    try { cmpKey.AddUserKey(new KcpKeyFile(strKeyFile)); }
                    catch (Exception exKey)
                    {
                        MessageService.ShowWarning(strKeyFile, KPRes.KeyFileError, exKey);
                        return(null);
                    }
                }
            }

            if (strUserAcc != null)
            {
                try { cmpKey.AddUserKey(new KcpUserAccount()); }
                catch (Exception exUA)
                {
                    MessageService.ShowWarning(exUA);
                    return(null);
                }
            }

            if (cmpKey.UserKeyCount > 0)
            {
                ClearKeyOptions(args, true);
                return(cmpKey);
            }

            return(null);
        }
        private void WriteObject(string name, ProtectedString value, bool bIsEntryString)
        {
            Debug.Assert(name != null);
            Debug.Assert(value != null); if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            m_xmlWriter.WriteStartElement(ElemString);
            m_xmlWriter.WriteStartElement(ElemKey);
            m_xmlWriter.WriteString(StrUtil.SafeXmlString(name));
            m_xmlWriter.WriteEndElement();
            m_xmlWriter.WriteStartElement(ElemValue);

            bool bProtected = value.IsProtected;

            if (bIsEntryString)
            {
                // Adjust memory protection setting (which might be different
                // from the database default, e.g. due to an import which
                // didn't specify the correct setting)
                if (name == PwDefs.TitleField)
                {
                    bProtected = m_pwDatabase.MemoryProtection.ProtectTitle;
                }
                else if (name == PwDefs.UserNameField)
                {
                    bProtected = m_pwDatabase.MemoryProtection.ProtectUserName;
                }
                else if (name == PwDefs.PasswordField)
                {
                    bProtected = m_pwDatabase.MemoryProtection.ProtectPassword;
                }
                else if (name == PwDefs.UrlField)
                {
                    bProtected = m_pwDatabase.MemoryProtection.ProtectUrl;
                }
                else if (name == PwDefs.NotesField)
                {
                    bProtected = m_pwDatabase.MemoryProtection.ProtectNotes;
                }
            }

            if (bProtected && (m_format == KdbxFormat.Default))
            {
                m_xmlWriter.WriteAttributeString(AttrProtected, ValTrue);

                byte[] pbEnc = value.ReadXorredString(m_randomStream);
                if (pbEnc.Length > 0)
                {
                    m_xmlWriter.WriteBase64(pbEnc, 0, pbEnc.Length);
                }
            }
            else
            {
                string strValue = value.ReadString();

                // If names should be localized, we need to apply the language-dependent
                // string transformation here. By default, language-dependent conversions
                // should be applied, otherwise characters could be rendered incorrectly
                // (code page problems).
                if (g_bLocalizedNames)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (char ch in strValue)
                    {
                        char chMapped = ch;

                        // Symbols and surrogates must be moved into the correct code
                        // page area
                        if (char.IsSymbol(ch) || char.IsSurrogate(ch))
                        {
                            UnicodeCategory cat = CharUnicodeInfo.GetUnicodeCategory(ch);
                            // Map character to correct position in code page
                            chMapped = (char)((int)cat * 32 + ch);
                        }
                        else if (char.IsControl(ch))
                        {
                            if (ch >= 256)                            // Control character in high ANSI code page
                            {
                                // Some of the control characters map to corresponding ones
                                // in the low ANSI range (up to 255) when calling
                                // ToLower on them with invariant culture (see
                                // http://lists.ximian.com/pipermail/mono-patches/2002-February/086106.html )
#if !KeePassLibSD
                                chMapped = char.ToLowerInvariant(ch);
#else
                                chMapped = char.ToLower(ch);
#endif
                            }
                        }

                        sb.Append(chMapped);
                    }

                    strValue = sb.ToString();                     // Correct string for current code page
                }

                if ((m_format == KdbxFormat.PlainXml) && bProtected)
                {
                    m_xmlWriter.WriteAttributeString(AttrProtectedInMemPlainXml, ValTrue);
                }

                m_xmlWriter.WriteString(StrUtil.SafeXmlString(strValue));
            }

            m_xmlWriter.WriteEndElement();             // ElemValue
            m_xmlWriter.WriteEndElement();             // ElemString
        }
        public override void Import(PwDatabase pwStorage, Stream sInput,
                                    IStatusLogger slLogger)
        {
            MemoryStream ms = new MemoryStream();

            MemUtil.CopyStream(sInput, ms);
            byte[] pbData = ms.ToArray();
            ms.Close();

            try
            {
                string strData = StrUtil.Utf8.GetString(pbData);
                if (strData.StartsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
                                       StrUtil.CaseIgnoreCmp) && (strData.IndexOf(
                                                                      "WhatSaved=\"Password Safe V3.29\"", StrUtil.CaseIgnoreCmp) >= 0))
                {
                    // Fix broken XML exported by Password Safe 3.29;
                    // this has been fixed in 3.30
                    strData = strData.Replace("<DefaultUsername<![CDATA[",
                                              "<DefaultUsername><![CDATA[");
                    strData = strData.Replace("<DefaultSymbols<![CDATA[",
                                              "<DefaultSymbols><![CDATA[");

                    pbData = StrUtil.Utf8.GetBytes(strData);
                }
            }
            catch (Exception) { Debug.Assert(false); }

            ms = new MemoryStream(pbData, false);
            XmlDocument xmlDoc = XmlUtilEx.CreateXmlDocument();

            xmlDoc.Load(ms);

            XmlNode xmlRoot = xmlDoc.DocumentElement;

            string strLineBreak = "\n";

            try
            {
                XmlAttributeCollection xac = xmlRoot.Attributes;
                XmlNode xmlBreak           = xac.GetNamedItem(AttribLineBreak);
                string  strBreak           = xmlBreak.Value;

                if (!string.IsNullOrEmpty(strBreak))
                {
                    strLineBreak = strBreak;
                }
                else
                {
                    Debug.Assert(false);
                }
            }
            catch (Exception) { Debug.Assert(false); }

            foreach (XmlNode xmlChild in xmlRoot.ChildNodes)
            {
                if (xmlChild.Name == ElemEntry)
                {
                    ImportEntry(xmlChild, pwStorage, strLineBreak);
                }
            }

            XmlNode xnUse = xmlRoot.SelectSingleNode(XPathUseDefaultUser);

            if (xnUse != null)
            {
                string strUse = XmlUtil.SafeInnerText(xnUse);
                if (StrUtil.StringToBool(strUse))
                {
                    XmlNode xn = xmlRoot.SelectSingleNode(XPathDefaultUser);
                    if ((xn != null) && (pwStorage.DefaultUserName.Length == 0))
                    {
                        pwStorage.DefaultUserName = XmlUtil.SafeInnerText(xn);
                        if (pwStorage.DefaultUserName.Length > 0)
                        {
                            pwStorage.DefaultUserNameChanged = DateTime.UtcNow;
                        }
                    }
                }
            }

            ms.Close();
        }
Exemple #8
0
        private static void ImportIcon(XmlNode xn, PwEntry pe, PwDatabase pd)
        {
            XmlNode xnIcon = xn.Attributes.GetNamedItem("ICON");

            if (xnIcon == null)
            {
                return;
            }

            string strIcon = xnIcon.Value;

            if (!StrUtil.IsDataUri(strIcon))
            {
                Debug.Assert(false); return;
            }

            try
            {
                byte[] pbImage = StrUtil.DataUriToData(strIcon);
                if ((pbImage == null) || (pbImage.Length == 0))
                {
                    Debug.Assert(false); return;
                }

                Image img = GfxUtil.LoadImage(pbImage);
                if (img == null)
                {
                    Debug.Assert(false); return;
                }

                byte[] pbPng;
                int    wMax = PwCustomIcon.MaxWidth;
                int    hMax = PwCustomIcon.MaxHeight;
                if ((img.Width <= wMax) && (img.Height <= hMax))
                {
                    using (MemoryStream msPng = new MemoryStream())
                    {
                        img.Save(msPng, ImageFormat.Png);
                        pbPng = msPng.ToArray();
                    }
                }
                else
                {
                    using (Image imgSc = GfxUtil.ScaleImage(img, wMax, hMax))
                    {
                        using (MemoryStream msPng = new MemoryStream())
                        {
                            imgSc.Save(msPng, ImageFormat.Png);
                            pbPng = msPng.ToArray();
                        }
                    }
                }
                img.Dispose();

                PwUuid pwUuid = null;
                int    iEx    = pd.GetCustomIconIndex(pbPng);
                if (iEx >= 0)
                {
                    pwUuid = pd.CustomIcons[iEx].Uuid;
                }
                else
                {
                    pwUuid = new PwUuid(true);
                    pd.CustomIcons.Add(new PwCustomIcon(pwUuid, pbPng));
                    pd.UINeedsIconUpdate = true;
                    pd.Modified          = true;
                }
                pe.CustomIconUuid = pwUuid;
            }
            catch (Exception) { Debug.Assert(false); }
        }
Exemple #9
0
        private static void ExportGroup(StringBuilder sb, PwGroup pg, uint uIndent,
                                        PwDatabase pd)
        {
            ExportData(sb, uIndent, "<DT><H3", null, false, null, false);
            ExportTimes(sb, pg);
            ExportData(sb, 0, ">", pg.Name, true, "</H3>", true);
            ExportData(sb, uIndent, "<DL><p>", null, false, null, true);

            foreach (PwGroup pgSub in pg.Groups)
            {
                ExportGroup(sb, pgSub, uIndent + 1, pd);
            }

#if DEBUG
            List <string> l = new List <string>();
            l.Add("Tag 1");
            l.Add("Tag 2");
            Debug.Assert(StrUtil.TagsToString(l, false) == "Tag 1;Tag 2");
#endif

            foreach (PwEntry pe in pg.Entries)
            {
                string strUrl = pe.Strings.ReadSafe(PwDefs.UrlField);
                if (strUrl.Length == 0)
                {
                    continue;
                }

                // Encode only when really required; '&' does not need
                // to be encoded
                bool bEncUrl = (strUrl.IndexOfAny(new char[] {
                    '\"', '<', '>'
                }) >= 0);

                ExportData(sb, uIndent + 1, "<DT><A HREF=\"", strUrl, bEncUrl,
                           "\"", false);

                ExportTimes(sb, pe);

                if (!pe.CustomIconUuid.Equals(PwUuid.Zero) && (pd != null))
                {
                    try
                    {
                        Image imgIcon = pd.GetCustomIcon(pe.CustomIconUuid, 16, 16);
                        if (imgIcon != null)
                        {
                            using (MemoryStream msIcon = new MemoryStream())
                            {
                                imgIcon.Save(msIcon, ImageFormat.Png);
                                byte[] pbIcon  = msIcon.ToArray();
                                string strIcon = StrUtil.DataToDataUri(pbIcon,
                                                                       "image/png");

                                ExportData(sb, 0, " ICON=\"", strIcon, false,
                                           "\"", false);
                            }
                        }
                        else
                        {
                            Debug.Assert(false);
                        }
                    }
                    catch (Exception) { Debug.Assert(false); }
                }

                if (pe.Tags.Count > 0)
                {
                    string strTags = StrUtil.TagsToString(pe.Tags, false);
                    strTags = strTags.Replace(';', ',');                     // Without space

                    ExportData(sb, 0, " TAGS=\"", strTags, true, "\"", false);
                }

                string strTitle = pe.Strings.ReadSafe(PwDefs.TitleField);
                if (strTitle.Length == 0)
                {
                    strTitle = strUrl;
                }

                ExportData(sb, 0, ">", strTitle, true, "</A>", true);

                string strNotes = pe.Strings.ReadSafe(PwDefs.NotesField);
                if (strNotes.Length > 0)
                {
                    ExportData(sb, uIndent + 1, "<DD>", strNotes, true, null, true);
                }
            }

            ExportData(sb, uIndent, "</DL><p>", null, false, null, true);
        }
        public void Build(RichTextBox rtb)
        {
            if (rtb == null)
            {
                throw new ArgumentNullException("rtb");
            }

            RichTextBox rtbOp   = CreateOpRtb();
            string      strText = m_sb.ToString();

            Dictionary <char, string> dEnc = new Dictionary <char, string>();

            if (MonoWorkarounds.IsRequired(586901))
            {
                StringBuilder sbEnc = new StringBuilder();
                for (int i = 0; i < strText.Length; ++i)
                {
                    char ch = strText[i];
                    if ((int)ch <= 255)
                    {
                        sbEnc.Append(ch);
                    }
                    else
                    {
                        string strCharEnc;
                        if (!dEnc.TryGetValue(ch, out strCharEnc))
                        {
                            strCharEnc = RtfbTag.GenerateRandomIdCode();
                            dEnc[ch]   = strCharEnc;
                        }
                        sbEnc.Append(strCharEnc);
                    }
                }
                strText = sbEnc.ToString();
            }

            rtbOp.Text = strText;
            Debug.Assert(rtbOp.Text == strText);             // Test committed

            if (m_fDefault != null)
            {
                rtbOp.Select(0, rtbOp.TextLength);
                rtbOp.SelectionFont = m_fDefault;
            }

            string strRtf = rtbOp.Rtf;

            rtbOp.Dispose();

            foreach (KeyValuePair <char, string> kvpEnc in dEnc)
            {
                strRtf = strRtf.Replace(kvpEnc.Value,
                                        StrUtil.RtfEncodeChar(kvpEnc.Key));
            }
            foreach (RtfbTag rTag in m_vTags)
            {
                strRtf = strRtf.Replace(rTag.IdCode, rTag.RtfCode);
            }

            rtb.Rtf = strRtf;
        }
Exemple #11
0
		private static List<UpdateComponentInfo> LoadInfoFilePriv(byte[] pbData,
			IOConnectionInfo iocSource)
		{
			if((pbData == null) || (pbData.Length == 0)) return null;

			int iOffset = 0;
			StrEncodingInfo sei = StrUtil.GetEncoding(StrEncodingType.Utf8);
			byte[] pbBom = sei.StartSignature;
			if((pbData.Length >= pbBom.Length) && MemUtil.ArraysEqual(pbBom,
				MemUtil.Mid(pbData, 0, pbBom.Length)))
				iOffset += pbBom.Length;

			string strData = sei.Encoding.GetString(pbData, iOffset, pbData.Length - iOffset);
			strData = StrUtil.NormalizeNewLines(strData, false);
			string[] vLines = strData.Split('\n');

			string strSigKey;
			g_dFileSigKeys.TryGetValue(iocSource.Path.ToLowerInvariant(), out strSigKey);
			string strLdSig = null;
			StringBuilder sbToVerify = ((strSigKey != null) ? new StringBuilder() : null);

			List<UpdateComponentInfo> l = new List<UpdateComponentInfo>();
			bool bHeader = true, bFooterFound = false;
			char chSep = ':'; // Modified by header
			for(int i = 0; i < vLines.Length; ++i)
			{
				string str = vLines[i].Trim();
				if(str.Length == 0) continue;

				if(bHeader)
				{
					chSep = str[0];
					bHeader = false;

					string[] vHdr = str.Split(chSep);
					if(vHdr.Length >= 2) strLdSig = vHdr[1];
				}
				else if(str[0] == chSep)
				{
					bFooterFound = true;
					break;
				}
				else // Component info
				{
					if(sbToVerify != null)
					{
						sbToVerify.Append(str);
						sbToVerify.Append('\n');
					}

					string[] vInfo = str.Split(chSep);
					if(vInfo.Length >= 2)
					{
						UpdateComponentInfo c = new UpdateComponentInfo(
							vInfo[0].Trim(), 0, iocSource.Path, string.Empty);
						c.VerAvailable = StrUtil.ParseVersion(vInfo[1]);

						AddComponent(l, c);
					}
				}
			}
			if(!bFooterFound) { Debug.Assert(false); return null; }

			if(sbToVerify != null)
			{
				if(!VerifySignature(sbToVerify.ToString(), strLdSig, strSigKey))
					return null;
			}

			return l;
		}
Exemple #12
0
        private void UpdateHexView()
        {
            int cbData = (m_bDataExpanded ? m_pbData.Length :
                          Math.Min(m_pbData.Length, 16 * 256));

            const int cbGrp  = 4;
            const int cbLine = 16;

            int iMaxAddrWidth = Convert.ToString(Math.Max(cbData - 1, 0), 16).Length;

            int cbDataUp = cbData;

            if ((cbDataUp % cbLine) != 0)
            {
                cbDataUp = cbDataUp + cbLine - (cbDataUp % cbLine);
            }
            Debug.Assert(((cbDataUp % cbLine) == 0) && (cbDataUp >= cbData));

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < cbDataUp; ++i)
            {
                if ((i % cbLine) == 0)
                {
                    sb.Append(Convert.ToString(i, 16).ToUpper().PadLeft(
                                  iMaxAddrWidth, '0'));
                    sb.Append(": ");
                }

                if (i < cbData)
                {
                    byte bt     = m_pbData[i];
                    byte btHigh = (byte)(bt >> 4);
                    byte btLow  = (byte)(bt & 0x0F);
                    if (btHigh >= 10)
                    {
                        sb.Append((char)('A' + btHigh - 10));
                    }
                    else
                    {
                        sb.Append((char)('0' + btHigh));
                    }
                    if (btLow >= 10)
                    {
                        sb.Append((char)('A' + btLow - 10));
                    }
                    else
                    {
                        sb.Append((char)('0' + btLow));
                    }
                }
                else
                {
                    sb.Append("  ");
                }

                if (((i + 1) % cbGrp) == 0)
                {
                    sb.Append(' ');
                }

                if (((i + 1) % cbLine) == 0)
                {
                    sb.Append(' ');
                    int iStart   = i - cbLine + 1;
                    int iEndExcl = Math.Min(iStart + cbLine, cbData);
                    for (int j = iStart; j < iEndExcl; ++j)
                    {
                        sb.Append(StrUtil.ByteToSafeChar(m_pbData[j]));
                    }
                    sb.AppendLine();
                }
            }

            if (cbData < m_pbData.Length)
            {
                sb.AppendLine(m_strDataExpand);
            }

            SetRtbData(sb.ToString(), false, true);

            if (cbData < m_pbData.Length)
            {
                int iLinkStart = m_rtbText.Text.LastIndexOf(m_strDataExpand);
                if (iLinkStart >= 0)
                {
                    m_rtbText.Select(iLinkStart, m_strDataExpand.Length);
                    UIUtil.RtfSetSelectionLink(m_rtbText);
                    m_rtbText.Select(0, 0);
                }
                else
                {
                    Debug.Assert(false);
                }
            }
        }
Exemple #13
0
        public static void OpenUrl(string strUrlToOpen, PwEntry peDataSource,
                                   bool bAllowOverride, string strBaseRaw)
        {
            // If URL is null, return, do not throw exception.
            Debug.Assert(strUrlToOpen != null); if (strUrlToOpen == null)
            {
                return;
            }

            string strPrevWorkDir = WinUtil.GetWorkingDirectory();
            string strThisExe     = WinUtil.GetExecutable();

            string strExeDir = UrlUtil.GetFileDirectory(strThisExe, false, true);

            WinUtil.SetWorkingDirectory(strExeDir);

            string strUrlFlt = strUrlToOpen;

            strUrlFlt = strUrlFlt.TrimStart(new char[] { ' ', '\t', '\r', '\n' });

            PwDatabase pwDatabase = null;

            try
            {
                pwDatabase = Program.MainForm.DocumentManager.SafeFindContainerOf(
                    peDataSource);
            }
            catch (Exception) { Debug.Assert(false); }

            bool bCmdQuotes = WinUtil.IsCommandLineUrl(strUrlFlt);

            SprContext ctx = new SprContext(peDataSource, pwDatabase,
                                            SprCompileFlags.All, false, bCmdQuotes);

            ctx.Base          = strBaseRaw;
            ctx.BaseIsEncoded = false;

            string strUrl = SprEngine.Compile(strUrlFlt, ctx);

            string strOvr = Program.Config.Integration.UrlSchemeOverrides.GetOverrideForUrl(
                strUrl);

            if (!bAllowOverride)
            {
                strOvr = null;
            }
            if (strOvr != null)
            {
                bool bCmdQuotesOvr = WinUtil.IsCommandLineUrl(strOvr);

                SprContext ctxOvr = new SprContext(peDataSource, pwDatabase,
                                                   SprCompileFlags.All, false, bCmdQuotesOvr);
                ctxOvr.Base          = strUrl;
                ctxOvr.BaseIsEncoded = bCmdQuotes;

                strUrl = SprEngine.Compile(strOvr, ctxOvr);
            }

            if (WinUtil.IsCommandLineUrl(strUrl))
            {
                string strApp, strArgs;
                StrUtil.SplitCommandLine(WinUtil.GetCommandLineFromUrl(strUrl),
                                         out strApp, out strArgs);

                try
                {
                    if ((strArgs != null) && (strArgs.Length > 0))
                    {
                        Process.Start(strApp, strArgs);
                    }
                    else
                    {
                        Process.Start(strApp);
                    }
                }
                catch (Win32Exception)
                {
                    StartWithoutShellExecute(strApp, strArgs);
                }
                catch (Exception exCmd)
                {
                    string strInf = KPRes.FileOrUrl + ": " + strApp;
                    if ((strArgs != null) && (strArgs.Length > 0))
                    {
                        strInf += MessageService.NewParagraph +
                                  KPRes.Arguments + ": " + strArgs;
                    }

                    MessageService.ShowWarning(strInf, exCmd);
                }
            }
            else             // Standard URL
            {
                try { Process.Start(strUrl); }
                catch (Exception exUrl)
                {
                    MessageService.ShowWarning(strUrl, exUrl);
                }
            }

            // Restore previous working directory
            WinUtil.SetWorkingDirectory(strPrevWorkDir);

            // SprEngine.Compile might have modified the database
            Program.MainForm.UpdateUI(false, null, false, null, false, null, false);
        }
Exemple #14
0
        private static string ComputeNewDisplayOrder(List <AceColumn> lNew,
                                                     List <AceColumn> lOld, string strOldOrder)
        {
            if ((lNew == null) || (lOld == null))
            {
                Debug.Assert(false); return(string.Empty);
            }
            if (string.IsNullOrEmpty(strOldOrder))
            {
                return(string.Empty);
            }

            List <AceColumnWithTag> lOldS = new List <AceColumnWithTag>();

            try
            {
                int[] vOld = StrUtil.DeserializeIntArray(strOldOrder);
                if ((vOld == null) || (vOld.Length != lOld.Count))
                {
                    Debug.Assert(false);
                    return(string.Empty);
                }

                for (int i = 0; i < vOld.Length; ++i)
                {
                    if (lOld[i] == null)
                    {
                        Debug.Assert(false); return(string.Empty);
                    }
                    lOldS.Add(new AceColumnWithTag(lOld[i], vOld[i]));
                }

                lOldS.Sort(AceColumnWithTag.CompareByTags);
            }
            catch (Exception) { Debug.Assert(false); return(string.Empty); }

            List <AceColumnWithTag> l = new List <AceColumnWithTag>();

            foreach (AceColumn c in lNew)
            {
                if (c != null)
                {
                    l.Add(new AceColumnWithTag(c, 0));
                }
                else
                {
                    Debug.Assert(false); return(string.Empty);
                }
            }

            long m = Math.Max(lNew.Count, lOld.Count);

            // Preserve order of previous columns
            for (int i = 0; i < lOldS.Count; ++i)
            {
                string strOldName = lOldS[i].TypeNameEx;

                foreach (AceColumnWithTag ct in l)
                {
                    if (ct.TypeNameEx == strOldName)
                    {
                        ct.Tag = m * i;
                        break;
                    }
                }
            }

            // Insert new columns based on their default position
            for (int i = 1; i < l.Count; ++i)
            {
                if (l[i].Tag == 0)
                {
                    l[i].Tag = l[i - 1].Tag + 1;
                }
            }

            l.Sort(AceColumnWithTag.CompareByTags);

            int[] v = new int[lNew.Count];
            for (int i = 0; i < v.Length; ++i)
            {
                for (int j = 0; j < l.Count; ++j)
                {
                    if (object.ReferenceEquals(l[j].Column, lNew[i]))
                    {
                        v[i] = j;
                        break;
                    }
                }
            }
            Debug.Assert(Array.IndexOf(v, 0) == Array.LastIndexOf(v, 0));

            return(StrUtil.SerializeIntArray(v));
        }
        private void OnFormLoad(object sender, EventArgs e)
        {
            if (m_lInfo == null)
            {
                throw new InvalidOperationException();
            }

            GlobalWindowManager.AddWindow(this, this);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_WWW, KPRes.UpdateCheck,
                                         KPRes.UpdateCheckResults);
            this.Icon = AppIcons.Default;
            this.Text = KPRes.UpdateCheck + " - " + PwDefs.ShortProductName;

            UIUtil.SetExplorerTheme(m_lvInfo, true);

            m_lvInfo.Columns.Add(KPRes.Component);
            m_lvInfo.Columns.Add(KPRes.Status);
            m_lvInfo.Columns.Add(KPRes.Installed);
            m_lvInfo.Columns.Add(KPRes.Available);

            List <Image> lImages = new List <Image>();

            lImages.Add(Properties.Resources.B16x16_Help);
            lImages.Add(Properties.Resources.B16x16_Apply);
            lImages.Add(Properties.Resources.B16x16_Redo);
            lImages.Add(Properties.Resources.B16x16_History);
            lImages.Add(Properties.Resources.B16x16_Error);
            m_ilIcons = UIUtil.BuildImageListUnscaled(lImages,
                                                      DpiUtil.ScaleIntX(16), DpiUtil.ScaleIntY(16));

            m_lvInfo.SmallImageList = m_ilIcons;

            string        strCat   = string.Empty;
            ListViewGroup lvg      = null;
            const uint    uMinComp = 2;

            foreach (UpdateComponentInfo uc in m_lInfo)
            {
                if (uc.Category != strCat)
                {
                    lvg = new ListViewGroup(uc.Category);
                    m_lvInfo.Groups.Add(lvg);
                    strCat = uc.Category;
                }

                ListViewItem lvi = new ListViewItem(uc.Name);

                string strStatus = KPRes.Unknown + ".";
                if (uc.Status == UpdateComponentStatus.UpToDate)
                {
                    strStatus      = KPRes.UpToDate + ".";
                    lvi.ImageIndex = 1;
                }
                else if (uc.Status == UpdateComponentStatus.NewVerAvailable)
                {
                    strStatus      = KPRes.NewVersionAvailable + "!";
                    lvi.ImageIndex = 2;
                }
                else if (uc.Status == UpdateComponentStatus.PreRelease)
                {
                    strStatus      = KPRes.PreReleaseVersion + ".";
                    lvi.ImageIndex = 3;
                }
                else if (uc.Status == UpdateComponentStatus.DownloadFailed)
                {
                    strStatus      = KPRes.UpdateCheckFailedNoDl;
                    lvi.ImageIndex = 4;
                }
                else
                {
                    lvi.ImageIndex = 0;
                }

                lvi.SubItems.Add(strStatus);
                lvi.SubItems.Add(StrUtil.VersionToString(uc.VerInstalled, uMinComp));

                if ((uc.Status == UpdateComponentStatus.UpToDate) ||
                    (uc.Status == UpdateComponentStatus.NewVerAvailable) ||
                    (uc.Status == UpdateComponentStatus.PreRelease))
                {
                    lvi.SubItems.Add(StrUtil.VersionToString(uc.VerAvailable, uMinComp));
                }
                else
                {
                    lvi.SubItems.Add("?");
                }

                if (lvg != null)
                {
                    lvi.Group = lvg;
                }
                m_lvInfo.Items.Add(lvi);
            }

            UIUtil.ResizeColumns(m_lvInfo, new int[] { 2, 2, 1, 1 }, true);
        }
Exemple #16
0
        private static void OpenUrlPriv(string strUrlToOpen, PwEntry peDataSource,
                                        bool bAllowOverride, string strBaseRaw)
        {
            if (string.IsNullOrEmpty(strUrlToOpen))
            {
                Debug.Assert(false); return;
            }

            if (WinUtil.OpenUrlPre != null)
            {
                OpenUrlEventArgs e = new OpenUrlEventArgs(strUrlToOpen, peDataSource,
                                                          bAllowOverride, strBaseRaw);
                WinUtil.OpenUrlPre(null, e);
                strUrlToOpen = e.Url;

                if (string.IsNullOrEmpty(strUrlToOpen))
                {
                    return;
                }
            }

            string strPrevWorkDir = WinUtil.GetWorkingDirectory();
            string strThisExe     = WinUtil.GetExecutable();

            string strExeDir = UrlUtil.GetFileDirectory(strThisExe, false, true);

            WinUtil.SetWorkingDirectory(strExeDir);

            string strUrl = CompileUrl(strUrlToOpen, peDataSource, bAllowOverride,
                                       strBaseRaw, null);

            if (WinUtil.IsCommandLineUrl(strUrl))
            {
                string strApp, strArgs;
                StrUtil.SplitCommandLine(WinUtil.GetCommandLineFromUrl(strUrl),
                                         out strApp, out strArgs);

                try
                {
                    try { NativeLib.StartProcess(strApp, strArgs); }
                    catch (Win32Exception)
                    {
                        ProcessStartInfo psi = new ProcessStartInfo();
                        psi.FileName = strApp;
                        if (!string.IsNullOrEmpty(strArgs))
                        {
                            psi.Arguments = strArgs;
                        }
                        psi.UseShellExecute = false;

                        NativeLib.StartProcess(psi);
                    }
                }
                catch (Exception exCmd)
                {
                    string strMsg = KPRes.FileOrUrl + ": " + strApp;
                    if (!string.IsNullOrEmpty(strArgs))
                    {
                        strMsg += MessageService.NewParagraph +
                                  KPRes.Arguments + ": " + strArgs;
                    }

                    MessageService.ShowWarning(strMsg, exCmd);
                }
            }
            else             // Standard URL
            {
                try { NativeLib.StartProcess(strUrl); }
                catch (Exception exUrl)
                {
                    MessageService.ShowWarning(strUrl, exUrl);
                }
            }

            // Restore previous working directory
            WinUtil.SetWorkingDirectory(strPrevWorkDir);

            // SprEngine.Compile might have modified the database
            MainForm mf = Program.MainForm;

            if (mf != null)
            {
                mf.UpdateUI(false, null, false, null, false, null, false);
            }
        }
Exemple #17
0
        public void SetKeySources(IOConnectionInfo iocDb, CompositeKey cmpKey)
        {
            string strID = GetKeyAssocID(iocDb);
            int    idx   = GetKeyAssocIndex(strID);

            if ((cmpKey == null) || !m_bRememberKeySources)
            {
                if (idx >= 0)
                {
                    m_vKeySources.RemoveAt(idx);
                }
                return;
            }

            AceKeyAssoc a = new AceKeyAssoc();

            a.DatabasePath = strID;

            IUserKey kcpPassword = cmpKey.GetUserKey(typeof(KcpPassword));

            a.Password = (kcpPassword != null);

            IUserKey kcpFile = cmpKey.GetUserKey(typeof(KcpKeyFile));

            if (kcpFile != null)
            {
                string strKeyFile = ((KcpKeyFile)kcpFile).Path;
                if (!string.IsNullOrEmpty(strKeyFile) && !StrUtil.IsDataUri(strKeyFile))
                {
                    if (!UrlUtil.IsAbsolutePath(strKeyFile))
                    {
                        strKeyFile = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(),
                                                              strKeyFile);
                    }

                    a.KeyFilePath = strKeyFile;
                }
            }

            IUserKey kcpCustom = cmpKey.GetUserKey(typeof(KcpCustomKey));

            if (kcpCustom != null)
            {
                a.KeyProvider = ((KcpCustomKey)kcpCustom).Name;
            }

            IUserKey kcpUser = cmpKey.GetUserKey(typeof(KcpUserAccount));

            a.UserAccount = (kcpUser != null);

            bool bAtLeastOne = (a.Password || (a.KeyFilePath.Length > 0) ||
                                (a.KeyProvider.Length > 0) || a.UserAccount);

            if (bAtLeastOne)
            {
                if (idx >= 0)
                {
                    m_vKeySources[idx] = a;
                }
                else
                {
                    m_vKeySources.Add(a);
                }
            }
            else if (idx >= 0)
            {
                m_vKeySources.RemoveAt(idx);
            }
        }
 public void OnOpenEntry()
 {
     foreach (ITotpPluginAdapter adapter in _pluginAdapters)
     {
         TotpData totpData = adapter.GetTotpData(App.Kp2a.GetDb().LastOpenedEntry.OutputStrings.ToDictionary(pair => StrUtil.SafeXmlString(pair.Key), pair => pair.Value.ReadString()), Application.Context, false);
         if (totpData.IsTotpEnry)
         {
             new UpdateTotpTimerTask(Application.Context, adapter).Run();
         }
     }
 }
        private void OnFormLoad(object sender, EventArgs e)
        {
            Debug.Assert(m_pbData != null);
            if (m_pbData == null)
            {
                throw new InvalidOperationException();
            }

            GlobalWindowManager.AddWindow(this);

            this.Icon           = AppIcons.Default;
            this.DoubleBuffered = true;

            m_strInitialFormRect = UIUtil.SetWindowScreenRectEx(this,
                                                                Program.Config.UI.DataEditorRect);

            m_bdc = BinaryDataClassifier.Classify(m_strDataDesc, m_pbData);
            uint            uStartOffset;
            StrEncodingInfo seiGuess = BinaryDataClassifier.GetStringEncoding(
                m_pbData, out uStartOffset);
            string strData;

            try
            {
                strData = (seiGuess.Encoding.GetString(m_pbData, (int)uStartOffset,
                                                       m_pbData.Length - (int)uStartOffset) ?? string.Empty);
                strData = StrUtil.ReplaceNulls(strData);
            }
            catch (Exception) { Debug.Assert(false); strData = string.Empty; }

            ++m_uBlockEvents;

            UIUtil.AssignShortcut(m_menuFileSave, Keys.Control | Keys.S);
            UIUtil.AssignShortcut(m_menuFileExit, Keys.Escape, null, true);
            UIUtil.AssignShortcut(m_menuEditUndo, Keys.Control | Keys.Z, null, true);
            UIUtil.AssignShortcut(m_menuEditRedo, Keys.Control | Keys.Y, null, true);
            UIUtil.AssignShortcut(m_menuEditCut, Keys.Control | Keys.X, null, true);
            UIUtil.AssignShortcut(m_menuEditCopy, Keys.Control | Keys.C, null, true);
            UIUtil.AssignShortcut(m_menuEditPaste, Keys.Control | Keys.V, null, true);
            UIUtil.AssignShortcut(m_menuEditDelete, Keys.Delete, null, true);
            UIUtil.AssignShortcut(m_menuEditSelectAll, Keys.Control | Keys.A, null, true);
            UIUtil.AssignShortcut(m_menuEditFind, Keys.Control | Keys.F);

            UIUtil.ConfigureTbButton(m_tbFileSave, KPRes.Save, null, m_menuFileSave);
            UIUtil.ConfigureTbButton(m_tbEditCut, KPRes.Cut, null, m_menuEditCut);
            UIUtil.ConfigureTbButton(m_tbEditCopy, KPRes.Copy, null, m_menuEditCopy);
            UIUtil.ConfigureTbButton(m_tbEditPaste, KPRes.Paste, null, m_menuEditPaste);
            UIUtil.ConfigureTbButton(m_tbEditUndo, KPRes.Undo, null, m_menuEditUndo);
            UIUtil.ConfigureTbButton(m_tbEditRedo, KPRes.Redo, null, m_menuEditRedo);
            UIUtil.ConfigureTbButton(m_tbFind, null, KPRes.Find, m_menuEditFind);

            // Formatting keyboard shortcuts are implemented by CustomRichTextBoxEx
            UIUtil.ConfigureTbButton(m_tbFormatBold, KPRes.Bold, KPRes.Bold +
                                     " (" + UIUtil.GetKeysName(Keys.Control | Keys.B) + ")", null);
            UIUtil.ConfigureTbButton(m_tbFormatItalic, KPRes.Italic, KPRes.Italic +
                                     " (" + UIUtil.GetKeysName(Keys.Control | Keys.I) + ")", null);
            UIUtil.ConfigureTbButton(m_tbFormatUnderline, KPRes.Underline, KPRes.Underline +
                                     " (" + UIUtil.GetKeysName(Keys.Control | Keys.U) + ")", null);
            UIUtil.ConfigureTbButton(m_tbFormatStrikeout, KPRes.Strikeout, null);
            UIUtil.ConfigureTbButton(m_tbColorForeground, KPRes.TextColor, null);
            UIUtil.ConfigureTbButton(m_tbColorBackground, KPRes.BackgroundColor, null);
            UIUtil.ConfigureTbButton(m_tbAlignLeft, KPRes.AlignLeft, KPRes.AlignLeft +
                                     " (" + UIUtil.GetKeysName(Keys.Control | Keys.L) + ")", null);
            UIUtil.ConfigureTbButton(m_tbAlignCenter, KPRes.AlignCenter, KPRes.AlignCenter +
                                     " (" + UIUtil.GetKeysName(Keys.Control | Keys.E) + ")", null);
            UIUtil.ConfigureTbButton(m_tbAlignRight, KPRes.AlignRight, KPRes.AlignRight +
                                     " (" + UIUtil.GetKeysName(Keys.Control | Keys.R) + ")", null);

            string strSearchTr = ((WinUtil.IsAtLeastWindowsVista ?
                                   string.Empty : " ") + KPRes.Search);

            UIUtil.SetCueBanner(m_tbFind, strSearchTr);

            UIUtil.SetToolTip(m_tbFontCombo, KPRes.Font, true);
            UIUtil.SetToolTip(m_tbFontSizeCombo, KPRes.Size, true);

            UIUtil.EnableAutoCompletion(m_tbFontCombo, true);
            UIUtil.EnableAutoCompletion(m_tbFontSizeCombo, true);

            m_rtbText.WordWrap = Program.Config.UI.DataEditorWordWrap;
            m_ctxText.Attach(m_rtbText, this);
            m_tssStatusMain.Text = KPRes.Ready;

            InitFormattingToolBar();

            bool bSimpleText = true, bDefaultFont = true;

            if (m_bdc == BinaryDataClass.RichText)
            {
                try
                {
                    if (strData.Length > 0)
                    {
                        m_rtbText.Rtf = StrUtil.RtfFix(strData);
                        bDefaultFont  = false;
                    }
                    else
                    {
                        m_rtbText.Text = string.Empty;
                    }

                    bSimpleText = false;
                }
                catch (Exception) { }                // Show as simple text
            }

            if (bSimpleText)
            {
                m_rtbText.Text           = strData;
                m_rtbText.SimpleTextOnly = true;

                // CR is upgraded to CR+LF
                m_bNewLinesWin = (StrUtil.GetNewLineSeq(strData) != "\n");
            }
            else
            {
                m_menuViewFont.Text = KPRes.FontDefault + "...";
            }

            if (bDefaultFont && Program.Config.UI.DataEditorFont.OverrideUIDefault)
            {
                m_rtbText.SelectAll();
                m_rtbText.SelectionFont = Program.Config.UI.DataEditorFont.ToFont();
            }

            m_rtbText.Select(0, 0);
            --m_uBlockEvents;
            UpdateUIState(false, true);
        }
Exemple #20
0
        public static bool GetParamBool(List <string> vParams, int iIndex)
        {
            string str = GetParamString(vParams, iIndex, string.Empty);

            return(StrUtil.StringToBool(str));
        }
Exemple #21
0
        internal static void GenerateSerializers(CommandLineArgs cl)
        {
            StringBuilder sb = new StringBuilder();
            int           t  = 0;

            AppendLine(sb, "// This is a generated file!", ref t);
            AppendLine(sb, "// Do not edit manually, changes will be overwritten.", ref t);
            AppendLine(sb);
            AppendLine(sb, "using System;", ref t);
            AppendLine(sb, "using System.Collections.Generic;", ref t);
            AppendLine(sb, "using System.Xml;", ref t);
            AppendLine(sb, "using System.Diagnostics;", ref t);
            AppendLine(sb);
            AppendLine(sb, "using KeePassLib.Interfaces;", ref t);
            AppendLine(sb);
            AppendLine(sb, "namespace KeePass.Util.XmlSerialization", ref t);
            AppendLine(sb, "{", ref t, 0, 1);
            AppendLine(sb, "public sealed partial class XmlSerializerEx : IXmlSerializerEx", ref t);
            AppendLine(sb, "{", ref t, 0, 1);
            AppendLine(sb, "private static char[] m_vEnumSeps = new char[] {", ref t, 0, 1);
            AppendLine(sb, "' ', '\\t', '\\r', '\\n', '|', ',', ';', ':'", ref t);
            AppendLine(sb, "};", ref t, -1, 0);

            Dictionary <string, XmlsTypeInfo> d =
                new Dictionary <string, XmlsTypeInfo>();

            d[typeof(AppConfigEx).FullName]   = new XmlsTypeInfo(typeof(AppConfigEx));
            d[typeof(KPTranslation).FullName] = new XmlsTypeInfo(typeof(KPTranslation));

            bool bTypeCreated = true;

            while (bTypeCreated)
            {
                bTypeCreated = false;
                foreach (KeyValuePair <string, XmlsTypeInfo> kvp in d)
                {
                    if (!kvp.Value.HasInfo)
                    {
                        d[kvp.Key]   = GenerateSerializer(kvp.Value.Type, d, t);
                        bTypeCreated = true;
                        break;                         // Iterator might be invalid
                    }
                }
            }

            foreach (KeyValuePair <string, XmlsTypeInfo> kvp in d)
            {
                AppendLine(sb);
                sb.Append(kvp.Value.ReadCode);
            }

            AppendLine(sb, "}", ref t, -1, 0);
            AppendLine(sb, "}", ref t, -1, 0);
            Debug.Assert(t == 0);

            string strFileData = StrUtil.NormalizeNewLines(sb.ToString(), true);

            string strFile = cl["out"];

            if (!string.IsNullOrEmpty(strFile))
            {
                strFile = UrlUtil.MakeAbsolutePath(WinUtil.GetExecutable(), strFile);
                File.WriteAllText(strFile, strFileData, StrUtil.Utf8);
                MessageService.ShowInfo("Saved XmlSerializerEx to:", strFile);
            }
        }
Exemple #22
0
        public static void ParametersToDataGridView(DataGridView dg,
                                                    IEcasParameterized p, IEcasObject objDefaults)
        {
            if (dg == null)
            {
                throw new ArgumentNullException("dg");
            }
            if (p == null)
            {
                throw new ArgumentNullException("p");
            }
            if (p.Parameters == null)
            {
                throw new ArgumentException();
            }
            if (objDefaults == null)
            {
                throw new ArgumentNullException("objDefaults");
            }
            if (objDefaults.Parameters == null)
            {
                throw new ArgumentException();
            }

            dg.Rows.Clear();
            dg.Columns.Clear();

            Color clrFG = dg.DefaultCellStyle.ForeColor;
            Color clrBG = dg.DefaultCellStyle.BackColor;

            // https://sourceforge.net/p/keepass/bugs/1808/
            if (UIUtil.IsDarkColor(clrFG) == UIUtil.IsDarkColor(clrBG))
            {
                clrFG = (UIUtil.IsDarkColor(clrBG) ? Color.White : Color.Black);
            }

            Color clrValueBG = clrBG;

            if (UIUtil.IsDarkColor(clrBG))
            {
                clrValueBG = UIUtil.LightenColor(clrValueBG, 0.075);
            }
            else
            {
                clrValueBG = UIUtil.DarkenColor(clrValueBG, 0.075);
            }

            dg.ColumnHeadersVisible                = false;
            dg.RowHeadersVisible                   = false;
            dg.GridColor                           = clrBG;
            dg.BackgroundColor                     = clrBG;
            dg.DefaultCellStyle.ForeColor          = clrFG;
            dg.DefaultCellStyle.BackColor          = clrBG;
            dg.DefaultCellStyle.SelectionForeColor = clrFG;
            dg.DefaultCellStyle.SelectionBackColor = clrBG;
            dg.AllowDrop                           = false;
            dg.AllowUserToAddRows                  = false;
            dg.AllowUserToDeleteRows               = false;
            dg.AllowUserToOrderColumns             = false;
            dg.AllowUserToResizeColumns            = false;
            dg.AllowUserToResizeRows               = false;
            // dg.EditMode: see below
            dg.Tag = p;

            int nWidth = (dg.ClientSize.Width - UIUtil.GetVScrollBarWidth());

            dg.Columns.Add("Name", KPRes.FieldName);
            dg.Columns.Add("Value", KPRes.FieldValue);
            dg.Columns[0].Width = (nWidth / 2);
            dg.Columns[1].Width = (nWidth / 2);

            bool bUseDefaults = true;

            if (objDefaults.Type == null)
            {
                Debug.Assert(false);
            }                                                                 // Optimistic
            else if (p.Type == null)
            {
                Debug.Assert(false);
            }                                                            // Optimistic
            else if (!objDefaults.Type.Equals(p.Type))
            {
                bUseDefaults = false;
            }

            for (int i = 0; i < p.Parameters.Length; ++i)
            {
                EcasParameter ep = p.Parameters[i];

                dg.Rows.Add();
                DataGridViewRow            row = dg.Rows[dg.Rows.Count - 1];
                DataGridViewCellCollection cc  = row.Cells;

                Debug.Assert(cc.Count == 2);
                cc[0].Value    = ep.Name;
                cc[0].ReadOnly = true;

                string strParam = (bUseDefaults ? EcasUtil.GetParamString(
                                       objDefaults.Parameters, i) : string.Empty);

                DataGridViewCell c = null;
                switch (ep.Type)
                {
                case EcasValueType.String:
                    c       = new DataGridViewTextBoxCell();
                    c.Value = strParam;
                    break;

                case EcasValueType.Bool:
                    c       = new DataGridViewCheckBoxCell(false);
                    c.Value = StrUtil.StringToBool(strParam);
                    break;

                case EcasValueType.EnumStrings:
                    DataGridViewComboBoxCell cmb = new DataGridViewComboBoxCell();
                    cmb.Sorted       = false;
                    cmb.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton;
                    int iFound = -1;
                    for (int e = 0; e < ep.EnumValues.ItemCount; ++e)
                    {
                        EcasEnumItem eei = ep.EnumValues.Items[e];
                        cmb.Items.Add(eei.Name);
                        if (eei.ID.ToString() == strParam)
                        {
                            iFound = e;
                        }
                    }
                    if (iFound >= 0)
                    {
                        cmb.Value = ep.EnumValues.Items[iFound].Name;
                    }
                    else if (ep.EnumValues.ItemCount > 0)
                    {
                        cmb.Value = ep.EnumValues.Items[0].Name;
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                    c = cmb;
                    break;

                case EcasValueType.Int64:
                    c       = new DataGridViewTextBoxCell();
                    c.Value = FilterTypeI64(strParam);
                    break;

                case EcasValueType.UInt64:
                    c       = new DataGridViewTextBoxCell();
                    c.Value = FilterTypeU64(strParam);
                    break;

                default:
                    Debug.Assert(false);
                    break;
                }

                if (c != null)
                {
                    cc[1]          = c;
                    cc[1].ReadOnly = false;
                }
                else
                {
                    cc[1].ReadOnly = true;
                }

                cc[1].Style.ForeColor          = clrFG;
                cc[1].Style.BackColor          = clrValueBG;
                cc[1].Style.SelectionForeColor = clrFG;
                cc[1].Style.SelectionBackColor = clrValueBG;
            }

            // Perform postponed setting of EditMode (cannot set it earlier
            // due to a Mono bug on FreeBSD);
            // https://sourceforge.net/p/keepass/discussion/329220/thread/cb8270e2/
            dg.EditMode = DataGridViewEditMode.EditOnEnter;
        }
Exemple #23
0
        private static bool CompileAssembly(PlgxPluginInfo plgx,
                                            ref CompilerResults cr, string strCompilerVersion)
        {
            const string StrCoreRef = "System.Core";
            const string StrCoreDll = "System.Core.dll";
            bool         bHasCore = false, bCoreAdded = false;

            foreach (string strAsm in plgx.CompilerParameters.ReferencedAssemblies)
            {
                if (UrlUtil.AssemblyEquals(strAsm, StrCoreRef))
                {
                    bHasCore = true;
                    break;
                }
            }
            if ((strCompilerVersion != null) && strCompilerVersion.StartsWith(
                    "v", StrUtil.CaseIgnoreCmp))
            {
                ulong v = StrUtil.ParseVersion(strCompilerVersion.Substring(1));
                if (!bHasCore && (v >= 0x0003000500000000UL))
                {
                    plgx.CompilerParameters.ReferencedAssemblies.Add(StrCoreDll);
                    bCoreAdded = true;
                }
            }

            bool bResult = false;

            try
            {
                Dictionary <string, string> dictOpt = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(strCompilerVersion))
                {
                    dictOpt.Add("CompilerVersion", strCompilerVersion);
                }

                // Windows 98 only supports the parameterless constructor;
                // check must be separate from the instantiation method
                if (WinUtil.IsWindows9x)
                {
                    dictOpt.Clear();
                }

                CodeDomProvider cdp = null;
                if (plgx.ProjectType == PlgxProjectType.CSharp)
                {
                    cdp = ((dictOpt.Count == 0) ? new CSharpCodeProvider() :
                           CreateCscProvider(dictOpt));
                }
                // else if(plgx.ProjectType == PlgxProjectType.VisualBasic)
                //	cdp = ((dictOpt.Count == 0) ? new VBCodeProvider() :
                //		new VBCodeProvider(dictOpt));
                else
                {
                    throw new InvalidOperationException();
                }

                cr = cdp.CompileAssemblyFromFile(plgx.CompilerParameters,
                                                 plgx.SourceFiles.ToArray());

                bResult = ((cr.Errors == null) || !cr.Errors.HasErrors);
            }
            catch (Exception) { }

            if (bCoreAdded)
            {
                plgx.CompilerParameters.ReferencedAssemblies.Remove(StrCoreDll);
            }

            // cr = null; // Keep previous results for output
            return(bResult);
        }
Exemple #24
0
        public static string ParametersToString(IEcasObject ecasObj,
                                                EcasParameter[] vParamInfo)
        {
            if (ecasObj == null)
            {
                throw new ArgumentNullException("ecasObj");
            }
            if (ecasObj.Parameters == null)
            {
                throw new ArgumentException();
            }

            bool bParamInfoValid = true;

            if ((vParamInfo == null) || (ecasObj.Parameters.Count > vParamInfo.Length))
            {
                Debug.Assert(false);
                bParamInfoValid = false;
            }

            StringBuilder sb = new StringBuilder();

            EcasCondition eCond = (ecasObj as EcasCondition);

            if (eCond != null)
            {
                if (eCond.Negate)
                {
                    sb.Append(KPRes.Not);
                }
            }

            for (int i = 0; i < ecasObj.Parameters.Count; ++i)
            {
                string strParam = ecasObj.Parameters[i];
                string strAppend;

                if (bParamInfoValid)
                {
                    EcasValueType t = vParamInfo[i].Type;
                    if (t == EcasValueType.String)
                    {
                        strAppend = strParam;
                    }
                    else if (t == EcasValueType.Bool)
                    {
                        strAppend = (StrUtil.StringToBool(strParam) ? KPRes.Yes : KPRes.No);
                    }
                    else if (t == EcasValueType.EnumStrings)
                    {
                        uint uEnumID;
                        if (uint.TryParse(strParam, out uEnumID) == false)
                        {
                            Debug.Assert(false);
                        }
                        EcasEnum ee = vParamInfo[i].EnumValues;
                        if (ee != null)
                        {
                            strAppend = ee.GetItemString(uEnumID, string.Empty);
                        }
                        else
                        {
                            Debug.Assert(false); strAppend = strParam;
                        }
                    }
                    else if (t == EcasValueType.Int64)
                    {
                        strAppend = FilterTypeI64(strParam);
                    }
                    else if (t == EcasValueType.UInt64)
                    {
                        strAppend = FilterTypeU64(strParam);
                    }
                    else
                    {
                        Debug.Assert(false); strAppend = strParam;
                    }
                }
                else
                {
                    strAppend = strParam;
                }

                if (string.IsNullOrEmpty(strAppend))
                {
                    continue;
                }
                string strAppTrimmed = strAppend.Trim();
                if (strAppTrimmed.Length == 0)
                {
                    continue;
                }
                if (sb.Length > 0)
                {
                    sb.Append(", ");
                }
                sb.Append(strAppTrimmed);
            }

            return(sb.ToString());
        }
Exemple #25
0
        private void UpdateHtmlDocument()
        {
            if (m_bBlockPreviewRefresh)
            {
                return;
            }

            m_bBlockPreviewRefresh = true;

            PwGroup pgDataSource = m_pgDataSource.CloneDeep();

            int    nSortEntries     = m_cmbSortEntries.SelectedIndex;
            string strSortFieldName = null;

            if (nSortEntries == 0)
            {
            }                                     // No sort
            else if (nSortEntries == 1)
            {
                strSortFieldName = PwDefs.TitleField;
            }
            else if (nSortEntries == 2)
            {
                strSortFieldName = PwDefs.UserNameField;
            }
            else if (nSortEntries == 3)
            {
                strSortFieldName = PwDefs.PasswordField;
            }
            else if (nSortEntries == 4)
            {
                strSortFieldName = PwDefs.UrlField;
            }
            else if (nSortEntries == 5)
            {
                strSortFieldName = PwDefs.NotesField;
            }
            else
            {
                Debug.Assert(false);
            }
            if (strSortFieldName != null)
            {
                SortGroupEntriesRecursive(pgDataSource, strSortFieldName);
            }

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
            sb.AppendLine("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");

            sb.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
            sb.AppendLine("<head>");
            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
            sb.Append("<title>");
            sb.Append(StrUtil.StringToHtml(pgDataSource.Name));
            sb.AppendLine("</title>");
            sb.AppendLine("<meta http-equiv=\"expires\" content=\"0\" />");
            sb.AppendLine("<meta http-equiv=\"cache-control\" content=\"no-cache\" />");
            sb.AppendLine("<meta http-equiv=\"pragma\" content=\"no-cache\" />");

            sb.AppendLine("<style type=\"text/css\"><!--");

            sb.AppendLine("body, p, div, h1, h2, h3, h4, h5, h6, ol, ul, li, td, th, dd, dt, a {");
            sb.AppendLine("\tfont-family: Tahoma, MS Sans Serif, Sans Serif, Verdana, sans-serif;");
            sb.AppendLine("\tfont-size: 10pt;");
            sb.AppendLine("}");
            sb.AppendLine("span.fserif {");
            sb.AppendLine("\tfont-family: Times New Roman, serif;");
            sb.AppendLine("}");
            sb.AppendLine("h1 { font-size: 2em; }");
            sb.AppendLine("h2 { font-size: 1.5em; }");
            sb.AppendLine("h3 { font-size: 1.2em; }");
            sb.AppendLine("h4 { font-size: 1em; }");
            sb.AppendLine("h5 { font-size: 0.89em; }");
            sb.AppendLine("h6 { font-size: 0.6em; }");
            sb.AppendLine("td {");
            sb.AppendLine("\ttext-align: left;");
            sb.AppendLine("\tvertical-align: top;");
            sb.AppendLine("}");
            sb.AppendLine("a:visited {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("}");
            sb.AppendLine("a:active {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("}");
            sb.AppendLine("a:link {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("}");
            sb.AppendLine("a:hover {");
            sb.AppendLine("\ttext-decoration: underline;");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("}");

            sb.AppendLine("--></style>");

            sb.AppendLine("</head><body>");

            sb.AppendLine("<h2>" + StrUtil.StringToHtml(pgDataSource.Name) + "</h2>");

            GroupHandler gh = null;
            EntryHandler eh = null;

            bool bGroup = m_cbGroups.Checked;
            bool bTitle = m_cbTitle.Checked, bUserName = m_cbUser.Checked;
            bool bPassword = m_cbPassword.Checked, bURL = m_cbUrl.Checked;
            bool bNotes = m_cbNotes.Checked;
            bool bCreation = m_cbCreation.Checked, bLastMod = m_cbLastMod.Checked;
            // bool bLastAcc = m_cbLastAccess.Checked;
            bool bExpire        = m_cbExpire.Checked;
            bool bAutoType      = m_cbAutoType.Checked;
            bool bTags          = m_cbTags.Checked;
            bool bCustomStrings = m_cbCustomStrings.Checked;

            bool bMonoPasswords = m_cbMonospaceForPasswords.Checked;

            if (m_rbMonospace.Checked)
            {
                bMonoPasswords = false;                                   // Monospaced anyway
            }
            bool bSmallMono = m_cbSmallMono.Checked;

            string strFontInit = string.Empty, strFontExit = string.Empty;

            if (m_rbSerif.Checked)
            {
                strFontInit = "<span class=\"fserif\">";
                strFontExit = "</span>";
            }
            else if (m_rbSansSerif.Checked)
            {
                strFontInit = string.Empty;
                strFontExit = string.Empty;
            }
            else if (m_rbMonospace.Checked)
            {
                strFontInit = (bSmallMono ? "<code><small>" : "<code>");
                strFontExit = (bSmallMono ? "</small></code>" : "</code>");
            }
            else
            {
                Debug.Assert(false);
            }

            string strTableInit = "<table width=\"100%\">";

            if (m_rbTabular.Checked)
            {
                // int nFieldCount = (bTitle ? 1 : 0) + (bUserName ? 1 : 0);
                // nFieldCount += (bPassword ? 1 : 0) + (bURL ? 1 : 0) + (bNotes ? 1 : 0);

                string strCellPre  = "<td>" + strFontInit;
                string strCellPost = strFontExit + "</td>";

                string strHTdInit = "<td><b>";
                string strHTdExit = "</b></td>";

                StringBuilder sbH = new StringBuilder();
                sbH.AppendLine();
                sbH.Append("<tr>");
                if (bGroup)
                {
                    sbH.AppendLine(strHTdInit + StrUtil.StringToHtml(KPRes.Group) + strHTdExit);
                }
                if (bTitle)
                {
                    sbH.AppendLine(strHTdInit + StrUtil.StringToHtml(KPRes.Title) + strHTdExit);
                }
                if (bUserName)
                {
                    sbH.AppendLine(strHTdInit + StrUtil.StringToHtml(KPRes.UserName) + strHTdExit);
                }
                if (bPassword)
                {
                    sbH.AppendLine(strHTdInit + StrUtil.StringToHtml(KPRes.Password) + strHTdExit);
                }
                if (bURL)
                {
                    sbH.AppendLine(strHTdInit + StrUtil.StringToHtml(KPRes.Url) + strHTdExit);
                }
                if (bNotes)
                {
                    sbH.AppendLine(strHTdInit + StrUtil.StringToHtml(KPRes.Notes) + strHTdExit);
                }
                if (bCreation)
                {
                    sbH.AppendLine(strHTdInit + StrUtil.StringToHtml(KPRes.CreationTime) + strHTdExit);
                }
                // if(bLastAcc) sbH.AppendLine(strHTdInit + StrUtil.StringToHtml(KPRes.LastAccessTime) + strHTdExit);
                if (bLastMod)
                {
                    sbH.AppendLine(strHTdInit + StrUtil.StringToHtml(KPRes.LastModificationTime) + strHTdExit);
                }
                if (bExpire)
                {
                    sbH.AppendLine(strHTdInit + StrUtil.StringToHtml(KPRes.ExpiryTime) + strHTdExit);
                }
                if (bTags)
                {
                    sbH.AppendLine(strHTdInit + StrUtil.StringToHtml(KPRes.Tags) + strHTdExit);
                }
                sbH.Append("</tr>");                 // No terminating \r\n

                strTableInit += sbH.ToString();
                sb.AppendLine(strTableInit);

                eh = delegate(PwEntry pe)
                {
                    sb.AppendLine("<tr>");

                    WriteTabularIf(bGroup, sb, StrUtil.StringToHtml(pe.ParentGroup.Name), strCellPre, strCellPost);
                    WriteTabularIf(bTitle, sb, pe, PwDefs.TitleField, strCellPre, strCellPost);
                    WriteTabularIf(bUserName, sb, pe, PwDefs.UserNameField, strCellPre, strCellPost);

                    if (bPassword)
                    {
                        if (bMonoPasswords)
                        {
                            sb.Append(bSmallMono ? "<td><code><small>" : "<td><code>");
                        }
                        else
                        {
                            sb.Append(strCellPre);
                        }

                        string strInner = StrUtil.StringToHtml(pe.Strings.ReadSafe(PwDefs.PasswordField));
                        if (strInner.Length > 0)
                        {
                            sb.Append(strInner);
                        }
                        else
                        {
                            sb.Append(@"&nbsp;");
                        }

                        if (bMonoPasswords)
                        {
                            sb.AppendLine(bSmallMono ? "</small></code></td>" : "</code></td>");
                        }
                        else
                        {
                            sb.AppendLine(strCellPost);
                        }
                    }

                    // WriteTabularIf(bURL, sb, pe, PwDefs.UrlField, strCellPre, strCellPost);
                    WriteTabularIf(bURL, sb, MakeUrlLink(pe.Strings.ReadSafe(PwDefs.UrlField),
                                                         strFontInit, strFontExit), strCellPre, strCellPost);

                    WriteTabularIf(bNotes, sb, pe, PwDefs.NotesField, strCellPre, strCellPost);

                    WriteTabularIf(bCreation, sb, TimeUtil.ToDisplayString(
                                       pe.CreationTime), strCellPre, strCellPost);
                    // WriteTabularIf(bLastAcc, sb, TimeUtil.ToDisplayString(
                    //	pe.LastAccessTime), strCellPre, strCellPost);
                    WriteTabularIf(bLastMod, sb, TimeUtil.ToDisplayString(
                                       pe.LastModificationTime), strCellPre, strCellPost);
                    WriteTabularIf(bExpire, sb, (pe.Expires ? TimeUtil.ToDisplayString(
                                                     pe.ExpiryTime) : KPRes.NeverExpires), strCellPre, strCellPost);

                    WriteTabularIf(bTags, sb, StrUtil.TagsToString(pe.Tags, true),
                                   strCellPre, strCellPost);

                    sb.AppendLine("</tr>");
                    return(true);
                };
            }
            else if (m_rbDetails.Checked)
            {
                sb.AppendLine(strTableInit);

                if (pgDataSource.Entries.UCount == 0)
                {
                    sb.AppendLine(@"<tr><td>&nbsp;</td></tr>");
                }

                eh = delegate(PwEntry pe)
                {
                    if (bGroup)
                    {
                        WriteDetailsLine(sb, KPRes.Group, pe.ParentGroup.Name, bSmallMono, bMonoPasswords, strFontInit, strFontExit);
                    }
                    if (bTitle)
                    {
                        WriteDetailsLine(sb, KPRes.Title, pe.Strings.ReadSafe(PwDefs.TitleField), bSmallMono, bMonoPasswords, strFontInit + "<b>", "</b>" + strFontExit);
                    }
                    if (bUserName)
                    {
                        WriteDetailsLine(sb, KPRes.UserName, pe.Strings.ReadSafe(PwDefs.UserNameField), bSmallMono, bMonoPasswords, strFontInit, strFontExit);
                    }
                    if (bPassword)
                    {
                        WriteDetailsLine(sb, KPRes.Password, pe.Strings.ReadSafe(PwDefs.PasswordField), bSmallMono, bMonoPasswords, strFontInit, strFontExit);
                    }
                    if (bURL)
                    {
                        WriteDetailsLine(sb, KPRes.Url, pe.Strings.ReadSafe(PwDefs.UrlField), bSmallMono, bMonoPasswords, strFontInit, strFontExit);
                    }
                    if (bNotes)
                    {
                        WriteDetailsLine(sb, KPRes.Notes, pe.Strings.ReadSafe(PwDefs.NotesField), bSmallMono, bMonoPasswords, strFontInit, strFontExit);
                    }
                    if (bCreation)
                    {
                        WriteDetailsLine(sb, KPRes.CreationTime, TimeUtil.ToDisplayString(
                                             pe.CreationTime), bSmallMono, bMonoPasswords, strFontInit, strFontExit);
                    }
                    // if(bLastAcc) WriteDetailsLine(sb, KPRes.LastAccessTime, TimeUtil.ToDisplayString(
                    //	pe.LastAccessTime), bSmallMono, bMonoPasswords, strFontInit, strFontExit);
                    if (bLastMod)
                    {
                        WriteDetailsLine(sb, KPRes.LastModificationTime, TimeUtil.ToDisplayString(
                                             pe.LastModificationTime), bSmallMono, bMonoPasswords, strFontInit, strFontExit);
                    }
                    if (bExpire)
                    {
                        WriteDetailsLine(sb, KPRes.ExpiryTime, (pe.Expires ? TimeUtil.ToDisplayString(
                                                                    pe.ExpiryTime) : KPRes.NeverExpires), bSmallMono, bMonoPasswords, strFontInit, strFontExit);
                    }

                    if (bAutoType)
                    {
                        foreach (AutoTypeAssociation a in pe.AutoType.Associations)
                        {
                            WriteDetailsLine(sb, KPRes.AutoType, a.WindowName +
                                             ": " + a.Sequence, bSmallMono, bMonoPasswords,
                                             strFontInit, strFontExit);
                        }
                    }

                    if (bTags)
                    {
                        WriteDetailsLine(sb, KPRes.Tags, StrUtil.TagsToString(
                                             pe.Tags, true), bSmallMono, bMonoPasswords, strFontInit,
                                         strFontExit);
                    }

                    foreach (KeyValuePair <string, ProtectedString> kvp in pe.Strings)
                    {
                        if (bCustomStrings && !PwDefs.IsStandardField(kvp.Key))
                        {
                            WriteDetailsLine(sb, kvp, bSmallMono, bMonoPasswords,
                                             strFontInit, strFontExit);
                        }
                    }

                    sb.AppendLine(@"<tr><td>&nbsp;</td></tr>");

                    return(true);
                };
            }
            else
            {
                Debug.Assert(false);
            }

            gh = delegate(PwGroup pg)
            {
                if (pg.Entries.UCount == 0)
                {
                    return(true);
                }

                sb.Append("</table><br /><hr /><h3>");
                sb.Append(StrUtil.StringToHtml(pg.GetFullPath(" - ", false)));
                sb.AppendLine("</h3>");
                sb.AppendLine(strTableInit);

                return(true);
            };

            pgDataSource.TraverseTree(TraversalMethod.PreOrder, gh, eh);

            if (m_rbTabular.Checked)
            {
                sb.AppendLine("</table>");
            }
            else if (m_rbDetails.Checked)
            {
                sb.AppendLine("</table><br />");
            }

            sb.AppendLine("</body></html>");

            try { UIUtil.SetWebBrowserDocument(m_wbMain, sb.ToString()); }
            catch (Exception) { }            // Throws in Mono 2.0+
            try { m_wbMain.AllowNavigation = false; }
            catch (Exception) { Debug.Assert(false); }

            m_bBlockPreviewRefresh = false;
        }
Exemple #26
0
        public static bool AutoOpenEntry(Activity activity, AutoExecItem item, bool bManual,
                                         ActivityLaunchMode launchMode)
        {
            string           str;
            PwEntry          pe       = item.Entry;
            SprContext       ctxNoEsc = new SprContext(pe, item.Database, SprCompileFlags.All);
            IOConnectionInfo ioc;

            if (!TryGetDatabaseIoc(item, out ioc))
            {
                return(false);
            }

            var ob = GetBoolEx(pe, "SkipIfNotExists", ctxNoEsc);

            if (!ob.HasValue) // Backw. compat.
            {
                ob = GetBoolEx(pe, "Skip if not exists", ctxNoEsc);
            }
            if (ob.HasValue && ob.Value)
            {
                if (!CheckFileExsts(ioc))
                {
                    return(false);
                }
            }

            CompositeKey ck = new CompositeKey();

            if (GetString(pe, PwDefs.PasswordField, ctxNoEsc, false, out str))
            {
                ck.AddUserKey(new KcpPassword(str));
            }

            if (GetString(pe, PwDefs.UserNameField, ctxNoEsc, false, out str))
            {
                string           strAbs = str;
                IOConnectionInfo iocKey = IOConnectionInfo.FromPath(strAbs);
                if (iocKey.IsLocalFile() && !UrlUtil.IsAbsolutePath(strAbs))
                {
                    //local relative paths not supported on Android
                    return(false);
                }


                ob = GetBoolEx(pe, "SkipIfKeyFileNotExists", ctxNoEsc);
                if (ob.HasValue && ob.Value)
                {
                    IOConnectionInfo iocKeyAbs = IOConnectionInfo.FromPath(strAbs);
                    if (!CheckFileExsts(iocKeyAbs))
                    {
                        return(false);
                    }
                }

                try { ck.AddUserKey(new KcpKeyFile(strAbs)); }
                catch (InvalidOperationException)
                {
                    Toast.MakeText(LocaleManager.LocalizedAppContext, Resource.String.error_adding_keyfile, ToastLength.Long).Show();
                    return(false);
                }
                catch (Exception) { throw; }
            }
            else // Try getting key file from attachments
            {
                ProtectedBinary pBin = pe.Binaries.Get("KeyFile.bin");
                if (pBin != null)
                {
                    ck.AddUserKey(new KcpKeyFile(IOConnectionInfo.FromPath(
                                                     StrUtil.DataToDataUri(pBin.ReadData(), null))));
                }
            }

            GetString(pe, "Focus", ctxNoEsc, true, out str);
            bool bRestoreFocus = str.Equals("Restore", StrUtil.CaseIgnoreCmp);

            PasswordActivity.Launch(activity, ioc, ck, launchMode, !
                                    bRestoreFocus);

            App.Kp2a.RegisterChildDatabase(ioc);

            return(true);
        }
        private KdbContext ReadXmlElement(KdbContext ctx, XmlReader xr)
        {
            Debug.Assert(xr.NodeType == XmlNodeType.Element);

            switch (ctx)
            {
            case KdbContext.Null:
                if (xr.Name == ElemDocNode)
                {
                    return(SwitchContext(ctx, KdbContext.KeePassFile, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.KeePassFile:
                if (xr.Name == ElemMeta)
                {
                    return(SwitchContext(ctx, KdbContext.Meta, xr));
                }
                else if (xr.Name == ElemRoot)
                {
                    return(SwitchContext(ctx, KdbContext.Root, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Meta:
                if (xr.Name == ElemGenerator)
                {
                    ReadString(xr);                             // Ignore
                }
                else if (xr.Name == ElemHeaderHash)
                {
                    // The header hash is typically only stored in
                    // KDBX <= 3.1 files, not in KDBX >= 4 files
                    // (here, the header is verified via a HMAC),
                    // but we also support it for KDBX >= 4 files
                    // (i.e. if it's present, we check it)

                    string strHash = ReadString(xr);
                    if (!string.IsNullOrEmpty(strHash) && (m_pbHashOfHeader != null) &&
                        !m_bRepairMode)
                    {
                        Debug.Assert(m_uFileVersion < FileVersion32_4);

                        byte[] pbHash = Convert.FromBase64String(strHash);
                        if (!MemUtil.ArraysEqual(pbHash, m_pbHashOfHeader))
                        {
                            throw new InvalidDataException(KLRes.FileCorrupted);
                        }
                    }
                }
                else if (xr.Name == ElemSettingsChanged)
                {
                    m_pwDatabase.SettingsChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemDbName)
                {
                    m_pwDatabase.Name = ReadString(xr);
                }
                else if (xr.Name == ElemDbNameChanged)
                {
                    m_pwDatabase.NameChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemDbDesc)
                {
                    m_pwDatabase.Description = ReadString(xr);
                }
                else if (xr.Name == ElemDbDescChanged)
                {
                    m_pwDatabase.DescriptionChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemDbDefaultUser)
                {
                    m_pwDatabase.DefaultUserName = ReadString(xr);
                }
                else if (xr.Name == ElemDbDefaultUserChanged)
                {
                    m_pwDatabase.DefaultUserNameChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemDbMntncHistoryDays)
                {
                    m_pwDatabase.MaintenanceHistoryDays = ReadUInt(xr, 365);
                }
                else if (xr.Name == ElemDbColor)
                {
                    string strColor = ReadString(xr);
                    if (!string.IsNullOrEmpty(strColor))
                    {
                        m_pwDatabase.Color = ColorTranslator.FromHtml(strColor);
                    }
                }
                else if (xr.Name == ElemDbKeyChanged)
                {
                    m_pwDatabase.MasterKeyChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemDbKeyChangeRec)
                {
                    m_pwDatabase.MasterKeyChangeRec = ReadLong(xr, -1);
                }
                else if (xr.Name == ElemDbKeyChangeForce)
                {
                    m_pwDatabase.MasterKeyChangeForce = ReadLong(xr, -1);
                }
                else if (xr.Name == ElemDbKeyChangeForceOnce)
                {
                    m_pwDatabase.MasterKeyChangeForceOnce = ReadBool(xr, false);
                }
                else if (xr.Name == ElemMemoryProt)
                {
                    return(SwitchContext(ctx, KdbContext.MemoryProtection, xr));
                }
                else if (xr.Name == ElemCustomIcons)
                {
                    return(SwitchContext(ctx, KdbContext.CustomIcons, xr));
                }
                else if (xr.Name == ElemRecycleBinEnabled)
                {
                    m_pwDatabase.RecycleBinEnabled = ReadBool(xr, true);
                }
                else if (xr.Name == ElemRecycleBinUuid)
                {
                    m_pwDatabase.RecycleBinUuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemRecycleBinChanged)
                {
                    m_pwDatabase.RecycleBinChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemEntryTemplatesGroup)
                {
                    m_pwDatabase.EntryTemplatesGroup = ReadUuid(xr);
                }
                else if (xr.Name == ElemEntryTemplatesGroupChanged)
                {
                    m_pwDatabase.EntryTemplatesGroupChanged = ReadTime(xr);
                }
                else if (xr.Name == ElemHistoryMaxItems)
                {
                    m_pwDatabase.HistoryMaxItems = ReadInt(xr, -1);
                }
                else if (xr.Name == ElemHistoryMaxSize)
                {
                    m_pwDatabase.HistoryMaxSize = ReadLong(xr, -1);
                }
                else if (xr.Name == ElemLastSelectedGroup)
                {
                    m_pwDatabase.LastSelectedGroup = ReadUuid(xr);
                }
                else if (xr.Name == ElemLastTopVisibleGroup)
                {
                    m_pwDatabase.LastTopVisibleGroup = ReadUuid(xr);
                }
                else if (xr.Name == ElemBinaries)
                {
                    return(SwitchContext(ctx, KdbContext.Binaries, xr));
                }
                else if (xr.Name == ElemCustomData)
                {
                    return(SwitchContext(ctx, KdbContext.CustomData, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.MemoryProtection:
                if (xr.Name == ElemProtTitle)
                {
                    m_pwDatabase.MemoryProtection.ProtectTitle = ReadBool(xr, false);
                }
                else if (xr.Name == ElemProtUserName)
                {
                    m_pwDatabase.MemoryProtection.ProtectUserName = ReadBool(xr, false);
                }
                else if (xr.Name == ElemProtPassword)
                {
                    m_pwDatabase.MemoryProtection.ProtectPassword = ReadBool(xr, true);
                }
                else if (xr.Name == ElemProtUrl)
                {
                    m_pwDatabase.MemoryProtection.ProtectUrl = ReadBool(xr, false);
                }
                else if (xr.Name == ElemProtNotes)
                {
                    m_pwDatabase.MemoryProtection.ProtectNotes = ReadBool(xr, false);
                }
                // else if(xr.Name == ElemProtAutoHide)
                //	m_pwDatabase.MemoryProtection.AutoEnableVisualHiding = ReadBool(xr, true);
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.CustomIcons:
                if (xr.Name == ElemCustomIconItem)
                {
                    return(SwitchContext(ctx, KdbContext.CustomIcon, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.CustomIcon:
                if (xr.Name == ElemCustomIconItemID)
                {
                    m_uuidCustomIconID = ReadUuid(xr);
                }
                else if (xr.Name == ElemCustomIconItemData)
                {
                    string strData = ReadString(xr);
                    if (!string.IsNullOrEmpty(strData))
                    {
                        m_pbCustomIconData = Convert.FromBase64String(strData);
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Binaries:
                if (xr.Name == ElemBinary)
                {
                    if (xr.MoveToAttribute(AttrId))
                    {
                        string          strKey = xr.Value;
                        ProtectedBinary pbData = ReadProtectedBinary(xr);

                        int iKey;
                        if (!StrUtil.TryParseIntInvariant(strKey, out iKey))
                        {
                            throw new FormatException();
                        }
                        if (iKey < 0)
                        {
                            throw new FormatException();
                        }

                        Debug.Assert(m_pbsBinaries.Get(iKey) == null);
                        Debug.Assert(m_pbsBinaries.Find(pbData) < 0);
                        m_pbsBinaries.Set(iKey, pbData);
                    }
                    else
                    {
                        ReadUnknown(xr);
                    }
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.CustomData:
                if (xr.Name == ElemStringDictExItem)
                {
                    return(SwitchContext(ctx, KdbContext.CustomDataItem, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.CustomDataItem:
                if (xr.Name == ElemKey)
                {
                    m_strCustomDataKey = ReadString(xr);
                }
                else if (xr.Name == ElemValue)
                {
                    m_strCustomDataValue = ReadString(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Root:
                if (xr.Name == ElemGroup)
                {
                    Debug.Assert(m_ctxGroups.Count == 0);
                    if (m_ctxGroups.Count != 0)
                    {
                        throw new FormatException();
                    }

                    m_pwDatabase.RootGroup = new PwGroup(false, false);
                    m_ctxGroups.Push(m_pwDatabase.RootGroup);
                    m_ctxGroup = m_ctxGroups.Peek();

                    return(SwitchContext(ctx, KdbContext.Group, xr));
                }
                else if (xr.Name == ElemDeletedObjects)
                {
                    return(SwitchContext(ctx, KdbContext.RootDeletedObjects, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Group:
                if (xr.Name == ElemUuid)
                {
                    m_ctxGroup.Uuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemName)
                {
                    m_ctxGroup.Name = ReadString(xr);
                }
                else if (xr.Name == ElemNotes)
                {
                    m_ctxGroup.Notes = ReadString(xr);
                }
                else if (xr.Name == ElemIcon)
                {
                    m_ctxGroup.IconId = ReadIconId(xr, PwIcon.Folder);
                }
                else if (xr.Name == ElemCustomIconID)
                {
                    m_ctxGroup.CustomIconUuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemTimes)
                {
                    return(SwitchContext(ctx, KdbContext.GroupTimes, xr));
                }
                else if (xr.Name == ElemIsExpanded)
                {
                    m_ctxGroup.IsExpanded = ReadBool(xr, true);
                }
                else if (xr.Name == ElemGroupDefaultAutoTypeSeq)
                {
                    m_ctxGroup.DefaultAutoTypeSequence = ReadString(xr);
                }
                else if (xr.Name == ElemEnableAutoType)
                {
                    m_ctxGroup.EnableAutoType = StrUtil.StringToBoolEx(ReadString(xr));
                }
                else if (xr.Name == ElemEnableSearching)
                {
                    m_ctxGroup.EnableSearching = StrUtil.StringToBoolEx(ReadString(xr));
                }
                else if (xr.Name == ElemLastTopVisibleEntry)
                {
                    m_ctxGroup.LastTopVisibleEntry = ReadUuid(xr);
                }
                else if (xr.Name == ElemCustomData)
                {
                    return(SwitchContext(ctx, KdbContext.GroupCustomData, xr));
                }
                else if (xr.Name == ElemGroup)
                {
                    m_ctxGroup = new PwGroup(false, false);
                    m_ctxGroups.Peek().AddGroup(m_ctxGroup, true);

                    m_ctxGroups.Push(m_ctxGroup);

                    return(SwitchContext(ctx, KdbContext.Group, xr));
                }
                else if (xr.Name == ElemEntry)
                {
                    m_ctxEntry = new PwEntry(false, false);
                    m_ctxGroup.AddEntry(m_ctxEntry, true);

                    m_bEntryInHistory = false;
                    return(SwitchContext(ctx, KdbContext.Entry, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.GroupCustomData:
                if (xr.Name == ElemStringDictExItem)
                {
                    return(SwitchContext(ctx, KdbContext.GroupCustomDataItem, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.GroupCustomDataItem:
                if (xr.Name == ElemKey)
                {
                    m_strGroupCustomDataKey = ReadString(xr);
                }
                else if (xr.Name == ElemValue)
                {
                    m_strGroupCustomDataValue = ReadString(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.Entry:
                if (xr.Name == ElemUuid)
                {
                    m_ctxEntry.Uuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemIcon)
                {
                    m_ctxEntry.IconId = ReadIconId(xr, PwIcon.Key);
                }
                else if (xr.Name == ElemCustomIconID)
                {
                    m_ctxEntry.CustomIconUuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemFgColor)
                {
                    string strColor = ReadString(xr);
                    if (!string.IsNullOrEmpty(strColor))
                    {
                        m_ctxEntry.ForegroundColor = ColorTranslator.FromHtml(strColor);
                    }
                }
                else if (xr.Name == ElemBgColor)
                {
                    string strColor = ReadString(xr);
                    if (!string.IsNullOrEmpty(strColor))
                    {
                        m_ctxEntry.BackgroundColor = ColorTranslator.FromHtml(strColor);
                    }
                }
                else if (xr.Name == ElemOverrideUrl)
                {
                    m_ctxEntry.OverrideUrl = ReadString(xr);
                }
                else if (xr.Name == ElemTags)
                {
                    m_ctxEntry.Tags = StrUtil.StringToTags(ReadString(xr));
                }
                else if (xr.Name == ElemTimes)
                {
                    return(SwitchContext(ctx, KdbContext.EntryTimes, xr));
                }
                else if (xr.Name == ElemString)
                {
                    return(SwitchContext(ctx, KdbContext.EntryString, xr));
                }
                else if (xr.Name == ElemBinary)
                {
                    return(SwitchContext(ctx, KdbContext.EntryBinary, xr));
                }
                else if (xr.Name == ElemAutoType)
                {
                    return(SwitchContext(ctx, KdbContext.EntryAutoType, xr));
                }
                else if (xr.Name == ElemCustomData)
                {
                    return(SwitchContext(ctx, KdbContext.EntryCustomData, xr));
                }
                else if (xr.Name == ElemHistory)
                {
                    Debug.Assert(m_bEntryInHistory == false);

                    if (m_bEntryInHistory == false)
                    {
                        m_ctxHistoryBase = m_ctxEntry;
                        return(SwitchContext(ctx, KdbContext.EntryHistory, xr));
                    }
                    else
                    {
                        ReadUnknown(xr);
                    }
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.GroupTimes:
            case KdbContext.EntryTimes:
                ITimeLogger tl = ((ctx == KdbContext.GroupTimes) ?
                                  (ITimeLogger)m_ctxGroup : (ITimeLogger)m_ctxEntry);
                Debug.Assert(tl != null);

                if (xr.Name == ElemCreationTime)
                {
                    tl.CreationTime = ReadTime(xr);
                }
                else if (xr.Name == ElemLastModTime)
                {
                    tl.LastModificationTime = ReadTime(xr);
                }
                else if (xr.Name == ElemLastAccessTime)
                {
                    tl.LastAccessTime = ReadTime(xr);
                }
                else if (xr.Name == ElemExpiryTime)
                {
                    tl.ExpiryTime = ReadTime(xr);
                }
                else if (xr.Name == ElemExpires)
                {
                    tl.Expires = ReadBool(xr, false);
                }
                else if (xr.Name == ElemUsageCount)
                {
                    tl.UsageCount = ReadULong(xr, 0);
                }
                else if (xr.Name == ElemLocationChanged)
                {
                    tl.LocationChanged = ReadTime(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryString:
                if (xr.Name == ElemKey)
                {
                    m_ctxStringName = ReadString(xr);
                }
                else if (xr.Name == ElemValue)
                {
                    m_ctxStringValue = ReadProtectedString(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryBinary:
                if (xr.Name == ElemKey)
                {
                    m_ctxBinaryName = ReadString(xr);
                }
                else if (xr.Name == ElemValue)
                {
                    m_ctxBinaryValue = ReadProtectedBinary(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryAutoType:
                if (xr.Name == ElemAutoTypeEnabled)
                {
                    m_ctxEntry.AutoType.Enabled = ReadBool(xr, true);
                }
                else if (xr.Name == ElemAutoTypeObfuscation)
                {
                    m_ctxEntry.AutoType.ObfuscationOptions =
                        (AutoTypeObfuscationOptions)ReadInt(xr, 0);
                }
                else if (xr.Name == ElemAutoTypeDefaultSeq)
                {
                    m_ctxEntry.AutoType.DefaultSequence = ReadString(xr);
                }
                else if (xr.Name == ElemAutoTypeItem)
                {
                    return(SwitchContext(ctx, KdbContext.EntryAutoTypeItem, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryAutoTypeItem:
                if (xr.Name == ElemWindow)
                {
                    m_ctxATName = ReadString(xr);
                }
                else if (xr.Name == ElemKeystrokeSequence)
                {
                    m_ctxATSeq = ReadString(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryCustomData:
                if (xr.Name == ElemStringDictExItem)
                {
                    return(SwitchContext(ctx, KdbContext.EntryCustomDataItem, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryCustomDataItem:
                if (xr.Name == ElemKey)
                {
                    m_strEntryCustomDataKey = ReadString(xr);
                }
                else if (xr.Name == ElemValue)
                {
                    m_strEntryCustomDataValue = ReadString(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.EntryHistory:
                if (xr.Name == ElemEntry)
                {
                    m_ctxEntry = new PwEntry(false, false);
                    m_ctxHistoryBase.History.Add(m_ctxEntry);

                    m_bEntryInHistory = true;
                    return(SwitchContext(ctx, KdbContext.Entry, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.RootDeletedObjects:
                if (xr.Name == ElemDeletedObject)
                {
                    m_ctxDeletedObject = new PwDeletedObject();
                    m_pwDatabase.DeletedObjects.Add(m_ctxDeletedObject);

                    return(SwitchContext(ctx, KdbContext.DeletedObject, xr));
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            case KdbContext.DeletedObject:
                if (xr.Name == ElemUuid)
                {
                    m_ctxDeletedObject.Uuid = ReadUuid(xr);
                }
                else if (xr.Name == ElemDeletionTime)
                {
                    m_ctxDeletedObject.DeletionTime = ReadTime(xr);
                }
                else
                {
                    ReadUnknown(xr);
                }
                break;

            default:
                ReadUnknown(xr);
                break;
            }

            return(ctx);
        }
Exemple #28
0
        private static void ExecuteCmd(string strCmd, string strFile)
        {
            if (strCmd == "convert_resx")
            {
                StreamWriter swOut = new StreamWriter(strFile + ".lng.xml",
                                                      false, new UTF8Encoding(false));

                XmlDocument xmlIn = XmlUtilEx.CreateXmlDocument();
                xmlIn.Load(strFile);

                foreach (XmlNode xmlChild in xmlIn.DocumentElement.ChildNodes)
                {
                    if (xmlChild.Name != "data")
                    {
                        continue;
                    }

                    swOut.Write("<Data Name=\"" + xmlChild.Attributes["name"].Value +
                                "\">\r\n\t<Value>" + xmlChild.SelectSingleNode("value").InnerXml +
                                "</Value>\r\n</Data>\r\n");
                }

                swOut.Close();
            }

            /* else if(strCmd == "compress")
             * {
             *      byte[] pbData = File.ReadAllBytes(strFile);
             *
             *      FileStream fs = new FileStream(strFile + ".lngx", FileMode.Create,
             *              FileAccess.Write, FileShare.None);
             *      GZipStream gz = new GZipStream(fs, CompressionMode.Compress);
             *
             *      gz.Write(pbData, 0, pbData.Length);
             *      gz.Close();
             *      fs.Close();
             * } */
            else if (strCmd == "src_from_xml")
            {
                XmlDocument xmlIn = XmlUtilEx.CreateXmlDocument();
                xmlIn.Load(strFile);

                foreach (XmlNode xmlTable in xmlIn.DocumentElement.SelectNodes("StringTable"))
                {
                    StreamWriter swOut = new StreamWriter(xmlTable.Attributes["Name"].Value +
                                                          ".Generated.cs", false, new UTF8Encoding(false));

                    swOut.WriteLine("// This is a generated file!");
                    swOut.WriteLine("// Do not edit manually, changes will be overwritten.");
                    swOut.WriteLine();
                    swOut.WriteLine("using System;");
                    swOut.WriteLine("using System.Collections.Generic;");
                    swOut.WriteLine();
                    swOut.WriteLine("namespace " + xmlTable.Attributes["Namespace"].Value);
                    swOut.WriteLine("{");
                    swOut.WriteLine("\t/// <summary>");
                    swOut.WriteLine("\t/// A strongly-typed resource class, for looking up localized strings, etc.");
                    swOut.WriteLine("\t/// </summary>");
                    swOut.WriteLine("\tpublic static partial class " + xmlTable.Attributes["Name"].Value);
                    swOut.WriteLine("\t{");

                    swOut.WriteLine("\t\tprivate static string TryGetEx(Dictionary<string, string> dictNew,");
                    swOut.WriteLine("\t\t\tstring strName, string strDefault)");
                    swOut.WriteLine("\t\t{");
                    swOut.WriteLine("\t\t\tstring strTemp;");
                    swOut.WriteLine();
                    swOut.WriteLine("\t\t\tif(dictNew.TryGetValue(strName, out strTemp))");
                    swOut.WriteLine("\t\t\t\treturn strTemp;");
                    swOut.WriteLine();
                    swOut.WriteLine("\t\t\treturn strDefault;");
                    swOut.WriteLine("\t\t}");
                    swOut.WriteLine();

                    swOut.WriteLine("\t\tpublic static void SetTranslatedStrings(Dictionary<string, string> dictNew)");
                    swOut.WriteLine("\t\t{");
                    swOut.WriteLine("\t\t\tif(dictNew == null) throw new ArgumentNullException(\"dictNew\");");
                    swOut.WriteLine();

#if DEBUG
                    string strLastName = string.Empty;
#endif
                    foreach (XmlNode xmlData in xmlTable.SelectNodes("Data"))
                    {
                        string strName = xmlData.Attributes["Name"].Value;

                        swOut.WriteLine("\t\t\tm_str" + strName +
                                        " = TryGetEx(dictNew, \"" + strName +
                                        "\", m_str" + strName + ");");

#if DEBUG
                        Debug.Assert((string.Compare(strLastName, strName, true) < 0),
                                     "Data names not sorted: " + strLastName + " - " + strName + ".");
                        strLastName = strName;
#endif
                    }

                    swOut.WriteLine("\t\t}");
                    swOut.WriteLine();

                    swOut.WriteLine("\t\tprivate static readonly string[] m_vKeyNames = {");
                    XmlNodeList xNodes = xmlTable.SelectNodes("Data");
                    for (int i = 0; i < xNodes.Count; ++i)
                    {
                        XmlNode xmlData = xNodes.Item(i);
                        swOut.WriteLine("\t\t\t\"" + xmlData.Attributes["Name"].Value +
                                        "\"" + ((i != xNodes.Count - 1) ? "," : string.Empty));
                    }

                    swOut.WriteLine("\t\t};");
                    swOut.WriteLine();

                    swOut.WriteLine("\t\tpublic static string[] GetKeyNames()");
                    swOut.WriteLine("\t\t{");
                    swOut.WriteLine("\t\t\treturn m_vKeyNames;");
                    swOut.WriteLine("\t\t}");

                    foreach (XmlNode xmlData in xmlTable.SelectNodes("Data"))
                    {
                        string strName  = xmlData.Attributes["Name"].Value;
                        string strValue = xmlData.SelectSingleNode("Value").InnerText;
                        if (strValue.Contains("\""))
                        {
                            // Console.WriteLine(strValue);
                            strValue = strValue.Replace("\"", "\"\"");
                        }

                        swOut.WriteLine();
                        swOut.WriteLine("\t\tprivate static string m_str" +
                                        strName + " =");
                        swOut.WriteLine("\t\t\t@\"" + strValue + "\";");

                        swOut.WriteLine("\t\t/// <summary>");
                        swOut.WriteLine("\t\t/// Look up a localized string similar to");
                        swOut.WriteLine("\t\t/// '" + StrUtil.StringToHtml(strValue) + "'.");
                        swOut.WriteLine("\t\t/// </summary>");
                        swOut.WriteLine("\t\tpublic static string " +
                                        strName);
                        swOut.WriteLine("\t\t{");
                        swOut.WriteLine("\t\t\tget { return m_str" + strName +
                                        "; }");
                        swOut.WriteLine("\t\t}");
                    }

                    swOut.WriteLine("\t}");                     // Close class
                    swOut.WriteLine("}");

                    swOut.Close();
                }
            }
        }
Exemple #29
0
        /* private void ShowWaitDocument()
         * {
         *      StringBuilder sbW = new StringBuilder();
         *      sbW.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
         *      sbW.AppendLine("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
         *      sbW.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
         *      sbW.AppendLine("<head>");
         *      sbW.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
         *      sbW.AppendLine("<title>...</title>");
         *      sbW.AppendLine("</head><body><br /><br />");
         *      sbW.AppendLine("<h1 style=\"text-align: center;\">&#8987;</h1>");
         *      sbW.AppendLine("</body></html>");
         *
         *      try { UIUtil.SetWebBrowserDocument(m_wbMain, sbW.ToString()); }
         *      catch(Exception) { Debug.Assert(NativeLib.IsUnix()); } // Throws in Mono 2.0+
         * } */

        private void UpdateHtmlDocument(bool bInitial)
        {
            if (m_bBlockPreviewRefresh)
            {
                return;
            }
            m_bBlockPreviewRefresh = true;
            if (!bInitial)
            {
                UIBlockInteraction(true);
            }
            // ShowWaitDocument();

            PwGroup pgDataSource = m_pgDataSource.CloneDeep();

            int    nSortEntries     = m_cmbSortEntries.SelectedIndex;
            string strSortFieldName = null;

            if (nSortEntries == 0)
            {
            }                                     // No sort
            else if (nSortEntries == 1)
            {
                strSortFieldName = PwDefs.TitleField;
            }
            else if (nSortEntries == 2)
            {
                strSortFieldName = PwDefs.UserNameField;
            }
            else if (nSortEntries == 3)
            {
                strSortFieldName = PwDefs.PasswordField;
            }
            else if (nSortEntries == 4)
            {
                strSortFieldName = PwDefs.UrlField;
            }
            else if (nSortEntries == 5)
            {
                strSortFieldName = PwDefs.NotesField;
            }
            else
            {
                Debug.Assert(false);
            }
            if (strSortFieldName != null)
            {
                SortGroupEntriesRecursive(pgDataSource, strSortFieldName);
            }

            bool bGroup = m_cbGroups.Checked;
            bool bTitle = m_cbTitle.Checked, bUserName = m_cbUser.Checked;
            bool bPassword = m_cbPassword.Checked, bUrl = m_cbUrl.Checked;
            bool bNotes = m_cbNotes.Checked;
            bool bCreation = m_cbCreation.Checked, bLastMod = m_cbLastMod.Checked;
            // bool bLastAcc = m_cbLastAccess.Checked;
            bool bExpire        = m_cbExpire.Checked;
            bool bAutoType      = m_cbAutoType.Checked;
            bool bTags          = m_cbTags.Checked;
            bool bCustomStrings = m_cbCustomStrings.Checked;
            bool bUuid          = m_cbUuid.Checked;

            PfOptions p = new PfOptions();

            p.MonoPasswords = m_cbMonospaceForPasswords.Checked;
            if (m_rbMonospace.Checked)
            {
                p.MonoPasswords = false;                                   // Monospace anyway
            }
            p.SmallMono = m_cbSmallMono.Checked;
            p.SprMode   = m_cmbSpr.SelectedIndex;
            p.Rtl       = (this.RightToLeft == RightToLeft.Yes);
            p.Database  = m_pdContext;
            if (m_cbIcon.Checked)
            {
                p.ClientIcons = m_ilClientIcons;
            }

            if (m_rbSerif.Checked)
            {
                p.FontInit = "<span class=\"fserif\">";
                p.FontExit = "</span>";
            }
            else if (m_rbSansSerif.Checked)
            {
                p.FontInit = string.Empty;
                p.FontExit = string.Empty;
            }
            else if (m_rbMonospace.Checked)
            {
                p.FontInit = (p.SmallMono ? "<code><small>" : "<code>");
                p.FontExit = (p.SmallMono ? "</small></code>" : "</code>");
            }
            else
            {
                Debug.Assert(false);
            }

            GFunc <string, string> h = new GFunc <string, string>(StrUtil.StringToHtml);
            GFunc <string, string> c = delegate(string strRaw)
            {
                return(CompileText(strRaw, p, true, false));
            };
            GFunc <string, string> cs = delegate(string strRaw)
            {
                return(CompileText(strRaw, p, true, true));
            };

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"");
            sb.AppendLine("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");

            sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"");
            string strLang = Program.Translation.Properties.Iso6391Code;

            if (string.IsNullOrEmpty(strLang))
            {
                strLang = "en";
            }
            strLang = h(strLang);
            sb.Append(" lang=\"" + strLang + "\" xml:lang=\"" + strLang + "\"");
            if (p.Rtl)
            {
                sb.Append(" dir=\"rtl\"");
            }
            sb.AppendLine(">");

            sb.AppendLine("<head>");
            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
            sb.Append("<title>");
            sb.Append(h(pgDataSource.Name));
            sb.AppendLine("</title>");
            sb.AppendLine("<meta http-equiv=\"expires\" content=\"0\" />");
            sb.AppendLine("<meta http-equiv=\"cache-control\" content=\"no-cache\" />");
            sb.AppendLine("<meta http-equiv=\"pragma\" content=\"no-cache\" />");

            sb.AppendLine("<style type=\"text/css\">");
            sb.AppendLine("/* <![CDATA[ */");

            sb.AppendLine("body, p, div, h1, h2, h3, h4, h5, h6, ol, ul, li, td, th, dd, dt, a {");
            sb.AppendLine("\tfont-family: \"Tahoma\", \"MS Sans Serif\", \"Sans Serif\", \"Verdana\", sans-serif;");
            sb.AppendLine("\tfont-size: 10pt;");
            sb.AppendLine("}");

            sb.AppendLine("span.fserif {");
            sb.AppendLine("\tfont-family: \"Times New Roman\", serif;");
            sb.AppendLine("}");

            sb.AppendLine("h1 { font-size: 2em; }");
            sb.AppendLine("h2 {");
            sb.AppendLine("\tfont-size: 1.5em;");
            sb.AppendLine("\tcolor: #000000;");
            sb.AppendLine("\tbackground-color: #D0D0D0;");
            sb.AppendLine("\tpadding-left: 2pt;");
            sb.AppendLine("\tpadding-right: 2pt;");             // RTL support
            sb.AppendLine("}");
            sb.AppendLine("h3 {");
            sb.AppendLine("\tfont-size: 1.2em;");
            sb.AppendLine("\tcolor: #000000;");
            sb.AppendLine("\tbackground-color: #D0D0D0;");
            sb.AppendLine("\tpadding-left: 2pt;");
            sb.AppendLine("\tpadding-right: 2pt;");             // RTL support
            sb.AppendLine("}");
            sb.AppendLine("h4 { font-size: 1em; }");
            sb.AppendLine("h5 { font-size: 0.89em; }");
            sb.AppendLine("h6 { font-size: 0.6em; }");

            sb.AppendLine("table {");
            sb.AppendLine("\twidth: 100%;");
            sb.AppendLine("\ttable-layout: fixed;");
            sb.AppendLine("}");

            sb.AppendLine("th {");
            sb.AppendLine("\ttext-align: " + (p.Rtl ? "right;" : "left;"));
            sb.AppendLine("\tvertical-align: top;");
            sb.AppendLine("\tfont-weight: bold;");
            sb.AppendLine("}");

            sb.AppendLine("td {");
            sb.AppendLine("\ttext-align: " + (p.Rtl ? "right;" : "left;"));
            sb.AppendLine("\tvertical-align: top;");
            sb.AppendLine("}");

            sb.AppendLine("a:visited {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("}");
            sb.AppendLine("a:active {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("}");
            sb.AppendLine("a:link {");
            sb.AppendLine("\ttext-decoration: none;");
            sb.AppendLine("\tcolor: #0000DD;");
            sb.AppendLine("}");
            sb.AppendLine("a:hover {");
            sb.AppendLine("\ttext-decoration: underline;");
            sb.AppendLine("\tcolor: #6699FF;");
            sb.AppendLine("}");

            sb.AppendLine(".field_name {");
            sb.AppendLine("\t-webkit-hyphens: auto;");
            sb.AppendLine("\t-moz-hyphens: auto;");
            sb.AppendLine("\t-ms-hyphens: auto;");
            sb.AppendLine("\thyphens: auto;");
            sb.AppendLine("}");
            sb.AppendLine(".field_data {");
            // sb.AppendLine("\tword-break: break-all;");
            sb.AppendLine("\toverflow-wrap: break-word;");
            sb.AppendLine("\tword-wrap: break-word;");
            sb.AppendLine("}");

            sb.AppendLine(".icon_cli {");
            sb.AppendLine("\tdisplay: inline-block;");
            sb.AppendLine("\tmargin: 0px 0px 0px 0px;");
            sb.AppendLine("\tpadding: 0px 0px 0px 0px;");
            sb.AppendLine("\tborder: 0px none;");
            sb.AppendLine("\twidth: 1.1em;");
            sb.AppendLine("\theight: 1.1em;");
            sb.AppendLine("\tvertical-align: top;");
            sb.AppendLine("}");

            // Add the temporary content identifier
            sb.AppendLine("." + Program.TempFilesPool.TempContentTag + " {");
            sb.AppendLine("\tfont-size: 10pt;");
            sb.AppendLine("}");

            sb.AppendLine("/* ]]> */");
            sb.AppendLine("</style>");
            sb.AppendLine("</head><body>");

            sb.AppendLine("<h2>" + h(pgDataSource.Name) + "</h2>");
            WriteGroupNotes(sb, pgDataSource);

            EntryHandler ehInit = delegate(PwEntry pe)
            {
                p.Entry = pe;

                if (p.SprMode != 0)
                {
                    p.SprContext = new SprContext(pe, p.Database,
                                                  SprCompileFlags.NonActive, false, false);
                }
                else
                {
                    Debug.Assert(p.SprContext == null);
                }

                Application.DoEvents();
                return(true);
            };

            EntryHandler eh           = null;
            string       strTableInit = "<table>";
            PwGroup      pgLast       = null;

            if (m_rbTabular.Checked)
            {
                int nEquiCols = 0;
                if (bGroup)
                {
                    ++nEquiCols;
                }
                if (bTitle)
                {
                    ++nEquiCols;
                }
                if (bUserName)
                {
                    ++nEquiCols;
                }
                if (bPassword)
                {
                    ++nEquiCols;
                }
                if (bUrl)
                {
                    ++nEquiCols;
                }
                if (bNotes)
                {
                    nEquiCols += 2;
                }
                if (bCreation)
                {
                    ++nEquiCols;
                }
                // if(bLastAcc) ++nEquiCols;
                if (bLastMod)
                {
                    ++nEquiCols;
                }
                if (bExpire)
                {
                    ++nEquiCols;
                }
                if (bTags)
                {
                    ++nEquiCols;
                }
                if (bUuid)
                {
                    ++nEquiCols;
                }
                if (nEquiCols == 0)
                {
                    nEquiCols = 1;
                }

                string strColWidth = (100.0f / (float)nEquiCols).ToString(
                    "F2", NumberFormatInfo.InvariantInfo);
                string strColWidth2 = (200.0f / (float)nEquiCols).ToString(
                    "F2", NumberFormatInfo.InvariantInfo);

                string strHTdInit = "<th class=\"field_name\" style=\"width: " +
                                    strColWidth + "%;\">";
                string strHTdInit2 = "<th class=\"field_name\" style=\"width: " +
                                     strColWidth2 + "%;\">";
                string strHTdExit    = "</th>";
                string strDataTdInit = "<td class=\"field_data\">";
                string strDataTdExit = "</td>";

                p.CellInit = strDataTdInit + p.FontInit;
                p.CellExit = p.FontExit + strDataTdExit;

                StringBuilder sbH = new StringBuilder();
                sbH.AppendLine();
                sbH.Append("<tr>");
                if (bGroup)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Group) + strHTdExit);
                }
                if (bTitle)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Title) + strHTdExit);
                }
                if (bUserName)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.UserName) + strHTdExit);
                }
                if (bPassword)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Password) + strHTdExit);
                }
                if (bUrl)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Url) + strHTdExit);
                }
                if (bNotes)
                {
                    sbH.AppendLine(strHTdInit2 + h(KPRes.Notes) + strHTdExit);
                }
                if (bCreation)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.CreationTime) + strHTdExit);
                }
                // if(bLastAcc) sbH.AppendLine(strHTdInit + h(KPRes.LastAccessTime) + strHTdExit);
                if (bLastMod)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.LastModificationTime) + strHTdExit);
                }
                if (bExpire)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.ExpiryTime) + strHTdExit);
                }
                if (bTags)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Tags) + strHTdExit);
                }
                if (bUuid)
                {
                    sbH.AppendLine(strHTdInit + h(KPRes.Uuid) + strHTdExit);
                }
                sbH.Append("</tr>");                 // No terminating \r\n

                strTableInit += sbH.ToString();
                sb.AppendLine(strTableInit);

                eh = delegate(PwEntry pe)
                {
                    ehInit(pe);

                    sb.AppendLine("<tr>");

                    WriteTabularIf(bGroup, sb, c(pe.ParentGroup.Name), p);
                    WriteTabularIf(bTitle, sb, pe, PwDefs.TitleField, p);
                    WriteTabularIf(bUserName, sb, pe, PwDefs.UserNameField, p);

                    if (bPassword)
                    {
                        if (p.MonoPasswords)
                        {
                            sb.Append(strDataTdInit + (p.SmallMono ?
                                                       "<code><small>" : "<code>"));
                        }
                        else
                        {
                            sb.Append(p.CellInit);
                        }

                        string strInner = cs(pe.Strings.ReadSafe(PwDefs.PasswordField));
                        if (strInner.Length == 0)
                        {
                            strInner = "&nbsp;";
                        }
                        sb.Append(strInner);

                        if (p.MonoPasswords)
                        {
                            sb.AppendLine((p.SmallMono ? "</small></code>" :
                                           "</code>") + strDataTdExit);
                        }
                        else
                        {
                            sb.AppendLine(p.CellExit);
                        }
                    }

                    // WriteTabularIf(bUrl, sb, pe, PwDefs.UrlField, p);
                    WriteTabularIf(bUrl, sb, MakeUrlLink(pe.Strings.ReadSafe(
                                                             PwDefs.UrlField), p), p);

                    WriteTabularIf(bNotes, sb, pe, PwDefs.NotesField, p);

                    WriteTabularIf(bCreation, sb, h(TimeUtil.ToDisplayString(
                                                        pe.CreationTime)), p);
                    // WriteTabularIf(bLastAcc, sb, h(TimeUtil.ToDisplayString(
                    //	pe.LastAccessTime)), p);
                    WriteTabularIf(bLastMod, sb, h(TimeUtil.ToDisplayString(
                                                       pe.LastModificationTime)), p);
                    WriteTabularIf(bExpire, sb, h(pe.Expires ? TimeUtil.ToDisplayString(
                                                      pe.ExpiryTime) : KPRes.NeverExpires), p);

                    WriteTabularIf(bTags, sb, h(StrUtil.TagsToString(pe.Tags, true)), p);

                    WriteTabularIf(bUuid, sb, pe.Uuid.ToHexString(), p);

                    sb.AppendLine("</tr>");
                    return(true);
                };
            }
            else if (m_rbDetails.Checked)
            {
                sb.AppendLine(strTableInit);

                if (pgDataSource.Entries.UCount == 0)
                {
                    sb.AppendLine(@"<tr><td>&nbsp;</td></tr>");
                }

                eh = delegate(PwEntry pe)
                {
                    ehInit(pe);

                    if ((pgLast != null) && (pgLast == pe.ParentGroup))
                    {
                        sb.AppendLine("<tr><td colspan=\"2\"><hr /></td></tr>");
                    }

                    if (bGroup)
                    {
                        WriteDetailsLine(sb, KPRes.Group, pe.ParentGroup.Name, p);
                    }
                    if (bTitle)
                    {
                        PfOptions pSub = p.CloneShallow();
                        pSub.FontInit = MakeIconImg(pe.IconId, pe.CustomIconUuid, pe,
                                                    p) + pSub.FontInit + "<b>";
                        pSub.FontExit = "</b>" + pSub.FontExit;

                        WriteDetailsLine(sb, KPRes.Title, pe.Strings.ReadSafe(
                                             PwDefs.TitleField), pSub);
                    }
                    if (bUserName)
                    {
                        WriteDetailsLine(sb, KPRes.UserName, pe.Strings.ReadSafe(
                                             PwDefs.UserNameField), p);
                    }
                    if (bPassword)
                    {
                        WriteDetailsLine(sb, KPRes.Password, pe.Strings.ReadSafe(
                                             PwDefs.PasswordField), p);
                    }
                    if (bUrl)
                    {
                        WriteDetailsLine(sb, KPRes.Url, pe.Strings.ReadSafe(
                                             PwDefs.UrlField), p);
                    }
                    if (bNotes)
                    {
                        WriteDetailsLine(sb, KPRes.Notes, pe.Strings.ReadSafe(
                                             PwDefs.NotesField), p);
                    }
                    if (bCreation)
                    {
                        WriteDetailsLine(sb, KPRes.CreationTime, TimeUtil.ToDisplayString(
                                             pe.CreationTime), p);
                    }
                    // if(bLastAcc) WriteDetailsLine(sb, KPRes.LastAccessTime, TimeUtil.ToDisplayString(
                    //	pe.LastAccessTime), p);
                    if (bLastMod)
                    {
                        WriteDetailsLine(sb, KPRes.LastModificationTime, TimeUtil.ToDisplayString(
                                             pe.LastModificationTime), p);
                    }
                    if (bExpire)
                    {
                        WriteDetailsLine(sb, KPRes.ExpiryTime, (pe.Expires ? TimeUtil.ToDisplayString(
                                                                    pe.ExpiryTime) : KPRes.NeverExpires), p);
                    }

                    if (bAutoType)
                    {
                        foreach (AutoTypeAssociation a in pe.AutoType.Associations)
                        {
                            WriteDetailsLine(sb, KPRes.AutoType, a.WindowName +
                                             ": " + a.Sequence, p);
                        }
                    }

                    if (bTags)
                    {
                        WriteDetailsLine(sb, KPRes.Tags, StrUtil.TagsToString(
                                             pe.Tags, true), p);
                    }
                    if (bUuid)
                    {
                        WriteDetailsLine(sb, KPRes.Uuid, pe.Uuid.ToHexString(), p);
                    }

                    foreach (KeyValuePair <string, ProtectedString> kvp in pe.Strings)
                    {
                        if (bCustomStrings && !PwDefs.IsStandardField(kvp.Key))
                        {
                            WriteDetailsLine(sb, kvp, p);
                        }
                    }

                    pgLast = pe.ParentGroup;
                    return(true);
                };
            }
            else
            {
                Debug.Assert(false);
            }

            GroupHandler gh = delegate(PwGroup pg)
            {
                if (pg.Entries.UCount == 0)
                {
                    return(true);
                }

                sb.Append("</table><br /><br /><h3>");                 // "</table><br /><hr /><h3>"
                // sb.Append(MakeIconImg(pg.IconId, pg.CustomIconUuid, pg, p));
                sb.Append(h(pg.GetFullPath(" - ", false)));
                sb.AppendLine("</h3>");
                WriteGroupNotes(sb, pg);
                sb.AppendLine(strTableInit);

                return(true);
            };

            pgDataSource.TraverseTree(TraversalMethod.PreOrder, gh, eh);

            if (m_rbTabular.Checked)
            {
                sb.AppendLine("</table>");
            }
            else if (m_rbDetails.Checked)
            {
                sb.AppendLine("</table><br />");
            }

            sb.AppendLine("</body></html>");

            try { UIUtil.SetWebBrowserDocument(m_wbMain, sb.ToString()); }
            catch (Exception) { Debug.Assert(NativeLib.IsUnix()); }            // Throws in Mono 2.0+
            try { m_wbMain.AllowNavigation = false; }
            catch (Exception) { Debug.Assert(false); }

            if (!bInitial)
            {
                UIBlockInteraction(false);
            }
            m_bBlockPreviewRefresh = false;
        }
Exemple #30
0
        public static string CreateSummaryList(PwGroup pgSubGroups, PwEntry[] vEntries)
        {
            int    nMaxEntries = 10;
            string strSummary  = string.Empty;

            if (pgSubGroups != null)
            {
                PwObjectList <PwGroup> vGroups = pgSubGroups.GetGroups(true);
                if (vGroups.UCount > 0)
                {
                    StringBuilder sbGroups = new StringBuilder();
                    sbGroups.Append("- ");
                    uint uToList = Math.Min(3U, vGroups.UCount);
                    for (uint u = 0; u < uToList; ++u)
                    {
                        if (sbGroups.Length > 2)
                        {
                            sbGroups.Append(", ");
                        }
                        sbGroups.Append(vGroups.GetAt(u).Name);
                    }
                    if (uToList < vGroups.UCount)
                    {
                        sbGroups.Append(", ...");
                    }
                    strSummary += sbGroups.ToString();                     // New line below

                    nMaxEntries -= 2;
                }
            }

            int nSummaryShow = Math.Min(nMaxEntries, vEntries.Length);

            if (nSummaryShow == (vEntries.Length - 1))
            {
                --nSummaryShow;                                                   // Plural msg
            }
            for (int iSumEnum = 0; iSumEnum < nSummaryShow; ++iSumEnum)
            {
                if (strSummary.Length > 0)
                {
                    strSummary += MessageService.NewLine;
                }

                PwEntry pe = vEntries[iSumEnum];
                strSummary += ("- " + StrUtil.CompactString3Dots(
                                   pe.Strings.ReadSafe(PwDefs.TitleField), 39));
                if (PwDefs.IsTanEntry(pe))
                {
                    string strTanIdx = pe.Strings.ReadSafe(PwDefs.UserNameField);
                    if (!string.IsNullOrEmpty(strTanIdx))
                    {
                        strSummary += (@" (#" + strTanIdx + @")");
                    }
                }
            }
            if (nSummaryShow != vEntries.Length)
            {
                strSummary += (MessageService.NewLine + "- " +
                               KPRes.MoreEntries.Replace(@"{PARAM}", (vEntries.Length -
                                                                      nSummaryShow).ToString()));
            }

            return(strSummary);
        }