Exemplo n.º 1
0
        /// <summary>
        /// Starts the CommandPanel in console mode.
        ///
        /// This mode expects the OPcodes (CommandToken) directly in the console and send them synchronously to the Zerobot process.
        /// </summary>
        /// <param name="args">cmd args</param>
        private void ConsoleMode(string[] args)
        {
            using (PipeStream pipeClient =
                       new AnonymousPipeClientStream(PipeDirection.Out, args[0]))
            {
                using (StreamWriter writer = new StreamWriter(pipeClient))
                {
                    while (true)
                    {
                        Console.Write(">> ");
                        string input = Console.ReadLine();
                        if (input.Equals("exit"))
                        {
                            break;
                        }

                        try
                        {
                            var expression = new TokenExpression(input);
                            writer.WriteLine(expression.ToString());
                            writer.Flush();

                            pipeClient.WaitForPipeDrain();
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"Error parsing your command: {e.Message}");
                            continue;
                        }
                    }
                }
            }
        }
Exemplo n.º 2
0
 public static void SendMessage(object message)
 {
     //MessageBox.Show("Message sent by Everythingbar");
     _writer.WriteLine(message);
     _moduleWritePipe.WaitForPipeDrain();
     //MessageBox.Show("PIPE DRAINED");
 }
Exemplo n.º 3
0
        public static void Run(string inPipeHandle, string outPipeHandle, string timesToRunStr)
        {
            int timesToRun = Int32.Parse(timesToRunStr);

            Console.WriteLine(outPipeHandle);

            using var clientPipeOut = new AnonymousPipeClientStream(PipeDirection.Out, outPipeHandle);
            using var clientPipeIn  = new AnonymousPipeClientStream(PipeDirection.In, inPipeHandle);
            using var clientWriter  = new StreamWriter(clientPipeOut)
                  {
                      AutoFlush = true
                  };
            using var clientReader = new StreamReader(clientPipeIn);

            for (int i = 0; i < timesToRun; ++i)
            {
                var currLine = clientReader.ReadLine();

                Console.WriteLine(currLine);

                clientWriter.WriteLine(lineToSend);

                clientPipeOut.WaitForPipeDrain();

                Thread.Sleep(100);
            }
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            if (args == null || args.Length < 2)
            {
                return;
            }

            // Get read and write pipe handles
            // Note: Roles are now reversed from how the other process is passing the handles in
            string pipeWriteHandle = args[0];
            string pipeReadHandle  = args[1];

            // Create 2 anonymous pipes (read and write) for duplex communications (each pipe is one-way)
            using (var pipeRead = new AnonymousPipeClientStream(PipeDirection.In, pipeReadHandle))
                using (var pipeWrite = new AnonymousPipeClientStream(PipeDirection.Out, pipeWriteHandle))
                {
                    try
                    {
                        var values = new List <string>();

                        // Get message from other process
                        using (var sr = new StreamReader(pipeRead))
                        {
                            string temp;

                            // Wait for 'sync message' from the other process
                            do
                            {
                                temp = sr.ReadLine();
                            } while (temp == null || !temp.StartsWith("SYNC"));

                            // Read until 'end message' from the server
                            while ((temp = sr.ReadLine()) != null && !temp.StartsWith("END"))
                            {
                                values.Add(temp);
                            }
                        }

                        // Send value to calling process
                        using (var sw = new StreamWriter(pipeWrite))
                        {
                            sw.AutoFlush = true;
                            // Send a 'sync message' and wait for the calling process to receive it
                            sw.WriteLine("SYNC");
                            pipeWrite.WaitForPipeDrain();

                            sw.WriteLine("Hello from Process B!");
                            sw.WriteLine("END");
                        }
                    }
                    catch (Exception ex)
                    {
                        //TODO Exception handling/logging
                        throw;
                    }
                }
        }
 public void Dispose()
 {
     _writer.WriteLine("GOODBYE");
     if (OperatingSystem.IsWindows())
     {
         _client.WaitForPipeDrain();
     }
     _writer.Dispose();
     _client.Dispose();
 }
Exemplo n.º 6
0
        public async Task SendMessageAsync(string message)
        {
            if (clientStream != null)
            {
                using (StreamWriter sw = new StreamWriter(clientStream))
                {
                    sw.AutoFlush = true;
                    await sw.WriteLineAsync(message);

                    clientStream.WaitForPipeDrain();
                }
            }
        }
Exemplo n.º 7
0
    public static void ClientPInvokeChecks()
    {
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
        {
            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.Out, server.ClientSafePipeHandle))
            {
                Task serverTask = Task.Run(() => DoStreamOperations(server));

                Assert.False(client.CanRead);
                Assert.False(client.CanSeek);
                Assert.False(client.CanTimeout);
                Assert.True(client.CanWrite);
                Assert.False(client.IsAsync);
                Assert.True(client.IsConnected);
                Assert.Equal(0, client.OutBufferSize);
                Assert.Equal(PipeTransmissionMode.Byte, client.ReadMode);
                Assert.NotNull(client.SafePipeHandle);
                Assert.Equal(PipeTransmissionMode.Byte, client.TransmissionMode);

                client.Write(new byte[] { 123 }, 0, 1);
                client.WriteAsync(new byte[] { 124 }, 0, 1).Wait();
                client.WaitForPipeDrain();
                client.Flush();

                serverTask.Wait();
            }
        }

        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
        {
            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.In, server.ClientSafePipeHandle))
            {
                Task serverTask = Task.Run(() => DoStreamOperations(server));

                Assert.Equal(4096, client.InBufferSize);
                byte[] readData = new byte[] { 0, 1 };
                Assert.Equal(1, client.Read(readData, 0, 1));
                Assert.Equal(1, client.ReadAsync(readData, 1, 1).Result);
                Assert.Equal(123, readData[0]);
                Assert.Equal(124, readData[1]);

                serverTask.Wait();
            }
        }
    }
Exemplo n.º 8
0
    public static void ClientPInvokeChecks()
    {
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
        {
            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.Out, server.ClientSafePipeHandle))
            {
                Task serverTask = DoServerOperationsAsync(server);
                Console.WriteLine("client.CanRead = {0}", client.CanRead);
                Console.WriteLine("client.CanSeek = {0}", client.CanSeek);
                Console.WriteLine("client.CanTimeout = {0}", client.CanTimeout);
                Console.WriteLine("client.CanWrite = {0}", client.CanWrite);
                Console.WriteLine("client.IsAsync = {0}", client.IsAsync);
                Console.WriteLine("client.IsConnected = {0}", client.IsConnected);
                Console.WriteLine("client.OutBufferSize = {0}", client.OutBufferSize);
                Console.WriteLine("client.ReadMode = {0}", client.ReadMode);
                Console.WriteLine("client.SafePipeHandle = {0}", client.SafePipeHandle);
                Console.WriteLine("client.TransmissionMode = {0}", client.TransmissionMode);

                client.Write(new byte[] { 123 }, 0, 1);
                client.WriteAsync(new byte[] { 124 }, 0, 1).Wait();
                client.WaitForPipeDrain();
                client.Flush();

                serverTask.Wait();
            }
        }

        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
        {
            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.In, server.ClientSafePipeHandle))
            {
                Task serverTask = DoServerOperationsAsync(server);

                Console.WriteLine("client.InBufferSize = {0}", client.InBufferSize);
                byte[] readData = new byte[] { 0, 1 };
                client.Read(readData, 0, 1);
                client.ReadAsync(readData, 1, 1).Wait();
                Assert.Equal(123, readData[0]);
                Assert.Equal(124, readData[1]);

                serverTask.Wait();
            }
        }
    }
Exemplo n.º 9
0
 static void Main(string[] args)
 {
     using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, args[0]))
     {
         using (StreamWriter pipeWriter = new StreamWriter(pipeClient))
         {
             pipeWriter.WriteLine("HELLO");
             pipeWriter.Flush();
             Thread.Sleep(750);
             pipeWriter.WriteLine("FROM");
             pipeWriter.Flush();
             Thread.Sleep(750);
             pipeWriter.WriteLine("PIPE");
             pipeWriter.Flush();
             Thread.Sleep(750);
             pipeWriter.WriteLine("QUIT");
             pipeWriter.Flush();
             pipeClient.WaitForPipeDrain();
         }
     }
 }
Exemplo n.º 10
0
        public static void Main(string[] args)
        {
            if (args == null || args.Length < 1)
            {
                return;
            }

            string pipeWriteHandle = args[0];

            Application.EnableVisualStyles();
            LoaderWin main = new LoaderWin();

            Application.Run(main);


            //If Cancel button was clicked
            if (LoaderWin.isCancelled)
            {
                return;
            }


            //Loading the file
            IFC_Loader.LoadFile(LoaderWin.FilePath);


            //Getting the IFC Elements
            IFC_Loader.GetIFCElements();

            List <IIfcColumn>             cols   = IFC_Loader.Columns;
            List <IIfcBuildingStorey>     stors  = IFC_Loader.Storeys;
            List <IIfcSlab>               slabs  = IFC_Loader.Floors;
            List <IIfcBeam>               beamms = IFC_Loader.Beams;
            List <IIfcMemberStandardCase> incs   = IFC_Loader.Inclines;

            List <IIfcColumn>             Stcols   = IFC_Loader.ColumnsSt;
            List <IIfcBeam>               Stbeamms = IFC_Loader.BeamsSt;
            List <IIfcMemberStandardCase> Stbraces = IFC_Loader.Braces;



            List <Column>    columns = columns = GetColumnsData(cols);
            List <double>    storeys = GetStoreyLevels(stors);
            List <FloorSlab> floors  = GetFloorsData(slabs);
            List <Beam>      beams   = GetBeamsData(beamms);
            List <Inclined>  inlines = GetInclinesData(incs);

            List <ColumnSt> steelColumn = GetColumnsSteelData(Stcols);
            List <BeamSt>   steelBeam   = GetBeamsSteelData(Stbeamms);
            List <Brace>    steelBrace  = GetBracesData(Stbraces);


            //Serializers
            XmlSerializer columnSerializer      = new XmlSerializer(typeof(List <Column>));
            XmlSerializer storeySerializer      = new XmlSerializer(typeof(List <double>));
            XmlSerializer floorSerializer       = new XmlSerializer(typeof(List <FloorSlab>));
            XmlSerializer beamsSerializer       = new XmlSerializer(typeof(List <Beam>));
            XmlSerializer inclinesSerializer    = new XmlSerializer(typeof(List <Inclined>));
            XmlSerializer steelColumnSerializer = new XmlSerializer(typeof(List <ColumnSt>));
            XmlSerializer steelBeamSerializer   = new XmlSerializer(typeof(List <BeamSt>));
            XmlSerializer braceSerializer       = new XmlSerializer(typeof(List <Brace>));


            StringWriter columnsXMLstring     = new StringWriter();
            StringWriter storeyXMLstring      = new StringWriter();
            StringWriter floorXMLstring       = new StringWriter();
            StringWriter beamsXMLstring       = new StringWriter();
            StringWriter inclinesXMLstring    = new StringWriter();
            StringWriter steelColumnXMLstring = new StringWriter();
            StringWriter steelBeamXMLstring   = new StringWriter();
            StringWriter braceXMLstring       = new StringWriter();



            storeySerializer.Serialize(storeyXMLstring, storeys);

            if (floorsImport)
            {
                floorSerializer.Serialize(floorXMLstring, floors);
            }
            else
            {
                floorSerializer.Serialize(floorXMLstring, new List <FloorSlab>());
            }

            if (colsImport)
            {
                columnSerializer.Serialize(columnsXMLstring, columns);
                steelColumnSerializer.Serialize(steelColumnXMLstring, steelColumn);
            }
            else
            {
                columnSerializer.Serialize(columnsXMLstring, new List <Column>());
                steelColumnSerializer.Serialize(steelColumnXMLstring, new List <ColumnSt>());
            }

            if (beamsImport)
            {
                beamsSerializer.Serialize(beamsXMLstring, beams);
                steelBeamSerializer.Serialize(steelBeamXMLstring, steelBeam);
            }
            else
            {
                beamsSerializer.Serialize(beamsXMLstring, new List <Beam>());
                steelBeamSerializer.Serialize(steelBeamXMLstring, new List <BeamSt>());
            }

            if (incsImport)
            {
                inclinesSerializer.Serialize(inclinesXMLstring, inlines);
                braceSerializer.Serialize(braceXMLstring, steelBrace);
            }
            else
            {
                inclinesSerializer.Serialize(inclinesXMLstring, new List <Inclined>());
                braceSerializer.Serialize(braceXMLstring, new List <Brace>());
            }


            //Create an output client pipe to send the XML data to the plugin
            using (var pipeWrite = new AnonymousPipeClientStream(PipeDirection.Out, pipeWriteHandle))
            {
                try
                {
                    using (var sw = new StreamWriter(pipeWrite))
                    {
                        sw.AutoFlush = true;
                        // Send a 'sync message' and wait for the calling process to receive it
                        sw.WriteLine("SYNC");
                        pipeWrite.WaitForPipeDrain();

                        //Sending the XML serialized objects
                        sw.WriteLine(columnsXMLstring.ToString());
                        sw.WriteLine("COLSEND");
                        sw.WriteLine(inclinesXMLstring.ToString());
                        sw.WriteLine("INCSEND");
                        sw.WriteLine(beamsXMLstring.ToString());
                        sw.WriteLine("BEAMSEND");
                        sw.WriteLine(steelColumnXMLstring.ToString());
                        sw.WriteLine("COLSTEELSEND");
                        sw.WriteLine(braceXMLstring.ToString());
                        sw.WriteLine("BRACESEND");
                        sw.WriteLine(steelBeamXMLstring.ToString());
                        sw.WriteLine("BEAMSSTEELEND");
                        sw.WriteLine(storeyXMLstring.ToString());
                        sw.WriteLine("STORSEND");
                        sw.WriteLine(floorXMLstring.ToString());
                        sw.WriteLine("END");

                        columnsXMLstring.Close();
                        storeyXMLstring.Close();
                        beamsXMLstring.Close();
                        floorXMLstring.Close();
                        inclinesXMLstring.Close();
                        steelBeamXMLstring.Close();
                        steelColumnXMLstring.Close();
                        braceXMLstring.Close();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>Main program</summary>
        static int Main(string[] args)
        {
            try
            {
                if (args == null || args.Length < 2)
                {
                    throw new Exception("Usage: APSIMRunner.exe pipeWriteHandle pipeReadHandle");
                }

                // Get read and write pipe handles
                // Note: Roles are now reversed from how the other process is passing the handles in
                string pipeWriteHandle = args[0];
                string pipeReadHandle  = args[1];

                // Add hook for manager assembly resolve method.
                AppDomain.CurrentDomain.AssemblyResolve += Manager.ResolveManagerAssembliesEventHandler;

                // Create 2 anonymous pipes (read and write) for duplex communications
                // (each pipe is one-way)
                using (var pipeRead = new AnonymousPipeClientStream(PipeDirection.In, pipeReadHandle))
                    using (var pipeWrite = new AnonymousPipeClientStream(PipeDirection.Out, pipeWriteHandle))
                    {
                        //while (args.Length > 0)
                        //    Thread.Sleep(200);

                        while (PipeUtilities.GetObjectFromPipe(pipeRead) is Simulation sim)
                        {
                            Exception error   = null;
                            var       storage = new StorageViaSockets(sim.FileName);
                            try
                            {
                                if (sim != null)
                                {
                                    // Remove existing DataStore
                                    sim.Children.RemoveAll(model => model is Models.Storage.DataStore);

                                    // Add in a socket datastore to satisfy links.
                                    sim.Children.Add(storage);

                                    // Run the simulation.
                                    sim.Run(new CancellationTokenSource());
                                }
                                else
                                {
                                    throw new Exception("Unknown job type");
                                }
                            }
                            catch (Exception err)
                            {
                                error = err;
                            }

                            // Signal end of job.
                            PipeUtilities.SendObjectToPipe(pipeWrite, new JobOutput
                            {
                                ErrorMessage = error,
                                ReportData   = storage.reportDataThatNeedsToBeWritten,
                                DataTables   = storage.dataTablesThatNeedToBeWritten
                            });

                            pipeWrite.WaitForPipeDrain();
                        }
                    }
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                return(1);
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= Manager.ResolveManagerAssembliesEventHandler;
            }
            return(0);
        }
Exemplo n.º 12
0
    public static async Task ClientPInvokeChecks()
    {
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In, System.IO.HandleInheritability.None, 4096))
        {
            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.Out, server.ClientSafePipeHandle))
            {
                Task serverTask = Task.Run(() => DoStreamOperations(server));

                Assert.False(client.CanRead);
                Assert.False(client.CanSeek);
                Assert.False(client.CanTimeout);
                Assert.True(client.CanWrite);
                Assert.False(client.IsAsync);
                Assert.True(client.IsConnected);
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    Assert.Equal(0, client.OutBufferSize);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Assert.True(client.OutBufferSize > 0);
                }
                else
                {
                    Assert.Throws <PlatformNotSupportedException>(() => client.OutBufferSize);
                }
                Assert.Equal(PipeTransmissionMode.Byte, client.ReadMode);
                Assert.NotNull(client.SafePipeHandle);
                Assert.Equal(PipeTransmissionMode.Byte, client.TransmissionMode);

                client.Write(new byte[] { 123 }, 0, 1);
                await client.WriteAsync(new byte[] { 124 }, 0, 1);

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    client.WaitForPipeDrain();
                }
                else
                {
                    Assert.Throws <PlatformNotSupportedException>(() => client.WaitForPipeDrain());
                }
                client.Flush();

                await serverTask;
            }
        }

        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
        {
            using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(PipeDirection.In, server.ClientSafePipeHandle))
            {
                Task serverTask = Task.Run(() => DoStreamOperations(server));

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    Assert.Equal(4096, client.InBufferSize);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Assert.True(client.InBufferSize > 0);
                }
                else
                {
                    Assert.Throws <PlatformNotSupportedException>(() => client.InBufferSize);
                }
                byte[] readData = new byte[] { 0, 1 };
                Assert.Equal(1, client.Read(readData, 0, 1));
                Assert.Equal(1, client.ReadAsync(readData, 1, 1).Result);
                Assert.Equal(123, readData[0]);
                Assert.Equal(124, readData[1]);

                await serverTask;
            }
        }
    }
Exemplo n.º 13
0
        private IReadOnlyList <Process> CreateProcessTree()
        {
            (Process Value, string Message)rootResult = ListenForAnonymousPipeMessage(rootPipeHandleString =>
            {
                Process root = CreateProcess(rhs =>
                {
                    (Process Value, string Message)child1Result = ListenForAnonymousPipeMessage(child1PipeHandleString =>
                    {
                        Process child1 = CreateProcess(c1hs =>
                        {
                            Process child2 = CreateProcess(() => WaitForever());
                            child2.Start();

                            SendMessage(child2.Id.ToString(), c1hs);

                            return(WaitForever());
                        }, child1PipeHandleString, autoDispose: false);

                        child1.Start();

                        return(child1);
                    });

                    var child1ProcessId = child1Result.Value.Id;
                    var child2ProcessId = child1Result.Message;
                    SendMessage($"{child1ProcessId};{child2ProcessId}", rhs);

                    return(WaitForever());
                }, rootPipeHandleString, autoDispose: false);

                root.Start();

                return(root);
            });

            IEnumerable <Process> childProcesses = rootResult.Message
                                                   .Split(';')
                                                   .Select(x => int.Parse(x))
                                                   .Select(pid => Process.GetProcessById(pid));

            return(new[] { rootResult.Value }
                   .Concat(childProcesses)
                   .ToList());

            int WaitForever()
            {
                Thread.Sleep(Timeout.Infinite);

                // never reaches here -- but necessary to satisfy method's signature
                return(SuccessExitCode);
            }

            void SendMessage(string message, string handleAsString)
            {
                using (var client = new AnonymousPipeClientStream(PipeDirection.Out, handleAsString))
                {
                    using (var sw = new StreamWriter(client))
                    {
                        sw.WriteLine(message);
                        client.WaitForPipeDrain();
                    }
                }
            }

            (T Value, string Message) ListenForAnonymousPipeMessage <T>(Func <string, T> action)
            {
                using (var pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
                {
                    string handleAsString = pipeServer.GetClientHandleAsString();

                    T result = action(handleAsString);

                    pipeServer.DisposeLocalCopyOfClientHandle();

                    using (var sr = new StreamReader(pipeServer))
                    {
                        return(result, sr.ReadLine());
                    }
                }
            }
        }
Exemplo n.º 14
0
        public void Run()
        {
            while (PipeUtilities.GetObjectFromPipe(pipeRead) is IRunnable runnable)
            {
                job = runnable;
                Exception         error   = null;
                StorageViaSockets storage = new StorageViaSockets();
                try
                {
                    if (runnable is Simulation sim)
                    {
                        storage = new StorageViaSockets(sim.FileName);

                        // Remove existing DataStore
                        sim.Children.RemoveAll(model => model is Models.Storage.DataStore);

                        // Add in a socket datastore to satisfy links.
                        sim.Children.Add(storage);

                        if (sim.Services != null)
                        {
                            sim.Services.RemoveAll(s => s is Models.Storage.IDataStore);
                            sim.Services.Add(storage);
                        }

                        // Initialise the model so that Simulation.Run doesn't call OnCreated.
                        // We don't need to recompile any manager scripts and a simulation
                        // should be ready to run at this point following a binary
                        // deserialisation.
                        sim.ParentAllDescendants();
                    }
                    else if (runnable is IModel model)
                    {
                        IDataStore oldStorage = model.FindInScope <IDataStore>();
                        if (oldStorage != null)
                        {
                            storage = new StorageViaSockets(oldStorage.FileName);
                        }

                        storage.Parent = model;
                        storage.Children.AddRange(model.Children.OfType <DataStore>().SelectMany(d => d.Children).Select(m => Apsim.Clone(m)));
                        model.Children.RemoveAll(m => m is DataStore);
                        model.Children.Add(storage);

                        model.ParentAllDescendants();
                    }

                    // Initiate progress updates.
                    lock (timerLock)
                        timer.Start();

                    // Run the job.
                    runnable.Run(new CancellationTokenSource());

                    // Stop progress updates.
                    lock (timerLock)
                        timer.Stop();
                }
                catch (Exception err)
                {
                    error = err;
                }

                // Signal end of job.
                lock (timerLock)
                {
                    PipeUtilities.SendObjectToPipe(pipeWrite, new JobOutput
                    {
                        ErrorMessage = error,
                        ReportData   = storage.reportDataThatNeedsToBeWritten,
                        DataTables   = storage.dataTablesThatNeedToBeWritten
                    });
                    pipeWrite.WaitForPipeDrain();
                }
            }
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            if (args == null || args.Length < 2)
            {
                return;
            }

            // get read and write pipe handles
            // note: Roles are now reversed from how the other process is passing the handles in
            string pipeWriteHandle = args[0];
            string pipeReadHandle  = args[1];

            // create 2 anonymous pipes (read and write) for duplex communications
            // (each pipe is one-way)
            using (var pipeRead = new AnonymousPipeClientStream(PipeDirection.In, pipeReadHandle))
                using (var pipeWrite = new AnonymousPipeClientStream(PipeDirection.Out, pipeWriteHandle))
                {
                    try
                    {
                        var lsValues = new List <string>();

                        // get message from other process
                        using (var sr = new StreamReader(pipeRead))
                        {
                            string sTempMessage;

                            // wait for "sync message" from the other process
                            do
                            {
                                sTempMessage = sr.ReadLine();
                            } while (sTempMessage == null || !sTempMessage.StartsWith("SYNC"));

                            // read until "end message" from the server
                            while ((sTempMessage = sr.ReadLine()) != null && !sTempMessage.StartsWith("END"))
                            {
                                lsValues.Add(sTempMessage);
                            }
                        }

                        // send value to calling process
                        using (var sw = new StreamWriter(pipeWrite))
                        {
                            sw.AutoFlush = true;
                            // send a "sync message" and wait for the calling process to receive it
                            sw.WriteLine("SYNC");
                            pipeWrite.WaitForPipeDrain(); // wait here

                            PassingObject   dataObject   = JsonConvert.DeserializeObject <PassingObject>(lsValues[0]);
                            ReturningObject returnObject = new ReturningObject();

                            try
                            {
                                // create a new ServerTextControl for the document processing
                                using (TXTextControl.ServerTextControl tx = new TXTextControl.ServerTextControl())
                                {
                                    tx.Create();
                                    tx.Load(dataObject.Document, TXTextControl.BinaryStreamType.InternalUnicodeFormat);

                                    using (MailMerge mailMerge = new MailMerge())
                                    {
                                        mailMerge.TextComponent = tx;
                                        mailMerge.MergeJsonData(dataObject.Data.ToString());
                                    }

                                    byte[] data;
                                    tx.Save(out data, TXTextControl.BinaryStreamType.AdobePDF);

                                    returnObject.Document = data;
                                }

                                sw.WriteLine(JsonConvert.SerializeObject(returnObject));
                                sw.WriteLine("END");
                            }
                            catch (Exception exc)
                            {
                                returnObject.Error = exc.Message;

                                sw.WriteLine(JsonConvert.SerializeObject(returnObject));
                                sw.WriteLine("END");
                            }
                        }
                    }
                    catch
                    {
                    }
                }
        }
Exemplo n.º 16
0
        public static void PopMessage(object obj, Type type)
        {
            if (type.Name == MessageTypeStrings.DATA)
            {
                Data   data        = (Data)obj;
                string contentType = data.DataMap[MessageTypeStrings.CONTENT_TYPE];

                switch (contentType)
                {
                case MessageTypeStrings.ASSIGN_USERNAME:
                    roomContext.SetUsername(data.DataMap[MessageTypeStrings.USERNAME]);
                    clntName = roomContext.GetMyUsername();
                    if (isHost)
                    {
                        // Server에게 방생성 요청
                        Data temp = new Data();
                        temp.DataMap[MessageTypeStrings.CONTENT_TYPE] = MessageTypeStrings.CREATE_ROOM;
                        temp.DataMap[MessageTypeStrings.ROOMNAME]     = roomName;
                        temp.DataMap[MessageTypeStrings.LIMIT]        = limit;
                        temp.DataMap[MessageTypeStrings.USERNAME]     = roomContext.GetMyUsername();
                        packetManager.PackMessage(protoObj: temp);
                    }
                    else
                    {
                        // Host가 아니라면, 방에 Enter
                        Data temp = new Data();
                        temp.DataMap[MessageTypeStrings.CONTENT_TYPE] = MessageTypeStrings.ENTER_ROOM;
                        temp.DataMap[MessageTypeStrings.ROOMNAME]     = roomName;
                        temp.DataMap[MessageTypeStrings.USERNAME]     = roomContext.GetMyUsername();
                        packetManager.PackMessage(protoObj: temp);
                    }
                    break;
                }
            }
            else if (type.Name == MessageTypeStrings.ROOMINFO)
            {
                // Accept Create/Enter Room
                RoomInfo room = (RoomInfo)obj;
                roomContext.SetRoomInfo(room);
                roomId = roomContext.RoomId;

                if (isHost)
                {
                    if (created)
                    {
                        return;
                    }

                    created      = true;
                    sw.AutoFlush = true;
                    sw.WriteLine("ROOM_CREATE_SUCCESS");
                    outPipe.WaitForPipeDrain();

                    // Controller로부터 Start 신호 받기
                    string rtn = sr.ReadLine();
                    if (rtn == "GAME_START")
                    {
                        Log("Get Start Signal from controller");
                        Data request = new Data();
                        request.DataMap.Add(MessageTypeStrings.CONTENT_TYPE, MessageTypeStrings.START_GAME);
                        request.DataMap.Add(MessageTypeStrings.ROOMID, roomContext.RoomId.ToString());
                        packetManager.PackMessage(protoObj: request);
                    }
                }
                else
                {
                    if (enter == 0)
                    {
                        Log("Ready_EVENT");
                        enter++;
                        packetManager.PackMessage(MessageType.READY_EVENT);
                    }
                    else if (enter == 1)
                    {
                        Log("Ready");
                        enter++;
                        sw.AutoFlush = true;
                        sw.WriteLine("READY");
                        outPipe.WaitForPipeDrain();
                    }
                }
            }
            else if (type.Name == MessageTypeStrings.INT32)
            {
                int messageType = (int)obj;
                if (messageType == MessageType.START_GAME)
                {
                    Log("GAME_START!");
                    sw.WriteLine("START");
                    //Dummy Data 송신
                    timer.Start();
                }
            }
            else if (type.Name == MessageTypeStrings.WORLDSTATE)
            {
                //Nothing;
                //Log(DummyFactory.ToString((WorldState)obj));
            }
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            Log.Logger = SetupLogger();

            if (args.Length == 2)
            {
                using (AnonymousPipeClientStream pipeClientReader =
                           new AnonymousPipeClientStream(PipeDirection.In, args[0]))
                    using (PipeStream pipeClientWriter =
                               new AnonymousPipeClientStream(PipeDirection.Out, args[1]))
                    {
                        CrawlDescription crawlDescription;

                        // read crawl description from pipe
                        try
                        {
                            using (StreamReader sr = new StreamReader(pipeClientReader))
                            {
                                string message;

                                do
                                {
                                    // TODO(zvp) : have to exit eventually.
                                    message = sr.ReadLine();
                                    Log.Debug("Pipe Received Message: {0}", message);
                                } while (message == null || !message.StartsWith("SYNC"));

                                message          = sr.ReadLine();
                                crawlDescription = JsonConvert.DeserializeObject <CrawlDescription>(message);
                                Log.Debug("Pipe Received Crawl Description: {0}", message);
                            }

                            // process the message
                            CrawlResult crawlResult = null;
                            using (Scraper scraper = new Scraper(crawlDescription))
                            {
                                scraper.Initialize();
                                crawlResult = scraper.Scrape().GetAwaiter().GetResult();
                            }

                            using (StreamWriter sw = new StreamWriter(pipeClientWriter))
                            {
                                sw.AutoFlush = true;

                                // write Sync message and wait for drain
                                sw.WriteLine("SYNC");
                                pipeClientWriter.WaitForPipeDrain();

                                // write back the crawl result
                                string serializedCrawlResult = JsonConvert.SerializeObject(crawlResult);
                                sw.WriteLine(serializedCrawlResult);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error("WebScraper Exception({0}): {1}", ex.GetType(), ex.Message);
                        }
                    }
            }
            else
            {
                Log.Error("Expected 2 Arguments (PipeWriteHandle and PipeReadHandle).");
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// 方法  匿名パイプを使用してローカル プロセス間の通信を行う
        /// http://msdn.microsoft.com/ja-jp/library/bb546102.aspx
        /// の親プロセス側実装(入出力に対応させた)
        /// ・AnonymousPipeServerStream クラス (System.IO.Pipes)
        ///  http://msdn.microsoft.com/ja-jp/library/system.io.pipes.anonymouspipeserverstream.aspx
        /// ・AnonymousPipeClientStream クラス (System.IO.Pipes)
        ///  http://msdn.microsoft.com/ja-jp/library/system.io.pipes.anonymouspipeclientstream.aspx
        /// </summary>
        public static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                using (PipeStream pipeClientIn =
                           new AnonymousPipeClientStream(PipeDirection.In, args[0]))
                {
                    using (PipeStream pipeClientOut =
                               new AnonymousPipeClientStream(PipeDirection.Out, args[1]))
                    {
                        // 匿名パイプでは、Message送信モードはサポートされません。
                        // http://msdn.microsoft.com/ja-jp/library/system.io.pipes.pipetransmissionmode.aspx

                        // 匿名パイプの送信モードを取得:Byteになっている筈(デバッグ)
                        Debug.WriteLine(string.Format(
                                            "[Child] pipeClientIn.TransmissionMode: {0}.",
                                            pipeClientIn.TransmissionMode.ToString()));
                        Debug.WriteLine(string.Format(
                                            "[Child] pipeClientOut.TransmissionMode: {0}.",
                                            pipeClientOut.TransmissionMode.ToString()));

                        using (StreamReader sr = new StreamReader(pipeClientIn))
                        {
                            using (StreamWriter sw = new StreamWriter(pipeClientOut))
                            {
                                string temp;
                                sw.AutoFlush = true;

                                while ((temp = sr.ReadLine()) != null)
                                {
                                    Debug.WriteLine("[Child] Debug: " + temp);

                                    // 前・子プロセスへの書き込みが
                                    // 全て読み取られるまで待つ。
                                    pipeClientOut.WaitForPipeDrain();


                                    if (temp.ToUpper().IndexOf("EXIT") != -1)
                                    {
                                        // 終了する場合
                                        Debug.WriteLine("[Child] Debug EXIT");
                                        sw.WriteLine("[Child] EXIT");
                                        sw.Flush();
                                        break;
                                    }
                                    else
                                    {
                                        // 継続する場合

                                        // 入力を反転して出力する。
                                        Debug.WriteLine("[Child] Debug Reversal: " + Program.Reverse(temp));
                                        sw.WriteLine("[Child] Reversal: " + Program.Reverse(temp));
                                        sw.Flush();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }