Tags down


Serialize and De-serialize XML with commented sections in C#

By : user2174924
Date : October 16 2020, 08:10 PM
Hope that helps I was wondering that how i can keep the commented part in XML (After serialization). Is there any way to do so? , Suppose an xml like this
code :
<?xml version="1.0" encoding="utf-8"?>
    <!--Foo Description!-->
    <!--Bar Description!-->

var xml = GenericSerializator<Test>.LoadObjectFromFile("test.xml");

xml.Foo += "1";
xml.FooCommnet += "2";
xml.Bar += "3";
xml.BarCommnet += "4";

GenericSerializator<Test>.SaveObjectToFile(xml, "test2.xml");

<?xml version="1.0" encoding="utf-16"?>
  <!--Foo Description!2-->
  <!--Bar Description!4-->
    internal static class GenericSerializator<T> where T : class
        public static T LoadObjectFromFile(string fileName)
            using (var file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                var xmlSerializer = new XmlSerializer(typeof(T));
                return (T)xmlSerializer.Deserialize(file);

        public static void SaveObjectToFile(object value, string fileName)
            var xmlSerializer = new XmlSerializer(typeof(T));
            using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                fileStream.Seek(0, SeekOrigin.End);
                using (var streamWriter = new StreamWriter(fileStream, Encoding.Unicode))
                    xmlSerializer.Serialize(streamWriter, value);

    public class Test : XmlSerializableWithComments
        [XmlIgnore, Description]
        public string FooCommnet { get; set; }

        public string Foo { get; set; }

        [XmlIgnore, Description]
        public string BarCommnet { get; set; }

        public string Bar { get; set; }

    public class XmlSerializableWithComments : IXmlSerializable
        private PropertyInfo[] Properties { get; set; }

        public XmlSerializableWithComments()
            Properties = GetType().GetProperties();

        public void WriteXml(XmlWriter writer)
            foreach (var propertyInfo in Properties)
                var value = propertyInfo.GetValue(this, null).ToString();
                if (propertyInfo.IsDefined(typeof(DescriptionAttribute), false))
                    writer.WriteElementString(propertyInfo.Name, value);

        public XmlSchema GetSchema()
            throw new NotImplementedException();

        public void ReadXml(XmlReader reader)
            while (reader.Read())
                if (reader.NodeType == XmlNodeType.EndElement)

                string comment = null;
                if (reader.NodeType == XmlNodeType.Comment)
                    comment = reader.Value;


                if (reader.NodeType == XmlNodeType.Element)
                    var propertyName = reader.LocalName;

                    PropertyInfo temp;
                    if ((temp = Properties.FirstOrDefault(i => i.Name == propertyName)) != null)
                        temp.SetValue(this, reader.Value);
                        if (!string.IsNullOrEmpty(comment))
                            if ((temp = Properties.FirstOrDefault(i => i.Name == propertyName + "Commnet")) != null)
                                temp.SetValue(this, comment);
                            comment = null;

Share : facebook icon twitter icon

Serialize nhibernate entity to json error: Cannot serialize a Session while connected

By : user3020098
Date : March 29 2020, 07:55 AM
I wish this helpful for you I started getting the same error when I switched from System.Web.Script.Serialization.JavaScriptSerializer to Newtonsoft.Json.
Using the contract resolver from this answer fixed this problem:
code :
string output = JsonConvert.SerializeObject(theObject,
                new JsonSerializerSettings()
                    ContractResolver = new NHibernateContractResolver()

Serialize objects with inheritance by defining serialize method only in base class?

By : Douglas Carroll
Date : March 29 2020, 07:55 AM
Hope that helps You just need to provide the serialization constructor and make the GetObjectData virtual in the base class so you can override it in the child classes.
code :
public NationDwarf(SerializationInfo info, StreamingContext context)
    : base(info, context)

Serialize and De-serialize a Django Enum field to accept Numerical and Text representation

By : Frederick Boone
Date : March 29 2020, 07:55 AM
it should still fix some issue As OP stated, you can do this easily using custom fields in drf v3.x. Here's a quick example of a generic custom field used to convert values <-> labels (e.g. enum values <-> textual representation):
code :
class KeyValueField(serializers.Field):
    """ A field that takes a field's value as the key and returns
    the associated value for serialization """

    labels = {}
    inverted_labels = {}

    def __init__(self, labels, *args, **kwargs):
        self.labels = labels
        # Check to make sure the labels dict is reversible, otherwise
        # deserialization may produce unpredictable results
        inverted = {}
        for k, v in labels.iteritems():
            if v in inverted:
                raise ValueError(
                    'The field is not deserializable with the given labels.'
                    ' Please ensure that labels map 1:1 with values'
            inverted[v] = k
        self.inverted_labels = inverted
        return super(KeyValueField, self).__init__(*args, **kwargs)

    def to_representation(self, obj):
        if type(obj) is list:
            return [self.labels.get(o, None) for o in obj]
            return self.labels.get(obj, None)

    def to_internal_value(self, data):
        if type(data) is list:
            return [self.inverted_labels.get(o, None) for o in data]
            return self.inverted_labels.get(data, None)
class MySerializer(serializers.Serializer):
    afield = KeyValueField(labels={0:'enum text 0', 1:'enum text 1'})

How to serialize async pthreads code sections

By : Frederic
Date : March 29 2020, 07:55 AM
I hope this helps . The answer by mevets identifies your bug. As mentioned, you can solve this with condition variables:
code :
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_safe = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_waiters = PTHREAD_COND_INITIALIZER;
int is_safe = 0;
long waiters = 0;

void acquire_access(void)
    while (!is_safe)
        pthread_cond_wait(&cond_safe, &mutex);

void surrender_access(void)
    if (!waiters)

void shared_resource_is_safe(void)
    if (waiters)
        is_safe = 1;
        while (waiters)
            pthread_cond_wait(&cond_waiters, &mutex);
        is_safe = 0;

Why is my simplified version of rapidjson/example/serialize/serialize.cpp throwing a segmentation fault?

By : user3027685
Date : March 29 2020, 07:55 AM
this will help Ok I finally found my problem by comparing my code line by line with the example in rapidjson/example/serialize/serialize.cpp:
when instantiating a rapidjson::Writer (or PrettyWritter), you need to call its constructor with the StringBuffer as argument. My code would then become:
code :
    int main(int argc, char* argv[]) {
  const char* json = "{\"address\":\"\", \"port\":9100}";
  Document doc;

  StringBuffer jsonBuffer;
  Writer<StringBuffer> jsonWriter(jsonBuffer);  // Update is here: give jsonBuffer to jsonWriter


  std::cout << "output json is : " << jsonBuffer.GetString() << endl;
  return 0;
Related Posts Related Posts :
  • DotNet Core Xunit Always Went to Catchblock
  • Datetime from strings adding time and date seperatly
  • Caliburn.micro, WPF and two comboboxes
  • How to activate Window started by another process
  • Remove line breaks in CSV file
  • Mock extension methods IElasticClient
  • MigraDoc: How to add a blank page after a section on odd pages?
  • c# override Generic BaseMethod of other type
  • Entity Framework inserting duplicates on Seeding database
  • Azure DevOps Release Pipeline, Read Environment Variables from C# Code
  • c#- Json as stream to excel
  • Add collection as SQL parameter to SqlCommand without using (Table-Valued-Parameter) type
  • How to call a method that uses PaintEventArgs and coordinates variables
  • How Can I Bind Data To DataGridView With EntityFramework In WPF
  • Is it safe to uninstall the Application Insights nuget packages?
  • Test if TextBox Exists C# WPF
  • How can I add a namespace to soap envelope in c#
  • Confused at control flow of async/await of c#
  • How to remove and create log in Windows Event Viewer
  • Get value from selected row DataGridView WPF
  • Xamarin Button Command Binding
  • Is it possible to inject a specific configuration class bound as a suboption and not to IConfiguration<MyType>?
  • How to shoot ball to Touch X position Unity 3D?
  • C# WPF textbox GotFocus SelectAll not working
  • C# if statement always returning false
  • accessing singleton created within ConfigureServices in the startup.cs file in asp.net core in the same ConfigureService
  • Set zoom level to see only 3 pins in Xamarin Forms
  • C# - OleDBDataAdapter.Fill(DataSet) throws "No value given for one or more required parameters. "
  • What happens if we don't use DTOs in our API?
  • How to display to the console list from another class?
  • EF Core Db First - filter out tables based on schema name
  • How to do JSON POST
  • How to safely change the unique key with Entitiy Framework - Database First
  • CS0103 Error in Visual Studio on simple project containing only a textbox and button
  • How to make custom user claims be available in API requests
  • SharpZipLib throw System.IO.FileNotFoundException on commit update
  • C# - check if substring is present in arraylist of strings
  • SSIS Script Task move all files not working
  • Unhandled exception occurs after handling exception
  • Reading selected checkboxes as int
  • Why projection is not including navigation nested properties in EF Core 2.0?
  • Structure to XML C# WinForms
  • Manipulate textbox on gridview C#
  • C# similar bitwise operations resulting in different answers
  • Linq to SQL Random Timeouts on Simple Small Queries
  • Return type as IEnumerable instead of just List?
  • How to get transient DbContext in ASP.NET MVC Core?
  • Grouping data in ViewModel ASP.NET MVC & C#
  • Using a parameter's property in an ArgumentException
  • EF Unable to determine the relationship represented by navigation property
  • Moq: running flows with FluentValidation
  • "Reset" switch statement after value is equal
  • What does the question mark followed by a period mean if it is next to a variable?
  • How to P/Invoke os_log?
  • Deep copy object properties (including those with private setter) to another object of the same type
  • How to generate new back colour if two object's back colour match?
  • How to calculate percentage of value inside arbitrary range?
  • typeof(T) when T is dynamically created is null?
  • Run the application faster with Run Query at Start
  • c# code returns System.Data.DataSet instead of Data itself?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org