Exemplo n.º 1
0
        public BeatmapImporter(BasicGameHost host,  BeatmapDatabase beatmaps = null)
        {
            this.beatmaps = beatmaps;

            channel = new IpcChannel<BeatmapImportMessage>(host);
            channel.MessageReceived += messageReceived;
        }
Exemplo n.º 2
0
        public void Send(string data)
        {
            try
            {
                var properties = new Hashtable();
                properties["portName"]            = Guid.NewGuid().ToString();
                properties["exclusiveAddressUse"] = false;
                properties["authorizedGroup"]     = "Everyone";

                var channel = new IpcChannel(properties, null, serverSinkProvider);

                try
                {
                    ChannelServices.RegisterChannel(channel, true);
                }
                catch
                {
                }

                var uri = string.Format("ipc://{0}/{1}.rem", typeof(IIpcClient).Name, typeof(RemoteObject).Name);
                var svc = Activator.GetObject(typeof(RemoteObject), uri) as IIpcClient;

                svc.Send(data);

                try
                {
                    ChannelServices.UnregisterChannel(channel);
                }
                catch
                {
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemplo n.º 3
0
        public static void CreateAndRegisterChannel(Type type)
        {
            IChannel channel     = new TcpChannel(int.Parse(System.Configuration.ConfigurationManager.AppSettings["ChannelPort"]));
            string   channelType = System.Configuration.ConfigurationManager.AppSettings["ChannelType"];

            if (channelType.ToLower() == "http")
            {
                channel = new HttpChannel(int.Parse(System.Configuration.ConfigurationManager.AppSettings["ChannelPort"]));
            }
            else if (channelType.ToLower() == "ipc")
            {
                channel = new IpcChannel(System.Configuration.ConfigurationManager.AppSettings["IpcChannelPortName"]);
            }
            bool   ensureSecurity = false;
            string security       = System.Configuration.ConfigurationManager.AppSettings["EnsureSecurity"];

            if (security == "1")
            {
                ensureSecurity = true;
            }
            ChannelServices.RegisterChannel(channel, ensureSecurity);
            string registerMode      = System.Configuration.ConfigurationManager.AppSettings["WellKnownObjectMode"];
            WellKnownObjectMode wkom = WellKnownObjectMode.Singleton;

            if (registerMode.ToLower() == "singlecall")
            {
                wkom = WellKnownObjectMode.SingleCall;
            }
            string objectClass = System.Configuration.ConfigurationManager.AppSettings["ObjectClass"];
            string objectUri   = "RemoteObject";

            if (!string.IsNullOrEmpty(objectClass))
            {
                objectUri = objectClass;
            }
            RemotingConfiguration.RegisterWellKnownServiceType(type, objectUri, wkom);
        }
Exemplo n.º 4
0
        public void Start()
        {
            Task.Factory.StartNew(() =>
            {
                var properties                    = new Hashtable();
                properties["portName"]            = typeof(IIpcClient).Name;
                properties["exclusiveAddressUse"] = false;
                properties["authorizedGroup"]     = "Everyone";

                var channel = new IpcChannel(properties, null, serverSinkProvider);

                try
                {
                    ChannelServices.RegisterChannel(channel, true);
                }
                catch
                {
                }

                var remoteObject = new RemoteObject(new _Server(this));

                RemotingServices.Marshal(remoteObject, typeof(RemoteObject).Name + ".rem");

                this.killer.WaitOne();

                RemotingServices.Disconnect(remoteObject);

                try
                {
                    ChannelServices.UnregisterChannel(channel);
                }
                catch
                {
                }
            });
        }
Exemplo n.º 5
0
        /// <summary>
        /// Registers IPC chnnael for remote communication
        /// </summary>
        private void RegisterChannelServices()
        {
            BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
            BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();

            serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
            System.Collections.IDictionary props = new Dictionary <string, string>();

            props["name"]     = String.Concat(SceReaderSettings.CompanyName, SceReaderSettings.ApplicationName, Environment.UserName);
            props["portName"] = MsdnReaderSettings.ChannelPortName;
            props["secure"]   = "true";
            props["tokenImpersonationLevel"] = "Impersonation";
            props["exclusiveAddressUse"]     = "false";

            // If channel is already registered - may happen if there is not enough time to unregister it on suspend, etc -
            // unregister and re-register it
            if (ChannelRegistered())
            {
                UnregisterChannelServices();
            }

            _channel = new IpcChannel(props, clientProvider, serverProvider);
            ChannelServices.RegisterChannel(_channel, true);
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            //IpcChannel channel = new IpcChannel("myhost");
            //ChannelServices.RegisterChannel(channel, false);
            //RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingObjects.Person), "RemotingPersonService", WellKnownObjectMode.SingleCall);

            HttpChannel httpChannel = new HttpChannel(9001);

            ChannelServices.RegisterChannel(httpChannel, false);

            TcpChannel tcpChannel = new TcpChannel(9002);

            ChannelServices.RegisterChannel(tcpChannel, false);

            IpcChannel ipcChannel = new IpcChannel("MyHost");

            ChannelServices.RegisterChannel(ipcChannel, false);

            RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingObjects.Person), "RemotingPersonService", WellKnownObjectMode.SingleCall);
            Console.ReadLine();

            System.Console.WriteLine("Server:Press Enter key to exit");
            System.Console.ReadLine();
        }
        public void TestIpc()
        {
            using (var server = new BackgroundGameHeadlessGameHost(@"server", new HostOptions {
                BindIPC = true
            }))
                using (var client = new HeadlessGameHost(@"client", new HostOptions {
                    BindIPC = true
                }))
                {
                    Assert.IsTrue(server.IsPrimaryInstance, @"Server wasn't able to bind");
                    Assert.IsFalse(client.IsPrimaryInstance, @"Client was able to bind when it shouldn't have been able to");

                    var serverChannel = new IpcChannel <Foobar>(server);
                    var clientChannel = new IpcChannel <Foobar>(client);

                    async void waitAction()
                    {
                        using (var received = new ManualResetEventSlim(false))
                        {
                            serverChannel.MessageReceived += message =>
                            {
                                Assert.AreEqual("example", message.Bar);
                                // ReSharper disable once AccessToDisposedClosure
                                received.Set();
                                return(null);
                            };

                            await clientChannel.SendMessageAsync(new Foobar { Bar = "example" }).ConfigureAwait(false);

                            received.Wait();
                        }
                    }

                    Assert.IsTrue(Task.Run(waitAction).Wait(10000), @"Message was not received in a timely fashion");
                }
        }
        public bool PassCommand(string filename, string encoding)
        {
            IpcChannel clientChanel = new IpcChannel("myClient");

            ChannelServices.RegisterChannel(clientChanel, false);
            IMyPadServer obj = (IMyPadServer)Activator.GetObject(
                typeof(IMyPadServer),
                "ipc://" + GetChannelName() + "/" + GetObjectName());

            try
            {
                obj.OpenPage(filename, encoding);
                return(true);
            }
            catch (RemotingException)
            {
                // Connection refused
                return(false);
            }
            finally
            {
                ChannelServices.UnregisterChannel(clientChanel);
            }
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            IpcChannel serverChannel = new IpcChannel("localhost:9090"); // Создаём канал сервера

            // Регистрируем канал сервера
            System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(serverChannel, false);

            // Обьявляем объекты для удаленных вызовов.
            System.Runtime.Remoting.RemotingConfiguration.
            RegisterWellKnownServiceType(typeof(ClassLibrary1.Class1), "RemoteObject1.rem",
                                         System.Runtime.Remoting.WellKnownObjectMode.Singleton);
            System.Runtime.Remoting.RemotingConfiguration.
            RegisterWellKnownServiceType(typeof(ClassLibrary2.Class2), "RemoteObject2.rem",
                                         System.Runtime.Remoting.WellKnownObjectMode.Singleton);
            System.Runtime.Remoting.RemotingConfiguration.
            RegisterWellKnownServiceType(typeof(ClassLibrary3.Class3), "RemoteObject3.rem",
                                         System.Runtime.Remoting.WellKnownObjectMode.Singleton);

            // Ожидаем реакции пользователя.
            Console.WriteLine("Server is running.\nIn this window will be displayed"
                              + " list all running methods.");
            Console.WriteLine("Press any button to stop the server...\n");
            Console.ReadLine();
        }
Exemplo n.º 10
0
        public void Run(MemoryReader reader, IpcChannel channel)
        {
            var o = reader.FindOffset(_pattern).Cast <int?>().FirstOrDefault();

            if (o == null)
            {
                channel.LogError("Could not find system message table");
                return;
            }

            var count = reader.ReadUInt32((int)o +
                                          _pattern.TakeWhile(x => x != null).Count());
            var func = reader.GetDelegate <GetMessageNameFunc>((int)o);
            var list = new List <Tuple <ushort, string> >();

            for (ushort i = 0; i < count; i++)
            {
                list.Add(Tuple.Create(i, Marshal.PtrToStringUni(func(i))));
            }

            channel.LogBasic("Found {0} system messages", list.Count);

            channel.SystemMessages = list;
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            try
            {
                RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;
                bool            secure     = false;
                int             port       = 12345;
                string          ipc        = String.Empty;
                bool            showhelp   = false;
                TypeFilterLevel typefilter = TypeFilterLevel.Low;

                OptionSet p = new OptionSet()
                {
                    { "s|secure", "Enable secure mode", v => secure = v != null },
                    { "p|port=", "Specify the local TCP port to listen on", v => port = int.Parse(v) },
                    { "t|typefilter=", "Specify the type filter level (low,full), default low",
                      v => typefilter = (TypeFilterLevel)Enum.Parse(typeof(TypeFilterLevel), v, true) },
                    { "i|ipc=", "Specify listening pipe name for IPC channel", v => ipc = v },
                    { "h|?|help", v => showhelp = v != null },
                };

                p.Parse(args);

                if (showhelp)
                {
                    Console.WriteLine("Example .NET Remoting Server");
                    Console.WriteLine("Copyright (c) James Forshaw 2014");
                    p.WriteOptionDescriptions(Console.Out);
                }
                else
                {
                    Trace.Listeners.Add(new ConsoleTraceListener(true));

                    IChannel    chan;
                    IDictionary properties = new Hashtable();

                    BinaryServerFormatterSinkProvider serverSinkProvider = new BinaryServerFormatterSinkProvider();
                    serverSinkProvider.TypeFilterLevel = typefilter;

                    if (!String.IsNullOrEmpty(ipc))
                    {
                        properties["portName"]        = ipc;
                        properties["authorizedGroup"] = "Everyone";

                        chan = new IpcChannel(properties, new BinaryClientFormatterSinkProvider(), serverSinkProvider);
                    }
                    else
                    {
                        properties["port"] = port;
                        chan = new TcpChannel(properties, new BinaryClientFormatterSinkProvider(), serverSinkProvider);
                    }

                    ChannelServices.RegisterChannel(chan, secure);    //register channel

                    RemotingConfiguration.RegisterWellKnownServiceType(
                        typeof(RemoteType),
                        "RemotingServer",
                        WellKnownObjectMode.Singleton);

                    bool isipc = chan is IpcChannel;

                    Console.WriteLine("Server Activated at {0}://{1}/RemotingServer", isipc ? "ipc" : "tcp", isipc ? ipc : "HOST:" + port.ToString());

                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 12
0
    public static void Main(string[] args)
    {
        //<snippet11>
        // Create the server channel.
        IpcChannel serverChannel =
            new IpcChannel("localhost:9090");

        //</snippet11>

        // Register the server channel.
        System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(
            serverChannel);

        //<snippet12>
        // Show the name of the channel.
        Console.WriteLine("The name of the channel is {0}.",
                          serverChannel.ChannelName);
        //</snippet12>

        //<snippet13>
        // Show the priority of the channel.
        Console.WriteLine("The priority of the channel is {0}.",
                          serverChannel.ChannelPriority);
        //</snippet13>

        //<snippet15>
        // Show the URIs associated with the channel.
        System.Runtime.Remoting.Channels.ChannelDataStore channelData =
            (System.Runtime.Remoting.Channels.ChannelDataStore)
            serverChannel.ChannelData;
        foreach (string uri in channelData.ChannelUris)
        {
            Console.WriteLine("The channel URI is {0}.", uri);
        }
        //</snippet15>

        // Expose an object for remote calls.
        System.Runtime.Remoting.RemotingConfiguration.
        RegisterWellKnownServiceType(
            typeof(RemoteObject), "RemoteObject.rem",
            System.Runtime.Remoting.WellKnownObjectMode.Singleton);

        //<snippet19>
        // Parse the channel's URI.
        string[] urls = serverChannel.GetUrlsForUri("RemoteObject.rem");
        if (urls.Length > 0)
        {
            string objectUrl = urls[0];
            string objectUri;
            string channelUri = serverChannel.Parse(objectUrl, out objectUri);
            Console.WriteLine("The object URI is {0}.", objectUri);
            Console.WriteLine("The channel URI is {0}.", channelUri);
            Console.WriteLine("The object URL is {0}.", objectUrl);
        }
        //</snippet19>

        // Wait for the user prompt.
        Console.WriteLine("Press ENTER to exit the server.");
        Console.ReadLine();
        Console.WriteLine("The server is exiting.");
    }
Exemplo n.º 13
0
        static void Run()
        {
            // Enable debugging if asked for
            if (debug)
            {
                var nconfig       = new LoggingConfiguration();
                var consoleTarget = new ColoredConsoleTarget();
                nconfig.AddTarget("console", consoleTarget);
                consoleTarget.Layout = "${logger} ${message}";

                var rule = new LoggingRule("*", LogLevel.Debug, consoleTarget);
                nconfig.LoggingRules.Add(rule);

                LogManager.Configuration = nconfig;
            }

            logger.Debug("Starting up IPC listener: {0}", channelName);

            var provider = new BinaryServerFormatterSinkProvider();

            provider.TypeFilterLevel = TypeFilterLevel.Full;

            IDictionary props = new Hashtable() as IDictionary;

            props["name"]     = "ipc";
            props["portName"] = channelName;

            IpcChannel ipcChannel = new IpcChannel(props, null, provider);

            ChannelServices.RegisterChannel(ipcChannel, false);
            Peach.Core.Agent.Monitors.WindowsDebug.DebuggerInstance.LastHeartBeat = DateTime.Now;

            try
            {
                Type commonInterfaceType = typeof(Peach.Core.Agent.Monitors.WindowsDebug.DebuggerInstance);

                RemotingConfiguration.RegisterWellKnownServiceType(
                    commonInterfaceType, "DebuggerInstance", WellKnownObjectMode.Singleton);

                while (true)
                {
                    Thread.Sleep(200);
                    if (Peach.Core.Agent.Monitors.WindowsDebug.DebuggerInstance.ExitInstance)
                    {
                        logger.Debug("ExitInstance is true!");
                        return;
                    }

                    // Timebomb!
                    if (timebomb && (DateTime.Now - Peach.Core.Agent.Monitors.WindowsDebug.DebuggerInstance.LastHeartBeat).TotalSeconds > 30)
                    {
                        logger.Debug("Last heartbeat over 30 seconds, exiting!");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Debug(ex.ToString());
            }
            finally
            {
                ChannelServices.UnregisterChannel(ipcChannel);
            }
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
#if !DEBUG
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#endif
            WorldWindow.VideoMemoryExhausted += ReportVideoMemoryExhaustion;

#if !DEBUG
            bool aborting = false;
#endif

#if DEBUG
            System.Text.StringBuilder oTemp = new System.Text.StringBuilder();
            foreach (String arg in args)
            {
                oTemp.Append(arg);
                oTemp.Append(Environment.NewLine);
            }
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                ShowMessageBox(
                    "Dapple is being invoked with the following command-line parameters:" + Environment.NewLine + oTemp.ToString() + Environment.NewLine + Environment.NewLine + "Attach debugger if desired, then press OK to continue.",
                    "Dapple Startup",
                    MessageBoxButtons.OK,
                    MessageBoxDefaultButton.Button1,
                    MessageBoxIcon.Information);
            }
#endif

            MontajRemote.RemoteInterface oRemoteInterface = null;
            IpcChannel oClientChannel = null;

            // Command line parsing
            CommandLineArguments cmdl = new CommandLineArguments(args);

            try
            {
                bool   blSelectPersonalDAP = false;
                bool   bAbort = false;
                string strView = "", strGeoTiff = "", strGeoTiffName = "", strLastView = "", strMapFileName = string.Empty;
                bool   bGeotiffTmp = false;
                String strKMLFile = String.Empty, strKMLName = String.Empty;
                bool   blKMLTmp = false;

                GeographicBoundingBox oAoi    = null;
                string strAoiCoordinateSystem = string.Empty;
                Dapple.Extract.Options.Client.ClientType eClientType = Dapple.Extract.Options.Client.ClientType.None;

                if (cmdl["h"] != null)
                {
                    PrintUsage();
                    return;
                }

                SetDCAvailability(cmdl);

                if (cmdl["callerprocid"] != null)
                {
                    g_iCallerProcID = Int32.Parse(cmdl["callerprocid"], CultureInfo.InvariantCulture);
                }

                if (cmdl[0] != null)
                {
                    if (String.Compare(cmdl[0], "ABORT") == 0 && cmdl[1] != null)
                    {
                        bAbort = true;
                    }
                    else
                    {
                        strView = Path.GetFullPath(cmdl[0]);
                        if (String.Compare(Path.GetExtension(strView), MainForm.ViewExt, true) != 0 || !File.Exists(strView))
                        {
                            PrintUsage();
                            return;
                        }
                    }
                }

                if (cmdl["geotiff"] != null)
                {
                    strGeoTiff = Path.GetFullPath(cmdl["geotiff"]);
                    if (!(String.Compare(Path.GetExtension(strGeoTiff), ".tiff", true) == 0 || String.Compare(Path.GetExtension(strGeoTiff), ".tif", true) == 0) || !File.Exists(strGeoTiff))
                    {
                        PrintUsage();
                        return;
                    }
                }

#if !DEBUG
                if (cmdl["noaborttool"] != null)
                {
                    g_blTestingMode = true;
                }
#endif
                if (cmdl["personaldap"] != null)
                {
                    blSelectPersonalDAP = true;
                }

                if (cmdl["geotifftmp"] != null)
                {
                    string strGeoTiffTmpVar = cmdl["geotifftmp"];
                    int    iIndex           = strGeoTiffTmpVar.IndexOf(":");
                    if (iIndex == -1)
                    {
                        PrintUsage();
                        return;
                    }

                    strGeoTiff     = Path.GetFullPath(strGeoTiffTmpVar.Substring(iIndex + 1));
                    strGeoTiffName = strGeoTiffTmpVar.Substring(0, iIndex);
                    bGeotiffTmp    = true;
                    if (strGeoTiffName.Length == 0 || !(String.Compare(Path.GetExtension(strGeoTiff), ".tiff", true) == 0 || String.Compare(Path.GetExtension(strGeoTiff), ".tif", true) == 0) || !File.Exists(strGeoTiff))
                    {
                        PrintUsage();
                        return;
                    }
                }

                if (cmdl["kmltmp"] != null)
                {
                    string strKMLTmpVar = cmdl["kmltmp"];
                    int    iIndex       = strKMLTmpVar.IndexOf(":");
                    if (iIndex == -1)
                    {
                        PrintUsage();
                        return;
                    }

                    strKMLFile = Path.GetFullPath(strKMLTmpVar.Substring(iIndex + 1));
                    strKMLName = strKMLTmpVar.Substring(0, iIndex);
                    blKMLTmp   = true;
                    if (strKMLName.Length == 0 || !(String.Compare(Path.GetExtension(strKMLFile), ".kmz", true) == 0 || String.Compare(Path.GetExtension(strKMLFile), ".kml", true) == 0) || !File.Exists(strKMLFile))
                    {
                        PrintUsage();
                        return;
                    }
                }

                if (cmdl["exitview"] != null)
                {
                    strLastView = Path.GetFullPath(cmdl["exitview"]);
                }

                if (cmdl["montajport"] != null)
                {
                    int iMontajPort = int.Parse(cmdl["montajport"], NumberStyles.Any, CultureInfo.InvariantCulture);

                    if (cmdl["dummyserver"] != null)
                    {
                        oClientChannel = new IpcChannel(String.Format(CultureInfo.InvariantCulture, "localhost:{0}", iMontajPort));
                        ChannelServices.RegisterChannel(oClientChannel, true);
                        RemotingConfiguration.RegisterWellKnownServiceType(typeof(MontajRemote.RemoteInterface), "MontajRemote", System.Runtime.Remoting.WellKnownObjectMode.Singleton);
                    }
                    else
                    {
                        oClientChannel = new IpcChannel();
                        ChannelServices.RegisterChannel(oClientChannel, true);
                    }

                    oRemoteInterface = (MontajRemote.RemoteInterface)Activator.GetObject(typeof(MontajRemote.RemoteInterface), String.Format(CultureInfo.InvariantCulture, "ipc://localhost:{0}/MontajRemote", iMontajPort));
                }

                if (cmdl["aoi"] != null)
                {
                    String[] strValues = cmdl["aoi"].Split(new char[] { ',' });
                    if (strValues.Length != 4)
                    {
                        ShowMessageBox(
                            "The -aoi command line argument has incorrect number of components.",
                            "Dapple Startup",
                            MessageBoxButtons.OK,
                            MessageBoxDefaultButton.Button1,
                            MessageBoxIcon.Error);
                        return;
                    }
                    double dMinX = 180, dMinY = 90, dMaxX = -180, dMaxY = -90;

                    bool bAoiArgument = double.TryParse(strValues[0], out dMinX);

                    if (bAoiArgument)
                    {
                        bAoiArgument = double.TryParse(strValues[1], out dMinY);
                    }

                    if (bAoiArgument)
                    {
                        bAoiArgument = double.TryParse(strValues[2], out dMaxX);
                    }

                    if (bAoiArgument)
                    {
                        bAoiArgument = double.TryParse(strValues[3], out dMaxY);
                    }

                    if (bAoiArgument)
                    {
                        oAoi = new GeographicBoundingBox(dMaxY, dMinY, dMinX, dMaxX);
                    }
                    else
                    {
                        ShowMessageBox(
                            "The -aoi command line argument has incorrectly-formatted component(s).",
                            "Dapple Startup",
                            MessageBoxButtons.OK,
                            MessageBoxDefaultButton.Button1,
                            MessageBoxIcon.Error);
                        return;
                    }

                    if (oAoi.North < oAoi.South || oAoi.East < oAoi.West)
                    {
                        ShowMessageBox(
                            "The -aoi command line argument specifies an incorrect bounding box.",
                            "Dapple Startup",
                            MessageBoxButtons.OK,
                            MessageBoxDefaultButton.Button1,
                            MessageBoxIcon.Error);
                        return;
                    }

                    if (cmdl["aoi_cs"] != null)
                    {
                        strAoiCoordinateSystem = cmdl["aoi_cs"];
                    }

                    if (string.IsNullOrEmpty(strAoiCoordinateSystem))
                    {
                        ShowMessageBox(
                            "The -aoi_cs command line parameter must be present when using -aoi parameter.",
                            "Dapple Startup",
                            MessageBoxButtons.OK,
                            MessageBoxDefaultButton.Button1,
                            MessageBoxIcon.Error);
                        return;
                    }

                    if (cmdl["filename_map"] != null)
                    {
                        strMapFileName = cmdl["filename_map"];
                    }
                }

                if (cmdl["client"] != null)
                {
                    try
                    {
                        eClientType = (Dapple.Extract.Options.Client.ClientType)Enum.Parse(eClientType.GetType(), cmdl["client"], true);
                    }
                    catch
                    {
                        ShowMessageBox(
                            "The -client command line is invalid.",
                            "Dapple Startup",
                            MessageBoxButtons.OK,
                            MessageBoxDefaultButton.Button1,
                            MessageBoxIcon.Error);
                        return;
                    }
                }


                // From now on in own path please and free the console
                Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.ExecutablePath));
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                if (bAbort)
                {
                    string strErrors = File.ReadAllText(args[1]);
#if !DEBUG
                    aborting = true;
#endif
                    ErrorDisplay errorDialog = new ErrorDisplay();
                    errorDialog.errorMessages(strErrors);
                    Application.Run(errorDialog);
                }
                else
                {
                    if (GetSystemMetrics(SM_REMOTESESSION) != 0)
                    {
                        ShowMessageBox(
                            "Dapple cannot be run over a remote connection.",
                            "Dapple Startup",
                            MessageBoxButtons.OK,
                            MessageBoxDefaultButton.Button1,
                            MessageBoxIcon.Error);
                        return;
                    }

                    Process instance = RunningInstance();

                    if (instance == null)
                    {
                        try
                        {
                            MainForm oForm = new MainForm(strView, strGeoTiff, strGeoTiffName, bGeotiffTmp, strKMLFile, strKMLName, blKMLTmp, strLastView, eClientType, oRemoteInterface, oAoi, strAoiCoordinateSystem, strMapFileName);
                            oForm.SetSelectPersonalDAPOnStartup(blSelectPersonalDAP);
                            Application.Run(oForm);
                        }
                        catch (Microsoft.DirectX.DirectXException)
                        {
                            if (g_blTestingMode == true)
                            {
                                throw;
                            }
                            else
                            {
                                ShowMessageBox(
                                    "Dapple was unable to locate a compatible graphics adapter. Make sure you are running the latest version of DirectX.",
                                    "Dapple Startup",
                                    MessageBoxButtons.OK,
                                    MessageBoxDefaultButton.Button1,
                                    MessageBoxIcon.Error);
                                return;
                            }
                        }
                        catch (System.Runtime.Remoting.RemotingException)
                        {
                            if (g_blTestingMode == true)
                            {
                                throw;
                            }
                            else
                            {
                                ShowMessageBox(
                                    "Dapple has experienced an error attempting to connect to " + EnumUtils.GetDescription(eClientType) + ". Restarting the application or your computer may fix this problem.",
                                    "Dapple Startup",
                                    MessageBoxButtons.OK,
                                    MessageBoxDefaultButton.Button1,
                                    MessageBoxIcon.Error);
                            }
                        }
                        catch (System.ComponentModel.Win32Exception)
                        {
                            if (g_blTestingMode == true)
                            {
                                throw;
                            }
                            else
                            {
                                ShowMessageBox(
                                    "Dapple has encountered an internal Win32 error during startup." + Environment.NewLine +
                                    "If this error persists, and you have a Logitech webcam installed, you may be able to resolve the error" + Environment.NewLine +
                                    "by disabling the 'Process Monitor' and 'LvSrvLauncher' services on your computer.",
                                    "Dapple Startup",
                                    MessageBoxButtons.OK,
                                    MessageBoxDefaultButton.Button1,
                                    MessageBoxIcon.Error);
                            }
                        }
                    }
                    else
                    {
                        HandleRunningInstance(instance);
                        if (strView.Length > 0 || strGeoTiff.Length > 0 || (strKMLName.Length > 0 && strKMLFile.Length > 0))
                        {
                            try
                            {
                                using (Segment s = new Segment("Dapple.OpenView", SharedMemoryCreationFlag.Create, 10000))
                                {
                                    string[] strData = new string[8];
                                    strData[0] = strView;
                                    strData[1] = strGeoTiff;
                                    strData[2] = strGeoTiffName;
                                    strData[3] = bGeotiffTmp ? "YES" : "NO";
                                    strData[4] = strLastView;
                                    strData[5] = blKMLTmp ? "YES" : "NO";
                                    strData[6] = strKMLName;
                                    strData[7] = strKMLFile;

                                    s.SetData(strData);
                                    SendMessage(instance.MainWindowHandle, MainForm.OpenViewMessage, IntPtr.Zero, IntPtr.Zero);
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
#if !DEBUG
            catch (Exception caught)
            {
                if (g_blTestingMode)
                {
                    throw;
                }
                else
                {
                    if (!aborting)
                    {
                        Utility.AbortUtility.Abort(caught, Thread.CurrentThread);
                    }
                }
            }
#endif
            finally
            {
                if (oRemoteInterface != null)
                {
                    try
                    {
                        oRemoteInterface.EndConnection();
                    }
                    catch (System.Runtime.Remoting.RemotingException) { }                     // Ignore these, they most likely mean that OM was closed before Dapple was.
                }
                if (oClientChannel != null)
                {
                    try
                    {
                        ChannelServices.UnregisterChannel(oClientChannel);
                    }
                    catch (System.Runtime.Remoting.RemotingException) { }                     // Ignore these, they most likely mean that OM was closed before Dapple was.
                }
            }
        }
Exemplo n.º 15
0
        static int Main()
        {
            // get application GUID as defined in AssemblyInfo.cs
            var appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

            // unique id for global mutex - Global prefix means it is global to the machine
            var mutexId = string.Format("Global\\{{{0}}}", appGuid);

            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);

            var securitySettings = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);

            // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
            var mutex = new Mutex(false, mutexId, out bool createdNew, securitySettings);

            if (!createdNew)
            {
                var setVals = ParseRegValues();

                if (!setVals)
                {
                    return(0);
                }


                // Create the channel.
                IpcChannel channel = new IpcChannel();

                // Register the channel.
                ChannelServices.RegisterChannel(channel, false);

                // Register as client for remote object.
                WellKnownClientTypeEntry remoteType = new WellKnownClientTypeEntry(typeof(VarSetter), "ipc://localhost:1337/SRUserInfo.rem");

                RemotingConfiguration.RegisterWellKnownClientType(remoteType);

                // Create a message sink.
                IMessageSink messageSink = channel.CreateMessageSink("ipc://localhost:1337/SRUserInfo.rem", null, out string objectUri);

                // Create an instance of the remote object.
                VarSetter service = new VarSetter();

                service.setVars(UserName, ExerciseId);

                return(0);
            }


            var hasHandle = false;

            try
            {
                try
                {
                    hasHandle = mutex.WaitOne(5000, false);
                    if (hasHandle == false)
                    {
                        throw new TimeoutException();
                    }
                }
                catch (AbandonedMutexException)
                {
                    // the mutex was abandoned in another process,
                    // it will still get acquired
                    hasHandle = true;
                }

                var setVals = ParseRegValues();

                if (!setVals)
                {
                    return(0);
                }

                OpenIPCAsync();

                Run();
            }
            finally
            {
                if (hasHandle)
                {
                    mutex.ReleaseMutex();
                    mutex.Dispose();
                }
            }

            return(0);
        }
Exemplo n.º 16
0
        internal static IpcChannel IpcCreateServer <TRemoteObject>(
            ref String RefChannelName,
            WellKnownObjectMode InObjectMode,
            TRemoteObject ipcInterface,
            params WellKnownSidType[] InAllowedClientSIDs) where TRemoteObject : MarshalByRefObject
        {
            String ChannelName = RefChannelName ?? GenerateName();

            ///////////////////////////////////////////////////////////////////
            // create security descriptor for IpcChannel...
            System.Collections.IDictionary Properties = new System.Collections.Hashtable();

            Properties["name"]     = ChannelName;
            Properties["portName"] = ChannelName;

            DiscretionaryAcl DACL = new DiscretionaryAcl(false, false, 1);

            if (InAllowedClientSIDs.Length == 0)
            {
                if (RefChannelName != null)
                {
                    throw new System.Security.HostProtectionException("If no random channel name is being used, you shall specify all allowed SIDs.");
                }

                // allow access from all users... Channel is protected by random path name!
                DACL.AddAccess(
                    AccessControlType.Allow,
                    new SecurityIdentifier(
                        WellKnownSidType.WorldSid,
                        null),
                    -1,
                    InheritanceFlags.None,
                    PropagationFlags.None);
            }
            else
            {
                for (int i = 0; i < InAllowedClientSIDs.Length; i++)
                {
                    DACL.AddAccess(
                        AccessControlType.Allow,
                        new SecurityIdentifier(
                            InAllowedClientSIDs[i],
                            null),
                        -1,
                        InheritanceFlags.None,
                        PropagationFlags.None);
                }
            }

            CommonSecurityDescriptor SecDescr = new CommonSecurityDescriptor(false, false,
                                                                             ControlFlags.GroupDefaulted |
                                                                             ControlFlags.OwnerDefaulted |
                                                                             ControlFlags.DiscretionaryAclPresent,
                                                                             null, null, null,
                                                                             DACL);

            //////////////////////////////////////////////////////////
            // create IpcChannel...
            BinaryClientFormatterSinkProvider BinaryClient = new BinaryClientFormatterSinkProvider();
            BinaryServerFormatterSinkProvider BinaryProv   = new BinaryServerFormatterSinkProvider();

            BinaryProv.TypeFilterLevel = TypeFilterLevel.Full;

            IpcChannel Result = new IpcChannel(Properties, BinaryClient, BinaryProv);

            ChannelServices.RegisterChannel(Result, false);

            if (ipcInterface == null)
            {
                RemotingConfiguration.RegisterWellKnownServiceType(
                    typeof(TRemoteObject),
                    ChannelName,
                    InObjectMode);
            }
            else
            {
                RemotingServices.Marshal(ipcInterface, ChannelName);
            }

            RefChannelName = ChannelName;

            return(Result);
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            Console.WriteLine(
            "Note: This example assumes the user has made his or her default HLAE Launcher"
            +" settings already (path to game etc.) and that the game has not been launched yet."
            );
            Console.WriteLine( "Launch \"hlae.exe -ipcremote\" and press [ENTER] to continue" );
            Console.ReadLine();

            IpcChannel channel = new IpcChannel();
            ChannelServices.RegisterChannel(channel, false);

            // Instead of creating a new object, this obtains a reference
            // to the server's single instance of the ServiceClass object:
            hlae.remoting.IHlaeRemote_1 myremote = (hlae.remoting.IHlaeRemote_1)Activator.GetObject(
            typeof(hlae.remoting.IHlaeRemote_1),
            "ipc://localhost:31337/Hlae.Remote.1"
            );

            try
            {
            // check if the interface is current or if it is deprecated (will be removed or replaced soon):
            if(myremote.IsDeprecated())
            {
                Console.WriteLine("WARNING: This program uses a deprecated interface, please tell the author to update to the new interface version.");
            }

            // get the users customargs:
            String customArgs = myremote.GetCustomArgs();

            Console.WriteLine("Users current CustomArgs are: {0}", customArgs);

            // Let's append s.th. to the user's custormargs:
            // For this example we will append s.th. that we'll be able to read in the console later.
            // Please note: some HLAE hooks might not yet be in place when those commands get executed!
            customArgs += " +echo HelloWorldFromRemoting";

            Console.WriteLine( "Launching with overriden new CustomArgs: {0}", customArgs);

            // Launche the game:
            if(!myremote.LaunchEx(customArgs))
            {
                Console.WriteLine("ERROR: HLAE Failed launching.");
            } else {
                Console.WriteLine("HLAE didn't report any problem when launching.");
            }

            }
            catch (Exception ex)
            {
            Console.WriteLine( String.Format("Exception of type: {0} occurred.", ex.ToString()) );
            Console.WriteLine( "Details: {0}", ex.Message );
            }
        }
Exemplo n.º 18
0
        public void MainFunc()
        {
            // Создаём каналы
            IpcChannel channel1 = new IpcChannel();
            IpcChannel channel2 = new IpcChannel();
            IpcChannel channel3 = new IpcChannel();
            IpcChannel channel4 = new IpcChannel();
            IpcChannel channel5 = new IpcChannel();

            // Регистрируем канал.
            System.Runtime.Remoting.Channels.ChannelServices.
            RegisterChannel(channel1, false);


            // Регистрируем клиентские удалённые обьекты.
            System.Runtime.Remoting.WellKnownClientTypeEntry remoteType1 =
                new System.Runtime.Remoting.WellKnownClientTypeEntry(
                    typeof(ClassLibrary1.Class1),
                    "ipc://localhost:9090/RemoteObject1.rem");

            System.Runtime.Remoting.WellKnownClientTypeEntry remoteType2 =
                new System.Runtime.Remoting.WellKnownClientTypeEntry(
                    typeof(ClassLibrary2.Class2),
                    "ipc://localhost:9090/RemoteObject2.rem");

            System.Runtime.Remoting.WellKnownClientTypeEntry remoteType3 =
                new System.Runtime.Remoting.WellKnownClientTypeEntry(
                    typeof(ClassLibrary3.Class3),
                    "ipc://localhost:9090/RemoteObject3.rem");

            System.Runtime.Remoting.WellKnownClientTypeEntry remoteType4 =
                new System.Runtime.Remoting.WellKnownClientTypeEntry(
                    typeof(ClassLibrary4.Class4),
                    "ipc://localhost:9090/RemoteObject4.rem");

            System.Runtime.Remoting.WellKnownClientTypeEntry remoteType5 =
                new System.Runtime.Remoting.WellKnownClientTypeEntry(
                    typeof(ClassLibrary5.Class5),
                    "ipc://localhost:9090/RemoteObject5.rem");

            System.Runtime.Remoting.RemotingConfiguration.
            RegisterWellKnownClientType(remoteType1);
            System.Runtime.Remoting.RemotingConfiguration.
            RegisterWellKnownClientType(remoteType2);
            System.Runtime.Remoting.RemotingConfiguration.
            RegisterWellKnownClientType(remoteType3);
            System.Runtime.Remoting.RemotingConfiguration.
            RegisterWellKnownClientType(remoteType4);
            System.Runtime.Remoting.RemotingConfiguration.
            RegisterWellKnownClientType(remoteType5);

            // Создаём приемники сообщений
            string objectUri;

            System.Runtime.Remoting.Messaging.IMessageSink messageSink1 =
                channel1.CreateMessageSink(
                    "ipc://localhost:9090/RemoteObject1.rem", null,
                    out objectUri);
            System.Runtime.Remoting.Messaging.IMessageSink messageSink2 =
                channel2.CreateMessageSink(
                    "ipc://localhost:9090/RemoteObject2.rem", null,
                    out objectUri);
            System.Runtime.Remoting.Messaging.IMessageSink messageSink3 =
                channel3.CreateMessageSink(
                    "ipc://localhost:9090/RemoteObject3.rem", null,
                    out objectUri);
            System.Runtime.Remoting.Messaging.IMessageSink messageSink4 =
                channel4.CreateMessageSink(
                    "ipc://localhost:9090/RemoteObject4.rem", null,
                    out objectUri);
            System.Runtime.Remoting.Messaging.IMessageSink messageSink5 =
                channel5.CreateMessageSink(
                    "ipc://localhost:9090/RemoteObject5.rem", null,
                    out objectUri);

            // Создание экземпляра удаленного объекта
            service1 = new ClassLibrary1.Class1();
            service2 = new ClassLibrary2.Class2();
            service3 = new ClassLibrary3.Class3();
            service4 = new ClassLibrary4.Class4();
            service5 = new ClassLibrary5.Class5();

            return;
        }
Exemplo n.º 19
0
 void ExposeFirstInstance()
 {
     RemotingServices.Marshal(FirstInstance, RemotingObjectName);
     RemotingChannel = new IpcChannel(Identifier);
     ChannelServices.RegisterChannel(RemotingChannel, false);
 }
Exemplo n.º 20
0
    public static void Main(string[] args)
    {
        // 引数が2つ必要。1番目のIPで、2番目がnodeに引き渡す.jsのファイル名
        if (args.Length < 3)
        {
            return;
        }

        // 常駐秀丸以外が何も起動していなければ、何もしない。(hideの秀丸も起動しているものとする)
        if (!HidemaruWindowInfo.IsFindWindow())
        {
            return;
        }

        try
        {
            // 1番めの引数にはIPが入っている50000~65535の範囲あたりを想定
            int IP = int.Parse(args[0]);

            bool bShowWindow = int.Parse(args[2]) > 0; // 1ならtrue, 0ならfalse

            // IPCサーバーチャンネルの生成.
            serverChannel = new IpcChannel("localhost:" + IP);

            // リモート用として、サーバーチャンネルを登録
            System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(serverChannel, false);

            // チャンネル名の表示.
            Console.WriteLine("チャンネルの名前は {0}.",
                              serverChannel.ChannelName);

            // チャンネルの優先度.
            Console.WriteLine("チャンネルの優先度は {0}.", serverChannel.ChannelPriority);

            // 該当のチャンネルデータの取得.
            System.Runtime.Remoting.Channels.ChannelDataStore channelData = (System.Runtime.Remoting.Channels.ChannelDataStore)serverChannel.ChannelData;
            // チャンネルの場所表示
            foreach (string uri in channelData.ChannelUris)
            {
                Console.WriteLine("チャンネルのURIは {0}.", uri);
            }

            // リモート呼び出しのため、オブジェクトを登録し、公開。サーバータイプ。シングルトン。
            System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(HmNodeRemoteObject), HmNodeRemoteObject.Name + IP + ".rem",
                System.Runtime.Remoting.WellKnownObjectMode.Singleton
                );

            // チャンネルの URI を分析.
            string[] urls = serverChannel.GetUrlsForUri(HmNodeRemoteObject.Name + IP + ".rem");
            if (urls.Length > 0)
            {
                string objectUrl = urls[0];
                string objectUri;
                string channelUri = serverChannel.Parse(objectUrl, out objectUri);
                Console.WriteLine("オブジェクトの URI は {0}.", objectUri);
                Console.WriteLine("チェンネルの URI は {0}.", channelUri);
                Console.WriteLine("オブジェクトの URL は {0}.", objectUrl);
            }

            // ユーザーの入力待ち
            // Console.WriteLine("サーバー終了には、リターンキーを入力");


            // Node.JSを、ファイル名やIPを指定して起動
            ProcessNodeJS.Start(args[1], IP, bShowWindow);

            // ShowDialogにすることで、一種モーダルとする。(常駐秀丸以外の)秀丸が無ければ、Close()してくる。
            // 外アプリからClose()した時に、正当な処理が行われるように(nodeもCloseできるように)、Formにしている。
            var f = new HmNodeProxyForm(IP, bShowWindow);
            f.ShowDialog();

            // Node.JSの終了
            ProcessNodeJS.Close();

            // チャンネルの解除
            System.Runtime.Remoting.Channels.ChannelServices.UnregisterChannel(serverChannel);

            HmNodeIPCServerListManager.UpdateProcessMap();

            // Console.WriteLine("サーバーを終了します。");
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message + "ううう");
        }
    }
Exemplo n.º 21
0
        static void Main()
#endif
        {
			string[] arguments = Environment.GetCommandLineArgs();
			string openHistory = arguments.FirstOrDefault((string s) => s.StartsWith("/openHistory:", StringComparison.CurrentCulture));
			string openBookmarks = arguments.FirstOrDefault((string s) => s.StartsWith("/openBookmarks:", StringComparison.CurrentCulture));
			Guid historyGuid = Guid.Empty;
			Guid[] bookmarkGuids = null;

			// If a history GUID was passed in on the command line
			if (openHistory != null)
			{
				historyGuid = new Guid(openHistory.Substring(openHistory.IndexOf(":", StringComparison.Ordinal) + 1));

				List<Process> existingProcesses = new List<Process>(Process.GetProcessesByName("EasyConnect"));

				if (existingProcesses.Count == 0)
					existingProcesses.AddRange(Process.GetProcessesByName("EasyConnect.vshost"));

				// If a process is already open, call the method in its IPC channel to tell it to open the given history entry and then exit this process
				if (existingProcesses.Count > 1)
				{
					IpcChannel ipcChannel = new IpcChannel("EasyConnectClient");
					ChannelServices.RegisterChannel(ipcChannel, false);

					HistoryMethods historyMethods = (HistoryMethods) Activator.GetObject(typeof (HistoryMethods), "ipc://EasyConnect/HistoryMethods");
					historyMethods.OpenToHistoryGuid(historyGuid);

					return;
				}
			}

				// If the user is trying to open bookmarks via the command line
			else if (openBookmarks != null)
			{
				string bookmarks = openBookmarks.Substring(openBookmarks.IndexOf(":", StringComparison.Ordinal) + 1);
				bookmarkGuids = (from bookmark in bookmarks.Split(',')
				                 where !String.IsNullOrEmpty(bookmark)
				                 select new Guid(bookmark)).ToArray();
			}

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

            bool encryptionSetup = false;

#if !APPX
            Task.Run(async () =>
            {
#endif
                await Options.Init();
                encryptionSetup = await SetupEncryption();
#if !APPX
            }).Wait();
#endif

            if (!encryptionSetup)
            {
                return;
            }

            MainForm mainForm = new MainForm(bookmarkGuids)
            {
                OpenToHistory = historyGuid
            };

            TitleBarTabsApplicationContext applicationContext = new TitleBarTabsApplicationContext();
            applicationContext.Start(mainForm);

            Application.Run(applicationContext);
		}
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            try
            {
                bool              secure        = false;
                int               port          = 12345;
                string            ipc           = string.Empty;
                bool              bind_any      = false;
                bool              showhelp      = false;
                TypeFilterLevel   typefilter    = TypeFilterLevel.Low;
                CustomErrorsModes custom_errors = CustomErrorsModes.Off;
                string            name          = "RemotingServer";
                bool              disable_transparent_proxy_fix = false;

                OptionSet p = new OptionSet()
                {
                    { "s|secure", "Enable secure mode", v => secure = v != null },
                    { "p|port=", "Specify the local TCP port to listen on", v => port = int.Parse(v) },
                    { "t|typefilter=", "Specify the type filter level (low,full), default low",
                      v => typefilter = (TypeFilterLevel)Enum.Parse(typeof(TypeFilterLevel), v, true) },
                    { "i|ipc=", "Specify listening pipe name for IPC channel", v => ipc = v },
                    { "e|error=", "Set custom error mode (On, Off, RemoteOnly) (don't show full errors in remote calls)",
                      v => custom_errors = (CustomErrorsModes)Enum.Parse(typeof(CustomErrorsModes), v, true) },
                    { "n|name=", "Set the remoting class name", v => name = v },
                    { "d", "Enable the 'AllowTransparentProxyMessage' setting fix.", v => disable_transparent_proxy_fix = v != null },
                    { "a|any", "When using TCP bind to any interface, otherwise only to localhost", v => bind_any = v != null },
                    { "h|?|help", v => showhelp = v != null },
                };

                Console.WriteLine("Example .NET Remoting Server");
                Console.WriteLine("Copyright (c) James Forshaw 2014");
                Console.WriteLine(".NET Version: {0}", Environment.Version);
                p.Parse(args);
                if (showhelp)
                {
                    p.WriteOptionDescriptions(Console.Out);
                }
                else
                {
                    SetAllowTransparentProxy(!disable_transparent_proxy_fix);
                    RemotingConfiguration.CustomErrorsMode = custom_errors;

                    Console.WriteLine("Enable Transparent Proxy Fix: {0}", disable_transparent_proxy_fix);
                    Console.WriteLine("Custom Errors Mode: {0}", custom_errors);
                    Console.WriteLine("Type Filter Level: {0}", typefilter);

                    Trace.Listeners.Add(new ConsoleTraceListener(true));

                    IChannel    chan;
                    IDictionary properties = new Hashtable();

                    BinaryServerFormatterSinkProvider serverSinkProvider = new BinaryServerFormatterSinkProvider();
                    serverSinkProvider.TypeFilterLevel = typefilter;

                    if (!string.IsNullOrEmpty(ipc))
                    {
                        properties["portName"]        = ipc;
                        properties["authorizedGroup"] = "Everyone";

                        chan = new IpcChannel(properties, new BinaryClientFormatterSinkProvider(), serverSinkProvider);
                    }
                    else
                    {
                        Console.WriteLine("Any Bind: {0}", bind_any);
                        properties["port"] = port;
                        properties["rejectRemoteRequests"] = !bind_any;
                        chan = new TcpChannel(properties, new BinaryClientFormatterSinkProvider(), serverSinkProvider);
                    }

                    ChannelServices.RegisterChannel(chan, secure);    //register channel

                    RemotingConfiguration.RegisterWellKnownServiceType(
                        typeof(RemoteType),
                        name,
                        WellKnownObjectMode.Singleton);

                    bool isipc = chan is IpcChannel;

                    Console.WriteLine("Server Activated at {0}://{1}/{2}", isipc ? "ipc" : "tcp", isipc ? ipc : "HOST:" + port.ToString(), name);
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 23
0
        private void ProcessMonitorThread()
        {
            Process process = null;

            while (true)
            {
                if (process == null)
                {
                    // looking for process
                    process = Common.FindProcess(System.IO.Path.GetFileNameWithoutExtension(processExeFullPath), processExeFullPath);

                    if (process != null)
                    {
                        Interface.LaunchedProcessFound();

                        // set process priority
                        if (!UseHlae && Config.Settings.GameProcessPriority != ProcessPriorityClass.Normal)
                        {
                            process.PriorityClass = Config.Settings.GameProcessPriority;
                        }

                        if (UseHlae)
                        {
                            // open IPC channel
                            IpcChannel channel = new IpcChannel();
                            ChannelServices.RegisterChannel(channel, true);

                            try
                            {
                                IHlaeRemote_1 remote = (IHlaeRemote_1)Activator.GetObject(typeof(IHlaeRemote_1), "ipc://localhost:31337/Hlae.Remote.1");

                                // bleh
                                Boolean connected = false;
                                Int32   attempts  = 0;

                                do
                                {
                                    try
                                    {
                                        connected = true;
                                        remote.GetCustomArgs();
                                    }
                                    catch (RemotingException)
                                    {
                                        connected = false;
                                        attempts++;
                                        Thread.Sleep(50);
                                    }
                                }while (!connected && attempts < 10);

                                if (!connected)
                                {
                                    MessageBox.Show("Failed to communicate with the HLAE process remotely. You must manually launch the game and enter the command \"exec coldemoplayer.cfg\" in the console.", Config.ProgramName);
                                }
                                else
                                {
                                    if (remote.IsDeprecated())
                                    {
                                        MessageBox.Show("Warning: HLAE interface depreciated.");
                                    }

                                    try
                                    {
                                        remote.LaunchEx(remote.GetCustomArgs() + launchParameters);
                                    }
                                    catch (Exception e)
                                    {
                                        MessageBox.Show("Warning: " + e.Message, "IPC error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                                    }
                                }
                            }
                            finally
                            {
                                ChannelServices.UnregisterChannel(channel);
                            }
                        }
                    }
                }
                else
                {
                    // found process, waiting for it to close
                    if (process.HasExited)
                    {
                        Interface.LaunchedProcessClosed();
                        return;
                    }
                }

                Thread.Sleep(250);
            }
        }
Exemplo n.º 24
0
 public IPCClient(string serverURL)
 {
     _serverUrl = "ipc://" + serverURL + '/';
     _ipcClient = new IpcChannel();
     ChannelServices.RegisterChannel(_ipcClient, true);
 }
Exemplo n.º 25
0
        /// <summary>Runs <see cref="action"/> with administrator privileges, requesting them by UAC if necessary.</summary>
        /// <param name="action">Action to execute.</param>
        public static void ExecuteWithAdministartorRights(Action action)
        {
            Verify.Argument.IsNotNull(action, "action");

            if (Utility.IsRunningWithAdministratorRights)
            {
                action();
            }
            else
            {
                const int    waitTime            = 50;
                const string RemotingChannelName = "gitter.UAC";
                const string RemotingObjectName  = "RemoteExecutor.rem";

                var ipc = new IpcChannel("RemoteExecutorClient");
                ChannelServices.RegisterChannel(ipc, false);
                try
                {
                    var     path = Path.Combine(Path.GetDirectoryName(typeof(Utility).Assembly.Location), "gitter.uac.exe");
                    Process administratorProcess;
                    bool    allowWaitForExit = false;
                    using (administratorProcess = new Process()
                    {
                        StartInfo = new ProcessStartInfo(path, "--remoting")
                        {
                            CreateNoWindow = true,
                        },
                    })
                    {
                        administratorProcess.Start();
                        try
                        {
                            IRemoteProcedureExecutor executor = null;
                            while (!administratorProcess.HasExited)
                            {
                                System.Threading.Thread.Sleep(waitTime);
                                try
                                {
                                    executor = (IRemoteProcedureExecutor)Activator.GetObject(typeof(IRemoteProcedureExecutor),
                                                                                             string.Format(@"ipc://{0}/{1}", RemotingChannelName, RemotingObjectName));
                                }
                                catch (Exception exc)
                                {
                                    if (exc.IsCritical())
                                    {
                                        throw;
                                    }
                                }
                                if (executor != null)
                                {
                                    break;
                                }
                            }
                            if (executor != null)
                            {
                                while (!administratorProcess.HasExited)
                                {
                                    try
                                    {
                                        executor.Execute(action);
                                        break;
                                    }
                                    catch (RemotingException)
                                    {
                                        System.Threading.Thread.Sleep(waitTime);
                                    }
                                }
                                if (!administratorProcess.HasExited)
                                {
                                    try
                                    {
                                        executor.Close();
                                        allowWaitForExit = true;
                                    }
                                    catch (Exception exc)
                                    {
                                        if (exc.IsCritical())
                                        {
                                            throw;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                throw new Exception();
                            }
                        }
                        finally
                        {
                            try
                            {
                                if (allowWaitForExit)
                                {
                                    if (!administratorProcess.WaitForExit(750))
                                    {
                                        administratorProcess.Kill();
                                    }
                                }
                                else
                                {
                                    administratorProcess.Kill();
                                }
                            }
                            catch (Exception exc)
                            {
                                if (exc.IsCritical())
                                {
                                    throw;
                                }
                            }
                        }
                    }
                }
                finally
                {
                    ChannelServices.UnregisterChannel(ipc);
                }
            }
        }
Exemplo n.º 26
0
        static int Main()
        {
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                Log.Line();
                Log.ErrorLine("Host assembly crashed: {0}", e.ExceptionObject);
                Console.ReadLine();
            };

            var asm     = Assembly.GetExecutingAssembly();
            var asmName = asm.GetName();
            var name    = $"{asmName.Name} {asmName.Version}";

            Console.Title = $"{name} - Host Process";

            Log.InfoLine("{0} initializing...", name);

            var path = GetExecutablePath();

            if (path == null)
            {
                Log.ErrorLine("Could not find Hellgate: London executable.");
                return(1);
            }

            var chanName = IpcChannel.Create();

            Log.InfoLine("Setting up IPC channel '{0}'...", chanName);

            var chan = IpcChannel.Connect(chanName);

            chan.Ping();

            Log.InfoLine("Launching '{0}'...", path);

            var location = asm.Location;

            RemoteHooking.CreateAndInject(path, Configuration.Instance.GameArguments, 0, location, location, out var pid, chanName);

            using var proc = Process.GetProcesses().FirstOrDefault(x => x.Id == pid);

            if (proc == null)
            {
                Log.ErrorLine("Could not locate Hellgate: London process ({0}).", pid);
                return(1);
            }

            while (chan.Wait(Configuration.Instance.IpcTimeout))
            {
                if (chan.ExitCode is int c)
                {
                    Log.SuccessLine("Exiting...");

                    if (chan.KillRequested)
                    {
                        proc.Kill();
                    }

                    return(c);
                }

                chan.Reset();
            }

            Log.Line();
            Log.ErrorLine("Lost connection to the game. Exiting...");
            Console.ReadLine();

            return(1);
        }
Exemplo n.º 27
0
    static void IpcServerLoop()
    {
        var     ipc            = new IpcChannel(Process.GetCurrentProcess().Id);
        Process currentProcess = Process.GetCurrentProcess();

        while (true)
        {
            String scriptToMonitor = "";

            for (int iRetry = 0; iRetry < 100; iRetry++)
            {
                bool b = ipc.Receive(ref scriptToMonitor, Timeout.Infinite);

                if (!b)
                {
                    continue;
                }

                break;
            }

            if (scriptToMonitor == "")
            {
                Console.WriteLine("Error: Too many failures, shutdowning...");
                break;
            }

            if (!File.Exists(scriptToMonitor))
            {
                Console.WriteLine("Error: File does not exists: " + scriptToMonitor);
                continue;
            }

            if (scriptsToMonitor.Contains(scriptToMonitor))
            {
                continue;
            }


            List <String> dirs = new List <string>();
            foreach (String script in scriptsToMonitor)
            {
                String dir = Path.GetDirectoryName(script);
                if (!dirs.Contains(dir))
                {
                    dirs.Add(dir);
                }
            }

            scriptsToMonitor.Add(scriptToMonitor);

            String newDir = Path.GetDirectoryName(scriptToMonitor);
            if (!dirs.Contains(newDir))
            {
                FileSystemWatcher watcher = new FileSystemWatcher();
                watcher.Path         = newDir;
                watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                watcher.Filter       = "*.cs";
                watcher.Changed     += FileChanged;
                watcher.Created     += FileChanged;
                watcher.Renamed     += FileChanged;
                // Begin watching.
                watcher.EnableRaisingEvents = true;
                DebugPrint("- Monitoring for folder '" + newDir + "'");
                fswatchers.Add(watcher);
            }

            FileReload(scriptToMonitor);
        } //while
    }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            if (args.Length < 1) //引数がないのは丘peopleなので...
            {
                Console.Error.WriteLine("Error!");
                return;
            }
            string[] argskun = args[0].Split('|');                                           //argsを分割。
            yukkuri_lib_interface.yukkuri_lib_interface yukkuri_inter;                       //インタフェースを作成。
            Dictionary <string, string> channelproperty = new Dictionary <string, string>(); //チャンネル作成用。

            channelproperty.Add("portName", argskun[1] + "_yukkuri_lib_kokkiemouse_client_" + argskun[0]);
            channelproperty.Add("name", argskun[0]);
            IpcChannel servChannel = new IpcChannel(channelproperty, null, new BinaryServerFormatterSinkProvider //チャンネル作成。
            {
                TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full,
            });

            ChannelServices.RegisterChannel(servChannel, true);                                                                                                                      //チャンネル登録。
            yukkuri_inter = Activator.GetObject(typeof(yukkuri_lib_interface.yukkuri_lib_interface),
                                                "ipc://" + argskun[1] + "_yukkuri_lib_kokkiemouse_" + argskun[0] + '/' + argskun[0]) as yukkuri_lib_interface.yukkuri_lib_interface; //サーバー(64bit)のインタフェースを取得。
            AquesTalk      aq    = new AquesTalk();                                                                                                                                  //Aquestalkのクラスを取得。
            CountdownEvent cekun = new CountdownEvent(1);                                                                                                                            //待機用。

            yukkuri_lib_interface.EventCallbackSink ebthink = new EventCallbackSink();                                                                                               //コールバック関数
            ebthink.OnClose += new CloseDelegate(() =>                                                                                                                               //Oncloseで呼ばれる。
            {
                cekun.Signal();                                                                                                                                                      //復帰。(終了)
            });
            ebthink.OnSpeak += new yukkuri_lib_interface.SpeakDelegate((yukkuri_lib_interface_EventArgs yukkuargs) =>                                                                //OnSpeakを定義
            {
                int speed     = yukkuargs.eventargs.speed;                                                                                                                           //speedを突っ込む。
                int size      = 0;                                                                                                                                                   //サイズが入る。
                string koe    = yukkuargs.eventargs.textdata;                                                                                                                        //コピー。
                IntPtr wavPtr = aq.AquesTalk_Synthe(koe, speed, out size);                                                                                                           //Aquestalk呼び出し。ポインタが返ってくる。
                if (wavPtr == IntPtr.Zero)                                                                                                                                           //ぬるぽなら
                {
                    SPEAK_RETURN spr2 = new SPEAK_RETURN();
                    switch (size)
                    {
                    case 100:
                        spr2.error.err_code = DLL_ERR_CODE.OTHER_ERROR;
                        spr2.error.message  = "Other error!";
                        break;

                    case 101:
                        spr2.error.err_code = DLL_ERR_CODE.out_of_memory;
                        spr2.error.message  = "OUT OF MEMORY!";
                        break;

                    case 102:
                        spr2.error.err_code = DLL_ERR_CODE.undefined_symbol;
                        spr2.error.message  = "UNDEFINED_SYMBOL";
                        break;

                    case 103:
                        spr2.error.err_code = DLL_ERR_CODE.minus_speed;
                        spr2.error.message  = "ERROR! SPEED is MINUS!";
                        break;

                    case 104:
                        spr2.error.err_code = DLL_ERR_CODE.Undefined_delimiter_code_detection;
                        spr2.error.message  = "Undefined delimiter code detection!";
                        break;

                    case 105:
                        spr2.error.err_code = DLL_ERR_CODE.undefined_symbol;
                        spr2.error.message  = "UNDEFINED_SYMBOL";
                        break;

                    case 106:
                        spr2.error.err_code = DLL_ERR_CODE.syntax_tag_error;
                        spr2.error.message  = "Syntax tag error";
                        break;

                    case 107:
                        spr2.error.err_code = DLL_ERR_CODE.tag_end_error;
                        spr2.error.message  = "TAG END OR '>' ERROR";
                        break;

                    case 108:
                        spr2.error.err_code = DLL_ERR_CODE.tag_value_invalid;
                        spr2.error.message  = "TAG VALUE INVALID ERROR";
                        break;

                    case 111:
                        spr2.error.err_code = DLL_ERR_CODE.text_not_found;
                        spr2.error.message  = "Text Not found";
                        break;

                    case 200:
                        spr2.error.err_code = DLL_ERR_CODE.too_long_text;
                        spr2.error.message  = "Too long text";
                        break;

                    case 201:
                        spr2.error.err_code = DLL_ERR_CODE.too_many_symbol;
                        spr2.error.message  = "Too many symbol";
                        break;

                    case 202:
                        spr2.error.err_code = DLL_ERR_CODE.too_long_text_buffer_over;
                        spr2.error.message  = "Too long text and buffer over";
                        break;

                    case 203:
                        spr2.error.err_code = DLL_ERR_CODE.out_of_heap_memory;
                        spr2.error.message  = "Out of heap memory";
                        break;

                    case 204:
                        spr2.error.err_code = DLL_ERR_CODE.too_long_text_buffer_over;
                        spr2.error.message  = "Too long text and buffer over";
                        break;

                    default:
                        spr2.error.err_code = DLL_ERR_CODE.OTHER_ERROR;
                        break;
                    }
                    return(spr2);
                }
                byte[] wavdata = new byte[size];        //C#側で配列を確保。
                Marshal.Copy(wavPtr, wavdata, 0, size); //ポインタの中身を配列にコピー。
                aq.AquesTalk_FreeWave(wavPtr);          //ポインタはもういらないしトラブルの元なので即開放
                yukkuri_lib_interface.SPEAK_RETURN spr = new yukkuri_lib_interface.SPEAK_RETURN();
                spr.error.err_code = yukkuri_lib_interface.DLL_ERR_CODE.NO_ERROR;
                spr.error.message  = "Success!";
                spr.wavdata        = wavdata;
                return(spr);//コピーした配列を返す。
            });

            /*
             * yukkuri_inter._run_speak += new yukkuri_lib_interface.yukkuri_lib_interface.CallEventHandler((ref byte[] wav, yukkuri_lib_interface.yukkuri_lib_interface.yukkuri_lib_interface_EventArgs e) =>
             * {
             *  if (!loaded) return;
             *  int speed = e.speed;
             *  int size = 0;
             *  string koe = e.textdata;
             *  IntPtr wavPtr = aq.AquesTalk_Synthe(koe, speed, out size);
             *  if(wavPtr==IntPtr.Zero )
             *  {
             *      wav= new byte[] { 0 };
             *      return;
             *  }
             *  wav = new byte[size];
             *  Marshal.Copy(wavPtr, wav, 0, size);
             *  aq.AquesTalk_FreeWave(wavPtr);
             * });
             */
            ebthink.OnDllLoad += new Dll_load_delegate((yukkuri_lib_interface_dllload_args eargs) =>  //OnDllLoadで呼ばれる。
            {
                try
                {
                    aq = new AquesTalk(eargs.dll_path); //パスをもとにAquestalkをロード。

                    yukkuri_inter.dll_loaded();         //ロード完了のイベント送信。
                }catch (IOException e)
                {
                    throw;
                }
            });
            Dll_load_delegate dllldel = new Dll_load_delegate(ebthink.DllLoadtoClient);   //delegateを定義。
            SpeakDelegate     spd     = new SpeakDelegate(ebthink.SpeakCallBackToClient); //delegateを定義。
            CloseDelegate     cld     = new CloseDelegate(ebthink.Close_toClient);        //delegateを定義。

            yukkuri_inter.AddEventListener_Dllload(dllldel);                              //delegateを突っ込む。
            yukkuri_inter.AddEventListener_Speak(spd);                                    //delegateを突っ込む。
            yukkuri_inter.AddEventListener_close(cld);                                    //delegateを突っ込む。
            TimerCallback timerdelegate = new TimerCallback((Object o) =>
            {
                try
                {
                    yukkuri_inter.discardkun();
                }catch (System.Runtime.Remoting.RemotingException e)
                {
                    cekun.Signal();
                }
            });
            Timer timer;

            yukkuri_inter.inited();//初期化完了イベントを発行。

            Task task = Task.Run(() =>
            {
                timer = new Timer(timerdelegate, null, 0, 3000);
            });

            cekun.Wait();//閉じないように。
        }
Exemplo n.º 29
0
		static void Main( string[] args )
		{
            // Read args
            ParseArgs(args);

            // Start up the GUI thread
            InitGUIThread();

			AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, "Starting up SwarmAgent ..." );
			AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent with remoting service" );

			// Register the local agent singleton
			RemotingConfiguration.RegisterWellKnownServiceType( typeof( Agent ), "SwarmAgent", WellKnownObjectMode.Singleton );

            AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent network channels" );

			// We're going to have two channels for the Agent: one for the actual Agent
			// application (IPC with infinite timeout) and one for all other remoting
			// traffic (TCP with infinite timeout that we monitor for drops)
			IpcChannel AgentIPCChannel = null;
            TcpChannel AgentTCPChannel = null;
            while( ( Ticking == true ) &&
				   ( ( AgentIPCChannel == null ) ||
				     ( AgentTCPChannel == null ) ) )
			{
				try
				{
					if( AgentIPCChannel == null )
					{
						// Register the IPC connection to the local agent
						string IPCChannelPortName = String.Format( "127.0.0.1:{0}", Properties.Settings.Default.AgentRemotingPort );
						AgentIPCChannel = new IpcChannel( IPCChannelPortName );
						ChannelServices.RegisterChannel( AgentIPCChannel, false );
					}

					if( AgentTCPChannel == null )
					{
						// Register the TCP connection to the local agent
						AgentTCPChannel = new TcpChannel( Properties.Settings.Default.AgentRemotingPort );
						ChannelServices.RegisterChannel( AgentTCPChannel, false );
					}
				}
				catch (RemotingException Ex)
				{
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Channel already registered, suggesting another SwarmAgent or client is running.");
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] If you feel this is in error, check your running process list for additional copies of");
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] SwarmAgent or UnrealLightmass (or other client) and consider killing them.");
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Sleeping for a few seconds and trying again...");
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, string.Format("[ERROR] Channel registration failed. Reason: {0}\n, Callstack: {1}.", Ex.Message, Ex.StackTrace));
					Thread.Sleep(3000);
				}
				catch (Exception Ex)
				{
					AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, string.Format("[ERROR] Channel registration failed. Reason: {0}\n, Callstack: {1}.", Ex.Message, Ex.StackTrace));
					Thread.Sleep(3000);
				}
			}

			// if we're still ticking, we should have both of our channels initialized
			if( Ticking )
			{
				Debug.Assert( AgentIPCChannel != null );
				Debug.Assert( AgentTCPChannel != null );
			}
			else
			{
				// Otherwise, we can simply return to exit
				return;
			}

			// Get the agent interface object using the IPC channel
			string LocalAgentURL = String.Format( "ipc://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString() );
			LocalAgent = ( Agent )Activator.GetObject( typeof( Agent ), LocalAgentURL );

			AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... initializing SwarmAgent" );
            
            // Init the local agent object (if this is the first call to it, it will be created now)
			bool AgentInitializedSuccessfully = false;
			try
			{
				AgentInitializedSuccessfully = LocalAgent.Init( Process.GetCurrentProcess().Id );
			}
			catch( Exception Ex )
			{
				AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with an IPC channel! Falling back to TCP..." );
				AgentApplication.Log( EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex.ToString() );

				// Try again with the TCP channel, which is slower but should work
				LocalAgentURL = String.Format( "tcp://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString() );
				LocalAgent = ( Agent )Activator.GetObject( typeof( Agent ), LocalAgentURL );

				try
				{
					AgentInitializedSuccessfully = LocalAgent.Init( Process.GetCurrentProcess().Id );
					if( AgentInitializedSuccessfully )
					{
						AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] RECOVERED by using TCP channel!" );
					}
				}
				catch( Exception Ex2 )
				{
					AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with a TCP channel! Fatal error." );
					AgentApplication.Log( EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex2.ToString() );

					ChannelServices.UnregisterChannel( AgentTCPChannel );
					ChannelServices.UnregisterChannel( AgentIPCChannel );
					return;
				}
			}

			// Only continue if we have a fully initialized agent
			if( ( LocalAgent != null ) && AgentInitializedSuccessfully )
			{
				AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... initialization successful, SwarmAgent now running" );
                
                // Loop until a quit/restart event has been requested
				while( !LocalAgent.ShuttingDown() )
				{
					try
					{
						// If we've stopped ticking, notify the agent that we want to shutdown
						if( !Ticking )
						{
							LocalAgent.RequestShutdown();
						}

						// Maintain the agent itself
						LocalAgent.MaintainAgent();

						// Maintain any running active connections
						LocalAgent.MaintainConnections();

						// Maintain the Agent's cache
						if( CacheRelocationRequested )
						{
							LocalAgent.RequestCacheRelocation();
							CacheRelocationRequested = false;
						}
						if( CacheClearRequested )
						{
							LocalAgent.RequestCacheClear();
							CacheClearRequested = false;
						}
						if( CacheValidateRequested )
						{
							LocalAgent.RequestCacheValidate();
							CacheValidateRequested = false;
						}
						LocalAgent.MaintainCache();

						// Maintain any running jobs
						LocalAgent.MaintainJobs();

						// If this is a deployed application which is configured to auto-update,
						// we'll check for any updates and, if there are any, request a restart
						// which will install them prior to restarting
#if !__MonoCS__
						if( ( AgentApplication.DeveloperOptions.UpdateAutomatically ) &&
							( ApplicationDeployment.IsNetworkDeployed ) &&
                            (DateTime.UtcNow > NextUpdateCheckTime))
						{
							if( CheckForUpdates() )
							{
								LocalAgent.RequestRestart();
							}
                            NextUpdateCheckTime = DateTime.UtcNow + TimeSpan.FromMinutes(1);
						}
#endif
					}
					catch( Exception Ex )
					{
                        AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.Message );
						AgentApplication.Log( EVerbosityLevel.ExtraVerbose, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.ToString() );
					}

					// Sleep for a little bit
					Thread.Sleep( 500 );
				}

				// Let the GUI destroy itself
				RequestQuit();
				
				bool AgentIsRestarting = LocalAgent.Restarting();

				// Do any required cleanup
				LocalAgent.Destroy();

				ChannelServices.UnregisterChannel( AgentTCPChannel );
				ChannelServices.UnregisterChannel( AgentIPCChannel );

				// Now that everything is shut down, restart if requested
				if( AgentIsRestarting )
				{
					ClearCache();
					InstallAllUpdates();
					Application.Restart();
				}
			}
		}
Exemplo n.º 30
0
            public static void StartNETRemotingHost(int int_NETRemotingChannelPort)
            {
                try
                {
                    BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider();
                    serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;

                    System.Collections.IDictionary hashTable_IpcServerChannelProperties = new System.Collections.Hashtable();

                    SecurityIdentifier securityIdentifier_obj = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

                    NTAccount nTAccount_obj = securityIdentifier_obj.Translate(typeof(NTAccount)) as NTAccount;

                    hashTable_IpcServerChannelProperties["portName"]            = "YakSys RCT Server Service IPC Port";
                    hashTable_IpcServerChannelProperties["authorizedGroup"]     = nTAccount_obj.Value;
                    hashTable_IpcServerChannelProperties["exclusiveAddressUse"] = false;


                    IpcChannel ipcServerChannel_ServerChannel = new IpcChannel(hashTable_IpcServerChannelProperties, null, serverProv);

                    ChannelServices.RegisterChannel(ipcServerChannel_ServerChannel, false);

                    RemotingConfiguration.ApplicationName = "YakSys RCT Server";


                    // Windows Vista/Windows 7 Service Desktop interact Layer-------------------------------------------------------------

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(ProcWindowService), "ClassObj_ProcWindowService_URI", WellKnownObjectMode.SingleCall);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(ProcWindowService.ApplicationStartPendingPool), "ClassObj_ProcWindowService_ApplicationStartPendingPool_URI", WellKnownObjectMode.SingleCall);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(ProcWindowService.RTDVContainer), "ClassObj_ProcWindowService_RTDVContainer_URI", WellKnownObjectMode.SingleCall);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(ProcWindowService.MessageBoxPendingPool), "ClassObj_ProcWindowService_MessageBoxPendingPool_URI", WellKnownObjectMode.SingleCall);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(ProcWindowService.ClipboardWrapper), "ClassObj_ProcWindowService_ClipboardWrapper_URI", WellKnownObjectMode.SingleCall);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(ProcWindowService.MicrophoneRecordWrapper), "ClassObj_ProcWindowService_MicrophoneRecordWrapper_URI", WellKnownObjectMode.SingleCall);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(ProcWindowService.WebCamContainer), "ClassObj_ProcWindowService_WebCamContainer_URI", WellKnownObjectMode.SingleCall);


                    // -------------------------------------------------------------------------------------------------------------------

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(ServerSettingsEnvironment), "ClassObj_ServerSettingsEnvironment_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(NetworkAction), "ClassObj_NetworkAction_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(NetworkSecurity), "ClassObj_NetworkSecurity_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(NetworkSecurity.UserAccount), "ClassObj_NetworkSecurity.UserAccount_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(NetworkSecurity.AccessRestrictionRuleObject), "ClassObj_NetworkSecurity.AccessRestrictionRuleObject_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(YakSysServerDBEnvironment), "ClassObj_YakSysServerDBEnvironment_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(YakSysServerDBEnvironment.SecurityDataBase), "ClassObj_YakSysServerDBEnvironment.SecurityDataBase_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(YakSysServerDBEnvironment.AccessRestrictionRule), "ClassObj_YakSysServerDBEnvironment.AccessRestrictionRule_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(YakSysRctServerV110XMLConfigImporter), "ClassObj_YakSysRctServerV110XMLConfigImporter_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(YakSysServerLog), "ClassObj_YakSysServerLog_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(YakSysTcpClient), "ClassObj_YakSysTcpClient_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(NetworkStatusAndStatistics), "ClassObj_NetworkStatusAndStatistics_URI", WellKnownObjectMode.Singleton);

                    RemotingConfiguration.RegisterWellKnownServiceType(typeof(YakSysTcpClient.SessionStatisticAndInfo), "ClassObj_YakSysTcpClient.SessionStatisticAndInfo_URI", WellKnownObjectMode.Singleton);
                }
                catch
                {
                    MessageBox.Show("Starting .NET Remoting Host using IPC channels failed!");
                }
            }
Exemplo n.º 31
0
        /// <summary>
        /// <see cref="yukkuri_lib"/> のコンストラクタ
        /// </summary>
        /// <param name="dll_path">使うAquestalkのDLLパス</param>
        /// <param name="application_id"> 独自のid。競合防止のため。</param>
        public yukkuri_lib(string dll_path, string application_id)
        {
            if (!File.Exists(dll_path))
            {
                throw new System.IO.FileNotFoundException("DLL Load failed! " + dll_path + " is not found!");
            }
            string           dll_name = Path.GetFileName(Path.GetDirectoryName(dll_path));                                    //dllのフォルダ名を取得。
            ProcessStartInfo psinfo   = new ProcessStartInfo();                                                               //子プロセス用。

            psinfo.FileName        = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\yukkuri_86_wrapper.exe"; //子プロセスのファイル名。
            psinfo.UseShellExecute = false;                                                                                   //シェルは使わん。
            psinfo.CreateNoWindow  = true;                                                                                    //ウィンドウも作らん。
            string dtnow = DateTime.Now.ToString("ddHHmmssfff");                                                              //現在時刻を取得

            psinfo.Arguments = dll_name + '|' + application_id + dtnow;                                                       //現在時刻をもとに作り、競合を回避。。
            System.Collections.IDictionary properties =
                new System.Collections.Hashtable();                                                                           //ハッシュテーブルを作成。
            properties["portName"]            = application_id + dtnow + "_yukkuri_lib_kokkiemouse_" + dll_name;              //ポートネーム生成。
            properties["exclusiveAddressUse"] = false;
            properties["name"] = dll_name;

            IpcChannel serverChannel = new IpcChannel(properties, null,
                                                      new BinaryServerFormatterSinkProvider
            {
                TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full,
            });                                                   //チャンネル生成。

            ChannelServices.RegisterChannel(serverChannel, true); //チャンネル登録

            /*yukkui = (yukkuri_lib_interface.yukkuri_lib_interface)Activator.GetObject(typeof(yukkuri_lib_interface.yukkuri_lib_interface),
             *  "ipc://yukkuri_lib_kokkiemouse/" + dll_name);
             */
            CountdownEvent inited_ev = new CountdownEvent(1);                   //待機用。

            yukkui         = new yukkuri_lib_interface.yukkuri_lib_interface(); //インターフェースを生成。
            yukkui.Oninit += new yukkuri_lib_interface.init_delegate(() =>      //初期化後に実行される
            {
                inited_ev.Signal();                                             //処理を再開。
            }
                                                                     );
            CountdownEvent loaded_dll_ev = new CountdownEvent(1); //dllを読み込むまでの待機用。

            yukkui.OnDllLoaded += new dll_loaded_delegate(() =>   //dllが読み込まれると実行
            {
                loaded_dll_ev.Signal();                           //処理を再開。
            });
            yukkui.Ondiscardloop += new Discard_loop(() =>
            {
                //そりゃ酢豚だからなんもしないさ。
#if DEBUG
                Debug.WriteLine("Stub Timer");
            #endif
            });
            RemotingServices.Marshal(yukkui, dll_name, typeof(yukkuri_lib_interface.yukkuri_lib_interface));    //定義したオブジェクトを登録。
            System.Runtime.Remoting.Channels.ChannelDataStore channelData =
                (System.Runtime.Remoting.Channels.ChannelDataStore)
                serverChannel.ChannelData;
            foreach (string uri in channelData.ChannelUris)
            {
                Debug.WriteLine("The channel URI is {0}.", uri); //デバッグ用。
            }
            Process.Start(psinfo);                               //子プロセス起動。
            inited_ev.Wait();                                    //初期化が完了するまで待機。
            try
            {
                yukkui.DllLoad_to_client(dll_path); //dllを読み込み。
            }catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            var letter = 'R';

            var chan = new IpcChannel(BuildFs.BuildFsApi.IpcChannelName);

            ChannelServices.RegisterChannel(chan, false);
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(BuildFsApiImpl), BuildFsApi.IpcChannelName, WellKnownObjectMode.Singleton);

            var fs = BuildFsFileSystem.Mount(letter, DokanOptions.FixedDrive);

            //fs.ForceRun = true;
            BuildFsApiImpl.Run = (location, commandLine, folder, custom) =>
            {
                try
                {
                    if (custom)
                    {
                        folder = Path.GetFullPath(folder);
                        var components = folder.SplitFast('\\', StringSplitOptions.RemoveEmptyEntries);
                        if (components[0].ToUpper() != letter + ":")
                        {
                            throw new Exception("Must be run in BuildFs drive.");
                        }

                        string exe;
                        string arguments;
                        BuildFsApi.ParseCommandLine(commandLine, out exe, out arguments);
                        commandLine = arguments;
                        BuildFsApi.ParseCommandLine(commandLine, out exe, out arguments);

                        fs.RunCached(components[1], string.Join("\\", components.Skip(2)), exe, arguments);
                    }
                    else
                    {
                        var    projname = "project";
                        var    find     = @"C:\Path\To\Project";
                        var    replace  = letter + @":\" + projname;
                        string exe;
                        string arguments;
                        folder      = folder.Replace(find, replace);
                        commandLine = commandLine.Replace(find, replace);
                        BuildFsApi.ParseCommandLine(commandLine, out exe, out arguments);

                        var realexe = Path.Combine(Path.GetDirectoryName(location), Path.GetFileNameWithoutExtension(location) + "-real.exe");
                        fs.RunCached(projname, folder, realexe, new ProcessUtils.RawCommandLineArgument(arguments));
                    }
                    Console.WriteLine("Success.");
                    return(0);
                }
                catch (ProcessException ex)
                {
                    Console.WriteLine("Failed with " + ex.ExitCode);
                    return(ex.ExitCode);
                }
            };


            //MainInternal(args, fs);


            // Example:

            //fs.AddProject(@"C:\Path\To\Project", "project");
            //fs.RunCached("project", "subdir", "nmake", "part-1");
            //fs.RunCached("project", "subdir", "nmake", "part-2");



            while (true)
            {
                Thread.Sleep(400000);
            }
        }