示例#1
0
    public static void Test()
    {
        var expression = new BinaryExpression(
            new BinaryExpression(new BooleanExpression(false), new BooleanExpression(true), Operator.And),
            new BinaryExpression(new BooleanExpression(true), new BooleanExpression(false), Operator.Or),
            Operator.Or);

        Debug.WriteLine("Initial expression: ");
        Debug.WriteLine(expression);     // "((False And True) Or (True Or False))"
        if (expression.ToString() != "((False And True) Or (True Or False))")
        {
            throw new InvalidOperationException();
        }
        var binary      = BinaryFormatterHelper.ToBinary(expression);
        var expression2 = BinaryFormatterHelper.FromBinary <BinaryExpression>(binary);

        Debug.WriteLine("Deserialized expression: ");
        Debug.WriteLine(expression2);
        if (expression.ToString() != expression2.ToString())
        {
            throw new InvalidOperationException();
        }
        else
        {
            Debug.WriteLine("Deserialized and original expressions are identical");
        }
    }
        public string Serialize(Object obj)
        {
            var messageRequest = new MethodCall(new[] {
                new Header(MessageHeader.Uri, "tcp://localhost:3000/TownCrier"),
                new Header(MessageHeader.MethodName, "Announce"),
                new Header(MessageHeader.MethodSignature, SignatureFor("Announce")),
                new Header(MessageHeader.TypeName, typeof(Crier).AssemblyQualifiedName),
                new Header(MessageHeader.Args, ArgsFor("Announce"))
            });
            var responseMessage = new MethodResponse(new[]
            {
                new Header(MessageHeader.Return, obj)
            }, messageRequest);

            var responseStream = BinaryFormatterHelper.SerializeObject(responseMessage);

            using (var stream = new MemoryStream())
            {
                var handle = new TcpProtocolHandle(stream);
                handle.WritePreamble();
                handle.WriteMajorVersion();
                handle.WriteMinorVersion();
                handle.WriteOperation(TcpOperations.Reply);
                handle.WriteContentDelimiter(TcpContentDelimiter.ContentLength);
                handle.WriteContentLength(responseStream.Length);
                handle.WriteTransportHeaders(null);
                handle.WriteContent(responseStream);
                return(Convert.ToBase64String(stream.ToArray()));
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Please, re-run only with arguments!");
                Console.ResetColor();
                Console.ReadLine();
            }
            else
            {
                var serverOptions = args[0];

                if (String.IsNullOrWhiteSpace(serverOptions))
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Server arguments not found!");
                    Console.ResetColor();
                    Console.ReadLine();
                }
                else
                {
                    var handle = GetConsoleWindow();
                    var model  = BinaryFormatterHelper.Deserialize <MonetServerOptionsModel>(serverOptions);

                    // Hide
                    ShowWindow(handle, SW_HIDE);

                    //environment
                    EnvironmentHelper.SetVariables("PATH", string.Format("{0}\\bin;{0}\\lib;{0}\\lib\\MonetDB5;", Directory.GetParent(Path.GetDirectoryName(model.ServerFileName)).FullName));

                    DiagnosticHelper.AutoLaunchApplicationToSleep(model.ServerFileName, model.ServerArguments);
                }
            }
        }
示例#4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="database"></param>
        /// <returns></returns>
        public int GetPort(string database)
        {
            var dataDir = Path.Combine(_serverConfiguration.DbFarmDir, database);
            var model   = BinaryFormatterHelper.Deserialize <MonetServerOptionsModel>(Path.Combine(dataDir, SERVER_OPTIONS_FILE));

            return(model?.Port ?? 0);
        }
        public void WriteRequestAndReadResponse()
        {
            var channel = new TcpChannel(8080);

            ChannelServices.RegisterChannel(channel, false);
            RemotingServices.Marshal(new ServiceClass(), "Remote");

            var uri = "tcp://localhost:8080/Remote";

            using (var client = new TcpClient())
            {
                client.Connect("localhost", 8080);
                using (var stream = client.GetStream())
                {
                    var messageRequest = new MethodCall(new Header[] {
                        new Header(MessageHeader.Uri, uri),
                        new Header(MessageHeader.MethodName, "Do"),
                        new Header(MessageHeader.MethodSignature, new Type[] { typeof(string) }),
                        new Header(MessageHeader.TypeName, typeof(ServiceClass).AssemblyQualifiedName),
                        new Header(MessageHeader.Args, new object[] { "Hi" })
                    });
                    var messageRequestStream = BinaryFormatterHelper.SerializeObject(messageRequest);

                    var handle = new TcpProtocolHandle(stream);

                    //send remoting request
                    handle.WritePreamble();
                    handle.WriteMajorVersion();
                    handle.WriteMinorVersion();
                    handle.WriteOperation(TcpOperations.Request);
                    handle.WriteContentDelimiter(TcpContentDelimiter.ContentLength);
                    handle.WriteContentLength(messageRequestStream.Length);
                    handle.WriteTransportHeaders(new Dictionary <string, object>()
                    {
                        { TcpTransportHeader.RequestUri, uri }
                    });
                    handle.WriteContent(messageRequestStream);

                    //read remoting response
                    Console.WriteLine("Preamble: {0}", handle.ReadPreamble());
                    Console.WriteLine("MajorVersion: {0}", handle.ReadMajorVersion());
                    Console.WriteLine("MinorVersion: {0}", handle.ReadMinorVersion());
                    var op = handle.ReadOperation();
                    Assert.AreEqual(TcpOperations.Reply, op);
                    Console.WriteLine("Operation: {0}", op);
                    Console.WriteLine("ContentDelimiter: {0}", handle.ReadContentDelimiter());
                    Console.WriteLine("ContentLength: {0}", handle.ReadContentLength());
                    handle.ReadTransportHeaders();
                    var messageResponse = BinaryFormatterHelper.DeserializeObject(handle.ReadContent()) as MethodResponse;
                    Assert.IsNotNull(messageResponse);
                    DumpHelper.DumpMessage(messageResponse);
                    if (messageResponse.Exception != null)
                    {
                        throw messageResponse.Exception;
                    }
                    Assert.AreEqual("Hi", messageResponse.ReturnValue);
                }
            }
        }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var data = new BinaryData {
            binaryData = BinaryFormatterHelper.ToByteArray(value)
        };

        serializer.Serialize(writer, data);
    }
示例#7
0
        public T Get <T>(string key)
        {
            var obj = _accessor.SelectByKey(key);

            return(obj != null
                ? BinaryFormatterHelper.Deserialize <T>(obj.Data.Value)
                : default(T));
        }
        private void ProcessUpdateLines(byte[] data)
        {
            Dictionary <int, string> updateLines = BinaryFormatterHelper.FromByteArray <Dictionary <int, string> >(data);

            // foreach (KeyValuePair<int,string> keyValuePair in updateLines) {
            // Log("ProcessUpdateLines: " + keyValuePair);
            // }
            CommunicationWrapper.UpdateLines(updateLines);
        }
示例#9
0
        public void ReadRequestAndWriteResponse()
        {
            IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
            var         endpoint    = new IPEndPoint(addressList[addressList.Length - 1], 9900);
            var         listener    = new TcpListener(endpoint);

            listener.Start();

            var t = new Thread(new ThreadStart(() =>
            {
                var c      = listener.AcceptTcpClient();
                var handle = new HttpProtocolHandle(c.GetStream());

                //read remoting request
                Trace.WriteLine(handle.ReadFirstLine());
                DumpHelper.DumpDictionary(handle.ReadHeaders());
                var messageRequest = BinaryFormatterHelper.DeserializeObject(handle.ReadContent()) as MethodCall;

                //HACK:SoapFormatter not work well
                //http://labs.developerfusion.co.uk/SourceViewer/browse.aspx?assembly=SSCLI&namespace=System.Runtime.Remoting
                //var f = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
                //f.Context = new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Other);
                //var mc = new MethodCall(this.Parse(headers));
                //var messageRequest = f.Deserialize(new System.IO.MemoryStream(content), new HeaderHandler(mc.HeaderHandler));

                Assert.IsNotNull(messageRequest);
                DumpHelper.DumpMessage(messageRequest);

                //write remoting response
                var responeMessage = new MethodResponse(new Header[] { new Header(MessageHeader.Return, messageRequest.Args[0]) }, messageRequest);
                var responseStream = BinaryFormatterHelper.SerializeObject(responeMessage);
                handle.WriteResponseFirstLine("200", "ok");
                handle.WriteHeaders(new Dictionary <string, object>()
                {
                    { HttpHeader.ContentLength, responseStream.Length }
                });
                handle.WriteContent(responseStream);

                //end httprequest
                c.Close();
            }));

            t.Start();

            //use BinaryFormatter via HTTP
            var channel = new HttpChannel(new Hashtable(), new BinaryClientFormatterSinkProvider(), null);

            ChannelServices.RegisterChannel(channel, false);
            var url     = string.Format("http://{0}/remote.rem", endpoint);
            var service = RemotingServices.Connect(typeof(ServiceClass), url) as ServiceClass;

            Assert.AreEqual("Hi", service.Do("Hi"));

            t.Abort();

            ChannelServices.UnregisterChannel(channel);
        }
示例#10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="database"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="Exception">Database already exists</exception>
        /// <exception cref="ArgumentNullException"><paramref name="database"/> is <see langword="null" />.</exception>
        public bool CreateDatabase(string database)
        {
            //to check in processes
            var dataDir = Path.Combine(_serverConfiguration.DbFarmDir, database);
            var model   = new MonetServerOptionsModel();

            if (DiagnosticHelper.IsRunningApplication(MSERVER_PROCESS_NAME, String.Format("--dbpath=\"{0}\"", dataDir)))
            {
                throw new MonetDbException("Database already created");
            }

            try
            {
                //database
                var serverFileName = string.Format("{0}\\bin\\mserver5.exe", _serverConfiguration.DbInstallerDir);
                var serverFileArgs = string.Format("--set \"prefix={0}\" " +
                                                   "--set \"exec_prefix={0}\" " +
                                                   "--set \"mapi_port={1}\" " +
                                                   "--dbpath=\"{2}\"  " +
                                                   "--set \"gdk_nr_threads={3}\" " +
                                                   "--set \"max_clients={4}\"",
                                                   _serverConfiguration.DbInstallerDir,
                                                   model.Port,
                                                   dataDir,
                                                   model.Threads,
                                                   model.MaxClients);

                model.ServerArguments = serverFileArgs;
                model.ServerFileName  = serverFileName;

                //environment
                EnvironmentHelper.SetVariables("PATH", string.Format("{0}\\bin;{0}\\lib;{0}\\lib\\MonetDB5;", _serverConfiguration.DbInstallerDir));

                if (DiagnosticHelper.AutoLaunchApplicationToSleep(serverFileName, serverFileArgs))
                {
                    //server options
                    BinaryFormatterHelper.Serialize(model, Path.Combine(dataDir, SERVER_OPTIONS_FILE));

                    //startup
                    ShellHelper.AddToStartup(ToTitle(database), Path.Combine(IoHelper.CurrentRoot, STARTUP_PROCESS_NAME), $"\"{Path.Combine(dataDir, SERVER_OPTIONS_FILE)}\"");

                    //logging
                    LoggerHelper.Write(LoggerOption.Info, "Client#{0} -> Created '{1}' database", CurrentClient.ClientId, database);

                    return(true);
                }
            }
            catch (Exception exception)
            {
                LoggerHelper.Write(LoggerOption.Error, exception.Message);

                throw;
            }

            return(false);
        }
示例#11
0
    private static void Test(A refObject, bool shouldBeEqual)
    {
        Console.WriteLine(string.Format("refObject and A.Empty are {0}.", object.ReferenceEquals(refObject, A.Empty) ? "identical" : "different"));
        var binary             = BinaryFormatterHelper.ToBase64String(refObject);
        var DeserializedObject = BinaryFormatterHelper.FromBase64String <A>(binary);

        Console.WriteLine(string.Format("DeserializedObject and A.Empty are {0}.", object.ReferenceEquals(refObject, A.Empty) ? "identical" : "different"));
        Debug.Assert(object.ReferenceEquals(refObject, A.Empty) == object.ReferenceEquals(DeserializedObject, A.Empty)); // No assert
        Debug.Assert(shouldBeEqual == object.ReferenceEquals(refObject, DeserializedObject));                            // No assert
    }
        private void GetGameDataNow(GameDataType gameDataType, object arg)
        {
            if (!Initialized)
            {
                return;
            }

            byte[] bytes = BinaryFormatterHelper.ToByteArray(new[] {
                gameDataType, arg
            });
            WriteMessageGuaranteed(new Message(MessageID.GetData, bytes));
        }
        private void ToggleGameSettingNow(string settingName, object value)
        {
            if (!Initialized)
            {
                return;
            }

            byte[] bytes = BinaryFormatterHelper.ToByteArray(new[] {
                settingName, value
            });
            WriteMessageGuaranteed(new Message(MessageID.ToggleGameSetting, bytes));
        }
        private void ProcessSendCurrentBindings(byte[] data)
        {
            Dictionary <int, List <int> >       nativeBindings = BinaryFormatterHelper.FromByteArray <Dictionary <int, List <int> > >(data);
            Dictionary <HotkeyID, List <Keys> > bindings       =
                nativeBindings.ToDictionary(pair => (HotkeyID)pair.Key, pair => pair.Value.Cast <Keys>().ToList());

            foreach (var pair in bindings)
            {
                Log(pair.ToString());
            }

            CommunicationWrapper.SetBindings(bindings);
        }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            return(null);
        }
        var data = serializer.Deserialize <BinaryData>(reader);

        if (data == null || data.binaryData == null)
        {
            return(null);
        }
        return(BinaryFormatterHelper.FromByteArray <T>(data.binaryData));
    }
        public void ReadRequestAndWriteResponse()
        {
            IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
            var         endpoint    = new IPEndPoint(addressList[addressList.Length - 1], 9900);
            var         listener    = new TcpListener(endpoint);

            listener.Start();

            var t = new Thread(new ThreadStart(() =>
            {
                var c      = listener.AcceptTcpClient();
                var handle = new TcpProtocolHandle(c.GetStream());

                //read remoting request
                Console.WriteLine("Preamble: {0}", handle.ReadPreamble());
                Console.WriteLine("MajorVersion: {0}", handle.ReadMajorVersion());
                Console.WriteLine("MinorVersion: {0}", handle.ReadMinorVersion());
                var op = handle.ReadOperation();
                Assert.AreEqual(TcpOperations.Request, op);
                Console.WriteLine("Operation: {0}", op);
                Console.WriteLine("ContentDelimiter: {0}", handle.ReadContentDelimiter());
                Console.WriteLine("ContentLength: {0}", handle.ReadContentLength());
                DumpHelper.DumpDictionary(handle.ReadTransportHeaders());
                var messageRequest = BinaryFormatterHelper.DeserializeObject(handle.ReadContent()) as MethodCall;
                Assert.IsNotNull(messageRequest);
                DumpHelper.DumpMessage(messageRequest);

                //write remoting response
                var responeMessage = new MethodResponse(new Header[] { new Header(MessageHeader.Return, messageRequest.Args[0]) }, messageRequest);
                var responseStream = BinaryFormatterHelper.SerializeObject(responeMessage);
                handle.WritePreamble();
                handle.WriteMajorVersion();
                handle.WriteMinorVersion();
                handle.WriteOperation(TcpOperations.Reply);
                handle.WriteContentDelimiter(TcpContentDelimiter.ContentLength);
                handle.WriteContentLength(responseStream.Length);
                handle.WriteTransportHeaders(null);
                handle.WriteContent(responseStream);
            }));

            t.Start();

            var url     = string.Format("tcp://{0}/remote.rem", endpoint);
            var service = RemotingServices.Connect(typeof(ServiceClass), url) as ServiceClass;

            Assert.AreEqual("Hi", service.Do("Hi"));

            t.Abort();
        }
 private void ProcessSendState(byte[] data)
 {
     try {
         StudioInfo studioInfo = StudioInfo.FromByteArray(data);
         CommunicationWrapper.StudioInfo = studioInfo;
     } catch (InvalidCastException) {
         string   studioVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(3);
         object[] objects       = BinaryFormatterHelper.FromByteArray <object[]>(data);
         string   modVersion    = objects.Length >= 10 ? objects[9].ToString() : "Unknown";
         MessageBox.Show(
             $"Studio v{studioVersion} and CelesteTAS v{modVersion} do not match. Please manually extract the studio from the \"game_path\\Mods\\CelesteTAS.zip\" file.",
             "Communication Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         Application.Exit();
     }
 }
    public static void Test()
    {
        var test = new TestConfiguration();

        Debug.WriteLine("\nTesting Xmlserializer...");
        var xml = XmlSerializationHelper.GetXml(test);

        using (new SetValue <bool>(TestConfiguration.ShowDebugInformation, true))
        {
            var testFromXml = XmlSerializationHelper.LoadFromXML <TestConfiguration>(xml);
            Debug.WriteLine("XmlSerializer result: " + testFromXml.ToString());
        }
        Debug.WriteLine("\nTesting Json.NET...");
        var json = JsonConvert.SerializeObject(test, Formatting.Indented);

        using (new SetValue <bool>(TestConfiguration.ShowDebugInformation, true))
        {
            var testFromJson = JsonConvert.DeserializeObject <TestConfiguration>(json);
            Debug.WriteLine("Json.NET result: " + testFromJson.ToString());
        }
        Debug.WriteLine("\nTesting DataContractSerializer...");
        var contractXml = DataContractSerializerHelper.GetXml(test);

        using (new SetValue <bool>(TestConfiguration.ShowDebugInformation, true))
        {
            var testFromContractXml = DataContractSerializerHelper.LoadFromXML <TestConfiguration>(contractXml);
            Debug.WriteLine("DataContractSerializer result: " + testFromContractXml.ToString());
        }
        Debug.WriteLine("\nTesting BinaryFormatter...");
        var binary = BinaryFormatterHelper.ToBase64String(test);

        using (new SetValue <bool>(TestConfiguration.ShowDebugInformation, true))
        {
            var testFromBinary = BinaryFormatterHelper.FromBase64String <TestConfiguration>(binary);
            Debug.WriteLine("BinaryFormatter result: " + testFromBinary.ToString());
        }
        Debug.WriteLine("\nTesting JavaScriptSerializer...");
        var javaScript = new JavaScriptSerializer().Serialize(test);

        using (new SetValue <bool>(TestConfiguration.ShowDebugInformation, true))
        {
            var testFromJavaScript = new JavaScriptSerializer().Deserialize <TestConfiguration>(javaScript);
            Debug.WriteLine("JavaScriptSerializer result: " + testFromJavaScript.ToString());
        }
    }
示例#19
0
        public void WriteRequestAndReadResponse()
        {
            var properties = new Hashtable()
            {
                { "port", 8080 }
            };
            var channel = new HttpChannel(properties, null, new BinaryServerFormatterSinkProvider());

            ChannelServices.RegisterChannel(channel, false);
            RemotingServices.Marshal(new ServiceClass(), "Remote");

            var uri = "http://localhost:8080/Remote";

            var messageRequest = new MethodCall(new Header[] {
                new Header(MessageHeader.Uri, uri),
                new Header(MessageHeader.MethodName, "Do"),
                new Header(MessageHeader.MethodSignature, new Type[] { typeof(string) }),
                new Header(MessageHeader.TypeName, typeof(ServiceClass).AssemblyQualifiedName),
                new Header(MessageHeader.Args, new object[] { "Hi" })
            });
            var messageRequestStream = BinaryFormatterHelper.SerializeObject(messageRequest);

            var wc = new WebClient();
            var messageResponse = BinaryFormatterHelper.DeserializeObject(wc.UploadData(uri, messageRequestStream)) as MethodResponse;

            Assert.IsNotNull(messageResponse);
            DumpHelper.DumpMessage(messageResponse);
            if (messageResponse.Exception != null)
            {
                throw messageResponse.Exception;
            }
            Assert.AreEqual("Hi", messageResponse.ReturnValue);

            //handle.WriteRequestFirstLine("POST", "/Remote");
            //handle.WriteHeaders(new Dictionary<string, object>() { { HttpHeader.ContentLength, messageRequestStream.Length } });
            //HACK:http will send 100 continue after read http header
            //handle.WriteContent(messageRequestStream);

            ChannelServices.UnregisterChannel(channel);
        }
        public void WriteRequestAndReadResponse()
        {
            //var properties = new Hashtable() { { "port", 8080 } };
            //var channel = new TcpChannel(properties, null, new SoapServerFormatterSinkProvider());
            //if using SOAP via TCP, messageRequestStream must be SOAP format
            var channel = new TcpChannel(8080);

            ChannelServices.RegisterChannel(channel, false);

            var    service = new ServiceClass();
            ObjRef obj     = RemotingServices.Marshal(service, "Remote");

            var uri = "tcp://localhost:8080/Remote";

            using (var client = new TcpClient())
            {
                client.Connect("localhost", 8080);
                using (var stream = client.GetStream())
                {
                    var messageRequest = new MethodCall(new Header[] {
                        new Header("__Uri", uri),
                        new Header("__MethodName", "Do"),
                        new Header("__MethodSignature", new Type[] { typeof(string) }),
                        new Header("__TypeName", typeof(ServiceClass).AssemblyQualifiedName),
                        new Header("__Args", new object[] { "Hi" })
                    });
                    var messageRequestStream = BinaryFormatterHelper.SerializeObject(messageRequest);

                    var writer = new ProtocolWriter(stream);
                    writer.WritePreamble();
                    writer.WriteMajorVersion();
                    writer.WriteMinorVersion();
                    writer.WriteOperation(TcpOperations.Request);
                    writer.WriteContentDelimiter(TcpContentDelimiter.ContentLength);
                    writer.WriteContentLength(messageRequestStream.Length);
                    writer.WriteTransportHeaders(uri);
                    writer.WriteBytes(messageRequestStream);


                    var reader = new ProtocolReader(stream);
                    Console.WriteLine("Preamble: {0}", reader.ReadPreamble());
                    Console.WriteLine("MajorVersion: {0}", reader.ReadMajorVersion());
                    Console.WriteLine("MinorVersion: {0}", reader.ReadMinorVersion());
                    var op = reader.ReadOperation();
                    Assert.AreEqual(TcpOperations.Reply, op);
                    Console.WriteLine("Operation: {0}", op);
                    Console.WriteLine("ContentDelimiter: {0}", reader.ReadContentDelimiter());
                    var length = reader.ReadContentLength();
                    Console.WriteLine("ContentLength: {0}", length);
                    reader.ReadTransportHeaders();
                    var messageResponse = BinaryFormatterHelper.DeserializeObject(reader.ReadBytes(length)) as MethodResponse;
                    Assert.IsNotNull(messageResponse);
                    DumpHelper.DumpMessage(messageResponse);
                    if (messageResponse.Exception != null)
                    {
                        throw messageResponse.Exception;
                    }
                    Assert.AreEqual("Hi", messageResponse.ReturnValue);
                }
            }
        }
            void ProcessReceive(SocketAsyncEventArgs e)
            {
                if (e.BytesTransferred > 0)
                {
                    if (e.SocketError == SocketError.Success)
                    {
                        totalBuffer = Combine(totalBuffer, e.Buffer);

                        if (e.AcceptSocket.Available == 0)
                        {
                            //.Net Remoting Protocol Parser
                            #region Read Request
                            Console.WriteLine("==== .Net Remoting Protocol Parser ====");
                            //1. Preamble, will be ".NET"
                            Console.WriteLine("Preamble: {0}", Encoding.ASCII.GetString(new byte[] {
                                totalBuffer[0],
                                totalBuffer[1],
                                totalBuffer[2],
                                totalBuffer[3]
                            }));
                            //2. MajorVersion, will be 1
                            Console.WriteLine("MajorVersion: {0}", totalBuffer[4]);
                            //3. MinorVersion, will be 0
                            Console.WriteLine("MinorVersion: {0}", totalBuffer[5]);
                            //4. Operation, will be 5 (request,onewayrequest...)
                            Console.WriteLine("Operation: {0}", (UInt16)(totalBuffer[6] & 0xFF | totalBuffer[7] << 8));
                            //5. TcpContentDelimiter and ContentLength
                            var header = (UInt16)(totalBuffer[8] & 0xFF | totalBuffer[9] << 8);
                            if (header == 1)
                            {
                                Console.WriteLine("Chunked: {0}", true);
                            }
                            else
                            {
                                Console.WriteLine("ContentLength: {0}"
                                                  , (int)((totalBuffer[10] & 0xFF)
                                                          | totalBuffer[11] << 8
                                                          | totalBuffer[12] << 16
                                                          | totalBuffer[13] << 24));
                            }

                            #region 6. ReadHeaders ITransportHeaders
                            Console.WriteLine("---- ITransportHeaders ----");
                            var index      = header == 1 ? 9 : 13;
                            var headerType = ReadUInt16(ref index);
                            while (headerType != TcpHeaders.EndOfHeaders)
                            {
                                if (headerType == TcpHeaders.Custom)
                                {
                                    Console.WriteLine("{0}: {1}", ReadCountedString(ref index), ReadCountedString(ref index));
                                }
                                else if (headerType == TcpHeaders.RequestUri)
                                {
                                    Console.WriteLine("RequestUri-Format: {0}", ReadByte(ref index));
                                    Console.WriteLine("RequestUri: {0}", ReadCountedString(ref index));
                                }
                                else if (headerType == TcpHeaders.StatusCode)
                                {
                                    Console.WriteLine("StatusCode-Format: {0}", ReadByte(ref index));
                                    var code = ReadUInt16(ref index);
                                    Console.WriteLine("StatusCode: {0}", code);
                                    //if (code != 0) error = true;
                                }
                                else if (headerType == TcpHeaders.StatusPhrase)
                                {
                                    Console.WriteLine("StatusPhrase-Format: {0}", ReadByte(ref index));
                                    Console.WriteLine("StatusPhrase: {0}", ReadCountedString(ref index));
                                }
                                else if (headerType == TcpHeaders.ContentType)
                                {
                                    Console.WriteLine("ContentType-Format: {0}", ReadByte(ref index));
                                    Console.WriteLine("ContentType: {0}", ReadCountedString(ref index));
                                }
                                else
                                {
                                    var headerFormat = (byte)ReadByte(ref index);

                                    switch (headerFormat)
                                    {
                                    case TcpHeaderFormat.Void: break;

                                    case TcpHeaderFormat.CountedString: ReadCountedString(ref index); break;

                                    case TcpHeaderFormat.Byte: ReadByte(ref index); break;

                                    case TcpHeaderFormat.UInt16: ReadUInt16(ref index); break;

                                    case TcpHeaderFormat.Int32: ReadInt32(ref index); break;

                                    default:
                                        throw new RemotingException("Remoting_Tcp_UnknownHeaderType");
                                    }
                                }

                                headerType = ReadUInt16(ref index);
                            }
                            #endregion

                            //7. RequestStream/Message
                            var requestStream = new byte[totalBuffer.Length - index - 1];
                            Buffer.BlockCopy(totalBuffer, index + 1, requestStream, 0, totalBuffer.Length - index - 1);
                            //using BinaryFormatterSink default
                            var requestMessage = BinaryFormatterHelper.DeserializeObject(requestStream) as MethodCall;
                            DumpHelper.DumpMessage(requestMessage);
                            #endregion

                            buffers     = new StringBuilder();
                            totalBuffer = new byte[0];

                            #region Write Response

                            //http://labs.developerfusion.co.uk/SourceViewer/browse.aspx?assembly=SSCLI&namespace=System.Runtime.Remoting
                            //else if (name.Equals("__Return"))
                            var responeMessage = new MethodResponse(
                                //just return args[0]
                                new Header[] { new Header("__Return", requestMessage.Args[0]) }
                                , requestMessage);

                            //responeMessage.ReturnValue//can not set
                            var responseStream = BinaryFormatterHelper.SerializeObject(responeMessage);
                            //1.Preamble
                            var preamble = Encoding.ASCII.GetBytes(".NET");
                            foreach (var b in preamble)
                            {
                                WriteByte(b);
                            }
                            //2.MajorVersion
                            WriteByte((byte)1);
                            //3.MinorVersion
                            WriteByte((byte)0);
                            //4.Operation
                            WriteUInt16(TcpOperations.Reply);
                            //5.TcpContentDelimiter and ContentLength
                            WriteUInt16(0);
                            WriteInt32(responseStream.Length);
                            //6.Headers
                            WriteUInt16(TcpHeaders.EndOfHeaders);
                            //7.ResponseStream/Message
                            foreach (var b in responseStream)
                            {
                                WriteByte(b);
                            }
                            #endregion

                            e.SetBuffer(totalBuffer, 0, totalBuffer.Length);
                            if (!e.AcceptSocket.SendAsync(e))
                            {
                                this.ProcessSend(e);
                            }
                        }
                        else if (!e.AcceptSocket.ReceiveAsync(e))
                        {
                            this.ProcessReceive(e);
                        }
                    }
                    else
                    {
                        //this.ProcessError(e);
                    }
                }
                else
                {
                    //this.CloseClientSocket(e);
                }
            }
示例#22
0
 public void Save(string key, object obj)
 {
     _accessor.Save(key, BinaryFormatterHelper.Serialize(obj));
 }