public void UpdateProcess(string computerId, string processId, ProcessDTO process)
        {
            ProcessPerfomance newProcessPerfomance = _mapper.Map <ProcessPerfomanceDTO, ProcessPerfomance>
                                                         (process.PerfomanceInformation);

            newProcessPerfomance.CreationDate = process.Information.CreationDate;
            newProcessPerfomance.RecordDate   = DateTime.Now;
            newProcessPerfomance.ProcessId    = processId;
            _unitOfWork.ProcessesPerfomance.Add(newProcessPerfomance);
            _unitOfWork.SaveChanges();

            ProcessInformation dbprocessInformation = _unitOfWork.ProcessesInformation
                                                      .GetProcessInformationByProcessId(processId);

            if (dbprocessInformation != null)
            {
                _unitOfWork.ProcessesInformation.Remove(dbprocessInformation);
            }
            ProcessInformation newProcessInformation = _mapper.Map <ProcessInformationDTO, ProcessInformation>
                                                           (process.Information);

            newProcessInformation.ProcessId = processId;

            _unitOfWork.ProcessesInformation.Add(newProcessInformation);
            _unitOfWork.SaveChanges();
        }
示例#2
0
 private static extern bool UnmanagedCreateProcess(string lpApplicationName,
                                                   string lpCommandLine, IntPtr lpProcessAttributes,
                                                   IntPtr lpThreadAttributes,
                                                   bool bInheritHandles, ProcessCreationFlags dwCreationFlags,
                                                   IntPtr lpEnvironment, string lpCurrentDirectory,
                                                   ref ProcessStartupInfo lpStartupInfo,
                                                   out ProcessInformation lpProcessInformation);
 public ProfiledProcessManager(int profiledProcessId)
 {
     _process         = Process.GetProcessById(profiledProcessId);
     _process.Exited += OnProfiledProcessExited;
     _process.EnableRaisingEvents = true;
     _processInformation          = new ProcessInformation(_process.Id, _process.ProcessName, new byte[0], _process.StartTime);
 }
        public void AddProcess(string computerId, ProcessDTO process)
        {
            Process newProcess = new Process
            {
                ComputerId = computerId,
                Name       = process.Information.Name,
            };

            _unitOfWork.Processes.Add(newProcess);
            _unitOfWork.SaveChanges();
            string processId = _unitOfWork.Processes
                               .GetProcessByComputerIdAndName(computerId, process.Information.Name).Id;

            ProcessPerfomance newProcessPerfomance = _mapper.Map <ProcessPerfomanceDTO, ProcessPerfomance>
                                                         (process.PerfomanceInformation);

            newProcessPerfomance.CreationDate = process.Information.CreationDate;
            newProcessPerfomance.ProcessId    = processId;
            newProcessPerfomance.RecordDate   = DateTime.Now;
            _unitOfWork.ProcessesPerfomance.Add(newProcessPerfomance);
            _unitOfWork.SaveChanges();

            ProcessInformation newProcessInformation = _mapper.Map <ProcessInformationDTO, ProcessInformation>
                                                           (process.Information);

            newProcessInformation.ProcessId = processId;
            _unitOfWork.ProcessesInformation.Add(newProcessInformation);
            _unitOfWork.SaveChanges();
        }
示例#5
0
        private void playButtonPanel_MouseUp(object sender, MouseEventArgs e)
        {
            if (usernameTextBox1.Text == "username" || usernameTextBox1.Text == "" || passwordTextBox1.Text == "password" || passwordTextBox1.Text == "")
            {
                MessageBox.Show(this, "Please fill out both username and password fields.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            new Task(() => {
                if (ProcessInformation.IsOpen("Project Altis Launcher"))
                {
                    HandleIDs.SendMessage(
                        HandleIDs.GetChildWindows(ProcessInformation.WindowHandle("Project Altis Launcher"))[(int)ControlLocation.UsernameText],
                        (int)WindowMessages.WM_SETTEXT, 0, usernameTextBox1.Text
                        );

                    HandleIDs.SendMessage(
                        HandleIDs.GetChildWindows(ProcessInformation.WindowHandle("Project Altis Launcher"))[(int)ControlLocation.PasswordText],
                        (int)WindowMessages.WM_SETTEXT, 0, passwordTextBox1.Text
                        );

                    HandleIDs.SendMessage(
                        HandleIDs.GetChildWindows(ProcessInformation.WindowHandle("Project Altis Launcher"))[(int)ControlLocation.PlayButton],
                        (int)WindowMessages.BM_CLICK, 0, null
                        );
                }
            }).Start();

            loadingLabel.Visible    = true;
            loadingProgress.Visible = true;
            loadingProgress.MarqueeAnimationSpeed = 30;
        }
示例#6
0
    public static void Main()
    {
        ProcessInformation PSI = new ProcessInformation();

        //Checking spotify available.
        if (PSI.isAvailable())
        {
            NameChangeTracker.create_object();                //Method call to create objects.
            NameChangeTracker NCT  = new NameChangeTracker(); //constructor call;
            IntPtr            hWnd = NameChangeTracker.hwnd_spotify;
            int pid = NameChangeTracker.processid;

            // Listen for name change changes for spotify(check pid!=0).
            IntPtr hWinEventHook = SetWinEventHook(0x0800c, 0x800c, IntPtr.Zero, procDelegate, Convert.ToUInt32(pid), 0, 0);
            // Listen for create window event across all processes/threads on current desktop.(check pid=0)
            IntPtr hWinEventHook_start = SetWinEventHook(0x00008000, 0x00008000, IntPtr.Zero, procDelegate_start, 0, 0, 0);

            Message msg = new Message();

            //GetMessage provides the necessary mesage loop that SetWinEventHook requires.

            while (GetMessage(ref msg, hWnd, 0, 0))
            {
                UnhookWinEvent(hWinEventHook);
                UnhookWinEvent(hWinEventHook_start);
            }
        }

        else
        {
            //Executed if spotify not running.
            MessageBox.Show("check spotify running or not", "Spotify Not Found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
示例#7
0
 private void sanityChecks_Tick(object sender, EventArgs e)
 {
     if (ProcessInformation.IsOpen("Altis"))
     {
         this.Close();
     }
 }
        /// <summary>
        /// Shows the exported funtions helper.
        /// </summary>
        /// <param name="process">The process.</param>
        /// <param name="selected">The selected.</param>
        private void ShowExportedFuntionsHelper(ProcessInformation process, ModuleInfo selected)
        {
            using (BackgroundWorker worker = new BackgroundWorker()) {
                // Work to do
                worker.DoWork += delegate(object a, DoWorkEventArgs b) {
                    ManageVisualState(AnimationState.Loading);
                    var symbols = DataExchange.GetSymbols(process.ProcessId.ToString(), selected);
                    b.Result = new object[] { symbols, selected };
                };

                // Code executed when Backgroundworker is completed
                worker.RunWorkerCompleted += delegate(object a, RunWorkerCompletedEventArgs b) {
                    ManageVisualState(AnimationState.Loaded);
                    ModuleInfo module = (ModuleInfo)((object[])b.Result)[1];
                    IEnumerable <SymbolInfo> symbols = (IEnumerable <SymbolInfo>)((object[])b.Result)[0];

                    if (symbols.Any())
                    {
                        (new Symbols(symbols, module)
                        {
                            Owner = this
                        }).ShowDialog();
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("The selected module does not export any symbol", "Information",
                                                       MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                };
                worker.RunWorkerAsync();
            }
        }
        static void InsertProcess(ProcessInformation proc_info)
        {
            var proc = new ServerResourcesDataAccess.Process()
            {
                Name   = proc_info.Name,
                Status = proc_info.Status,
                PID    = proc_info.Pid
            };

            using (var context = new ServerResourcesContext())
            {
                var associated_proc = context.Process.Where(P => P.Name == proc.Name).SingleOrDefault();
                proc.Server_User_FK = context.Server_User.Where(SU => SU.Name == proc_info.User).SingleOrDefault().Id;

                if (associated_proc != null)
                {
                    associated_proc.PID            = proc.PID;
                    associated_proc.Server_User_FK = proc.Server_User_FK;
                }
                else
                {
                    context.Add(proc);
                }

                context.SaveChanges();
            }
        }
示例#10
0
        private static void set_environment_options(ChocolateyConfiguration config)
        {
            config.Information.PlatformType             = Platform.get_platform();
            config.Information.PlatformVersion          = Platform.get_version();
            config.Information.PlatformName             = Platform.get_name();
            config.Information.ChocolateyVersion        = VersionInformation.get_current_assembly_version();
            config.Information.ChocolateyProductVersion = VersionInformation.get_current_informational_version();
            config.Information.FullName = Assembly.GetExecutingAssembly().FullName;
            config.Information.Is64BitOperatingSystem = Environment.Is64BitOperatingSystem;
            config.Information.Is64BitProcess         = (IntPtr.Size == 8);
            config.Information.IsInteractive          = Environment.UserInteractive;
            config.Information.UserName            = System.Environment.UserName;
            config.Information.UserDomainName      = System.Environment.UserDomainName;
            config.Information.IsUserAdministrator = ProcessInformation.user_is_administrator();
            config.Information.IsUserSystemAccount = ProcessInformation.user_is_system();
            config.Information.IsUserRemoteDesktop = ProcessInformation.user_is_terminal_services();
            config.Information.IsUserRemote        = ProcessInformation.user_is_remote();
            config.Information.IsProcessElevated   = ProcessInformation.process_is_elevated();

            if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("https_proxy")) && string.IsNullOrWhiteSpace(config.Proxy.Location))
            {
                config.Proxy.Location = Environment.GetEnvironmentVariable("https_proxy");
            }

            if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("http_proxy")) && string.IsNullOrWhiteSpace(config.Proxy.Location))
            {
                config.Proxy.Location = Environment.GetEnvironmentVariable("http_proxy");
            }

            if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("no_proxy")) && string.IsNullOrWhiteSpace(config.Proxy.BypassList))
            {
                config.Proxy.BypassList = Environment.GetEnvironmentVariable("no_proxy");
            }
        }
        /// <summary>
        /// Displays the memory helper.
        /// </summary>
        /// <param name="process">The process.</param>
        /// <param name="selected">The selected.</param>
        private void DisplayMemoryHelper(ProcessInformation process, ModuleInfo selected)
        {
            using (BackgroundWorker worker = new BackgroundWorker()) {
                // Work to do
                worker.DoWork += delegate(object a, DoWorkEventArgs b) {
                    ManageVisualState(AnimationState.Loading);

                    var allocations = DataExchange.GetAllocations(process.ProcessId.ToString(), selected.Name)
                                      .Where(x => !string.IsNullOrEmpty(x.AllocationBaseInHex) &&
                                             x.AllocationBaseInHex.Equals(selected.BaseOfDllInHex,
                                                                          StringComparison.OrdinalIgnoreCase));

                    b.Result = new object[] { allocations, selected.Name, process.ProcessId.ToString() };
                };

                // Code executed when Backgroundworker is completed
                worker.RunWorkerCompleted += delegate(object a, RunWorkerCompletedEventArgs b) {
                    ManageVisualState(AnimationState.Loaded);
                    string v = ((object[])b.Result)[1].ToString(), w = ((object[])b.Result)[2].ToString();
                    IEnumerable <AllocationInformation> allocations = (IEnumerable <AllocationInformation>)((object[])b.Result)[0];

                    if (allocations.Any())
                    {
                        (new MemoryAllocation(allocations, v, w)).ShowDialog();
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("Unable to retrieve allocation information", "Information",
                                                       MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                };
                worker.RunWorkerAsync();
            }
        }
示例#12
0
        public static extern IntPtr CreateProcessA(String lpApplicationName, String lpCommandLine, SecurityAttributes lpProcessAttributes, SecurityAttributes lpThreadAttributes, Boolean bInheritHandles, CreateProcessFlags dwCreationFlags,
                                                   IntPtr lpEnvironment,
                                                   String lpCurrentDirectory,
                                                   [In] StartupInfo lpStartupInfo,
                                                   out ProcessInformation lpProcessInformation

                                                   );
 public static bool MobiIt(string HTMLFile)
 {
     fileLocation mobiFiles = new fileLocation();
     GatherFileInformation fileHandler = new GatherFileInformation(HTMLFile);
     mobiFiles = fileHandler.Getfiles();
     if (mobiFiles.fileExt.ToLower() == "html" || mobiFiles.fileExt.ToLower() == "htm")
     {
         ProcessInformation mobiApp = new ProcessInformation();
         mobiApp.applicationString = @"app\mobigen.exe";
         mobiApp.applicationSwitch = null;
         mobiApp.applicationArgString = "\"" + mobiFiles.fileLocationDir + "\\" + mobiFiles.fileName + "." + mobiFiles.fileExt + "\"";
         ExecuteExternalProcessor mobiProcessor = new ExecuteExternalProcessor(mobiApp);
         if (!File.Exists(mobiFiles.fileLocationDir + "\\" + mobiFiles.fileName + ".mobi"))
         {
             DialogResult fileConvertFailed = MessageBox.Show("Display Error Information?", "Conversion Failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
             if (fileConvertFailed == DialogResult.Yes)
             {
                 MessageBox.Show(mobiProcessor.GetapplicationStdOutput());
             }
             return false;
         }
         return true;
     }
     return false;
 }
        private bool CreateProcessACallback(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, IntPtr lpStartupInfo, out ProcessInformation lpProcessInformation)
        {
            // Determine whether the child process belongs to the implementation and also needs hooking
            bool needsInjection;
            try
            {
                string target = Path.GetFullPath(string.IsNullOrEmpty(lpApplicationName) ? lpCommandLine.Trim('"') : lpApplicationName);
                needsInjection = target.StartsWith(_implementationDir) || target.StartsWith('"' + _implementationDir);
            }
            catch
            {
                needsInjection = false;
            }

            // Start the process suspended
            if (needsInjection) dwCreationFlags |= UnsafeNativeMethods.CreateSuspended;

            var result = UnsafeNativeMethods.CreateProcessA(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, out lpProcessInformation);

            // Inject the hooking DLL (and resume the process)
            if (needsInjection)
            {
                RemoteHooking.Inject(lpProcessInformation.dwProcessId, AssemblyStrongName, AssemblyStrongName,
                    // Custom arguments
                    _implementationDir, _registryFilter, _relaunchControl);
            }

            return result;
        }
        public void CanStartMessageBroker()
        {
            var queueFactory = Substitute.For<IQueueFactory>();
            var messageBrokerConfig = new MessageBrokerConfig { RemoteQueueName = "MyRemoteQueueName", ServiceName = "TestBroker" };
            var entityConnectionConfig = new EntityConnectionConfig(new DatabaseConnectionConfig("(localdb)\\MSSQLLocalDB", "ABJA_Ripples"));
            var logger = NullLogger.Instance;
            var repositoryContextFactory = new RepositoryContextFactory(logger, entityConnectionConfig);
            var queueHandlerFactory = new QueueHandlerFactory(logger, queueFactory);
            var processInformation = new ProcessInformation();

            using (var messageBroker = new MessageBroker(logger, messageBrokerConfig, repositoryContextFactory, queueHandlerFactory, queueFactory, processInformation))
            {
                var cancellationToken = new CancellationToken();
                messageBroker.Start(cancellationToken);

                messageBroker.Handler(new MessageBusServiceHandshakeMessage
                {
                    ServiceName = "MyServiceName",
                    ServerName = "MyTestServer",
                    ReplyQueue = "MyQueue",
                    SendDateTime = DateTimeOffset.Now,
                    SubscribeHandlers = new List<SubscribeHandler> { new SubscribeHandler { Name = "MySubscriber", QueueName = "MyQueue", Durable = true, MessageType = "string", Topic = "MyTopic" } }
                });
            }
        }
示例#16
0
        private static void DoCreateProcessA()
        {
            var si = new StartupInfoA();
            var pi = new ProcessInformation();

            Win32Interop.CreateProcessA("c:\\windows\\system32\\Notepad.exe", "", IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero,
                                        null, ref si, ref pi);
        }
示例#17
0
        public async Task <ProcessInformation> GetByIdAsync(int id)
        {
            string cmd = $@"SELECT * FROM `production_process` pp
	                        LEFT JOIN `production` p ON p.id = pp.production_id
	                        LEFT JOIN `gtin` g ON g.id = p.gtin_id
	                        WHERE pp.`is_deleted` = 0 AND pp.`id` = '{id}' "    ;

            var conn = DbConnection;

            if (conn == null)
            {
                conn = DALHelper.GetConnection();
            }
            try
            {
                using (var reader = await conn.QueryMultipleAsync(cmd, transaction: DbTransaction))
                {
                    return(reader.Read <Process, Production, GTIN, ProcessInformation>(
                               (processRs, productionRs, gTINRs) =>
                    {
                        ProcessInformation process = null;
                        if (processRs != null)
                        {
                            var serializedParent = JsonConvert.SerializeObject(processRs);
                            process = JsonConvert.DeserializeObject <ProcessInformation>(serializedParent);
                        }
                        else
                        {
                            process = new ProcessInformation();
                        }

                        if (productionRs != null)
                        {
                            var serializedParent = JsonConvert.SerializeObject(productionRs);
                            process.Production = JsonConvert.DeserializeObject <ProductionInformation>(serializedParent);

                            if (gTINRs != null)
                            {
                                process.Production.GTIN = gTINRs.ToInformation();
                            }
                        }
                        return process;
                    }
                               ).FirstOrDefault());
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (DbConnection == null)
                {
                    conn.Dispose();
                }
            }
        }
示例#18
0
        public static bool launch(string game, string arguments)
        {
            String binPath;
            String exe;
            String dll;

            //Lets get our games straight
            if (game == "ETS2")
            {
                Environment.SetEnvironmentVariable("SteamGameId", "227300");
                Environment.SetEnvironmentVariable("SteamAppID", "227300");

                binPath    = Launcher.ETS2Location + "\\bin\\win_x64";
                exe        = "\\eurotrucks2.exe";
                dll        = "\\core_ets2mp.dll";
                arguments += " -64bit";
            }
            else if (game == "ATS")
            {
                Environment.SetEnvironmentVariable("SteamGameId", "270880");
                Environment.SetEnvironmentVariable("SteamAppID", "270880");

                binPath    = Launcher.ATSLocation + "\\bin\\win_x64";
                exe        = "\\amtrucks.exe";
                dll        = "\\core_atsmp.dll";
                arguments += " -64bit";
            }
            else
            {
                return(false); //Invalid game, lets not do this
            }

            //Intialize variables 'n stuff
            ProcessInformation processInformation  = default(ProcessInformation);
            Startupinfo        startupinfo         = default(Startupinfo);
            SecurityAttributes securityAttributes  = default(SecurityAttributes);
            SecurityAttributes securityAttributes2 = default(SecurityAttributes);

            startupinfo.cb              = Marshal.SizeOf(startupinfo);
            securityAttributes.nLength  = Marshal.SizeOf(securityAttributes);
            securityAttributes2.nLength = Marshal.SizeOf(securityAttributes2);

            //Lets run the game!

            if (!CreateProcess(binPath + exe, arguments, ref securityAttributes, ref securityAttributes2, false, 4u, IntPtr.Zero, binPath, ref startupinfo, out processInformation))
            {
                return(false);
            }

            if (!Inject(processInformation.hProcess, Launcher.TruckersMPLocation + dll))
            {
                return(false);
            }

            ResumeThread(processInformation.hThread);
            return(true);
        }
示例#19
0
        public void ShouldComposeNewProcessInformationForNewGeneration()
        {
            Random rng = new Random();

            for (Int32 i = 0; i < TestConstants.TestRepeats; i++)
            {
                Int32 populationSize = rng.Next(1, 1000);
                Int32 geneSize       = rng.Next(1, 1000);

                Population <TestIndividual <Int32>, Int32> GetPopulation()
                {
                    var population = new Population <TestIndividual <Int32>, Int32>();
                    IList <TestIndividual <Int32> > individuals = new List <TestIndividual <Int32> >();

                    for (Int32 j = 0; j < populationSize; j++)
                    {
                        var newIndividual = new TestIndividual <Int32>();

                        Chromosome <Int32> newChromosome =
                            ChromosomeInitializers.GetRandomChromosome <Chromosome <Int32>, Int32>(geneSize
                                                                                                   , rng_ => ChromosomeInitializers.GetRandomInt32(rng_, 0, 10));

                        newIndividual.SetChromosome(newChromosome);
                        individuals.Add(newIndividual);
                    }

                    population.SetPopulation(individuals);
                    population.OrderByFitness(new PopulationTests.TestFitnessFunctionInt32());

                    return(population);
                }

                Population <TestIndividual <Int32>, Int32> population1 = GetPopulation();
                Population <TestIndividual <Int32>, Int32> population2 = GetPopulation();

                var composer =
                    new ProcessInformationComposer <Population <TestIndividual <Int32>, Int32>, TestIndividual <Int32>,
                                                    Int32>();

                ProcessInformation firstProcessInformation  = composer.ComposeProcessInformation(null, population1);
                ProcessInformation secondProcessInformation =
                    composer.ComposeProcessInformation(firstProcessInformation, population2);

                Assert.Equal(firstProcessInformation.Generation, secondProcessInformation.Generation - 1);

                Assert.Equal(firstProcessInformation.TotalFitnessDelta, firstProcessInformation.TotalFitness);
                Assert.Equal(firstProcessInformation.FittestFitnessDelta, firstProcessInformation.FittestFitness);
                Assert.Equal(firstProcessInformation.FittestNFitnessDelta, firstProcessInformation.FittestNFitness);

                Assert.Equal(secondProcessInformation.TotalFitnessDelta
                             , secondProcessInformation.TotalFitness - firstProcessInformation.TotalFitness);
                Assert.Equal(secondProcessInformation.FittestFitnessDelta
                             , secondProcessInformation.FittestFitness - firstProcessInformation.FittestFitness);
                Assert.Equal(secondProcessInformation.FittestNFitnessDelta
                             , secondProcessInformation.FittestNFitness - firstProcessInformation.FittestNFitness);
            }
        }
        private void UpdateEWA(ProcessInformation aProcessInformation)
        {
            if (!Directory.Exists(Path.Combine(EmpyrionConfiguration.ModPath, @"EWALoader\Update\EWALoader\EWA")))
            {
                return;
            }

            try
            {
                WithinUpdate = true;
                RetrieveHostProcessInformation(aProcessInformation);

                GameAPI.Console_Write($"ModClientDll: EWA_Update");
                OutServer?.SendMessage(new ClientHostComData()
                {
                    Command = ClientHostCommand.UpdateEWA
                });

                if (mHostProcess != null)
                {
                    try
                    {
                        mHostProcessAlive = null;

                        for (int i = 0; i < 5 * 60; i++)
                        {
                            Thread.Sleep(1000);
                            if (mHostProcess.HasExited)
                            {
                                break;
                            }
                        }

                        try { mHostProcess.CloseMainWindow(); } catch { }

                        mHostProcess = null;
                        CurrentConfig.Current.HostProcessId = 0;
                        CurrentConfig.Save();
                    }
                    catch (Exception Error)
                    {
                        GameAPI.Console_Write($"UpdateEWA: Game_Exit {Error}");
                    }
                }

                UpdateEWAFiles();
            }
            catch (Exception Error)
            {
                GameAPI.Console_Write($"UpdateEWA: EWA_Update {Error}");
            }
            finally
            {
                WithinUpdate = false;
            }
        }
示例#21
0
 private void button1_Click(object sender, EventArgs e)
 {
     //exit button gotta fix event name
     if (ProcessInformation.IsOpen(ProcessName))
     {
         Process pName = Process.GetProcessesByName(ProcessName)[0];
         pName.Kill();
     }
     this.Close();
 }
示例#22
0
        private static void DoCreateProcessW(string exeToLaunch, string exeArguments)
        {
            var  si       = new StartupInfoW();
            var  pi       = new ProcessInformation();
            bool processW = Win32WInterop.CreateProcessW(exeToLaunch, exeArguments, IntPtr.Zero, IntPtr.Zero,
                                                         false, 0, IntPtr.Zero,
                                                         null, ref si, ref pi);

            Debug.Assert(processW, "Error creating process");
        }
示例#23
0
 public static extern bool CreateProcess(string lpApplicationName,
                                         string lpCommandLine,
                                         IntPtr lpProcessAttributes,
                                         IntPtr lpThreadAttributes,
                                         [MarshalAs(UnmanagedType.Bool)] bool bInheritHandles,
                                         uint dwCreationFlags,
                                         IntPtr lpEnvironment,
                                         string lpCurrentDirectory,
                                         ref Startupinfo lpStartupInfo,
                                         out ProcessInformation lpProcessInformation);
示例#24
0
 public static extern bool CreateProcessWithTokenW(
     SafeNativeHandle token,
     LogonFlags logonFlags,
     [MarshalAs(UnmanagedType.LPWStr)] string applicationName,
     [MarshalAs(UnmanagedType.LPWStr)] string commandLine,
     ProcessCreationFlags creationFlags,
     IntPtr environment,
     [MarshalAs(UnmanagedType.LPWStr)] string currentDirectory,
     [In] ref StartupInfo startupInfo,
     out ProcessInformation processInformation);
示例#25
0
文件: Kernel32.cs 项目: radtek/WCF
 public static extern bool CreateProcess(String imageName,
                                         String cmdLine,
                                         IntPtr lpProcessAttributes,
                                         IntPtr lpThreadAttributes,
                                         bool boolInheritHandles,
                                         CreationFlags dwCreationFlags,
                                         IntPtr lpEnvironment,
                                         String lpszCurrentDir,
                                         ref StartupInfo si,
                                         out ProcessInformation pi);
示例#26
0
文件: Utils.cs 项目: sys-lam/LOLBITS
 public static extern bool CreateProcessWithTokenW(
     IntPtr hToken,
     LogonFlags dwLogonFlags,
     string lpApplicationName,
     string lpCommandLine,
     CreationFlags dwCreationFlags,
     IntPtr lpEnvironment,
     string lpCurrentDirectory,
     [In] ref StartupInfo lpStartupInfo,
     out ProcessInformation lpProcessInformation);
        public async Task <int> CreateWorkspaceAsync(int templateArtifactId)
        {
            Console2.WriteDisplayStartLine("Creating new Workspace");

            try
            {
                const string workspaceCreationFailErrorMessage = "Failed to create new workspace";
                RsapiClient.APIOptions.WorkspaceID = -1;

                //Create the workspace object and apply any desired properties.
                Workspace newWorkspace = new Workspace
                {
                    Name             = Constants.Workspace.NAME,
                    Accessible       = Constants.Workspace.ACCESSIBLE,
                    DatabaseLocation = Constants.Workspace.DATABASE_LOCATION
                };

                ProcessOperationResult processOperationResult = await Task.Run(() => RsapiClient.Repositories.Workspace.CreateAsync(templateArtifactId, newWorkspace));

                if (!processOperationResult.Success)
                {
                    throw new Exception(workspaceCreationFailErrorMessage);
                }

                ProcessInformation processInformation = await Task.Run(() => RsapiClient.GetProcessState(RsapiClient.APIOptions, processOperationResult.ProcessID));

                const int maxTimeInMilliseconds         = (Constants.Waiting.MAX_WAIT_TIME_IN_MINUTES * 60 * 1000);
                const int sleepTimeInMilliSeconds       = Constants.Waiting.SLEEP_TIME_IN_SECONDS * 1000;
                int       currentWaitTimeInMilliseconds = 0;

                while ((currentWaitTimeInMilliseconds < maxTimeInMilliseconds) && (processInformation.State != ProcessStateValue.Completed))
                {
                    Thread.Sleep(sleepTimeInMilliSeconds);

                    processInformation = await Task.Run(() => RsapiClient.GetProcessState(RsapiClient.APIOptions, processOperationResult.ProcessID));

                    currentWaitTimeInMilliseconds += sleepTimeInMilliSeconds;
                }

                int?workspaceArtifactId = processInformation.OperationArtifactIDs.FirstOrDefault();
                if (workspaceArtifactId == null)
                {
                    throw new Exception(workspaceCreationFailErrorMessage);
                }

                Console2.WriteDebugLine($"Workspace ArtifactId: {workspaceArtifactId.Value}");
                Console2.WriteDisplayEndLine("Created new Workspace!");

                return(workspaceArtifactId.Value);
            }
            catch (Exception ex)
            {
                throw new Exception("An error occured when creating Workspace", ex);
            }
        }
 public static int Create(Relativity.Client.IRSAPIClient proxy, string workspaceName, string templateName, int?serverId = null)
 {
     try
     {
         int num1 = 0;
         proxy.APIOptions.WorkspaceID = -1;
         if (templateName == string.Empty)
         {
             throw new SystemException("Template name is blank in your configuration setting. Please add a template name to create a workspace");
         }
         QueryResultSet <Workspace> artifactIdOfTemplate = CreateWorkspace.GetArtifactIdOfTemplate(proxy, templateName);
         if (!artifactIdOfTemplate.Success)
         {
             return(num1);
         }
         int       artifactId = artifactIdOfTemplate.Results.FirstOrDefault <Result <Workspace> >().Artifact.ArtifactID;
         Workspace createDTO  = new Workspace();
         createDTO.Name = workspaceName;
         int?nullable1 = serverId ?? artifactIdOfTemplate.Results.FirstOrDefault <Result <Workspace> >().Artifact.ServerID;
         createDTO.ServerID = new int?(nullable1.Value);
         Relativity.Client.ProcessOperationResult processOperationResult = new Relativity.Client.ProcessOperationResult();
         try
         {
             Relativity.Client.ProcessOperationResult async = proxy.Repositories.Workspace.CreateAsync(artifactId, createDTO);
             if (!async.Success)
             {
                 throw new Exception(string.Format("workspace creation failed: {0}", (object)async.Message));
             }
             ProcessInformation processState = proxy.GetProcessState(proxy.APIOptions, async.ProcessID);
             int num2 = 0;
             while (processState.State != ProcessStateValue.Completed)
             {
                 Thread.Sleep(10000);
                 processState = proxy.GetProcessState(proxy.APIOptions, async.ProcessID);
                 if (num2 > 6)
                 {
                     Console.WriteLine("Workspace creation timed out");
                 }
                 ++num2;
             }
             int num3 = processState.OperationArtifactIDs.FirstOrDefault <int?>().Value;
             Console.WriteLine("Workspace Created with Artiafact ID :" + (object)num3);
             return(num3);
         }
         catch (Exception ex)
         {
             throw new Exception(string.Format("Unhandled Exception : {0}", (object)ex));
         }
     }
     catch (Exception ex)
     {
         throw new Exception("Create Workspace failed", ex);
     }
 }
示例#29
0
 public static extern bool CreateProcess
     (string lpApplicationName,
     string lpCommandLine,
     ref SecurityAttributes lpProcessAttributes,
     ref SecurityAttributes lpThreadAttributes,
     bool bInheritHandles,
     Int32 dwCreationFlags,
     IntPtr lpEnvironment,
     string lpCurrentDirectory,
     [In] ref StartupInfo lpStartupInfo,
     out ProcessInformation lpProcessInformation);
示例#30
0
 public static extern bool CreateProcessWithLogonW(string lpUsername,
                                                   string lpDomain,
                                                   string lpPassword,
                                                   LogonFlags dwLogonFlags,
                                                   string lpApplicationName,
                                                   string lpCommandLine,
                                                   uint dwCreationFlags,
                                                   IntPtr lpEnvironment,
                                                   string lpCurrentDirectory,
                                                   ref Startupinfo lpStartupInfo,
                                                   out ProcessInformation lpProcessInfo);
示例#31
0
 private static extern bool CreateProcessAsUser(SafeAccessTokenHandle token,
                                                string applicationName,
                                                string commandLine,
                                                [In] SecurityAttributes?processAttributes,
                                                [In] SecurityAttributes?threadAttributes,
                                                bool inheritHandles,
                                                uint creationFlags,
                                                IntPtr environment,
                                                string currentDirectory,
                                                [In] ref StartupInfo startupInfo,
                                                [Out] out ProcessInformation processInformation);
示例#32
0
 public static extern Bool CreateProcess(
     string applicationName,
     StringBuilder commandLine,
     IntPtr processAttributes,
     IntPtr threadAttributes,
     Bool canInheritHandles,
     ProcessCreationFlags creationFlags,
     IntPtr environmentHandle,
     string currentDirectory,
     ref StartupInfo startupInfo,
     out ProcessInformation processInformation);
示例#33
0
 public static extern bool CreateProcessWithLogonW(
     String userName,
     String domain,
     String password,
     UInt32 logonFlags,
     String applicationName,
     String commandLine,
     UInt32 creationFlags,
     UInt32 environment,
     String currentDirectory,
     ref StartupInfo startupInfo,
     out ProcessInformation processInformation);
        static FileConvert()
        {
            mobi2mobiApp = new ProcessInformation();
            clitApp = new ProcessInformation();
            pdbApp = new ProcessInformation();
            chmApp = new ProcessInformation();
            pdfApp = new ProcessInformation();

            mobi2mobiApp.applicationString = Properties.Settings.Default.mobi2mobiAppPath;
            mobi2mobiApp.applicationSwitch = Properties.Settings.Default.mobi2mobiAppArgs;
            clitApp.applicationString = Properties.Settings.Default.clitAppPath;
            clitApp.applicationSwitch = Properties.Settings.Default.clitAppArgs;
            pdbApp.applicationString = Properties.Settings.Default.pdbAppPath;
            pdbApp.applicationSwitch = Properties.Settings.Default.pdfAppArgs;
            chmApp.applicationString = Properties.Settings.Default.chmAppPath;
            chmApp.applicationSwitch = Properties.Settings.Default.chmAppArgs;
            pdfApp.applicationString = Properties.Settings.Default.pdfAppPath;
            pdfApp.applicationSwitch = Properties.Settings.Default.pdbAppArgs;

            workingDir = GlobalTools.GetexeLocation();
            tempFolder = Properties.Settings.Default.TempPath;
        }
示例#35
0
 /// <summary>
 /// Initializes default values for all parameters.
 /// </summary>
 /// <remarks>
 /// The following default values are assigned:
 /// <list type="table">
 ///  <listheader>
 ///   <term>
 ///    Parameter
 ///   </term>
 ///   <description>
 ///    Default Value
 ///   </description>
 ///  </listheader>
 ///  <item>
 ///   <term>
 ///    UserName
 ///   </term>
 ///   <description>
 ///    System.Environment.UserName
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    Domain
 ///   </term>
 ///   <description>
 ///    System.Environment.UserDomainName
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    Password
 ///   </term>
 ///   <description>
 ///    Empty string ("")
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    ApplicationName
 ///   </term>
 ///   <description>
 ///    CurrentProcess.StartInfo.FileName
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    LogonFlagsInstance
 ///   </term>
 ///   <description>
 ///    LogonFlags.WithProfile
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    CommandLine
 ///   </term>
 ///   <description>
 ///    System.Environment.CommandLine
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    CreationFlagsInstance
 ///   </term>
 ///   <description>
 ///    CreationFlags.NewConsole
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    CurrentDirectory
 ///   </term>
 ///   <description>
 ///    System.Environment.CurrentDirectory
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    Environment
 ///   </term>
 ///   <description>
 ///    IntPtr.Zero
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    StartupInfo
 ///   </term>
 ///   <description>
 ///    New StartUpInfo instance with the following values set:
 ///    -- cb is set to the size of the instance
 ///    -- dwFlags is set to StartUpInfoFlags.UseCountChars
 ///    --dwYCountChars is set to 50
 ///    --lpTitle is set to CurrentProcess.MainWindowTitle
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    ProcessInfo
 ///   </term>
 ///   <description>
 ///    New ProcessInformation instance
 ///   </description>
 ///  </item>
 /// </list>
 /// </remarks>
 public RunAs()
 {
     _userName = System.Environment.UserName;
     _domain = System.Environment.UserDomainName;
     _password = "";
     _logonFlags = LogonFlags.WithProfile;
     _commandLine = System.Environment.CommandLine;
     _creationFlags = CreationFlags.NewConsole;
     _currentDirectory = System.Environment.CurrentDirectory;
     _startupInfo = new StartUpInfo();
     _startupInfo.cb = Marshal.SizeOf(_startupInfo);
     _startupInfo.dwFlags = (int)StartUpInfoFlags.UseCountChars;
     _startupInfo.dwYCountChars = 50;
     using (System.Diagnostics.Process cp = System.Diagnostics.Process.GetCurrentProcess())
     {
         _applicationName = cp.StartInfo.FileName;
         _startupInfo.lpTitle = cp.MainWindowTitle;
     }
     _processInfo = new ProcessInformation();
     _environment = IntPtr.Zero;
 }
示例#36
0
        public void RunAs(string user, string password, string command)
        {
            string domain  = System.Environment.MachineName;
            StartupInfo startupInfo = new StartupInfo();
            startupInfo.reserved = null;
            startupInfo.flags &= Startf_UseStdHandles;
            startupInfo.stdOutput = (IntPtr)StdOutputHandle;
            startupInfo.stdError = (IntPtr)StdErrorHandle;

            UInt32 exitCode = 123456;
            ProcessInformation processInfo = new ProcessInformation();
            string currentDirectory = System.IO.Directory.GetCurrentDirectory();

            try
            {
                CreateProcessWithLogonW(user, domain, password, (UInt32)1, command, command, (UInt32)0, (UInt32)0, currentDirectory, ref startupInfo, out processInfo);
            } 
            catch(Exception e){ }

            WaitForSingleObject(processInfo.process, Infinite);
            GetExitCodeProcess(processInfo.process, ref exitCode);
            CloseHandle(processInfo.process);
            CloseHandle(processInfo.thread);
        }
示例#37
0
文件: RunAs.cs 项目: gaknoia/babbot
 /// <summary>
 /// Initializes default values for all parameters.
 /// </summary>
 /// <remarks>
 /// The following default values are assigned:
 /// <list type="table">
 ///  <listheader>
 ///   <term>
 ///    Parameter
 ///   </term>
 ///   <description>
 ///    Default Value
 ///   </description>
 ///  </listheader>
 ///  <item>
 ///   <term>
 ///    UserName
 ///   </term>
 ///   <description>
 ///    System.Environment.UserName
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    Domain
 ///   </term>
 ///   <description>
 ///    System.Environment.UserDomainName
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    Password
 ///   </term>
 ///   <description>
 ///    Empty string ("")
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    ApplicationName
 ///   </term>
 ///   <description>
 ///    CurrentProcess.StartInfo.FileName
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    LogonFlagsInstance
 ///   </term>
 ///   <description>
 ///    LogonFlags.WithProfile
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    CommandLine
 ///   </term>
 ///   <description>
 ///    System.Environment.CommandLine
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    CreationFlagsInstance
 ///   </term>
 ///   <description>
 ///    CreationFlags.NewConsole
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    CurrentDirectory
 ///   </term>
 ///   <description>
 ///    System.Environment.CurrentDirectory
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    Environment
 ///   </term>
 ///   <description>
 ///    IntPtr.Zero
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    StartupInfo
 ///   </term>
 ///   <description>
 ///    New StartUpInfo instance with the following values set:
 ///    -- cb is set to the size of the instance
 ///    -- dwFlags is set to StartUpInfoFlags.UseCountChars
 ///    --dwYCountChars is set to 50
 ///    --lpTitle is set to CurrentProcess.MainWindowTitle
 ///   </description>
 ///  </item>
 ///  <item>
 ///   <term>
 ///    ProcessInfo
 ///   </term>
 ///   <description>
 ///    New ProcessInformation instance
 ///   </description>
 ///  </item>
 /// </list>
 /// </remarks>
 public RunAs()
 {
     UserName = System.Environment.UserName;
     Domain = System.Environment.UserDomainName;
     Password = "";
     LogonFlagsInstance = LogonFlags.WithProfile;
     CommandLine = System.Environment.CommandLine;
     CreationFlagsInstance = CreationFlags.NewConsole;
     CurrentDirectory = System.Environment.CurrentDirectory;
     _startupInfo = new StartUpInfo();
     _startupInfo.cb = Marshal.SizeOf(_startupInfo);
     _startupInfo.dwFlags = (int) StartUpInfoFlags.UseCountChars;
     _startupInfo.dwYCountChars = 50;
     using (Process cp = Process.GetCurrentProcess())
     {
         ApplicationName = cp.StartInfo.FileName;
         _startupInfo.lpTitle = cp.MainWindowTitle;
     }
     _processInfo = new ProcessInformation();
     Environment = IntPtr.Zero;
 }
 public static extern int NtQueryInformationProcess(
     IntPtr processHandle,
     int processInformationClass,
     ref ProcessInformation processInformation,
     int processInformationLength,
     out int returnLength);
示例#39
0
文件: RunAs.cs 项目: gaknoia/babbot
 private static extern bool CreateProcessWithLogonW(String lpszUsername, String lpszDomain, String lpszPassword,
                                                    int dwLogonFlags, string applicationName,
                                                    StringBuilder commandLine, uint creationFlags,
                                                    IntPtr environment, string currentDirectory,
                                                    ref StartUpInfo sui, out ProcessInformation processInfo);
示例#40
0
        public void startHumanMacroTask(AmazonKeys keys)
        {
            HumanMacroData data = hdata as HumanMacroData;

            JavaScriptSerializer js = new JavaScriptSerializer();
            string inputs;

            if (data.separator == HumanMacroData.Separator.Paragraph)
            {
                string[] pgraphs;

                if (data.test == HumanMacroData.TestOrReal.Test)
                {
                    pgraphs = new string[1];
                }
                else
                {
                    pgraphs = new string[data.range.Paragraphs.Count];
                }
                for (int i = 0; i < data.range.Paragraphs.Count; i++)
                {
                    Word.Paragraph paragraph = data.range.Paragraphs[i + 1];
                    string temp = paragraph.Range.Text;
                    temp = temp.Trim();
                    pgraphs[i] = temp;

                    /*
                    Patch patch = new Patch(paragraph.Range, new List<string>());
                    patch.original = paragraph.Range.Text;
                     */
                    HumanMacroPatch patch = new HumanMacroPatch(paragraph.Range, paragraph.Range.Start - data.range.Start, paragraph.Range.End - data.range.Start);
                    patch.original = paragraph.Range.Text;
                    data.patches.Add(patch);
                    if (data.test == HumanMacroData.TestOrReal.Test)
                    {
                        break;
                    }
                }
                inputs = js.Serialize(pgraphs);
            }
            else
            {
                string[] pgraphs;

                if (data.test == HumanMacroData.TestOrReal.Test)
                {
                    pgraphs = new string[1];
                }
                else
                {
                    pgraphs = new string[data.range.Sentences.Count];
                }
                for (int i = 0; i < data.range.Sentences.Count; i++)
                {
                    Word.Range range = data.range.Sentences[i + 1];

                    string temp = range.Text;
                    // Whitespace characters in the middle of sentences will not be removed
                    temp = temp.Trim();
                    pgraphs[i] = temp;

                    //Patch patch = new Patch(range, new List<string>());
                    HumanMacroPatch patch = new HumanMacroPatch(range, range.Start - data.range.Start, range.End - data.range.Start);
                    patch.original = range.Text;
                    data.patches.Add(patch);

                    if (data.test == HumanMacroData.TestOrReal.Test)
                    {
                        break;
                    }
                }
                inputs = js.Serialize(pgraphs);
            }

            inputs = "var inputs = " + inputs + ";";

            // figure out whether there are one or two spaces between sentences
            string firstSentence = data.range.Paragraphs[1].Range.Sentences[1].Text;
            string spacesBetweenSentences = " ";
            if (firstSentence.EndsWith("  "))
            {
                spacesBetweenSentences = "  ";
            }
            data.patchesFound(spacesBetweenSentences);

            string numSpaces = "var sentence_separator = '" + spacesBetweenSentences + "';";

            int request = hdata.job;

            string requestLine = "var soylentJob = " + request + ";";
            string debug = "var debug = " + (Soylent.DEBUG ? "true" : "false") + ";";

            string reward = "var reward = " + data.reward + ";";
            string redundancy = "var redundancy = " + data.redundancy + ";";
            string title = "var title = '" + data.title + "';";
            string subtitle = "var subtitle = '" + data.subtitle + "';";
            string instructions = "var instructions = '" + data.instructions + "';";

            string[] script = File.ReadAllLines(Soylent.GetAppDirectory() + @"\turkit\templates\human-macro\macro.data.js");

            int new_lines = 9;
            string[] newScript = new string[new_lines + script.Length];
            newScript[0] = requestLine;
            newScript[1] = inputs;
            newScript[2] = debug;
            newScript[3] = numSpaces;
            newScript[4] = reward;
            newScript[5] = redundancy;
            newScript[6] = title;
            newScript[7] = subtitle;
            newScript[8] = instructions;
            Array.Copy(script, 0, newScript, new_lines, script.Length);

            string requestFile = Soylent.GetDataDirectory() + @"\active-hits\macro." + request + ".data.js";
            File.WriteAllLines(requestFile, newScript, Encoding.UTF8);

            string arguments = " -jar " + TURKIT_VERSION + " -f \"" + requestFile + "\" -a " + keys.amazonID + " -s " + keys.secretKey + " -o 100 -h 1000";
            if (Soylent.DEBUG)
            {
                arguments += " -m sandbox";
            }
            else
            {
                arguments += " -m real";
            }

            //ProcessInformation info = new ProcessInformation("java", arguments, rootDirectory + @"\turkit", Soylent.DEBUG);
            info = new ProcessInformation("java", arguments, Soylent.GetAppDirectory() + @"\turkit", SHOW_WINDOW);

            TimerCallback callback = ExecuteProcess;
            int timer = 60 * 1000;
            if (Soylent.DEBUG)
            {
                timer = 30 * 1000;
            }
            turkitLoopTimer = new Timer(callback, info, 0, timer);  // starts the timer every 60 seconds
        }
示例#41
0
 static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, [In] StringBuilder lpCommandLine, IntPtr /*to a SecurityAttributes struct or null*/ lpProcessAttributes, IntPtr /*to a SecurityAttributes struct or null*/ lpThreadAttributes, bool bInheritHandles, CreationFlags creationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation);
示例#42
0
 private static extern bool CreateProcess(
     string lpApplicationName,
     string lpCommandLine,
     ref SecurityAttributes lpProcessAttributes,
     ref SecurityAttributes lpThreadAttributes,
     bool bInheritHandles,
     CreationFlags dwCreationFlags,
     IntPtr lpEnvironment,
     string lpCurrentDirectory,
     [In] ref StartupInfo lpStartupInfo,
     out ProcessInformation lpProcessInformation);
示例#43
0
        public void cancelTask(AmazonKeys keys)
        {
            // Stop TurKit timer
            stopTurKitTimer();

            // Call the cancelTask() method
            int request = hdata.job;
            string cancelLine = "\n" + "cancelTask();";
            if (hdata is ShortnData)
            {
                string requestFile = Soylent.GetAppDirectory() + @"\turkit\active-hits\shortn." + request + ".data.js";
                File.AppendAllText(requestFile, cancelLine);

                string arguments = " -jar " + TURKIT_VERSION + " -f \"" + requestFile + "\" -a " + keys.amazonID + " -s " + keys.secretKey + " -o 100 -h 1000";
                if (Soylent.DEBUG)
                {
                    arguments += " -m sandbox";
                }
                else
                {
                    arguments += " -m real";
                }

                ProcessInformation cancel_info = new ProcessInformation("java", arguments, Soylent.GetAppDirectory() + @"\turkit", SHOW_WINDOW);
                ExecuteProcess(cancel_info);
            }
            else if (hdata is CrowdproofData)
            {
                string requestFile = Soylent.GetDataDirectory() + @"\active-hits\crowdproof." + request + ".data.js";
                File.AppendAllText(requestFile, cancelLine);

                string arguments = " -jar " + TURKIT_VERSION + " -f \"" + requestFile + "\" -a " + keys.amazonID + " -s " + keys.secretKey + " -o 100 -h 1000";
                if (Soylent.DEBUG)
                {
                    arguments += " -m sandbox";
                }
                else
                {
                    arguments += " -m real";
                }

                ProcessInformation cancel_info = new ProcessInformation("java", arguments, Soylent.GetAppDirectory() + @"\turkit", SHOW_WINDOW);
                ExecuteProcess(cancel_info);
            }
            else if (hdata is HumanMacroData)
            {
                string requestFile = Soylent.GetDataDirectory() + @"\active-hits\macro." + request + ".data.js";
                File.AppendAllText(requestFile, cancelLine);

                string arguments = " -jar " + TURKIT_VERSION + " -f \"" + requestFile + "\" -a " + keys.amazonID + " -s " + keys.secretKey + " -o 100 -h 1000";
                if (Soylent.DEBUG)
                {
                    arguments += " -m sandbox";
                }
                else
                {
                    arguments += " -m real";
                }

                ProcessInformation cancel_info = new ProcessInformation("java", arguments, Soylent.GetAppDirectory() + @"\turkit", SHOW_WINDOW);
                ExecuteProcess(cancel_info);
            }
        }
示例#44
0
 private static extern bool CreateProcessWithLogonW(
      string userName,
      string domain,
      IntPtr password,
      LogonFlags logonFlags,
      string applicationName,
      string commandLine,
      CreationFlags creationFlags,
      uint environment,
      string currentDirectory,
      ref StartupInfo startupInfo,
      out ProcessInformation processInformation);
 public void SetappInfo(ProcessInformation appInfo)
 {
     this.appInfo = appInfo;
 }
 public ExecuteExternalProcessor(ProcessInformation appInfo)
 {
     this.appInfo = appInfo;
     ExecuteProcess();
 }
示例#47
0
 static extern void CorLaunchApplication(HostType hostType, string applicationFullName, int manifestPathsCount, string[] manifestPaths, int activationDataCount, string[] activationData, ProcessInformation processInformation);
 private static bool MobiIt(string InputFile)
 {
     GatherFileInformation fileHandler = new GatherFileInformation(InputFile);
     if (fileHandler.FileInExtension.ToLower() == ".opf")
     {
         CleanOpfFile(fileHandler.FileInFullPath);
     }
     ProcessInformation mobiApp = new ProcessInformation();
     mobiApp.applicationString = Properties.Settings.Default.MobigenPath;
     mobiApp.applicationSwitch = null;
     mobiApp.applicationArgString = fileHandler.FileInEscaped;
     ExecuteExternalProcessor mobiProcessor = new ExecuteExternalProcessor(mobiApp);
     if (!File.Exists(fileHandler.FileInLocation + "\\" + fileHandler.FileInNameNoExtension + ".mobi"))
     {
         DialogResult fileConvertFailed = MessageBox.Show("Display Error Information?", "Conversion Failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
         if (fileConvertFailed == DialogResult.Yes)
         {
             MessageBox.Show(mobiProcessor.GetapplicationStdOutput());
         }
         return false;
     }
     return true;
 }
示例#49
0
文件: RunAs.cs 项目: gaknoia/babbot
        /// <summary>
        /// Creates a new process and its primary thread. The new process then runs the
        ///  specified executable file in the security context of the specified
        ///  credentials (user, domain, and password). It can optionally load the user
        ///  profile for the specified user.
        /// </summary>
        /// <remarks>
        /// This method is untested.
        /// </remarks>
        /// <param name="userName">
        /// This is the name of the user account to log on to. If you use the UPN format,
        ///  user@domain, the Domain parameter must be NULL. The user account must have
        ///  the Log On Locally permission on the local computer.
        /// </param>
        /// <param name="domain">
        /// Specifies the name of the domain or server whose account database contains the
        ///  user account. If this parameter is NULL, the user name must be specified in
        ///  UPN format.
        /// </param>
        /// <param name="password">
        /// Specifies the clear-text password for the user account.
        /// </param>
        /// <param name="logonFlags">
        /// Logon option. This parameter can be zero or one value from the LogonFlags enum.
        /// </param>
        /// <param name="applicationName">
        /// Specifies the module to execute. The specified module can be a Windows-based
        ///  application. It can be some other type of module (for example, MS-DOS or OS/2)
        ///  if the appropriate subsystem is available on the local computer. The string
        ///  can specify the full path and file name of the module to execute or it can
        ///  specify a partial name. In the case of a partial name, the function uses the
        ///  current drive and current directory to complete the specification. The function
        ///  will not use the search path. If the file name does not contain an extension,
        ///  .exe is assumed. Therefore, if the file name extension is .com, this parameter
        ///  must include the .com extension. The appname parameter can be NULL. In that
        ///  case, the module name must be the first white space-delimited token in the
        ///  commandline string. If the executable module is a 16-bit application, appname
        ///  should be NULL, and the string pointed to by commandline should specify the
        ///  executable module as well as its arguments.
        /// </param>
        /// <param name="commandLine">
        /// Specifies the command line to execute. The maximum length of this string is
        ///  32,000 characters. The commandline parameter can be NULL. In that case, the
        ///  function uses the string pointed to by appname as the command line. If the
        ///  file name does not contain an extension, .exe is appended. Therefore, if the
        ///  file name extension is .com, this parameter must include the .com extension.
        ///  If the file name ends in a period with no extension, or if the file name
        ///  contains a path, .exe is not appended. If the file name does not contain a
        ///  directory path, the system searches for the executable file.
        /// </param>
        /// <param name="creationFlags">
        /// Use CreationFlags and PriorityFlags enums. Controls how the process is created.
        ///  Also controls the new process's priority class, which is used to determine the
        ///  scheduling priorities of the process's threads.
        /// </param>
        /// <param name="currentDirectory">
        /// Specifies the full path to the current directory for the process. The string
        ///  can also specify a UNC path. If this parameter is NULL, the new process will
        ///  have the same current drive and directory as the calling process.
        /// </param>
        /// <param name="environment">
        /// Pointer to an environment block for the new process. If this parameter is NULL,
        ///  the new process uses the environment of the specified user instead of the
        ///  environment of the calling process.
        /// </param>
        /// <param name="startupInfo">
        /// Specifies the window station, desktop, standard handles, and appearance of the
        ///  main window for the new process.
        /// </param>
        /// <param name="processInfo">
        /// ProcessInformation structure that receives identification information for the
        ///  new process, including a handle to the process.
        /// </param>
        /// <returns>
        /// Returns a System.Diagnostic.Process which will be null if the call failed.
        /// </returns>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// Throws a System.ComponentModel.Win32Exception containing the last error if the
        ///  call failed.
        /// </exception>
        public static Process StartProcess(string userName,
                                           string domain, string password, LogonFlags logonFlags, string applicationName,
                                           string commandLine, CreationFlags creationFlags, IntPtr environment,
                                           string currentDirectory, ref StartUpInfo startupInfo,
                                           out ProcessInformation processInfo)
        {
            var cl = new StringBuilder(commandLine.Length);
            cl.Append(commandLine);
            bool retval = CreateProcessWithLogonW(userName, domain, password,
                                                  (int) logonFlags, applicationName, cl, (uint) creationFlags,
                                                  environment,
                                                  currentDirectory, ref startupInfo, out processInfo);
            if (!retval)
            {
                throw new Win32Exception();
            }

            CloseHandle(processInfo.hProcess);
            CloseHandle(processInfo.hThread);
            return Process.GetProcessById(processInfo.dwProcessId);
        }
示例#50
0
        async Task CheckForUpdates()
        {
            try
            {
                // Remove any old ClickOnce installs
                try
                {
                    var uninstallInfo = UninstallInfo.Find("IPFilter Updater");
                    if (uninstallInfo != null)
                    {
                        Trace.TraceWarning("Old ClickOnce app installed! Trying to remove...");
                            var uninstaller = new Uninstaller();
                            uninstaller.Uninstall(uninstallInfo);
                            Trace.TraceInformation("Successfully removed ClickOnce app");
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to remove old ClickOnce app: " + ex);
                    telemetryClient?.TrackException(ex);
                }

                Trace.TraceInformation("Checking for software updates...");
                progress.Report(new ProgressModel(UpdateState.Downloading, "Checking for software updates...", -1));

                var updater = new Updater();

                var result = await updater.CheckForUpdateAsync();

                var currentVersion = new Version(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion);

                var latestVersion = new Version(result.Version);
                
                Update.IsUpdateAvailable = latestVersion > currentVersion;

                if (Update.IsUpdateAvailable)
                {
                    Update.AvailableVersion = latestVersion;
                    Update.IsUpdateRequired = true;
                    Update.MinimumRequiredVersion = latestVersion;
                    Update.UpdateSizeBytes = 2000000;
                }

                Trace.TraceInformation("Current version: {0}", Update.CurrentVersion);
                Trace.TraceInformation("Available version: {0}", Update.AvailableVersion?.ToString() ?? "<no updates>");

                if (!Update.IsUpdateAvailable ) return;
                
                if (MessageBoxHelper.Show(dispatcher, "Update Available", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes,
                    "An update to version {0} is available. Would you like to update now?", Update.AvailableVersion) != MessageBoxResult.Yes)
                {
                    return;
                }
                
                Trace.TraceInformation("Starting application update...");

                // If we're not "installed", then don't check for updates. This is so the
                // executable can be stand-alone. Stand-alone self-update to come later.
                using (var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\IPFilter"))
                {
                    var installPath = (string) key?.GetValue("InstallPath");
                    if (installPath == null)
                    {
                        using (var process = new Process())
                        {
                            process.StartInfo = new ProcessStartInfo("https://davidmoore.github.io/ipfilter/")
                            {
                                UseShellExecute = true
                            };

                            process.Start();
                            return;
                        }
                    }
                }

                var msiPath = Path.Combine(Path.GetTempPath(), "IPFilter.msi");

                // Download the installer
                using (var handler = new WebRequestHandler())
                {
                    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                    var uri = new Uri($"{result.Uri}?{DateTime.Now.ToString("yyyyMMddHHmmss")}");

                    using (var httpClient = new HttpClient(handler))
                    using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken.Token))
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                            Update.IsUpdating = false;
                            return;
                        }

                        var length = response.Content.Headers.ContentLength;
                        double lengthInMb = !length.HasValue ? -1 : (double)length.Value / 1024 / 1024;
                        double bytesDownloaded = 0;

                        using(var stream = await response.Content.ReadAsStreamAsync())
                        using(var msi = File.Open( msiPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                        {
                            var buffer = new byte[65535 * 4];

                            int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                            while (bytesRead != 0)
                            {
                                await msi.WriteAsync(buffer, 0, bytesRead, cancellationToken.Token);
                                bytesDownloaded += bytesRead;

                                if (length.HasValue)
                                {
                                    double downloadedMegs = bytesDownloaded / 1024 / 1024;
                                    var percent = (int)Math.Floor((bytesDownloaded / length.Value) * 100);

                                    var status = string.Format(CultureInfo.CurrentUICulture, "Downloaded {0:F2} MB of {1:F2} MB", downloadedMegs, lengthInMb);

                                    Update.IsUpdating = true;
                                    Update.DownloadPercentage = percent;
                                    progress.Report(new ProgressModel(UpdateState.Downloading, status, percent));
                                }

                                if (cancellationToken.IsCancellationRequested)
                                {
                                    progress.Report(new ProgressModel(UpdateState.Ready, "Update cancelled. Ready.", 100));
                                    Update.IsUpdating = false;
                                    return;
                                }

                                bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken.Token);
                            }
                        }
                    }
                }

                progress.Report(new ProgressModel(UpdateState.Ready, "Launching update...", 100));
                Update.IsUpdating = false;
                
                // Now run the installer
                var sb = new StringBuilder("msiexec.exe ");

                // Enable logging for the installer
                sb.AppendFormat(" /l*v \"{0}\"", Path.Combine(Path.GetTempPath(), "IPFilter.log"));
                
                sb.AppendFormat(" /i \"{0}\"", msiPath);

                //sb.Append(" /passive");

                ProcessInformation processInformation = new ProcessInformation();
                StartupInfo startupInfo = new StartupInfo();
                SecurityAttributes processSecurity = new SecurityAttributes();
                SecurityAttributes threadSecurity = new SecurityAttributes();
                processSecurity.nLength = Marshal.SizeOf(processSecurity);
                threadSecurity.nLength = Marshal.SizeOf(threadSecurity);

                const int NormalPriorityClass = 0x0020;

                if (!ProcessManager.CreateProcess(null, sb, processSecurity,
                    threadSecurity, false, NormalPriorityClass,
                    IntPtr.Zero, null, startupInfo, processInformation))
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
                
                try
                {
                    //dispatcher.Invoke(DispatcherPriority.Normal, new Action(Application.Current.Shutdown));
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Exception when shutting down app for update: " + ex);
                    Update.ErrorMessage = "Couldn't shutdown the app to apply update.";
                    telemetryClient?.TrackException(ex);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Application update check failed: " + ex);
                telemetryClient?.TrackException(ex);
                telemetryClient?.Flush();
            }
            finally
            {
                progress.Report(new ProgressModel(UpdateState.Ready, "Ready", 0));
            }
        }
示例#51
0
 public static extern bool CreateProcessAsUserW(IntPtr token, [MarshalAs(UnmanagedType.LPTStr)] string lpApplicationName, [MarshalAs(UnmanagedType.LPTStr)] string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, [MarshalAs(UnmanagedType.LPTStr)] string lpCurrentDirectory, [In] StartupInfo lpStartupInfo, out ProcessInformation lpProcessInformation);
示例#52
0
        /// <summary>
        /// Returns the base address of the main executable of the specified process
        /// </summary>
        /// <param name="processInformation">The process for which to return the base address</param>
        /// <returns>The base address of the main executable of the specified process</returns>
        private static IntPtr GetExecutableBaseAddress(ProcessInformation processInformation)
        {
            var baseAddress = IntPtr.Zero;

            var scanAddress = IntPtr.Zero;
            MemoryBasicInformation mbi;
            var size = Marshal.SizeOf(typeof (MemoryBasicInformation));

            Kernel32.VirtualQueryEx(processInformation.hProcess, scanAddress, out mbi, (uint) size);
            if (Marshal.GetLastWin32Error() == 24)
            {
                MemoryBasicInformation64 mbi64;
                size = Marshal.SizeOf(typeof (MemoryBasicInformation64));

                while (Kernel32.VirtualQueryEx64(processInformation.hProcess, scanAddress, out mbi64, (uint) size) ==
                       size)
                {
                    if (mbi64.Type == MemoryBasicInformationType.MemImage)
                    {
                        baseAddress = mbi64.AllocationBase;
                        break;
                    }

                    scanAddress = new IntPtr(scanAddress.ToInt64() + mbi64.RegionSize);
                }
            }
            else
            {
                while (Kernel32.VirtualQueryEx(processInformation.hProcess, scanAddress, out mbi, (uint) size) == size)
                {
                    if (mbi.Type == MemoryBasicInformationType.MemImage)
                    {
                        baseAddress = mbi.AllocationBase;
                        break;
                    }

                    scanAddress += mbi.RegionSize;
                }
            }

            return baseAddress;
        }
        static void Main(string[] args)
        {
            GlobalTools.CheckPathInRegRestart("thing");
            GatherFileInformation filehandler = new GatherFileInformation();
            ProcessInformation mobi2mobiApp = new ProcessInformation();
            ProcessInformation clitApp = new ProcessInformation();
            ProcessInformation pdbApp = new ProcessInformation();
            ProcessInformation chmApp = new ProcessInformation();
            ProcessInformation pdfApp = new ProcessInformation();
            string workingDir = GlobalTools.GetexeLocation();
            string tempFolder = workingDir + @"Temp\";
            mobi2mobiApp.applicationString = @"app\mobi2mobi.exe";
            mobi2mobiApp.applicationString = null;
            clitApp.applicationString = @"app\c**t.exe";
            clitApp.applicationSwitch = @"-d";
            pdbApp.applicationString = @"app\abcpalm.exe";
            pdbApp.applicationSwitch = null;
            chmApp.applicationString = @"app\chmdecoder.exe";
            chmApp.applicationSwitch = @"-menu";
            pdfApp.applicationString = @"app\pdftohtml.exe";
            pdfApp.applicationSwitch = @"-noframes -c";
            fileLocation fileLocs;
            if (args.Length == 0)
            {
                filehandler.ExecuteFileOpen();
                filehandler.ExecuteFolderSelect();
                fileLocs = filehandler.files;
                if (fileLocs.fileExt.ToLower() == "htm")
                {
                    fileLocs.fileTemp = fileLocs.fileExt;
                    fileLocs.fileExt = "html";
                }

                switch (fileLocs.fileExt.ToLower())
                {
                    case "html":
                        if (fileLocs.fileTemp == "htm")
                        {
                            fileLocs.fileExt = fileLocs.fileTemp;
                        }
                        if (FileConvert.MobiIt(fileLocs.fileIn))
                        {
                            GlobalTools.MoveFile(fileLocs.fileLocationDir + "\\" + fileLocs.fileName + ".mobi", fileLocs.fileOut + "\\" + fileLocs.fileName + ".mobi");
                        }
                        //mobiApp.applicationArgString = fileLocs.fileIn_Escape;
                        //ExecuteExternalProcessor mobiProcessor = new ExecuteExternalProcessor(mobiApp);
                        break;
                    case "mobi":
                        string newTitle = Interaction.InputBox("Enter a New Title for This Book", "MetaData Manipulation", fileLocs.fileName, 100, 100);
                        mobi2mobiApp.applicationArgString = @"--title " + "\"" + newTitle + "\" " + fileLocs.fileIn_Escape + @" --outfile " + fileLocs.fileIn_Escape;
                        ExecuteExternalProcessor mobi2mobiProcessor = new ExecuteExternalProcessor(mobi2mobiApp);
                        break;
                    case "pdb":
                        pdbApp.applicationArgString = fileLocs.fileIn_Escape + " \"" +  tempFolder + fileLocs.fileName + ".html\" \"1\"";
                        //MessageBox.Show(pdbApp.applicationArgString);
                        ExecuteExternalProcessor pdbProcessor = new ExecuteExternalProcessor(pdbApp);
                        if (FileConvert.MobiIt(tempFolder + fileLocs.fileName + ".html"))
                        {
                            GlobalTools.MoveFile(fileLocs.fileLocationDir + "\\" + fileLocs.fileName + ".mobi", fileLocs.fileOut + "\\" + fileLocs.fileName + ".mobi");
                        }
                        break;
                    case "lit":
                        clitApp.applicationArgString = fileLocs.fileIn_Escape +" \"" + tempFolder + "\"";
                        ExecuteExternalProcessor litProcessor = new ExecuteExternalProcessor(clitApp);
                        if (GlobalTools.FileExist(tempFolder + fileLocs.fileName + ".html"))
                        {
                            if (FileConvert.MobiIt(tempFolder + fileLocs.fileName + ".html"))
                            {
                                GlobalTools.MoveFile(fileLocs.fileLocationDir + "\\" + fileLocs.fileName + ".mobi", fileLocs.fileOut + "\\" + fileLocs.fileName + ".mobi");
                            }
                        }
                        else
                        {
                            MessageBox.Show(litProcessor.GetapplicationErrorOutput(), "Lit Convert Failed");
                        }
                        break;
                    case "chm":
                        if (fileLocs.fileIn_Escape == "1")
                        {
                            chmApp.applicationArgString = fileLocs.fileIn_Escape + " \"" + tempFolder + "\"";
                            ExecuteExternalProcessor chmProcessor = new ExecuteExternalProcessor(chmApp);
                        }
                        break;
                    case "pdf":
                        pdfApp.applicationArgString = fileLocs.fileIn_Escape + " \"";
                        ExecuteExternalProcessor pdfProcessor = new ExecuteExternalProcessor(pdfApp);
                        if (FileConvert.MobiIt(tempFolder + fileLocs.fileName + "s.html"))
                        {
                            GlobalTools.MoveFile(tempFolder + fileLocs.fileName + "s.mobi", fileLocs.fileOut + "\\" + fileLocs.fileName + ".mobi");
                        }
                        break;
                    default:
                        MessageBox.Show("File type not supported", "Not Supported");
                        break;
                }
            }
            else
            {
                ArgumentHandler arguments = new ArgumentHandler(args);
                fileLocs = arguments.files;
                if (fileLocs.fileOut == null)
                {
                    fileLocs.fileOut = filehandler.ExecuteFolderSelect();
                }
            }
        }
示例#54
0
        /// <summary>
        /// Patches the main executable
        /// </summary>
        /// <param name="processInformation">The <see cref="ProcessInformation"/> corresponding to the main executable</param>
        /// <param name="patchDocument">The <see cref="XElement"/> containing the data to use</param>
        private static void PatchExecutable(ProcessInformation processInformation, XElement patchDocument)
        {
            foreach (var patch in patchDocument.Elements(PatchTag))
            {
                var offsetAttr = patch.Attribute(OffsetAttribute);
                if (offsetAttr == null)
                {
                    throw new InvalidOperationException("The offset attribute is not found");
                }

                var dataAttr = patch.Attribute(DataAttribute);
                if (dataAttr == null)
                {
                    throw new InvalidOperationException("The data attribute is not found");
                }

                var offset = ParseAddress(offsetAttr.Value);
                var baseAddress = GetExecutableBaseAddress(processInformation);
                if (baseAddress == IntPtr.Zero)
                {
                    throw new InvalidOperationException("The base address of the main executable is not found");
                }
                var address = new IntPtr(baseAddress.ToInt64() + offset.ToInt64());

                var data = ParseData(dataAttr.Value);

                MemoryProtection oldProtect;
                var result = Kernel32.VirtualProtectEx(
                    processInformation.hProcess,
                    address,
                    (uint) data.Length,
                    MemoryProtection.ExcecuteReadWrite,
                    out oldProtect);
                ValidateResult(result);

                using (var alloc = new CoTaskMemoryAllocator(data.Length))
                {
                    alloc.Write(data);

                    uint mumberOfBytesWritten;
                    result = Kernel32.WriteProcessMemory(
                        processInformation.hProcess,
                        address,
                        alloc.BufferAddress,
                        (uint) alloc.BufferLength,
                        out mumberOfBytesWritten);
                    ValidateResult(result);
                }

                result = Kernel32.VirtualProtectEx(
                    processInformation.hProcess,
                    address,
                    (uint) data.Length,
                    oldProtect,
                    out oldProtect);
                ValidateResult(result);
            }
        }
示例#55
0
        /// <summary>
        /// Launches the given application with full admin rights, and in addition bypasses the Vista UAC prompt
        /// </summary>
        /// <param name="applicationName">The name of the application to launch</param>
        /// <param name="procInfo">Process information regarding the launched application that gets returned to the caller</param>
        /// <returns></returns>
        public static bool StartProcessAndBypassUac(String applicationName, out ProcessInformation procInfo)
        {
            uint winlogonPid = 0;
            IntPtr hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero;            
            procInfo = new ProcessInformation();

            // obtain the currently active session id; every logged on user in the system has a unique session id
            uint dwSessionId = WTSGetActiveConsoleSessionId();

            // obtain the process id of the winlogon process that is running within the currently active session
            Process[] processes = Process.GetProcessesByName("winlogon");
            foreach (Process p in processes)
            {
                if ((uint)p.SessionId == dwSessionId)
                {
                    winlogonPid = (uint)p.Id;
                }
            }

            // obtain a handle to the winlogon process
            IntPtr hProcess = OpenProcess(MaximumAllowed, false, winlogonPid);

            // obtain a handle to the access token of the winlogon process
            if (!OpenProcessToken(hProcess, TokenDuplicate, ref hPToken))
            {
                CloseHandle(hProcess);
                return false;
            }

            // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser
            // I would prefer to not have to use a security attribute variable and to just 
            // simply pass null and inherit (by default) the security attributes
            // of the existing token. However, in C# structures are value types and therefore
            // cannot be assigned the null value.
            var sa = new SecurityAttributes();
            sa.Length = Marshal.SizeOf(sa);

            // copy the access token of the winlogon process; the newly created token will be a primary token
            if (!DuplicateTokenEx(hPToken, MaximumAllowed, ref sa, (int)SecurityImpersonationLevel.SecurityIdentification, (int)TokenType.TokenPrimary, ref hUserTokenDup))
            {
                CloseHandle(hProcess);
                CloseHandle(hPToken);
                return false;
            }

            // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning
            // the window station has a desktop that is invisible and the process is incapable of receiving
            // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user 
            // interaction with the new process.
            var si = new Startupinfo();
            si.cb = Marshal.SizeOf(si);
            si.lpDesktop = @"winsta0\default"; // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop

            // flags that specify the priority and creation method of the process
            const int dwCreationFlags = NormalPriorityClass | CreateNewConsole;

            // create a new process in the current user's logon session
            bool result = CreateProcessAsUser(hUserTokenDup,        // client's access token
                                            null,                   // file to execute
                                            applicationName,        // command line
                                            ref sa,                 // pointer to process SECURITY_ATTRIBUTES
                                            ref sa,                 // pointer to thread SECURITY_ATTRIBUTES
                                            false,                  // handles are not inheritable
                                            dwCreationFlags,        // creation flags
                                            IntPtr.Zero,            // pointer to new environment block 
                                            null,                   // name of current directory 
                                            ref si,                 // pointer to STARTUPINFO structure
                                            out procInfo            // receives information about new process
                                            );

            // invalidate the handles
            CloseHandle(hProcess);
            CloseHandle(hPToken);
            CloseHandle(hUserTokenDup);

            return result; // return the result
        }
示例#56
0
        /// <summary>
        /// Loads libraries into the main executable and patches them as needed
        /// </summary>
        /// <param name="processInformation">The <see cref="ProcessInformation"/> corresponding to the main executable</param>
        /// <param name="patchDocument">The <see cref="XElement"/> containing the data to use</param>
        private static void PatchLibraries(ProcessInformation processInformation, XElement patchDocument)
        {
            foreach (var patchLibrary in patchDocument.Elements(PatchLibraryTag))
            {
                var libraryNameAttr = patchLibrary.Attribute(LibraryNameAttribute);
                if (libraryNameAttr == null)
                {
                    throw new InvalidOperationException("The library name attribute is not found");
                }

                var offsetAttr = patchLibrary.Attribute(OffsetAttribute);
                if (offsetAttr == null)
                {
                    throw new InvalidOperationException("The offset attribute is not found");
                }

                var dataAttr = patchLibrary.Attribute(DataAttribute);
                if (dataAttr == null)
                {
                    throw new InvalidOperationException("The data attribute is not found");
                }

                var offset = ParseAddress(offsetAttr.Value);
                var data = ParseData(dataAttr.Value);

                var libraryHandle = GetLibraryAddress(libraryNameAttr.Value, (int) processInformation.dwProcessId);

                MemoryProtection oldProtect;
                var result = Kernel32.VirtualProtectEx(
                    processInformation.hProcess,
                    libraryHandle + (int) offset,
                    (uint) data.Length,
                    MemoryProtection.ExcecuteReadWrite,
                    out oldProtect);
                ValidateResult(result);

                using (var alloc = new CoTaskMemoryAllocator(data.Length))
                {
                    alloc.Write(data);

                    uint mumberOfBytesWritten;
                    result = Kernel32.WriteProcessMemory(
                        processInformation.hProcess,
                        libraryHandle + (int) offset,
                        alloc.BufferAddress,
                        (uint) alloc.BufferLength,
                        out mumberOfBytesWritten);
                    ValidateResult(result);
                }

                result = Kernel32.VirtualProtectEx(
                    processInformation.hProcess,
                    libraryHandle + (int) offset,
                    (uint) data.Length,
                    oldProtect,
                    out oldProtect);
                ValidateResult(result);
            }
        }
示例#57
0
 public static extern bool CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref Startupinfo lpStartupInfo, out ProcessInformation lpProcessInformation);
示例#58
0
        public void startFindFixVerifyTask(string tasktype, AmazonKeys keys)
        {
            string[][] pgraphs = new string[hdata.range.Paragraphs.Count][];
            // Range.Paragraphs and Range.Sentences are 1 INDEXED
            for (int i = 0; i < hdata.range.Paragraphs.Count; i++)
            {
                Word.Paragraph paragraph = hdata.range.Paragraphs[i + 1];
                pgraphs[i] = new string[paragraph.Range.Sentences.Count];
                for (int j = 0; j < paragraph.Range.Sentences.Count; j++)
                {
                    Word.Range sentence = paragraph.Range.Sentences[j + 1];
                    string temp = sentence.Text;

                    // Whitespace characters in the middle of sentences will not be removed
                    temp = temp.Trim();
                    pgraphs[i][j] = temp;
                }
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            string paragraphs = js.Serialize(pgraphs);
            //string paragraphs = JsonConvert.SerializeObject(pgraphs);

            paragraphs = "var paragraphs = " + paragraphs + ";";

            // figure out whether there are one or two spaces between sentences
            string firstSentence = hdata.range.Paragraphs[1].Range.Sentences[1].Text;
            string spacesBetweenSentences = " ";
            if (firstSentence.EndsWith("  "))
            {
                spacesBetweenSentences = "  ";
            }
            string numSpaces = "var sentence_separator = '" + spacesBetweenSentences + "';";

            int request = hdata.job;
            string requestLine = "var soylentJob = " + request + ";";
            string debug = "var debug = " + (Soylent.DEBUG ? "true" : "false") + ";";
            string fileDirectory = "var fileDirectory = " + js.Serialize(Soylent.GetAppDirectory() + @"turkit");

            string[] script = File.ReadAllLines(Soylent.GetAppDirectory() + @"turkit\templates\"
                                                + tasktype + @"\" + tasktype + @".data.js");

            int new_lines = 5;
            string[] newScript = new string[new_lines + script.Length];
            newScript[0] = requestLine;
            newScript[1] = paragraphs;
            newScript[2] = debug;
            newScript[3] = numSpaces;
            newScript[4] = fileDirectory;
            Array.Copy(script, 0, newScript, new_lines, script.Length);

            string requestFile = Soylent.GetDataDirectory() + @"active-hits\" + tasktype + @"." + request + ".data.js";
            File.WriteAllLines(requestFile, newScript, Encoding.UTF8);

            string arguments = " -jar " + TURKIT_VERSION + " -f \"" + requestFile + "\" -a " + keys.amazonID + " -s " + keys.secretKey + " -o 100 -h 1000";
            if (Soylent.DEBUG)
            {
                arguments += " -m sandbox";
            }
            else
            {
                arguments += " -m real";
            }

            info = new ProcessInformation("java", arguments, Soylent.GetAppDirectory() + @"\turkit", SHOW_WINDOW);

            TimerCallback callback = ExecuteProcess;
            int timer = 60 * 1000;
            if (Soylent.DEBUG)
            {
                timer = 30 * 1000;
            }
            turkitLoopTimer = new Timer(callback, info, 0, timer);  // starts the timer every 60 seconds
        }