public static UInt64 Hash(this Schema s)
        {
            var Types = s.GetMap().OrderBy(t => t.Key, StringComparer.Ordinal).Select(t => t.Value).ToList();
            var TypesWithoutDescription = Types.Select(t => MapWithoutDescription(t)).ToList();

            var sha = new SHA256CryptoServiceProvider();

            Byte[] result;

            using (var ms = Streams.CreateMemoryStream())
            {
                bs.Value.Write(TypesWithoutDescription, ms);
                ms.Position = 0;

                result = sha.ComputeHash(ms.ToUnsafeStream());
            }

            using (var ms = Streams.CreateMemoryStream())
            {
                ms.Write(result.Skip(result.Length - 8).ToArray());
                ms.Position = 0;

                return(ms.ReadUInt64B());
            }
        }
 public XElement BinaryToTree(Byte[] b)
 {
     using (var s = Streams.CreateMemoryStream())
     {
         s.Write(b);
         s.Position = 0;
         var v = bs.Read <T>(s);
         return(xs.Write(v));
     }
 }
            public Byte[] TreeToBinary(XElement x)
            {
                var v = xs.Read <T>(x);

                using (var s = Streams.CreateMemoryStream())
                {
                    bs.Write(v, s);
                    s.Position = 0;
                    return(s.Read((int)(s.Length)));
                }
            }
Example #4
0
        public static void ExpressionSchemaToBinary(List <String> DataDirs, String BinaryPath)
        {
            var ExpressionSchema = GetExpressionSchema();
            var eal = new ExpressionAssemblyLoader(ExpressionSchema);

            foreach (var DataDir in DataDirs)
            {
                foreach (var tf in Directory.EnumerateFiles(DataDir, "*.tree", SearchOption.AllDirectories))
                {
                    eal.LoadAssembly(tf);
                }
            }
            var a  = eal.GetResult();
            var bs = BinarySerializerWithString.Create();

            Byte[] Compiled;
            using (var ms = Streams.CreateMemoryStream())
            {
                bs.Write(a, ms);
                ms.Position = 0;
                Compiled    = ms.Read((int)(ms.Length));
            }
            if (File.Exists(BinaryPath))
            {
                Byte[] Original;
                using (var fs = Streams.OpenReadable(BinaryPath))
                {
                    Original = fs.Read((int)(fs.Length));
                }
                if (Compiled.SequenceEqual(Original))
                {
                    return;
                }
            }
            var BinaryDir = FileNameHandling.GetFileDirectory(BinaryPath);

            if (BinaryDir != "" && !Directory.Exists(BinaryDir))
            {
                Directory.CreateDirectory(BinaryDir);
            }
            using (var fs = Streams.CreateWritable(BinaryPath))
            {
                fs.Write(Compiled);
            }
        }
        public static Byte[] GetUnifiedBinaryRepresentation(this Schema s)
        {
            var Modules = s.Modules.Select(m => new ModuleDecl {
                Name = m.Name, Functions = m.Functions.OrderBy(f => f.Name, StringComparer.OrdinalIgnoreCase).ToList(), Description = ""
            }).OrderBy(m => m.Name, StringComparer.OrdinalIgnoreCase).ToList();
            var ss = new Schema {
                Modules = Modules, Imports = new List <String> {
                }
            };

            var bs = Niveum.ObjectSchema.BinarySerializerWithString.Create();

            using (var ms = Streams.CreateMemoryStream())
            {
                bs.Write(ss, ms);
                ms.Position = 0;

                var Bytes = ms.Read((int)(ms.Length));
                return(Bytes);
            }
        }
Example #6
0
        public String Write(List <TypeDef> Types, String Comment = null)
        {
            var f = WriteToForest(Types, Comment);

            String Compiled;

            using (var ms = Streams.CreateMemoryStream())
            {
                using (var tw = Txt.CreateTextWriter(ms.Partialize(0, Int64.MaxValue, 0).AsNewWriting(), TextEncoding.UTF8))
                {
                    var sw = new TreeFormatSyntaxWriter(tw);
                    sw.Write(f);
                }
                ms.Position = 0;
                using (var tr = Txt.CreateTextReader(ms.Partialize(0, ms.Length).AsNewReading(), TextEncoding.UTF8))
                {
                    Compiled = tr.ReadToEnd();
                }
            }
            return(Compiled);
        }
 public BinaryCountPacketServer(IBinarySerializationServerAdapter SerializationServerAdapter, CheckCommandAllowedDelegate CheckCommandAllowed, IBinaryTransformer Transformer = null, int ReadBufferSize = 8 * 1024)
 {
     this.ss = SerializationServerAdapter;
     this.c  = new Context(ReadBufferSize);
     this.CheckCommandAllowed = CheckCommandAllowed;
     this.Transformer         = Transformer;
     this.ss.ServerEvent     += (CommandName, CommandHash, Parameters) =>
     {
         var    CommandNameBytes = TextEncoding.UTF16.GetBytes(CommandName);
         Byte[] Bytes;
         using (var ms = Streams.CreateMemoryStream())
         {
             ms.WriteInt32(CommandNameBytes.Length);
             ms.Write(CommandNameBytes);
             ms.WriteUInt32(CommandHash);
             ms.WriteInt32(Parameters.Length);
             ms.Write(Parameters);
             ms.Position = 0;
             Bytes       = ms.Read((int)(ms.Length));
         }
         var BytesLength = Bytes.Length;
         lock (c.WriteBufferLockee)
         {
             if (Transformer != null)
             {
                 Transformer.Transform(Bytes, 0, BytesLength);
             }
             c.WriteBuffer.Add(Bytes);
         }
         if (OutputByteLengthReport != null)
         {
             OutputByteLengthReport(CommandName, BytesLength);
         }
         if (this.ServerEvent != null)
         {
             this.ServerEvent();
         }
     };
 }
        public static UInt64 Hash(this Schema s)
        {
            var Bytes = GetUnifiedBinaryRepresentation(s);
            var sha   = new SHA256CryptoServiceProvider();

            Byte[] result;

            using (var ms = Streams.CreateMemoryStream())
            {
                ms.Write(Bytes);
                ms.Position = 0;

                result = sha.ComputeHash(ms.ToUnsafeStream());
            }

            using (var ms = Streams.CreateMemoryStream())
            {
                ms.Write(result.Skip(result.Length - 8).ToArray());
                ms.Position = 0;

                return(ms.ReadUInt64B());
            }
        }
        public StreamedVirtualTransportServerHandleResult Handle(int Count)
        {
            var ret = StreamedVirtualTransportServerHandleResult.CreateContinue();

            var Buffer        = c.ReadBuffer.Array;
            var FirstPosition = c.ReadBuffer.Offset;
            var BufferLength  = c.ReadBuffer.Offset + c.ReadBuffer.Count;

            if (Transformer != null)
            {
                Transformer.Inverse(Buffer, BufferLength, Count);
            }
            BufferLength += Count;

            while (true)
            {
                var r = TryShift(c, Buffer, FirstPosition, BufferLength - FirstPosition);
                if (r == null)
                {
                    break;
                }
                FirstPosition = r.Position;

                if (r.Command != null)
                {
                    var CommandName = r.Command.CommandName;
                    var CommandHash = r.Command.CommandHash;
                    var Parameters  = r.Command.Parameters;
                    if (InputByteLengthReport != null)
                    {
                        InputByteLengthReport(CommandName, r.Command.ByteLength);
                    }
                    if (ss.HasCommand(CommandName, CommandHash) && (CheckCommandAllowed != null ? CheckCommandAllowed(CommandName) : true))
                    {
                        ret = StreamedVirtualTransportServerHandleResult.CreateCommand(new StreamedVirtualTransportServerHandleResultCommand
                        {
                            CommandName    = CommandName,
                            ExecuteCommand = (OnSuccess, OnFailure) =>
                            {
                                Action <Byte[]> OnSuccessInner = OutputParameters =>
                                {
                                    var CommandNameBytes = TextEncoding.UTF16.GetBytes(CommandName);
                                    Byte[] Bytes;
                                    using (var ms = Streams.CreateMemoryStream())
                                    {
                                        ms.WriteInt32(CommandNameBytes.Length);
                                        ms.Write(CommandNameBytes);
                                        ms.WriteUInt32(CommandHash);
                                        ms.WriteInt32(OutputParameters.Length);
                                        ms.Write(OutputParameters);
                                        ms.Position = 0;
                                        Bytes       = ms.Read((int)(ms.Length));
                                    }
                                    var BytesLength = Bytes.Length;
                                    lock (c.WriteBufferLockee)
                                    {
                                        if (Transformer != null)
                                        {
                                            Transformer.Transform(Bytes, 0, BytesLength);
                                        }
                                        c.WriteBuffer.Add(Bytes);
                                    }
                                    if (OutputByteLengthReport != null)
                                    {
                                        OutputByteLengthReport(CommandName, BytesLength);
                                    }
                                    OnSuccess();
                                };
                                ss.ExecuteCommand(CommandName, CommandHash, Parameters, OnSuccessInner, OnFailure);
                            }
                        });
                    }
                    else
                    {
                        ret = StreamedVirtualTransportServerHandleResult.CreateBadCommand(new StreamedVirtualTransportServerHandleResultBadCommand {
                            CommandName = CommandName
                        });
                    }
                    break;
                }
            }

            if (BufferLength >= Buffer.Length && FirstPosition > 0)
            {
                var CopyLength = BufferLength - FirstPosition;
                for (int i = 0; i < CopyLength; i += 1)
                {
                    Buffer[i] = Buffer[FirstPosition + i];
                }
                BufferLength  = CopyLength;
                FirstPosition = 0;
            }
            if (FirstPosition >= BufferLength)
            {
                c.ReadBuffer = new ArraySegment <Byte>(Buffer, 0, 0);
            }
            else
            {
                c.ReadBuffer = new ArraySegment <Byte>(Buffer, FirstPosition, BufferLength - FirstPosition);
            }

            return(ret);
        }
Example #10
0
        private static Regex r = new Regex(@"^/(?<CommandName>\S+)(\s+(?<Params>.*))?$", RegexOptions.ExplicitCapture); //Regex是线程安全的
        private void Button_Send_Click(object sender, RoutedEventArgs e)
        {
            if (sock == null)
            {
                throw new InvalidOperationException();
            }

            var Str = TextBox_Send.Text;
            var m   = GetMode();

            Byte[] SendBuffer;
            if (m == Mode.Escaped)
            {
                Str        = Str.Descape();
                SendBuffer = Encoding.UTF8.GetBytes(Str);
            }
            else if (m == Mode.Binary)
            {
                var Sche  = Schema();
                var a     = SchemaAssembly();
                var Lines = Regex.Split(Str, @"\n|\r\n").Select(l => l.Trim(' ')).Where(l => l != "").ToList();
                using (var s = Streams.CreateMemoryStream())
                {
                    foreach (var Line in Lines)
                    {
                        var ma = r.Match(Line);
                        if (!ma.Success)
                        {
                            throw new InvalidOperationException("InvalidLine: " + Line);
                        }
                        var CommandName = ma.Result("${CommandName}");
                        var CommandDef  = Sche.Types.Where(t => t.FullName() == CommandName && t.Version() == "").Single();
                        var jParameters = JToken.Parse(ma.Result("${Params}"));
                        var tRequest    = a.GetType(CommandName + "Request");
                        var oRequest    = a.GetType("JsonTranslator").GetMethod(CommandName + "RequestFromJson").Invoke(null, new Object[] { jParameters });
                        var Parameters  = (Byte[])a.GetType("BinaryTranslator").GetMethod("Serialize").MakeGenericMethod(tRequest).Invoke(null, new Object[] { oRequest });
                        var CommandHash = (UInt32)(Sche.GetSubSchema(new TypeDef[] { CommandDef }, new TypeSpec[] { }).GetNonversioned().GetNonattributed().Hash().Bits(31, 0));

                        var CommandNameBytes = TextEncoding.UTF16.GetBytes(CommandName);
                        s.WriteInt32(CommandNameBytes.Length);
                        s.Write(CommandNameBytes);
                        s.WriteUInt32(CommandHash);
                        s.WriteInt32(Parameters.Length);
                        s.Write(Parameters);
                    }
                    s.Position = 0;
                    SendBuffer = s.Read((int)(s.Length));
                }
            }
            else if (m == Mode.Line)
            {
                var Lines = Regex.Split(Str, @"\n|\r\n").Select(l => l.Trim(' ')).Where(l => l != "").ToList();
                Str        = String.Join("\r\n", Lines) + "\r\n";
                SendBuffer = Encoding.UTF8.GetBytes(Str);
            }
            else
            {
                throw new InvalidOperationException();
            }

            Action Completed = () => this.Dispatcher.BeginInvoke((Action)(() =>
            {
            }));
            Action <SocketError> Faulted = se => this.Dispatcher.BeginInvoke((Action)(() =>
            {
                MessageBox.Show(this, (new SocketException((int)se)).Message, "Error");
                ForceDisconnect();
            }));

            sock.SendAsync(SendBuffer, 0, SendBuffer.Length, Completed, Faulted);
        }