Beispiel #1
0
 public override void Install(IApplicationLicense license, Client.IExecutionContext context, ref bool forceCreation)
 {
     var settings = this.SettingsAs<ProcessLicenseManagerSettings>();
     var process = settings.GetProcess(license.KeyAs<ProcessLicenseKey>());
     process.Start();
     if (settings.WaitForExit)
     {
         process.WaitForExit();
     }
 }
Beispiel #2
0
        public override void Install(IApplicationLicense license, Client.IExecutionContext context, ref bool forceCreation)
        {
            if (context.HasCompleted | context.AutoLaunch)
            {
                var licenseKey = license.KeyAs<ProcessLicenseKey>();

                #region Start Process
                //create process for executable
                var process = context.Executable.GetProcessForExecutable(context.Profile);

                //get executable aruments
                string executableArgument = process.StartInfo.Arguments;

                //get expanded key arguments
                string newArguments = Environment.ExpandEnvironmentVariables(licenseKey.Value);

                if (!string.IsNullOrWhiteSpace(executableArgument))
                {
                    //compile parameters
                    process.StartInfo.Arguments = string.Format("{0} {1}", newArguments, executableArgument);
                }
                else
                {
                    //only license arguments passed
                    process.StartInfo.Arguments = newArguments;
                }

                //start process
                if (process.Start())
                {
                    //executables process creation should not be forced
                    forceCreation = false;

                    //add process to context
                    context.AddProcess(process, true);
                }
                #endregion
            }
        }
Beispiel #3
0
        public override void Install(IApplicationLicense license, IExecutionContext context, ref bool forceCreation)
        {
            if (context.HasCompleted | context.AutoLaunch)
            {
                #region Validation
                //get installation directory
                string originPath = this.GetOriginPath();

                if (String.IsNullOrWhiteSpace(originPath))
                {
                    context.Client.Log.AddError("Could not obtain Origin client executable path.", null, LogCategories.Configuration);
                    return;
                }

                if (!File.Exists(originPath))
                {
                    context.Client.Log.AddError(String.Format("Origin client executable not found at {0}.", originPath), null, LogCategories.Configuration);
                    return;
                }

                #endregion

                #region Clear XML Configuration

                //get folder name
                string folderName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Origin");

                //get file name
                string fileName = Path.Combine(folderName, "local.xml");

                if (!Directory.Exists(folderName))
                    Directory.CreateDirectory(folderName);

                //create new stream and write or update its configuration data
                using (var xmlStream = new FileStream(fileName, FileMode.OpenOrCreate))
                {
                    XmlDocument document = new XmlDocument();
                    //preserve white space
                    document.PreserveWhitespace = true;

                    try
                    {
                        document.Load(xmlStream);
                    }
                    catch (XmlException)
                    {
                        //could not load
                    }

                    XmlNode settingsNode = null;

                    #region Find Settings Node
                    if (document.HasChildNodes)
                    {
                        foreach (XmlNode node in document.ChildNodes)
                        {
                            if (node.Name == "Settings")
                            {
                                settingsNode = node;
                                break;
                            }
                        }
                    }
                    #endregion

                    #region Create Settings Node
                    if (settingsNode == null)
                    {
                        settingsNode = document.CreateElement("Settings");
                        document.AppendChild(settingsNode);
                    }
                    #endregion

                    bool isSet = false;

                    #region Update Existing Node
                    if (settingsNode.HasChildNodes)
                    {
                        foreach (XmlLinkedNode el in settingsNode.ChildNodes)
                        {
                            if (el is XmlElement)
                            {
                                var element = (XmlElement)el;
                                if (element.HasAttribute("key") && element.Attributes["key"].Value == "AcceptedEULAVersion")
                                {
                                    if (element.Attributes["value"].Value == "0")
                                        element.Attributes["value"].Value = (2).ToString();

                                    isSet = true;
                                    break;
                                }
                            }
                        }
                    }
                    #endregion

                    #region Clear Additional Settings
                    if (settingsNode.HasChildNodes)
                    {
                        List<XmlElement> removedElements = new List<XmlElement>();
                        foreach (XmlLinkedNode el in settingsNode.ChildNodes)
                        {
                            if (el is XmlElement)
                            {
                                var element = (XmlElement)el;
                                if (element.HasAttribute("key") &&
                                    element.Attributes["key"].Value == "AutoLogin" ||
                                    element.Attributes["key"].Value == "LoginAsInvisible" ||
                                    element.Attributes["key"].Value == "LoginEmail" ||
                                    element.Attributes["key"].Value == "LoginToken" ||
                                    element.Attributes["key"].Value == "RememberMeEmail")
                                {
                                    removedElements.Add(element);
                                }
                            }
                        }

                        foreach (var element in removedElements)
                        {
                            settingsNode.RemoveChild(element);
                        }
                    }
                    #endregion

                    #region Create new node
                    if (!isSet)
                    {
                        var setting = document.CreateElement("Setting");
                        settingsNode.AppendChild(setting);
                        setting.SetAttribute("key", "AcceptedEULAVersion");
                        setting.SetAttribute("type", "2");
                        setting.SetAttribute("value", "2");
                    }
                    #endregion

                    //reset stream
                    xmlStream.SetLength(0);

                    //save document
                    document.Save(xmlStream);
                }
                #endregion

                string processName = Path.GetFileNameWithoutExtension(originPath);

                #region Initialize Process

                //get existing origin process
                var originProcess = Process.GetProcessesByName(processName).Where(x => String.Compare(x.MainModule.FileName, originPath, true) == 0).FirstOrDefault();

                bool processExisted = originProcess != null;

                if (!processExisted)
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.FileName = originPath;
                    startInfo.Arguments = "/NoEULA";
                    startInfo.WorkingDirectory = Path.GetDirectoryName(originPath);
                    startInfo.ErrorDialog = false;
                    startInfo.UseShellExecute = false;

                    //create origin process
                    originProcess = new Process() { StartInfo = startInfo };
                }

                originProcess.EnableRaisingEvents = true;
                originProcess.Exited += new EventHandler(OnInternalProcessExited);

                #endregion

                #region Start Origin
                if (processExisted || originProcess.Start())
                {
                    //mark process created
                    forceCreation = true;

                    //atach handlers
                    context.ExecutionStateChaged += OnExecutionStateChaged;

                    //add process to context process list
                    context.AddProcess(originProcess, true);

                    if (CoreProcess.WaitForWindowCreated(originProcess, 120000, true))
                    {
                        try
                        {
                            IntPtr mainWindow = originProcess.MainWindowHandle;

                            //create input simulator
                            WindowsInput.KeyboardSimulator sim = new WindowsInput.KeyboardSimulator();

                            if (!this.FocusField(originProcess, OriginInputFileds.Username, 50))
                                return;

                            //clear username filed
                            sim.ModifiedKeyStroke(WindowsInput.Native.VirtualKeyCode.LCONTROL, WindowsInput.Native.VirtualKeyCode.VK_A);

                            //send back to clear any possible typed value
                            sim.KeyPress(WindowsInput.Native.VirtualKeyCode.BACK);

                            //set username
                            sim.TextEntry(license.KeyAs<UserNamePasswordLicenseKeyBase>().Username);

                            if (!this.FocusField(originProcess, OriginInputFileds.Password, 50))
                                return;

                            //clear password filed
                            sim.ModifiedKeyStroke(WindowsInput.Native.VirtualKeyCode.LCONTROL, WindowsInput.Native.VirtualKeyCode.VK_A);

                            //send back to clear any possible typed value
                            sim.KeyPress(WindowsInput.Native.VirtualKeyCode.BACK);

                            //set password
                            sim.TextEntry(license.KeyAs<UserNamePasswordLicenseKeyBase>().Password);

                            //proceed with login
                            sim.KeyPress(WindowsInput.Native.VirtualKeyCode.RETURN);

                            //set environment variable
                            Environment.SetEnvironmentVariable("LICENSEKEYUSER", license.KeyAs<OriginLicenseKey>().Username);

                            //wait for window to be destroyed
                            if (CoreProcess.WaitForWindowDestroyed(mainWindow, 120000))
                                //delay installation process
                                System.Threading.Thread.Sleep(3000);
                        }
                        catch
                        {
                            throw;
                        }
                    }
                    else
                    {
                        context.Client.Log.AddError("Origin client window was not created after specified period of time.", null, LogCategories.Configuration);
                    }
                }
                else
                {
                    context.Client.Log.AddError(String.Format("Origin client executable {0} could not be started.", originPath), null, LogCategories.Configuration);
                }
                #endregion
            }
        }
Beispiel #4
0
        public override void Install(IApplicationLicense license, IExecutionContext context, ref bool forceCreation)
        {
            if (context.HasCompleted | context.AutoLaunch)
            {
                #region Variables
                string executablePath = String.Empty,
                    workingDirectory = String.Empty,
                    arguments = String.Empty;
                var key = license.KeyAs<SteamLicenseKey>();
                #endregion

                #region Initialize Variables
                if (!String.IsNullOrWhiteSpace(context.Executable.ExecutablePath))
                {
                    executablePath = Environment.ExpandEnvironmentVariables(context.Executable.ExecutablePath);
                }
                else
                {
                    throw new ArgumentNullException("Steam executable path invalid", "ExecutablePath");
                }
                if (!String.IsNullOrWhiteSpace(context.Executable.WorkingDirectory))
                {
                    workingDirectory = Environment.ExpandEnvironmentVariables(context.Executable.WorkingDirectory);
                }
                else
                {
                    workingDirectory = Path.GetDirectoryName(executablePath);
                }
                if (!String.IsNullOrWhiteSpace(context.Executable.Arguments))
                {
                    arguments = Environment.ExpandEnvironmentVariables(context.Executable.Arguments);
                }
                arguments = String.Format("-login {0} {1} {2}", key.Username, key.Password, arguments);
                #endregion

                #region Initialize Process
                var streamProcess = new Process();
                streamProcess.StartInfo.FileName = executablePath;
                streamProcess.StartInfo.WorkingDirectory = workingDirectory;
                streamProcess.StartInfo.Arguments = arguments;
                streamProcess.StartInfo.UseShellExecute = false;
                streamProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                streamProcess.EnableRaisingEvents = true;
                streamProcess.Exited += new EventHandler(OnInternalProcessExited);
                #endregion

                #region Start steam process
                context.ExecutionStateChaged += OnExecutionStateChaged;

                //set environment variables
                if (!String.IsNullOrWhiteSpace(key.Username))
                    Environment.SetEnvironmentVariable("LICENSEKEYUSER", key.Username);

                if (!String.IsNullOrWhiteSpace(key.AccountId))
                    Environment.SetEnvironmentVariable("LICENSEKEYUSERID", key.AccountId);

                if (streamProcess.Start())
                {
                    //executables process creation should not be forced
                    forceCreation = false;

                    //add process to context
                    context.AddProcess(streamProcess, true);
                }
                else
                {
                    throw new Exception("Steam process was not created.");
                }

                #endregion
            }
        }
Beispiel #5
0
        public override void Install(IApplicationLicense license, Client.IExecutionContext context, ref bool forceCreation)
        {
            #region Initialize Variables
            var settings = this.SettingsAs<RegistryLicenseManagerSettings>();
            string registryPath = string.Empty,valuePath = string.Empty;
            object value = null;
            if (!String.IsNullOrWhiteSpace(settings.RegistryPath))
            {
                registryPath = Environment.ExpandEnvironmentVariables(settings.KeyPath);
                valuePath = Environment.ExpandEnvironmentVariables(settings.ValueName);
                if (settings.ValueKind == RegistryValueKind.Binary)
                {
                    #region Convert string to binary
                    try
                    {
                        string[] bytes = license.KeyAs<RegistryLicenseKey>().Value.Split(',');
                        byte[] array = new byte[bytes.Count()];
                        int index = 0;
                        foreach (var stringByte in bytes)
                        {
                            array[index] = Byte.Parse(stringByte, System.Globalization.NumberStyles.HexNumber);
                            index++;
                        }
                        value = array;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Could not convert binary data.", ex);
                    }
                    #endregion
                }
                else
                {
                    value = Environment.ExpandEnvironmentVariables(license.KeyAs<RegistryLicenseKey>().Value);
                }
            }
            else
            {
                throw new Exception("Invalid registry path specified.");
            }
            #endregion

            #region Get base key
            RegistryKey baseKey = null;
            switch (settings.Hive)
            {
                case RegistryHive.Users:
                    baseKey = Registry.Users;
                    break;
                case RegistryHive.PerformanceData:
                    baseKey = Registry.PerformanceData;
                    break;
                case RegistryHive.ClassesRoot:
                    baseKey = Registry.ClassesRoot;
                    break;
                case RegistryHive.CurrentConfig:
                    baseKey = Registry.CurrentConfig;
                    break;
                case RegistryHive.CurrentUser:
                    baseKey = Registry.CurrentUser;
                    break;
                case RegistryHive.LocalMachine:
                    baseKey = Registry.LocalMachine;
                    break;
                default:
                    throw new ArgumentException("Invalid registry hive specified.");
            }
            #endregion

            #region Set Values
            var destinationKey = baseKey.OpenSubKey(registryPath, true);
            if (destinationKey == null)
            {
                destinationKey = baseKey.CreateSubKey(registryPath);
            }
            destinationKey.SetValue(valuePath, value, settings.ValueKind);
            destinationKey.Close();
            #endregion
        }
Beispiel #6
0
        public override void Install(IApplicationLicense license, IExecutionContext context, ref bool forceCreation)
        {
            if (context.HasCompleted | context.AutoLaunch)
            {
                var key = license.KeyAs<MineCraftLicenseKey>();

                #region VALIDATION

                if (key == null)
                    throw new ArgumentNullException("Key");

                if (String.IsNullOrWhiteSpace(key.Username))
                    throw new ArgumentNullException("Username");

                if (String.IsNullOrWhiteSpace(key.Password))
                    throw new ArgumentNullException("Password");

                #endregion

                #region AUTH
                var auth = new AuthenticateRequest();
                auth.ClientToken = Guid.NewGuid().ToString();
                auth.Username = key.Username;
                auth.Password = key.Password;

                WebRequest request = WebRequest.Create(api_path);
                request.ContentType = "application/json";
                request.Method = "POST";

                try
                {
                    using (var requestStream = request.GetRequestStream())
                    {
                        string input = JsonConvert.SerializeObject(auth);
                        byte[] requestPayload = Encoding.Default.GetBytes(input);
                        requestStream.Write(requestPayload, 0, requestPayload.Length);
                    };
                }
                catch (WebException)
                {
                    throw;
                }
                #endregion

                #region RESPONSE
                AuthenticateRespnse authResponse;

                try
                {
                    var response = request.GetResponse();
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            authResponse = JsonConvert.DeserializeObject<AuthenticateRespnse>(reader.ReadToEnd());
                        }
                    }
                }
                catch (WebException)
                {
                    throw;
                }
                #endregion

                #region PROFILE
                var selectedProfile = authResponse.SelectedProfile;

                if (selectedProfile == null)
                {
                    selectedProfile = new MinecraftProfile();
                    selectedProfile.Id = Guid.NewGuid().ToString();
                    selectedProfile.Name = "Demo";
                }

                //create profile
                var launcherProfile = new LauncherProfile();
                launcherProfile.ClientToken = authResponse.ClientToken;
                launcherProfile.SelectedProfile = selectedProfile.Name;

                //create profile entry
                launcherProfile.Profiles.Add(selectedProfile.Name, new LauncherUserProfile() { Name = selectedProfile.Name, PlayerUUID = selectedProfile.Id });

                //create auth database entry
                launcherProfile.AuthenticationDatabase.Add(selectedProfile.Id, new Authentication()
                {
                    Username = auth.Username,
                    AccessToken = authResponse.AccessToken,
                    UUID = Guid.Parse(selectedProfile.Id).ToString(),
                    DisplayName = selectedProfile.Name
                });

                //create destination directory if required
                if (!Directory.Exists(target_directory_path))
                    Directory.CreateDirectory(target_directory_path);

                var output = JsonConvert.SerializeObject(launcherProfile, Formatting.Indented);

                //write to configuration file
                using (var launcher_profile_stream = new FileStream(target_file_path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    //clear all file contents
                    launcher_profile_stream.SetLength(0);
                    //write data
                    using (StreamWriter writer = new StreamWriter(launcher_profile_stream))
                    {
                        writer.Write(output);
                    }
                }
                #endregion
            }
        }
Beispiel #7
0
        public override void Install(IApplicationLicense license, IExecutionContext context, ref bool forceCreation)
        {
            if (context.HasCompleted | context.AutoLaunch)
            {
                #region Validation
                //get installation directory
                string uplayPath = this.GetUplayPath();

                if (String.IsNullOrWhiteSpace(uplayPath) || !File.Exists(uplayPath))
                {
                    context.Client.Log.AddError(String.Format("Uplay client executable not found at {0}.", uplayPath), null, LogCategories.Configuration);
                    return;
                }

                #endregion

                string processName = Path.GetFileNameWithoutExtension(uplayPath);

                #region Initialize Process

                //get existing uplay process
                var uplayProcess = Process.GetProcessesByName(processName).Where(x => String.Compare(x.MainModule.FileName, uplayPath, true) == 0).FirstOrDefault();

                bool processExisted = uplayProcess != null;

                if(!processExisted)
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.FileName = uplayPath;
                    startInfo.WorkingDirectory = Path.GetDirectoryName(uplayPath);
                    startInfo.ErrorDialog = false;
                    startInfo.UseShellExecute = false;

                    //create uplay process
                    uplayProcess = new Process() { StartInfo = startInfo };
                }

                uplayProcess.EnableRaisingEvents = true;
                uplayProcess.Exited += new EventHandler(OnInternalProcessExited);

                #endregion

                #region Start Uplay
                if (uplayProcess.Start())
                {
                    //mark process created
                    forceCreation = true;

                    //atach handlers
                    context.ExecutionStateChaged += OnExecutionStateChaged;

                    //add process to context process list
                    context.AddProcess(uplayProcess, true);

                    if (CoreProcess.WaitForWindowCreated(uplayProcess, 120000, true))
                    {
                        try
                        {
                            //disable input
                            User32.BlockInput(true);

                            //get window
                            WindowInfo uplayWindow = new WindowInfo(uplayProcess.MainWindowHandle);

                            //activate origin window
                            uplayWindow.BringToFront();
                            uplayWindow.Activate();

                            //give some time to activate fields
                            System.Threading.Thread.Sleep(5000);

                            //disable input
                            User32.BlockInput(true);
                            //activate origin window
                            uplayWindow.BringToFront();
                            uplayWindow.Activate();

                            //create input simulator
                            WindowsInput.KeyboardSimulator sim = new WindowsInput.KeyboardSimulator();

                            //send tab
                            sim.ModifiedKeyStroke(WindowsInput.Native.VirtualKeyCode.LCONTROL, WindowsInput.Native.VirtualKeyCode.TAB);

                            //clear username filed
                            sim.ModifiedKeyStroke(WindowsInput.Native.VirtualKeyCode.LCONTROL, WindowsInput.Native.VirtualKeyCode.VK_A);

                            //disable input
                            User32.BlockInput(true);
                            //activate origin window
                            uplayWindow.BringToFront();
                            uplayWindow.Activate();

                            //send back to clear any possible typed value
                            sim.KeyDown(WindowsInput.Native.VirtualKeyCode.BACK);

                            //disable input
                            User32.BlockInput(true);
                            //activate origin window
                            uplayWindow.BringToFront();
                            uplayWindow.Activate();

                            //set username
                            sim.TextEntry(license.KeyAs<UserNamePasswordLicenseKeyBase>().Username);

                            //disable input
                            User32.BlockInput(true);
                            //activate origin window
                            uplayWindow.BringToFront();
                            uplayWindow.Activate();

                            //swicth field
                            sim.KeyDown(WindowsInput.Native.VirtualKeyCode.TAB);

                            //disable input
                            User32.BlockInput(true);
                            //activate origin window
                            uplayWindow.BringToFront();
                            uplayWindow.Activate();

                            //clear password filed
                            sim.ModifiedKeyStroke(WindowsInput.Native.VirtualKeyCode.LCONTROL, WindowsInput.Native.VirtualKeyCode.VK_A);

                            //disable input
                            User32.BlockInput(true);
                            //activate origin window
                            uplayWindow.BringToFront();
                            uplayWindow.Activate();

                            //send back to clear any possible typed value
                            sim.KeyDown(WindowsInput.Native.VirtualKeyCode.BACK);

                            //disable input
                            User32.BlockInput(true);
                            //activate origin window
                            uplayWindow.BringToFront();
                            uplayWindow.Activate();

                            //set password
                            sim.TextEntry(license.KeyAs<UserNamePasswordLicenseKeyBase>().Password);

                            //disable input
                            User32.BlockInput(true);
                            //activate origin window
                            uplayWindow.BringToFront();
                            uplayWindow.Activate();

                            //proceed with login
                            sim.KeyDown(WindowsInput.Native.VirtualKeyCode.RETURN);

                            //disable input
                            User32.BlockInput(true);

                            //activate origin window
                            uplayWindow.BringToFront();
                            uplayWindow.Activate();

                            //set environment variable
                            Environment.SetEnvironmentVariable("LICENSEKEYUSER", license.KeyAs<UplayLicenseKey>().Username);

                            //delay installation process
                            System.Threading.Thread.Sleep(5000);
                        }
                        catch
                        {
                            throw;
                        }
                        finally
                        {
                            //enable input
                            User32.BlockInput(false);
                        }

                    }
                    else
                    {
                        context.Client.Log.AddError("Uplay client window was not created after specified period of time.", null, LogCategories.Configuration);
                    }
                }
                else
                {
                    context.Client.Log.AddError(String.Format("Uplay client executable {0} could not be started.", uplayPath), null, LogCategories.Configuration);
                }
                #endregion
            }
        }
Beispiel #8
0
        public override void Install(IApplicationLicense license, IExecutionContext context, ref bool forceCreation)
        {
            if (context.HasCompleted | context.AutoLaunch)
            {
                if(cToken!=null && cToken.Token.CanBeCanceled)
                {
                    cToken.Cancel();
                }
                else
                {
                    cToken = new CancellationTokenSource();
                }

                var settings = this.SettingsAs<BattleNetManagerSettings>();
                var key = license.KeyAs<BattleNetLicenseKey>();

                #region VALIDATION

                if (settings == null)
                    throw new ArgumentNullException("Settings");

                if (key == null)
                    throw new ArgumentNullException("Key");

                if (string.IsNullOrWhiteSpace(key.Username))
                    throw new ArgumentNullException("Username");

                if (string.IsNullOrWhiteSpace(key.Password))
                    throw new ArgumentNullException("Password");

                #endregion

                //get full path to executable
                string fulleExePath = Environment.ExpandEnvironmentVariables(context.Executable.ExecutablePath);

                //if working directory not specified set it to null
                string workingDirectory = string.IsNullOrWhiteSpace(context.Executable.WorkingDirectory) ? null : Environment.ExpandEnvironmentVariables(context.Executable.WorkingDirectory);

                string userName = key.Username;
                string passWord = key.Password;

                #region VALIDATE FILE EXISTS
                if (!File.Exists(fulleExePath))
                {
                    context.WriteMessage(string.Format("BattleNet executable not found at {0}", fulleExePath));
                    return;
                }
                #endregion

                #region PROCESS CLEANUP
                //ensure no battlenet processes running
                foreach (var processModuleFileName in processImageFileNames)
                {
                    if (string.IsNullOrWhiteSpace(processModuleFileName))
                        continue;

                    var processList = Process.GetProcessesByName(processModuleFileName);
                    processList.ToList().ForEach(x =>
                    {
                        try
                        {
                            x.Kill();
                        }
                        catch
                        {
                            Trace.WriteLine(string.Format("Could not kill BattleNet process {0}", processModuleFileName));
                        }
                    });
                }
                #endregion

                #region CONFIG CLEANUP
                //ensure configuration valid for login operation
                if (File.Exists(configPath))
                {
                    var fullConfig = File.ReadAllText(configPath);
                    fullConfig = RemoveLineForPattern(fullConfig, @"AutoLogin");
                    fullConfig = RemoveLineForPattern(fullConfig, @"SavedAccountNames");
                    File.WriteAllText(configPath, fullConfig);
                }
                #endregion

                //create process start info
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = fulleExePath;
                startInfo.WorkingDirectory = workingDirectory;

                //startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                //startInfo.CreateNoWindow = true;

                //create process class
                Process bnProcess = new Process() { StartInfo = startInfo };

                //try to start process and add it to execution context
                if (context.AddProcessIfStarted(bnProcess,true))
                {
                    //assign event handler
                    context.ExecutionStateChaged += OnExecutionStateChaged;

                    //enable event raising and hook event handlers
                    bnProcess.EnableRaisingEvents = true;
                    bnProcess.Exited += OnInternalProcessExited;

                    //wait for battlenet window
                    var task = WindowInfo.WaitForWindowCreatedAsync("Battle.net Login", -1,cToken.Token );

                    try
                    {
                        task.Wait();
                    }
                    catch (AggregateException aex)
                    {
                        aex.Handle(ex =>
                        {
                            // Handle the cancelled tasks
                            TaskCanceledException tcex = ex as TaskCanceledException;
                            if (tcex != null)
                            {
                                Console.WriteLine("Handling cancellation of task {0}", tcex.Task.Id);
                                return true;
                            }

                            // Not handling any other types of exception.
                            return false;
                        });
                        return;
                    }

                    if (!task.Result.Item1)
                    {
                        //window not found
                        return;
                    }

                    Process targetProcess = task.Result.Item2.First();

                    #region SIM
                    try
                    {

                        IntPtr window = targetProcess.MainWindowHandle;

                        WindowInfo info = new WindowInfo(window);

                        if (info.IsMinimized)
                            info.Restore();

                        info.BringToFront();
                        info.Activate();

                        //block user input
                        User32.BlockInput(true);

                        Thread.Sleep(5000);

                        KeyboardSimulator sim = new KeyboardSimulator();
                        MouseSimulator msim = new MouseSimulator();

                        var x = info.Location.X + info.Width - 150;
                        var y = info.Location.Y + 150;
                        System.Windows.Forms.Cursor.Position = new System.Drawing.Point(x, y);
                        msim.LeftButtonClick();

                        //clear username filed
                        sim.ModifiedKeyStroke(WindowsInput.Native.VirtualKeyCode.LCONTROL, WindowsInput.Native.VirtualKeyCode.VK_A);

                        //send back to clear any possible typed value
                        sim.KeyPress(WindowsInput.Native.VirtualKeyCode.BACK);

                        //set username
                        sim.TextEntry(userName);

                        //reactivate
                        info.BringToFront();
                        info.Activate();

                        x = info.Location.X + info.Width - 150;
                        y = info.Location.Y + 200;
                        System.Windows.Forms.Cursor.Position = new System.Drawing.Point(x, y);

                        msim.LeftButtonClick();

                        //clear password filed
                        sim.ModifiedKeyStroke(WindowsInput.Native.VirtualKeyCode.LCONTROL, WindowsInput.Native.VirtualKeyCode.VK_A);

                        //send back to clear any possible typed value
                        sim.KeyPress(WindowsInput.Native.VirtualKeyCode.BACK);

                        //set password
                        sim.TextEntry(passWord);

                        //proceed with login
                        sim.KeyPress(WindowsInput.Native.VirtualKeyCode.RETURN);
                    }
                    catch(Exception ex)
                    {
                        context.WriteMessage(string.Format("License installation failed {0}", ex.Message));
                    }
                    finally
                    {
                        //unblock user input
                        User32.BlockInput(false);
                    }
                    #endregion
                }
            }
        }
Beispiel #9
0
        public override void Install(IApplicationLicense license, IExecutionContext context, ref bool forceCreation)
        {
            //clear current account
            using(var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Blizzard Entertainment\Battle.net\D3",true))
            {
                if(key !=null )
                    key.DeleteValue("AccountName",false);
            }

            this.License = license;
            this.Context = context;
            context.ExecutionStateChaged += OnExecutionStateChaged;

            //set environment variable
            Environment.SetEnvironmentVariable("LICENSEKEYUSER", license.KeyAs<UserNamePasswordLicenseKeyBase>().Username);
        }