private static T ParseXml <T>(string xml) where T : new() { var reader = new SimpleXmlReader(XmlReader.Create(new StringReader(xml), xmlReaderSettings)); return(Deserialize <T> .From(reader)); }
internal void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer) { if (type == null || serializer == null || deserializer == null) return; _customSerializer.Add(type, serializer); _customDeserializer.Add(type, deserializer); // reset property cache Instance.ResetPropertyCache(); }
/// <summary> /// Fetches location info by city name from related remote api /// </summary> /// <param name="cityName">City Name</param> /// <returns>LocationModel</returns> internal static LocationModel FetchLocationInfo(string cityName) { cityName = RemoveDiacritics(cityName.ToLower()); LocationModel locationModel = null; var currrentTSHour = Convert.ToInt64((Math.Floor((decimal)(DateTime.Now.ToEpoch()) / 3600) * 3600)); if (!methodRequests.ContainsKey(currrentTSHour)) // eger guncel saat dict icinde yoksa ekleme ve onceki saatle islem yapma bolumu { methodRequests[currrentTSHour] = new ConcurrentDictionary <string, LocationModel>(); } if (methodRequests[currrentTSHour].ContainsKey(cityName)) { return(methodRequests[currrentTSHour].Where(r => r.Key == cityName).Select(r => r.Value).FirstOrDefault()); } Stopwatch sw = Stopwatch.StartNew(); try { using (var httpClient = new HttpClient()) { using (var response = httpClient.GetAsync(_LocationWSURL.Replace("[LOCATION]", cityName ?? "istanbul")).Result) { using (var content = response.Content) { //get the json result from location api var result = content.ReadAsStringAsync().Result; locationModel = Deserialize.FromJson(result).FirstOrDefault(); sw.Stop(); if (locationModel != null) { //TO DO : consider same spelled different places.. //This is more simple to check if the record is available or not then if record not available save etc.. var res = DBlite.ExecuteSQL($"INSERT OR IGNORE INTO Location (CityName, Latitude, Longitude, QueryElapsedMilliseconds) VALUES (@CityName, @Latitude, @Longitude, @QueryElapsedMilliseconds);", new ArrayList { new SQLiteParameter("@CityName", cityName), new SQLiteParameter("@Latitude", locationModel.Lat), new SQLiteParameter("@Longitude", locationModel.Lon), new SQLiteParameter("@QueryElapsedMilliseconds", sw.ElapsedMilliseconds) }); if (res == -1) { Log.Error("Location table insert error"); } else { var dt = DBlite.GetData($"SELECT Id, Latitude, Longitude, QueryElapsedMilliseconds FROM Location WHERE CityName = @CityName;", new ArrayList { new SQLiteParameter("@CityName", cityName) }); if (dt != null && dt.Rows.Count > 0) { var dr = dt.Rows[0]; locationModel = new LocationModel { CityId = dr["Id"].Obj2Int32(), CityName = cityName, Lat = dr["Latitude"].Obj2String(), Lon = dr["Longitude"].Obj2String(), QueryElapsedMilliseconds = dr["QueryElapsedMilliseconds"].Obj2Int64(), }; //max 50 records if (methodRequests.Count >= 50) { methodRequests[currrentTSHour] = new ConcurrentDictionary <string, LocationModel>(); } //if cityId does not exist if (!methodRequests[currrentTSHour].ContainsKey(cityName)) { methodRequests[currrentTSHour].TryAdd(cityName, locationModel); } } } } } } } } catch (Exception ex) { Log.Error("LocationService : " + ex.ToString()); } return(locationModel); }
public static AddableArray <T> Deserialize(string str, Deserialize <T> deserialize) { string type_string = typeof(T).ConvertToCsharpSource(); string type_string_xml = type_string.Replace("<", "-").Replace(">", "-"); T[] list; Equate <T> equate = null; int count = 0; using (XmlReader xmlReader = XmlReader.Create(new StringReader(str))) { if (!xmlReader.Read() || !xmlReader.IsStartElement() || xmlReader.IsEmptyElement || !xmlReader.Name.Equals("ListArray")) { throw new FormatException("Invalid input during ListArray deserialization."); } bool typeExists = false; bool equateExists = false; bool countExists = false; while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "Type": string typeFromXml = xmlReader.Value; if (!type_string_xml.Equals(typeFromXml)) { throw new FormatException("Type mismatch during a ListArray deserialization (ListArray<T>: T does not match the type in the string to deserialize)."); } typeExists = true; break; case "Equate": if (string.IsNullOrWhiteSpace(xmlReader.Value)) { throw new FormatException("Invalid input during ListArray deserialization (Equate attribute is invalid or missing a value)."); } string[] splits = xmlReader.Value.Split(','); if (splits.Length != 3) { throw new FormatException("Invalid input during ListArray deserialization (Equate attribute has an invalid value)."); } string methodName = splits[0]; string declaringTypeFullName = splits[1]; string assembly = splits[2]; throw new NotImplementedException(); //equate = Meta.Compile<Equate<T>>(string.Concat(declaringTypeFullName, ".", methodName)); equateExists = true; break; case "Count": if (string.IsNullOrWhiteSpace(xmlReader.Value)) { throw new FormatException("Invalid input during ListArray deserialization (Count attribute is invalid or missing a value)."); } if (!int.TryParse(xmlReader.Value, out count) || count < 0) { throw new FormatException("Invalid input during ListArray deserialization (Count attribute is invalid)."); } countExists = true; break; default: continue; } } if (!equateExists) { throw new FormatException("Invalid input during ListArray deserialization (required attribute Equate does not exist)."); } if (!countExists) { throw new FormatException("Invalid input during ListArray deserialization (required attribute Count does not exist)."); } if (!typeExists) { throw new FormatException("Invalid input during ListArray deserialization (required attribute Type does not exist)."); } xmlReader.MoveToElement(); list = new T[count]; for (int i = 0; i < count; i++) { while (xmlReader.Name == null || !xmlReader.Name.Equals("Item")) { xmlReader.Read(); } if (!xmlReader.IsStartElement() || xmlReader.IsEmptyElement) { throw new FormatException("Invalid input during ListArray deserialization."); } if (xmlReader.Value == null) { throw new FormatException("Invalid input during ListArray deserialization (missing or invalid contents of Item #" + i + ")."); } int index; bool indexExists = false; while (xmlReader.MoveToNextAttribute()) { if (string.IsNullOrWhiteSpace(xmlReader.Name)) { throw new FormatException("Invalid input during ListArray deserialization (invalid attribute of Item #" + i + ")."); } if (!xmlReader.Name.Equals("Index")) { continue; } if (string.IsNullOrWhiteSpace(xmlReader.Value) || !int.TryParse(xmlReader.Value, out index) || index != i) { throw new FormatException("Invalid input during ListArray deserialization (invalid index attribute of Item #" + i + ")."); } indexExists = true; } if (!indexExists) { throw new FormatException("Invalid input during ListArray deserialization (missing required Index attribute for Item #" + i + ")."); } xmlReader.MoveToElement(); string item_string = xmlReader.ReadString().Trim(); list[i] = deserialize(item_string); if (i < count - 1 && !xmlReader.ReadToNextSibling("Item")) { throw new FormatException("Invalid input during ListArray deserialization (count attribute and amount of data provided do not match)."); } } } return(new AddableArray <T>(list, count, equate)); }
public void FastBinaryReader_Skip_WString_OverflowLength_Throws() { var data = new byte[] { 0x0a, 0x00, 0x00, 0x09, 0x02, 0x00, 0x27, 0x49, 0x39, 0x54, 0x36, 0x75, 0x29, 0x53, 0x43, 0x56, 0x3d, 0x21, 0x74, 0x56, 0x46, 0x39, 0x22, 0x7a, 0x58, 0x34, 0x70, 0x2d, 0x70, 0x69, 0x5b, 0x27, 0x23, 0x40, 0x32, 0x60, 0x2c, 0x43, 0x3a, 0x3f, 0x6c, 0x36, 0x55, 0x38, 0x7a, 0x54, 0x12, 0x03, 0x00, 0xff, // count -1 0xff, 0xff, 0xff, 0xff, 0x3c, 0x00, }; var input = new InputBuffer(data); var reader = new FastBinaryReader <InputBuffer>(input); Assert.Throws <OverflowException>(() => Deserialize <BondedAlias> .From(reader)); data = new byte[] { 0x0a, 0x00, 0x00, 0x09, 0x02, 0x00, 0x27, 0x49, 0x39, 0x54, 0x36, 0x75, 0x29, 0x53, 0x43, 0x56, 0x3d, 0x21, 0x74, 0x56, 0x46, 0x39, 0x22, 0x7a, 0x58, 0x34, 0x70, 0x2d, 0x70, 0x69, 0x5b, 0x27, 0x23, 0x40, 0x32, 0x60, 0x2c, 0x43, 0x3a, 0x3f, 0x6c, 0x36, 0x55, 0x38, 0x7a, 0x54, 0x12, 0x03, 0x00, 0x80, // count (5 byte) = int.MaxValue / 2 + 1 0x80, 0x80, 0x80, 0x04, 0x3c, 0x00, }; input = new InputBuffer(data); reader = new FastBinaryReader <InputBuffer>(input); Assert.Throws <OverflowException>(() => Deserialize <BondedAlias> .From(reader)); }
internal static object Deserialize(ObjectReader stream, Deserialize <ObjectReader> info) { object value = info(stream); return(value); }
public static void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer) { Manager.RegisterCustomType(type, serializer, deserializer); }
public static T DeserializeJson <T>(Stream stream) { var reader = new SimpleJsonReader(stream); return(Deserialize <T> .From(reader)); }
public void should_deserialize_mail_address() { Deserialize.FormUrlEncoded <OutOfTheBoxTypes>("[email protected]") .MailAddress.ShouldEqual(new MailAddress("*****@*****.**")); }
public void should_deserialize_byte_array() { Deserialize.FormUrlEncoded <OutOfTheBoxTypes>("ByteArray=b2ggaGFp") .ByteArray.ShouldEqual(ASCIIEncoding.ASCII.GetBytes("oh hai")); }
public void should_deserialize_version() { Deserialize.FormUrlEncoded <OutOfTheBoxTypes>("Version=1.2.3.4") .Version.ShouldEqual(Version.Parse("1.2.3.4")); }
public void should_deserialize_ip_address() { Deserialize.FormUrlEncoded <OutOfTheBoxTypes>("IPAddress=192.168.1.1") .IPAddress.ShouldEqual(IPAddress.Parse("192.168.1.1")); }
public void should_exclude_types_when() { Deserialize.Json <IDictionary <string, ComplexType> >( "{ \"item\": { \"Property\": \"hai\" } }", x => x.ExcludeTypesWhen((t, o) => t.Name == "ComplexType")).ShouldTotal(0); }
/// <summary> /// Register a custom serializer/deserializer by the type and type code specified. /// </summary> /// <param name="typeCode"> /// The type code. /// </param> /// <param name="type"> /// The type. /// </param> /// <param name="serialize"> /// The serialize delegate. /// </param> /// <param name="deserialize"> /// The deserialize delegate. /// </param> /// <returns> /// <c>true</c> if the serializer and deserialize delegate has been registered successfully, otherwise <c>false</c>. /// </returns> public static bool Register(int typeCode, Type type, Serialize serialize, Deserialize deserialize) { return Register(typeCode, type, serialize) && Decoder.Register(typeCode, type, deserialize); }
/// <summary> /// 数据接收 /// </summary> /// <param name="data"></param> public override void DataReceive(string data) { try { if (string.IsNullOrEmpty(data)) { return; } HJ212Model model = Deserialize.DeserializeBase(data); CommandType type = Util.GetCommandType((MiddleCode)model.CN); switch (type) { case CommandType.Notice: NoticeResponse(model); break; case CommandType.Request: CommandResult res = RequestResponse(model); if (res != CommandResult.Ready) { return; } break; case CommandType.Upload: RequestResponse(model, CommandResult.Forbidden); return; case CommandType.Other: return; case CommandType.None: RequestResponse(model, CommandResult.Forbidden); return; default: RequestResponse(model, CommandResult.Forbidden); return; } switch ((MiddleCode)model.CN) { case MiddleCode.SetTimeOutReSendTimes: SetTimeOutReSendTimes(model); break; case MiddleCode.GetSceneDeviceTime: UploadSceneDeviceTime(model); break; case MiddleCode.SetSceneDeviceTime: SetSceneDeviceTime(model); break; case MiddleCode.GetRtdDataInterval: UploadRtdDataInterval(model); break; case MiddleCode.SetRtdDataInterval: SetRtdDataInterval(model); break; case MiddleCode.GetMinuteDataInterval: UploadMinuteDataInterval(model); break; case MiddleCode.SetMinuteDataInterval: SetMinuteDataInterval(model); break; case MiddleCode.SetSceneDevicePassword: SetSceneDevicePassword(model); break; case MiddleCode.GetRtdData: GetRtdData(model); break; case MiddleCode.StopRtdData: StopRtdData(model); break; case MiddleCode.GetDeviceRunState: GetDeviceRunState(model); break; case MiddleCode.StopDeviceRunState: StopDeviceRunState(model); break; case MiddleCode.GetDayData: UploadDayData(model); break; case MiddleCode.GetDeviceRunTimeDayData: UploadDeviceRunTimeDayData(model); break; case MiddleCode.GetMinuteData: UploadMinuteData(model); break; case MiddleCode.GetHourData: UploadHourData(model); break; case MiddleCode.RangeCalibration: RangeCalibration(model); break; case MiddleCode.GetCycleData: UploadCycleData(model); break; case MiddleCode.TakeSampleImmediately: TakeSampleImmediately(model); break; case MiddleCode.StartClear: StartClear(model); break; case MiddleCode.CompareSample: CompareSample(model); break; case MiddleCode.LeaveSuperstandardSample: UploadSuperstandardSample(model); break; case MiddleCode.SetSampleTimeInterval: SetSampleTimeInterval(model); break; case MiddleCode.GetSampleTimeInterval: UploadSampleTimeInterval(model); break; case MiddleCode.GetSampleTime: UploadSampleTime(model); break; case MiddleCode.GetSceneDeviceUUID: UploadSceneDeviceUUID(model); break; case MiddleCode.GetSceneDeviceInfo: UploadSceneDeviceInfo(model); break; case MiddleCode.SetSceneDeviceParam: SetSceneDeviceParam(model); break; } } catch (Exception ex) { throw ex; } }
public void should_filter_types() { Deserialize.Json <IDictionary <string, ComplexType> >( "{ \"item\": { \"Property\": \"hai\" } }", x => x.ExcludeType <ComplexType>()).ShouldTotal(0); }
static void Main(string[] args) { if (args.Length < 3) { Console.WriteLine("Usage:\nBond.CompatibilityTest json|compact|compact2|fast|simple|simple2|schema input_file output_file [json|compact|fast|simple|simple2]"); return; } var fromProtocol = args[0]; var toProtocol = fromProtocol; var inputFile = args[1]; var outputFile = args[2]; if (args.Length == 4) { toProtocol = args[3]; } using (var inputStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read)) { var input = new InputStream(inputStream); using (var outputStream = new FileStream(outputFile, FileMode.Create)) { var output = new OutputStream(outputStream); if (fromProtocol == "json") { var reader = new SimpleJsonReader(inputStream); var writer = new SimpleJsonWriter(outputStream); var transcoder = new Transcoder <SimpleJsonReader, SimpleJsonWriter>(Schema <Compat> .RuntimeSchema); transcoder.Transcode(reader, writer); writer.Flush(); } else if (fromProtocol == "compact") { var reader = new CompactBinaryReader <InputStream>(input); Write(reader, output, toProtocol); } else if (fromProtocol == "compact2") { var reader = new CompactBinaryReader <InputStream>(input, 2); Write(reader, output, toProtocol); } else if (fromProtocol == "fast") { var reader = new FastBinaryReader <InputStream>(input, 2); Write(reader, output, toProtocol); } else if (fromProtocol == "simple") { var reader = new SimpleBinaryReader <InputStream>(input); Write(reader, output, toProtocol); } else if (fromProtocol == "simple2") { var reader = new SimpleBinaryReader <InputStream>(input, 2); Write(reader, output, toProtocol); } else if (fromProtocol == "schema") { SchemaDef schema; var c = (char)inputStream.ReadByte(); inputStream.Seek(0, SeekOrigin.Begin); if (c == '{') { var reader = new SimpleJsonReader(inputStream); schema = Deserialize <SchemaDef> .From(reader); } else { schema = Unmarshal <SchemaDef> .From(input); } if (!Comparer.Equal(schema, Schema <Compat> .RuntimeSchema.SchemaDef)) { Console.WriteLine("SchemaDef is different"); } var writer = new CompactBinaryWriter <OutputStream>(output); Marshal.To(writer, Schema <Compat> .RuntimeSchema.SchemaDef); output.Flush(); } else { Console.WriteLine("Unsupported input protocol {0}", fromProtocol); } } } }
public static T DeserializeTagged <T>(IClonableTaggedProtocolReader reader) { return(Deserialize <T> .From(reader)); }
static void Main() { var circle = new Circle { Type = Type.Circle, Radius = 3.14 }; var rectangle = new Rectangle { Type = Type.Rectangle, Width = 10, Height = 5.5 }; var src = new Polymorphic { Shapes = { new Bonded <Circle>(circle), new Bonded <Rectangle>(rectangle) } }; var output = new OutputBuffer(); var writer = new CompactBinaryWriter <OutputBuffer>(output); Serialize.To(writer, src); var input = new InputBuffer(output.Data); var reader = new CompactBinaryReader <InputBuffer>(input); var dst = Deserialize <Polymorphic> .From(reader); var deserializers = new Dictionary <Type, Deserializer <CompactBinaryReader <InputBuffer> > > { { Type.Circle, new Deserializer <CompactBinaryReader <InputBuffer> >(typeof(Circle)) }, { Type.Rectangle, new Deserializer <CompactBinaryReader <InputBuffer> >(typeof(Rectangle)) } }; foreach (var item in dst.Shapes) { // Deserialize item as Shape and extract object type var type = item.Deserialize().Type; // Select one of the precreated deserializers based on the item type var shape = deserializers[type].Deserialize(item); if (shape.GetType() == typeof(Circle)) { ThrowIfFalse(Comparer.Equal(circle, shape as Circle)); } if (shape.GetType() == typeof(Rectangle)) { ThrowIfFalse(Comparer.Equal(rectangle, shape as Rectangle)); } // Alternatively the generic method IBonded<T>.Deserialize<U> can be used if (type == Type.Circle) { var c = item.Deserialize <Circle>(); ThrowIfFalse(Comparer.Equal(circle, c)); } if (type == Type.Rectangle) { var r = item.Deserialize <Rectangle>(); ThrowIfFalse(Comparer.Equal(rectangle, r)); } } }
public async void ExportToExcel(ProgressBar progressBar) { // Display the ProgressBar control. progressBar.Visible = true; // Set Minimum to 1 to represent the first file being copied. progressBar.Minimum = 1; // Set the initial value of the ProgressBar. progressBar.Value = 1; // Set the Step property to a value of 1 to represent each file being copied. progressBar.Step = 1; object Nothing = System.Reflection.Missing.Value; var app = new Microsoft.Office.Interop.Excel.Application(); app.Visible = false; Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Add(Nothing); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets[1]; worksheet.Name = "Employee Exported"; worksheet.StandardWidth = 20; // Show save file dialog SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Excel Files|*.xlsx"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { // storing header part in Excel Employee employee = new Employee(); worksheet.Cells[1, 1] = "Id"; worksheet.Cells[1, 2] = "Name"; worksheet.Cells[1, 3] = "Email"; worksheet.Cells[1, 4] = "Gender"; worksheet.Cells[1, 5] = "Status"; var response = await EmployeeHelper.ListPage(); PaginationEmployee paginationInfo = Deserialize.DeserializeEmployeePagination(response); int total = paginationInfo.Total; int pages = paginationInfo.Pages; int page = paginationInfo.Page; int limit = paginationInfo.Limit; IList <Employee> employeeList = new List <Employee>(); int countPage = pages; // Set Maximum to the total number of files to copy. progressBar.Maximum = total; int cellCount = 1; for (int i = 1; i <= pages; i++) { var responseList = await ListAll(i); employeeList = Deserialize.DeserializeEmployeSearch(responseList); for (int j = 0; j < employeeList.Count; j++) { cellCount++; worksheet.Cells[cellCount, 1] = employeeList[j].Id; worksheet.Cells[cellCount, 2] = employeeList[j].Name; worksheet.Cells[cellCount, 3] = employeeList[j].Email; worksheet.Cells[cellCount, 4] = employeeList[j].Gender; worksheet.Cells[cellCount, 5] = employeeList[j].Status; progressBar.PerformStep(); } } progressBar.Visible = false; worksheet.SaveAs(saveFileDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing); workBook.Close(false, Type.Missing, Type.Missing); app.Quit(); } }
internal static object Deserialize(JsonUstring stream, Deserialize <JsonUstring> info) { object value = info(stream); return(value); }
public static T Init <T>() { return(Deserialize <T> .From(new RandomReader(random))); }
#pragma warning disable CS0618 // Type or member is obsolete; this does not involve any form of user input. Any possible threats presented here already exist in the object being copied public static object CopyByBinarySerialization(this object obj) => Deserialize <object> .Binary(Serialize.Binary(obj));
public void Rate() { Logger.Log("Starting rate."); Logger.Log("Loading policy."); // load policy - open file policy.json var policyJson = Reader.ReadFromJson("policy.json"); var policy = Deserialize.To <Policy>(policyJson); switch (policy.Type) { case PolicyType.Auto: Logger.Log("Rating AUTO policy..."); Logger.Log("Validating policy."); if (string.IsNullOrEmpty(policy.Make)) { Logger.Log("Auto policy must specify Make"); return; } if (policy.Make == "BMW") { if (policy.Deductible < 500) { Rating = 1000m; } Rating = 900m; } break; case PolicyType.Land: Logger.Log("Rating LAND policy..."); Logger.Log("Validating policy."); if (policy.BondAmount == 0 || policy.Valuation == 0) { Logger.Log("Land policy must specify Bond Amount and Valuation."); return; } if (policy.BondAmount < 0.8m * policy.Valuation) { Logger.Log("Insufficient bond amount."); return; } Rating = policy.BondAmount * 0.05m; break; case PolicyType.Life: Logger.Log("Rating LIFE policy..."); Logger.Log("Validating policy."); if (policy.DateOfBirth == DateTime.MinValue) { Logger.Log("Life policy must include Date of Birth."); return; } if (policy.DateOfBirth < DateTime.Today.AddYears(-100)) { Logger.Log("Centenarians are not eligible for coverage."); return; } if (policy.Amount == 0) { Logger.Log("Life policy must include an Amount."); return; } var age = DateTime.Today.Year - policy.DateOfBirth.Year; if ((policy.DateOfBirth.Month == DateTime.Today.Month && DateTime.Today.Day < policy.DateOfBirth.Day) || DateTime.Today.Month < policy.DateOfBirth.Month) { age--; } var baseRate = policy.Amount * age / 200; if (policy.IsSmoker) { Rating = baseRate * 2; break; } Rating = baseRate; break; default: Logger.Log("Unknown policy type"); break; } Logger.Log("Rating completed."); }
public async static Task <object> CopyByBinarySerializationAsync(this object obj) => await Task.Run(() => Deserialize <object> .Binary(Serialize.Binary(obj)));
/// <summary> /// Register custom type handlers for your own types not natively handled by fastJSON /// </summary> /// <param name="type"></param> /// <param name="serializer"></param> /// <param name="deserializer"></param> public static void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer) { Reflection.Instance.RegisterCustomType(type, serializer, deserializer); }
public EventStoreAdapter(GetEventStoreConnection getEventStoreConnection, Serialize serialize, Deserialize deserialize) { _getEventStoreConnection = getEventStoreConnection; _createEventData = (se, ct) => Defaults.CreateEventData(se, serialize, ct); _resolveStreamEvent = (re, ct) => Defaults.ResolveStreamEvent(re, deserialize, ct); }
/// <summary> /// Initializes a new instance of the <see cref="DecoderInfo"/> class. /// </summary> /// <param name="type"> /// The type. /// </param> /// <param name="deserialize"> /// The deserialize. /// </param> internal DecoderInfo(Type type, Deserialize deserialize) { this.Type = type; this.Deserialize = deserialize; }
public static ISerializedRW <A> lambda <A>( Serialize <A> serialize, Deserialize <DeserializeInfo <A> > deserialize ) => new Lambda <A>(serialize, deserialize);
/// <summary> /// Register a custom deserializer by the type and type code specified. /// </summary> /// <param name="typeCode"> /// The type code. /// </param> /// <param name="type"> /// The type. /// </param> /// <param name="deserialize"> /// The deserialize delegate. /// </param> /// <returns> /// <c>true</c> if the deserialize delegate has been registered successfully, otherwise <c>false</c>. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="type"/> is null. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="deserialize"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="typeCode"/> is not in the valid range. /// </exception> public static bool Register(int typeCode, Type type, Deserialize deserialize) { if (type == null) { throw new ArgumentNullException("type"); } if (deserialize == null) { throw new ArgumentNullException("deserialize"); } Encoder.Register(typeCode, type); var internalTypeCode = Encoder.ToInternalTypeCode(typeCode); return DecoderInfos.TryAdd((Tags)internalTypeCode, new DecoderInfo(type, deserialize)); }
public Lambda(Serialize <A> serialize, Deserialize <DeserializeInfo <A> > deserialize) { _serialize = serialize; _deserialize = deserialize; }
internal void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer) { if (type != null && serializer != null && deserializer != null) { _customSerializer.Add(type, serializer); _customDeserializer.Add(type, deserializer); // reset property cache Reflection.Instance.ResetPropertyCache(); } }
/// <summary> /// Deserializes an <see cref="IPipFingerprintEntryData"/> of the appropriate concrete type (or null if the type is unknown). /// <see cref="PipFingerprintEntry"/> is a tagged polymorphic container (see <see cref="Kind"/>), /// and this operation unwraps it. The returned instance contains all relevant data for the entry. /// </summary> public IPipFingerprintEntryData Deserialize(CacheQueryData cacheQueryData = null) { if (Kind == PipFingerprintEntryKind.Unknown) { return(null); } if (m_deserializedEntryData != null) { return(m_deserializedEntryData); } try { InputBuffer buffer = new InputBuffer(DataBlob); CompactBinaryReader <InputBuffer> reader = new CompactBinaryReader <InputBuffer>(buffer); IPipFingerprintEntryData deserialized; switch (Kind) { case PipFingerprintEntryKind.DescriptorV1: deserialized = Deserialize <PipCacheDescriptor> .From(reader); break; case PipFingerprintEntryKind.DescriptorV2: deserialized = Deserialize <PipCacheDescriptorV2Metadata> .From(reader); break; case PipFingerprintEntryKind.GraphDescriptor: deserialized = Deserialize <PipGraphCacheDescriptor> .From(reader); break; case PipFingerprintEntryKind.FileDownload: deserialized = Deserialize <FileDownloadDescriptor> .From(reader); break; case PipFingerprintEntryKind.PackageDownload: deserialized = Deserialize <PackageDownloadDescriptor> .From(reader); break; case PipFingerprintEntryKind.GraphInputDescriptor: deserialized = Deserialize <PipGraphInputDescriptor> .From(reader); break; default: throw Contract.AssertFailure("Unhandled PipFingerprintEntryKind"); } Interlocked.CompareExchange(ref m_deserializedEntryData, deserialized, comparand: null); return(Volatile.Read(ref m_deserializedEntryData)); } catch (Exception exception) { if (IsCorrupted) { OutputBuffer valueBuffer = new OutputBuffer(1024); CompactBinaryWriter <OutputBuffer> writer = new CompactBinaryWriter <OutputBuffer>(valueBuffer); Serialize.To(writer, this); // Include in the log the hash of this instance so that we can trace it in the cache log, and obtain the file in the CAS. ContentHash valueHash = ContentHashingUtilities.HashBytes( valueBuffer.Data.Array, valueBuffer.Data.Offset, valueBuffer.Data.Count); const string Unspecified = "<Unspecified>"; string actualEntryBlob = Unspecified; string actualEntryHash = Unspecified; if (cacheQueryData != null && cacheQueryData.ContentCache != null) { var maybeActualContent = cacheQueryData.ContentCache.TryLoadContent( cacheQueryData.MetadataHash, failOnNonSeekableStream: true, byteLimit: 20 * 1024 * 1024).Result; if (maybeActualContent.Succeeded && maybeActualContent.Result != null) { actualEntryBlob = ToByteArrayString(maybeActualContent.Result); actualEntryHash = ContentHashingUtilities.HashBytes(maybeActualContent.Result).ToString(); } } Logger.Log.DeserializingCorruptedPipFingerprintEntry( Events.StaticContext, kind: Kind.ToString(), weakFingerprint: cacheQueryData?.WeakContentFingerprint.ToString() ?? Unspecified, pathSetHash: cacheQueryData?.PathSetHash.ToString() ?? Unspecified, strongFingerprint: cacheQueryData?.StrongContentFingerprint.ToString() ?? Unspecified, expectedHash: cacheQueryData?.MetadataHash.ToString() ?? Unspecified, // expected metadata hash hash: valueHash.ToString(), // re-computed hash blob: ToDataBlobString(), // blob of data carried by pip fingerprint entry actualHash: actualEntryHash, // actual pip fingerprint entry hash actualEntryBlob: actualEntryBlob); // actual pip fingerprint entry blob throw new BuildXLException("Deserializing corrupted pip fingerprint entry", exception, ExceptionRootCause.CorruptedCache); } // We don't expect this to happen so rethrow the exception. throw; } }