Search Results

Search found 257 results on 11 pages for 'deserialization'.

Page 9/11 | < Previous Page | 5 6 7 8 9 10 11  | Next Page >

  • Is it possible to handle User Defined Exception using JAX WS Dispatch API ?

    - by snowflake
    Hello, I'm performing dynamic webservices call using following code snippet: JAXBContext jc = getJAXBContext(requestClass, responseClass, jaxbContextExtraClasses); Dispatch<Object> dispatch = service.createDispatch(portQName, jc, Service.Mode.PAYLOAD); Object requestValue = getRequestValue(requestClass, pOrderedParameters); JAXBElement<?> request = new JAXBElement(new QName(serviceQNameStr, pOperationName), requestValue.getClass(), null, requestValue); Object tmpResponse = dispatch.invoke(request); Invocation works perfectly, except if I add a user defined exception on the service (a basic UserException extends java.lang.Exception). First I get: javax.xml.bind.UnmarshalException: unexpected element (uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Fault"). Expected elements are <{http://my.namespace/}myMethod,<{http://my.namespace/}myResponse Then I added the UserException_Exception JAX-WS generated type to my JAXB Context, and then get: Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions java.lang.StackTraceElement does not have a no-arg default constructor. this problem is related to the following location: at java.lang.StackTraceElement at public java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace() at java.lang.Throwable at java.lang.Exception Only solution available I found are: dispatch directly a Soap message and handle Soap fault directly (this is the way Jboss JAX-WS implementation performs a standard JAX-WS call using services interfaces). This is not an available solution for me, I want to use a high level implementation (the more I get close to Soap message the less dynamic my code can be) usage of JAXBRIContext.ANNOTATION_READER, which is implementation specific and not an available solution for me, in order to annotate annotates java.lang.Exception as @XmlTransient The service with a user defined exception performs well using the JAX-WS generated standard client stubs and using a tool such Soap UI. Problem occurs in deserialization of the message when I have no user defined exception artifact in the JAXB context, and during invocation when I add those non JAXB compatible artifacts in the JAXB context. I'm usign Jboss WS webservice stack within Jboss 4.2.3.GA Any elegant solution to this problem is welcomed !

    Read the article

  • Retrieve data from .dat file.

    - by Zach
    We have an application which requires us to read data from a file (.dat) dynamically using deserialization. We are actually getting first object and it throws null pointer exception when we are accessing other objects using a "for" loop. File file=null; FileOutputStream fos=null; BufferedOutputStream bos=null; ObjectOutputStream oos=null; try{ file=new File("account4.dat"); fos=new FileOutputStream(file,true); bos=new BufferedOutputStream(fos); oos=new ObjectOutputStream(bos); oos.writeObject(m); System.out.println("object serialized"); amlist=new MemberAccountList(); oos.close(); } catch(Exception ex){ ex.printStackTrace(); } Reading objects: try{ MemberAccount m1; file=new File("account4.dat");//add your code here fis=new FileInputStream(file); bis=new BufferedInputStream(fis); ois=new ObjectInputStream(bis); System.out.println(ois.readObject()); while(ois.readObject()!=null){ m1=(MemberAccount)ois.readObject(); System.out.println(m1.toString()); }/mList.addElement(m1); // Here we have the issue throwing null pointer exception Enumeration elist=mList.elements(); while(elist.hasMoreElements()){ obj=elist.nextElement(); System.out.println(obj.toString()); }/ } catch(ClassNotFoundException e){ } catch(EOFException e){ System.out.println("end"); } catch(Exception ex){ ex.printStackTrace(); }

    Read the article

  • Java SortedMap to Scala TreeMap

    - by Dave
    I'm having trouble converting a java SortedMap into a scala TreeMap. The SortedMap comes from deserialization and needs to be converted into a scala structure before being used. Some background, for the curious, is that the serialized structure is written through XStream and on desializing I register a converter that says anything that can be assigned to SortedMap[Comparable[_],_] should be given to me. So my convert method gets called and is given an Object that I can safely cast because I know it's of type SortedMap[Comparable[_],_]. That's where it gets interesting. Here's some sample code that might help explain it. // a conversion from comparable to ordering scala> implicit def comparable2ordering[A <: Comparable[A]](x: A): Ordering[A] = new Ordering[A] { | def compare(x: A, y: A) = x.compareTo(y) | } comparable2ordering: [A <: java.lang.Comparable[A]](x: A)Ordering[A] // jm is how I see the map in the converter. Just as an object. I know the key // is of type Comparable[_] scala> val jm : Object = new java.util.TreeMap[Comparable[_], String]() jm: java.lang.Object = {} // It's safe to cast as the converter only gets called for SortedMap[Comparable[_],_] scala> val b = jm.asInstanceOf[java.util.SortedMap[Comparable[_],_]] b: java.util.SortedMap[java.lang.Comparable[_], _] = {} // Now I want to convert this to a tree map scala> collection.immutable.TreeMap() ++ (for(k <- b.keySet) yield { (k, b.get(k)) }) <console>:15: error: diverging implicit expansion for type Ordering[A] starting with method Tuple9 in object Ordering collection.immutable.TreeMap() ++ (for(k <- b.keySet) yield { (k, b.get(k)) })

    Read the article

  • Are there any radix/patricia/critbit trees for Python?

    - by Andrew Dalke
    I have about 10,000 words used as a set of inverted indices to about 500,000 documents. Both are normalized so the index is a mapping of integers (word id) to a set of integers (ids of documents which contain the word). My prototype uses Python's set as the obvious data type. When I do a search for a document I find the list of N search words and their corresponding N sets. I want to return the set of documents in the intersection of those N sets. Python's "intersect" method is implemented as a pairwise reduction. I think I can do better with a parallel search of sorted sets, so long as the library offers a fast way to get the next entry after i. I've been looking for something like that for some time. Years ago I wrote PyJudy but I no longer maintain it and I know how much work it would take to get it to a stage where I'm comfortable with it again. I would rather use someone else's well-tested code, and I would like one which supports fast serialization/deserialization. I can't find any, or at least not any with Python bindings. There is avltree which does what I want, but since even the pair-wise set merge take longer than I want, I suspect I want to have all my operations done in C/C++. Do you know of any radix/patricia/critbit tree libraries written as C/C++ extensions for Python? Failing that, what is the most appropriate library which I should wrap? The Judy Array site hasn't been updated in 6 years, with 1.0.5 released in May 2007. (Although it does build cleanly so perhaps It Just Works.)

    Read the article

  • Thread Local Memory, Using std::string's internal buffer for c-style Scratch Memory.

    - by Hassan Syed
    I am using Protocol Buffers and OpensSSL to generate, HMACs and then CBC encrypt the two fields to obfuscate the session cookies -- similar Kerberos tokens. Protocol Buffers' API communicates with std::strings and has a buffer caching mechanism; I exploit the caching mechanism, for successive calls in the the same thread, by placing it in thread local memory; additionally the OpenSSL HMAC and EVP CTX's are also placed in the same thread local memory structure ( see this question for some detail on why I use thread local memory and the massive amount of speedup it enables even with a single thread). The generation and deserialization, "my algorithms", of these cookie strings uses intermediary void *s and std::strings and since Protocol Buffers has an internal memory retention mechanism I want these characteristics for "my algorithms". So how do I implement a common scratch memory ? I don't know much about the rdbuf(streambuf - strinbuf ??) of the std::string object. I would presumeably need to grow it to the lowest common size ever encountered during the execution of "my algorithms". Thoughts ? My question I guess would be: " is the internal buffer of a string re-usable, and if so, how ?" Edit: See comments to Vlad's answer please.

    Read the article

  • Modifying NSMutableDictionary from a single index format into nested (array within array)

    - by Michael Robinson
    I need to take the member ID off the top of this and create an array inside that contains the rest of the JSON return. Here is my JSON return. [{"F_Name_VC":"Frank", "L_Name_VC":"Johnson", "userid":"18", "age":"23", },] After it is json-deserialized it looks like this: I need convert it to be transformed into this, with children sub-array: Someone else posted a similar question but without the fact that it was coming from a JSON deserialization. There were two answers but no conclusion to the question. (Answer 1): NSDictionary *item1 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@" member",[NSNumber numberWithInt:3],nil] forKeys:[NSArray arrayWithObjects:@"Title",@"View",nil]]; Answer (2): NSMutableArray *Rows = [NSMutableArray arrayWithCapacity: 1]; for (int i = 0; i < 4; ++i) { NSMutableArray *theChildren = [NSMutableArray arrayWithCapacity: 1]; [theChildren addObject: [NSString stringWithFormat: @"tester %d", i]]; NSString *aTitle = [NSString stringWithFormat: @"Item %d", i]; NSDictionary *anItem = [NSDictionary dictionaryWithObjectsAndKeys: aTitle, @"Title", theChildren, @"Children"]; [Rows addObject: anItem]; } NSDictionary *Root = [NSDictionary withObject: Rows andKey: @"Rows"]; Here is my JSON return and save code: NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding]; NSError *error = nil; NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error]; if (dict) { rowsArray = [dict objectForKey:@"member"]; [rowsArray retain]; } Thanks in advance. Every tutorial on JSON only shows a simple array being returned, never with children..It's driving me crazy trying to figure this out.

    Read the article

  • Replace apostrophe in json string with empty string

    - by user572844
    Hi, I have problem with deserialization of json string, because string is bad format. For example json object consist string property statusMessage with value "Hello "dog" ". The correct format should be "Hello \" dog \" " . I would like remove apostrophes from this property. Something Like this. "Hello "dog" ". - "Hello dog ". Here is it original json string which I work. "{\"jancl\":{\"idUser\":18438201,\"nick\":\"JANCl\",\"photo\":\"1\",\"sex\":1,\"photoAlbums\":1,\"videoAlbums\":0,\"sefNick\":\"jancl\",\"profilPercent\":75,\"emphasis\":false,\"age\":\"-\",\"isBlocked\":false,\"PHOTO\":{\"normal\":\"http://u.aimg.sk/fotky/1843/82/n_18438201.jpg?v=1\",\"medium\":\"http://u.aimg.sk/fotky/1843/82/m_18438201.jpg?v=1\",\"24x24\":\"http://u.aimg.sk/fotky/1843/82/s_18438201.jpg?v=1\"},\"PLUS\":{\"active\":false,\"activeTo\":\"0000-00-00\"},\"LOCATION\":{\"idRegion\":\"6\",\"regionName\":\"Trenciansky kraj\",\"idCity\":\"138\",\"cityName\":\"Trencianske Teplice\"},\"STATUS\":{\"isLoged\":true,\"isChating\":false,\"idChat\":0,\"roomName\":\"\",\"lastLogin\":1294925369},\"PROJECT_STATUS\":{\"photoAlbums\":1,\"photoAlbumsFavs\":0,\"videoAlbums\":0,\"videoAlbumsFavs\":0,\"videoAlbumsExts\":0,\"blogPosts\":0,\"emailNew\":0,\"postaNew\":0,\"clubInvitations\":0,\"dashboardItems\":1},\"STATUS_MESSAGE\":{\"statusMessage\":\"\"Status\"\",\"addTime\":\"1294872330\"},\"isFriend\":false,\"isIamFriend\":false}}" Problem is here, json string consist this object: "STATUS_MESSAGE": {"statusMessage":" "some "bad" value" ", "addTime" :"1294872330"} Condition of string which I want modified: string start with "statusMessage":" string can has any *lenght from 0 -N * string end with ", "addTime So I try write pattern for string which start with "statusMessage":", has any lenght and is ended with ", "addTime. Here is it: const string pattern = " \" statusMessage \" : \" .*? \",\"addTime\" "; var regex = new Regex(pattern, RegexOptions.IgnoreCase); //here i would replace " with empty string string result = regex.Replace(jsonString, match => ???); But I think pattern is wrong, also I don’t know how replace apostrophe with empty string (remove apostrophne). My goal is : "statusMessage":" "some "bad" value" to "statusMessage":" "some bad value" Thank for advice

    Read the article

  • How to store a list in a column of a database table.

    - by John Berryman
    Howdy! So, per Mehrdad's answer to a related question, I get it that a "proper" database table column doesn't store a list. Rather, you should create another table that effectively holds the elements of said list and then link to it directly or through a junction table. However, the type of list I want to create will be composed of unique items (unlike the linked question's fruit example). Furthermore, the items in my list are explicitly sorted - which means that if I stored the elements in another table, I'd have to sort them every time I accessed them. Finally, the list is basically atomic in that any time I wish to access the list, I will want to access the entire list rather than just a piece of it - so it seems silly to have to issue a database query to gather together pieces of the list. AKX's solution (linked above) is to serialize the list and store it in a binary column. But this also seems inconvenient because it means that I have to worry about serialization and deserialization. Is there any better solution? If there is no better solution, then why? It seems that this problem should come up from time to time. ... just a little more info to let you know where I'm coming from. As soon as I had just begun understanding SQL and databases in general, I was turned on to LINQ to SQL, and so now I'm a little spoiled because I expect to deal with my programming object model without having to think about how the objects are queried or stored in the database. Thanks All! John

    Read the article

  • Cast errors with IXmlSerializable

    - by Nathan
    I am trying to use the IXmlSerializable interface to deserialize an Object (I am using it because I need specific control over what gets deserialized and what does not. See my previous question for more information). However, I'm stumped as to the error message I get. Below is the error message I get (I have changed some names for clarity): An unhandled exception of type 'System.InvalidCastException' occurred in App.exe Additional information: Unable to cast object of type 'System.Xml.XmlNode[]' to type 'MyObject'. MyObject has all the correct methods defined for the interface, and regardless of what I put in the method body for ReadXml() I still get this error. It doesn't matter if it has my implementation code or if it's just blank. I did some googling and found an error that looks similar to this involving polymorphic objects that implement IXmlSerializable. However, my class does not inherit from any others (besides Object). I suspected this may be an issue because I never reference XmlNode any other time in my code. Microsoft describes a solution to the polymorphism error: https://connect.microsoft.com/VisualStudio/feedback/details/422577/incorrect-deserialization-of-polymorphic-type-that-implements-ixmlserializable?wa=wsignin1.0#details The code the error occurs at is as follows. The object to be read back in is an ArrayList of "MyObjects" IO::FileStream ^fs = gcnew IO::FileStream(filename, IO::FileMode::Open); array<System::Type^>^ extraTypes = gcnew array<System::Type^>(1); extraTypes[0] = MyObject::typeid; XmlSerializer ^xmlser = gcnew XmlSerializer(ArrayList::typeid, extraTypes); System::Object ^obj; obj = xmlser->Deserialize(fs); fs->Close(); ArrayList ^al = safe_cast<ArrayList^>(obj); MyObject ^objs; for each(objs in al) //Error occurs here { //do some processing } Thanks for reading and for any help.

    Read the article

  • Fluent NHibernate mapping List<Point> as value to single column

    - by Paja
    I have this class: public class MyEntity { public virtual int Id { get; set; } public virtual List<Point> Vectors { get; set; } } How can I map the Vectors in Fluent NHibernate to a single column (as value)? I was thinking of this: public class Vectors : ISerializable { public List<Point> Vectors { get; set; } /* Here goes ISerializable implementation */ } public class MyEntity { public virtual int Id { get; set; } public virtual Vectors Vectors { get; set; } } Is it possible to map the Vectors like this, hoping that Fluent NHibernate will initialize Vectors class as standard ISerializable? Or how else could I map List<Point> to a single column? I guess I will have to write the serialization/deserialization routines myself, which is not a problem, I just need to tell FNH to use those routines. I guess I should use IUserType or ICompositeUserType, but I have no idea how to implement them, and how to tell FNH to cooperate.

    Read the article

  • Jquery Ajax json Serializable

    - by willsonchan
    I am learing using jquery ajax to hander the JSON..i writre a demo code. HTMLCODE $(function () { $("#add").click(function () { var json = '{ "str":[{"Role_ID":"2","Customer_ID":"155","Brands":"Chloe;","Country_ID":"96;"}]}'; $.ajax({ url: "func.aspx/GetJson", type: "POST", contentType: "application/json", dataType: 'json', data: json, success: function (result) { alert(result); }, error: function () { alert("error"); } }); }); }); <div> <input type="button" value="add" id="add" /> </div> i got a input and bind a script function to it, now the proble is comeing.. my C# functiong like that. [WebMethod] public static string GetJson(object str) { return str.ToString();//good for work } [Serializable] public class TestClass { public TestClass() { } public TestClass(string role_id, string customer_id, string brands, string countryid) { this.Role_ID = role_id; this.Customer_ID = customer_id; this.Brands = brands; this.Country_ID = countryid; } public string Role_ID { get; set; } public string Customer_ID { get; set; } public string Brands { get; set; } public string Country_ID { get; set; } } when i user public static string GetJson(object str) everything is so good.~~ no error at all but . when i try to use my own class TestClass. firebug tell me that "Type 'TestClass' is not supported for deserialization of an array." .any body can give me help:XD

    Read the article

  • Problems with Json Serialize Dictionary<Enum, Int32>

    - by dbemerlin
    Hi, whenever i try to serialize the dictionary i get the exception: System.ArgumentException: Type 'System.Collections.Generic.Dictionary`2[[Foo.DictionarySerializationTest+TestEnum, Foo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not supported for serialization/deserialization of a dictionary, keys must be strings or object My Testcase is: public class DictionarySerializationTest { private enum TestEnum { A, B, C } public void SerializationTest() { Dictionary<TestEnum, Int32> data = new Dictionary<TestEnum, Int32>(); data.Add(TestEnum.A, 1); data.Add(TestEnum.B, 2); data.Add(TestEnum.C, 3); JavaScriptSerializer serializer = new JavaScriptSerializer(); String result = serializer.Serialize(data); // Throws } public void SerializationStringTest() { Dictionary<String, Int32> data = new Dictionary<String, Int32>(); data.Add(TestEnum.A.ToString(), 1); data.Add(TestEnum.B.ToString(), 2); data.Add(TestEnum.C.ToString(), 3); JavaScriptSerializer serializer = new JavaScriptSerializer(); String result = serializer.Serialize(data); // Succeeds } } Of course i could use .ToString() whenever i enter something into the Dictionary but since it's used quite often in performance relevant methods i would prefer using the enum. My only solution is using .ToString() and converting before entering the performance critical regions but that is clumsy and i would have to change my code structure just to be able to serialize the data. Does anyone have an idea how i could serialize the dictionary as <Enum, Int32>? I use the System.Web.Script.Serialization.JavaScriptSerializer for serialization.

    Read the article

  • How to read data from file(.dat) in append mode

    - by govardhan
    We have an application which requires us to read data from a file (.dat) dynamically using deserialization. We are actually getting first object and it throws null pointer exception and "java.io.StreamCorruptedException:invalid type code:AC" when we are accessing other objects using a "for" loop. File file=null; FileOutputStream fos=null; BufferedOutputStream bos=null; ObjectOutputStream oos=null; try{ file=new File("account4.dat"); fos=new FileOutputStream(file,true); bos=new BufferedOutputStream(fos); oos=new ObjectOutputStream(bos); oos.writeObject(m); System.out.println("object serialized"); amlist=new MemberAccountList(); oos.close(); } catch(Exception ex){ ex.printStackTrace(); } Reading objects: try{ MemberAccount m1; file=new File("account4.dat");//add your code here fis=new FileInputStream(file); bis=new BufferedInputStream(fis); ois=new ObjectInputStream(bis); System.out.println(ois.readObject()); **while(ois.readObject()!=null){ m1=(MemberAccount)ois.readObject(); System.out.println(m1.toString()); }/*mList.addElement(m1);** // Here we have the issue throwing null pointer exception Enumeration elist=mList.elements(); while(elist.hasMoreElements()){ obj=elist.nextElement(); System.out.println(obj.toString()); }*/ } catch(ClassNotFoundException e){ } catch(EOFException e){ System.out.println("end"); } catch(Exception ex){ ex.printStackTrace(); }

    Read the article

  • how to read in a list of custom configuration objects

    - by Johnny
    hi, I want to implement Craig Andera's custom XML configuration handler in a slightly different scenario. What I want to be able to do is to read in a list of arbitrary length of custom objects defined as: public class TextFileInfo { public string Name { get; set; } public string TextFilePath { get; set; } public string XmlFilePath { get; set; } } I managed to replicate Craig's solution for one custom object but what if I want several? Craig's deserialization code is: public class XmlSerializerSectionHandler : IConfigurationSectionHandler { public object Create(object parent, object configContext, XmlNode section) { XPathNavigator nav = section.CreateNavigator(); string typename = (string)nav.Evaluate("string(@type)"); Type t = Type.GetType(typename); XmlSerializer ser = new XmlSerializer(t); return ser.Deserialize(new XmlNodeReader(section)); } } I think I could do this if I could get Type t = Type.GetType("System.Collections.Generic.List<TextFileInfo>") to work but it throws Could not load type 'System.Collections.Generic.List<Test1.TextFileInfo>' from assembly 'Test1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

    Read the article

  • Deserialize json with json.net c#

    - by 76mel
    Hi, am new to Json so a little green. I have a Rest Based Service that returns a json string; {"treeNode":[{"id":"U-2905","pid":"R","userId":"2905"}, {"id":"U-2905","pid":"R","userId":"2905"}]} I have been playing with the Json.net and trying to Deserialize the string into Objects etc. I wrote an extention method to help. public static T DeserializeFromJSON<T>(this Stream jsonStream, Type objectType) { T result; using (StreamReader reader = new StreamReader(jsonStream)) { JsonSerializer serializer = new JsonSerializer(); try { result = (T)serializer.Deserialize(reader, objectType); } catch (Exception e) { throw; } } return result; } I was expecting an array of treeNode[] objects. But its seems that I can only deserialize correctly if treeNode[] property of another object. public class treeNode { public string id { get; set; } public string pid { get; set; } public string userId { get; set; } } I there a way to to just get an straight array from the deserialization ? Cheers

    Read the article

  • A good data model for finding a user's favorite stories

    - by wings
    Original Design Here's how I originally had my Models set up: class UserData(db.Model): user = db.UserProperty() favorites = db.ListProperty(db.Key) # list of story keys # ... class Story(db.Model): title = db.StringProperty() # ... On every page that displayed a story I would query UserData for the current user: user_data = UserData.all().filter('user =' users.get_current_user()).get() story_is_favorited = (story in user_data.favorites) New Design After watching this talk: Google I/O 2009 - Scalable, Complex Apps on App Engine, I wondered if I could set things up more efficiently. class FavoriteIndex(db.Model): favorited_by = db.StringListProperty() The Story Model is the same, but I got rid of the UserData Model. Each instance of the new FavoriteIndex Model has a Story instance as a parent. And each FavoriteIndex stores a list of user id's in it's favorited_by property. If I want to find all of the stories that have been favorited by a certain user: index_keys = FavoriteIndex.all(keys_only=True).filter('favorited_by =', users.get_current_user().user_id()) story_keys = [k.parent() for k in index_keys] stories = db.get(story_keys) This approach avoids the serialization/deserialization that's otherwise associated with the ListProperty. Efficiency vs Simplicity I'm not sure how efficient the new design is, especially after a user decides to favorite 300 stories, but here's why I like it: A favorited story is associated with a user, not with her user data On a page where I display a story, it's pretty easy to ask the story if it's been favorited (without calling up a separate entity filled with user data). fav_index = FavoriteIndex.all().ancestor(story).get() fav_of_current_user = users.get_current_user().user_id() in fav_index.favorited_by It's also easy to get a list of all the users who have favorited a story (using the method in #2) Is there an easier way? Please help. How is this kind of thing normally done?

    Read the article

  • Alternatives to static methods on interfaces for enforcing consistency

    - by jayshao
    In Java, I'd like to be able to define marker interfaces, that forced implementations to provide static methods. For example, for simple text-serialization/deserialization I'd like to be able to define an interface that looked something like this: public interface TextTransformable<T>{ public static T fromText(String text); public String toText(); Since interfaces in Java can't contain static methods though (as noted in a number of other posts/threads: here, here, and here this code doesn't work. What I'm looking for however is some reasonable paradigm to express the same intent, namely symmetric methods, one of which is static, and enforced by the compiler. Right now the best we can come up with is some kind of static factory object or generic factory, neither of which is really satisfactory. Note: in our case our primary use-case is we have many, many "value-object" types - enums, or other objects that have a limited number of values, typically carry no state beyond their value, and which we parse/de-parse thousands of time a second, so actually do care about reusing instances (like Float, Integer, etc.) and its impact on memory consumption/g.c. Any thoughts?

    Read the article

  • What's the difference between the [OptionalField] and [NonSerialized]

    - by IbrarMumtaz
    I came across this question on transcender: What should you apply to a field if its value is not required during deserialization? Me = [NonSerialized], ANSWER = [OptionalField] My gut reaction was NonSerialised, I have no idea why but in the space of 5 seconds thats what I thought but to my surprise, Transcender says I am wrong. OK fair enough .... but why? looking more closely at the question I have a good idea what to look out for as far as the [Nonseralized] attribute is concerned but still I would really like this clearing up. As far as I can tell the former has relationship with versioning conflicts between newer and older versions of the same assembly. The later is more concerned with not serializing a field FULLSTOP. Is there anything else that might pick these two apart? MSDN does not really say much about this as they both are used on the BinaryFormatters and SoapFormatter with the XMLFormatter using the XMLIgnoreAttribute. My second question is can you mix and match either one of the two attributes ... I am yet to use them as I have not had an excuse to mess about with them. So my curiosity can only go so far. Just throwing this one out there, but does my answer have something to do with the way [OnDeserialized] and the IdeserilizationCallback interface is implemented???? Am guessing here .... Thanks In Advance UPDATE: I know that optional field attribute does not serialize the value held by a data member but NonSerialized will not even serialise the data member or its value. That sounds about a right???? That's all I got on these two attributes.

    Read the article

  • Importing data from third party datasource (open architecture design )

    - by mare
    How would you design an application (classes, interfaces in class library) in .NET when we have a fixed database design on our side and we need to support imports of data from third party data sources, which will most likely be in XML? For instance, let us say we have a Products table in our DB which has columns Id Title Description TaxLevel Price and on the other side we have for instance Products: ProductId ProdTitle Text BasicPrice Quantity. Currently I do it like this: Have the third party XML convert to classes and XSD's and then deserialize its contents into strong typed objects (what we get as a result of this process is classes like ThirdPartyProduct, ThirdPartyClassification, etc.). Then I have methods like this: InsertProduct(ThirdPartyProduct newproduct) I do not use interfaces at the moment but I would like them to. What I would like is implement something like public class Contoso_ProductSynchronization : ProductSynchronization InsertProduct(ContosoProduct p) where ProductSynchronization will be an interface or abstract class. There will most likely be many implementations of ProductSynchronization. I cannot hardcode the types - classes like ContosoProduct, NorthwindProduct might be created from the third party XML's (so preferably I would continue to use deserialization). Hopefully someone will understand what I'm trying to explain here. Just imagine you are the seller and you have numerous providers and each one uses their own proprietary XML format. I don't mind the development, which will of course be needed everytime new format appears, because it will only require 10-20 methods to be implemented, I just want the architecture to be open and support that.

    Read the article

  • Handling very large lists of objects without paging?

    - by user246114
    Hi, I have a class which can contain many small elements in a list. Looks like: public class Farm { private ArrayList<Horse> mHorses; } just wondering what will happen if the mHorses array grew to something crazy like 15,000 elements. I'm assuming that trying to write and read this from the datastore would be crazy, because I'd get killed on the serialization process. It's important that I can get the entire array in one shot without paging, and each Horse element may only have two string properties in it, so they are pretty lightweight: public class Horse { private String mId; private String mName; } I don't need these horses indexed at all. Does it sound reasonable to just store the mHorse array as a raw Text field, and force my clients to do the deserialization? Something like: public class Farm { private Text mHorsesSerialized; } then whenever the client receives a Farm instance, it has to take the raw string of horses, and split it in order to reinstantiate the list, something like: // GWT client perhaps Farm farm = rpcCall.getMyFarm(); String horsesSerialized = farm.getHorses(); String[] horseBlocks = horsesSerialized.split(","); for (int i = 0; i < horseBlocks.length; i++) { // .. continue deserializing the individual objects ... } yeah... so hopefully it would be quick to read a Farm instance from the datastore, and the serialization penalty is paid by the client, Thanks

    Read the article

  • iPhone -trouble with a loading data from webservice into a tableview

    - by medampudi
    I am using a Window based application and then loading up my initial navigationview based controller. After loading it if the user is not registered/ does not have a credentials present then it takes the user to a login view controller . loginViewController *sampleView = [[loginViewController alloc] initWithNibName:@"loginViewController" bundle:nil]; [self.navigationController presentModalViewController:sampleView animated:YES]; [sampleView release]; then right after that i try to load the table with data that i get from a webservice using asiHTTP .. for this question lets say it takes 3 seconds time to get the data and then deserialize it . now... my question is it works out okey in the later runs as I store the username and password in a seure location... but in the first instance.... i am not able to get the data to laod to the tableview... I have tried a lot of things... 1. Initially the data fetch methods was in a diffrent methods.. so i thought that might be the problem as then moved it the same place as the tbleviewController(navigationController) 2. I event put in the Reload data at the end of the functionality for the data parsing and deserialization... nothing happens. 3. i did not understand the concept of @property and alll.... 4. The screen is black screen with nothing displayed on it for a good 5 seconds in the consecutive launches of the app.... so could we have something like a MBPorgressHUD implemented for the same. could any one please help for these scenarios and guidance as to what paths to take from here...

    Read the article

  • Complicated API issue with calling assemblies dynamically?

    - by Stefanos Tses
    I have an interesting challenge that I'm wondering if anyone here can give me some direction. I'm writing a .Net windows forms application that runs on a network and uses an SQL Server to save and pull data. I want to offer a mini "plugin" API, where developers can build their own assemblies and implement a specific interface (IDataManipulate). These assemblies then can be used by my application to call the interface functions and do something. I can create assemblies using my API, copy the file to a folder in my local hard drive and configure my application to use Reflection to call a specific function from the implemented interface (IDataManipulate.Execute). The problem: Since the application will be installed in multiple workstations in the network, is impossible to copy the plugin dlls the users will create to each machine. Solutions I tried: Solution 1 Copy the API dll to a network share. Problem: Requires AllowPartiallyTrustedCallersAttribute, which requires .Net singing, which I can't force from my users. Solution 2 (preferred) Serialize the dll object, save it to the database, deserialize it and call IDataManipulate.Execute. Problem: After deserialization, I try cast it to a IDataManipulate object but returns an error looking for the actual dll file. Solution 3 Save the dll bytes as byte[] to the database and recreate the dll at the local PC every time the user starts my application. Problem: Dll may have dependencies, which I don't know if I can detect. Any suggestions will be greatly appreciated. Thanks

    Read the article

  • How do I deserialize a namespaced element to an object in .net?

    - by pc1oad1etter
    Given this XML snippet: ... <InSide:setHierarchyUpdates> <automaticUpdateInterval>5</automaticUpdateInterval> <shouldRunAutomaticUpdates>true<shouldRunAutomaticUpdates> </InSide:setHierarchyUpdates> ... I am attempting to serialize this object: Imports System.Xml.Serialization <XmlRoot(ElementName:="setHierarchyUpdates", namespace:="InSide")> _ Public Class HierarchyUpdate <XmlElement(ElementName:="shouldRunAutomaticUpdates")> _ Public shouldRunAutomaticUpdates As Boolean <XmlElement(ElementName:="automaticUpdateInterval")> _ Public automaticUpdateInterval As Integer End Class Like this: Dim hierarchyUpdater As New HierarchyUpdate Dim x As New XmlSerializer(hierarchyUpdater.GetType) Dim objReader As Xml.XmlNodeReader = New Xml.XmlNodeReader(myXMLNode) hierarchyUpdater = x.Deserialize(objReader) However, the object, after deserialization, has values of false and zero. If I switch the objReader to a streamreader and read this in as a file, with none of its parents and no namespaces, it works: <setHierarchyUpdates> <automaticUpdateInterval>5</automaticUpdateInterval> <shouldRunAutomaticUpdates>true<shouldRunAutomaticUpdates> </setHierarchyUpdates> What am I doing wrong? Should I use something other than XMLRoot in the class definition, because, as an XML node, it's not really the root? If so, what? Why are no errors returned when this fails?

    Read the article

  • NHibernate Performance Optimization | Suggestions invited!!!

    - by user336749
    Hi, I’m facing an issue with NHibernate performance and can you please suggest me some optimizations? Below mentioned is a small summary of my application architecture I have a windows service which is listening to a messaging bus. On receiving a message the service creates an object out of which a property is the received xml snippet and saves the message to the DB (uses NH). There is a WPF UI with a readonly connection to the DB, and on refresh of the UI it displays the objects on the screen. While the UI does a refresh, it retrieves the xml and deserializes it , from which the object’s properties are derived and binded to the screen. For example assume an xml XXX is received by the service, it deserializes the xml , creates the book object and save it to the DB and a property/column is SCHEMA which contains the xml snippet. The UI while refreshed searches all book objects by ID and creates the book objects out of the xml which is being saved (yes, the xml is the constructor param). Now my issue is that the refresh takes more than 2 minutes to display say 50 book objects. I analyzed it using the NHibernate profiler, and found that the time spend within the DB is negligible, however time spent to create the entities is proportionally huge(10ms:1990 ms).I guess it’s due to the fairly huge size of xml snippet and it’s deserialization. My question is, how can I improve the performance. I dispose sessions after every refresh and is not lazy loading (please note that the time spend in DB is negligible). On every refresh it’s possible that all objects are updated by some downstream systems or maybe one of them are updated.Can I implement some sort of caching mechanism in this case? Thanks in advance for any suggestions. Regards, -Mike

    Read the article

  • Entities used to serialize data have changed. How can the serialized data be upgraded for the new entities?

    - by i8abug
    Hi, I have a bunch of simple entity instances that I have serialized to a file. In the future, I know that the structure of these entities (ie, maybe I will rename Name to Header or something). The thing is, I don't want to lose the data that I have saved in all these old files. What is the proper way to either load the data from the old entities into new entities upgrade the old files so that they can be used with new entities Note: I think I am stuck with binary serialization, not xml serialization. Thanks in advance! Edit: So I have an answer for the case I have described. I can use a dataContractSerializer and do something like [DataMember("bar")] private string foo; and change the name in the code and keep the same name that was used for serialization. But what about the following additional cases: The original entity has new members which can be serialized Some serialized members that were in the original entity are removed Some members have actually changed in function (suppose that the original class had a FirstName and LastName member and it has been refactored to have only a FullName member which combines the two) To handle these, I need some sort of interpreter/translator deserialization class but I have no idea what I should use

    Read the article

< Previous Page | 5 6 7 8 9 10 11  | Next Page >