コード例 #1
0
            public static ComplexEventAction RequestState <TCurrentEntity, TEntityView>(int processId, Expression <Func <TEntityView, dynamic> > property) where TEntityView : SystemInterfaces.IEntityView where TCurrentEntity : IEntityId
            {
                return(new ComplexEventAction(
                           key: $"RequestState-{typeof(TEntityView).GetFriendlyName()}",
                           processId: processId,
                           actionTrigger: ActionTrigger.Any,
                           events: new List <IProcessExpectedEvent>
                {
                    new ProcessExpectedEvent <ICurrentEntityChanged <TCurrentEntity> >(
                        "CurrentEntity", processId, e => e.Entity != null,
                        expectedSourceType: new SourceType(typeof(IViewModel)),
                        //todo: check this cuz it comes from viewmodel
                        processInfo: new StateEventInfo(processId, RevolutionData.Context.Process.Events.CurrentEntityChanged)),

                    new ProcessExpectedEvent <IEntityFound <TCurrentEntity> >(
                        "CurrentEntity", processId, e => e.Entity != null,
                        expectedSourceType: new SourceType(typeof(IViewModel)),
                        //todo: check this cuz it comes from viewmodel
                        processInfo: new StateEventInfo(processId, RevolutionData.Context.Entity.Events.EntityFound)),
                    new ProcessExpectedEvent <IEntityUpdated <TCurrentEntity> >(
                        "CurrentEntity", processId, e => e.Entity != null,
                        expectedSourceType: new SourceType(typeof(IViewModel)),
                        //todo: check this cuz it comes from viewmodel
                        processInfo: new StateEventInfo(processId, RevolutionData.Context.Entity.Events.EntityUpdated)),
                    new ProcessExpectedEvent <IEntityViewWithChangesFound <TCurrentEntity> >(
                        "CurrentEntity", processId, e => e.Entity != null,
                        expectedSourceType: new SourceType(typeof(IViewModel)),
                        //todo: check this cuz it comes from viewmodel
                        processInfo: new StateEventInfo(processId, RevolutionData.Context.EntityView.Events.EntityViewFound))
                },
                           expectedMessageType: typeof(IProcessStateMessage <TEntityView>),
                           action: ProcessActions.RequestState(property),
                           processInfo: new StateCommandInfo(processId, RevolutionData.Context.Process.Commands.UpdateState)));
            }
コード例 #2
0
        public static void Invoke(TargetAction action, Definition.CodeCleanerType[] type)
        {
            try
            {
                var projects       = DteServiceProvider.Instance.ActiveSolutionProjects as Array;
                var currentProject = projects.GetValue(0) as Project;

                if (currentProject.ProjectItems == null)
                {
                    return;
                }
                if (currentProject.FullName.ToLower().EndsWith(".shproj"))
                {
                    MessageBox.Show("Clean up can't be called direlctly on Shared Project", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                for (var i = 1; i <= currentProject.ProjectItems.Count; i++)
                {
                    ActionCSharpOnProjectItem.Action(currentProject.ProjectItems.Item(i), action, type);
                }
            }
            catch (Exception e)
            {
                ErrorNotification.EmailError(e);
                ProcessActions.GeeksProductivityToolsProcess();
            }
        }
コード例 #3
0
        public static void Invoke(TargetAction action, CleanupOptions cleanupOptions)
        {
            try
            {
                var projects       = DteServiceProvider.Instance.ActiveSolutionProjects as Array;
                var currentProject = projects.GetValue(0) as Project;

                if (currentProject.ProjectItems == null)
                {
                    return;
                }

                if (currentProject.FullName.EndsWith(".shproj", StringComparison.OrdinalIgnoreCase))
                {
                    System.Windows.MessageBox
                    .Show("Clean up can't be called direlctly on Shared Project", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                for (var i = 1; i <= currentProject.ProjectItems.Count; i++)
                {
                    ActionCSharpOnProjectItem.Action(currentProject.ProjectItems.Item(i), action, cleanupOptions);
                }
            }
            catch (Exception e)
            {
                ErrorNotification.WriteErrorToOutputWindow(e);
                ErrorNotification.WriteErrorToFile(e);
                ProcessActions.GeeksProductivityToolsProcess();
            }
        }
コード例 #4
0
        public static void DoCleanup(ProjectItem item, CodeCleanerType[] actionType, bool fileWindowMustBeOpend = false)
        {
            if (!item.IsCsharpFile() || item.IsCSharpDesignerFile())
            {
                return;
            }

            try
            {
                var path = item.Properties.Item("FullPath").Value.ToString();
                if (path.EndsWithAny(new[] { "AssemblyInfo.cs", "TheApplication.cs" }))
                {
                    return;
                }

                var window = item.Open(Constants.vsViewKindCode);

                window.Activate();
                foreach (var actionTypeItem in actionType)
                {
                    CodeCleanerHost.Run(item, actionTypeItem);
                }
                if (fileWindowMustBeOpend == false)
                {
                    window.Close(vsSaveChanges.vsSaveChangesYes);
                }
            }
            catch (Exception e)
            {
                ErrorNotification.EmailError(e);
                ProcessActions.GeeksProductivityToolsProcess();
            }
        }
コード例 #5
0
        public static void Invoke(TargetAction action, CleanupOptions cleanupOptions)
        {
            try
            {
                var projects = SolutionActions.FindProjects(DteServiceProvider.Instance);

                for (var i = 0; i < projects.Count; i++)
                {
                    var currentProject = projects[i];
                    if (currentProject.ProjectItems == null)
                    {
                        continue;
                    }
                    if (currentProject.FullName.ToLower().EndsWith(".shproj"))
                    {
                        continue;
                    }

                    for (var j = 1; j < currentProject.ProjectItems.Count; j++)
                    {
                        ActionCSharpOnProjectItem.Action(currentProject.ProjectItems.Item(j), action, cleanupOptions);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorNotification.EmailError(e);
                ProcessActions.GeeksProductivityToolsProcess();
            }
        }
コード例 #6
0
        public static void Invoke(TargetAction action, CleanupOptions cleanupOptions)
        {
            try
            {
                var projects = SolutionActions.FindProjects(DteServiceProvider.Instance);

                for (var i = 0; i < projects.Count; i++)
                {
                    var currentProject = projects[i];
                    if (currentProject.ProjectItems == null)
                    {
                        continue;
                    }
                    if (currentProject.FullName.EndsWith(".shproj", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    for (var j = 1; j < currentProject.ProjectItems.Count; j++)
                    {
                        ActionCSharpOnProjectItem.Action(currentProject.ProjectItems.Item(j), action, cleanupOptions);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorNotification.WriteErrorToFile(e);
                ErrorNotification.WriteErrorToOutputWindow(e);
                ProcessActions.GeeksProductivityToolsProcess();
            }
        }
コード例 #7
0
 public static ComplexEventAction UpdateState <TEntityView>(int processId) where TEntityView : SystemInterfaces.IEntityView
 {
     return(new ComplexEventAction(
                key: $"UpdateState-{typeof(TEntityView).GetFriendlyName()}",
                processId: processId,
                actionTrigger: ActionTrigger.Any,
                events: new List <IProcessExpectedEvent>
     {
         new ProcessExpectedEvent <IEntityViewWithChangesUpdated <TEntityView> > (processId: processId,
                                                                                  eventPredicate: e => e.Entity != null,
                                                                                  processInfo: new StateEventInfo(processId, RevolutionData.Context.Entity.Events.EntityUpdated),
                                                                                  expectedSourceType: new SourceType(typeof(IEntityRepository)),
                                                                                  key: "EntityView"),
         new ProcessExpectedEvent <IEntityViewWithChangesFound <TEntityView> > (processId: processId,
                                                                                eventPredicate: e => e.Entity != null,
                                                                                processInfo: new StateEventInfo(processId, RevolutionData.Context.Entity.Events.EntityFound),
                                                                                expectedSourceType: new SourceType(typeof(IEntityRepository)),
                                                                                key: "EntityView"),
         new ProcessExpectedEvent <IEntityFound <TEntityView> > (processId: processId,
                                                                 eventPredicate: e => e.Entity != null,
                                                                 processInfo: new StateEventInfo(processId, RevolutionData.Context.Entity.Events.EntityFound),
                                                                 expectedSourceType: new SourceType(typeof(IEntityRepository)),
                                                                 key: "EntityView")
     },
                expectedMessageType: typeof(IProcessStateMessage <TEntityView>),
                action: ProcessActions.UpdateEntityViewState <TEntityView>(),
                processInfo: new StateCommandInfo(processId, RevolutionData.Context.Process.Commands.UpdateState)));
 }
コード例 #8
0
        public override async Task <SyntaxNode> CleanUpAsync(SyntaxNode initialSourceNode)
        {
            var item = ProjectItemDetails.ProjectItem;

            try
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                item.Open(Constants.vsViewKindCode);

                var document = item.Document;
                document.Activate();

                try { document.DTE.ExecuteCommand(UsingsCommands.RemoveAndSortCommandName); }
                catch (Exception ex)
                {
                    if (ex.Message != "Command \"Edit.RemoveAndSort\" is not available.")
                    {
                        throw;
                    }

                    document.Activate();
                    document.DTE.ExecuteCommand(UsingsCommands.RemoveAndSortCommandName);
                }

                var doc      = (EnvDTE.TextDocument)(document.Object("TextDocument"));
                var p        = doc.StartPoint.CreateEditPoint();
                var s        = p.GetText(doc.EndPoint);
                var modified = SyntaxFactory.ParseSyntaxTree(s);

                if (IsReportOnlyMode &&
                    !IsEquivalentToUNModified(await modified.GetRootAsync()))
                {
                    CollectMessages(new ChangesReport(initialSourceNode)
                    {
                        LineNumber = 1,
                        Column     = 1,
                        Message    = "Your Using usage is not good",
                        Generator  = nameof(UsingDirectiveOrganizer)
                    });

                    document.Undo();
                    return(initialSourceNode);
                }

                document.Save();
            }
            catch (Exception e)
            {
                ErrorNotification.WriteErrorToFile(e, initialSourceNode.GetFilePath());
                ErrorNotification.WriteErrorToOutputWindow(e, initialSourceNode.GetFilePath());
                ProcessActions.GeeksProductivityToolsProcess();
            }

            return(item.ToSyntaxNode());
        }
コード例 #9
0
 public static ComplexEventAction UpdateStateList <TEntityView>(int processId) where TEntityView : SystemInterfaces.IEntityView
 {
     return(new ComplexEventAction(
                key: $"UpdateStateList-{typeof(TEntityView).GetFriendlyName()}",
                processId: processId,
                events: new List <IProcessExpectedEvent>
     {
         new ProcessExpectedEvent <IEntityViewSetWithChangesLoaded <TEntityView> > (
             "EntityViewSet", processId, e => e.EntitySet != null, expectedSourceType: new SourceType(typeof(IEntityViewRepository)),
             processInfo: new StateEventInfo(processId, RevolutionData.Context.EntityView.Events.EntityViewSetLoaded))
     },
                expectedMessageType: typeof(IProcessStateList <TEntityView>),
                action: ProcessActions.UpdateEntityViewStateList <TEntityView>(),
                processInfo: new StateCommandInfo(processId, RevolutionData.Context.Process.Commands.UpdateState)));
 }
コード例 #10
0
        public override SyntaxNode CleanUp(SyntaxNode initialSourceNode)
        {
            try
            {
                var window = ProjectItemDetails.ProjectItem.Open(Constants.vsViewKindCode);

                window.Activate();
                ProjectItemDetails.ProjectItem.Document.DTE.ExecuteCommand(UsingsCommands.REMOVE_AND_SORT_COMMAND_NAME);
                window.Close(vsSaveChanges.vsSaveChangesYes);
            }
            catch (Exception e)
            {
                ErrorNotification.EmailError(e);
                ProcessActions.GeeksProductivityToolsProcess();
            }
            return(ProjectItemDetails.ProjectItem.ToSyntaxNode());
        }
コード例 #11
0
            public static ComplexEventAction IntializePulledProcessState <TEntityView>(int processId, string entityName) where TEntityView : SystemInterfaces.IEntityView
            {
                return(new ComplexEventAction(

                           key: $"InitalizeProcessState-{typeof(TEntityView).GetFriendlyName()}",
                           processId: processId,
                           events: new List <IProcessExpectedEvent>
                {
                    new ProcessExpectedEvent(key: "ProcessStarted",
                                             processId: processId,
                                             eventPredicate: e => e != null,
                                             eventType: typeof(ISystemProcessStarted),
                                             processInfo: new StateEventInfo(processId, RevolutionData.Context.Process.Events.ProcessStarted),
                                             expectedSourceType: new SourceType(typeof(IComplexEventService))),
                },
                           expectedMessageType: typeof(IProcessStateMessage <TEntityView>),
                           action: ProcessActions.IntializePulledProcessState <TEntityView>(entityName),
                           processInfo: new StateCommandInfo(processId, RevolutionData.Context.Process.Commands.CreateState)));
            }
コード例 #12
0
        public static void Invoke(TargetAction action, CleanupOptions cleanupOptions)
        {
            try
            {
                var ideSelectedItems = DteServiceProvider.Instance.SelectedItems;

                for (int itemIndex = 1; itemIndex <= ideSelectedItems.Count; itemIndex++)
                {
                    var selectItem = ideSelectedItems.Item(itemIndex);

                    var selectedProjectItem = selectItem.ProjectItem;

                    if (selectedProjectItem != null)
                    {
                        if (selectedProjectItem.ProjectItems == null || selectedProjectItem.ProjectItems.Count == 0 && action != null)
                        {
                            action(selectedProjectItem, cleanupOptions, true);
                        }
                        else
                        {
                            ActionCSharpOnProjectItem.Action(selectedProjectItem, action, cleanupOptions);
                        }
                    }
                    else if (selectItem.Project != null)
                    {
                        ActionCSharpOnProject.Invoke(action, cleanupOptions);
                    }
                    else
                    {
                        ActionCSharpOnSolution.Invoke(action, cleanupOptions);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorNotification.WriteErrorToFile(e);
                ErrorNotification.WriteErrorToOutputWindow(e);
                ProcessActions.GeeksProductivityToolsProcess();
            }
        }
コード例 #13
0
        public static void Invoke(TargetAction action, Definition.CodeCleanerType[] type)
        {
            try
            {
                var ideSelectedItems = DteServiceProvider.Instance.SelectedItems;

                for (int itemIndex = 1; itemIndex <= ideSelectedItems.Count; itemIndex++)
                {
                    var selectItem = ideSelectedItems.Item(itemIndex);

                    var selectedProjectItem = selectItem.ProjectItem;

                    if (selectedProjectItem != null)
                    {
                        if (selectedProjectItem.ProjectItems == null || selectedProjectItem.ProjectItems.Count == 0)
                        {
                            action(selectedProjectItem, type, true);
                        }
                        else
                        {
                            ActionCSharpOnProjectItem.Action(selectedProjectItem, action, type);
                        }
                    }
                    else if (selectItem.Project != null)
                    {
                        ActionCSharpOnProject.Invoke(action, type);
                    }
                    else
                    {
                        ActionCSharpOnSolution.Invoke(action, type);
                    }
                }
            }
            catch (Exception e)
            {
                ErrorNotification.EmailError(e);
                ProcessActions.GeeksProductivityToolsProcess();
            }
        }
コード例 #14
0
        private void processPropertiesMenuItem_Click(object sender, EventArgs e)
        {
            string type = listHandles.SelectedItems[0].SubItems[1].Text;
            int    pid;

            if (type == "DLL" || type == "Mapped File")
            {
                pid = (int)listHandles.SelectedItems[0].Tag;
            }
            else
            {
                pid = ((SystemHandleEntry)listHandles.SelectedItems[0].Tag).ProcessId;
            }

            if (Program.ProcessProvider.Dictionary.ContainsKey(pid))
            {
                ProcessActions.ShowProperties(this, pid, Program.ProcessProvider.Dictionary[pid].Name);
            }
            else
            {
                PhUtils.ShowError("The process does not exist.");
            }
        }
コード例 #15
0
        public override SyntaxNode CleanUp(SyntaxNode initialSourceNode)
        {
            try
            {
                Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

                var window = ProjectItemDetails.ProjectItem.Open(Constants.vsViewKindCode);
                //window = ProjectItemDetails.ProjectItem.Document.DTE
                //    .ItemOperations.OpenFile(ProjectItemDetails.ProjectItem.Document.Path
                //    , Constants.vsViewKindCode);
                //window.Activate();
                ProjectItemDetails.ProjectItem.Document.Activate();
                ProjectItemDetails.ProjectItem.Document.DTE.ExecuteCommand(UsingsCommands.REMOVE_AND_SORT_COMMAND_NAME);
                ProjectItemDetails.ProjectItem.Document.Save();
                //window.Document.Save();
            }
            catch (Exception e)
            {
                ErrorNotification.EmailError(e);
                ProcessActions.GeeksProductivityToolsProcess();
            }

            return(ProjectItemDetails.ProjectItem.ToSyntaxNode());
        }
コード例 #16
0
        public static void DoCleanup(ProjectItem item, CleanupOptions cleanupOptions, bool fileWindowMustBeOpend = false)
        {
            if (!item.IsCsharpFile() || item.IsCSharpDesignerFile())
            {
                return;
            }

            try
            {
                var path = item.Properties.Item("FullPath").Value.ToString();
                if (path.EndsWithAny(new[] { "AssemblyInfo.cs", "TheApplication.cs" }))
                {
                    return;
                }

                var documentText = item.ToSyntaxNode().SyntaxTree.GetText().ToString();
                if (documentText.Contains("[EscapeGCop(\"Auto generated code.\")]"))
                {
                    return;
                }

                if (item.ToSyntaxNode()
                    .DescendantNodesOfType <AttributeSyntax>()
                    .Any(x => x.Name.ToString() == "EscapeGCop" &&
                         x.ArgumentList != null &&
                         x.ArgumentList.Arguments.FirstOrDefault().ToString()
                         == "\"Auto generated code.\""))
                {
                    return;
                }

                var window = item.Open(Constants.vsViewKindCode);
                window.Activate();

                foreach (var actionTypeItem in cleanupOptions.ActionTypes)
                {
                    if (actionTypeItem == VSIX.TidyCSharp.Cleanup.CodeCleanerType.NormalizeWhiteSpaces)
                    {
                        continue;
                    }
                    if (actionTypeItem == VSIX.TidyCSharp.Cleanup.CodeCleanerType.OrganizeUsingDirectives)
                    {
                        continue;
                    }
                    if (actionTypeItem == VSIX.TidyCSharp.Cleanup.CodeCleanerType.ConvertMsharpGeneralMethods)
                    {
                        continue;
                    }

                    CodeCleanerHost.Run(item, actionTypeItem, cleanupOptions);
                }

                if (cleanupOptions.ActionTypes.Contains(VSIX.TidyCSharp.Cleanup.CodeCleanerType.NormalizeWhiteSpaces))
                {
                    CodeCleanerHost.Run(item, VSIX.TidyCSharp.Cleanup.CodeCleanerType.NormalizeWhiteSpaces, cleanupOptions);
                }

                if (cleanupOptions.ActionTypes.Contains(VSIX.TidyCSharp.Cleanup.CodeCleanerType.OrganizeUsingDirectives))
                {
                    window.Document.Close(vsSaveChanges.vsSaveChangesYes);

                    CodeCleanerHost.Run(item, VSIX.TidyCSharp.Cleanup.CodeCleanerType.OrganizeUsingDirectives, cleanupOptions);

                    if (fileWindowMustBeOpend == false)
                    {
                        window = item.Open(Constants.vsViewKindCode);

                        window.Activate();
                    }
                }
                else
                {
                    window.Document.Save();
                }

                if (cleanupOptions.ActionTypes.Contains(VSIX.TidyCSharp.Cleanup.CodeCleanerType.ConvertMsharpGeneralMethods))
                {
                    CodeCleanerHost.Run(item, VSIX.TidyCSharp.Cleanup.CodeCleanerType.ConvertMsharpGeneralMethods, cleanupOptions);
                }

                if (fileWindowMustBeOpend == false)
                {
                    window.Close(vsSaveChanges.vsSaveChangesYes);
                }
            }
            catch (Exception e)
            {
                ErrorNotification.WriteErrorToFile(e, item.Properties.Item("FullPath").Value.ToString());
                ErrorNotification.WriteErrorToOutputWindow(e, item.Properties.Item("FullPath").Value.ToString());
                ProcessActions.GeeksProductivityToolsProcess();
            }
        }
コード例 #17
0
        public static void ReportOnlyDoNotCleanup(ProjectItem item, CleanupOptions cleanupOptions, bool fileWindowMustBeOpend = false)
        {
            if (!item.IsCsharpFile() || item.IsCSharpDesignerFile())
            {
                return;
            }

            try
            {
                ThreadHelper.JoinableTaskFactory
                .Run(async delegate
                {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                });

                // Sometimes cannot find document's file
                try
                {
                    var documentText = item.ToSyntaxNode().SyntaxTree.GetText().ToString();
                    if (documentText.Contains("[EscapeGCop(\"Auto generated code.\")]"))
                    {
                        return;
                    }
                }
                catch
                {
                    return;
                }

                var path = item.Properties.Item("FullPath").Value.ToString();
                if (path.EndsWithAny(new[] { "AssemblyInfo.cs", "TheApplication.cs" }))
                {
                    return;
                }

                using (var tidyruntimelog = new StreamWriter(Path.Combine(Path.GetTempPath(), "TidyCurrentfilelog.txt"), true))
                    tidyruntimelog.WriteLine(path);


                foreach (var actionTypeItem in cleanupOptions.ActionTypes)
                {
                    if (actionTypeItem != VSIX.TidyCSharp.Cleanup.CodeCleanerType.NormalizeWhiteSpaces &&
                        actionTypeItem != VSIX.TidyCSharp.Cleanup.CodeCleanerType.OrganizeUsingDirectives &&
                        actionTypeItem != VSIX.TidyCSharp.Cleanup.CodeCleanerType.ConvertMsharpGeneralMethods)
                    {
                        var watch = System.Diagnostics.Stopwatch.StartNew();
                        CodeCleanerHost.Run(item, actionTypeItem, cleanupOptions, true);
                        watch.Stop();

                        using (var tidyruntimelog = new StreamWriter(Path.Combine(Path.GetTempPath(), "TidyCurrentActionslog.txt"), true))
                        {
                            tidyruntimelog.WriteLine("Phase1-" + actionTypeItem.ToString() + "-" + watch.ElapsedMilliseconds + " ms");
                        }
                    }
                }

                if (cleanupOptions.ActionTypes.Contains(VSIX.TidyCSharp.Cleanup.CodeCleanerType.NormalizeWhiteSpaces))
                {
                    var watch = System.Diagnostics.Stopwatch.StartNew();
                    CodeCleanerHost.Run(item, VSIX.TidyCSharp.Cleanup.CodeCleanerType.NormalizeWhiteSpaces, cleanupOptions, true);
                    watch.Stop();

                    using (var tidyruntimelog = new StreamWriter(Path.Combine(Path.GetTempPath(), "TidyCurrentActionslog.txt"), true))
                    {
                        tidyruntimelog.WriteLine("Phase2-" + "NormalizeWhiteSpaces" + "-" + watch.ElapsedMilliseconds + " ms");
                    }
                }

                if (cleanupOptions.ActionTypes.Contains(VSIX.TidyCSharp.Cleanup.CodeCleanerType.OrganizeUsingDirectives))
                {
                    var watch = System.Diagnostics.Stopwatch.StartNew();
                    CodeCleanerHost.Run(item, VSIX.TidyCSharp.Cleanup.CodeCleanerType.OrganizeUsingDirectives, cleanupOptions, true);
                    watch.Stop();

                    using (var tidyruntimelog = new StreamWriter(Path.Combine(Path.GetTempPath(), "TidyCurrentActionslog.txt"), true))
                    {
                        tidyruntimelog.WriteLine("Phase3-" + "OrganizeUsingDirectives" + "-" + watch.ElapsedMilliseconds + " ms");
                    }
                }

                if (cleanupOptions.ActionTypes.Contains(VSIX.TidyCSharp.Cleanup.CodeCleanerType.ConvertMsharpGeneralMethods))
                {
                    var watch = System.Diagnostics.Stopwatch.StartNew();
                    CodeCleanerHost.Run(item, VSIX.TidyCSharp.Cleanup.CodeCleanerType.ConvertMsharpGeneralMethods, cleanupOptions, true);
                    watch.Stop();

                    using (var tidyruntimelog = new StreamWriter(Path.Combine(Path.GetTempPath(), "TidyCurrentActionslog.txt"), true))
                    {
                        tidyruntimelog.WriteLine("Phase4-" + "ConvertMsharpGeneralMethods" + "-" + watch.ElapsedMilliseconds + " ms");
                    }
                }
            }
            catch (Exception e)
            {
                ErrorNotification.WriteErrorToFile(e, item.Properties.Item("FullPath").Value.ToString());
                ErrorNotification.WriteErrorToOutputWindow(e, item.Properties.Item("FullPath").Value.ToString());
                ProcessActions.GeeksProductivityToolsProcess();
            }
        }
コード例 #18
0
        public static void Run(IDictionary <string, string> args)
        {
            try
            {
                ThemingScope.Activate();
            }
            catch
            { }

            if (!args.ContainsKey("-type"))
            {
                throw new Exception("-type switch required.");
            }

            string type = args["-type"].ToLowerInvariant();

            if (!args.ContainsKey("-obj"))
            {
                throw new Exception("-obj switch required.");
            }

            string obj = args["-obj"];

            if (!args.ContainsKey("-action"))
            {
                throw new Exception("-action switch required.");
            }

            string action = args["-action"].ToLowerInvariant();

            WindowFromHandle window = new WindowFromHandle(IntPtr.Zero);

            if (args.ContainsKey("-hwnd"))
            {
                window = new WindowFromHandle(new IntPtr(int.Parse(args["-hwnd"])));
            }

            try
            {
                switch (type)
                {
                case "processhacker":
                {
                    switch (action)
                    {
                    case "runas":
                    {
                        using (var manager = new ServiceManagerHandle(ScManagerAccess.CreateService))
                        {
                            Random r           = new Random((int)(DateTime.Now.ToFileTime() & 0xffffffff));
                            string serviceName = "";

                            for (int i = 0; i < 8; i++)
                            {
                                serviceName += (char)('A' + r.Next(25));
                            }

                            using (var service = manager.CreateService(
                                       serviceName,
                                       serviceName + " (Process Hacker Assistant)",
                                       ServiceType.Win32OwnProcess,
                                       ServiceStartType.DemandStart,
                                       ServiceErrorControl.Ignore,
                                       obj,
                                       "",
                                       "LocalSystem",
                                       null))
                            {
                                // Create a mailslot so we can receive the error code for Assistant.
                                using (var mhandle = MailslotHandle.Create(
                                           FileAccess.GenericRead, @"\Device\Mailslot\" + args["-mailslot"], 0, 5000)
                                       )
                                {
                                    try { service.Start(); }
                                    catch { }
                                    service.Delete();

                                    Win32Error errorCode = (Win32Error)mhandle.Read(4).ToInt32();

                                    if (errorCode != Win32Error.Success)
                                    {
                                        throw new WindowsException(errorCode);
                                    }
                                }
                            }
                        }
                    }
                    break;

                    default:
                        throw new Exception("Unknown action '" + action + "'");
                    }
                }
                break;

                case "process":
                {
                    var      processes  = Windows.GetProcesses();
                    string[] pidStrings = obj.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    int[]    pids       = new int[pidStrings.Length];
                    string[] names      = new string[pidStrings.Length];

                    for (int i = 0; i < pidStrings.Length; i++)
                    {
                        pids[i]  = int.Parse(pidStrings[i]);
                        names[i] = processes[pids[i]].Name;
                    }

                    switch (action)
                    {
                    case "terminate":
                        ProcessActions.Terminate(window, pids, names, true);
                        break;

                    case "suspend":
                        ProcessActions.Suspend(window, pids, names, true);
                        break;

                    case "resume":
                        ProcessActions.Resume(window, pids, names, true);
                        break;

                    case "reduceworkingset":
                        ProcessActions.ReduceWorkingSet(window, pids, names, false);
                        break;

                    default:
                        throw new Exception("Unknown action '" + action + "'");
                    }
                }
                break;

                case "thread":
                {
                    foreach (string tid in obj.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        switch (action)
                        {
                        case "terminate":
                        {
                            try
                            {
                                using (var thandle =
                                           new ThreadHandle(int.Parse(tid), ThreadAccess.Terminate))
                                    thandle.Terminate();
                            }
                            catch (Exception ex)
                            {
                                DialogResult result = MessageBox.Show(window,
                                                                      "Could not terminate thread with ID " + tid + ":\n\n" +
                                                                      ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                if (result == DialogResult.Cancel)
                                {
                                    return;
                                }
                            }
                        }
                        break;

                        case "suspend":
                        {
                            try
                            {
                                using (var thandle =
                                           new ThreadHandle(int.Parse(tid), ThreadAccess.SuspendResume))
                                    thandle.Suspend();
                            }
                            catch (Exception ex)
                            {
                                DialogResult result = MessageBox.Show(window,
                                                                      "Could not suspend thread with ID " + tid + ":\n\n" +
                                                                      ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                if (result == DialogResult.Cancel)
                                {
                                    return;
                                }
                            }
                        }
                        break;

                        case "resume":
                        {
                            try
                            {
                                using (var thandle =
                                           new ThreadHandle(int.Parse(tid), ThreadAccess.SuspendResume))
                                    thandle.Resume();
                            }
                            catch (Exception ex)
                            {
                                DialogResult result = MessageBox.Show(window,
                                                                      "Could not resume thread with ID " + tid + ":\n\n" +
                                                                      ex.Message, "Process Hacker", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

                                if (result == DialogResult.Cancel)
                                {
                                    return;
                                }
                            }
                        }
                        break;

                        default:
                            throw new Exception("Unknown action '" + action + "'");
                        }
                    }
                }
                break;

                case "service":
                {
                    switch (action)
                    {
                    case "start":
                    {
                        ServiceActions.Start(window, obj, false);
                    }
                    break;

                    case "continue":
                    {
                        ServiceActions.Continue(window, obj, false);
                    }
                    break;

                    case "pause":
                    {
                        ServiceActions.Pause(window, obj, false);
                    }
                    break;

                    case "stop":
                    {
                        ServiceActions.Stop(window, obj, false);
                    }
                    break;

                    case "delete":
                    {
                        ServiceActions.Delete(window, obj, true);
                    }
                    break;

                    case "config":
                    {
                        using (ServiceHandle service = new ServiceHandle(obj, ServiceAccess.ChangeConfig))
                        {
                            ServiceType serviceType;

                            if (args["-servicetype"] == "Win32OwnProcess, InteractiveProcess")
                            {
                                serviceType = ServiceType.Win32OwnProcess | ServiceType.InteractiveProcess;
                            }
                            else if (args["-servicetype"] == "Win32ShareProcess, InteractiveProcess")
                            {
                                serviceType = ServiceType.Win32ShareProcess | ServiceType.InteractiveProcess;
                            }
                            else
                            {
                                serviceType = (ServiceType)Enum.Parse(typeof(ServiceType), args["-servicetype"]);
                            }

                            var startType = (ServiceStartType)
                                            Enum.Parse(typeof(ServiceStartType), args["-servicestarttype"]);
                            var errorControl = (ServiceErrorControl)
                                               Enum.Parse(typeof(ServiceErrorControl), args["-serviceerrorcontrol"]);

                            string binaryPath     = null;
                            string loadOrderGroup = null;
                            string userAccount    = null;
                            string password       = null;

                            if (args.ContainsKey("-servicebinarypath"))
                            {
                                binaryPath = args["-servicebinarypath"];
                            }
                            if (args.ContainsKey("-serviceloadordergroup"))
                            {
                                loadOrderGroup = args["-serviceloadordergroup"];
                            }
                            if (args.ContainsKey("-serviceuseraccount"))
                            {
                                userAccount = args["-serviceuseraccount"];
                            }
                            if (args.ContainsKey("-servicepassword"))
                            {
                                password = args["-servicepassword"];
                            }

                            if (!Win32.ChangeServiceConfig(service,
                                                           serviceType, startType, errorControl,
                                                           binaryPath, loadOrderGroup, IntPtr.Zero, null, userAccount, password, null))
                            {
                                Win32.Throw();
                            }
                        }
                    }
                    break;

                    default:
                        throw new Exception("Unknown action '" + action + "'");
                    }
                }
                break;

                case "session":
                {
                    int sessionId = int.Parse(obj);

                    switch (action)
                    {
                    case "disconnect":
                    {
                        SessionActions.Disconnect(window, sessionId, false);
                    }
                    break;

                    case "logoff":
                    {
                        SessionActions.Logoff(window, sessionId, false);
                    }
                    break;

                    default:
                        throw new Exception("Unknown action '" + action + "'");
                    }
                }
                break;

                default:
                    throw new Exception("Unknown object type '" + type + "'");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(window, ex.Message, "Process Hacker", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #19
0
        public static void DoCleanup(ProjectItem item, CleanupOptions cleanupOptions, bool fileWindowMustBeOpend = false)
        {
            if (!item.IsCsharpFile() || item.IsCSharpDesignerFile())
            {
                return;
            }

            try
            {
                var path = item.Properties.Item("FullPath").Value.ToString();
                if (path.EndsWithAny(new[] { "AssemblyInfo.cs", "TheApplication.cs" }))
                {
                    return;
                }

                var window = item.Open(Constants.vsViewKindCode);

                window.Activate();

                foreach (var actionTypeItem in cleanupOptions.ActionTypes)
                {
                    if (actionTypeItem == VSIX.TidyCSharp.Cleanup.CodeCleanerType.NormalizeWhiteSpaces)
                    {
                        continue;
                    }
                    if (actionTypeItem == VSIX.TidyCSharp.Cleanup.CodeCleanerType.OrganizeUsingDirectives)
                    {
                        continue;
                    }

                    CodeCleanerHost.Run(item, actionTypeItem, cleanupOptions);
                }

                if (cleanupOptions.ActionTypes.Contains(VSIX.TidyCSharp.Cleanup.CodeCleanerType.NormalizeWhiteSpaces))
                {
                    CodeCleanerHost.Run(item, VSIX.TidyCSharp.Cleanup.CodeCleanerType.NormalizeWhiteSpaces, cleanupOptions);
                }

                if (cleanupOptions.ActionTypes.Contains(VSIX.TidyCSharp.Cleanup.CodeCleanerType.OrganizeUsingDirectives))
                {
                    window.Document.Close(vsSaveChanges.vsSaveChangesYes);

                    CodeCleanerHost.Run(item, VSIX.TidyCSharp.Cleanup.CodeCleanerType.OrganizeUsingDirectives, cleanupOptions);

                    if (fileWindowMustBeOpend == false)
                    {
                        window = item.Open(Constants.vsViewKindCode);

                        window.Activate();
                    }
                }
                else
                {
                    window.Document.Save();
                }

                if (fileWindowMustBeOpend == false)
                {
                    window.Close(vsSaveChanges.vsSaveChangesYes);
                }
            }
            catch (Exception e)
            {
                ErrorNotification.EmailError(e);
                ProcessActions.GeeksProductivityToolsProcess();
            }
        }