Ejemplo n.º 1
0
        public static Commit GetCommit(this IDataRecord record, ISerialize serializer)
        {
            var headers = serializer.Deserialize(record, HeadersIndex) as IDictionary<string, object>;
            var events = serializer.Deserialize(record, PayloadIndex) as ICollection<EventMessage>;
            var snapshot = serializer.Deserialize(record, SnapshotIndex);

            return new Commit(
                record[StreamIdIndex].ToGuid(),
                record[CommitIdIndex].ToGuid(),
                (long)record[StreamRevisionIndex],
                (long)record[CommitSequenceIndex],
                headers,
                events,
                snapshot);
        }
Ejemplo n.º 2
0
 public static Snapshot GetSnapshot(this IDataRecord record, ISerialize serializer)
 {
     return new Snapshot(
         record[StreamIdIndex].ToGuid(),
         record[StreamRevisionIndex].ToInt(),
         serializer.Deserialize<object>(record, PayloadIndex));
 }
Ejemplo n.º 3
0
        public static Task <ICommit> GetCommit(this IDataRecord record, ISerialize serializer, ISqlDialect sqlDialect)
        {
            Logger.Verbose(Messages.DeserializingCommit, serializer.GetType());
            var headers = serializer.Deserialize <Dictionary <string, object> >(record, HeadersIndex);
            var events  = serializer.Deserialize <List <EventMessage> >(record, PayloadIndex);

            var commit = new Commit(record[BucketIdIndex].ToString(),
                                    record[StreamIdOriginalIndex].ToString(),
                                    record[StreamRevisionIndex].ToInt(),
                                    record[CommitIdIndex].ToGuid(),
                                    record[CommitSequenceIndex].ToInt(),
                                    sqlDialect.ToDateTime(record[CommitStampIndex]),
                                    new LongCheckpoint(record[CheckpointIndex].ToLong()).Value,
                                    headers,
                                    events);

            return(Task.FromResult <ICommit>(commit));
        }
Ejemplo n.º 4
0
 public Input PostInputData(HttpListenerContext context)
 {
     using (StreamReader streamReader = new StreamReader(context.Request.InputStream))
     {
         String strReader = streamReader.ReadToEnd();
         Input  input     = serializer.Deserialize <Input>(strReader);
         return(input);
     }
 }
Ejemplo n.º 5
0
 public virtual T Deserialize <T>(Stream input)
 {
     if (Logger.IsVerboseEnabled)
     {
         Logger.Verbose(Messages.DeserializingStream, typeof(T));
     }
     using (var decompress = new DeflateStream(input, CompressionMode.Decompress, true))
         return(_inner.Deserialize <T>(decompress));
 }
Ejemplo n.º 6
0
        static void InitializeParty()
        {
            isOkListen = false;

            #region Initialization Card
            Deck <Card> cards = InitializeCard();
            #endregion

            #region Assign Class
            Deck <Character> characters = ISerialize.Deserialize <Deck <Character> >(@"_Datas\Characters.json");
            foreach (Client client in clients)
            {
                client.character = characters.GetRandomElement(rand, true);
            }
            #endregion

            #region Assign Role
            int numberPlayer = clients.Count;
            if (numberPlayer == 2)
            {
                AssignRole(numberPlayer, 1, 0, 0, 1);
            }
            if (numberPlayer == 4)
            {
                AssignRole(numberPlayer, 1, 0, 1, 2);
            }
            else if (numberPlayer == 5)
            {
                AssignRole(numberPlayer, 1, 1, 1, 2);
            }
            else if (numberPlayer == 6)
            {
                AssignRole(numberPlayer, 1, 1, 1, 3);
            }
            else if (numberPlayer == 7)
            {
                AssignRole(numberPlayer, 1, 2, 1, 3);
            }
            #endregion

            #region Assign Card
            foreach (Client client in clients)
            {
                client.SetCards(cards.PopFirstElement(client.character.maxLife));
            }
            #endregion

            #region Create GameState
            gameState = new GameState(clients, cards);
            #endregion

            #region Start GameLoop
            gameLoop = new Thread(GameLoop);
            gameLoop.Start();
            isOkListenMJ = false;
            #endregion
        }
Ejemplo n.º 7
0
        public static Snapshot GetSnapshot(this IDataRecord record, ISerialize serializer)
        {
            Logger.Verbose(Messages.DeserializingSnapshot);

            return(new Snapshot(
                       record[StreamIdIndex].ToGuid(),
                       record[StreamRevisionIndex].ToInt(),
                       serializer.Deserialize <object>(record, PayloadIndex)));
        }
Ejemplo n.º 8
0
 public T Deserialize <T>(object document)
 {
     if (Logger.IsVerboseEnabled)
     {
         Logger.Verbose(Messages.DeserializingStream, typeof(T));
     }
     byte[] bytes = FromBase64(document as string) ?? document as byte[];
     return(_serializer.Deserialize <T>(bytes));
 }
        public static Snapshot GetSnapshot(this IDataRecord record, ISerialize serializer, string streamIdOriginal)
        {
            Logger.Verbose(Messages.DeserializingSnapshot);

            return new Snapshot(
                record[BucketIdIndex].ToString(),
                streamIdOriginal,
                record[StreamRevisionIndex].ToInt(),
                serializer.Deserialize<object>(record, PayloadIndex));
        }
        private CommitAttempt EmulateSerializationDeserialization(CommitAttempt attempt)
        {
            // serialization
            var headersPayload = serializer.Serialize(attempt.Headers);
            var eventsPayload  = serializer.Serialize(attempt.Events.ToList());
            // deserialization
            var headers = serializer.Deserialize <Dictionary <string, object> >(headersPayload);
            var events  = serializer.Deserialize <List <EventMessage> >(eventsPayload);

            return(new CommitAttempt(
                       attempt.BucketId,
                       attempt.StreamId,
                       attempt.StreamRevision,
                       attempt.CommitId,
                       attempt.CommitSequence,
                       attempt.CommitStamp,
                       headers,
                       events));
        }
Ejemplo n.º 11
0
        public static Snapshot GetSnapshot(this IDataRecord record, ISerialize serializer, string streamIdOriginal)
        {
            Logger.LogTrace(Messages.DeserializingSnapshot);

            return(new Snapshot(
                       record[BucketIdIndex].ToString(),
                       streamIdOriginal,
                       record[StreamRevisionIndex].ToInt(),
                       serializer.Deserialize <object>(record, PayloadIndex)));
        }
Ejemplo n.º 12
0
        public static List<EventMessage> ToEventList(this BsonValue value, ISerialize serializer)
        {
            if (serializer == null)
                return new List<EventMessage>();

            if (!(serializer is MongoSerializer))
                return serializer.Deserialize<List<EventMessage>>(value.AsByteArray);

            return value.AsBsonArray.Select(item => BsonSerializer.Deserialize<EventMessage>(item.AsBsonDocument)).ToList();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Deserializes the array of bytes provided.
        /// </summary>
        /// <typeparam name="T">The type of object to be deserialized.</typeparam>
        /// <param name="serializer">The serializer to use.</param>
        /// <param name="serialized">The serialized array of bytes.</param>
        /// <returns>The reconstituted object, if any.</returns>
        public static T Deserialize <T>(this ISerialize serializer, byte[] serialized)
        {
            serialized = serialized ?? new byte[] {};
            if (serialized.Length == 0)
            {
                return(default(T));
            }

            using (var stream = new MemoryStream(serialized))
                return(serializer.Deserialize <T>(stream));
        }
Ejemplo n.º 14
0
 public static Commit ToCommit(this RavenCommit commit, ISerialize serializer)
 {
     return new Commit(
         commit.StreamId,
         commit.StreamRevision,
         commit.CommitId,
         commit.CommitSequence,
         commit.CommitStamp,
         commit.Headers,
         serializer.Deserialize<List<EventMessage>>(commit.Payload));
 }
Ejemplo n.º 15
0
        void EventAppeared(EventStoreCatchUpSubscription sub, ResolvedEvent evnt)
        {
            var type = Type.GetType(evnt.Event.EventType);

            var json = UTF8Encoding.Default.GetString(evnt.Event.Data);
            var msg  = (Message)_serializer.Deserialize(json, type);

            var worker = FindWorker(msg.ActorId);

            worker.EnqueueKick(msg.ActorId);
        }
Ejemplo n.º 16
0
 static void WaitingData()
 {
     while (true)
     {
         byte[] bytes  = new byte[DataToSend.bufferSize];
         int    result = stream.Read(bytes, 0, bytes.Length);
         if (result == -1)
         {
             continue;
         }
         DataToSend data = (DataToSend)ISerialize.Deserialize(bytes);
         DispatcherReceive(data);
     }
 }
Ejemplo n.º 17
0
        static void GameLoop()
        {
            while (true)
            {
                #region CheckEndGame
                Role winner = gameState.CheckEndGame();
                if (winner != Role.None)
                {
                    Client sherif = clients[gameState.IndexSherif];

                    IEnumerable <Client> adjudants = clients.Where(x => x.role == Role.Adjudant);

                    IEnumerable <Client> renegats = clients.Where(x => x.role == Role.Renegat);

                    IEnumerable <Client> horslaloi = clients.Where(x => x.role == Role.HorsLaLoi);

                    if (winner == Role.Sherif)
                    {
                        SendMessageToAll(new DataToSend(myIP, Command.StringToDraw, "La partie est finie !"));
                        SendMessage(clients.Where(x => x.role == Role.Sherif || x.role == Role.Adjudant), "Vous avez gagnés la partie !");
                        SendMessage(clients.Where(x => x.role == Role.HorsLaLoi || x.role == Role.Renegat), "Vous avez perdus la partie !");
                    }
                    else if (winner == Role.Renegat)
                    {
                        SendMessageToAll(new DataToSend(myIP, Command.StringToDraw, "La partie est finie !"));
                        SendMessage(clients.Where(x => x.role == Role.Renegat), "Vous avez gagnés la partie !");
                        SendMessage(clients.Where(x => x.role == Role.HorsLaLoi || x.role == Role.Sherif || x.role == Role.Adjudant), "Vous avez perdus la partie !");
                    }
                    else if (winner == Role.HorsLaLoi)
                    {
                        SendMessageToAll(new DataToSend(myIP, Command.StringToDraw, "La partie est finie !"));
                        SendMessage(clients.Where(x => x.role == Role.HorsLaLoi), "Vous avez gagnés la partie !");
                        SendMessage(clients.Where(x => x.role == Role.Renegat || x.role == Role.Sherif || x.role == Role.Adjudant), "Vous avez perdus la partie !");
                    }

                    gameLoop.Abort();
                }
                #endregion

                Client currentPlayer = gameState.currentPlayer;
                SendMessage(currentPlayer.ID, new DataToSend(myIP, Command.StringToDraw, "C'est votre tour !"));
                byte[] bytes = currentPlayer.ReceiveMessage(DataToSend.bufferSize);
                if (bytes.Length == 0)
                {
                    continue;
                }
                Dispatcher((DataToSend)ISerialize.Deserialize(bytes));
            }
        }
Ejemplo n.º 18
0
        public virtual T Deserialize <T>(Stream input)
        {
            Logger.Verbose(Messages.DeserializingStream, typeof(T));

            using (var aes = new AesManaged())
            {
                aes.Key  = _encryptionKey;
                aes.IV   = GetInitVectorFromStream(input, aes.IV.Length);
                aes.Mode = CipherMode.CBC;

                using (ICryptoTransform decryptor = aes.CreateDecryptor())
                    using (var decryptedStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
                        return(_inner.Deserialize <T>(decryptedStream));
            }
        }
Ejemplo n.º 19
0
        public virtual T Deserialize <T>(Stream input)
        {
            Logger.LogTrace(Messages.DeserializingStream, typeof(T));

            using (var rijndael = new RijndaelManaged())
            {
                rijndael.Key  = _encryptionKey;
                rijndael.IV   = GetInitVectorFromStream(input, rijndael.IV.Length);
                rijndael.Mode = CipherMode.CBC;

                using (ICryptoTransform decryptor = rijndael.CreateDecryptor())
                    using (var decryptedStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
                        return(_inner.Deserialize <T>(decryptedStream));
            }
        }
Ejemplo n.º 20
0
        public T Deserialize <T>(Stream input)
        {
            var graph         = _inner.Deserialize <T>(input);
            var eventMessages = graph as List <EventMessage>;

            if (eventMessages != null)
            {
                foreach (var eventMessage in eventMessages)
                {
                    eventMessage.Body = _eventSerializerFunc().Deserialize((string)eventMessage.Body);
                }
            }

            return(graph);
        }
        public static T Deserialize <T>(this ISerialize serializer, IDataRecord record, int index)
        {
            if (index >= record.FieldCount)
            {
                return(default(T));
            }

            object value = record[index];

            if (value == null || value == DBNull.Value)
            {
                return(default(T));
            }

            if (serializer is JsonSerializer)
            {
                var json = (string)value;
                return(json.Length == 0 ? default(T) : serializer.Deserialize <T>(Encoding.UTF8.GetBytes(json)));
            }

            var bytes = (byte[])value;

            return(bytes.Length == 0 ? default(T) : serializer.Deserialize <T>(bytes));
        }
Ejemplo n.º 22
0
        public static T Deserialize <T>(this ISerialize serializer, IDataRecord record, int index)
        {
            if (index >= record.FieldCount)
            {
                return(default(T));
            }

            object value = record[index];

            if (value == null || value == DBNull.Value)
            {
                return(default(T));
            }

            var bytes = (byte[])value;

            return(bytes.Length == 0 ? default(T) : serializer.Deserialize <T>(bytes));
        }
Ejemplo n.º 23
0
        public static void ListenUdpBroadcast()
        {
            Socket     socketListener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint localEndPoint  = new IPEndPoint(IPAddress.Any, Port);

            socketListener.Bind(localEndPoint);
            byte[]   data     = new byte[1024 * 5];
            EndPoint endPoint = localEndPoint;

            Console.WriteLine("The server avaible (UDP)");
            while (true)
            {
                int          amount           = socketListener.ReceiveFrom(data, ref endPoint);
                MemoryStream messageContainer = new MemoryStream(data, 0, data.Length);
                messageContainer.Position = 0;
                MessageSearchRequest message = (MessageSearchRequest)messageSerializer.Deserialize(messageContainer,
                                                                                                   typeof(MessageSearchRequest), null);
                HandleSearchMessage(message);
            }
        }
Ejemplo n.º 24
0
        public async Task <Message> Invoke(Message message)
        {
            var result = message.CopyToResponse();
            //找到本地方法 调用
            byte   serializeType = message.SerializeType;
            string serverName    = message.ServerName;
            string methodName    = message.MessageName;

            try
            {
                ISerialize serialize   = SerializeManage.Instance.GetSerialize(serializeType);//获取序列化对象
                Type       serviceType = ServiceTypeManage.Instance.GetType(serverName);
                AssertUtils.IsNotNull(serviceType, ExceptionCode.NOTFOUND_ERROR, "服务不存在");

                object service = _rpcServiceProxyFactory.GetService(serviceType); // _serviceProvider.GetService(serviceType);
                //object service = _serviceProvider.GetService(serviceType);
                MethodInfo      methodInfo     = service.GetType().GetMethod(methodName);
                ParameterInfo[] parameterInfos = methodInfo.GetParameters();
                object[]        inParms        = null;
                if (parameterInfos.Length > 0)
                {
                    object requestObj = serialize.Deserialize(parameterInfos[0].ParameterType, message.Data);
                    inParms = new object[] { requestObj };
                }
                var callResult = await MethodUtils.InvokeMethodAsync(service, methodInfo, inParms) as RpcResult;

                AssertUtils.IsNotNull(callResult, ExceptionCode.INTETNAL_ERROR, "返回空");

                result.ReturnCode    = callResult != null ? callResult.Code : 0;
                result.ReturnMessage = callResult != null ? callResult.Message : "";

                result.Data = serialize.Serialize(GetRpcResultData(callResult));
            }
            catch (Exception ex)
            {
                result.ReturnCode    = ExceptionCode.INTETNAL_ERROR;
                result.ReturnMessage = "内部错误";
                _logger.Error($"{serverName}.{methodName}, {ex.Message},{ex.StackTrace}");
            }
            return(result);//serialize.Serialize(result);
        }
Ejemplo n.º 25
0
        public static void Initialize(ISerialize serializer)
        {
            var confPath = Files.GetConfigSpFile();

            if (File.Exists(confPath) && confPath.EndsWith(".json"))
            {
                try
                {
                    var value = serializer.Deserialize <ConfigDataSpecial>(File.ReadAllText(confPath));
                    _current = value;
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Failed to load special json config.\r\n\r\nMessage: {ex.Message}\r\nStack Trace: {ex.StackTrace}");
                }
            }
            else
            {
                _current = new ConfigDataSpecial(false);
            }

            _current.InitializeComponent();
        }
Ejemplo n.º 26
0
        static void ListenMJ()
        {
            if (clients.Count == 0)
            {
                Console.WriteLine("!!! Il n'y a aucun joueur de connecté !!!");
                return;
            }
            Client client = clients[0]; // FOR BUILD

            //Client client = clients[clients.Count - 1]; // FOR TEST
            Console.WriteLine("Actually listenning the client " + client.ID);
            SendMessage(client.ID, new DataToSend(myIP, Command.StringToDraw, "Il y a plusieurs joueurs de connecté"));
            //InitializeParty(); //HERE FOR TEST TO REMOVE FOR BUILD
            while (isOkListenMJ)
            {
                byte[] bytes = client.ReceiveMessage(DataToSend.bufferSize); // Peut être source de problème à check
                if (bytes.Length == 0)
                {
                    continue;
                }
                DataToSend data = (DataToSend)ISerialize.Deserialize(bytes);
                Dispatcher(data);
            }
        }
Ejemplo n.º 27
0
        static Deck <Card> InitializeCard() // A REVOIR
        {
            List <CardRepartition> cardRepartition = ISerialize.Deserialize <List <CardRepartition> >(@"_Datas/Cards.json");

            Deck <Card> cards = new Deck <Card>();

            foreach (CardRepartition CR in cardRepartition)
            {
                for (int i = 0; i < CR.number; i++)
                {
                    switch (CR.type)
                    {
                    case CardType.Bang:
                        Bang b = new Bang("Bang", (Couleur)rand.Next(0, 4), (Value)rand.Next(0, 13), Cible.APorteeDeTire, "Enlève un point de vie à un joueur à porté de tir", -1);
                        cards.Add(b);
                        break;

                    case CardType.Discard:
                        Discard d = new Discard("Discard", (Couleur)rand.Next(0, 4), (Value)rand.Next(0, 13), Cible.SoiMeme, "Fait échouer un Bang", -1);
                        cards.Add(d);
                        break;

                    case CardType.Draw:
                        Draw dd = new Draw("Draw", (Couleur)rand.Next(0, 4), (Value)rand.Next(0, 13), Cible.SoiMeme, "Pioche 2 cartes", -1);
                        cards.Add(dd);
                        break;

                    case CardType.Duel:
                        Duel ddd = new Duel("Duel", (Couleur)rand.Next(0, 4), (Value)rand.Next(0, 13), Cible.NimporteQui, "Provoque un duel", -1);
                        cards.Add(ddd);
                        break;

                    case CardType.Heal:
                        Heal h = new Heal("Heal", (Couleur)rand.Next(0, 4), (Value)rand.Next(0, 13), Cible.NimporteQui, "Soigne un point de vie", -1);
                        cards.Add(h);
                        break;

                    case CardType.Miss:
                        Miss m = new Miss("Miss", (Couleur)rand.Next(0, 4), (Value)rand.Next(0, 13), Cible.SoiMeme, "Esquive un Bang", -1);
                        cards.Add(m);
                        break;

                    case CardType.Jail:
                        Jail j = new Jail("Jail", (Couleur)rand.Next(0, 4), (Value)rand.Next(0, 13), Cible.NimporteQui, "Emprisonne quelqu'un");
                        cards.Add(j);
                        break;

                    case CardType.ModRange:
                        ModRange mr = new ModRange("Mustang", (Couleur)rand.Next(0, 4), (Value)rand.Next(0, 13), Cible.SoiMeme, "Distance +1 pour les autres joueurs");
                        cards.Add(mr);
                        break;

                    case CardType.Stash:
                        Stash s = new Stash("Stash", (Couleur)rand.Next(0, 4), (Value)rand.Next(0, 13), Cible.SoiMeme, "Quand Bang reçu, piocher une carte, si coeur alors esquive");
                        cards.Add(s);
                        break;

                    case CardType.Weapon:
                        Weapon w = new Weapon("Pistoulet", (Couleur)rand.Next(0, 4), (Value)rand.Next(0, 13), Cible.SoiMeme, "Augmente la porté de 1");
                        cards.Add(w);
                        break;

                    default:
                        break;
                    }
                }
            }

            cards.Shuffle();

            return(cards);
        }
Ejemplo n.º 28
0
 private GetEventStoreCommitAttempt.Dto DeserializeEvent(ResolvedEvent resolved)
 {
     return(_serializer.Deserialize <GetEventStoreCommitAttempt.Dto>(resolved.Event.Data));
 }
Ejemplo n.º 29
0
 public T Deserialize <T>(object document)
 {
     Logger.LogTrace(Messages.DeserializingStream, typeof(T));
     byte[] bytes = FromBase64(document as string) ?? document as byte[];
     return(_serializer.Deserialize <T>(bytes));
 }
Ejemplo n.º 30
0
        private void Port_OnReceived(object sender, PortReceivedEventArgs args)
        {
            if (args.Data.Length > BUFFER_SIZE)
            {
                _wOffset = 0;
                _rOffset = 0;
                _length  = 0;
                return;
            }
            if (BUFFER_SIZE >= _wOffset + args.Length)
            {
                Array.Copy(args.Data, 0, _buffer, _wOffset % BUFFER_SIZE, args.Length);
            }
            else
            {
                Array.Copy(args.Data, 0, _buffer, _wOffset % BUFFER_SIZE, BUFFER_SIZE - _wOffset);
                Array.Copy(args.Data, BUFFER_SIZE - _wOffset, _buffer, 0, (args.Length - (BUFFER_SIZE - _wOffset)) % BUFFER_SIZE);
            }
            _wOffset = (_wOffset + _length) % BUFFER_SIZE;
            _length += args.Length;
            if (BUFFER_SIZE < _length)
            {
                _rOffset = _wOffset;
                _length  = BUFFER_SIZE;
            }

            byte[] d;
            int    startOffset = -1;
            int    endOffset   = -1;

            for (int o = _rOffset, l = _length; (--l) > 0; o = (++o) % BUFFER_SIZE)
            {
                if ((byte)(0x80 + _AGVNo) == _buffer[o])
                {
                    startOffset = o;
                }
                else if ((byte)(0xFF - (0x80 + _AGVNo)) == _buffer[o])
                {
                    if (0 > startOffset)
                    {
                        continue;
                    }

                    endOffset = (o + 1) % BUFFER_SIZE;
                    if (startOffset < endOffset)
                    {
                        d = new byte[endOffset - startOffset];
                        Array.Copy(_buffer, startOffset, d, 0, d.Length);
                    }
                    else
                    {
                        d = new byte[(BUFFER_SIZE - startOffset + endOffset)];
                        Array.Copy(_buffer, startOffset, d, 0, BUFFER_SIZE - startOffset);
                        Array.Copy(_buffer, 0, d, BUFFER_SIZE - startOffset, endOffset);
                    }
                    _length    -= _rOffset < endOffset ? endOffset - _rOffset : BUFFER_SIZE - _rOffset + endOffset;
                    _rOffset    = endOffset;
                    startOffset = -1;
                    endOffset   = -1;

                    //TODO:d
                    try
                    {
                        TPosition pos   = default(TPosition);
                        TState    state = default(TState);
                        var       res   = _serialize.Deserialize <StateResult>(d);
                        if (res.UPHead == (0x80 + _AGVNo) && eAgvResultWord.State == res.CommandWord)
                        {
                            Position = (TPosition)System.Enum.ToObject(typeof(TPosition), res.NodeNumber);
                            State    = (TState)System.Enum.ToObject(typeof(TState), res.State);
                        }
                    }
                    catch
                    {
                        var code = BitConverter.ToString(d).Replace('-', ' '); //args.Data
                        Logger.LogInfo($"AGV{_AGVNo}:OnReceived, code:{code}");
                    }
                }
            }
        }
Ejemplo n.º 31
0
 /// <summary>
 /// 反序列化
 /// </summary>
 /// <typeparam name="T">原始对象类型</typeparam>
 /// <param name="binary">二进制数据</param>
 /// <returns>原始对象</returns>
 public static T Deserialize <T>(byte[] binary)
 {
     return((T)DefaultSerializer.Deserialize(binary));
 }
Ejemplo n.º 32
0
        public static void Load()
        {
            ArrayList ClassList = new ArrayList();

            if (!File.Exists("Scriptsave.bin") && !File.Exists("Scriptsave.idx"))
            {
                return;
            }

            Console.Write("Scriptsave: Loading...");

            using (FileStream idx = new FileStream("Scriptsave.idx", FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                BinaryFileReader idxReader = new BinaryFileReader(new BinaryReader(idx));

                int Count = idxReader.ReadInt();

                for (int i = 0; i < Count; i++)
                {
                    string ClassName = idxReader.ReadString();

                    ConstructorInfo info = Utility.FindConstructor(ClassName);

                    if (info == null)
                    {
                        Console.WriteLine("failed");
                        Console.WriteLine("Error: Type '{0}' was not found. Delete this type? (y/n)", ClassName);

                        if (Console.ReadLine() == "y")
                        {
                            Console.Write("Scriptsave: Loading...");
                            idxReader.ReadLong();
                            idxReader.ReadInt();
                        }
                        else
                        {
                            Console.WriteLine("Type will not be deleted. An exception will be thrown when you press return");
                            Console.ReadLine();
                            throw new Exception(String.Format("Bad type '{0}'", ClassName));
                        }
                    }
                    else
                    {
                        long pos    = idxReader.ReadLong();
                        int  length = idxReader.ReadInt();
                        if (info.Invoke(null) is ISerialize)
                        {
                            ClassList.Add(new ClassEntry(ClassName, pos, length));
                        }
                        else
                        {
                            Console.WriteLine("failed");
                            Console.WriteLine("Error: Type '{0}' is not ISerialize. Delete this type? (y/n)", ClassName);
                            if (Console.ReadLine() == "y")
                            {
                                Console.Write("Scriptsave: Loading...");
                            }
                            else
                            {
                                Console.WriteLine("Type will not be deleted. An exception will be thrown when you press return");
                                Console.ReadLine();
                                throw new Exception(String.Format("Bad type '{0}'", ClassName));
                            }
                        }
                    }
                }
            }

            if (File.Exists("Scriptsave.bin"))
            {
                using (FileStream bin = new FileStream("Scriptsave.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin));

                    for (int i = 0; i < ClassList.Count; ++i)
                    {
                        ClassEntry entry = (ClassEntry)ClassList[i];
                        ISerialize ser   = entry.Class;

                        reader.Seek(entry.Position, SeekOrigin.Begin);

                        ser.Deserialize(reader);
                        if (reader.Position != (entry.Position + entry.Length))
                        {
                            Console.WriteLine("failed");
                            Console.WriteLine(String.Format("***** Bad serialize on '{0}' type *****", entry.ClassName));
                            Console.WriteLine("Do you want to remove this serialize? (y/n)");
                            string FailName = entry.ClassName;
                            if (Console.ReadLine() == "y")
                            {
                                ClassList.RemoveAt(i);
                                BinaryFileWriter idx = new BinaryFileWriter("Scriptsave.idx");
                                idx.Write(ClassList.Count);
                                foreach (ClassEntry classentry in ClassList)
                                {
                                    idx.Write(classentry.ClassName);
                                    idx.Write(classentry.Position);
                                    idx.Write(classentry.Length);
                                }
                                idx.Close();
                                Console.WriteLine("Serialization of '" + FailName + "' removed.");
                                Console.WriteLine("An exception will be thrown when you press return");
                                Console.ReadLine();
                                throw new Exception(String.Format("Bad serialize"));
                            }
                            else
                            {
                                Console.WriteLine("Serialization of '" + FailName + "' don't removed.");
                                Console.WriteLine("An exception will be thrown when you press return");
                                Console.ReadLine();
                                throw new Exception(String.Format("Bad serialize"));
                            }
                        }
                    }
                    reader.Close();
                    Console.WriteLine("done");
                }
            }
        }
Ejemplo n.º 33
0
        public static Snapshot ToSnapshot(this RavenSnapshot snapshot, ISerialize serializer)
        {
            if (snapshot == null)
                return null;

            return new Snapshot(
                snapshot.StreamId,
                snapshot.StreamRevision,
                serializer.Deserialize<object>(snapshot.Payload));
        }
Ejemplo n.º 34
0
 public virtual T Deserialize <T>(Stream input)
 {
     Logger.LogTrace(Messages.DeserializingStream, typeof(T));
     using (var decompress = new DeflateStream(input, CompressionMode.Decompress, true))
         return(_inner.Deserialize <T>(decompress));
 }