.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Object serialization to XML string

Posted By:      Posted Date: May 22, 2011    Points: 0   Category :WPF

Hi there,

Does anybody know how can I serialize an object to string that is XML representation of object.

So far I serialize object to XML file, get its content and store them in DB. I want to bypass XML file and get serialized object to string directly.


View Complete Post

More Related Resource Links

Cannot send List inside of Dictionary

List<string> receivers = new List<string>(); foreach (object item in listBoxControl1.SelectedItems) receivers.Add((string)item); Dictionary<string, object> inArgs = new Dictionary<string, object>(); inArgs.Add("Receivers", receivers); inArgs.Add("Sender", client.name); inArgs.Add("Message", memoEdit2.Text); inArgs.Add("IsGuaranteedDelivery", true); inArgs.Add("DataType", TransmitToClientDataType.ChatMessage); if (service != null) service.AddTask("orion_send", inArgs); There is an error with serialization at last string because List<string> object. I tryed to send List<T> object via WCF, it's succesfull. But why there are problems with List<T> included to Dictionary?

Controlling object serialization

I have a class called Marker and I've written SerializeToXml function that serializes the class to xml. The problem is that I'm getting xml declaration and namespace that I don't need. How can I set up the serialization so that this information is not included ? Code Snippet <?xml version="1.0" encoding="utf-16"?><Marker xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">Here is my SerializeToXml function: Code Snippet public void SerializeToXML(System.IO.StringWriter writer){            XmlSerializer mySerializer = new XmlSerializer(typeof(Marker));                     mySerializer.Serialize(writer, this);} Thanks !

Weird Issue with the MOSS Search : FileExtension metadata object type instead of string

Hello, We 've got a strange issue with the search and especially with the FileExtension metadata. when we make a query on the search engine, we receive for the FileExtension metadata an unexcpected result. here is a printscreen showing the issue. http://cid-53eee937847a625e.photos.live.com/self.aspx/Public/Untitled.jpg as you can see the Type of the FileExtension is object and it should be string and I checked the type of the object and it's System.String[] the element at the index 0 contains the value! what's wrong ? thx in advance

Unable to cast object of type 'System.Guid' to type 'System.String'.

protected void Button1_Click(object sender, EventArgs e) { using (BurnbetDataContext dc = new BurnbetDataContext()) { var q = (from c in dc.GetTable<tbl_Payment>() where c.ID == 5 select c).Single<tbl_Payment>(); dc.GetTable<tbl_Payment>().DeleteOnSubmit(q); dc.SubmitChanges(); } } }System.InvalidCastException was unhandled by user code  Message=Unable to cast object of type 'System.Guid' to type 'System.String'.  Source=System.Data.Linq  StackTrace:       at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)       at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)       at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)       at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)&nb

converting a rdr object to a string


I inherited some code and I need to change a line so that instead of testing to see if the value in a table column is not null, it also tests to see if the value is not empty.

The existing line is:

if (rdr["InnLinkURL"] != null)

"InnLinkURL" is the name of the column being tested.

I thought a solution could be something like:

if (String.IsNullOrEmpty(InnLinkURL) == true)

Not sure how to convert the object to a string, though.

public static string ToString(
 object value

If someone could show me the proper syntax I'd be grateful.

As an alternative, I tried this also but it doesn't seem to work (no errors, just doesn't return true)

if ((rdr["InnLinkURL"] != null) && (rdr["InnLinkURL"] != ""));

WCF Serialization EDM Object


HI, I got a WCF Service with a EDM, and I got a problem with Serialization. I can't serialize this List<User> that GetAllUsers method return.

The WCF Service have a method like this:

################# Service1.svc.cs ##################
    public class Service1 : IService1
        public List<User> GetAllUsers(string term)
            using (GESEMPEntities context = new GESEMPEntities())
                var query = from user in context.User
                            where user.User_Email == term
                            select user;

                return query.ToList();

Unable to cast object of type 'System.DBNull' to type 'System.String'.


 I saw lots of post about this issue. but haven't got good solution for that yet. Basically, what I did is that: I have a table in SQL database and some of data fields allow null. I built Objectdatasource through dataset. When I built update page using dataset. It generate the following error before showing the update page correctly. It seems I have issue to retrieve the null value from the database through using objectdatasource through dataset. Any suggestions?




Error attached below:

Unable to cast object of type 'System.DBNull' to type 'System.String'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.

Source Error:

Line 1178:            get {
Line 1179:                try {
Line 1180:                    return ((string)(this[this.tablemember.CurrentCityStateColumn]));
Line 1181:                

Keep updating Session object with a new List c#


I have a Session object

Session["MyListObjects"] = null;

When a user hits a button I want to creat a List<string> object and add to session object.

Let's say if user hits the button 10 times, I would get 10 List<string> objects and
add to Session["MyListObjects"] and

Finally I want to read all the List<string> objects from the session object.

Please let me know how to do that.

JSON string to Object


If I have a  string  containing  valid JSON

how can I conver to an obect in c#?

Object of type 'System.Int32' cannot be converted to type 'System.String


When i'm trying to update a table using dynamic data, i'm getting the following error. I was trying to google the solution for the whole day, but it didnt work. I tried to declare the type of parameters like this

<asp:LinqDataSource ID="DetailsDataSource" runat="server" EnableUpdate="true"
                onupdating="DetailsDataSource_Updating" > <UpdateParameters><asp:Parameter Name="PK_ID" Type="Int32" /><asp:Parameter Name="id" Type="Int32" />
                <asp:Parameter Name="c_titulu" Type="Int32" />
                <asp:Parameter Name="perio" Type="Int32" />

Object Serialization


Class 1
public class Class1
    private int _id;

    public int Id
        get { return _id; }
        set { _id = value; }
    private string _name;

    public string Name
        get { return _name; }
        set { _name = value; }

Default Page

ob.Name = TextBox1.Text;
        ob.Id = Convert.ToInt32(TextBox2.Text);
        SqlConnection con = new SqlConnection(connstr);
        SqlCommand cmd = new SqlCommand("insert into user1 values(@name,@id)", con);
        cmd.Parameters.AddWithValue("@name", ob.Name);
        cmd.Parameters.AddWithValue("@id", ob.Id);

Private Method Writeperson when i trying to use xmlserailizer it's saying it cannot be acces due to its proctection level

private void WritePerson()
        XmlSerializer ob1 = new XmlSerializer();
        StreamWriter sw = new StreamWriter(Server.MapPath("person.xml"));
        ob1.Serialize(sw, ob);

what i m doing wrong can anyone tell me


Convert XML to object returns null due to unwanted string


Hello All,

I am facing very odd problem, when I check my xml string than in header it contain one unwanted string square [], like below, due to that casting to object is not happening. Due to that it returns null

[]<?xml version="1.0"?>

But when I remove [] and convert to object then it works fine. Any one has any idea.

Parsing Query string using Client Object model [ECMA]



i want to access querystring using client object model using ECMA script.

for eg http://localhost:80/demopage.aspx?test=123

can we read value of test using ECMA script




2 dimensional table with indexing by string(object)



I've got a problem i need to create 2 dimensional table which will be indexed by string for example:

table["London","Cambridge"] = 120;

or jagged:

table["London"]["Cambridge"] = 120;

How to declare Collection or array that can handle this?


I found solution but im not sure it is the best.

Dictionary<string, Dictionary<string, int>> test = new Dictionary<string, Dictionary<string, int>>();

But  when i wanna create a new value i need to initialize new dictionary, so why i thing that solution is not the rightest:

table.Add("London", new Dictionary<string, int> {{"Cambridge",120}});

So how in the best way create 2 dimensional array indexed by string (mayby create new class that can handle this)?


Struggling with XML De-serialization, XML Wont De-serialize into my Object


So here's the situation. I'm writing a simple program that utilizes an api from a site. All the data requested from the api returns in XML. I've had success with XML in the past so I tried giving this a shot. No such chance.


The array that's suppose to be containing at least one of the objects is null after trying to de-serialize into it, I'm sure I'm just doing something wrong. Anyway, here's the the XML, de-serializing method, and the object class.


The method:

private repositories FromXml(string xmlString)
      var xmlSerializer = new XmlSerializer(typeof(repositories));
      repositories data = (repositories)xmlSerializer.Deserialize(new StringReader(xmlString));
      return data;

The object classes:

public class repository
    public string name;

Serialization using SQL server or storing a table object as text in a text column



I have a requirement in SQL server 2008 as follows:

I need to Insert into a particular table say Output at runtime where one of the columns (Content) of type text should contain an object of another table (Audit). This is currently being done through C# by serializing the Audit table and updating the Content with the serialized value. But this needs to be done in SQL now as per the requirement.

Can this be done by creating an object of Audit and storing in Output.Content in SQL itself?

Thanks in advance for the help.




ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend