コード例 #1
0
        public async Task can_append_and_query_events(SerializerType serializerType)
        {
            StoreOptions(_ =>
            {
                _.UseDefaultSerialization(serializerType: serializerType);
                _.UseNodaTime();
            });

            var startDate = DateTime.UtcNow;

            var streamId = Guid.NewGuid();

            var @event = new MonsterSlayed()
            {
                QuestId = Guid.NewGuid(),
                Name    = "test"
            };

            using (var session = theStore.OpenSession())
            {
                session.Events.Append(streamId, @event);
                session.SaveChanges();

                var streamState  = session.Events.FetchStreamState(streamId);
                var streamState2 = await session.Events.FetchStreamStateAsync(streamId);

                var streamState3 = session.Events.FetchStream(streamId, timestamp: startDate);
            }
        }
コード例 #2
0
        public static Handshake GetHandshakeResponse(this Handshake handshakeRequest, ICollection <string> subProtocols, byte maxSize)
        {
            Handshake handshakeResponse;

            if (handshakeRequest.ReservedOctets != 0)
            {
                handshakeResponse = new Handshake(HandshakeErrorCode.UseOfReservedBits);
            }
            else
            {
                SerializerType serializerType = handshakeRequest.SerializerType;

                string requestedSubprotocol = serializerType.GetSubProtocol();

                if (!subProtocols.Contains(requestedSubprotocol))
                {
                    handshakeResponse = new Handshake(HandshakeErrorCode.SerializerUnsupported);
                }
                else
                {
                    handshakeResponse = new Handshake(maxSize, serializerType);
                }
            }

            return(handshakeResponse);
        }
コード例 #3
0
        public static async Task <IAttempt <T> > TryGetSetAsync <T>(
            this ICacheService cacheService,
            string cacheKeyName,
            SerializerType serializerType,
            Func <CancellationToken, Task <T> > retrievalFromSourceAction,
            CancellationToken cancellationToken)
        {
            var attempt = await cacheService.TryGetAsync <T>(cacheKeyName, serializerType, cancellationToken);

            if (attempt.Successful)
            {
                return(attempt);
            }

            var value = await retrievalFromSourceAction(cancellationToken);

            var setAttempt = await cacheService.TrySetAsync(cacheKeyName, value, serializerType, cancellationToken);

            if (setAttempt.Successful)
            {
                return(Attempt.Success(value));
            }

            return(attempt);
        }
コード例 #4
0
        public void bug_1276_can_select_instant(SerializerType serializerType)
        {
            StoreOptions(_ => _.UseNodaTime());

            var dateTime   = DateTime.UtcNow;
            var instantUTC = Instant.FromDateTimeUtc(dateTime.ToUniversalTime());
            var testDoc    = TargetWithDates.Generate(dateTime);

            using (var session = theStore.OpenSession())
            {
                session.Insert(testDoc);
                session.SaveChanges();
            }

            using (var query = theStore.QuerySession())
            {
                var resulta = query.Query <TargetWithDates>()
                              .Where(c => c.Id == testDoc.Id)
                              .Single();

                var result = query.Query <TargetWithDates>()
                             .Where(c => c.Id == testDoc.Id)
                             .Select(c => new { c.Id, c.InstantUTC })
                             .Single();

                result.ShouldNotBeNull();
                result.Id.ShouldBe(testDoc.Id);
                ShouldBeEqualWithDbPrecision(result.InstantUTC, instantUTC);
            }
        }
コード例 #5
0
        public NLogWriterService(bool useFileLogging, SerializerType type)
        {
            _type = type;
            var config = LogManager.Configuration;

            if (config == null)
            {
                throw new Exception("Cannot load Nlog config. Please check and make sure NLog.config exists on server.");
            }

            LogManager.ReconfigExistingLoggers();

            foreach (var level in config.LoggingRules.SelectMany(rule => rule.Levels))
            {
                _enabledLogLevels.Add(FromNlogLevel(level));
            }

            _curLogger = LogManager.GetCurrentClassLogger();
            switch (type)
            {
            case SerializerType.Json:
                break;

            case SerializerType.Xml:
                _curSerializer = new XmlSerializer(typeof(LogObject));
                break;

            default:
                throw new ArgumentOutOfRangeException("type");
            }
        }
コード例 #6
0
        public Program(SerializerType serializerType)
        {
            this.init(serializerType);
            Task.Run(async() => {
                Stopwatch sw = new Stopwatch();

                sw.Start();
                await this.readAndDeserializeAll();
                await this.serializeAndWriteAll();
                sw.Stop();

                Console.Clear();
                Console.WriteLine(
                    $"Store has {Program.instance.store.Count} JSON files deserialized/serialized in {sw.ElapsedMilliseconds} miliseconds."
                    );
                Console.WriteLine(
                    Program.instance.exceptions.Count == 0
                                                ? "Reading/writing with no error."
                                                : $"Reading/writing with {Program.instance.exceptions.Count} error(s)."
                    );
#if !DEBUG
                Environment.Exit(0);
#endif
            });
        }
コード例 #7
0
        private bool IsXmlSerializer(ModelElement mel)
        {
            SerializerType serializer = mel is XsdMessage ? ((XsdMessage)mel).ServiceContractModel.SerializerType :
                                        ((XsdElementFault)mel).Operation.ServiceContractModel.SerializerType;

            return(serializer == SerializerType.XmlSerializer);
        }
コード例 #8
0
        private void SaveLoadConfigurationData(Role role, SerializerType serializer)
        {
            FileInfo          _fileInfo      = GetFileName(role, serializer, @"ConfigurationData{0}.{1}");
            ConfigurationData _configuration = null;

            switch (role)
            {
            case Role.Producer:
                _configuration = ReferenceConfiguration.LoadProducer();
                break;

            case Role.Consumer:
                _configuration = ReferenceConfiguration.LoadConsumer();
                break;

            default:
                break;
            }
            ConfigurationDataFactoryIO.Save <ConfigurationData>(_configuration, serializer, _fileInfo, (x, y, z) => { Console.WriteLine(z); });
            _fileInfo.Refresh();
            Assert.IsTrue(_fileInfo.Exists);
            ConfigurationData _mirror = ConfigurationDataFactoryIO.Load <ConfigurationData>(serializer, _fileInfo, (x, y, z) => { Console.WriteLine(z); }, () => { });

            ReferenceConfiguration.Compare(_configuration, _mirror);
        }
コード例 #9
0
        private static FileInfo GetFileName(Role role, SerializerType serializer, string fileNameTemplate)
        {
            string _extension = serializer == SerializerType.Xml ? "xml" : "json";
            string _fileName  = String.Format(fileNameTemplate, role, _extension);

            return(new FileInfo(_fileName));
        }
コード例 #10
0
        public static string ToXmlString <T>(this T input, SerializerType serializerType)
        {
            if (input == null)
            {
                return(String.Empty);
            }

            using (var stream = new MemoryStream())
            {
                if (serializerType == SerializerType.SoapFormatter)
                {
                    input.ToXml(stream);
                }
                else if (serializerType == SerializerType.XmlSerializer)
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    xmlSerializer.Serialize(stream, input);
                }
                else if (serializerType == SerializerType.DataContractSerializer)
                {
                    DataContractSerializer dcSerializer = new DataContractSerializer(input.GetType());
                    dcSerializer.WriteObject(stream, input);
                }

                stream.Position = 0;
                var sr = new StreamReader(stream);
                return(sr.ReadToEnd());
            }
        }
コード例 #11
0
ファイル: JWT.cs プロジェクト: gkurts/jwt
        public JsonWebToken(SerializerType serializerType)
        {
            switch (serializerType)
            {
            case SerializerType.DefaultSerializer:
                JsonSerializer = new DefaultJsonSerializer();
                break;

            case SerializerType.NewtonsoftJsonSerializer:
                JsonSerializer = new NewtonsoftJsonSerializer();
                break;

            case SerializerType.ServiceStackJsonSerializer:
                JsonSerializer = new ServiceStackJsonSerializer();
                break;

            default:
                JsonSerializer = new DefaultJsonSerializer();
                break;
            }

            HashAlgorithms = new Dictionary <JwtHashAlgorithm, Func <byte[], byte[], byte[]> >
            {
                { JwtHashAlgorithm.HS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return(sha.ComputeHash(value)); } } },
                { JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new HMACSHA384(key)) { return(sha.ComputeHash(value)); } } },
                { JwtHashAlgorithm.HS512, (key, value) => { using (var sha = new HMACSHA512(key)) { return(sha.ComputeHash(value)); } } }
            };
        }
コード例 #12
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="hostName"></param>
        /// <param name="userName"></param>
        /// <param name="port"></param>
        /// <param name="password"></param>
        /// <param name="maxQueueCount"></param>
        /// <param name="serializerType"></param>
        /// <param name="loger"></param>
        /// <param name="writeWorkerTaskNumber"></param>
        private RabbitMQClient(string hostName, string userName, string password, int?port, int maxQueueCount
                               , SerializerType serializerType, ILoger loger = null, short writeWorkerTaskNumber = 4)
        {
            factory          = new ConnectionFactory();
            factory.HostName = hostName;
            if (!port.HasValue || port.Value < 0)
            {
                factory.Port = 5672;
            }
            else
            {
                factory.Port = port.Value;
            }
            factory.Password = password;
            factory.UserName = userName;

            serializer = SerializerFactory.Create(serializerType);
            _queue     = new System.Collections.Concurrent.BlockingCollection <StrongBox <QueueMessage> >();

            _maxQueueCount = maxQueueCount > 0 ? maxQueueCount : Options.DefaultMaxQueueCount;


            this.loger = loger;

            var         scheduler   = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, writeWorkerTaskNumber).ExclusiveScheduler;
            TaskFactory taskFactory = new TaskFactory(scheduler);

            for (int i = 0; i < writeWorkerTaskNumber; i++)
            {
                taskFactory.StartNew(QueueToWrite, TaskCreationOptions.LongRunning);
            }
        }
コード例 #13
0
ファイル: Serialize.cs プロジェクト: ronin1/GeoDataSource
        public static bool SerializeBinaryToDisk <T>(T request, string filename,
                                                     SerializerType type = SerializerType.Default)
            where T : class
        {
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            using (var fs = new FileStream(filename, FileMode.CreateNew, FileAccess.Write))
            {
                switch (type)
                {
                case SerializerType.BinaryFormatter:
                {
                    new BinaryFormatter().Serialize(fs, request);
                    break;
                }

                default:
                {
                    Serializer.Serialize(fs, request);
                    break;
                }
                }
                fs.Flush();
            }
            return(File.Exists(filename));
        }
コード例 #14
0
ファイル: Serialize.cs プロジェクト: ronin1/GeoDataSource
        public static T DeserializeBinaryFromResource <T>(string name, SerializerType type = SerializerType.Default)
            where T : class
        {
            using (Stream stm = typeof(GeoData).Assembly.GetManifestResourceStream(name))
            {
                object o;
                switch (type)
                {
                case SerializerType.BinaryFormatter:
                {
                    o = new BinaryFormatter().Deserialize(stm);
                    break;
                }

                default:
                {
                    o = Serializer.Deserialize <T>(stm);
                    break;
                }
                }
                if (o != null && o is T)
                {
                    return(o as T);
                }
                else
                {
                    return(null);
                }
            }
        }
コード例 #15
0
ファイル: Serialize.cs プロジェクト: ronin1/GeoDataSource
        public static T DeserializeBinaryFromDisk <T>(string filename, SerializerType type = SerializerType.Default)
            where T : class
        {
            using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                object o;
                switch (type)
                {
                case SerializerType.BinaryFormatter:
                {
                    o = new BinaryFormatter().Deserialize(fs);
                    break;
                }

                default:
                {
                    o = Serializer.Deserialize <T>(fs);
                    break;
                }
                }
                if (o != null && o is T)
                {
                    return(o as T);
                }
                else
                {
                    return(null);
                }
            }
        }
コード例 #16
0
        private void TestSerialization(SerializerType serializerType, bool dontSetSerializerType = false)
        {
            const int    intData    = 123;
            const string stringData = "sjkdnfkjsdnf";

            var entry = new TransactionEntry();

            if (!dontSetSerializerType)
            {
                entry.ReqResSerializerType = serializerType;
            }

            entry.RequestObject = new TestSerializableData()
            {
                IntData    = intData,
                StringData = stringData
            };

            var serialized = entry.Request;

            var deserialized = Deserialize <TestSerializableData>(serialized, serializerType);

            Assert.IsNotNull(deserialized);
            Assert.AreEqual(intData, deserialized.IntData);
            Assert.AreEqual(stringData, deserialized.StringData);
        }
コード例 #17
0
ファイル: Serialize.cs プロジェクト: NickHola/Backupper
        public static bool SerializeInFile(object obj, string fileFullPath, SerializerType serialType = SerializerType.ntsJson, bool visualErr = true)
        {
            string testo, errUte;

            testo  = "";
            errUte = "";

            if (visualErr == true)
            {
                errUte = Log.main.errUserText;
            }

            if (FS.ValidaPercorsoFile(fileFullPath, true, out fileFullPath, verEsistenza: CheckExistenceOf.PathFolderOnly) == false)
            {
                return(false);
            }

            if (SerializeInText(obj, ref testo, serialType) == false)
            {
                return(false);
            }

            try
            {
                File.WriteAllText(fileFullPath, testo);
            }
            catch (Exception ex)
            {
                Log.main.Add(new Mess(LogType.ERR, errUte, "Eccezione in sezione file, ex.mess:<" + ex.Message + ">", visualMsgBox: false));
                return(false);
            }

            return(true);
        }
コード例 #18
0
ファイル: Serialize.cs プロジェクト: NickHola/Backupper
        public static bool DeserializeFromFile(string fileFullPath, ref object obj, SerializerType serialType = SerializerType.ntsJson, bool visualErr = true)
        {
            string testo, errUte;

            errUte = "";

            if (visualErr == true)
            {
                errUte = Log.main.errUserText;
            }

            if (FS.ValidaPercorsoFile(fileFullPath, true, out fileFullPath, verEsistenza: CheckExistenceOf.FolderAndFile) == false)
            {
                return(false);
            }

            try {
                testo = File.ReadAllText(fileFullPath);
            } catch (Exception ex) {
                Log.main.Add(new Mess(LogType.ERR, errUte, "Eccezione in sezione file, ex.mess:<" + ex.Message + ">", visualMsgBox: false));
                return(false);
            }

            if (DeserializeFromText(testo, ref obj, serialType) == false)
            {
                return(false);
            }
            return(true);
        }
コード例 #19
0
        /// <summary>
        /// Deserialize a xml representation to an object using XmlSerializerType.Xml or XmlSerializerType.DataContract.
        /// </summary>
        ///
        /// <typeparam name="T">
        /// Type of the object returned.
        /// </typeparam>
        ///
        /// <param name="serializerType">
        /// Serializer to use.
        /// </param>
        ///
        /// <param name="content">
        /// String representation to deserialize.
        /// </param>
        ///
        /// <returns>
        /// The object.
        /// </returns>
        public static T ToObject <T>(SerializerType serializerType, string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                ThrowException.ThrowArgumentNullException("content");
            }

            if (serializerType == SerializerType.DataContract)
            {
                using (var stream = new MemoryStream())
                {
                    byte[] data = Encoding.UTF8.GetBytes(content);
                    stream.Write(data, 0, data.Length);
                    stream.Position = 0;

                    var dcSerializer = new DataContractSerializer(typeof(T));
                    return((T)dcSerializer.ReadObject(stream));
                }
            }
            else if (serializerType == SerializerType.Json)
            {
                return(_jsonSerializer.Deserialize <T>(content.Trim()));
            }
            else
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                using (var reader = new StringReader(content))
                {
                    return((T)xmlSerializer.Deserialize(reader));
                }
            }
        }
コード例 #20
0
 public Stream GetCountryInfos(string format)
 {
     try
     {
         ValidateRequestMethod(HttpVerb.GET);
         User u = GetCurrentUser();
         AuditServiceCall(string.Format("GetCountryCodes: {0}", u.UserName));
         List <CountryInfo> result = BcEntityContext.Create().GetCountryInfos();
         if (string.IsNullOrEmpty(format))
         {
             return(GetStreamFromObject(result));
         }
         Stream         errorStream    = null;
         SerializerType serializerType = GetSerializerTypeFromFormat(format, out errorStream);
         if (errorStream != null)
         {
             return(errorStream);
         }
         return(GetStreamFromObject(result, serializerType));
     }
     catch (Exception ex)
     {
         ExceptionHandler.HandleException(ex);
         UpdateHttpStatusOnException(ex);
         throw ex;
     }
 }
コード例 #21
0
        public static string Serialize <T>(T ObjectToSerialize, SerializerType UseSerializer)
        {
            using (MemoryStream serialiserStream = new MemoryStream())
            {
                string serialisedString = null;
                switch (UseSerializer)
                {
                case SerializerType.Json:
                    // init the Serializer with the Type to Serialize
                    DataContractJsonSerializer serJson = new DataContractJsonSerializer(typeof(T));
                    // The serializer fills the Stream with the Object's Serialized Representation.
                    serJson.WriteObject(serialiserStream, ObjectToSerialize);
                    break;

                case SerializerType.Xml:
                default:
                    DataContractSerializer serXml = new DataContractSerializer(typeof(T));
                    serXml.WriteObject(serialiserStream, ObjectToSerialize);
                    break;
                }
                // Rewind the stream to the start so we can now read it.
                serialiserStream.Position = 0;
                using (StreamReader sr = new StreamReader(serialiserStream))
                {
                    // Use the StreamReader to get the serialized text out
                    serialisedString = sr.ReadToEnd();
                    sr.Close();
                }
                return(serialisedString);
            }
        }
コード例 #22
0
        public async Task AppliesDistributedCacheSoftTimeoutAsync(SerializerType serializerType)
        {
            var simulatedDelayMs      = 5_000;
            var distributedCache      = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
            var chaosDistributedCache = new ChaosDistributedCache(distributedCache);

            chaosDistributedCache.SetAlwaysDelayExactly(TimeSpan.FromMilliseconds(simulatedDelayMs));
            using (var memoryCache = new MemoryCache(new MemoryCacheOptions()))
            {
                using (var fusionCache = new FusionCache(new FusionCacheOptions(), memoryCache))
                {
                    fusionCache.SetupDistributedCache(chaosDistributedCache, GetSerializer(serializerType));
                    await fusionCache.SetAsync <int>("foo", 42, new FusionCacheEntryOptions().SetDurationSec(1).SetFailSafe(true));

                    await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);

                    var sw  = Stopwatch.StartNew();
                    var res = await fusionCache.GetOrSetAsync <int>("foo", async ct => throw new Exception("Sloths are cool"), new FusionCacheEntryOptions().SetDurationSec(1).SetFailSafe(true).SetDistributedCacheTimeouts(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(1_000)));

                    sw.Stop();

                    Assert.Equal(42, res);
                    Assert.True(sw.ElapsedMilliseconds >= 100, "Distributed cache soft timeout not applied");
                    Assert.True(sw.ElapsedMilliseconds < simulatedDelayMs, "Distributed cache soft timeout not applied");
                }
            }
        }
コード例 #23
0
        public void DistributedCacheCircuitBreakerActuallyWorks(SerializerType serializerType)
        {
            var circuitBreakerDuration = TimeSpan.FromSeconds(2);
            var distributedCache       = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
            var chaosDistributedCache  = new ChaosDistributedCache(distributedCache);

            using (var memoryCache = new MemoryCache(new MemoryCacheOptions()))
            {
                using (var fusionCache = new FusionCache(new FusionCacheOptions()
                {
                    DistributedCacheCircuitBreakerDuration = circuitBreakerDuration
                }, memoryCache))
                {
                    fusionCache.DefaultEntryOptions.AllowBackgroundDistributedCacheOperations = false;
                    fusionCache.SetupDistributedCache(chaosDistributedCache, GetSerializer(serializerType));

                    fusionCache.Set <int>("foo", 1, options => options.SetDurationSec(60).SetFailSafe(true));
                    chaosDistributedCache.SetAlwaysThrow();
                    fusionCache.Set <int>("foo", 2, options => options.SetDurationSec(60).SetFailSafe(true));
                    chaosDistributedCache.SetNeverThrow();
                    fusionCache.Set <int>("foo", 3, options => options.SetDurationSec(60).SetFailSafe(true));
                    Thread.Sleep(circuitBreakerDuration);
                    memoryCache.Remove("foo");
                    var res = fusionCache.GetOrDefault <int>("foo", -1);

                    Assert.Equal(1, res);
                }
            }
        }
コード例 #24
0
        private Handshake GetHandshakeResponse(Handshake handshakeRequest)
        {
            Handshake handshakeResponse;

            if (handshakeRequest.ReservedOctects != 0)
            {
                handshakeResponse = new Handshake(HandshakeErrorCode.UseOfReservedBits);
            }
            else
            {
                SerializerType serializerType = handshakeRequest.SerializerType;

                string requestedSubprotocol = GetSubProtocol(serializerType);

                if (!SubProtocols.Contains(requestedSubprotocol))
                {
                    handshakeResponse = new Handshake(HandshakeErrorCode.SerializerUnsupported);
                }
                else
                {
                    handshakeResponse = new Handshake(MaxSize, serializerType);
                }
            }

            return(handshakeResponse);
        }
コード例 #25
0
        /// <summary>
        /// Create a new ExcelMediaTypeFormatter.
        /// </summary>
        /// <param name="autoFit">True if the formatter should autofit columns after writing the data. (Default
        /// true.)</param>
        /// <param name="autoFilter">True if an autofilter should be applied to the worksheet. (Default false.)</param>
        /// <param name="freezeHeader">True if the header row should be frozen. (Default false.)</param>
        /// <param name="headerHeight">Height of the header row.</param>
        /// <param name="cellHeight">Height of each row of data.</param>
        /// <param name="cellStyle">An action method that modifies the worksheet cell style.</param>
        /// <param name="headerStyle">An action method that modifies the cell style of the first (header) row in the
        /// worksheet.</param>
        public XlsxMediaTypeFormatter(
            IHttpContextAccessor httpContextAccessor,
            IModelMetadataProvider modelMetadataProvider,
            bool autoFit                    = true,
            bool autoFilter                 = false,
            bool freezeHeader               = false,
            double?headerHeight             = null,
            Action <ExcelStyle> cellStyle   = null,
            Action <ExcelStyle> headerStyle = null,
            SerializerType serializerType   = SerializerType.Default,
            bool isExportJsonToXls          = false,
            string fileExtension            = null
            )
        {
            SupportedMediaTypes.Clear();
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.ms-excel"));

            AutoFit      = autoFit;
            AutoFilter   = autoFilter;
            FreezeHeader = freezeHeader;
            HeaderHeight = headerHeight;
            CellStyle    = cellStyle;
            HeaderStyle  = headerStyle;

            _serializerType      = serializerType;
            _isExportJsonToXls   = isExportJsonToXls;
            _fileExtension       = fileExtension;
            _httpContextAccessor = httpContextAccessor;
        }
コード例 #26
0
        protected static string Serialize(object val, SerializerType serializerType)
        {
            if (val == null)
            {
                return(null);
            }

            var serialized = val as string;

            if (serialized != null)
            {
                return(serialized);
            }

            switch (serializerType)
            {
            case SerializerType.DataContractSerializer:
                return(SerializationFactory.DataContractSerialize(val));

            case SerializerType.DataContractJsonSerializer:
                return(SerializationFactory.DataContractJsonSerialize(val));

            case SerializerType.JsonNetSerializer:
                return(SerializationFactory.JsonNetSerialize(val));

            case SerializerType.XmlSerializer:
            default:
                return(SerializationFactory.XmlSerialize(val));
            }

            #endregion
        }
コード例 #27
0
ファイル: FileTool.cs プロジェクト: azukiyui/UnityTools
        static public T Read <T>(string filePath, SerializerType type = SerializerType.Binary) where T : new()
        {
            var ret = default(T);

            if (File.Exists(filePath))
            {
                try
                {
                    switch (type)
                    {
                    case SerializerType.XML:
                    {
                        using (var fs = new StreamReader(filePath, System.Text.Encoding.UTF8))
                        {
                            var serializer = new XmlSerializer(typeof(T));
                            ret = (T)serializer.Deserialize(fs);
                            fs.Close();
                        }
                    }
                    break;

                    case SerializerType.Json:
                    {
                        using (var fs = new StreamReader(filePath, System.Text.Encoding.UTF8))
                        {
                            var json = fs.ReadToEnd();
                            ret = JsonUtility.FromJson <T>(json);
                            fs.Close();
                        }
                    }
                    break;

                    case SerializerType.Binary:
                    {
                        using (var fs = new FileStream(filePath, FileMode.Open))
                        {
                            var serializer = new BinaryFormatter();
                            ret = (T)serializer.Deserialize(fs);
                            fs.Flush();
                            fs.Close();
                        }
                    }
                    break;
                    }
                }
                catch (Exception e)
                {
                    LogTool.Log(e.Message + " " + filePath, LogLevel.Warning, LogChannel.IO);
                }
            }
            else
            {
                LogTool.Log(filePath + " not found, create new one", LogLevel.Warning, LogChannel.IO);
                ret = new T();
                Write(filePath, ret, type);
            }

            return(ret);
        }
コード例 #28
0
 public ISerializer Create <T>(SerializerType serializerType)
 {
     if (serializerType == SerializerType.Xml)
     {
         return(CreateXml <T>());
     }
     return(CreateBinary());
 }
コード例 #29
0
 public static ISerializer ResolveSerializer(SerializerType serializerType)
 {
     return(serializerType switch
     {
         SerializerType.Json => new JsonSerializer(),
         SerializerType.Base64 => new Base64Serializer(),
         _ => throw ConfigError($"Serializer type {serializerType} is not supported"),
     });
コード例 #30
0
 public GsBusConfig()
 {
     HostName       = "localhost";
     VirtualHost    = "/";
     UserName       = "******";
     Password       = "******";
     SerializerType = SerializerType.Avro;
 }
コード例 #31
0
ファイル: SerializationMember.cs プロジェクト: daszat/zetbox
 public SerializationMember(string templatename, SerializerType type, string xmlns, string xmlname, params object[] templateparams)
 {
     if (templatename.Contains("EagerLoadingSerialization"))
     {
     }
     this.TemplateName = templatename;
     this.SerializerType = type;
     this.TemplateParams = templateparams;
     this.XmlNamespace = xmlns;
     this.XmlName = xmlname;
 }
コード例 #32
0
 public static void AddToSerializers(SerializationMembersList list,
     SerializerType type,
     string xmlnamespace,
     string xmlname,
     string backingStoreName,
     string enumerationType)
 {
     if (list != null)
     {
         list.Add("Serialization.EnumBinarySerialization", type, xmlnamespace, xmlname, backingStoreName, enumerationType);
     }
 }
コード例 #33
0
		public static ISerializer Produce(SerializerType type)
		{
			switch(type)
			{
			case SerializerType.Migrant:
				return new MigrantSerializer();
			case SerializerType.ProtoBuf:
				return new ProtobufSerializer();
			default:
				throw new ArgumentOutOfRangeException();
			}
		}
コード例 #34
0
ファイル: SerializerFactory.cs プロジェクト: jpierson/Migrant
 public ISerializer Produce(SerializerType type)
 {
     switch(type)
     {
     case SerializerType.MigrantGenerated:
         return new MigrantSerializer(true);
     case SerializerType.MigrantReflection:
         return new MigrantSerializer(false);
     case SerializerType.ProtoBuf:
         return new ProtobufSerializer();
     default:
         throw new ArgumentOutOfRangeException();
     }
 }
コード例 #35
0
 public static ISerializerProvider Create(SerializerType serializerType = SerializerType.Binary)
 {
     switch (serializerType)
     {
         case SerializerType.Binary:
             return new BinarySerializerProvider();
         case SerializerType.Soap:
             return new SoapSerializerProvider();
         case SerializerType.Xml:
             return new XmlSerializerProvider();
         default:
             return new BinarySerializerProvider();
     }
 }
コード例 #36
0
 /// <summary>
 /// 缓存类型
 /// </summary>
 private static IDataSerializer GetDataSerializer(SerializerType serializerType)
 {
     if (_serializerDict.ContainsKey(serializerType))
     {
         return _serializerDict[serializerType];
     }
     else
     {
         var typeName = _typeNameDict[serializerType];
         IDataSerializer serializer = (IDataSerializer)Assembly.Load(typeName[0]).CreateInstance(string.Concat(typeName[0], ".", typeName[1]));
         if (serializer != null)
         {
             _serializerDict[serializerType] = serializer;
         }
         return serializer;
     }
 }
コード例 #37
0
 public static void AddToSerializers(SerializationMembersList list,
     SerializerType type,
     string xmlnamespace,
     string xmlname,
     string memberType,
     string memberName)
 {
     if (list != null)
     {
         list.Add(
             "Serialization.SimplePropertySerialization",
             type,
             xmlnamespace,
             xmlname,
             memberType,
             memberName);
     }
 }
コード例 #38
0
        public void BindData(byte[] data, SerializerType serializerType)
        {
            string viewType;
            var encoding = new UTF8Encoding(false);
            switch (serializerType)
            {
                case SerializerType.Xml:
                case SerializerType.XmlDataContract:
                    viewType = "xml";
                    _xmldocument = new XmlDocument();
                    _xmldocument.LoadXml(encoding.GetString(data, 0, data.Length));
                    var provider = new XmlDataProvider
                                       {
                                           Document = _xmldocument
                                       };
                    var binding = new Binding
                                      {
                                          Source = provider, XPath = "child::node()"
                                      };
                    XmlView.SetBinding(ItemsControl.ItemsSourceProperty, binding);
                    break;
                case SerializerType.JsonDataContract:
                case SerializerType.JsonNewtonsoft:
                    viewType = "json";
                    XmlView.SetBinding(ItemsControl.ItemsSourceProperty, new Binding());
                    JsonView.Text = encoding.GetString(data, 0, data.Length);
                    break;
                default:
                    viewType = "binary";
                    BinaryView.BindData(data);
                    break;
            }

            foreach (TabItem item in ViewTabControl.Items)
            {
                var tag = item.Tag as string;
                Debug.Assert(!String.IsNullOrWhiteSpace(tag));

                if (string.Compare(tag, viewType, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    ViewTabControl.SelectedItem = item;
                }
            }
        }
コード例 #39
0
 /// <summary>
 ///		Convierte los datos de un archivo a una cadena
 /// </summary>
 public string ConvertToString(SerializerType intType, MLFile objMLFile)
 {
     return GetWriter(intType).ConvertToString(objMLFile);
 }
コード例 #40
0
 private void LoadUsingSerializer(Role role, SerializerType serializer)
 {
     FileInfo _fileInfo = GetFileName(role, serializer, @"TestData\ConfigurationData{0}.{1}");
       Assert.IsTrue(_fileInfo.Exists, _fileInfo.ToString());
       ConfigurationData _mirror = null;
       ConfigurationData _source = null;
       switch (role)
       {
     case Role.Producer:
       _source = ReferenceConfiguration.LoadProducer();
       break;
     case Role.Consumer:
       _source = ReferenceConfiguration.LoadConsumer();
       break;
       }
       string _message = null;
       switch (serializer)
       {
     case SerializerType.Json:
       _mirror = ConfigurationDataFactoryIO.Load<ConfigurationData>
     (() => JSONDataContractSerializers.Load<ConfigurationData>(_fileInfo, (x, y, z) => { _message = z; Assert.AreEqual<TraceEventType>(TraceEventType.Verbose, x); }), () => { });
       break;
     case SerializerType.Xml:
       _mirror = ConfigurationDataFactoryIO.Load<ConfigurationData>
     (() => XmlDataContractSerializers.Load<ConfigurationData>(_fileInfo, (x, y, z) => { _message = z; Assert.AreEqual<TraceEventType>(TraceEventType.Verbose, x); }), () => { });
       break;
       }
       Console.WriteLine(_message);
       Assert.IsNotNull(_mirror);
       Assert.IsFalse(String.IsNullOrEmpty(_message));
       Assert.IsTrue(_message.Contains(_fileInfo.FullName));
       ReferenceConfiguration.Compare(_source, _mirror);
 }
コード例 #41
0
 private void SaveLoadConfigurationData(Role role, SerializerType serializer)
 {
     FileInfo _fileInfo = GetFileName(role, serializer, @"ConfigurationData{0}.{1}");
       ConfigurationData _configuration = null;
       switch (role)
       {
     case Role.Producer:
       _configuration = ReferenceConfiguration.LoadProducer();
       break;
     case Role.Consumer:
       _configuration = ReferenceConfiguration.LoadConsumer();
       break;
     default:
       break;
       }
       ConfigurationDataFactoryIO.Save<ConfigurationData>(_configuration, serializer, _fileInfo, (x, y, z) => { Console.WriteLine(z); });
       _fileInfo.Refresh();
       Assert.IsTrue(_fileInfo.Exists);
       ConfigurationData _mirror = ConfigurationDataFactoryIO.Load<ConfigurationData>(serializer, _fileInfo, (x, y, z) => { Console.WriteLine(z); }, () => { });
       ReferenceConfiguration.Compare(_configuration, _mirror);
 }
コード例 #42
0
 public WebMethodHandler(MethodInfo method, object viewModelInstance, SerializerType serializes)
 {
     _method = method;
     _viewModelInstance = viewModelInstance;
     _serializes = serializes;
 }
コード例 #43
0
 public CacheConfiguration()
 {
     this._firstLevelCacheType = FirstLevelCacheType.ConcurrentDictionary;
     this._secondLevelCacheType = SecondLevelCacheType.None;
     this._serializerType = SerializerType.ProtoBufNet;
 }
			public void TestDoValidate(SerializerType objectToValidate, object currentTarget, string key, ValidationResults validationResults)
			{
				this.DoValidate(objectToValidate, currentTarget, key, validationResults);
			}
コード例 #45
0
 /// <summary>
 ///		Obtiene un parser determinado
 /// </summary>
 private Services.IWriter GetWriter(SerializerType intType)
 {
     return new Services.WriterFactory().GetInstance(intType);
 }
コード例 #46
0
ファイル: Program.cs プロジェクト: Indifer/Raven.Serializer
        public static void Factory(int seed, SerializerType type, Mall mall)
        {
            //var serializer = global::MsgPack.Serialization.MessagePackSerializer.Get<Mall>();
            IDataSerializer serializer = SerializerFactory.Create(type);
            Stopwatch sw = new Stopwatch();
            byte[] data = null;

            sw.Restart();
            for (var i = 0; i < seed; i++)
            {
                data = serializer.Serialize(mall);
            }
            sw.Stop();

            Console.WriteLine("{1} Serialize:{0}ms", sw.ElapsedMilliseconds, serializer.GetType().Name);

            sw.Restart();
            for (var i = 0; i < seed; i++)
            {
                mall = serializer.Deserialize<Mall>(data);
            }
            sw.Stop();

            Console.WriteLine("{1} Deserialize:{0}ms", sw.ElapsedMilliseconds, serializer.GetType().Name);
        }
コード例 #47
0
 /// <summary>
 /// 创建类型
 /// </summary>
 /// <param name="serializerType"></param>
 /// <returns></returns>
 public static IDataSerializer Create(SerializerType serializerType)
 {
     IDataSerializer serializer = GetDataSerializer(serializerType);
     //IDataSerializer serializer = (IDataSerializer)Activator.CreateInstance(type, new object[] { });
     return serializer;
 }
コード例 #48
0
 private static FileInfo GetFileName(Role role, SerializerType serializer, string fileNameTemplate)
 {
     string _extension = serializer == SerializerType.Xml ? "xml" : "json";
       string _fileName = String.Format(fileNameTemplate, role, _extension);
       return new FileInfo(_fileName);
 }
コード例 #49
0
 /// <summary>
 ///		Interpreta un archivo de un tipo
 /// </summary>
 public MLFile Parse(SerializerType intType, string strFileName, bool blnIncludeComments = false)
 {
     return GetParser(intType, blnIncludeComments).Parse(strFileName);
 }
コード例 #50
0
 /// <summary>
 ///		Interpreta un archivo de un tipo
 /// </summary>
 public MLFile ParseText(SerializerType intType, string strText, bool blnIncludeComments = false)
 {
     return GetParser(intType, blnIncludeComments).ParseText(strText);
 }
コード例 #51
0
 /// <summary>
 ///		Graba los datos en un archivo
 /// </summary>
 public void Save(SerializerType intType, MLFile objMLFile, string strFileName)
 {
     GetWriter(intType).Save(objMLFile, strFileName);
 }
コード例 #52
0
 /// <summary>
 ///		Obtiene un parser determinado
 /// </summary>
 private Services.IParser GetParser(SerializerType intType, bool blnIncludeComments = false)
 {
     return new Services.ParserFactory().GetInstance(intType, blnIncludeComments);
 }