Search Results

Search found 318 results on 13 pages for 'serializer'.

Page 1/13 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Using an alternate JSON Serializer in ASP.NET Web API

    - by Rick Strahl
    The new ASP.NET Web API that Microsoft released alongside MVC 4.0 Beta last week is a great framework for building REST and AJAX APIs. I've been working with it for quite a while now and I really like the way it works and the complete set of features it provides 'in the box'. It's about time that Microsoft gets a decent API for building generic HTTP endpoints into the framework. DataContractJsonSerializer sucks As nice as Web API's overall design is one thing still sucks: The built-in JSON Serialization uses the DataContractJsonSerializer which is just too limiting for many scenarios. The biggest issues I have with it are: No support for untyped values (object, dynamic, Anonymous Types) MS AJAX style Date Formatting Ugly serialization formats for types like Dictionaries To me the most serious issue is dealing with serialization of untyped objects. I have number of applications with AJAX front ends that dynamically reformat data from business objects to fit a specific message format that certain UI components require. The most common scenario I have there are IEnumerable query results from a database with fields from the result set rearranged to fit the sometimes unconventional formats required for the UI components (like jqGrid for example). Creating custom types to fit these messages seems like overkill and projections using Linq makes this much easier to code up. Alas DataContractJsonSerializer doesn't support it. Neither does DataContractSerializer for XML output for that matter. What this means is that you can't do stuff like this in Web API out of the box:public object GetAnonymousType() { return new { name = "Rick", company = "West Wind", entered= DateTime.Now }; } Basically anything that doesn't have an explicit type DataContractJsonSerializer will not let you return. FWIW, the same is true for XmlSerializer which also doesn't work with non-typed values for serialization. The example above is obviously contrived with a hardcoded object graph, but it's not uncommon to get dynamic values returned from queries that have anonymous types for their result projections. Apparently there's a good possibility that Microsoft will ship Json.NET as part of Web API RTM release.  Scott Hanselman confirmed this as a footnote in his JSON Dates post a few days ago. I've heard several other people from Microsoft confirm that Json.NET will be included and be the default JSON serializer, but no details yet in what capacity it will show up. Let's hope it ends up as the default in the box. Meanwhile this post will show you how you can use it today with the beta and get JSON that matches what you should see in the RTM version. What about JsonValue? To be fair Web API DOES include a new JsonValue/JsonObject/JsonArray type that allow you to address some of these scenarios. JsonValue is a new type in the System.Json assembly that can be used to build up an object graph based on a dictionary. It's actually a really cool implementation of a dynamic type that allows you to create an object graph and spit it out to JSON without having to create .NET type first. JsonValue can also receive a JSON string and parse it without having to actually load it into a .NET type (which is something that's been missing in the core framework). This is really useful if you get a JSON result from an arbitrary service and you don't want to explicitly create a mapping type for the data returned. For serialization you can create an object structure on the fly and pass it back as part of an Web API action method like this:public JsonValue GetJsonValue() { dynamic json = new JsonObject(); json.name = "Rick"; json.company = "West Wind"; json.entered = DateTime.Now; dynamic address = new JsonObject(); address.street = "32 Kaiea"; address.zip = "96779"; json.address = address; dynamic phones = new JsonArray(); json.phoneNumbers = phones; dynamic phone = new JsonObject(); phone.type = "Home"; phone.number = "808 123-1233"; phones.Add(phone); phone = new JsonObject(); phone.type = "Home"; phone.number = "808 123-1233"; phones.Add(phone); //var jsonString = json.ToString(); return json; } which produces the following output (formatted here for easier reading):{ name: "rick", company: "West Wind", entered: "2012-03-08T15:33:19.673-10:00", address: { street: "32 Kaiea", zip: "96779" }, phoneNumbers: [ { type: "Home", number: "808 123-1233" }, { type: "Mobile", number: "808 123-1234" }] } If you need to build a simple JSON type on the fly these types work great. But if you have an existing type - or worse a query result/list that's already formatted JsonValue et al. become a pain to work with. As far as I can see there's no way to just throw an object instance at JsonValue and have it convert into JsonValue dictionary. It's a manual process. Using alternate Serializers in Web API So, currently the default serializer in WebAPI is DataContractJsonSeriaizer and I don't like it. You may not either, but luckily you can swap the serializer fairly easily. If you'd rather use the JavaScriptSerializer built into System.Web.Extensions or Json.NET today, it's not too difficult to create a custom MediaTypeFormatter that uses these serializers and can replace or partially replace the native serializer. Here's a MediaTypeFormatter implementation using the ASP.NET JavaScriptSerializer:using System; using System.Net.Http.Formatting; using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Json; using System.IO; namespace Westwind.Web.WebApi { public class JavaScriptSerializerFormatter : MediaTypeFormatter { public JavaScriptSerializerFormatter() { SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")); } protected override bool CanWriteType(Type type) { // don't serialize JsonValue structure use default for that if (type == typeof(JsonValue) || type == typeof(JsonObject) || type== typeof(JsonArray) ) return false; return true; } protected override bool CanReadType(Type type) { if (type == typeof(IKeyValueModel)) return false; return true; } protected override System.Threading.Tasks.Taskobject OnReadFromStreamAsync(Type type, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, FormatterContext formatterContext) { var task = Taskobject.Factory.StartNew(() = { var ser = new JavaScriptSerializer(); string json; using (var sr = new StreamReader(stream)) { json = sr.ReadToEnd(); sr.Close(); } object val = ser.Deserialize(json,type); return val; }); return task; } protected override System.Threading.Tasks.Task OnWriteToStreamAsync(Type type, object value, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, FormatterContext formatterContext, System.Net.TransportContext transportContext) { var task = Task.Factory.StartNew( () = { var ser = new JavaScriptSerializer(); var json = ser.Serialize(value); byte[] buf = System.Text.Encoding.Default.GetBytes(json); stream.Write(buf,0,buf.Length); stream.Flush(); }); return task; } } } Formatter implementation is pretty simple: You override 4 methods to tell which types you can handle and then handle the input or output streams to create/parse the JSON data. Note that when creating output you want to take care to still allow JsonValue/JsonObject/JsonArray types to be handled by the default serializer so those objects serialize properly - if you let either JavaScriptSerializer or JSON.NET handle them they'd try to render the dictionaries which is very undesirable. If you'd rather use Json.NET here's the JSON.NET version of the formatter:// this code requires a reference to JSON.NET in your project #if true using System; using System.Net.Http.Formatting; using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Json; using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Converters; namespace Westwind.Web.WebApi { public class JsonNetFormatter : MediaTypeFormatter { public JsonNetFormatter() { SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")); } protected override bool CanWriteType(Type type) { // don't serialize JsonValue structure use default for that if (type == typeof(JsonValue) || type == typeof(JsonObject) || type == typeof(JsonArray)) return false; return true; } protected override bool CanReadType(Type type) { if (type == typeof(IKeyValueModel)) return false; return true; } protected override System.Threading.Tasks.Taskobject OnReadFromStreamAsync(Type type, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, FormatterContext formatterContext) { var task = Taskobject.Factory.StartNew(() = { var settings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, }; var sr = new StreamReader(stream); var jreader = new JsonTextReader(sr); var ser = new JsonSerializer(); ser.Converters.Add(new IsoDateTimeConverter()); object val = ser.Deserialize(jreader, type); return val; }); return task; } protected override System.Threading.Tasks.Task OnWriteToStreamAsync(Type type, object value, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, FormatterContext formatterContext, System.Net.TransportContext transportContext) { var task = Task.Factory.StartNew( () = { var settings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, }; string json = JsonConvert.SerializeObject(value, Formatting.Indented, new JsonConverter[1] { new IsoDateTimeConverter() } ); byte[] buf = System.Text.Encoding.Default.GetBytes(json); stream.Write(buf,0,buf.Length); stream.Flush(); }); return task; } } } #endif   One advantage of the Json.NET serializer is that you can specify a few options on how things are formatted and handled. You get null value handling and you can plug in the IsoDateTimeConverter which is nice to product proper ISO dates that I would expect any Json serializer to output these days. Hooking up the Formatters Once you've created the custom formatters you need to enable them for your Web API application. To do this use the GlobalConfiguration.Configuration object and add the formatter to the Formatters collection. Here's what this looks like hooked up from Application_Start in a Web project:protected void Application_Start(object sender, EventArgs e) { // Action based routing (used for RPC calls) RouteTable.Routes.MapHttpRoute( name: "StockApi", routeTemplate: "stocks/{action}/{symbol}", defaults: new { symbol = RouteParameter.Optional, controller = "StockApi" } ); // WebApi Configuration to hook up formatters and message handlers // optional RegisterApis(GlobalConfiguration.Configuration); } public static void RegisterApis(HttpConfiguration config) { // Add JavaScriptSerializer formatter instead - add at top to make default //config.Formatters.Insert(0, new JavaScriptSerializerFormatter()); // Add Json.net formatter - add at the top so it fires first! // This leaves the old one in place so JsonValue/JsonObject/JsonArray still are handled config.Formatters.Insert(0, new JsonNetFormatter()); } One thing to remember here is the GlobalConfiguration object which is Web API's static configuration instance. I think this thing is seriously misnamed given that GlobalConfiguration could stand for anything and so is hard to discover if you don't know what you're looking for. How about WebApiConfiguration or something more descriptive? Anyway, once you know what it is you can use the Formatters collection to insert your custom formatter. Note that I insert my formatter at the top of the list so it takes precedence over the default formatter. I also am not removing the old formatter because I still want JsonValue/JsonObject/JsonArray to be handled by the default serialization mechanism. Since they process in sequence and I exclude processing for these types JsonValue et al. still get properly serialized/deserialized. Summary Currently DataContractJsonSerializer in Web API is a pain, but at least we have the ability with relatively limited effort to replace the MediaTypeFormatter and plug in our own JSON serializer. This is useful for many scenarios - if you have existing client applications that used MVC JsonResult or ASP.NET AJAX results from ASMX AJAX services you can plug in the JavaScript serializer and get exactly the same serializer you used in the past so your results will be the same and don't potentially break clients. JSON serializers do vary a bit in how they serialize some of the more complex types (like Dictionaries and dates for example) and so if you're migrating it might be helpful to ensure your client code doesn't break when you switch to ASP.NET Web API. Going forward it looks like Microsoft is planning on plugging in Json.Net into Web API and make that the default. I think that's an awesome choice since Json.net has been around forever, is fast and easy to use and provides a ton of functionality as part of this great library. I just wish Microsoft would have figured this out sooner instead of now at the last minute integrating with it especially given that Json.Net has a similar set of lower level JSON objects JsonValue/JsonObject etc. which now will end up being duplicated by the native System.Json stuff. It's not like we don't already have enough confusion regarding which JSON serializer to use (JavaScriptSerializer, DataContractJsonSerializer, JsonValue/JsonObject/JsonArray and now Json.net). For years I've been using my own JSON serializer because the built in choices are both limited. However, with an official encorsement of Json.Net I'm happily moving on to use that in my applications. Let's see and hope Microsoft gets this right before ASP.NET Web API goes gold.© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api  AJAX  ASP.NET   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • A small, intra-app Object to String Serializer

    - by Rick Strahl
    On a few occasions I've needed a very compact serializer for small and simple, flat object serialization, typically for storage in Cookies or a FormsAuthentication ticket in ASP.NET. XML and JSON serialization are too verbose for those scenarios so a simple property serializer that strings together the values was needed. Originally I did this by hand, but here is a class that automates the process.

    Read the article

  • problem in loading class from 'me.prettyprint.hector.api.Serializer'

    - by dhananjay patil
    I have created executable jar but having some problem with Class not found Exception. When I type command: java -jar JarFileName.jar arguments.. I get error message, Exception in thread "main" java.lang.NoClassDefFoundError: me/prettyprint/hector/api/Serializer at com.ensarm.niidle.web.scraper.NiidleScrapeManager.main(NiidleScrapeManager.java:21) Caused by: java.lang.ClassNotFoundException: me.prettyprint.hector.api.Serializer at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) ... 1 more please tell me solution for this,class is not getting loaded from the external jar

    Read the article

  • how to write own serializer/deserializer?

    - by joseph
    Hello, I need to save objects - instances of classes - in my app like some filetype. How I can write own serializer/deserializer for it? Or exist some easier way how to save objects to some filetype? Using of io.serialization was commented as not so good solution for "real" app. Why?

    Read the article

  • JavaScript/JSON Serializer

    - by Water Cooler v2
    I see that a JSON serializer is present in the System.Web.Script.Serialization namespace, and is shipped in the System.Web.Extensions.dll assembly. Is this assembly distributed with the .NET framework v4.0 redistributable? Is it also guaranteed to be present on a user's machine if any edition of Visual Studio 2010 is installed?

    Read the article

  • How can I determine whether xml serializer can serialize a file

    - by ldsenow
    Hi, How can I determine whether xml serializer can serialize a file which is in a shared location and monitored by a file monitor. The file monitor has a list of parsers which are used to parse files in the shared folder. Once a file gets dropped into the folder, the file monitor will ask the registered parsers whether any of them can handle this file, if yes, the monitor will move the file out from the shared folder and assigns the task to the parser. Since some of the files are quite big, so I need to have a quick check on each parsers. How can I determine my xml parser can serialize the file without loading the full file into the memory?

    Read the article

  • How to configure a Custom Datacontract Serializer or XMLSerializer

    - by user364445
    Im haveing some xml that have this structure <Person Id="*****" Name="*****"> <AccessControlEntries> <AccessControlEntry Id="*****" Name="****"/> </AccessControlEntries> <AccessControls /> <IdentityGroups> <IdentityGroup Id="****" Name="*****" /> </IdentityGroups></Person> and i also have this entities [DataContract(IsReference = true)] public abstract class EntityBase { protected bool serializing; [DataMember(Order = 1)] [XmlAttribute()] public string Id { get; set; } [DataMember(Order = 2)] [XmlAttribute()] public string Name { get; set; } [OnDeserializing()] public void OnDeserializing(StreamingContext context) { this.Initialize(); } [OnSerializing()] public void OnSerializing(StreamingContext context) { this.serializing = true; } [OnSerialized()] public void OnSerialized(StreamingContext context) { this.serializing = false; } public abstract void Initialize(); public string ToXml() { var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; var sb = new System.Text.StringBuilder(); using (var writer = System.Xml.XmlWriter.Create(sb, settings)) { var serializer = new XmlSerializer(this.GetType()); serializer.Serialize(writer, this); } return sb.ToString(); } } [DataContract()] public abstract class Identity : EntityBase { private EntitySet<AccessControlEntry> accessControlEntries; private EntitySet<IdentityGroup> identityGroups; public Identity() { Initialize(); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "AccessControlEntries")] public EntitySet<AccessControlEntry> AccessControlEntries { get { if ((this.serializing && (this.accessControlEntries==null || this.accessControlEntries.HasLoadedOrAssignedValues == false))) { return null; } return accessControlEntries; } set { accessControlEntries.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] [Association(Name = "IdentityGroups")] public EntitySet<IdentityGroup> IdentityGroups { get { if ((this.serializing && (this.identityGroups == null || this.identityGroups.HasLoadedOrAssignedValues == false))) { return null; } return identityGroups; } set { identityGroups.Assign(value); } } private void attach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Add(this); } private void dettach_accessControlEntry(AccessControlEntry entity) { entity.Identities.Remove(this); } private void attach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } private void dettach_IdentityGroup(IdentityGroup entity) { entity.MemberIdentites.Add(this); } public override void Initialize() { this.accessControlEntries = new EntitySet<AccessControlEntry>( new Action<AccessControlEntry>(this.attach_accessControlEntry), new Action<AccessControlEntry>(this.dettach_accessControlEntry)); this.identityGroups = new EntitySet<IdentityGroup>( new Action<IdentityGroup>(this.attach_IdentityGroup), new Action<IdentityGroup>(this.dettach_IdentityGroup)); } } [XmlType(TypeName = "AccessControlEntry")] public class AccessControlEntry : EntityBase, INotifyPropertyChanged { private EntitySet<Service> services; private EntitySet<Identity> identities; private EntitySet<Permission> permissions; public AccessControlEntry() { services = new EntitySet<Service>(new Action<Service>(attach_Service), new Action<Service>(dettach_Service)); identities = new EntitySet<Identity>(new Action<Identity>(attach_Identity), new Action<Identity>(dettach_Identity)); permissions = new EntitySet<Permission>(new Action<Permission>(attach_Permission), new Action<Permission>(dettach_Permission)); } [DataMember(Order = 3, EmitDefaultValue = false)] public EntitySet<Permission> Permissions { get { if ((this.serializing && (this.permissions.HasLoadedOrAssignedValues == false))) { return null; } return permissions; } set { permissions.Assign(value); } } [DataMember(Order = 4, EmitDefaultValue = false)] public EntitySet<Identity> Identities { get { if ((this.serializing && (this.identities.HasLoadedOrAssignedValues == false))) { return null; } return identities; } set { identities.Assign(identities); } } [DataMember(Order = 5, EmitDefaultValue = false)] public EntitySet<Service> Services { get { if ((this.serializing && (this.services.HasLoadedOrAssignedValues == false))) { return null; } return services; } set { services.Assign(value); } } private void attach_Permission(Permission entity) { entity.AccessControlEntires.Add(this); } private void dettach_Permission(Permission entity) { entity.AccessControlEntires.Remove(this); } private void attach_Identity(Identity entity) { entity.AccessControlEntries.Add(this); } private void dettach_Identity(Identity entity) { entity.AccessControlEntries.Remove(this); } private void attach_Service(Service entity) { entity.AccessControlEntries.Add(this); } private void dettach_Service(Service entity) { entity.AccessControlEntries.Remove(this); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(name)); } #endregion public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "Person")] public class Person : Identity { private EntityRef<Login> login; [DataMember(Order = 3)] [XmlAttribute()] public string Nombre { get; set; } [DataMember(Order = 4)] [XmlAttribute()] public string Apellidos { get; set; } [DataMember(Order = 5)] public Login Login { get { return login.Entity; } set { var previousValue = this.login.Entity; if (((previousValue != value) || (this.login.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.login.Entity = null; previousValue.Person = null; } this.login.Entity = value; if ((value != null)) value.Person = this; } } } public override void Initialize() { base.Initialize(); } } [DataContract()] [XmlType(TypeName = "Login")] public class Login : EntityBase { private EntityRef<Person> person; [DataMember(Order = 3)] public string UserID { get; set; } [DataMember(Order = 4)] public string Contrasena { get; set; } [DataMember(Order = 5)] public Domain Dominio { get; set; } public Person Person { get { return person.Entity; } set { var previousValue = this.person.Entity; if (((previousValue != value) || (this.person.HasLoadedOrAssignedValue == false))) { if ((previousValue != null)) { this.person.Entity = null; previousValue.Login = null; } this.person.Entity = value; if ((value != null)) value.Login = this; } } } public override void Initialize() { throw new NotImplementedException(); } } [DataContract()] [XmlType(TypeName = "IdentityGroup")] public class IdentityGroup : Identity { private EntitySet<Identity> memberIdentities; public IdentityGroup() { Initialize(); } public override void Initialize() { this.memberIdentities = new EntitySet<Identity>(new Action<Identity>(this.attach_Identity), new Action<Identity>(this.dettach_Identity)); } [DataMember(Order = 3, EmitDefaultValue = false)] [Association(Name = "MemberIdentities")] public EntitySet<Identity> MemberIdentites { get { if ((this.serializing && (this.memberIdentities.HasLoadedOrAssignedValues == false))) { return null; } return memberIdentities; } set { memberIdentities.Assign(value); } } private void attach_Identity(Identity entity) { entity.IdentityGroups.Add(this); } private void dettach_Identity(Identity entity) { entity.IdentityGroups.Remove(this); } } [DataContract()] [XmlType(TypeName = "Group")] public class Group : Identity { public override void Initialize() { throw new NotImplementedException(); } } but the ToXml() response something like this <Person xmlns:xsi="************" xmlns:xsd="******" ID="******" Name="*****"/><AccessControlEntries/></Person> but what i want is something like this <Person Id="****" Name="***" Nombre="****"> <AccessControlEntries/> <IdentityGroups/> </Person>

    Read the article

  • "No message serializer has been configured" error when starting NServiceBus endpoint

    - by SteveBering
    My GenericHost hosted service is failing to start with the following message: 2010-05-07 09:13:47,406 [1] FATAL NServiceBus.Host.Internal.GenericHost [(null)] <(null) - System.InvalidOperationException: No message serializer has been con figured. at NServiceBus.Unicast.Transport.Msmq.MsmqTransport.CheckConfiguration() in d:\BuildAgent-02\work\672d81652eaca4e1\src\impl\unicast\NServiceBus.Unicast.Msmq\ MsmqTransport.cs:line 241 at NServiceBus.Unicast.Transport.Msmq.MsmqTransport.Start() in d:\BuildAgent-02\work\672d81652eaca4e1\src\impl\unicast\NServiceBus.Unicast.Msmq\MsmqTransport .cs:line 211 at NServiceBus.Unicast.UnicastBus.NServiceBus.IStartableBus.Start(Action startupAction) in d:\BuildAgent-02\work\672d81652eaca4e1\src\unicast\NServiceBus.Uni cast\UnicastBus.cs:line 694 at NServiceBus.Unicast.UnicastBus.NServiceBus.IStartableBus.Start() in d:\BuildAgent-02\work\672d81652eaca4e1\src\unicast\NServiceBus.Unicast\UnicastBus.cs:l ine 665 at NServiceBus.Host.Internal.GenericHost.Start() in d:\BuildAgent-02\work\672d81652eaca4e1\src\host\NServiceBus.Host\Internal\GenericHost.cs:line 77 My endpoint configuration looks like: public class ServiceEndpointConfiguration : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization { public void Init() { // build out persistence infrastructure var sessionFactory = Bootstrapper.InitializePersistence(); // configure NServiceBus infrastructure var container = Bootstrapper.BuildDependencies(sessionFactory); // set up logging log4net.Config.XmlConfigurator.Configure(); Configure.With() .Log4Net() .UnityBuilder(container) .XmlSerializer(); } } And my app.config looks like: <configSections> <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" /> <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" /> <section name="Logging" type="NServiceBus.Config.Logging, NServiceBus.Core" /> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" /> </configSections> <Logging Threshold="DEBUG" /> <MsmqTransportConfig InputQueue="NServiceBus.ServiceInput" ErrorQueue="NServiceBus.Errors" NumberOfWorkerThreads="1" MaxRetries="2" /> <UnicastBusConfig DistributorControlAddress="" DistributorDataAddress="" ForwardReceivedMessagesTo="NServiceBus.Auditing"> <MessageEndpointMappings> <!-- publishers don't need to set this for their own message types --> </MessageEndpointMappings> </UnicastBusConfig> <connectionStrings> <add name="Db" connectionString="Data Source=..." providerName="System.Data.SqlClient" /> </connectionStrings> <log4net debug="true"> <root> <level value="INFO"/> </root> <logger name="NHibernate"> <level value="ERROR" /> </logger> </log4net> This has worked in the past, but seems to be failing when the generic host starts. My endpoint configuration is below, along with the app.config for the service. What is strange is that in my endpoint configuration, I am specifying to use the XmlSerializer for message serialization. I don't see any other errors in the console output preceding the error message. What am I missing? Thanks, Steve

    Read the article

  • XML serializer filename

    - by Alexander
    I want to serialize an object into an xml and I want the filename of the xml to be random as following 636211ad-ef28-47b9-aa60-207d3fbb9580.xml fc3b491e5-59ac-4f6a-81e5-27e971b903ed.xml I am just curious on how to do such thing?

    Read the article

  • Coercing Json Serializer into producing a particular datetime format (yyyy-mm-ddThh:mm:ss.msmsmsZ)

    - by Chris McCall
    MyClass theSession = new MyClass() { accountId = 12345, timeStamp = DateTime.Now, userType = "theUserType" }; System.Web.Script.Serialization.JavaScriptSerializer Json = new System.Web.Script.Serialization.JavaScriptSerializer(); Response.Write(Json.Serialize(theSession)); Produces: {"accountId":12345,"timeStamp":"\/Date(1268420981135)\/","userType":"theUserType"} How can I present the date as: "timestamp":"2010-02-15T23:53:35.963Z" ?

    Read the article

  • C# xml serializer - Unable to generate a temporary class

    - by gosom
    I am trying to serialize an xml to a class with the following way: XmlSerializer ser = new XmlSerializer(typeof(PSW5ns.PSW5)); StringReader stringReader; stringReader = new StringReader(response_xml); XmlTextReader xmlReader; xmlReader = new XmlTextReader(stringReader); PSW5ns.PSW5 obj; obj = (PSW5ns.PSW5)ser.Deserialize(xmlReader); xmlReader.Close(); stringReader.Close(); the class PSW5 is generated automatically by xsd.exe using an PSW5.xsd file given to me. I have done the same for other classes and it works. Now i get the following error (during runtime) : {"Unable to generate a temporary class (result=1).\r\nerror CS0030: Cannot convert type 'PSW5ns.TAX_INF[]' to 'PSW5ns.TAX_INF'\r\nerror CS0029: Cannot implicitly convert type 'PSW5ns.TAX_INF' to 'PSW5ns.TAX_INF[]'\r\n"} I am confused because it works for other classes the same way. I would appreciate any suggestions. Thanks inadvance, Giorgos

    Read the article

  • Easy XML Serializer for Java

    - by sdoca
    I'm looking for a way to serialize Java objects into XML for use by a RESTful web service. I don't have an XSD. I have looked at the following: JAXB - fairly heavy weight with annotations required on classes and also an ObjectFactory class and/or a jaxb.index file Simple - requires annotations but no other config classes/files. Unfortunately it can't serialize Sets. XStream - no annotations etc. required, but doesn't support generics Does anyone else have any suggestions?

    Read the article

  • MongoDB C# - Hide property from serializer

    - by ehftwelve
    This is what my user model looks like: namespace Api.Models { public class User { [BsonId(IdGenerator = typeof(StringObjectIdGenerator))] [BsonRequired] public string Id { get; set; } [Required(ErrorMessage = "Username is required.")] [StringLength(20, MinimumLength=3, ErrorMessage="Username must be between 3 and 20 characters.")] [BsonRequired] public string Username { get; set; } [Required(ErrorMessage="Email is required.")] [EmailAddress(ErrorMessage="Valid email required.")] [BsonRequired] public string Email { get; set; } [Required(ErrorMessage = "Password is required.")] [StringLength(50, MinimumLength=8, ErrorMessage="Password must be between 8 and 50 characters.")] [BsonRequired] public string Password { get; set; } [BsonRequired] public string Salt { get; set; } } } I want to write, and require, all of the properties into the MongoDB Database. What I don't want to do, is expose the Password and Salt properties when I send this through the request. Is there any sort of data attribute that I can set that will write it, but not expose it when displayed to any API user?

    Read the article

  • C# xml serializer - serialize derived objects

    - by gln
    Hi, I want to serialize the following: [Serializable] [DefaultPropertyAttribute("Name")] [XmlInclude(typeof(ItemInfo))] [XmlInclude(typeof(ItemInfoA))] [XmlInclude(typeof(ItemInfoB))] public class ItemInfo { private string name; [XmlArray("Items"), XmlArrayItem(typeof(ItemInfo))] private ArrayList arr; private ItemInfo parentItemInfo; } [Serializable] [XmlInclude(typeof(ItemInfo))] [XmlInclude(typeof(ItemInfoA))] [XmlInclude(typeof(ItemInfoB))] public class ItemInfoA : ItemInfo { ... } [Serializable] [XmlInclude(typeof(ItemInfo))] [XmlInclude(typeof(ItemInfoA))] [XmlInclude(typeof(ItemInfoB))] public class ItemInfoB : ItemInfo { ... } The class itemInfo describes a container which can hold other itemInfo objects in the array list, the parentItemInfo describes which is the parent container of the item info. Since ItemInfoA and ItemInfoB derive from ItemInfo they can also be a member of the array list and the parentItemInfo, therefore when trying to serialize these objects (which can hold many objects in hierarchy) it fails with exception can't generate the xml file - innerexception. My question is: What attributes do I need to add the ItemInfo class so it will be serializable? Note: the exception is only when the ItemInfo[A]/[B] are initialized with parentItemInfo or the arrayList. Help please! Thanks!

    Read the article

  • What .NET serializers have fixed size output for a given class?

    - by Jader Dias
    XML based serializers have variable size output for a given class. I can't use them to append data to my Memcached list, since I won't be able to retrieve that information later. But if I knew my serializer produced a fixed size output (N bytes), I could retrieve my data by splitting my list in N bytes chunks and then deserializing those chunks individually. I have created my own serializer for my class, but what other serializers I could use?

    Read the article

  • how to get json string value?

    - by Net205
    var responseFromServer = "{\"flag\":true,\"message\":\"\",\"result\":{\"ServicePermission\":true,\"UserGroupPermission\":true}}"; var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var responseValue = serializer.DeserializeObject(responseFromServer); responseFromServer value is get a webservice, and then how to get the json string value, such as "flag","Servicepermission"??

    Read the article

  • Why does DataContractJsonSerializer not include generic like JavaScriptSerializer?

    - by Patrick Magee
    So the JavaScriptSerializer was deprecated in favor of the DataContractJsonSerializer. var client = new WebClient(); var json = await client.DownloadStringTaskAsync(url); // http://example.com/api/people/1 // Deprecated, but clean looking and generally fits in nicely with // other code in my app domain that makes use of generics var serializer = new JavaScriptSerializer(); Person p = serializer.Deserialize<Person>(json); // Now have to make use of ugly typeof to get the Type when I // already know the Type at compile type. Why no Generic type T? var serializer = new DataContractJsonSerializer(typeof(Person)); Person p = serializer.ReadObject(json) as Person; The JavaScriptSerializer is nice and allows you to deserialize using a type of T generic in the function name. Understandably, it's been deprecated for good reason, with the DataContractJsonSerializer, you can decorate your Type to be deserialized with various things so it isn't so brittle like the JavaScriptSerializer, for example [DataMember(name = "personName")] public string Name { get; set; } Is there a particular reason why they decided to only allow users to pass in the Type? Type type = typeof(Person); var serializer = new DataContractJsonSerializer(type); Person p = serializer.ReadObject(json) as Person; Why not this? var serializer = new DataContractJsonSerializer(); Person p = serializer.ReadObject<Person>(json); They can still use reflection with the DataContract decorated attributes based on the T that I've specified on the .ReadObject<T>(json)

    Read the article

  • Android XmlSerializer limitation?

    - by Rexb
    Hi all, My task is just to get an xml string using XmlSerializer. Problem is that it seems like the serializer stops adding any new element and/or attribute to the xml document when it reaches certain length (perhaps 10,000 char?). My questions: have you experience this kind of problem? What could be possible solutions? Here is my sample test code: public void doSerialize() throws XmlPullParserException, IllegalArgumentException, IllegalStateException, IOException { StringWriter writer = new StringWriter(); XmlSerializer serializer = XmlPullParserFactory.newInstance().newSerializer(); serializer.setOutput(writer); serializer.startDocument(null, null); serializer.startTag(null, "START"); for (int i = 0; i < 20; i++) { serializer.attribute(null, "ATTR" + i, "VAL " + i); } serializer.startTag(null, "DATA"); for (int i = 0; i < 500; i++) { serializer.attribute(null, "attr" + i, "value " + i); } serializer.endTag(null, "DATA"); serializer.endTag(null, "START"); serializer.endDocument(); String xml = writer.toString(); // value: until 493rd attribute int n = xml.length(); // value: 10125 } Any help will be greatly appreciated.

    Read the article

  • Solved: Operation is not valid due to the current state of the object

    - by ChrisD
    We use public static methods decorated with [WebMethod] to support our Ajax Postbacks.   Recently, I received an error from a UI developing stating he was receiving the following error when attempting his post back: {   "Message": "Operation is not valid due to the current state of the object.",   "StackTrace": "   at System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject(IDictionary`2 dictionary, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",   "ExceptionType": "System.InvalidOperationException" }   Goggling this error brought me little support.  All the results talked about increasing the aspnet:MaxJsonDeserializerMembers value to handle larger payloads.  Since 1) I’m not using the asp.net ajax model and 2) the payload is very small, this clearly was not the cause of my issue. Here’s the payload the UI developer was sending to the endpoint: {   "FundingSource": {     "__type": "XX.YY.Engine.Contract.Funding.EvidenceBasedFundingSource,  XX.YY.Engine.Contract",     "MeansType": 13,     "FundingMethodName": "LegalTender",   },   "AddToProfile": false,   "ProfileNickName": "",   "FundingAmount": 0 } By tweaking the JSON I’ve found the culprit. Apparently the default JSS Serializer used doesn’t like the assembly name in the __type value.  Removing the assembly portion of the type name resolved my issue. { "FundingSource": { "__type": "XX.YY.Engine.Contract.Funding.EvidenceBasedFundingSource", "MeansType": 13, "FundingMethodName": "LegalTender", }, "AddToProfile": false, "ProfileNickName": "", "FundingAmount": 0 }

    Read the article

  • .NET: Serializing object to a file from a 3rd party assembly

    - by MacGyver
    Below is a link that describes how to serialize an object. But it requires you implement from ISerializable for the object you are serializing. What I'd like to do is serialize an object that I did not define--an object based on a class in a 3rd party assembly (from a project reference) that is not implementing ISerializable. Is that possible? How can this be done? http://www.switchonthecode.com/tutorials/csharp-tutorial-serialize-objects-to-a-file Property (IWebDriver = interface type): private IWebDriver driver; Object Instance (FireFoxDriver is a class type): driver = new FirefoxDriver(firefoxProfile); ================ 3/21/2012 update after answer posted Why would this throw an error? It doesn't like this line: serializedObject.DriverInstance = (FirefoxDriver)driver; ... Error: Cannot implicitly convert type 'OpenQA.Selenium.IWebDriver' to 'OpenQA.Selenium.Firefox.FirefoxDriver'. An explicit conversion exists (are you missing a cast?) Here is the code: FirefoxDriverSerialized serializedObject = new FirefoxDriverSerialized(); Serializer serializer = new Serializer(); serializedObject = serializer.DeSerializeObject(@"C:\firefoxDriver.qa"); driver = serializedObject.DriverInstance; if (driver == null) { driver = new FirefoxDriver(firefoxProfile); serializedObject.DriverInstance = (FirefoxDriverSerialized)driver; serializer.SerializeObject(@"C:\firefoxDriver.qa", serializedObject); } Here are the two Serializer classes I built: public class Serializer { public Serializer() { } public void SerializeObject(string filename, FirefoxDriverSerialized objectToSerialize) { Stream stream = File.Open(filename, FileMode.Create); BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, objectToSerialize); stream.Close(); } public FirefoxDriverSerialized DeSerializeObject(string filename) { FirefoxDriverSerialized objectToSerialize; Stream stream = File.Open(filename, FileMode.Open); BinaryFormatter bFormatter = new BinaryFormatter(); objectToSerialize = (FirefoxDriverSerialized)bFormatter.Deserialize(stream); stream.Close(); return objectToSerialize; } } [Serializable()] public class FirefoxDriverSerialized : FirefoxDriver, ISerializable { private FirefoxDriver driverInstance; public FirefoxDriver DriverInstance { get { return this.driverInstance; } set { this.driverInstance = value; } } public FirefoxDriverSerialized() { } public FirefoxDriverSerialized(SerializationInfo info, StreamingContext ctxt) { this.driverInstance = (FirefoxDriver)info.GetValue("DriverInstance", typeof(FirefoxDriver)); } public void GetObjectData(SerializationInfo info, StreamingContext ctxt) { info.AddValue("DriverInstance", this.driverInstance); } } ================= 3/23/2012 update #2 - fixed serialization/de-serialization, but having another issue (might be relevant for new question) This fixed the calling code. Because we're deleting the *.qa file when we call the WebDriver.Quit() because that's when we chose to close the browser. This will kill off our cached driver as well. So if we start with a new browser window, we'll hit the catch block and create a new instance and save it to our *.qa file (in the serialized form). FirefoxDriverSerialized serializedObject = new FirefoxDriverSerialized(); Serializer serializer = new Serializer(); try { serializedObject = serializer.DeSerializeObject(@"C:\firefoxDriver.qa"); driver = serializedObject.DriverInstance; } catch { driver = new FirefoxDriver(firefoxProfile); serializedObject = new FirefoxDriverSerialized(); serializedObject.DriverInstance = (FirefoxDriver)driver; serializer.SerializeObject(@"C:\firefoxDriver.qa", serializedObject); } However, still getting this exception: Acu.QA.Main.Test_0055_GiftCertificate_UserCheckout: SetUp : System.Runtime.Serialization.SerializationException : Type 'OpenQA.Selenium.Firefox.FirefoxDriver' in Assembly 'WebDriver, Version=2.16.0.0, Culture=neutral, PublicKeyToken=1c2bd1631853048f' is not marked as serializable. TearDown : System.NullReferenceException : Object reference not set to an instance of an object. The 3rd line in this code block is throwing the exception: public void SerializeObject(string filename, FirefoxDriverSerialized objectToSerialize) { Stream stream = File.Open(filename, FileMode.Create); BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, objectToSerialize); // <=== this line stream.Close(); }

    Read the article

  • Saxon XSLT-Transformation: How to change serialization of an empty tag from <x/> to <x></x>?

    - by Ben
    Hello folks! I do some XSLT-Transformation using Saxon HE 9.2 with the output later being unmarshalled by Castor 1.3.1. The whole thing runs with Java at the JDK 6. My XSLT-Transformation looks like this: <xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns="http://my/own/custom/namespace/for/the/target/document"> <xsl:output method="xml" encoding="UTF-8" indent="no" /> <xsl:template match="/"> <ns:item> <ns:property name="id"> <xsl:value-of select="/some/complicated/xpath" /> </ns:property> <!-- ... more ... --> </xsl:template> So the thing is: if the XPath-expression /some/complicated/xpath evaluates to an empty sequence, the Saxon serializer writes <ns:property/> instead of <ns:property></ns:property>. This, however, confuses the Castor unmarshaller, which is next in the pipeline and which unmarshals the output of the transformation to instances of XSD-generated Java-code. So my question is: How can I tell the Saxon-serializer to output empty tags not as standalone tags? Here is what I am proximately currently doing to execute the transformation: import net.sf.saxon.s9api.*; import javax.xml.transform.*; import javax.xml.transform.sax.SAXSource; // ... // read data XMLReader xmlReader = XMLReaderFactory.createXMLReader(); // ... there is some more setting up the xmlReader here ... InputStream xsltStream = new FileInputStream(xsltFile); InputStream inputStream = new FileInputStream(inputFile); Source xsltSource = new SAXSource(xmlReader, new InputSource(xsltStream)); Source inputSource = new SAXSource(xmlReader, new InputSource(inputStream)); XdmNode input = processor.newDocumentBuilder().build(inputSource); // initialize transformation configuration Processor processor = new Processor(false); XsltCompiler compiler = processor.newXsltCompiler(); compiler.setErrorListener(this); XsltExecutable executable = compiler.compile(xsltSource); Serializer serializer = new Serializer(); serializer.setOutputProperty(Serializer.Property.METHOD, "xml"); serializer.setOutputProperty(Serializer.Property.INDENT, "no"); serializer.setOutputStream(output); // execute transformation XsltTransformer transformer = executable.load(); transformer.setInitialContextNode(input); transformer.setErrorListener(this); transformer.setDestination(serializer); transformer.setSchemaValidationMode(ValidationMode.STRIP); transformer.transform(); I'd appreciate any hint pointing in the direction of a solution. :-) In case of any unclarity I'd be happy to give more details. Nightly greetings from Germany, Benjamin

    Read the article

  • LLBLGen Pro and JSON serialization

    - by FransBouma
    I accidentally removed a reply from my previous blogpost, and as this blog-engine here at weblogs.asp.net is apparently falling apart, I can't re-add it as it thought it would be wise to disable comment controls on all posts, except new ones. So I'll post the reply here as a quote and reply on it. 'Steven' asks: What would the future be for LLBLGen Pro to support JSON for serialization? Would it be worth the effort for a LLBLGenPro user to bother creating some code templates to produce additional JSON serializable classes? Or just create some basic POCO classes which could be used for exchange of client/server data and use DTO to map these back to LLBGenPro ones? If I understand the work around, it is at the expense of losing xml serialization. Well, as described in the previous post, to enable JSON serialization, you can do that with a couple of lines and some attribute assignments. However, indeed, the attributes might make the XML serialization not working, as described in the previous blogpost. This is the case if the service you're using serializes objects using the DataContract serializer: this serializer will give up to serialize the entity objects to XML as the entity objects implement IXmlSerializable and this is a no-go area for the DataContract serializer. However, if your service doesn't use a DataContract serializer, or you serialize the objects manually to Xml using an xml serializer, you're fine. When you want to switch to Xml serializing again, instead of JSON in WebApi, and you have decorated the entity classes with the data-contract attributes, you can switch off the DataContract serializer, by setting a global configuration setting: var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter; xml.UseXmlSerializer = true; This will make the WebApi use the XmlSerializer, and run the normal IXmlSerializable interface implementation.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >