internal static Stream Serialize <T>(T instance, ProtoBufFormatter formatter = null) { formatter = formatter ?? new ProtoBufFormatter(); var stream = new MemoryStream(); formatter.Serialize(stream, instance); stream.Position = 0; return(stream); }
public async void WhenUsedToDeserializeShouldCreateCorrectObject() { var formatter = new ProtoBufFormatter(); var item = new Item { Id = 1, Name = "Filip" }; var content = new ObjectContent <Item>(item, formatter); var deserializedItem = await content.ReadAsAsync <Item>(new[] { formatter }); Assert.Same(item, deserializedItem); }
public void Full_stack_smoke_test() { var config = new EngineConfiguration().ForIsolatedTest(); ProtoBufFormatter.ConfigureSnapshots <TodoModel>(config, null); Engine <TodoModel> engine = Engine.Create(BuildComplexModel(), config); engine.CreateSnapshot(); engine.Close(); engine = Engine.Load <TodoModel>(config); var model = (TodoModel)engine.GetModel(); Dump(model); }
public void CanDeserializeType() { // Arrange var formatter = new ProtoBufFormatter(); var graph = new Employee(16) { Name = "Kalle", Age = 42 }; // Act var result = SerializationHelper.Clone<Employee>(graph, formatter); // Assert Assert.IsInstanceOf<Employee>(result); Assert.AreEqual("Kalle", result.Name); Assert.AreEqual(42, result.Age); Assert.AreEqual(16,result.ShoeSize); }
public async void WhenWritingToStreamShouldSuccessfullyComplete() { var formatter = new ProtoBufFormatter(); var item = new Item { Id = 1, Name = "Filip" }; var ms = new MemoryStream(); await formatter.WriteToStreamAsync(typeof(Item), item, ms, new ByteArrayContent(new byte[0]), new Mock <TransportContext>().Object); var deserialized = ProtoBufFormatter.Model.Deserialize(ms, null, typeof(Item)); Assert.Same(deserialized, item); }
public async void WhenReadingFromStreamShouldSuccessfullyComplete() { var formatter = new ProtoBufFormatter(); var item = new Item { Id = 1, Name = "Filip" }; var ms = new MemoryStream(); ProtoBufFormatter.Model.Serialize(ms, item); var deserialized = await formatter.ReadFromStreamAsync(typeof(Item), ms, new ByteArrayContent(new byte[0]), new Mock <IFormatterLogger>().Object); Assert.Same(deserialized as Item, item); }
public void CanDeserializeType() { // Arrange var formatter = new ProtoBufFormatter(); var graph = new Employee(16) { Name = "Kalle", Age = 42 }; // Act var result = SerializationHelper.Clone <Employee>(graph, formatter); // Assert Assert.IsInstanceOf <Employee>(result); Assert.AreEqual("Kalle", result.Name); Assert.AreEqual(42, result.Age); Assert.AreEqual(16, result.ShoeSize); }
public void CanDeserializeComplexType() { // Arrange var formatter = new ProtoBufFormatter<Company>(); var graph = new Company() { Name = "Initech Corporation", Employees = new List<Employee> { new Employee() { Name = "Peter Gibbons", Age = 34 }, new Employee() { Name = "Michael Bolton", Age = 39 } } }; // Act var result = SerializationHelper.Clone<Company>(graph, formatter); // Assert Assert.AreEqual("Initech Corporation", result.Name); Assert.IsNotNull(result.Employees); Assert.AreEqual(2, result.Employees.Count); Assert.AreEqual("Peter Gibbons", result.Employees.ElementAt(0).Name); Assert.AreEqual("Michael Bolton", result.Employees.ElementAt(1).Name); }
public static void Register(HttpConfiguration config) { // Configure Json and Xml formatters config.Formatters.JsonPreserveReferences(); config.Formatters.XmlPreserveReferences(); // Configure ProtoBuf formatter var protoFormatter = new ProtoBufFormatter(); protoFormatter.ProtobufPreserveReferences(typeof(Category) .Assembly.GetTypes()); config.Formatters.Add(protoFormatter); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
public void Setup() { _config = new EngineConfiguration().ForIsolatedTest(); _config.PacketOptions = PacketOptions.Checksum; //assign unique ints to commands var commandTypeTags = new Dictionary <Type, int> { { typeof(AddItemCommand), 1 }, { typeof(RemoveItemCommand), 2 } }; //dynamic registration of command type (no attributes) var typeModel = TypeModel.Create(); MetaType mt = typeModel.Add(typeof(RemoveItemCommand), false) .Add(1, "Id"); mt.UseConstructor = false; ProtoBufFormatter.ConfigureJournaling(_config, commandTypeTags, typeModel); _store = _config.CreateStore(); }
static void Main(string[] args) { // Prompt user for media type Console.WriteLine("Select media type: {1} Xml, {2} Json, {3} Protobuf"); int selection = int.Parse(Console.ReadLine()); // Configure accept header and media type formatter MediaTypeFormatter formatter; string acceptHeader; switch (selection) { case 1: formatter = new XmlMediaTypeFormatter(); ((XmlMediaTypeFormatter)formatter).XmlPreserveReferences (typeof(Category), typeof(List <Product>)); acceptHeader = "application/xml"; break; case 2: formatter = new JsonMediaTypeFormatter(); ((JsonMediaTypeFormatter)formatter).JsonPreserveReferences(); acceptHeader = "application/json"; break; case 3: formatter = new ProtoBufFormatter(); ((ProtoBufFormatter)formatter).ProtobufPreserveReferences (typeof(Category).Assembly.GetTypes()); acceptHeader = "application/x-protobuf"; break; default: Console.WriteLine("Invalid selection: {0}", selection); return; } // Set base address to optionally use Fiddler Console.WriteLine("\nUse Fiddler?"); bool useFiddler = Console.ReadLine().ToUpper() == "Y"; string address = string.Format("http://localhost{0}:51248/api/", useFiddler ? ".fiddler" : string.Empty); // Create an http client with service base address var client = new HttpClient { BaseAddress = new Uri(address) }; // Set request accept header client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); // Get values response HttpResponseMessage response = client.GetAsync("customers").Result; response.EnsureSuccessStatusCode(); // Read response content as string array var customers = response.Content.ReadAsAsync <List <Customer> > (new[] { formatter }).Result; foreach (var c in customers) { Console.WriteLine("{0} {1} {2} {3}", c.CustomerId, c.CompanyName, c.City, c.Country); } // Get customer orders Console.WriteLine("\nCustomer Id:"); string customerId = Console.ReadLine(); response = client.GetAsync("orders?customerId=" + customerId).Result; response.EnsureSuccessStatusCode(); // Read response content var orders = response.Content.ReadAsAsync <List <Order> > (new[] { formatter }).Result; foreach (var o in orders) { PrintOrderWithDetails(o); } // Create a new order Console.WriteLine("\nPress Enter to create a new order"); Console.ReadLine(); var newOrder = new Order { CustomerId = customerId, OrderDate = DateTime.Today, ShippedDate = DateTime.Today.AddDays(1), OrderDetails = new List <OrderDetail> { new OrderDetail { ProductId = 1, Quantity = 5, UnitPrice = 10 }, new OrderDetail { ProductId = 2, Quantity = 10, UnitPrice = 20 }, new OrderDetail { ProductId = 4, Quantity = 40, UnitPrice = 40 } } }; // Post the new order response = client.PostAsync("orders", newOrder, formatter).Result; response.EnsureSuccessStatusCode(); var order = response.Content.ReadAsAsync <Order>(new[] { formatter }).Result; PrintOrderWithDetails(order); // Update the order date Console.WriteLine("\nPress Enter to update order date"); Console.ReadLine(); order.OrderDate = order.OrderDate.GetValueOrDefault().AddDays(1); // Put the updated order response = client.PutAsync("orders", order, formatter).Result; response.EnsureSuccessStatusCode(); order = response.Content.ReadAsAsync <Order>(new[] { formatter }).Result; PrintOrderWithDetails(order); // Delete the order Console.WriteLine("\nPress Enter to delete the order"); Console.ReadLine(); // Send delete response = client.DeleteAsync("Orders/" + order.OrderId).Result; response.EnsureSuccessStatusCode(); // Verify delete response = client.GetAsync("Orders/" + order.OrderId).Result; if (!response.IsSuccessStatusCode) { Console.WriteLine("Order deleted"); } Console.WriteLine("Press Enter to exit"); Console.ReadLine(); }
public void FormatterHasStreamingContext() { var formatter = new ProtoBufFormatter(); Assert.IsNotNull(formatter.Context); }
internal static T Clone <T>(T item, ProtoBufFormatter formatter = null) { return(Deserialize <T>(Serialize(item, formatter), formatter)); }
internal static T Deserialize <T>(Stream stream, ProtoBufFormatter formatter = null) { formatter = formatter ?? new ProtoBufFormatter(); return((T)formatter.Deserialize(stream)); }
static void Main(string[] args) { // Prompt user for media type Console.WriteLine("Select media type: {1} Xml, {2} Json, {3} Protobuf"); int selection = int.Parse(Console.ReadLine()); // Configure accept header and media type formatter MediaTypeFormatter formatter; string acceptHeader; switch (selection) { case 1: formatter = new XmlMediaTypeFormatter(); ((XmlMediaTypeFormatter)formatter).XmlPreserveReferences (typeof(Category), typeof(List <Product>)); acceptHeader = "application/xml"; break; case 2: formatter = new JsonMediaTypeFormatter(); ((JsonMediaTypeFormatter)formatter).JsonPreserveReferences(); acceptHeader = "application/json"; break; case 3: formatter = new ProtoBufFormatter(); ((ProtoBufFormatter)formatter).ProtobufPreserveReferences (typeof(Category).Assembly.GetTypes()); acceptHeader = "application/x-protobuf"; break; default: Console.WriteLine("Invalid selection: {0}", selection); return; } // Create an http client with service base address var client = new HttpClient { BaseAddress = new Uri("http://localhost:51245/api/products/"), }; // Set request accept header client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); // Get values response HttpResponseMessage response = client.GetAsync("").Result; response.EnsureSuccessStatusCode(); // Read response content as string array var products = response.Content.ReadAsAsync <List <Product> > (new[] { formatter }).Result; foreach (var p in products) { Console.WriteLine("{0} {1} {2} {3}", p.ProductId, p.ProductName, p.UnitPrice.GetValueOrDefault().ToString("C"), p.Category.CategoryName); } }
/// <summary> /// Реализует создание protobuf-форматтера. /// </summary> /// <returns>Возвращает protobuf-форматтер.</returns> public static ProtoBufFormatter CreateProtoBufFormatter() { var formatter = new ProtoBufFormatter(); return(formatter); }
public void SerializationContextStateIsSetToPersistence() { var formatter = new ProtoBufFormatter(); Assert.AreEqual(StreamingContextStates.Persistence, formatter.Context.State); }