Example #1
0
		private void OnFormLoad(object sender, EventArgs e)
		{
			GlobalWindowManager.AddWindow(this);

			this.Icon = Properties.Resources.KeePass;
			this.Text = m_strTitle;

			m_nIconDim = m_tvFolders.ItemHeight;

			if(UIUtil.VistaStyleListsSupported)
			{
				m_tvFolders.ShowLines = false;

				UIUtil.SetExplorerTheme(m_tvFolders, true);
				UIUtil.SetExplorerTheme(m_lvFiles, true);
			}

			m_btnOK.Text = (m_bSaveMode ? KPRes.SaveCmd : KPRes.OpenCmd);
			m_lblHint.Text = m_strHint;

			if(UIUtil.ColorsEqual(m_lblHint.ForeColor, Color.Black))
				m_lblHint.ForeColor = Color.FromArgb(96, 96, 96);

			int nWidth = m_lvFiles.ClientSize.Width - UIUtil.GetVScrollBarWidth();
			m_lvFiles.Columns.Add(KPRes.Name, (nWidth * 3) / 4);
			m_lvFiles.Columns.Add(KPRes.Size, nWidth / 4, HorizontalAlignment.Right);

			InitialPopulateFolders();

			string strWorkDir = Program.Config.Application.GetWorkingDirectory(m_strContext);
			if(string.IsNullOrEmpty(strWorkDir))
				strWorkDir = WinUtil.GetHomeDirectory();
			BrowseToFolder(strWorkDir);

			EnableControlsEx();
		}
Example #2
0
        private void GetAppComponents()
        {
            ListViewItem lvi = new ListViewItem(KPRes.KeePassLibCLong);

            if (!Kdb3File.IsLibraryInstalled())
            {
                lvi.SubItems.Add(KPRes.NotInstalled);
            }
            else
            {
                lvi.SubItems.Add(Kdb3Manager.KeePassVersionString + " (0x" +
                                 Kdb3Manager.LibraryBuild.ToString("X4") + ")");
            }

            m_lvComponents.Items.Add(lvi);

            lvi = new ListViewItem(KPRes.XslStylesheets);
            string strPath = WinUtil.GetExecutable();

            strPath = UrlUtil.GetFileDirectory(strPath, true, false);
            bool bInstalled = File.Exists(strPath + AppDefs.XslFileHtmlLite);

            bInstalled &= File.Exists(strPath + AppDefs.XslFileHtmlFull);
            bInstalled &= File.Exists(strPath + AppDefs.XslFileHtmlTabular);

            if (!bInstalled)
            {
                lvi.SubItems.Add(KPRes.NotInstalled);
            }
            else
            {
                lvi.SubItems.Add(PwDefs.VersionString);
            }

            m_lvComponents.Items.Add(lvi);
        }
        private void PostShowDialog(string strPrevWorkDir, DialogResult dr)
        {
            string strCur = null;

            // Modern file dialogs (on Windows >= Vista) do not change the
            // working directory (in contrast to Windows <= XP), thus we
            // derive the working directory from the first file
            try
            {
                if (dr == DialogResult.OK)
                {
                    string strFile = null;
                    if (m_bSaveMode)
                    {
                        strFile = this.FileDialog.FileName;
                    }
                    else if (this.FileDialog.FileNames.Length > 0)
                    {
                        strFile = this.FileDialog.FileNames[0];
                    }

                    if (!string.IsNullOrEmpty(strFile))
                    {
                        strCur = UrlUtil.GetFileDirectory(strFile, false, true);
                    }
                }
            }
            catch (Exception) { Debug.Assert(false); }

            if (!string.IsNullOrEmpty(strCur))
            {
                Program.Config.Application.SetWorkingDirectory(m_strContext, strCur);
            }

            WinUtil.SetWorkingDirectory(strPrevWorkDir);
        }
        /// <summary>
        /// 服务端数据保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string gssip   = cbGSSip.Text;
                string gssport = tPort.Text.Trim();
                if (!WinUtil.isIpaddres(gssip))
                {
                    MessageBox.Show("服务器IP地址格式不正确!");
                    return;
                }
                if (!WinUtil.IsNumber(gssport))
                {
                    MessageBox.Show("服务器端口号应该为数字!");
                    return;
                }

                string sql = "UPDATE GSSCONFIG SET GSSIP='" + gssip + "',GSSPORT='" + gssport + "'WHERE ID=1";
                int    row = DbHelperSQLite.ExecuteSql(sql);
                if (row >= 1)
                {
                    MessageBox.Show("服务端参数保存成功!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("服务端参数保存失败!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString().ErrorLogger();
                MessageBox.Show("服务端参数提交失败!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //日志记录
                ShareData.Log.Warn("服务端参数提交失败!" + ex.Message);
            }
        }
Example #5
0
        private void OnRichTextBoxLinkClicked(object sender, LinkClickedEventArgs e)
        {
            try
            {
                string strLink = e.LinkText;
                if (string.IsNullOrEmpty(strLink))
                {
                    Debug.Assert(false); return;
                }

                if ((strLink == m_strDataExpand) && (m_tscViewers.Text == m_strViewerHex))
                {
                    m_bDataExpanded = true;
                    UpdateHexView();
                    m_rtbText.Select(m_rtbText.TextLength, 0);
                    m_rtbText.ScrollToCaret();
                }
                else
                {
                    WinUtil.OpenUrl(strLink, null);
                }
            }
            catch (Exception) { }            // ScrollToCaret might throw (but still works)
        }
Example #6
0
        private static void CheckShieldify()
        {
            List <string> lShieldify = new List <string>();

            try
            {
                m_bShieldify = false;
                if (KeePassLib.Native.NativeLib.IsUnix())
                {
                    lShieldify.Add("Detected Unix");
                    return;
                }
                if (!WinUtil.IsAtLeastWindows7)
                {
                    lShieldify.Add("Detected Windows < 7");
                    return;
                }
                string sPF86   = EnsureNonNull(Environment.GetEnvironmentVariable("ProgramFiles(x86)"));
                string sPF86_2 = string.Empty;
                try { sPF86_2 = EnsureNonNull(Environment.GetFolderPath((Environment.SpecialFolder) 42)); }                //Environment.SpecialFolder.ProgramFilesX86
                catch { sPF86_2 = sPF86; }
                string sPF = EnsureNonNull(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
                string sKP = EnsureNonNull(UrlUtil.GetFileDirectory(WinUtil.GetExecutable(), true, false));
                m_bShieldify = sKP.StartsWith(sPF86) || sKP.StartsWith(sPF) || sKP.StartsWith(sPF86_2);
                lShieldify.Add("KeePass folder inside ProgramFiles(x86): " + sKP.StartsWith(sPF86));
                lShieldify.Add("KeePass folder inside Environment.SpecialFolder.ProgramFilesX86: " + sKP.StartsWith(sPF86_2));
                lShieldify.Add("KeePass folder inside Environment.SpecialFolder.ProgramFiles: " + sKP.StartsWith(sPF));
                return;
            }
            catch (Exception ex) { lShieldify.Add("Exception: " + ex.Message); return; }
            finally
            {
                lShieldify.Insert(0, "Shieldify: " + m_bShieldify.ToString());
                PluginDebug.AddInfo("Check Shieldify", 0, lShieldify.ToArray());
            }
        }
Example #7
0
        private static void ChangePathRelAbs(IOConnectionInfo ioc, bool bMakeAbsolute)
        {
            if (ioc == null)
            {
                Debug.Assert(false); return;
            }

            if (ioc.IsLocalFile() == false)
            {
                return;
            }

            string strBase = WinUtil.GetExecutable();
            bool   bIsAbs  = UrlUtil.IsAbsolutePath(ioc.Path);

            if (bMakeAbsolute && !bIsAbs)
            {
                ioc.Path = UrlUtil.MakeAbsolutePath(strBase, ioc.Path);
            }
            else if (!bMakeAbsolute && bIsAbs)
            {
                ioc.Path = UrlUtil.MakeRelativePath(strBase, ioc.Path);
            }
        }
 /// <summary>
 /// 保存网络配置
 /// </summary>
 private void SaveConfig()
 {
     try
     {
         string gssip   = tGSSIP.Text;
         string gssport = tPort.Text.Trim();
         if (!WinUtil.isIpaddres(gssip))
         {
             MsgBox.Show(LanguageResource.Language.Tip_ErrorServiceIPFormat);
             return;
         }
         if (!WinUtil.IsNumber(gssport))
         {
             MsgBox.Show(LanguageResource.Language.Tip_PortShouldNumber);
             return;
         }
         string sql = "UPDATE GSSCONFIG SET GSSIP='" + gssip + "',GSSPORT='" + gssport + "'WHERE ID=1";
         int    row = DbHelperSQLite.ExecuteSql(sql);
         if (row >= 1)
         {
             MsgBox.Show(LanguageResource.Language.Tip_SuccessSaveNetConfig, LanguageResource.Language.Tip_Tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
             SetConfigView();
         }
         else
         {
             MsgBox.Show(LanguageResource.Language.Tip_ErrorSaveNetConfig, LanguageResource.Language.Tip_Tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     catch (System.Exception ex)
     {
         ex.ToString().ErrorLogger();
         MsgBox.Show(LanguageResource.Language.Tip_ErrorSaveNetConfigTip, LanguageResource.Language.Tip_Tip, MessageBoxButtons.OK, MessageBoxIcon.Error);
         //日志记录
         ShareData.Log.Error(ex);
     }
 }
Example #9
0
        public static void ConfigureProcess()
        {
            Debug.Assert(!m_bInitialized);             // Configure process before use
            if (NativeLib.IsUnix())
            {
                return;
            }

            // try
            // {
            //	ConfigurationManager.AppSettings.Set(
            //		"EnableWindowsFormsHighDpiAutoResizing", "true");
            // }
            // catch(Exception) { Debug.Assert(false); }
#if DEBUG
            // Ensure that the .config file enables high DPI features
            string strExeConfig = WinUtil.GetExecutable() + ".config";
            if (File.Exists(strExeConfig))
            {
                string strCM = "System.Configuration.ConfigurationManager, ";
                strCM += "System.Configuration, Version=";
                strCM += Environment.Version.Major.ToString() + ".0.0.0, ";
                strCM += "Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

                Type tCM = Type.GetType(strCM, false);
                if (tCM != null)
                {
                    PropertyInfo pi = tCM.GetProperty("AppSettings",
                                                      (BindingFlags.Public | BindingFlags.Static));
                    if (pi != null)
                    {
                        NameValueCollection nvc = (pi.GetValue(null, null) as
                                                   NameValueCollection);
                        if (nvc != null)
                        {
                            Debug.Assert(string.Equals(nvc.Get(
                                                           "EnableWindowsFormsHighDpiAutoResizing"),
                                                       "true", StrUtil.CaseIgnoreCmp));
                        }
                        else
                        {
                            Debug.Assert(false);
                        }
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
                else
                {
                    Debug.Assert(false);
                }                                             // Assembly should be loaded
            }
#endif

            try
            {
                // SetProcessDPIAware is obsolete; use
                // SetProcessDpiAwareness on Windows 10 and higher
                if (WinUtil.IsAtLeastWindows10)                // 8.1 partially
                {
                    if (NativeMethods.SetProcessDpiAwareness(
                            NativeMethods.ProcessDpiAwareness.SystemAware) < 0)
                    {
                        Debug.Assert(false);
                    }
                }
                else if (WinUtil.IsAtLeastWindowsVista)
                {
                    if (!NativeMethods.SetProcessDPIAware())
                    {
                        Debug.Assert(false);
                    }
                }
            }
            catch (Exception) { Debug.Assert(false); }
        }
Example #10
0
        private static string CompileInternal(string strText, SprContext ctx,
                                              uint uRecursionLevel)
        {
            if (strText == null)
            {
                Debug.Assert(false); return(string.Empty);
            }
            if (ctx == null)
            {
                Debug.Assert(false); ctx = new SprContext();
            }

            if (uRecursionLevel >= SprEngine.MaxRecursionDepth)
            {
                Debug.Assert(false);                 // Most likely a recursive reference
                return(string.Empty);                // Do not return strText (endless loop)
            }

            string   str = strText;
            MainForm mf  = Program.MainForm;

            bool bExt = ((ctx.Flags & (SprCompileFlags.ExtActive |
                                       SprCompileFlags.ExtNonActive)) != SprCompileFlags.None);

            if (bExt && (SprEngine.FilterCompilePre != null))
            {
                SprEventArgs args = new SprEventArgs(str, ctx.Clone());
                SprEngine.FilterCompilePre(null, args);
                str = args.Text;
            }

            if ((ctx.Flags & SprCompileFlags.Comments) != SprCompileFlags.None)
            {
                str = RemoveComments(str);
            }

            // The following realizes {T-CONV:/Text/Raw/}, which should be
            // one of the first transformations (except comments)
            if ((ctx.Flags & SprCompileFlags.TextTransforms) != SprCompileFlags.None)
            {
                str = PerformTextTransforms(str, ctx, uRecursionLevel);
            }

            if ((ctx.Flags & SprCompileFlags.Run) != SprCompileFlags.None)
            {
                str = RunCommands(str, ctx, uRecursionLevel);
            }

            if ((ctx.Flags & SprCompileFlags.DataActive) != SprCompileFlags.None)
            {
                str = PerformClipboardCopy(str, ctx, uRecursionLevel);
            }

            if (((ctx.Flags & SprCompileFlags.DataNonActive) != SprCompileFlags.None) &&
                (str.IndexOf(@"{CLIPBOARD}", SprEngine.ScMethod) >= 0))
            {
                string strCb = null;
                try { strCb = ClipboardUtil.GetText(); }
                catch (Exception) { Debug.Assert(false); }
                str = Fill(str, @"{CLIPBOARD}", strCb ?? string.Empty, ctx, null);
            }

            if ((ctx.Flags & SprCompileFlags.AppPaths) != SprCompileFlags.None)
            {
                str = AppLocator.FillPlaceholders(str, ctx);
            }

            if (ctx.Entry != null)
            {
                if ((ctx.Flags & SprCompileFlags.PickChars) != SprCompileFlags.None)
                {
                    str = ReplacePickPw(str, ctx, uRecursionLevel);
                }

                if ((ctx.Flags & SprCompileFlags.EntryStrings) != SprCompileFlags.None)
                {
                    str = FillEntryStrings(str, ctx, uRecursionLevel);
                }

                if ((ctx.Flags & SprCompileFlags.EntryStringsSpecial) != SprCompileFlags.None)
                {
                    str = FillEntryStringsSpecial(str, ctx, uRecursionLevel);
                }

                if (((ctx.Flags & SprCompileFlags.EntryProperties) != SprCompileFlags.None) &&
                    (str.IndexOf(@"{UUID}", SprEngine.ScMethod) >= 0))
                {
                    str = Fill(str, @"{UUID}", ctx.Entry.Uuid.ToHexString(), ctx, null);
                }

                if (((ctx.Flags & SprCompileFlags.PasswordEnc) != SprCompileFlags.None) &&
                    (str.IndexOf(@"{PASSWORD_ENC}", SprEngine.ScMethod) >= 0))
                {
                    string strPwCmp = SprEngine.CompileInternal(@"{PASSWORD}",
                                                                ctx.WithoutContentTransformations(), uRecursionLevel + 1);
                    str = Fill(str, @"{PASSWORD_ENC}", StrUtil.EncryptString(
                                   strPwCmp), ctx, null);
                }

                PwGroup pg = ctx.Entry.ParentGroup;
                if (((ctx.Flags & SprCompileFlags.Group) != SprCompileFlags.None) &&
                    (pg != null))
                {
                    str = FillGroupPlh(str, @"{GROUP", pg, ctx, uRecursionLevel);
                }
            }

            if ((ctx.Flags & SprCompileFlags.Paths) != SprCompileFlags.None)
            {
                if (mf != null)
                {
                    PwGroup pgSel = mf.GetSelectedGroup();
                    if (pgSel != null)
                    {
                        str = FillGroupPlh(str, @"{GROUP_SEL", pgSel, ctx, uRecursionLevel);
                    }
                }

                str = Fill(str, @"{APPDIR}", UrlUtil.GetFileDirectory(
                               WinUtil.GetExecutable(), false, false), ctx, uRecursionLevel);

                str = Fill(str, @"{ENV_DIRSEP}", Path.DirectorySeparatorChar.ToString(),
                           ctx, null);

                string strPF86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
                if (string.IsNullOrEmpty(strPF86))
                {
                    strPF86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                }
                if (strPF86 != null)
                {
                    str = Fill(str, @"{ENV_PROGRAMFILES_X86}", strPF86, ctx, uRecursionLevel);
                }
                else
                {
                    Debug.Assert(false);
                }

                if (ctx.Database != null)
                {
                    string strPath = ctx.Database.IOConnectionInfo.Path;
                    string strDir  = UrlUtil.GetFileDirectory(strPath, false, false);
                    string strName = UrlUtil.GetFileName(strPath);

                    // For backward compatibility only
                    str = Fill(str, @"{DOCDIR}", strDir, ctx, uRecursionLevel);

                    str = Fill(str, @"{DB_PATH}", strPath, ctx, uRecursionLevel);
                    str = Fill(str, @"{DB_DIR}", strDir, ctx, uRecursionLevel);
                    str = Fill(str, @"{DB_NAME}", strName, ctx, uRecursionLevel);
                    str = Fill(str, @"{DB_BASENAME}", UrlUtil.StripExtension(
                                   strName), ctx, uRecursionLevel);
                    str = Fill(str, @"{DB_EXT}", UrlUtil.GetExtension(
                                   strPath), ctx, uRecursionLevel);
                }
            }

            if ((ctx.Flags & SprCompileFlags.AutoType) != SprCompileFlags.None)
            {
                // Use Bksp instead of Del (in order to avoid Ctrl+Alt+Del);
                // https://sourceforge.net/p/keepass/discussion/329220/thread/4f1aa6b8/
                str = StrUtil.ReplaceCaseInsensitive(str, @"{CLEARFIELD}",
                                                     @"{HOME}+({END}){BKSP}{DELAY 50}");
            }

            if (((ctx.Flags & SprCompileFlags.DateTime) != SprCompileFlags.None) &&
                (str.IndexOf(@"{DT_", SprEngine.ScMethod) >= 0))
            {
                DateTime dtNow = DateTime.UtcNow;
                str = Fill(str, @"{DT_UTC_YEAR}", dtNow.Year.ToString("D4"),
                           ctx, null);
                str = Fill(str, @"{DT_UTC_MONTH}", dtNow.Month.ToString("D2"),
                           ctx, null);
                str = Fill(str, @"{DT_UTC_DAY}", dtNow.Day.ToString("D2"),
                           ctx, null);
                str = Fill(str, @"{DT_UTC_HOUR}", dtNow.Hour.ToString("D2"),
                           ctx, null);
                str = Fill(str, @"{DT_UTC_MINUTE}", dtNow.Minute.ToString("D2"),
                           ctx, null);
                str = Fill(str, @"{DT_UTC_SECOND}", dtNow.Second.ToString("D2"),
                           ctx, null);
                str = Fill(str, @"{DT_UTC_SIMPLE}", dtNow.ToString("yyyyMMddHHmmss"),
                           ctx, null);

                dtNow = dtNow.ToLocalTime();
                str   = Fill(str, @"{DT_YEAR}", dtNow.Year.ToString("D4"),
                             ctx, null);
                str = Fill(str, @"{DT_MONTH}", dtNow.Month.ToString("D2"),
                           ctx, null);
                str = Fill(str, @"{DT_DAY}", dtNow.Day.ToString("D2"),
                           ctx, null);
                str = Fill(str, @"{DT_HOUR}", dtNow.Hour.ToString("D2"),
                           ctx, null);
                str = Fill(str, @"{DT_MINUTE}", dtNow.Minute.ToString("D2"),
                           ctx, null);
                str = Fill(str, @"{DT_SECOND}", dtNow.Second.ToString("D2"),
                           ctx, null);
                str = Fill(str, @"{DT_SIMPLE}", dtNow.ToString("yyyyMMddHHmmss"),
                           ctx, null);
            }

            if ((ctx.Flags & SprCompileFlags.References) != SprCompileFlags.None)
            {
                str = SprEngine.FillRefPlaceholders(str, ctx, uRecursionLevel);
            }

            if (((ctx.Flags & SprCompileFlags.EnvVars) != SprCompileFlags.None) &&
                (str.IndexOf('%') >= 0))
            {
                foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
                {
                    string strKey = (de.Key as string);
                    if (string.IsNullOrEmpty(strKey))
                    {
                        Debug.Assert(false); continue;
                    }

                    string strValue = (de.Value as string);
                    if (strValue == null)
                    {
                        Debug.Assert(false); strValue = string.Empty;
                    }

                    str = Fill(str, @"%" + strKey + @"%", strValue, ctx, uRecursionLevel);
                }
            }

            if ((ctx.Flags & SprCompileFlags.Env) != SprCompileFlags.None)
            {
                str = FillUriSpecial(str, ctx, @"{BASE", (ctx.Base ?? string.Empty),
                                     ctx.BaseIsEncoded, uRecursionLevel);
            }

            str = EntryUtil.FillPlaceholders(str, ctx, uRecursionLevel);

            if ((ctx.Flags & SprCompileFlags.PickChars) != SprCompileFlags.None)
            {
                str = ReplacePickChars(str, ctx, uRecursionLevel);
            }

            if (bExt && (SprEngine.FilterCompile != null))
            {
                SprEventArgs args = new SprEventArgs(str, ctx.Clone());
                SprEngine.FilterCompile(null, args);
                str = args.Text;
            }

            if (ctx.EncodeAsAutoTypeSequence)
            {
                str = StrUtil.NormalizeNewLines(str, false);
                str = str.Replace("\n", @"{ENTER}");
            }

            return(str);
        }
Example #11
0
        private static string RunCommands(string strText, SprContext ctx,
                                          uint uRecursionLevel)
        {
            string        str = strText;
            int           iStart;
            List <string> lParams;

            while (ParseAndRemovePlhWithParams(ref str, ctx, uRecursionLevel,
                                               @"{CMD:", out iStart, out lParams, false))
            {
                if (lParams.Count == 0)
                {
                    continue;
                }

                string strBaseRaw = null;
                if ((ctx != null) && (ctx.Base != null))
                {
                    if (ctx.BaseIsEncoded)
                    {
                        strBaseRaw = UntransformContent(ctx.Base, ctx);
                    }
                    else
                    {
                        strBaseRaw = ctx.Base;
                    }
                }

                string strCmd = WinUtil.CompileUrl((lParams[0] ?? string.Empty),
                                                   ((ctx != null) ? ctx.Entry : null), true, strBaseRaw, true);
                if (WinUtil.IsCommandLineUrl(strCmd))
                {
                    strCmd = WinUtil.GetCommandLineFromUrl(strCmd);
                }
                if (string.IsNullOrEmpty(strCmd))
                {
                    continue;
                }

                Process p = null;
                try
                {
                    StringComparison sc = StrUtil.CaseIgnoreCmp;

                    string strOpt = ((lParams.Count >= 2) ? lParams[1] :
                                     string.Empty);
                    Dictionary <string, string> d = SplitParams(strOpt);

                    ProcessStartInfo psi = new ProcessStartInfo();

                    string strApp, strArgs;
                    StrUtil.SplitCommandLine(strCmd, out strApp, out strArgs);
                    if (string.IsNullOrEmpty(strApp))
                    {
                        continue;
                    }
                    psi.FileName = strApp;
                    if (!string.IsNullOrEmpty(strArgs))
                    {
                        psi.Arguments = strArgs;
                    }

                    string strMethod  = GetParam(d, "m", "s");
                    bool   bShellExec = !strMethod.Equals("c", sc);
                    psi.UseShellExecute = bShellExec;

                    string strO    = GetParam(d, "o", (bShellExec ? "0" : "1"));
                    bool   bStdOut = strO.Equals("1", sc);
                    if (bStdOut)
                    {
                        psi.RedirectStandardOutput = true;
                    }

                    string strWS = GetParam(d, "ws", "n");
                    if (strWS.Equals("h", sc))
                    {
                        psi.CreateNoWindow = true;
                        psi.WindowStyle    = ProcessWindowStyle.Hidden;
                    }
                    else if (strWS.Equals("min", sc))
                    {
                        psi.WindowStyle = ProcessWindowStyle.Minimized;
                    }
                    else if (strWS.Equals("max", sc))
                    {
                        psi.WindowStyle = ProcessWindowStyle.Maximized;
                    }
                    else
                    {
                        Debug.Assert(psi.WindowStyle == ProcessWindowStyle.Normal);
                    }

                    string strVerb = GetParam(d, "v", null);
                    if (!string.IsNullOrEmpty(strVerb))
                    {
                        psi.Verb = strVerb;
                    }

                    bool bWait = GetParam(d, "w", "1").Equals("1", sc);

                    p = NativeLib.StartProcessEx(psi);
                    if (p == null)
                    {
                        Debug.Assert(false); continue;
                    }

                    if (bStdOut)
                    {
                        string strOut = (p.StandardOutput.ReadToEnd() ?? string.Empty);

                        // Remove trailing new-line characters, like $(...);
                        // https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
                        // https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html#Command-Substitution
                        strOut = strOut.TrimEnd('\r', '\n');

                        strOut = TransformContent(strOut, ctx);
                        str    = str.Insert(iStart, strOut);
                    }

                    if (bWait)
                    {
                        p.WaitForExit();
                    }
                }
                catch (Exception ex)
                {
                    string strMsg = strCmd + MessageService.NewParagraph + ex.Message;
                    MessageService.ShowWarning(strMsg);
                }
                finally
                {
                    try { if (p != null)
                          {
                              p.Dispose();
                          }
                    }
                    catch (Exception) { Debug.Assert(false); }
                }
            }

            return(str);
        }
Example #12
0
 private void OnBtnGetMore(object sender, EventArgs e)
 {
     WinUtil.OpenUrl(PwDefs.PluginsUrl, null);
 }
Example #13
0
        /// <summary>
        /// 公告工具:停止公告
        /// </summary>
        public static string GameNoticeStop(string taskid)
        {
            if (!WinUtil.IsNumber(taskid))
            {
                return("命令传输错误");
            }
            try
            {
                string sql = @"SELECT F_GameName,F_URInfo,F_TUseData FROM T_Tasks  WITH(NOLOCK)  where F_ID= " + taskid + "";

                DataSet ds = DbHelperSQL.Query(sql);

                if (ds == null || ds.Tables[0].Rows.Count == 0)
                {
                    return("此工单已经不存在");
                }
                DataRow dr = ds.Tables[0].Rows[0];

                string   area    = dr["F_TUseData"].ToString();
                string[] TareaAs = area.Split('|');
                foreach (string TareaA in TareaAs)
                {
                    string[] TareaBs = TareaA.Split(',');
                    if (TareaBs.Length != 3)
                    {
                        return("公告范围参数不正确");
                    }
                }

                string   reback = "";
                string[] areaAs = area.Split('|');
                foreach (string areaA in areaAs)
                {
                    string[] areaBs = areaA.Split(',');
                    if (areaBs.Length == 3)
                    {
                        reback += "游戏大区" + areaBs[0] + ">>";
                        string url = GetWebServUrlID(dr["F_GameName"].ToString(), areaBs[0]);
                        if (url.Trim().Length == 0)
                        {
                            reback += "服务器:WEBSERVICE地址配置不正确;";
                        }
                        else
                        {
                            webserv.Url         = url;
                            webserv.Credentials = System.Net.CredentialCache.DefaultCredentials;
                            reback += webserv.GameNoticeStop(taskid);
                        }
                    }
                }
                if (reback.Replace("true", "成功").Length + areaAs.Length * 2 == reback.Length)
                {
                    reback = "true";
                }
                return(reback);
            }
            catch (System.Exception ex)
            {
                ShareData.Log.Error(ex);
                return(ex.Message);
            }
        }
Example #14
0
        /// <summary>
        /// Loads the working directory set by the user
        /// </summary>
        private void ShowSettings(Configuration pConfig = null)
        {
            Configuration config = null;

            if (pConfig == null)
            {
                config = Configuration.GetNewInstance();
            }
            else
            {
                config = pConfig;
            }

            Epi.DataSets.Config.SettingsRow settings = config.Settings;

            try
            {
                autoTouchKeyboard.Checked = settings.AutoTouchKeyboard;
            }
            catch { }

            try
            {
                checkBoxSparseConnection.Checked = settings.SparseConnection;
            }
            catch { }

            // Representation of boolean values ...
            cmbYesAs.SelectedItem     = settings.RepresentationOfYes;
            cmbNoAs.SelectedItem      = settings.RepresentationOfNo;
            cmbMissingAs.SelectedItem = settings.RepresentationOfMissing;

            // HTML output options ...
            cbxShowPrompt.Checked     = settings.ShowCompletePrompt;
            cbxSelectCriteria.Checked = settings.ShowSelection;
            cbxPercents.Checked       = settings.ShowPercents;
            cbxGraphics.Checked       = settings.ShowGraphics;
            cbxHyperlinks.Checked     = settings.ShowHyperlinks;
            cbxTablesOutput.Checked   = settings.ShowTables;

            // Statistics Options
            WinUtil.SetSelectedRadioButton(settings.StatisticsLevel.ToString(), gbxStatistics);
            numericUpDownPrecision.Value = settings.PrecisionForStatistics;

            // Record Processing
            WinUtil.SetSelectedRadioButton(settings.RecordProcessingScope.ToString(), gbxProcessRecords);
            cbxIncludeMissing.Checked = settings.IncludeMissingValues;
            //settingsPanel.ShowSettings();
            txtWorkingDirectory.Text = config.Directories.Working;

            try
            {
                txtMapKey.Text = config.Settings.MapServiceKey;
            }
            catch { }

            try
            {
                txtIOCoding.Text = config.Settings.IOCodeFile;
            }
            catch { }

            object selectedItem = null;

            foreach (object item in lbxLanguages.Items)
            {
                if (((DropDownListItem)item).Key.Equals(config.Settings.Language))
                {
                    selectedItem = item;
                    break;
                }
            }
            lbxLanguages.SelectedItem          = selectedItem;
            cmbDatabaseFormat.SelectedValue    = config.Settings.DefaultDataDriver;
            cmbDefaultDataFormat.SelectedValue = config.Settings.DefaultDataFormatForRead;

            /*if (config.Settings.WebServiceAuthMode == null)
             * {
             *  rbUseWindows.Checked = false;
             *  rbNoWindows.Checked = true;
             * }
             * else
             * {*/

            if (config.Settings.WebServiceAuthMode == 1)
            {
                rbUseWindows.Checked = true;
            }
            else
            {
                rbNoWindows.Checked = true;
            }
            try
            {
                if (config.Settings.EWEServiceAuthMode == 1)
                {
                    EWErbUseWindows.Checked = true;
                }
                else
                {
                    EWErbNoWindows.Checked = true;
                }
            }
            catch (Exception)
            {
                Configuration _config = Configuration.GetNewInstance();
                _config.Settings.EWEServiceAuthMode = 0;     // 0 = Anon, 1 = NT
                Configuration.Save(_config);
            }
            //}
            try {
                if (config.Settings.WebServiceBindingMode == "wshttp")
                {
                    rbWSHTTP.Checked = true;
                }
                else
                {
                    rbBasic.Checked = true;
                }
                if (config.Settings.EWEServiceBindingMode == "wshttp")
                {
                    EWErbWSHTTP.Checked = true;
                }
                else
                {
                    EWErbBasic.Checked = true;
                }
            }
            catch (Exception ex)
            {
                rbBasic.Checked = true;
            }

            txtEndpoint.Text        = config.Settings.WebServiceEndpointAddress;
            EWEEndPointTextBox.Text = config.Settings.EWEServiceEndpointAddress;
        }
Example #15
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);
            }
        }
Example #16
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            GlobalWindowManager.AddWindow(this);
            if (m_bRedirectActivation)
            {
                Program.MainForm.RedirectActivationPush(this);
            }

            m_bInitializing = true;

            string strBannerDesc = WinUtil.CompactPath(m_ioInfo.Path, 45);

            m_bannerImage.Image = BannerFactory.CreateBanner(m_bannerImage.Width,
                                                             m_bannerImage.Height, BannerStyle.Default,
                                                             Properties.Resources.B48x48_KGPG_Key2, KPRes.EnterCompositeKey,
                                                             strBannerDesc);
            this.Icon = Properties.Resources.KeePass;

            FontUtil.AssignDefaultBold(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbKeyFile);
            FontUtil.AssignDefaultBold(m_cbUserAccount);

            m_ttRect.SetToolTip(m_cbHidePassword, KPRes.TogglePasswordAsterisks);
            m_ttRect.SetToolTip(m_btnOpenKeyFile, KPRes.KeyFileSelect);

            string strNameEx = UrlUtil.GetFileName(m_ioInfo.Path);

            if (strNameEx.Length > 0)
            {
                this.Text += " - " + strNameEx;
            }

            m_tbPassword.Text = string.Empty;
            m_secPassword.Attach(m_tbPassword, ProcessTextChangedPassword, true);

            m_cmbKeyFile.Items.Add(KPRes.NoKeyFileSpecifiedMeta);
            m_cmbKeyFile.SelectedIndex = 0;

            if ((Program.CommandLineArgs.FileName != null) &&
                (m_ioInfo.Path == Program.CommandLineArgs.FileName))
            {
                string str;

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.Password];
                if (str != null)
                {
                    m_cbPassword.Checked = true;
                    m_tbPassword.Text    = str;
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PasswordEncrypted];
                if (str != null)
                {
                    m_cbPassword.Checked = true;
                    m_tbPassword.Text    = StrUtil.DecryptString(str);
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.KeyFile];
                if (str != null)
                {
                    m_cbKeyFile.Checked = true;

                    m_cmbKeyFile.Items.Add(str);
                    m_cmbKeyFile.SelectedIndex = m_cmbKeyFile.Items.Count - 1;
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PreSelect];
                if (str != null)
                {
                    m_cbKeyFile.Checked = true;

                    m_cmbKeyFile.Items.Add(str);
                    m_cmbKeyFile.SelectedIndex = m_cmbKeyFile.Items.Count - 1;
                }
            }

            m_cbHidePassword.Checked = true;
            OnCheckedHidePassword(sender, e);

            Debug.Assert(m_cmbKeyFile.Text.Length != 0);

            m_btnExit.Enabled = m_bCanExit;
            m_btnExit.Visible = m_bCanExit;

            UIUtil.ApplyKeyUIFlags(Program.Config.UI.KeyPromptFlags,
                                   m_cbPassword, m_cbKeyFile, m_cbUserAccount, m_cbHidePassword);

            if ((Program.Config.UI.KeyPromptFlags & (ulong)AceKeyUIFlags.DisableKeyFile) != 0)
            {
                UIUtil.SetEnabled(m_cmbKeyFile, m_cbKeyFile.Checked);
                UIUtil.SetEnabled(m_btnOpenKeyFile, m_cbKeyFile.Checked);
            }

            CustomizeForScreenReader();
            EnableUserControls();

            m_bInitializing = false;

            // Local, but thread will continue to run anyway
            Thread th = new Thread(new ThreadStart(this.AsyncFormLoad));

            th.Start();

            this.BringToFront();
            this.Activate();
            m_tbPassword.Focus();
        }
Example #17
0
 private void OnTextLinkClicked(object sender, LinkClickedEventArgs e)
 {
     WinUtil.OpenUrl(e.LinkText, null);
 }
Example #18
0
        private static string Compile(string strTmpRoot, PlgxPluginInfo plgx,
                                      string strBuildPre, string strBuildPost)
        {
            if (strTmpRoot == null)
            {
                Debug.Assert(false); return(null);
            }

            RunBuildCommand(strBuildPre, UrlUtil.EnsureTerminatingSeparator(
                                strTmpRoot, false), null);

            PlgxCsprojLoader.LoadDefault(strTmpRoot, plgx);

            List <string> vCustomRefs = new List <string>();

            foreach (string strIncRefAsm in plgx.IncludedReferencedAssemblies)
            {
                string strSrcAsm = plgx.GetAbsPath(UrlUtil.ConvertSeparators(
                                                       strIncRefAsm));
                string strCached = PlgxCache.AddCacheFile(strSrcAsm, plgx);
                if (string.IsNullOrEmpty(strCached))
                {
                    throw new InvalidOperationException();
                }
                vCustomRefs.Add(strCached);
            }

            CompilerParameters cp = plgx.CompilerParameters;

            cp.OutputAssembly = UrlUtil.EnsureTerminatingSeparator(strTmpRoot, false) +
                                UrlUtil.GetFileName(PlgxCache.GetCacheFile(plgx, false, false));
            cp.GenerateExecutable      = false;
            cp.GenerateInMemory        = false;
            cp.IncludeDebugInformation = false;
            cp.TreatWarningsAsErrors   = false;
            cp.ReferencedAssemblies.Add(WinUtil.GetExecutable());
            foreach (string strCustomRef in vCustomRefs)
            {
                cp.ReferencedAssemblies.Add(strCustomRef);
            }

            cp.CompilerOptions = "-define:" + GetDefines();

            CompileEmbeddedRes(plgx);
            PrepareSourceFiles(plgx);

            string[] vCompilers;
            Version  vClr = Environment.Version;
            int      iClrMajor = vClr.Major, iClrMinor = vClr.Minor;

            if ((iClrMajor >= 5) || ((iClrMajor == 4) && (iClrMinor >= 5)))
            {
                vCompilers = new string[] {
                    null,
                    "v4.5",
                    "v4",                     // Suggested in CodeDomProvider.CreateProvider doc
                    "v4.0",                   // Suggested in community content of the above
                    "v4.0.30319",             // Deduced from file system
                    "v3.5"
                };
            }
            else if (iClrMajor == 4)            // 4.0
            {
                vCompilers = new string[] {
                    null,
                    "v4",                     // Suggested in CodeDomProvider.CreateProvider doc
                    "v4.0",                   // Suggested in community content of the above
                    "v4.0.30319",             // Deduced from file system
                    "v4.5",
                    "v3.5"
                };
            }
            else             // <= 3.5
            {
                vCompilers = new string[] {
                    null,
                    "v3.5",
                    "v4",                     // Suggested in CodeDomProvider.CreateProvider doc
                    "v4.0",                   // Suggested in community content of the above
                    "v4.0.30319",             // Deduced from file system
                    "v4.5"
                };
            }

            CompilerResults cr            = null;
            StringBuilder   sbCompilerLog = new StringBuilder();
            bool            bCompiled     = false;

            for (int iCmp = 0; iCmp < vCompilers.Length; ++iCmp)
            {
                if (CompileAssembly(plgx, out cr, vCompilers[iCmp]))
                {
                    bCompiled = true;
                    break;
                }

                if (cr != null)
                {
                    AppendCompilerResults(sbCompilerLog, vCompilers[iCmp], cr);
                }
            }

            if (!bCompiled)
            {
                if (Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null)
                {
                    SaveCompilerResults(plgx, sbCompilerLog);
                }

                throw new InvalidOperationException();
            }

            Program.TempFilesPool.Add(cr.PathToAssembly);

            Debug.Assert(cr.PathToAssembly == cp.OutputAssembly);
            string strCacheAsm = PlgxCache.AddCacheAssembly(cr.PathToAssembly, plgx);

            RunBuildCommand(strBuildPost, UrlUtil.EnsureTerminatingSeparator(
                                strTmpRoot, false), UrlUtil.GetFileDirectory(strCacheAsm, true, false));

            return(strCacheAsm);
        }
Example #19
0
 private void OnLinkDonate(object sender, LinkLabelLinkClickedEventArgs e)
 {
     WinUtil.OpenUrl(PwDefs.DonationsUrl, null);
     this.Close();
 }
Example #20
0
        private void OnFormLoad(object sender, EventArgs e)
        {
            m_bInitializing = true;

            GlobalWindowManager.AddWindow(this);
            // if(m_bRedirectActivation) Program.MainForm.RedirectActivationPush(this);

            string strBannerTitle = (!string.IsNullOrEmpty(m_strCustomTitle) ?
                                     m_strCustomTitle : KPRes.EnterCompositeKey);
            string strBannerDesc = WinUtil.CompactPath(m_ioInfo.Path, 45);

            BannerFactory.CreateBannerEx(this, m_bannerImage,
                                         Properties.Resources.B48x48_KGPG_Key2, strBannerTitle, strBannerDesc);
            this.Icon = AppIcons.Default;

            FontUtil.SetDefaultFont(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbPassword);
            FontUtil.AssignDefaultBold(m_cbKeyFile);
            FontUtil.AssignDefaultBold(m_cbUserAccount);

            UIUtil.ConfigureToolTip(m_ttRect);
            // m_ttRect.SetToolTip(m_cbHidePassword, KPRes.TogglePasswordAsterisks);
            m_ttRect.SetToolTip(m_btnOpenKeyFile, KPRes.KeyFileSelect);

            PwInputControlGroup.ConfigureHideButton(m_cbHidePassword, m_ttRect);

            string strStart = (!string.IsNullOrEmpty(m_strCustomTitle) ?
                               m_strCustomTitle : KPRes.OpenDatabase);
            string strNameEx = UrlUtil.GetFileName(m_ioInfo.Path);

            if (!string.IsNullOrEmpty(strNameEx))
            {
                this.Text = strStart + " - " + strNameEx;
            }
            else
            {
                this.Text = strStart;
            }

            // Must be set manually due to possible object override
            m_tbPassword.TextChanged += this.ProcessTextChangedPassword;

            // m_cmbKeyFile.OrderedImageList = m_lKeyFileImages;
            AddKeyFileSuggPriv(KPRes.NoKeyFileSpecifiedMeta, true);

            // Do not directly compare with Program.CommandLineArgs.FileName,
            // because this may be a relative path instead of an absolute one
            string strCmdLineFile = Program.CommandLineArgs.FileName;

            if ((strCmdLineFile != null) && (Program.MainForm != null))
            {
                strCmdLineFile = Program.MainForm.IocFromCommandLine().Path;
            }
            if ((strCmdLineFile != null) && strCmdLineFile.Equals(m_ioInfo.Path,
                                                                  StrUtil.CaseIgnoreCmp))
            {
                string str;

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.Password];
                if (str != null)
                {
                    m_cbPassword.Checked = true;
                    m_tbPassword.Text    = str;
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PasswordEncrypted];
                if (str != null)
                {
                    m_cbPassword.Checked = true;
                    m_tbPassword.Text    = StrUtil.DecryptString(str);
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PasswordStdIn];
                if (str != null)
                {
                    ProtectedString ps = KeyUtil.ReadPasswordStdIn(true);
                    if (ps != null)
                    {
                        m_cbPassword.Checked = true;
                        m_tbPassword.TextEx  = ps;
                    }
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.KeyFile];
                if (str != null)
                {
                    m_cbKeyFile.Checked = true;
                    AddKeyFileSuggPriv(str, true);
                }

                str = Program.CommandLineArgs[AppDefs.CommandLineOptions.PreSelect];
                if (str != null)
                {
                    m_cbKeyFile.Checked = true;
                    AddKeyFileSuggPriv(str, true);
                }
            }

            m_cbHidePassword.Checked = true;
            OnCheckedHidePassword(sender, e);

            Debug.Assert(m_cmbKeyFile.Text.Length != 0);

            m_btnExit.Enabled = m_bCanExit;
            m_btnExit.Visible = m_bCanExit;

            ulong uKpf = Program.Config.UI.KeyPromptFlags;

            UIUtil.ApplyKeyUIFlags(uKpf, m_cbPassword, m_cbKeyFile,
                                   m_cbUserAccount, m_cbHidePassword);

            if ((uKpf & (ulong)AceKeyUIFlags.DisableKeyFile) != 0)
            {
                UIUtil.SetEnabled(m_cmbKeyFile, m_cbKeyFile.Checked);
                UIUtil.SetEnabled(m_btnOpenKeyFile, m_cbKeyFile.Checked);
            }

            if (((uKpf & (ulong)AceKeyUIFlags.CheckPassword) != 0) ||
                ((uKpf & (ulong)AceKeyUIFlags.UncheckPassword) != 0))
            {
                m_bPwStatePreset = true;
            }
            if (((uKpf & (ulong)AceKeyUIFlags.CheckUserAccount) != 0) ||
                ((uKpf & (ulong)AceKeyUIFlags.UncheckUserAccount) != 0))
            {
                m_bUaStatePreset = true;
            }

            CustomizeForScreenReader();
            EnableUserControls();

            m_bInitializing = false;

            // E.g. command line options have higher priority
            m_bCanModKeyFile = (m_cmbKeyFile.SelectedIndex == 0);

            m_aKeyAssoc = Program.Config.Defaults.GetKeySources(m_ioInfo);
            if (m_aKeyAssoc != null)
            {
                if (m_aKeyAssoc.Password && !m_bPwStatePreset)
                {
                    m_cbPassword.Checked = true;
                }

                if (m_aKeyAssoc.KeyFilePath.Length > 0)
                {
                    AddKeyFileSuggPriv(m_aKeyAssoc.KeyFilePath, null);
                }

                if (m_aKeyAssoc.UserAccount && !m_bUaStatePreset)
                {
                    m_cbUserAccount.Checked = true;
                }
            }

            foreach (KeyProvider prov in Program.KeyProviderPool)
            {
                AddKeyFileSuggPriv(prov.Name, null);
            }

            // Local, but thread will continue to run anyway
            Thread th = new Thread(new ThreadStart(this.AsyncFormLoad));

            th.Start();
            // ThreadPool.QueueUserWorkItem(new WaitCallback(this.AsyncFormLoad));

            this.BringToFront();
            this.Activate();
            // UIUtil.SetFocus(m_tbPassword, this); // See OnFormShown
        }
Example #21
0
        static void Main(string[] args)
        {
            DesignMode = false;             // The designer doesn't call Main()

            CommandLineArgs = new CommandLineArgs(args);

            try
            {
                DpiUtil.ConfigureProcess();
                DpiUtil.TrySetDpiFromCurrentDesktop();
            }
            catch
            {
                // ignored
            }

            MonoSpaceFont = new FontEx
            {
                Font   = new Font("Courier New", DpiUtil.ScaleIntX(13), GraphicsUnit.Pixel),
                Width  = DpiUtil.ScaleIntX(8),
                Height = DpiUtil.ScaleIntY(16)
            };

            NativeMethods.EnableDebugPrivileges();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;

            Settings = SettingsSerializer.Load();
            Logger   = new GuiLogger();

            if (!NativeMethods.IsUnix() && Settings.RunAsAdmin && !WinUtil.IsAdministrator)
            {
                WinUtil.RunElevated(Process.GetCurrentProcess().MainModule?.FileName, args.Length > 0 ? string.Join(" ", args) : null);
                return;
            }

#if !DEBUG
            try
            {
#endif
            using (var coreFunctions = new CoreFunctionsManager())
            {
                RemoteProcess = new RemoteProcess(coreFunctions);

                MainForm = new MainForm();

                Application.Run(MainForm);

                RemoteProcess.Dispose();
            }
#if !DEBUG
        }

        catch (Exception ex)
        {
            ShowException(ex);
        }
#endif

            SettingsSerializer.Save(Settings);
        }
Example #22
0
 private static void InitializeStatic()
 {
     m_strAppExePath = WinUtil.GetExecutable();
 }
Example #23
0
        private static string RunCommands(string strText, SprContext ctx,
                                          uint uRecursionLevel)
        {
            string        str = strText;
            int           iStart;
            List <string> lParams;

            while (ParseAndRemovePlhWithParams(ref str, ctx, uRecursionLevel,
                                               @"{CMD:", out iStart, out lParams, true))
            {
                if (lParams.Count == 0)
                {
                    continue;
                }
                string strCmd = lParams[0];
                if (string.IsNullOrEmpty(strCmd))
                {
                    continue;
                }

                Process p = null;
                try
                {
                    StringComparison sc = StrUtil.CaseIgnoreCmp;

                    string strOpt = ((lParams.Count >= 2) ? lParams[1] :
                                     string.Empty);
                    Dictionary <string, string> d = SplitParams(strOpt);

                    ProcessStartInfo psi = new ProcessStartInfo();

                    string strApp, strArgs;
                    StrUtil.SplitCommandLine(strCmd, out strApp, out strArgs);
                    strApp = WinUtil.CompileUrl((strApp ?? string.Empty),
                                                ((ctx != null) ? ctx.Entry : null), true, null);
                    if (string.IsNullOrEmpty(strApp))
                    {
                        continue;
                    }
                    psi.FileName = strApp;
                    if (!string.IsNullOrEmpty(strArgs))
                    {
                        psi.Arguments = strArgs;
                    }

                    string strMethod  = GetParam(d, "m", "s");
                    bool   bShellExec = !strMethod.Equals("c", sc);
                    psi.UseShellExecute = bShellExec;

                    string strO    = GetParam(d, "o", (bShellExec ? "0" : "1"));
                    bool   bStdOut = strO.Equals("1", sc);
                    if (bStdOut)
                    {
                        psi.RedirectStandardOutput = true;
                    }

                    string strWS = GetParam(d, "ws", "n");
                    if (strWS.Equals("h", sc))
                    {
                        psi.CreateNoWindow = true;
                        psi.WindowStyle    = ProcessWindowStyle.Hidden;
                    }
                    else if (strWS.Equals("min", sc))
                    {
                        psi.WindowStyle = ProcessWindowStyle.Minimized;
                    }
                    else if (strWS.Equals("max", sc))
                    {
                        psi.WindowStyle = ProcessWindowStyle.Maximized;
                    }
                    else
                    {
                        Debug.Assert(psi.WindowStyle == ProcessWindowStyle.Normal);
                    }

                    string strVerb = GetParam(d, "v", null);
                    if (!string.IsNullOrEmpty(strVerb))
                    {
                        psi.Verb = strVerb;
                    }

                    bool bWait = GetParam(d, "w", "1").Equals("1", sc);

                    p = Process.Start(psi);
                    if (p == null)
                    {
                        Debug.Assert(false); continue;
                    }

                    if (bStdOut)
                    {
                        string strOut = p.StandardOutput.ReadToEnd();
                        strOut = TransformContent(strOut, ctx);
                        str    = str.Insert(iStart, strOut);
                    }

                    if (bWait)
                    {
                        p.WaitForExit();
                    }
                }
                catch (Exception ex)
                {
                    string strMsg = strCmd + MessageService.NewParagraph + ex.Message;
                    MessageService.ShowWarning(strMsg);
                }
                finally
                {
                    try { if (p != null)
                          {
                              p.Dispose();
                          }
                    }
                    catch (Exception) { Debug.Assert(false); }
                }
            }

            return(str);
        }
Example #24
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.Diagnostics;", ref t);
            AppendLine(sb, "using System.Xml;", 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);
            }
        }
Example #25
0
        private static string ReadFile(BinaryReader br, PlgxPluginInfo plgx,
                                       IStatusLogger slStatus)
        {
            uint uSig1    = br.ReadUInt32();
            uint uSig2    = br.ReadUInt32();
            uint uVersion = br.ReadUInt32();

            if ((uSig1 != PlgxSignature1) || (uSig2 != PlgxSignature2))
            {
                return(null);                // Ignore file, don't throw
            }
            if ((uVersion & PlgxVersionMask) > (PlgxVersion & PlgxVersionMask))
            {
                throw new PlgxException(KLRes.FileVersionUnsupported);
            }

            string strPluginPath = null;
            string strTmpRoot = null;
            bool?  obContent = null;
            string strBuildPre = null, strBuildPost = null;

            while (true)
            {
                KeyValuePair <ushort, byte[]> kvp = ReadObject(br);

                if (kvp.Key == PlgxEOF)
                {
                    break;
                }
                else if (kvp.Key == PlgxFileUuid)
                {
                    plgx.FileUuid = new PwUuid(kvp.Value);
                }
                else if (kvp.Key == PlgxBaseFileName)
                {
                    plgx.BaseFileName = StrUtil.Utf8.GetString(kvp.Value);
                }
                else if (kvp.Key == PlgxCreationTime)
                {
                }                                                        // Ignore
                else if (kvp.Key == PlgxGeneratorName)
                {
                }
                else if (kvp.Key == PlgxGeneratorVersion)
                {
                }
                else if (kvp.Key == PlgxPrereqKP)
                {
                    ulong uReq = MemUtil.BytesToUInt64(kvp.Value);
                    if (uReq > PwDefs.FileVersion64)
                    {
                        throw new PlgxException(KLRes.FileNewVerReq);
                    }
                }
                else if (kvp.Key == PlgxPrereqNet)
                {
                    ulong uReq  = MemUtil.BytesToUInt64(kvp.Value);
                    ulong uInst = WinUtil.GetMaxNetFrameworkVersion();
                    if ((uInst != 0) && (uReq > uInst))
                    {
                        throw new PlgxException(KPRes.NewerNetRequired);
                    }
                }
                else if (kvp.Key == PlgxPrereqOS)
                {
                    string strOS  = "," + WinUtil.GetOSStr() + ",";
                    string strReq = "," + StrUtil.Utf8.GetString(kvp.Value) + ",";
                    if (strReq.IndexOf(strOS, StrUtil.CaseIgnoreCmp) < 0)
                    {
                        throw new PlgxException(KPRes.PluginOperatingSystemUnsupported);
                    }
                }
                else if (kvp.Key == PlgxPrereqPtr)
                {
                    uint uReq = MemUtil.BytesToUInt32(kvp.Value);
                    if (uReq > (uint)IntPtr.Size)
                    {
                        throw new PlgxException(KPRes.PluginOperatingSystemUnsupported);
                    }
                }
                else if (kvp.Key == PlgxBuildPre)
                {
                    strBuildPre = StrUtil.Utf8.GetString(kvp.Value);
                }
                else if (kvp.Key == PlgxBuildPost)
                {
                    strBuildPost = StrUtil.Utf8.GetString(kvp.Value);
                }
                else if (kvp.Key == PlgxBeginContent)
                {
                    if (obContent.HasValue)
                    {
                        throw new PlgxException(KLRes.FileCorrupted);
                    }

                    string strCached = PlgxCache.GetCacheFile(plgx, true, false);
                    if (!string.IsNullOrEmpty(strCached) && plgx.AllowCached)
                    {
                        strPluginPath = strCached;
                        break;
                    }

                    if (slStatus != null)
                    {
                        slStatus.SetText(KPRes.PluginsCompilingAndLoading,
                                         LogStatusType.Info);
                    }

                    obContent = true;
                    if (plgx.LogStream != null)
                    {
                        plgx.LogStream.WriteLine("Content:");
                    }
                }
                else if (kvp.Key == PlgxFile)
                {
                    if (!obContent.HasValue || !obContent.Value)
                    {
                        throw new PlgxException(KLRes.FileCorrupted);
                    }

                    if (strTmpRoot == null)
                    {
                        strTmpRoot = CreateTempDirectory();
                    }
                    ExtractFile(kvp.Value, strTmpRoot, plgx);
                }
                else if (kvp.Key == PlgxEndContent)
                {
                    if (!obContent.HasValue || !obContent.Value)
                    {
                        throw new PlgxException(KLRes.FileCorrupted);
                    }

                    obContent = false;
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            if ((strPluginPath == null) && plgx.AllowCompile)
            {
                strPluginPath = Compile(strTmpRoot, plgx, strBuildPre, strBuildPost);
            }

            return(strPluginPath);
        }
Example #26
0
 private void FiddlerApplication_AfterSessionComplete(Session oS)
 {
     if (oS.responseBodyBytes.Length < Settings.SessionSizeLimit)
     {
         sessions.Add(oS);
     }
     if (oS.responseCode == 404 && oS.HostnameIs("cdn.wiiuusbhelper.com"))
     {
         string path     = oS.PathAndQuery;
         string fileName = Path.GetFileName(path);
         if (path.StartsWith("/res/emulators/") && !File.Exists(Path.Combine("\\emulators", fileName)))
         {
             string noExt = Path.GetFileNameWithoutExtension(fileName);
             if (Enum.TryParse(noExt, out EmulatorConfiguration.Emulator emulator))
             {
                 new Thread(() =>
                 {
                     // Get rid of the exception caused by not finding the file
                     int pid       = Program.GetHelperProcess().Id;
                     int lastCount = -1;
                     while (true)
                     {
                         int newCount = WinUtil.GetWindowCount(pid);
                         if (lastCount != -1 && lastCount != newCount)
                         {
                             break;
                         }
                         lastCount = newCount;
                         Thread.Sleep(30);
                     }
                     WinUtil.CloseWindow(WinUtil.GetForegroundWindow());
                     DialogResult result = MessageBox.Show("It appears you are trying to set-up a game with " + noExt + ", but it has not been downloaded yet.\nWould you like to download it?", "Emulator missing", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                     if (result == DialogResult.Yes)
                     {
                         EmulatorConfiguration config       = EmulatorConfiguration.GetConfiguration(emulator);
                         EmulatorConfigurationDialog dialog = new EmulatorConfigurationDialog(config);
                         Program.ShowChildDialog(dialog);
                     }
                 }).Start();
             }
         }
         else if (path == "/res/prerequisites/java.exe")
         {
             DialogResult result = MessageBox.Show("To download this game you need Java installed on your computer. Install now?\nCancel the download to prevent additional messages.", "Java required", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
             if (result == DialogResult.Yes)
             {
                 Process.Start("https://www.java.com/en/download/");
             }
         }
     }
     else if (oS.HostnameIs("application.wiiuusbhelper.com") && oS.PathAndQuery == "/res/db/data.usb")
     {
         MessageBox.Show("You're using a legacy version of Wii U USB Helper.\nSupport for this version is limited which means some features may not work correctly.\nPlease update to a more recent version for better stability.", "Legacy version detected", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
     }
     else if (oS.HostnameIs("cloud.wiiuusbhelper.com") && oS.PathAndQuery == "/saves/login.php" && Settings.ShowCloudWarning && !shownCloudWarning)
     {
         shownCloudWarning = true;
         var cloudWarning = new CheckboxDialog("The cloud save backup service is hosted by Willzor and is in no way affiliated to USBHelperLauncher. We cannot guarantee the continuity of these services and as such advise against relying on them.", "Do not show this again.", "Cloud service warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         new Thread(() => Program.ShowChildDialog(cloudWarning)).Start();
         Settings.ShowCloudWarning = !cloudWarning.Checked;
         Settings.Save();
     }
 }
Example #27
0
 private void OnLinkHomepage(object sender, LinkLabelLinkClickedEventArgs e)
 {
     WinUtil.OpenUrl(PwDefs.HomepageUrl, null);
     this.Close();
 }
Example #28
0
 private void OnBtnGetMore(object sender, EventArgs e)
 {
     WinUtil.OpenUrl(PwDefs.TranslationsUrl, null);
     this.DialogResult = DialogResult.Cancel;
 }
Example #29
0
        private static void ExportEntry(PwEntry pe, string strDir, PwExportInfo pxi)
        {
            PwDatabase pd  = ((pxi != null) ? pxi.ContextDatabase : null);
            SprContext ctx = new SprContext(pe, pd, SprCompileFlags.NonActive, false, false);

            KeyValuePair <string, string>?okvpCmd = null;
            string strUrl = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.UrlField), ctx);

            if (WinUtil.IsCommandLineUrl(strUrl))
            {
                strUrl = WinUtil.GetCommandLineFromUrl(strUrl);

                if (!NativeLib.IsUnix())                // LNKs only supported on Windows
                {
                    string strApp, strArgs;
                    StrUtil.SplitCommandLine(strUrl, out strApp, out strArgs);

                    if (!string.IsNullOrEmpty(strApp))
                    {
                        okvpCmd = new KeyValuePair <string, string>(strApp, strArgs);
                    }
                }
            }
            if (string.IsNullOrEmpty(strUrl))
            {
                return;
            }
            bool bLnk = okvpCmd.HasValue;

            string strTitleCmp = SprEngine.Compile(pe.Strings.ReadSafe(PwDefs.TitleField), ctx);

            if (string.IsNullOrEmpty(strTitleCmp))
            {
                strTitleCmp = KPRes.Entry;
            }
            string strTitle = Program.Config.Defaults.WinFavsFileNamePrefix + strTitleCmp;

            string strSuffix = Program.Config.Defaults.WinFavsFileNameSuffix +
                               (bLnk ? ".lnk" : ".url");

            strSuffix = UrlUtil.FilterFileName(strSuffix);

            string strFileBase = (UrlUtil.EnsureTerminatingSeparator(strDir,
                                                                     false) + UrlUtil.FilterFileName(strTitle));
            string strFile = strFileBase + strSuffix;
            int    iFind   = 2;

            while (File.Exists(strFile))
            {
                strFile = strFileBase + " (" + iFind.ToString() + ")" + strSuffix;
                ++iFind;
            }

            if (!Directory.Exists(strDir))
            {
                try { Directory.CreateDirectory(strDir); }
                catch (Exception exDir)
                {
                    throw new Exception(strDir + MessageService.NewParagraph + exDir.Message);
                }

                WaitForDirCommit(strDir, true);
            }

            try
            {
                if (bLnk)
                {
                    int    ccMaxDesc = NativeMethods.INFOTIPSIZE - 1 - LnkDescSuffix.Length;
                    string strDesc   = StrUtil.CompactString3Dots(strUrl, ccMaxDesc) +
                                       LnkDescSuffix;

                    ShellLinkEx sl = new ShellLinkEx(okvpCmd.Value.Key,
                                                     okvpCmd.Value.Value, strDesc);
                    sl.Save(strFile);
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine(@"[InternetShortcut]");
                    sb.AppendLine(@"URL=" + strUrl);                     // No additional line break
                    sb.AppendLine(@"[" + PwDefs.ShortProductName + @"]");
                    sb.AppendLine(IniTypeKey + @"=" + IniTypeValue);
                    // Terminating line break is important

                    File.WriteAllText(strFile, sb.ToString(), Encoding.Default);
                }
            }
            catch (Exception exWrite)
            {
                throw new Exception(strFile + MessageService.NewParagraph + exWrite.Message);
            }
        }
Example #30
0
        public static void Main(string[] args)
        {
#if DEBUG
            // Program.DesignMode should not be queried before executing
            // Main (e.g. by a static Control) when running the program
            // normally
            Debug.Assert(!m_bDesignModeQueried);
#endif
            m_bDesignMode = false;             // Designer doesn't call Main method

            m_cmdLineArgs = new CommandLineArgs(args);

            // Before loading the configuration
            string strWaDisable = m_cmdLineArgs[
                AppDefs.CommandLineOptions.WorkaroundDisable];
            if (!string.IsNullOrEmpty(strWaDisable))
            {
                MonoWorkarounds.SetEnabled(strWaDisable, false);
            }

            DpiUtil.ConfigureProcess();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.DoEvents();             // Required

#if DEBUG
            string strInitialWorkDir = WinUtil.GetWorkingDirectory();
#endif

            if (!CommonInit())
            {
                CommonTerminate(); return;
            }

            if (m_appConfig.Application.Start.PluginCacheClearOnce)
            {
                PlgxCache.Clear();
                m_appConfig.Application.Start.PluginCacheClearOnce = false;
                AppConfigSerializer.Save(Program.Config);
            }

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtRegister] != null)
            {
                ShellUtil.RegisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId,
                                            KPRes.FileExtName, WinUtil.GetExecutable(), PwDefs.ShortProductName, false);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtUnregister] != null)
            {
                ShellUtil.UnregisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoad] != null)
            {
                // All important .NET assemblies are in memory now already
                try { SelfTest.Perform(); }
                catch (Exception) { Debug.Assert(false); }
                MainCleanUp();
                return;
            }

            /* if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadRegister] != null)
             * {
             *      string strPreLoadPath = WinUtil.GetExecutable().Trim();
             *      if(strPreLoadPath.StartsWith("\"") == false)
             *              strPreLoadPath = "\"" + strPreLoadPath + "\"";
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, strPreLoadPath,
             *              @"--" + AppDefs.CommandLineOptions.PreLoad, true);
             *      MainCleanUp();
             *      return;
             * }
             * if(m_cmdLineArgs[AppDefs.CommandLineOptions.PreLoadUnregister] != null)
             * {
             *      ShellUtil.RegisterPreLoad(AppDefs.PreLoadName, string.Empty,
             *              string.Empty, false);
             *      MainCleanUp();
             *      return;
             * } */
            if ((m_cmdLineArgs[AppDefs.CommandLineOptions.Help] != null) ||
                (m_cmdLineArgs[AppDefs.CommandLineOptions.HelpLong] != null))
            {
                AppHelp.ShowHelp(AppDefs.HelpTopics.CommandLine, null);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetUrlOverride];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigClearUrlOverride] != null)
            {
                Program.Config.Integration.UrlOverride = string.Empty;
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigGetUrlOverride] != null)
            {
                try
                {
                    string strFileOut = UrlUtil.EnsureTerminatingSeparator(
                        UrlUtil.GetTempPath(), false) + "KeePass_UrlOverride.tmp";
                    string strContent = ("[KeePass]\r\nKeeURLOverride=" +
                                         Program.Config.Integration.UrlOverride + "\r\n");
                    File.WriteAllText(strFileOut, strContent);
                }
                catch (Exception) { Debug.Assert(false); }
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ConfigSetLanguageFile] != null)
            {
                Program.Config.Application.LanguageFile = m_cmdLineArgs[
                    AppDefs.CommandLineOptions.ConfigSetLanguageFile];
                AppConfigSerializer.Save(Program.Config);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreate] != null)
            {
                PlgxPlugin.CreateFromCommandLine();
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.PlgxCreateInfo] != null)
            {
                PlgxPlugin.CreateInfoFile(m_cmdLineArgs.FileName);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ShowAssemblyInfo] != null)
            {
                MessageService.ShowInfo(Assembly.GetExecutingAssembly().ToString());
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXmlSerializerEx] != null)
            {
                XmlSerializerEx.GenerateSerializers(m_cmdLineArgs);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.MakeXspFile] != null)
            {
                XspArchive.CreateFile(m_cmdLineArgs.FileName, m_cmdLineArgs["d"]);
                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.Version] != null)
            {
                Console.WriteLine(PwDefs.ShortProductName + " " + PwDefs.VersionString);
                Console.WriteLine(PwDefs.Copyright);
                MainCleanUp();
                return;
            }
#if DEBUG
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.TestGfx] != null)
            {
                List <Image> lImg = new List <Image>();
                lImg.Add(Properties.Resources.B16x16_Browser);
                lImg.Add(Properties.Resources.B48x48_Keyboard_Layout);
                ImageArchive aHighRes = new ImageArchive();
                aHighRes.Load(Properties.Resources.Images_Client_HighRes);
                lImg.Add(aHighRes.GetForObject("C12_IRKickFlash"));
                if (File.Exists("Test.png"))
                {
                    lImg.Add(Image.FromFile("Test.png"));
                }
                Image img = GfxUtil.ScaleTest(lImg.ToArray());
                img.Save("GfxScaleTest.png", ImageFormat.Png);
                return;
            }
#endif
            // #if (DEBUG && !KeePassLibSD)
            // if(m_cmdLineArgs[AppDefs.CommandLineOptions.MakePopularPasswordTable] != null)
            // {
            //	PopularPasswords.MakeList();
            //	MainCleanUp();
            //	return;
            // }
            // #endif

            try { m_nAppMessage = NativeMethods.RegisterWindowMessage(m_strWndMsgID); }
            catch (Exception) { Debug.Assert(NativeLib.IsUnix()); }

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ExitAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Exit);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoType] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.AutoType);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.AutoTypeSelected] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.AutoTypeSelected);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.OpenEntryUrl] != null)
            {
                string strEntryUuid = m_cmdLineArgs[AppDefs.CommandLineOptions.Uuid];
                if (!string.IsNullOrEmpty(strEntryUuid))
                {
                    IpcParamEx ipUrl = new IpcParamEx(IpcUtilEx.CmdOpenEntryUrl,
                                                      strEntryUuid, null, null, null, null);
                    IpcUtilEx.SendGlobalMessage(ipUrl);
                }

                MainCleanUp();
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.LockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Lock);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.UnlockAll] != null)
            {
                BroadcastAppMessageAndCleanUp(AppMessage.Unlock);
                return;
            }
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent] != null)
            {
                string strName = m_cmdLineArgs[AppDefs.CommandLineOptions.IpcEvent];
                if (!string.IsNullOrEmpty(strName))
                {
                    string[] vFlt = KeyUtil.MakeCtxIndependent(args);

                    IpcParamEx ipEvent = new IpcParamEx(IpcUtilEx.CmdIpcEvent, strName,
                                                        CommandLineArgs.SafeSerialize(vFlt), null, null, null);
                    IpcUtilEx.SendGlobalMessage(ipEvent);
                }

                MainCleanUp();
                return;
            }

            // Mutex mSingleLock = TrySingleInstanceLock(AppDefs.MutexName, true);
            bool bSingleLock = GlobalMutexPool.CreateMutex(AppDefs.MutexName, true);
            // if((mSingleLock == null) && m_appConfig.Integration.LimitToSingleInstance)
            if (!bSingleLock && m_appConfig.Integration.LimitToSingleInstance)
            {
                ActivatePreviousInstance(args);
                MainCleanUp();
                return;
            }

            Mutex mGlobalNotify = TryGlobalInstanceNotify(AppDefs.MutexNameGlobal);

            AutoType.InitStatic();

            CustomMessageFilterEx cmfx = new CustomMessageFilterEx();
            Application.AddMessageFilter(cmfx);

#if DEBUG
            if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null)
            {
                throw new Exception(AppDefs.CommandLineOptions.DebugThrowException);
            }

            m_formMain = new MainForm();
            Application.Run(m_formMain);
#else
            try
            {
                if (m_cmdLineArgs[AppDefs.CommandLineOptions.DebugThrowException] != null)
                {
                    throw new Exception(AppDefs.CommandLineOptions.DebugThrowException);
                }

                m_formMain = new MainForm();
                Application.Run(m_formMain);
            }
            catch (Exception exPrg)
            {
                // Catch message box exception;
                // https://sourceforge.net/p/keepass/patches/86/
                try { MessageService.ShowFatal(exPrg); }
                catch (Exception) { Console.Error.WriteLine(exPrg.ToString()); }
            }
#endif

            Application.RemoveMessageFilter(cmfx);

            Debug.Assert(GlobalWindowManager.WindowCount == 0);
            Debug.Assert(MessageService.CurrentMessageCount == 0);

            MainCleanUp();

#if DEBUG
            string strEndWorkDir = WinUtil.GetWorkingDirectory();
            Debug.Assert(strEndWorkDir.Equals(strInitialWorkDir, StrUtil.CaseIgnoreCmp));
#endif

            if (mGlobalNotify != null)
            {
                GC.KeepAlive(mGlobalNotify);
            }
            // if(mSingleLock != null) { GC.KeepAlive(mSingleLock); }
        }