private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     CommonLog.Error(((Exception)e.ExceptionObject).Message + ((Exception)e.ExceptionObject).InnerException.Message);
 }
        public static int Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;

            // start the program ...

            if (Environment.UserInteractive)
            {
                string parameter   = "";
                bool   needDetails = false;

                if (args != null && args.Length >= 1)
                {
                    parameter = args[0];
                    parameter = parameter.Trim();

                    if (parameter == "install" || parameter == "uninstall" ||
                        parameter == "silent-install" || parameter == "silent-uninstall")
                    {
                        if (parameter == "silent-install" || parameter == "silent-uninstall")
                        {
                            if (parameter == "silent-install")
                            {
                                parameter = "install";
                            }
                            else if (parameter == "silent-uninstall")
                            {
                                parameter = "uninstall";
                            }
                        }
                        else
                        {
                            // redirect console output to parent process, normally it should be "cmd"
                            AttachConsole(ATTACH_PARENT_PROCESS);
                            needDetails = true;
                        }

                        string svcName = "";

                        if (args.Length >= 2)
                        {
                            string[] svcNameArgs = new string[args.Length - 1];
                            for (int i = 1; i < args.Length; i++)
                            {
                                svcNameArgs[i - 1] = args[i];
                            }

                            for (int i = 0; i < svcNameArgs.Length; i++)
                            {
                                if (svcName.Length == 0)
                                {
                                    svcName = svcNameArgs[i];
                                }
                                else
                                {
                                    svcName = svcName + " " + svcNameArgs[i];
                                }
                            }

                            svcName = svcName.Trim();
                        }

                        if (svcName.Length > 0)
                        {
                            SVC_NAME = svcName;
                        }
                    }
                    else
                    {
                        parameter = "";
                    }
                }

                parameter = parameter.Trim();
                if (parameter == "install" && SVC_NAME.Length > 0)
                {
                    Console.WriteLine("Start to install service with name [" + SVC_NAME + "]");
                    CommonLog.Info("Installing service...");
                    try
                    {
                        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                        CommonLog.Info("OK");
                        Console.WriteLine("Installed service [" + SVC_NAME + "] successfully");
                        if (needDetails)
                        {
                            Console.WriteLine("You might need to press enter to end the process");
                        }
                    }
                    catch (Exception ex)
                    {
                        CommonLog.Error("Error: " + ex.Message);
                        Console.WriteLine("Failed to install service [" + SVC_NAME + "]");
                        if (needDetails)
                        {
                            Console.WriteLine("You might need to press enter to end the process");
                        }
                        return(-1);
                    }
                }
                else if (parameter == "uninstall" && SVC_NAME.Length > 0)
                {
                    Console.WriteLine("Start to uninstall service [" + SVC_NAME + "]");
                    CommonLog.Info("Uninstalling service...");
                    try
                    {
                        ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                        CommonLog.Info("OK");
                        Console.WriteLine("Uninstalled service [" + SVC_NAME + "] successfully");
                        if (needDetails)
                        {
                            Console.WriteLine("You might need to press enter to end the process");
                        }
                    }
                    catch (Exception ex)
                    {
                        CommonLog.Error("Error: " + ex.Message);
                        //Console.WriteLine("Failed to uninstall service [" + SVC_NAME + "]");
                        if (needDetails)
                        {
                            Console.WriteLine("You might need to press enter to end the process");
                        }
                        return(-1);
                    }
                }
                else // Run as a console app normally ...
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new MainForm());
                    Environment.Exit(0);
                }
            }
            else
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new MediaService()
                };
                ServiceBase.Run(ServicesToRun);
            }

            return(0);
        }
        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.

            m_MediaResourceManager.Clear();
            m_MediaResourceManager.LoadHandlers();

            ConfigurationManager.RefreshSection("appSettings");
            ConfigurationManager.RefreshSection("media-servers");

            try
            {
                ConfigurationManager.RefreshSection("channel-input-queue-lengths");
            }
            catch { }

            CommonLog.Info("=== Media Server is starting ===");

            var appSettings = ConfigurationManager.AppSettings;

            string allAvailableChannels = "";

            if (appSettings.AllKeys.Contains("AvailableChannels"))
            {
                allAvailableChannels = appSettings["AvailableChannels"];
            }
            if (allAvailableChannels.Length > 0)
            {
                m_MediaResourceManager.SetAvailableChannelNames(allAvailableChannels);
            }

            string remoteValidationURL = "";

            if (appSettings.AllKeys.Contains("RemoteValidationURL"))
            {
                remoteValidationURL = appSettings["RemoteValidationURL"];
            }

            Dictionary <string, int> channelInputQueueLengths = null;

            try
            {
                var channelInputQueueLengthSetting = ConfigurationManager.GetSection("channel-input-queue-lengths") as NameValueCollection;
                if (channelInputQueueLengthSetting != null)
                {
                    channelInputQueueLengths = new Dictionary <string, int>();
                    var channelKeys = channelInputQueueLengthSetting.AllKeys;
                    foreach (var key in channelKeys)
                    {
                        int len = 0;
                        if (Int32.TryParse(channelInputQueueLengthSetting[key], out len))
                        {
                            if (!channelInputQueueLengths.ContainsKey(key))
                            {
                                channelInputQueueLengths.Add(key, len);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CommonLog.Error("Failed to load channel-input-queue-lengths: ");
                CommonLog.Error(ex.ToString());
            }

            var mediaServerSettings = (NameValueCollection)ConfigurationManager.GetSection("media-servers");
            var allKeys             = mediaServerSettings.AllKeys;

            foreach (var key in allKeys)
            {
                string                json        = mediaServerSettings[key];
                ServerSetting         setting     = JsonConvert.DeserializeObject <ServerSetting>(json);
                HttpSourceMediaServer mediaServer = new HttpSourceMediaServer(key, m_MediaResourceManager, CommonLog.GetLogger(),
                                                                              setting.InputIp, setting.InputPort, setting.OutputIp, setting.OutputPort, setting.InputWhitelist, setting.CertFile, setting.CertKey, channelInputQueueLengths);
                mediaServer.InputQueueSize         = setting.InputQueueSize;
                mediaServer.InputBufferSize        = setting.InputBufferSize;
                mediaServer.OutputQueueSize        = setting.OutputQueueSize;
                mediaServer.OutputBufferSize       = setting.OutputBufferSize;
                mediaServer.OutputSocketBufferSize = setting.OutputSocketBufferSize;
                mediaServer.SetClientValidator(new MediaClientValidator(CommonLog.GetLogger(), remoteValidationURL));
            }

            var servers = m_MediaResourceManager.GetServerList();

            foreach (var item in servers)
            {
                if (item.Start())
                {
                    CommonLog.Info("Media Server is working on port " + item.InputPort
                                   + " (input) and port " + item.OutputPort + " (output) ... ");
                }
            }
        }