private ICore ConnectToMCEBuddyEngine()
 {
     // Connect to the engine
     try
     {
         ICore pipeProxy = MCEBuddyEngineConnect.ConnectToLocalEngine();
         pipeProxy.EngineRunning(); // Test to check if we are really connected
         return(pipeProxy);
     }
     catch
     {
         return(null);
     }
 }
예제 #2
0
        static int Main(string[] args)
        {
            if (_pipeProxy != null)
            {
                Log.WriteSystemEventLog("MCEBuddy engine app already running, cannot start another instance.", EventLogEntryType.Error);
                return(-1); // We can't start engine's
            }

            if (!AppProcess.HaveAdministrativeRights())
            {
                Log.WriteSystemEventLog("Start MCEBuddy engine app with Administrative rights.", EventLogEntryType.Information);
                AppProcess.StartAppWithAdministrativeRights(Application.ExecutablePath); // Engine needs Admin rights for firewall and binding
                return(-2);                                                              // Exit, the process will restart with admin rights
            }

            // Capture the Window close event if the user manually closes it
            _controlHandler = new HandlerRoutine(ConsoleCloseCheck); // Setup a static object otherwise on some systems it crashes with null pointer exception due to garbage collection
            SetConsoleCtrlHandler(_controlHandler, true);

            // Now that we are running, first Stop the the Windows Service otherwise we don't be able to start (stop before starting the GUI to prevent closure)
            Log.WriteSystemEventLog("Trying to stop MCEBuddy engine service.", EventLogEntryType.Information);
            WindowsService.StopService(GlobalDefs.MCEBUDDY_SERVICE_NAME, 10000);

            //Start MCEBuddy GUI with Normal user rights (just incase this is running admin rights
            try
            {
                if (AppProcess.HaveAdministrativeRights())
                {
                    AppProcess.StartAppWithMediumPrivilegeFromUISession(Path.Combine(GlobalDefs.AppPath, "MCEBuddy.GUI.exe"), "", false);
                }
                else // Normal user
                {
                    Process Proc = new Process();
                    Proc.StartInfo.FileName       = Path.Combine(GlobalDefs.AppPath, "MCEBuddy.GUI.exe");
                    Proc.StartInfo.CreateNoWindow = false;
                    Proc.StartInfo.WindowStyle    = ProcessWindowStyle.Normal;
                    Proc.Start();
                }
            }
            catch (Exception e)
            {
                // Sometimes the DLL does not work or is missing or running on wrong windows version, catch it and log it
                Log.WriteSystemEventLog("MCEBuddy engine app: Unable to start MCEBuddy GUI. Error ->\r\n" + e.ToString(), EventLogEntryType.Warning);
            }

            Log.WriteSystemEventLog("Starting MCEBuddy engine app.", EventLogEntryType.Information);
            MCEBuddyConf.GlobalMCEConfig = new MCEBuddyConf(GlobalDefs.ConfigFile); // Read the settings for global objects

            MCEBuddyConf.CheckDefaultJobPaths();                                    // Update paths before we start the engine to it is read

            _host = new ServiceHost(typeof(Core));
            TimeSpan timeoutPeriod = GlobalDefs.PIPE_TIMEOUT;

            // Create a binding for network SOAP WEB SERVICES
            string serverString = GlobalDefs.MCEBUDDY_WEB_SOAP_PIPE;

            serverString = serverString.Replace(GlobalDefs.MCEBUDDY_SERVER_PORT, MCEBuddyConf.GlobalMCEConfig.GeneralOptions.localServerPort.ToString()); // Update the Server Port with that from the config file
            BasicHttpBinding ntb = new BasicHttpBinding(GlobalDefs.MCEBUDDY_PIPE_SECURITY);

            ntb.OpenTimeout            = ntb.CloseTimeout = ntb.SendTimeout = ntb.ReceiveTimeout = timeoutPeriod;
            ntb.TransferMode           = TransferMode.Buffered;
            ntb.MaxReceivedMessageSize = ntb.MaxBufferPoolSize = ntb.MaxBufferSize = Int32.MaxValue;
            ntb.ReaderQuotas           = XmlDictionaryReaderQuotas.Max;
            ServiceEndpoint soapEndpoint = _host.AddServiceEndpoint(typeof(ICore), ntb, serverString);

            // Increase the max objects allowed in serialization channel otherwise we lose the connection when there more than 5K objects in the queue
            foreach (OperationDescription operation in soapEndpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior = operation.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;

                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                }
            }

            // Create a binding for local NAMED PIPES
            NetNamedPipeBinding npb = new NetNamedPipeBinding();

            npb.OpenTimeout            = npb.CloseTimeout = npb.SendTimeout = npb.ReceiveTimeout = timeoutPeriod;
            npb.TransferMode           = TransferMode.Buffered;
            npb.MaxReceivedMessageSize = npb.MaxBufferPoolSize = npb.MaxBufferSize = Int32.MaxValue;
            npb.ReaderQuotas           = XmlDictionaryReaderQuotas.Max;
            ServiceEndpoint namedPipeEndpoint = _host.AddServiceEndpoint(typeof(ICore), npb, GlobalDefs.MCEBUDDY_LOCAL_NAMED_PIPE);

            // Increase the max objects allowed in serialization channel otherwise we lose the connection when there more than 5K objects in the queue
            foreach (OperationDescription operation in namedPipeEndpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior = operation.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;

                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                }
            }

            _host.CloseTimeout = GlobalDefs.PIPE_TIMEOUT;
            _host.Open();

            _pipeProxy = MCEBuddyEngineConnect.ConnectToLocalEngine();
            if (MCEBuddyConf.GlobalMCEConfig.GeneralOptions.engineRunning)
            {
                _pipeProxy.Start();
            }

            // Now that we are up and running
            SystemEvents.PowerModeChanged += OnPowerChange; // Register for power event changes

            ConsoleKeyInfo cki;

            Console.Title        = "MCEBuddy 2.x Service Started, Press ESC to stop";
            Console.WindowHeight = 15;
            Console.WindowWidth  = 80;
            int  lastNumJobs = 0;
            bool Shutdown    = false;

            while (!Shutdown)
            {
                if (_forceClosed)
                {
                    return(1); // Someone forced the closure, the handler will clean up. Exit now
                }
                if (Console.KeyAvailable)
                {
                    cki = Console.ReadKey(true);
                    if (cki.Key == ConsoleKey.Escape)
                    {
                        Log.WriteSystemEventLog("MCEBuddy engine app received user shutdown request.", EventLogEntryType.Information);
                        Shutdown = true;
                    }
                }

                try
                {
                    for (int i = 0, numJobs = _pipeProxy.NumConversionJobs(); i < numJobs; i++)
                    {
                        if (lastNumJobs != numJobs) // The number of conversion jobs has changed
                        {
                            Console.Clear();        // Clear the screen
                        }
                        string outputStr = "";
                        outputStr = "Job" + i.ToString();
                        JobStatus status = _pipeProxy.GetJobStatus(i);
                        if (status != null)
                        {
                            outputStr += " " + status.CurrentAction;
                            if (status.PercentageComplete > 0)
                            {
                                outputStr += " " + status.PercentageComplete.ToString("#0.0", CultureInfo.InvariantCulture) + "%";
                            }
                            else if (-1 == status.PercentageComplete)
                            {
                                outputStr += " Working..."; //some processes like ReMuxSupp don't update perc
                            }
                            if (!String.IsNullOrEmpty(status.ETA))
                            {
                                outputStr += " ETA=" + status.ETA;
                            }

                            if (!String.IsNullOrEmpty(status.SourceFile))
                            {
                                outputStr += " " + Path.GetFileName(status.SourceFile);
                            }
                        }
                        else
                        {
                            outputStr += " Idle";
                        }
                        if (outputStr.Length > 78)
                        {
                            outputStr = outputStr.Substring(0, 78);
                        }
                        Console.SetCursorPosition(0, i);
                        Console.Write(outputStr.PadRight(78));
                        lastNumJobs = _pipeProxy.NumConversionJobs();
                    }
                }
                catch (Exception) //while debugging catch Proxy Faulted state and reset it
                {
                    if (_forceClosed)
                    {
                        return(1);
                    }

                    if (Shutdown)
                    {
                        break; // we are done here
                    }
                    _pipeProxy = MCEBuddyEngineConnect.ConnectToLocalEngine();
                }

                System.Threading.Thread.Sleep(GlobalDefs.LOCAL_ENGINE_POLL_PERIOD);
            }

            ConsoleCloseCheck(ControlSignalType.CTRL_CLOSE_EVENT); // Gracefully shutdown the engine and restart the windows service

            return(0);                                             // All good
        }
예제 #3
0
        protected override void OnStart(string[] args)
        {
            Log.WriteSystemEventLog("MCEBuddy service OnStart called", EventLogEntryType.Information);

            try
            {
                RequestAdditionalTime(10000);                                           // Ask for 10 second to complete initial operations and not mark service as unresponsive

                MCEBuddyConf.GlobalMCEConfig = new MCEBuddyConf(GlobalDefs.ConfigFile); // Read the settings for global objects

                MCEBuddyConf.CheckDefaultJobPaths();                                    // Update paths before we start the engine to it is read

                _host = new ServiceHost(typeof(Core));
                TimeSpan timeoutPeriod = GlobalDefs.PIPE_TIMEOUT;

                // Create a binding for network SOAP WEB SERVICES
                string serverString = GlobalDefs.MCEBUDDY_WEB_SOAP_PIPE;
                serverString = serverString.Replace(GlobalDefs.MCEBUDDY_SERVER_PORT, MCEBuddyConf.GlobalMCEConfig.GeneralOptions.localServerPort.ToString(System.Globalization.CultureInfo.InvariantCulture)); // Update the Server Port with that from the config file
                BasicHttpBinding ntb = new BasicHttpBinding(GlobalDefs.MCEBUDDY_PIPE_SECURITY);
                ntb.OpenTimeout            = ntb.CloseTimeout = ntb.SendTimeout = ntb.ReceiveTimeout = timeoutPeriod;
                ntb.TransferMode           = TransferMode.Buffered;
                ntb.MaxReceivedMessageSize = ntb.MaxBufferPoolSize = ntb.MaxBufferSize = Int32.MaxValue;
                ntb.ReaderQuotas           = XmlDictionaryReaderQuotas.Max;
                ServiceEndpoint soapEndpoint = _host.AddServiceEndpoint(typeof(ICore), ntb, serverString);
                // Increase the max objects allowed in serialization channel otherwise we lose the connection when there more than 5K objects in the queue
                foreach (OperationDescription operation in soapEndpoint.Contract.Operations)
                {
                    DataContractSerializerOperationBehavior dataContractBehavior = operation.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;

                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                    }
                }

                // Create a binding for local NAMED PIPES
                NetNamedPipeBinding npb = new NetNamedPipeBinding();
                npb.OpenTimeout            = npb.CloseTimeout = npb.SendTimeout = npb.ReceiveTimeout = timeoutPeriod;
                npb.TransferMode           = TransferMode.Buffered;
                npb.MaxReceivedMessageSize = npb.MaxBufferPoolSize = npb.MaxBufferSize = Int32.MaxValue;
                npb.ReaderQuotas           = XmlDictionaryReaderQuotas.Max;
                ServiceEndpoint namedPipeEndpoint = _host.AddServiceEndpoint(typeof(ICore), npb, GlobalDefs.MCEBUDDY_LOCAL_NAMED_PIPE);
                // Increase the max objects allowed in serialization channel otherwise we lose the connection when there more than 5K objects in the queue
                foreach (OperationDescription operation in namedPipeEndpoint.Contract.Operations)
                {
                    DataContractSerializerOperationBehavior dataContractBehavior = operation.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;

                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                    }
                }

                _host.CloseTimeout = GlobalDefs.PIPE_TIMEOUT;
                _host.Open();

                Log.WriteSystemEventLog("MCEBuddy service started on port " + MCEBuddyConf.GlobalMCEConfig.GeneralOptions.localServerPort.ToString(System.Globalization.CultureInfo.InvariantCulture), EventLogEntryType.Information);

                _pipeProxy = MCEBuddyEngineConnect.ConnectToLocalEngine();
                if (MCEBuddyConf.GlobalMCEConfig.GeneralOptions.engineRunning) // Check for last saved state by user
                {
                    _pipeProxy.Start();
                    Log.WriteSystemEventLog(Localise.GetPhrase("Last user saved state: MCEBuddy engine started"), EventLogEntryType.Information);
                }
                else
                {
                    Log.WriteSystemEventLog(Localise.GetPhrase("Last user saved state: MCEBuddy engine NOT started"), EventLogEntryType.Information);
                }
            }
            catch (Exception e)
            {
                Log.WriteSystemEventLog(Localise.GetPhrase("MCEBuddy service failed to start. Error:") + e.ToString(), EventLogEntryType.Error);
            }
        }
예제 #4
0
        static int Main(string[] args)
        {
            Log.AppLog   = new Log(Log.LogDestination.Console); // Redirect to console all output
            Log.LogLevel = Log.LogEntryType.Debug;              // Print all messages
            ICore      _pipeProxy     = null;
            CLIOptions cliOptions     = new CLIOptions();
            string     currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            Log.AppLog.WriteEntry("", "\r\nMCEBuddy.UserCLI is a Command Line Interface for users to interact with the MCEBuddy engine", Log.LogEntryType.Debug);
            Log.AppLog.WriteEntry("", "Copyright (c) Ramit Bhalla, Build Version : " + currentVersion, Log.LogEntryType.Debug);
            Log.AppLog.WriteEntry("", "Build Date : " + System.IO.File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString(System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Debug);
            Log.AppLog.WriteEntry("", "", Log.LogEntryType.Debug);

            if (args.Length < 2) // Atleast 2 arguments are required
            {
                Usage();
                return(-1);
            }

            try
            {
                CommandLineParser parser = new CommandLineParser();
                if (!parser.ParseArguments(args, cliOptions))
                {
                    throw new Exception("Invalid Options");
                }
            }
            catch (Exception e)
            {
                Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI Invalid Input Error -> " + e.ToString() + "\r\n", Log.LogEntryType.Error);
                Usage();
                return(-1); // Bad usage
            }

            Log.AppLog.WriteEntry("", "\r\nMCEBuddy.UserCLI trying to connect to Engine " + cliOptions.Server + " on Port " + cliOptions.Port + "\r\n", Log.LogEntryType.Debug);

            // Connect to the engine
            try // Try to reconnect
            {
                string remoteServerName = cliOptions.Server;
                int    remoteServerPort = cliOptions.Port;

                _pipeProxy = MCEBuddyEngineConnect.ConnectToRemoteEngine(remoteServerName, remoteServerPort);
                _pipeProxy.EngineRunning(); // Test to check if we are really connected

                Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI successfully connected to MCEBuddy engine", Log.LogEntryType.Debug);

                // Pass the command to the engine
                switch (cliOptions.Command)
                {
                // Engine commands
                case "engine":
                    Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI processing command engine", Log.LogEntryType.Debug);

                    // Engine actions
                    switch (cliOptions.Action)
                    {
                    case "start":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI starting engine", Log.LogEntryType.Debug);
                        _pipeProxy.Start();
                        break;

                    case "stop":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI stopping engine", Log.LogEntryType.Debug);
                        _pipeProxy.Stop(true);
                        break;

                    case "pause":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI pausing engine", Log.LogEntryType.Debug);
                        _pipeProxy.SuspendConversion(true);
                        break;

                    case "resume":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI resuming engine", Log.LogEntryType.Debug);
                        _pipeProxy.SuspendConversion(false);
                        break;

                    case "rescan":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI rescanning monitor locations and logs", Log.LogEntryType.Debug);
                        _pipeProxy.Rescan();
                        break;

                    default:
                        Log.AppLog.WriteEntry("", "Invalid action " + cliOptions.Action, Log.LogEntryType.Error);
                        Usage();
                        return(-1);
                    }
                    break;

                // Adding a file to the queue
                case "addfile":
                    Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI processing command addfile", Log.LogEntryType.Debug);
                    if (String.IsNullOrWhiteSpace(cliOptions.Action))
                    {
                        Log.AppLog.WriteEntry("", "Invalid filename " + cliOptions.Action, Log.LogEntryType.Error);
                        Usage();
                        return(-1);
                    }

                    Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI adding file " + cliOptions.Action + " to the conversion queue", Log.LogEntryType.Debug);
                    if (Util.Net.IsUNCPath(Util.Net.GetUNCPath(cliOptions.Action)))     // check if the files are on a remote computer
                    {
                        Log.AppLog.WriteEntry("", "Networked files will be accessed using the logon credentials of the MCEBuddy Service, not the currently logged on user. You can manually specify the network credentials from the Settings -> Expert Settings page in MCEBuddy.", Log.LogEntryType.Warning);
                    }
                    _pipeProxy.AddManualJob(cliOptions.Action);
                    break;

                // Removing a job from the queue
                case "removejob":
                    Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI processing command removejob", Log.LogEntryType.Debug);
                    int fileNo;
                    if (String.IsNullOrWhiteSpace(cliOptions.Action) || (!int.TryParse(cliOptions.Action, out fileNo)) || (fileNo < 1))     // job starts at 1 for users
                    {
                        Log.AppLog.WriteEntry("", "Invalid job number " + cliOptions.Action, Log.LogEntryType.Error);
                        Usage();
                        return(-1);
                    }

                    Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI removing job " + fileNo + " from the conversion queue", Log.LogEntryType.Debug);
                    _pipeProxy.CancelJob(new int[] { --fileNo });   // MCEBuddy start jobs at 0
                    break;

                // Change priority
                case "priority":
                    Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI processing command change priority", Log.LogEntryType.Debug);
                    switch (cliOptions.Action)
                    {
                    case "low":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI setting priority to low", Log.LogEntryType.Debug);
                        _pipeProxy.ChangePriority("Low");
                        break;

                    case "normal":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI setting priority to normal", Log.LogEntryType.Debug);
                        _pipeProxy.ChangePriority("Normal");
                        break;

                    case "high":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI setting priority to high", Log.LogEntryType.Debug);
                        _pipeProxy.ChangePriority("High");
                        break;

                    default:
                        Log.AppLog.WriteEntry("", "Invalid priority " + cliOptions.Action, Log.LogEntryType.Error);
                        Usage();
                        return(-1);
                    }
                    break;

                // Remove file from History
                case "deletehistoryitem":
                    Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI processing command deleting file entry from history", Log.LogEntryType.Debug);
                    if (String.IsNullOrWhiteSpace(cliOptions.Action))
                    {
                        Log.AppLog.WriteEntry("", "Invalid filename " + cliOptions.Action, Log.LogEntryType.Error);
                        Usage();
                        return(-1);
                    }

                    Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI deleting item " + cliOptions.Action + " from History", Log.LogEntryType.Debug);
                    _pipeProxy.DeleteHistoryItem(cliOptions.Action);
                    break;

                // UPnP
                case "upnp":
                    Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI processing command UPnP", Log.LogEntryType.Debug);
                    switch (cliOptions.Action)
                    {
                    case "enable":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI enabling UPnP access port fowarding", Log.LogEntryType.Debug);
                        _pipeProxy.SetUPnPState(true);
                        break;

                    case "disable":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI disabling UPnP access port fowarding", Log.LogEntryType.Debug);
                        _pipeProxy.SetUPnPState(false);
                        break;

                    default:
                        Log.AppLog.WriteEntry("", "Invalid UPnP state " + cliOptions.Action, Log.LogEntryType.Error);
                        Usage();
                        return(-1);
                    }
                    break;

                // Firewall
                case "firewall":
                    Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI processing command Firewall", Log.LogEntryType.Debug);
                    switch (cliOptions.Action)
                    {
                    case "enable":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI enabling Firewall exception for MCEBuddy remote access", Log.LogEntryType.Debug);
                        _pipeProxy.SetFirewallException(true);
                        break;

                    case "disable":
                        Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI disabling Firewall exception for MCEBuddy remote access", Log.LogEntryType.Debug);
                        _pipeProxy.SetFirewallException(false);
                        break;

                    default:
                        Log.AppLog.WriteEntry("", "Invalid Firewall exception state " + cliOptions.Action, Log.LogEntryType.Error);
                        Usage();
                        return(-1);
                    }
                    break;

                default:
                    Log.AppLog.WriteEntry("", "Invalid command " + cliOptions.Command, Log.LogEntryType.Error);
                    Usage();
                    return(-1);
                }

                // Successful
                Log.AppLog.WriteEntry("", "\r\nMCEBuddy.UserCLI Successful!!", Log.LogEntryType.Debug);
                return(0); // we good here
            }
            catch (Exception e)
            {
                Log.AppLog.WriteEntry("", "MCEBuddy.UserCLI Error -> " + e.ToString() + "\r\n", Log.LogEntryType.Error);
                Log.AppLog.WriteEntry("", "\r\nMCEBuddy.UserCLI Failed!!", Log.LogEntryType.Debug);
                return(-2); // too bad
            }
        }