Ejemplo n.º 1
0
        private void OnCheckedChangedAutoRun(object sender, EventArgs e)
        {
            if (m_bLoadingSettings)
            {
                return;
            }

            bool bRequested = m_cbAutoRun.Checked;
            bool bCurrent   = ShellUtil.GetStartWithWindows(AppDefs.AutoRunName);

            if (bRequested != bCurrent)
            {
                string strPath = WinUtil.GetExecutable().Trim();
                if (strPath.StartsWith("\"") == false)
                {
                    strPath = "\"" + strPath + "\"";
                }
                ShellUtil.SetStartWithWindows(AppDefs.AutoRunName, strPath,
                                              bRequested);

                bool bNew = ShellUtil.GetStartWithWindows(AppDefs.AutoRunName);

                if (bNew != bRequested)
                {
                    m_cbAutoRun.Checked = bNew;
                }
            }
        }
Ejemplo n.º 2
0
        private void LoadIntegrationOptions()
        {
            Keys kAT = (Keys)Program.Config.Integration.HotKeyGlobalAutoType;

            m_hkGlobalAutoType.HotKey          = (kAT & Keys.KeyCode);
            m_hkGlobalAutoType.HotKeyModifiers = (kAT & Keys.Modifiers);
            m_hkGlobalAutoType.RenderHotKey();
            m_kPrevATHKKey = (m_hkGlobalAutoType.HotKey | m_hkGlobalAutoType.HotKeyModifiers);

            Keys kATS = (Keys)Program.Config.Integration.HotKeySelectedAutoType;

            m_hkSelectedAutoType.HotKey          = (kATS & Keys.KeyCode);
            m_hkSelectedAutoType.HotKeyModifiers = (kATS & Keys.Modifiers);
            m_hkSelectedAutoType.RenderHotKey();
            m_kPrevATSHKKey = (m_hkSelectedAutoType.HotKey | m_hkSelectedAutoType.HotKeyModifiers);

            Keys kSW = (Keys)Program.Config.Integration.HotKeyShowWindow;

            m_hkShowWindow.HotKey          = (kSW & Keys.KeyCode);
            m_hkShowWindow.HotKeyModifiers = (kSW & Keys.Modifiers);
            m_hkShowWindow.RenderHotKey();
            m_kPrevSWHKKey = (m_hkShowWindow.HotKey | m_hkShowWindow.HotKeyModifiers);

            m_cbAutoRun.Checked = ShellUtil.GetStartWithWindows(AppDefs.AutoRunName);
            m_cbSingleClickTrayAction.Checked = Program.Config.UI.TrayIcon.SingleClickDefault;

            string strOverride = Program.Config.Integration.UrlOverride;

            m_cbUrlOverride.Checked = (strOverride.Length > 0);
            m_tbUrlOverride.Text    = strOverride;
        }
Ejemplo n.º 3
0
        private static void LinkFloder()
        {
            string sourseFloder = EditorUtility.OpenFolderPanel("选择源文件夹", PathUtil.ApplicationBasePath, "");

            if (string.IsNullOrEmpty(sourseFloder))
            {
                throw new ArgumentException("无效的路径");
            }

            string toPath       = PathUtil.AssetPath2FullPath(AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]));
            string toFolderPath = Path.Combine(toPath, Path.GetFileName(sourseFloder));

            if (Directory.Exists(toFolderPath))
            {
                throw new ArgumentException("操作终止" + toPath + " 路径下已存在同名文件夹");
            }
            sourseFloder = sourseFloder.Replace("/", "\\");
            toFolderPath = toFolderPath.Replace("/", "\\");
            string cmd = string.Format("mklink /j {0} {1} & echo ok", toFolderPath, sourseFloder);

            Debug.Log(cmd);
            string result = ShellUtil.RunCmdCommand(cmd);

            if (result.Contains("<<===>>"))
            {
                AssetDatabase.Refresh();
            }
            else
            {
                Debug.LogError("操作可能出错,请自行检查");
            }
        }
Ejemplo n.º 4
0
        /// <summary>Initializes a new instance of the <see cref="ShellItem"/> class.</summary>
        /// <param name="parent">The parent Shell item.</param>
        /// <param name="name">The name of the child item.</param>
        public ShellItem(ShellItem parent, string name)
        {
            if (parent == null)
            {
                throw new ArgumentNullException(nameof(parent));
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (!parent.IsFolder)
            {
                throw new ArgumentException("Parent argument must be a folder.");
            }

            if (parent.IsFileSystem)
            {
                Init(ShellUtil.GetShellItemForPath(Path.Combine(parent.FileSystemPath, name)));
            }
            else
            {
                var   eaten = 0;
                PIDL  tempPidl;
                SFGAO attr = 0;
                parent.GetIShellFolder().ParseDisplayName(IntPtr.Zero, null, name, ref eaten, out tempPidl, ref attr);
                Init(tempPidl);
            }
        }
Ejemplo n.º 5
0
        public static void StartNewInstance(IWin32Window parent, bool requireAdmin, params string[] args)
        {
            string        str;
            StringBuilder builder = new StringBuilder();

            foreach (string str2 in args)
            {
                builder.Append(' ');
                if (str2.IndexOf(' ') != -1)
                {
                    builder.Append('"');
                }
                builder.Append(str2);
                if (str2.IndexOf(' ') != -1)
                {
                    builder.Append('"');
                }
            }
            if (builder.Length > 0)
            {
                str = builder.ToString(1, builder.Length - 1);
            }
            else
            {
                str = null;
            }
            ShellUtil.Execute(parent, Application.ExecutablePath, str, requireAdmin ? ExecutePrivilege.RequireAdmin : ExecutePrivilege.AsInvokerOrAsManifest, ExecuteWaitType.ReturnImmediately);
        }
Ejemplo n.º 6
0
        public void Start()
        {
            string str2;
            string str3;
            int    num;

            try
            {
                string path = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "paint.net"), "Optimization");
                Directory.CreateDirectory(path);
                string profile = ((this.args != null) && (this.args.Length >= 1)) ? "Startup.1.profile" : "Startup.0.profile";
                ProfileOptimization.SetProfileRoot(path);
                ProfileOptimization.StartProfile(profile);
            }
            catch (Exception)
            {
            }
            try
            {
                new Uri(Environment.GetEnvironmentVariable("windir"), UriKind.Absolute);
            }
            catch (Exception exception)
            {
                if (!(exception is UriFormatException) && !(exception is ArgumentNullException))
                {
                    throw;
                }
                string environmentVariable = Environment.GetEnvironmentVariable("systemroot");
                Environment.SetEnvironmentVariable("windir", environmentVariable);
            }
            string sxsRootDirPath = Path.Combine(Application.StartupPath, "SxS");

            ShellUtil.LoadUniversalCrt(sxsRootDirPath);
            ShellUtil.LoadVisualCppRuntime(sxsRootDirPath);
            ShellUtil.LoadOpenMP(sxsRootDirPath);
            Control.CheckForIllegalCrossThreadCalls = true;
            Application.SetCompatibleTextRenderingDefault(false);
            Application.EnableVisualStyles();
            Processor.LockLogicalCpuCount();
            string[] args = TryRemoveArg(this.args, "/sleep=", out str2);
            if (!string.IsNullOrWhiteSpace(str2) && int.TryParse(str2, out num))
            {
                Thread.Sleep(num);
            }
            args = TryRemoveArg(args, "/skipRepairAttempt", out str3);
            if ((str3 == null) && this.CheckForImportantFiles())
            {
                StartNewInstance(null, false, args);
            }
            else
            {
                string str4;
                args = TryRemoveArg(args, "/mutexName=", out str4);
                string mutexName = string.IsNullOrWhiteSpace(str4) ? "PaintDotNet" : str4;
                this.StartPart2(mutexName, args);
            }
        }
Ejemplo n.º 7
0
        public static IShellItem CreateShellItem(string path)
        {
            if (!PathFileExists(path))
            {
                return(null);
            }

            return(ShellUtil.GetShellItemForPath(path));
        }
Ejemplo n.º 8
0
        private void LoadIntegrationOptions()
        {
            Keys kAT = (Keys)Program.Config.Integration.HotKeyGlobalAutoType;

            m_hkGlobalAutoType.HotKey          = (kAT & Keys.KeyCode);
            m_hkGlobalAutoType.HotKeyModifiers = (kAT & Keys.Modifiers);
            m_hkGlobalAutoType.RenderHotKey();
            m_kPrevATHKKey = (m_hkGlobalAutoType.HotKey | m_hkGlobalAutoType.HotKeyModifiers);
            if (AppConfigEx.IsOptionEnforced(Program.Config.Integration, "HotKeyGlobalAutoType"))
            {
                m_hkGlobalAutoType.Enabled = false;
            }

            Keys kATS = (Keys)Program.Config.Integration.HotKeySelectedAutoType;

            m_hkSelectedAutoType.HotKey          = (kATS & Keys.KeyCode);
            m_hkSelectedAutoType.HotKeyModifiers = (kATS & Keys.Modifiers);
            m_hkSelectedAutoType.RenderHotKey();
            m_kPrevATSHKKey = (m_hkSelectedAutoType.HotKey | m_hkSelectedAutoType.HotKeyModifiers);
            if (AppConfigEx.IsOptionEnforced(Program.Config.Integration, "HotKeySelectedAutoType"))
            {
                m_hkSelectedAutoType.Enabled = false;
            }

            Keys kSW = (Keys)Program.Config.Integration.HotKeyShowWindow;

            m_hkShowWindow.HotKey          = (kSW & Keys.KeyCode);
            m_hkShowWindow.HotKeyModifiers = (kSW & Keys.Modifiers);
            m_hkShowWindow.RenderHotKey();
            m_kPrevSWHKKey = (m_hkShowWindow.HotKey | m_hkShowWindow.HotKeyModifiers);
            if (AppConfigEx.IsOptionEnforced(Program.Config.Integration, "HotKeyShowWindow"))
            {
                m_hkShowWindow.Enabled = false;
            }

            m_cbAutoRun.Checked = ShellUtil.GetStartWithWindows(AppDefs.AutoRunName);

            m_cbSingleClickTrayAction.Checked = Program.Config.UI.TrayIcon.SingleClickDefault;
            if (AppConfigEx.IsOptionEnforced(Program.Config.UI.TrayIcon, "SingleClickDefault"))
            {
                m_cbSingleClickTrayAction.Enabled = false;
            }

            string strOverride = Program.Config.Integration.UrlOverride;

            m_cbUrlOverride.Checked = (strOverride.Length > 0);
            m_tbUrlOverride.Text    = strOverride;
            if (AppConfigEx.IsOptionEnforced(Program.Config.Integration, "UrlOverride"))
            {
                m_cbUrlOverride.Enabled = false;
            }

            if (AppConfigEx.IsOptionEnforced(Program.Config.Integration, "UrlSchemeOverrides"))
            {
                m_btnSchemeOverrides.Enabled = false;
            }
        }
Ejemplo n.º 9
0
        private void OnLanguageChangedFromSettingsDialog(CultureInfo oldLanguage)
        {
            CultureInfo parent    = AppSettings.Instance.UI.Language.Value;
            Icon        icon      = PdnResources.GetImageResource("Icons.MenuUtilitiesLanguageIcon.png").Reference.ToIcon();
            string      str       = PdnResources.GetString("ConfirmLanguageDialog.Title");
            Image       image     = null;
            string      str2      = PdnResources.GetString("ConfirmLanguageDialog.IntroText");
            Image       reference = PdnResources.GetImageResource("Icons.RightArrowBlue.png").Reference;
            string      format    = PdnResources.GetString("ConfirmLanguageDialog.RestartTB.ExplanationText.Format");
            CultureInfo info2     = new CultureInfo("en-US");

            if (parent.Equals(info2))
            {
                parent = parent.Parent;
            }
            string     nativeName      = parent.NativeName;
            string     explanationText = string.Format(format, nativeName);
            TaskButton button          = new TaskButton(reference, PdnResources.GetString("ConfirmLanguageDialog.RestartTB.ActionText"), explanationText);
            TaskButton button2         = new TaskButton(PdnResources.GetImageResource("Icons.CancelIcon.png").Reference, PdnResources.GetString("ConfirmLanguageDialog.CancelTB.ActionText"), PdnResources.GetString("ConfirmLanguageDialog.CancelTB.ExplanationText"));
            int        num             = (TaskDialog.DefaultPixelWidth96Dpi * 5) / 4;
            TaskDialog dialog2         = new TaskDialog {
                Icon                  = icon,
                Title                 = str,
                TaskImage             = image,
                ScaleTaskImageWithDpi = true,
                IntroText             = str2
            };

            dialog2.TaskButtons     = new TaskButton[] { button, button2 };
            dialog2.AcceptButton    = button;
            dialog2.CancelButton    = button2;
            dialog2.PixelWidth96Dpi = num;
            TaskDialog dialog = dialog2;

            if (dialog.Show(this.AppWorkspace) == button)
            {
                if (ShellUtil.IsActivityQueuedForRestart)
                {
                    MessageBoxUtil.ErrorBox(this.AppWorkspace, PdnResources.GetString("Effect.PluginErrorDialog.CantQueue2ndRestart"));
                }
                else
                {
                    CloseAllWorkspacesAction action = new CloseAllWorkspacesAction();
                    action.PerformAction(this.AppWorkspace);
                    if (!action.Cancelled)
                    {
                        ShellUtil.RestartApplication();
                        Startup.CloseApplication();
                    }
                }
            }
            else
            {
                AppSettings.Instance.UI.Language.Value = oldLanguage;
            }
        }
Ejemplo n.º 10
0
        public bool LaunchFolder(IWin32Window owner, string folderPath)
        {
            Validate.Begin().IsNotNull <IWin32Window>(owner, "owner").IsNotNull <string>(folderPath, "folderPath").Check().IsNotZero(owner.Handle, "owner.Handle").IsNotEmpty(folderPath, "folderPath").Check();
            Result result = delegate {
                ShellUtil.BrowseFolder2(owner, folderPath);
            }.Try();

            result.Observe();
            return(!result.IsError);
        }
Ejemplo n.º 11
0
 private static IShellItem2 CreateItemFromJumpPath(JumpPath jumpPath)
 {
     try
     {
         return(ShellUtil.GetShellItemForPath(Path.GetFullPath(jumpPath.Path)));
     }
     catch (Exception)
     {
     }
     return(null);
 }
Ejemplo n.º 12
0
        private static bool InitializeWithItem(string pszFile, IPreviewHandler previewHandler)
        {
            if (previewHandler is IInitializeWithItem initializeWithItem)
            {
                var psi = ShellUtil.GetShellItemForPath(pszFile);
                initializeWithItem.Initialize(psi, STGM.STGM_READ).ThrowIfFailed("InitializeWithItem::Initialize");
                Log.Debug("PreviewHandler::InitializeWithItem");
                return(true);
            }

            return(false);
        }
Ejemplo n.º 13
0
 public void Finish(IUpdatesServiceHost host)
 {
     if (!this.finishing)
     {
         try
         {
             if (this.haveFinished)
             {
                 throw new ApplicationException("already called Finish()");
             }
             this.finishing    = true;
             this.haveFinished = true;
             bool flag      = Security.VerifySignedFile(base.StateMachine.UIContext, this.installerPath, false, false);
             bool cancelled = false;
             host.CloseAllWorkspaces(out cancelled);
             if (flag && !cancelled)
             {
                 AppSettings.Instance.Updates.PackageFileName.Value = this.installerPath;
                 if (string.Compare(Path.GetExtension(this.installerPath), ".exe", true) == 0)
                 {
                     ShellUtil.IsActivityQueuedForRestart = false;
                     Form parent = new Form {
                         BackColor = Color.Red
                     };
                     parent.TransparencyKey = parent.BackColor;
                     parent.ShowInTaskbar   = false;
                     parent.FormBorderStyle = FormBorderStyle.None;
                     parent.StartPosition   = FormStartPosition.CenterScreen;
                     parent.Show();
                     try
                     {
                         ShellUtil.Execute(parent, this.installerPath, "/skipConfig /restartPdnOnExit", ExecutePrivilege.RequireAdmin, ExecuteWaitType.ReturnImmediately);
                     }
                     catch (Exception exception)
                     {
                         ExceptionDialog.ShowErrorDialog(parent, exception);
                     }
                     parent.Close();
                     Startup.CloseApplication();
                 }
             }
             else
             {
                 FileSystem.TryDeleteFile(this.installerPath);
             }
         }
         finally
         {
             this.finishing = false;
         }
     }
 }
Ejemplo n.º 14
0
        private static IShellItem2 CreateItemFromJumpPath(JumpPath jumpPath)
        {
            Debug.Assert(jumpPath != null);

            try
            {
                // This will return null if the path doesn't exist.
                return(ShellUtil.GetShellItemForPath(Path.GetFullPath(jumpPath.Path)));
            }
            catch (Exception)
            {
                // Don't propagate exceptions here.  If we couldn't create the item, it's just invalid.
            }

            return(null);
        }
        public void RunCommand()
        {
            var cmdResult = ShellUtil.RunCommand("date", "+%T");

            Assert.IsNotNull(cmdResult);
            Assert.AreEqual(ShellCommandOutcome.Success, cmdResult.Outcome);
            Assert.IsTrue(!string.IsNullOrWhiteSpace(cmdResult.Output));
            var dateTime = DateTime.Parse(cmdResult.Output);

            Assert.IsTrue(DateTime.Now.Subtract(dateTime) < TimeSpan.FromSeconds(1));

            cmdResult = ShellUtil.RunCommand("git", "branch --show-current");
            Assert.IsNotNull(cmdResult);
            Assert.AreEqual(ShellCommandOutcome.Success, cmdResult.Outcome);
            Assert.IsTrue(!string.IsNullOrWhiteSpace(cmdResult.Output));
            string[] likelyBranches = new string[] { "master", "development", };
            Assert.IsTrue(likelyBranches.Contains(cmdResult.Output.Replace(Environment.NewLine, string.Empty)));
        }
Ejemplo n.º 16
0
 /// <summary>Initializes a new instance of the <see cref="ShellItem"/> class.</summary>
 /// <param name="knownFolder">A known folder reference.</param>
 protected ShellItem(KNOWNFOLDERID knownFolder)
 {
     if (IsMin7)
     {
         SHGetKnownFolderItem(knownFolder.Guid(), KNOWN_FOLDER_FLAG.KF_FLAG_DEFAULT, SafeTokenHandle.Null, typeof(IShellItem).GUID, out var ppv).ThrowIfFailed();
         Init((IShellItem)ppv);
     }
     else
     {
         var csidl = knownFolder.SpecialFolder();
         if (csidl == null)
         {
             throw new ArgumentOutOfRangeException(nameof(knownFolder), @"Cannot translate this known folder to a value understood by systems prior to Windows 7.");
         }
         var path = new StringBuilder(MAX_PATH);
         SHGetFolderPath(IntPtr.Zero, (int)csidl.Value, SafeTokenHandle.Null, SHGFP.SHGFP_TYPE_CURRENT, path).ThrowIfFailed();
         Init(ShellUtil.GetShellItemForPath(path.ToString()));
     }
 }
Ejemplo n.º 17
0
        internal virtual void PrepareVistaDialog(IFileDialog dialog)
        {
            dialog.SetDefaultExtension(this.DefaultExt);
            dialog.SetFileName(this.CriticalFileName);
            if (!string.IsNullOrEmpty(this.InitialDirectory))
            {
                IShellItem shellItemForPath = ShellUtil.GetShellItemForPath(this.InitialDirectory);
                if (shellItemForPath != null)
                {
                    dialog.SetDefaultFolder(shellItemForPath);
                    dialog.SetFolder(shellItemForPath);
                }
            }
            dialog.SetTitle(this.Title);
            FOS options = (FOS)((this.Options & 1063690) | 536870912 | 64);

            dialog.SetOptions(options);
            COMDLG_FILTERSPEC[] filterItems = FileDialog.GetFilterItems(this.Filter);
            if (filterItems.Length != 0)
            {
                dialog.SetFileTypes((uint)filterItems.Length, filterItems);
                dialog.SetFileTypeIndex((uint)this.FilterIndex);
            }
            IList <FileDialogCustomPlace> customPlaces = this.CustomPlaces;

            if (customPlaces != null && customPlaces.Count != 0)
            {
                foreach (FileDialogCustomPlace customPlace in customPlaces)
                {
                    IShellItem shellItem = FileDialog.ResolveCustomPlace(customPlace);
                    if (shellItem != null)
                    {
                        try
                        {
                            dialog.AddPlace(shellItem, FDAP.BOTTOM);
                        }
                        catch (ArgumentException)
                        {
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
        private ErrorCode OpenSolution()
        {
            Solution solution = GetGenerator().Solution;
            var      file     = new FileInfo(Path.Combine(solution.OutputDir, solution.Name + ".sln"));

            if (!file.Exists)
            {
                Log.Error("Could not find a solution file to open. Was it generated?");
                return(ErrorCode.CliError);
            }

            try
            {
                string command   = ExpandableVars.Instance.ExpandAllInString(solution.OpenCommand);
                string process   = command;
                string args      = "";
                int    argsIndex = command.IndexOf(' ') + 1;
                if (argsIndex > 1)
                {
                    process = command.Substring(0, argsIndex - 1);
                    args    = command.Substring(argsIndex);
                }

                var psi = new ProcessStartInfo(process, args)
                {
                    WorkingDirectory = Directory.GetCurrentDirectory()
                };
                ShellUtil.StartProcess(psi, ConsoleOutputHandler, ConsoleErrorHandler, true, true, 1);
            }
            catch (Exception ex)
            {
                Log.Error("Failed to execute open command. See exception below.");
                Log.Error(ex.ToString());
                return(ErrorCode.CliError);
            }

            return(ErrorCode.Success);
        }
Ejemplo n.º 19
0
        public static void CopyToClipboard(List <string> fullPaths)
        {
            StringBuilder stringBuilder = new StringBuilder("Set-Clipboard -Path ");

            for (int i = 0; i < fullPaths.Count; i++)
            {
                if (i != 0)
                {
                    stringBuilder.Append(",");
                }
                stringBuilder.Append("\"");
                stringBuilder.Append(fullPaths[i]);
                stringBuilder.Append("\"");
            }
            if (ShellUtil.RunPowershellCommand(stringBuilder.Replace("/", "\\").ToString()))
            {
                Debug.Log("已复制文件列表到 剪切板!!!");
            }
            else
            {
                Debug.LogError("复制出错!");
            }
        }
Ejemplo n.º 20
0
        protected override void ExecuteJob(IJobExecutionContext context)
        {
            Process      pro  = null;
            StreamWriter sIn  = null;
            StreamReader sOut = null;
            string       command;

            try
            {
                var dataMap = context.MergedJobDataMap;
                ShellCommand = dataMap.GetString("shell-command");
                ShellName    = dataMap.GetString("shell-name");
                OutFolder    = dataMap.GetString("out-folder");
                FileName     = dataMap.GetString("file-name");
                FileFormat   = dataMap.GetString("file-format");
                FileExt      = dataMap.GetString("file-ext");
                string fileName = Path.Combine(OutFolder, string.Concat(FileName, DateTime.Now.ToString(FileFormat), ".", FileExt));
                command = ShellCommand.Replace("{fileName}", fileName);
                Logger.Info($"[命令]-- {command}");
                if (!Directory.Exists(OutFolder))
                {
                    Directory.CreateDirectory(OutFolder);
                }
                var result = ShellUtil.ExecuteCommand(ShellName, p =>
                {
                    p(command);
                    p("exit 0");
                }, null);
                string message = result ? fileName : "失败";
                Logger.Info($@"[结果]-- {message}");
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
Ejemplo n.º 21
0
 private void OnBtnFileExtCreate(object sender, EventArgs e)
 {
     ShellUtil.RegisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId,
                                 KPRes.FileExtName, WinUtil.GetExecutable(), PwDefs.ShortProductName, true);
 }
Ejemplo n.º 22
0
        protected override Task ExecuteJob(IJobExecutionContext context)
        {
            var dataMap = context.MergedJobDataMap;

            ScriptPath     = dataMap.GetString("shell-script-path");
            ShellName      = dataMap.GetString("shell") ?? "/bin/bash";
            DbType         = dataMap.GetString("db-type") ?? "MySql";
            DbConnString   = dataMap.GetString("conn-string") ?? "";
            NoticeApi      = dataMap.GetString("notice-api") ?? "";
            NoticeApi2     = dataMap.GetString("notice-api-2") ?? "";
            AfterShellSql  = dataMap.GetString("after-shell-sql") ?? "";
            BeforeShellSql = dataMap.GetString("before-shell-sql") ?? "";
            var       logService = new LogService(DbType, DbConnString);
            Stopwatch stopwatch  = new Stopwatch();

            //如果表还没初始化
            if (TableInit.TableInit.IsInit == false)
            {
                TableInit.TableInit.Init(DbType, DbConnString);
                TableInit.TableInit.IsInit = true;
            }


            if (IsActive)
            {
                Logger.Info("存在执行中任务,跳过该周期!");
            }
            else
            {
                IsActive = true;
                string command = string.Empty;
                string querySql;
                long?  task_detail_id = 0;
                string ttime          = string.Empty;
                string thour          = string.Empty;
                string phone_number   = string.Empty;
                string type1          = string.Empty;
                string type3          = string.Empty;
                int    step_no        = 1;

                // Logger.Info($"任务数据--{Environment.NewLine}ShellName={ShellName}{Environment.NewLine}ScriptPath={ScriptPath}{Environment.NewLine}DbType={DbType}{Environment.NewLine}DbConnString={DbConnString}{Environment.NewLine}BeforeShellSql={BeforeShellSql}{Environment.NewLine}AfterShellSql={AfterShellSql}{Environment.NewLine}NoticeApi={NoticeApi}{Environment.NewLine}NoticeApi2={NoticeApi2}");
                try
                {
                    DbConnection conn;
                    switch (DbType)
                    {
                    case "MsSql":
                        conn     = new SqlConnection(DbConnString);
                        querySql = @"select top 1 task_detail_id,ttime,thour,def_cellname,type1,type3 from manager_task_detail where reply='1001' ";
                        break;

                    default:
                        conn     = new MySqlConnection(DbConnString);
                        querySql = @"select task_detail_id,ttime,thour,def_cellname,type1,type3 from manager_task_detail where reply='1001' limit 1";
                        break;
                    }
                    using (conn)
                    {
                        try
                        {
                            conn.Open();

                            var cmd = conn.CreateCommand();
                            cmd.CommandType    = System.Data.CommandType.Text;
                            cmd.CommandText    = querySql;
                            cmd.CommandTimeout = 0;
                            var reader = cmd.ExecuteReader();
                            if (reader.HasRows)
                            {
                                List <string> arguments = new List <string>()
                                {
                                };

                                while (reader.Read())
                                {
                                    //int i = 0;
                                    task_detail_id = reader.GetInt64(0);
                                    ttime          = reader.GetString(1);
                                    thour          = reader.GetString(2);
                                    phone_number   = reader.GetString(3);
                                    type1          = reader.GetString(4);
                                    type3          = reader.GetString(5);
                                    int type3Value = type3.Contains("未接通") ? 1 : type3.Contains("掉话") ? 2 : type3.ToUpper().Contains("ESRVCC切换失败") ? 4 : type3.Contains("切换失败") ? 3 : throw new ArgumentOutOfRangeException($"TYPE3不在范围内:{type3}");

                                    Logger.Info($"查询到工单{{task_detail_id:{task_detail_id},ttime:{ttime},thour:{thour},phone_number:{phone_number},type1:{type1},type3:{type3}}}");

                                    ShellName.Split(";").ToList().ForEach(shell =>
                                    {
                                        arguments.Add($"{shell} {ttime} {thour} {phone_number} {type1} {type3Value}");
                                    });

                                    break;
                                }
                                conn.Close();


                                if (!string.IsNullOrEmpty(BeforeShellSql))
                                {
                                    conn.Open();
                                    cmd.CommandText = BeforeShellSql.Replace("@select_date", ttime);//替换日期占位符


                                    //记录日志到数据表
                                    var step_1 = logService.Insert(new TableEntity.SingleUserAnalysisHistoryInfo()
                                    {
                                        col_create_time = DateTime.Now,
                                        error_msg       = "",                                  //异常信息
                                        run_status      = RunStatus.执行中.ToString(),
                                        spend_time      = 0,                                   //耗时
                                        step_name       = "(BeforeShellSql)执行shell脚本之前的sql脚本", //步骤名称
                                        step_no         = step_no,                             //步骤编号
                                        step_remark     = "",                                  //备注
                                        task_detail_id  = task_detail_id ?? 0                  //工单id
                                    });
                                    stopwatch.Restart();                                       //计时器开始
                                    int asqResult = 0;

                                    try
                                    {
                                        asqResult = cmd.ExecuteNonQuery();
                                        Logger.Info($" {asqResult} 行受影响");
                                    }
                                    catch (Exception ex)
                                    {
                                        step_1.error_msg = ex.Message;
                                    }

                                    stopwatch.Stop();//计时器停止
                                    step_1.run_status  = RunStatus.已执行.ToString();
                                    step_1.step_remark = $" {asqResult} 行受影响";
                                    step_1.spend_time  = (int)stopwatch.Elapsed.TotalSeconds;
                                    logService.Update(step_1);

                                    conn.Close();
                                }


                                Logger.Info($"--------------开始执行SHELL命令--------------");

                                arguments.ForEach(argument =>
                                {
                                    step_no++;
                                    //执行shell脚本
                                    Logger.Info($"/bin/bash {argument}");
                                    //记录日志到数据表
                                    var step_2 = logService.Insert(new TableEntity.SingleUserAnalysisHistoryInfo()
                                    {
                                        col_create_time = DateTime.Now,
                                        error_msg       = "",                          //异常信息
                                        run_status      = RunStatus.执行中.ToString(),
                                        spend_time      = 0,                           //耗时
                                        step_name       = "执行shell脚本,脚本参数" + argument, //步骤名称
                                        step_no         = step_no,                     //步骤编号
                                        step_remark     = "",                          //备注
                                        task_detail_id  = task_detail_id ?? 0          //工单id
                                    });
                                    stopwatch.Restart();                               //计时器开始

                                    var result = ShellUtil.ExecuteCommand("/bin/bash", argument, null);

                                    stopwatch.Stop();//计时器停止
                                    step_2.run_status   = RunStatus.已执行.ToString();
                                    step_2.step_remark += "执行结果:" + (result.Item1 == true ? "无错误" : string.Concat("有错误,", result.Item2));
                                    step_2.spend_time   = (int)stopwatch.Elapsed.TotalSeconds;
                                    logService.Update(step_2);
                                });
                                Logger.Info($"--------------执行SHELL命令完成--------------");



                                Logger.Info($"[AfterShellSql:]-- {AfterShellSql}");
                                if (!string.IsNullOrEmpty(AfterShellSql))
                                {
                                    conn.Open();
                                    cmd.CommandText = AfterShellSql.Replace("@select_date", ttime).Replace("@select_hour", thour);//替换日期占位符

                                    //记录日志到数据表
                                    var step_3 = logService.Insert(new TableEntity.SingleUserAnalysisHistoryInfo()
                                    {
                                        col_create_time = DateTime.Now,
                                        error_msg       = "",                                 //异常信息
                                        run_status      = RunStatus.执行中.ToString(),
                                        spend_time      = 0,                                  //耗时
                                        step_name       = "(AfterShellSql)执行shell脚本之后的sql脚本", //步骤名称
                                        step_no         = step_no,                            //步骤编号
                                        step_remark     = "",                                 //备注
                                        task_detail_id  = task_detail_id ?? 0                 //工单id
                                    });
                                    stopwatch.Restart();                                      //计时器开始
                                    int asqResult = 0;

                                    try
                                    {
                                        asqResult = cmd.ExecuteNonQuery();
                                        Logger.Info($" {asqResult} 行受影响");
                                    }
                                    catch (Exception ex)
                                    {
                                        step_3.error_msg = ex.Message;
                                    }

                                    stopwatch.Stop();//计时器停止
                                    step_3.run_status  = RunStatus.已执行.ToString();
                                    step_3.step_remark = $" {asqResult} 行受影响";
                                    step_3.spend_time  = (int)stopwatch.Elapsed.TotalSeconds;
                                    logService.Update(step_3);

                                    conn.Close();
                                }

                                step_no++;
                                //记录日志到数据表
                                var step_4 = logService.Insert(new TableEntity.SingleUserAnalysisHistoryInfo()
                                {
                                    col_create_time = DateTime.Now,
                                    error_msg       = "",                     //异常信息
                                    run_status      = RunStatus.执行中.ToString(),
                                    spend_time      = 0,                      //耗时
                                    step_name       = "生成工单结果 并更新reply为1002", //步骤名称
                                    step_no         = step_no,                //步骤编号
                                    step_remark     = "",                     //备注
                                    task_detail_id  = task_detail_id ?? 0     //工单id
                                });
                                stopwatch.Restart();                          //计时器开始

                                //生成工单结果 并更新reply为1002
                                //NoticeApi2 : http://120.76.26.161:5000/api/WorkorderService/BuildCellQuestion
                                var httpResult = HttpUtil.HttpGet(NoticeApi2 + $"?task_detail_id={task_detail_id}", timeout: 120);
                                Logger.Info("生成工单结果:" + httpResult);

                                stopwatch.Stop();//计时器停止
                                step_4.run_status  = RunStatus.已执行.ToString();
                                step_4.step_remark = httpResult;
                                step_4.spend_time  = (int)stopwatch.Elapsed.TotalSeconds;
                                logService.Update(step_4);



                                //通知专家系统网站该工单已经处理完毕
                                //10秒/次*30次无结果则跳过,直接通知专家系统
                                int i = 0;
                                while (i++ < 30)
                                {
                                    conn.Open();
                                    cmd.CommandText = $"select reply from manager_task_detail where task_detail_id={task_detail_id}";
                                    string analysisResult = (string)cmd.ExecuteScalar();
                                    conn.Close();
                                    if (analysisResult != "1001")
                                    {
                                        break;
                                    }
                                    Thread.Sleep(1000 * 10);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex);
                        }
                        finally
                        {
                            conn.Close();
                            //NoticeApi : http://120.76.26.161:5000/TaskManagement/OnTuAnalysisFinished
                            if (task_detail_id.GetValueOrDefault() != 0)
                            {
                                Logger.Info("通知专家系统:" + HttpUtil.HttpGet(NoticeApi + $"?id={task_detail_id}", timeout: 60));
                            }
                        }
                        //Thread.Sleep(10*1000);//测试存在执行中任务
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
                finally
                {
                    IsActive = false;
                }
            }
            return(TaskUtil.CompletedTask);
        }
Ejemplo n.º 23
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); }
        }
Ejemplo n.º 24
0
        public static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.DoEvents();

            int nRandomSeed = (int)DateTime.Now.Ticks;

            // Prevent overflow (see Random class constructor)
            if (nRandomSeed == int.MinValue)
            {
                nRandomSeed = 17;
            }
            m_rndGlobal = new Random(nRandomSeed);

            // Set global localized strings
            PwDatabase.LocalizedAppName = PwDefs.ShortProductName;
            Kdb4File.DetermineLanguageId();

            m_appConfig = AppConfigSerializer.Load();
            if (m_appConfig.Logging.Enabled)
            {
                AppLogEx.Open(PwDefs.ShortProductName);
            }

            AppPolicy.Current = m_appConfig.Security.Policy.CloneDeep();

            string strHelpFile = UrlUtil.StripExtension(WinUtil.GetExecutable()) +
                                 ".chm";

            AppHelp.LocalHelpFile = strHelpFile;

            string strLangFile = m_appConfig.Application.LanguageFile;

            if ((strLangFile != null) && (strLangFile.Length > 0))
            {
                strLangFile = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(), true) +
                              strLangFile;

                try
                {
                    m_kpTranslation = KPTranslation.LoadFromFile(strLangFile);

                    KPRes.SetTranslatedStrings(
                        m_kpTranslation.SafeGetStringTableDictionary(
                            "KeePass.Resources.KPRes"));
                    KLRes.SetTranslatedStrings(
                        m_kpTranslation.SafeGetStringTableDictionary(
                            "KeePassLib.Resources.KLRes"));
                }
                catch (FileNotFoundException) { }                // Ignore
                catch (Exception) { Debug.Assert(false); }
            }

            m_cmdLineArgs = new CommandLineArgs(args);

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtRegister] != null)
            {
                ShellUtil.RegisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId,
                                            KPRes.FileExtName, WinUtil.GetExecutable(), PwDefs.ShortProductName, false);
                MainCleanUp();
                return;
            }
            else if (m_cmdLineArgs[AppDefs.CommandLineOptions.FileExtUnregister] != null)
            {
                ShellUtil.UnregisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId);
                MainCleanUp();
                return;
            }
            else if ((m_cmdLineArgs[AppDefs.CommandLineOptions.Help] != null) ||
                     (m_cmdLineArgs[AppDefs.CommandLineOptions.HelpLong] != null))
            {
                AppHelp.ShowHelp(AppDefs.HelpTopics.CommandLine, null);
                MainCleanUp();
                return;
            }

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

            if (m_cmdLineArgs[AppDefs.CommandLineOptions.ExitAll] != null)
            {
                try
                {
                    NativeMethods.SendMessage((IntPtr)NativeMethods.HWND_BROADCAST,
                                              m_nAppMessage, (IntPtr)AppMessage.Exit, IntPtr.Zero);
                }
                catch (Exception) { Debug.Assert(false); }

                MainCleanUp();
                return;
            }

            Mutex mSingleLock = TrySingleInstanceLock(AppDefs.MutexName, true);

            if ((mSingleLock == null) && m_appConfig.Integration.LimitToSingleInstance)
            {
                ActivatePreviousInstance(args);
                MainCleanUp();
                return;
            }

            Mutex mGlobalNotify = TryGlobalInstanceNotify(AppDefs.MutexNameGlobal);

#if DEBUG
            m_formMain = new MainForm();
            Application.Run(m_formMain);
#else
            try
            {
                m_formMain = new MainForm();
                Application.Run(m_formMain);
            }
            catch (Exception exPrg)
            {
                MessageService.ShowFatal(exPrg);
            }
#endif

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

            MainCleanUp();

            if (mGlobalNotify != null)
            {
                GC.KeepAlive(mGlobalNotify);
            }
            if (mSingleLock != null)
            {
                GC.KeepAlive(mSingleLock);
            }
        }
Ejemplo n.º 25
0
 /// <summary>Initializes a new instance of the <see cref="ShellItem"/> class.</summary>
 /// <param name="path">The file system path of the item.</param>
 public ShellItem(string path)
 {
     Init(ShellUtil.GetShellItemForPath(path));
 }
Ejemplo n.º 26
0
        protected override void PerformAction(object parameter)
        {
            var photo = parameter as FacebookPhoto;

            if (photo == null)
            {
                return;
            }

            string defaultFileName = "Facebook Photo";

            if (photo.Album != null)
            {
                defaultFileName = photo.Album.Title + " (" + (photo.Album.Photos.IndexOf(photo) + 1) + ")";
            }

            string filePath = null;

            if (Utility.IsOSVistaOrNewer)
            {
                IFileSaveDialog pFileSaveDialog = null;
                try
                {
                    pFileSaveDialog = CLSID.CoCreateInstance <IFileSaveDialog>(CLSID.FileSaveDialog);
                    pFileSaveDialog.SetOptions(pFileSaveDialog.GetOptions() | FOS.FORCEFILESYSTEM | FOS.OVERWRITEPROMPT);
                    pFileSaveDialog.SetTitle("Select where to save the photo");
                    pFileSaveDialog.SetOkButtonLabel("Save Photo");
                    var filterspec = new COMDLG_FILTERSPEC {
                        pszName = "Images", pszSpec = "*.jpg;*.png;*.bmp;*.gif"
                    };
                    pFileSaveDialog.SetFileTypes(1, ref filterspec);
                    pFileSaveDialog.SetFileName(defaultFileName);
                    Guid clientId = _SavePhotoId;
                    pFileSaveDialog.SetClientGuid(ref clientId);

                    IShellItem pItem = null;
                    try
                    {
                        pItem = ShellUtil.GetShellItemForPath(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
                        pFileSaveDialog.SetDefaultFolder(pItem);
                    }
                    finally
                    {
                        Utility.SafeRelease(ref pItem);
                    }

                    HRESULT hr = pFileSaveDialog.Show(new WindowInteropHelper(Application.Current.MainWindow).Handle);
                    if (hr.Failed)
                    {
                        Assert.AreEqual((HRESULT)Win32Error.ERROR_CANCELLED, hr);
                        return;
                    }

                    pItem = null;
                    try
                    {
                        pItem    = pFileSaveDialog.GetResult();
                        filePath = ShellUtil.GetPathFromShellItem(pItem);
                    }
                    finally
                    {
                        Utility.SafeRelease(ref pItem);
                    }
                }
                finally
                {
                    Utility.SafeRelease(ref pFileSaveDialog);
                }
            }
            else
            {
                var saveFileDialog = new Microsoft.Win32.SaveFileDialog
                {
                    Filter           = "Image Files|*.jpg;*.png;*.bmp;*.gif",
                    FileName         = defaultFileName,
                    InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                };

                if (saveFileDialog.ShowDialog(Application.Current.MainWindow) != true)
                {
                    return;
                }

                filePath = saveFileDialog.FileName;
            }

            FacebookImageSaveOptions fiso = FacebookImageSaveOptions.FindBetterName;

            // We told the file dialog to prompt about overwriting, so if the user specified a location
            // with a file extension and the file already exists, prepare to overwrite.
            // This isn't quite right because the file extension may be different, so we may overwrite a jpg
            // when it was asked to be a gif, but it's not a likely scenario.
            if (System.IO.File.Exists(filePath))
            {
                fiso = FacebookImageSaveOptions.Overwrite;
            }

            photo.Image.SaveToFile(FacebookImageDimensions.Big, filePath, true, fiso, _OnPhotoSaveProgressCallback, null);
        }
Ejemplo n.º 27
0
        protected override void PerformAction(object parameter)
        {
            var album = parameter as FacebookPhotoAlbum;

            if (album == null)
            {
                return;
            }

            string folderPath = null;

            if (Utility.IsOSVistaOrNewer)
            {
                IFileOpenDialog pFolderDialog = null;
                try
                {
                    pFolderDialog = CLSID.CoCreateInstance <IFileOpenDialog>(CLSID.FileOpenDialog);
                    pFolderDialog.SetOptions(pFolderDialog.GetOptions() | FOS.NOREADONLYRETURN | FOS.PICKFOLDERS);
                    pFolderDialog.SetTitle(string.Format("Select where to save \"{0}\"", album.Title));
                    pFolderDialog.SetOkButtonLabel("Save Album");

                    HRESULT hr = pFolderDialog.Show(new WindowInteropHelper(Application.Current.MainWindow).Handle);
                    if (hr.Failed)
                    {
                        return;
                    }

                    IShellItem pItem = null;
                    try
                    {
                        pItem      = pFolderDialog.GetResult();
                        folderPath = ShellUtil.GetPathFromShellItem(pItem);
                    }
                    finally
                    {
                        Utility.SafeRelease(ref pItem);
                    }
                }
                finally
                {
                    Utility.SafeRelease(ref pFolderDialog);
                }
            }
            else
            {
                var folderDialog = new System.Windows.Forms.FolderBrowserDialog
                {
                    Description         = "Choose where to save the album.",
                    ShowNewFolderButton = true,
                };
                if (folderDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }

                folderPath = folderDialog.SelectedPath;
            }

            album.SaveToFolder(folderPath, _OnAlbumSaveProgressCallback, null);
            Process.Start(new ProcessStartInfo {
                FileName = folderPath
            });
        }
Ejemplo n.º 28
0
 private void OnBtnFileExtRemove(object sender, EventArgs e)
 {
     ShellUtil.UnregisterExtension(AppDefs.FileExtension.FileExt, AppDefs.FileExtension.ExtId);
 }
Ejemplo n.º 29
0
        protected override Task ExecuteJob(IJobExecutionContext context)
        {
            Logger.Info($"******************************新周期触发(线程ID:{Thread.CurrentThread.ManagedThreadId})******************************");
            var dataMap = context.MergedJobDataMap;

            ScriptPath    = dataMap.GetString("shell-script-path");
            ShellName     = dataMap.GetString("shell") ?? "/bin/bash";
            DbType        = dataMap.GetString("db-type") ?? "MySql";
            DbConnString  = dataMap.GetString("conn-string") ?? "";
            NoticeApi     = dataMap.GetString("notice-api") ?? "";
            NoticeApi2    = dataMap.GetString("notice-api-2") ?? "";
            AfterShellSql = dataMap.GetString("after-shell-sql") ?? "";

            if (IsActive)
            {
                Logger.Info("存在执行中任务,跳过该周期!");
            }
            else
            {
                IsActive = true;
                string command = string.Empty;
                string querySql;
                long?  task_detail_id = 0;
                try
                {
                    DbConnection conn;
                    switch (DbType)
                    {
                    case "MsSql":
                        conn     = new SqlConnection(DbConnString);
                        querySql = @"select top 1 task_detail_id,ttime,thour,def_cellname,type1,type3 from manager_task_detail where reply='1001' limit 1";
                        break;

                    default:
                        conn     = new MySqlConnection(DbConnString);
                        querySql = @"select task_detail_id,ttime,thour,def_cellname,type1,type3 from manager_task_detail where reply='1001' limit 1";
                        break;
                    }
                    using (conn)
                    {
                        try
                        {
                            conn.Open();

                            var cmd = conn.CreateCommand();
                            cmd.CommandType    = System.Data.CommandType.Text;
                            cmd.CommandText    = querySql;
                            cmd.CommandTimeout = 0;
                            var reader = cmd.ExecuteReader();
                            if (reader.HasRows)
                            {
                                string arguments = string.Empty;

                                while (reader.Read())
                                {
                                    int i = 0;
                                    task_detail_id = reader.GetInt64(0);
                                    string type3      = reader.GetString(5);
                                    int    type3Value = type3.Contains("未接通") ? 1 :
                                                        type3.Contains("掉话") ? 2 :
                                                        type3.Contains("切换失败") ? 3 :
                                                        throw new ArgumentException($"TYPE3不在范围内:{type3}");

                                    Logger.Info($"查询到工单:task_detail_id={reader.GetString(0)},ttime={reader.GetString(1)},thour={reader.GetString(2)},def_cellname={reader.GetString(3)},type1={reader.GetString(4)},type3={type3}");
                                    arguments = $"{ShellName} {reader.GetString(1)} {reader.GetString(2)} {reader.GetString(3)} {reader.GetString(4)} {type3Value}";
                                    break;
                                }
                                conn.Close();

                                //var result = ExecShellCommand(p =>
                                //{
                                //    p(command);
                                //    p("exit 0");
                                //});
                                Logger.Info($"--------------开始执行SHELL命令--------------");
                                Logger.Info($"/bin/bash {arguments}");
                                var result = ShellUtil.ExecuteCommand("/bin/bash", arguments, null);
                                Logger.Info($"--------------执行SHELL命令完成--------------");
                                Logger.Info($"[AfterShellSql:]-- {AfterShellSql}");
                                if (!string.IsNullOrEmpty(AfterShellSql))
                                {
                                    conn.Open();
                                    cmd.CommandText = AfterShellSql;
                                    try
                                    {
                                        var asqResult = cmd.ExecuteNonQuery();
                                        Logger.Info($" {asqResult} 行受影响");
                                    }
                                    catch { }
                                    conn.Close();
                                }

                                HttpUtil.HttpGet(NoticeApi2 + $"?task_detail_id={task_detail_id}", timeout: 60);

                                while (true)
                                {
                                    conn.Open();
                                    cmd.CommandText = $"select reply from manager_task_detail where task_detail_id={task_detail_id}";
                                    string analysisResult = (string)cmd.ExecuteScalar();
                                    conn.Close();
                                    if (analysisResult != "1001")
                                    {
                                        IsActive = false;
                                        Logger.Info("通知专家系统:" + HttpUtil.HttpGet(NoticeApi + $"?id={task_detail_id}", timeout: 60));
                                        break;
                                    }
                                    Thread.Sleep(1000);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.ErrorException(ex.Message, ex);
                        }
                        finally
                        {
                            conn.Close();
                            Logger.Info("通知专家系统:" + HttpUtil.HttpGet(NoticeApi + $"?id={task_detail_id}", timeout: 60));
                        }
                        //Thread.Sleep(10*1000);//测试存在执行中任务
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorException(ex.Message, ex);
                }
                finally
                {
                    IsActive = false;
                }
            }
            Logger.Info($"******************************周期结束(线程ID:{Thread.CurrentThread.ManagedThreadId})******************************)");
            return(TaskUtil.CompletedTask);
        }
Ejemplo n.º 30
0
        private DialogResult AskInstallNowOrOnExit(IWin32Window owner, string newVersionName, string moreInfoUrl)
        {
            Image reference;

            Func <bool> < > 9__1;
            Icon          icon          = PdnResources.GetImageResource("Icons.MenuUtilitiesCheckForUpdatesIcon.png").Reference.ToIcon();
            string        str           = PdnResources.GetString("UpdatePromptTaskDialog.Title");
            ImageResource imageResource = PdnResources.GetImageResource("Images.UpdatePromptTaskDialog.TaskImage.png");

            try
            {
                reference = imageResource.Reference;
            }
            catch (Exception)
            {
                reference = null;
            }
            string       str2  = PdnResources.GetString("UpdatePromptTaskDialog.IntroText");
            TaskAuxLabel label = new TaskAuxLabel {
                Text     = newVersionName,
                TextFont = new Font(this.host.UISite.Font.FontFamily, this.host.UISite.Font.Size * 1.35f, FontStyle.Regular)
            };
            TaskButton button = new TaskButton(PdnResources.GetImageResource("Icons.Updates.InstallAtExit.png").Reference, PdnResources.GetString("UpdatePromptTaskDialog.InstallOnExitTB.ActionText"), PdnResources.GetString("UpdatePromptTaskDialog.InstallOnExitTB.DescriptionText"));
            TaskButton tail   = new TaskButton(PdnResources.GetImageResource("Icons.Updates.InstallNow.png").Reference, PdnResources.GetString("UpdatePromptTaskDialog.InstallNowTB.ActionText"), PdnResources.GetString("UpdatePromptTaskDialog.InstallNowTB.DescriptionText"));
            string     str3   = PdnResources.GetString("UpdatePromptTaskDialog.AuxButtonText");
            Action     auxButtonClickHandler = delegate {
                (< > 9__1 ?? (< > 9__1 = () => ShellUtil.LaunchUrl2(this.host.UISite.Win32Window, moreInfoUrl))).Eval <bool>().Observe();
            };
            TaskAuxButton button3 = new TaskAuxButton {
                Text = str3
            };

            button3.Clicked += delegate(object s, EventArgs e) {
                auxButtonClickHandler();
            };
            TaskButton[] buttonArray = (from tb in Enumerable.Empty <TaskButton>().Concat <TaskButton>(((PdnInfo.IsExpired || ShellUtil.IsActivityQueuedForRestart) ? null : button)).Concat <TaskButton>(tail)
                                        where tb > null
                                        select tb).ToArrayEx <TaskButton>();
            TaskDialog dialog2 = new TaskDialog {
                Icon            = icon,
                Title           = str,
                TaskImage       = reference,
                IntroText       = str2,
                TaskButtons     = buttonArray,
                AcceptButton    = tail,
                CancelButton    = null,
                PixelWidth96Dpi = (TaskDialog.DefaultPixelWidth96Dpi * 3) / 2
            };

            dialog2.AuxControls = new TaskAuxControl[] { label, button3 };
            TaskButton button4 = dialog2.Show(owner);

            if (button4 == tail)
            {
                return(DialogResult.Yes);
            }
            if (button4 == button)
            {
                return(DialogResult.OK);
            }
            return(DialogResult.Cancel);
        }