Serialization between different domains - c#

I'm new to serialization.I need to send a Serialized object from a one web site to another web site.
i'm using following serialization code in my first web site
private void Serialize()
{
Cuser cat = new Cuser();
cat.UserNO = 1;
cat.UerName = "chamara";
cat.Passwod = "123";
XmlSerializer ser = new XmlSerializer(cat.GetType());
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
ser.Serialize(writer, cat);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
Response.Redirect("https://site1.com.au");
}
now i need to retrieve(deserialize) these data from site1.com.i have the deserialization code.i need to know how can i transfer this object? and am i using serialization for the correct purpose? hope my explanation is clear enough to understand the issue.

There is some chance that you want to render data in a form on site-1 and automatically post the form to site-2 with client side script.

Related

Serialization value without create object C#

I have work with a MainWindow.xaml class and I want to save some values of my class in my case: private static int bestrecord = 0;
How can I save this value and restore it without a created class just for it?
Because with Serialization you can save only an object and I just want to save this variable.
Thank you.
You can use Application Settings functionality, which is pretty much designed for saving simple variables which are part of the application state, and need to be restored in future sessions.
The documentation is here.
Once you've creating a setting using the designer in the IDE, you can load settings like this:
var mySetting = Properties.Settings.Default.MySettingName;
You can edit your variable normally and save it like this
Properties.Settings.Default.MySettingName = mySetting ;
Properties.Settings.Default.Save();
I have found a very good way for save my score in xml file.
I'm based on Examples of XML Serialization.
For do that i have create 2 function:
private void SerializeElement()
{
XmlSerializer ser = new XmlSerializer(typeof(XmlElement));
XmlElement myElement = new XmlDocument().CreateElement("bestRecord");
myElement.InnerText = bestRecord.ToString();
TextWriter writer = new StreamWriter("text.xml");
ser.Serialize(writer, myElement);
writer.Close();
}
and
private static int deserialize()
{
XmlSerializer ser = new XmlSerializer(typeof(XmlElement));
StreamReader lecteur = new StreamReader("text.xml");
XmlDocument myElement = new XmlDocument();
XmlElement p = (XmlElement) ser.Deserialize(lecteur);
lecteur.Close();
return int.Parse(p.InnerText);
}
the xml file look like:
<?xml version="1.0" encoding="utf-8"?>
<bestRecord>8</bestRecord>

Simple client server to send XML information to CRUD database

I need to develop a resident app to get info from Win32_BaseBoard class when is required by another app by XML without create any file and then this app must insert or update that information on database.
I saw a few apps but always have to create a file and i don't know if already exists something like that.
The code below will create memory stream with the data instead of writing to a file.
///old code
//XmlSerializer serializer = new XmlSerializer(typeof(AppConfig));
//StreamWriter writer = new StreamWriter(FILENAME);
//serializer.Serialize(writer, config);
//new code
string input = "Your XML here";
string output = "";
XmlSerializer serializer = new XmlSerializer(typeof(AppConfig));
MemoryStream mstream = new MemoryStream(Encoding.UTF8.GetBytes(input));
StreamWriter writer = new StreamWriter(mstream);
serializer.Serialize(writer, config);
​

Save XML Response into Session in C#

I need to save the xml response into sesssion. but I have tried this But It didn't . but I Have save xml request as session It worked. I Have attached working and non working code. can any one please help me on this. I don't want save the xml response as file.
Working Code
String xmltest = Session["xmlreq"].ToString();
SoapClient soap = new SoapClient();
string prueba = soap.RequestResponseMethod("getHotelValuedAvail", xmltest);
string tham = HttpUtility.HtmlDecode(prueba);
XmlDocument doc = new XmlDocument();
doc.LoadXml(tham);
doc.Save(Server.MapPath("hotelrs.xml"));
XslTransform myXslTransform;
myXslTransform = new XslTransform();
myXslTransform.Load(Server.MapPath("hotel.xsl"));
myXslTransform.Transform(Server.MapPath("hotelrs.xml"), Server.MapPath("transformhotels.xml"));
Non working Code
String xmltest = Session["xmlreq"].ToString();
SoapClient soap = new SoapClient();
string prueba = soap.RequestResponseMethod("getHotelValuedAvail", xmltest);
string tham = HttpUtility.HtmlDecode(prueba);
Session.Add("xmlrs", tham);
XmlDocument doc = new XmlDocument();
doc.LoadXml(Session["xmlrs"].ToString());
//doc.Save(Server.MapPath("hotelrs.xml"));
XmlDocument trdoc = new XmlDocument();
XslTransform myXslTransform;
myXslTransform = new XslTransform();
myXslTransform.Load(Server.MapPath("hotel.xsl"));
myXslTransform.Transform(doc.InnerXml, trdoc.InnerXml);
Session.Add("xmltrs", trdoc.InnerXml);
1.Declare a variable.
2.store ur xml request data in that variable.
3.Declare another variable say (String Result).
4.Now Result="Call ur method here which will give u a xml response".
5.Session["Outcome"]=Result;
6.No need to use any XMLDocument here.
If u want to format ur XML response, use XSLT template.
In aspx page
<div id="DivLoad">
<asp:Xml ID="xmlDaynamic" runat="server" Visible="true"></asp:Xml>
</div>
In cs
xmlDaynamic.DocumentContent = session["outcome"];
xmlDaynamic.TransformSource = "yourxslttemplate.xslt";
Hope this will help you.

how to display a string from a rest webservice in windows forms?

how can display a string from a rest webservice in windows forms my xml looks like this:
<string>whatever</string>
How can you display that in a textbox in win forms?
If I try
string uri = string.Format("etc/{0}/{1} Sad.Text, Happy.Text");
XDocument xDoc = XDocument.Load(uri);
string mystring = xDoc.Element("String").Value;
textBox1.Text = mystring;
You get an object reference error?
XML elements are case-sensitive. Try,
string mystring = xDoc.Element("string").Value;
A better way to solve the problem is to not use XML to return a simple string. The media type text/plain is designed to do that. If you are using Microsoft's ASP.NET Web API just return
return new HttpResponseMessage() {
Content = new StringContent("etc/{0}/{1} Sad.Text, Happy.Text")
};
and on the client (using this http://nuget.org/Packages/system.net.http) do,
var httpClient = new HttpClient();
textBox1.Text = httpClient.GetAsync(uri).Result.Content.ReadAsString();
I would use XmlSerializer to get the information out of XML returned by the web service. I am assuming that your XML is just in a string. You could do something like this for your simple example, but this would also work for more complex objects returned by a REST web service.
XmlSerializer xs = new XmlSerializer ( typeof ( string ) );
MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(restResult));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
string textBoxVal = xs.Deserialize(memoryStream);

How do I create an XmlNode from a call to XmlSerializer.Serialize?

I am using a class library which represents some of its configuration in .xml. The configuration is read in using the XmlSerializer. Fortunately, the classes which represent the .xml use the XmlAnyElement attribute at which allows me to extend the configuration data for my own purposes without modifying the original class library.
<?xml version="1.0" encoding="utf-8"?>
<Config>
<data>This is some data</data>
<MyConfig>
<data>This is my data</data>
</MyConfig>
</Config>
This works well for deserialization. I am able to allow the class library to deserialize the .xml as normal and the I can use my own XmlSerializer instances with a XmlNodeReader against the internal XmlNode.
public class Config
{
[XmlElement]
public string data;
[XmlAnyElement]
public XmlNode element;
}
public class MyConfig
{
[XmlElement]
public string data;
}
class Program
{
static void Main(string[] args)
{
using (Stream fs = new FileStream(#"c:\temp\xmltest.xml", FileMode.Open))
{
XmlSerializer xser1 = new XmlSerializer(typeof(Config));
Config config = (Config)xser1.Deserialize(fs);
if (config.element != null)
{
XmlSerializer xser2 = new XmlSerializer(typeof(MyConfig));
MyConfig myConfig = (MyConfig)xser2.Deserialize(new XmlNodeReader(config.element));
}
}
}
I need to create a utility which will allow the user to generate a new configuration file that includes both the class library configuration as well my own configuration, so new objects will be created which were not read from the .xml file. The question is how can I serialize the data back into .xml?
I realize that I have to initially call XmlSerializer.Serialize on my data before calling the same method on the class library configuration. However, this requires that my data is represented by an XmlNode after calling Serialize. What is the best way to serialize an object into an XmlNode using the XmlSerializer?
Thanks,
-kevin
btw-- It looks like an XmlNodeWriter class written by Chris Lovett was available at one time from Microsoft, but the links are now broken. Does anyone know of an alternative location to get this class?
So you need to have your class contain custom configuration information, then serialize that class to XML, then make that serialized XML into an XML node: is that right?
Could you just take the string created by the XMLSerializer and wrap that in it's own XML tags?
XmlSerializer xs = new XmlSerializer(typeof(MyConfig));
StringWriter xout = new StringWriter();
xs.Serialize(xout, myConfig);
XmlDocument x = new XmlDocument();
x.LoadXml("<myConfig>" + xout.ToString() + "</myConfig>");
Now x is an XmlDocument containing one element, "<myconfig>", which has your serialized custom configuration in it.
Is that at all what you're looking for?
It took a bit of work, but the XPathNavigator route does work... just remember to call .Close on the XmlWriter, .Flush() doesn't do anything:
//DataContractSerializer serializer = new DataContractSerializer(typeof(foo));
XmlSerializer serializer = new XmlSerializer(typeof(foo));
XmlDocument doc = new XmlDocument();
XPathNavigator nav = doc.CreateNavigator();
XmlWriter writer = nav.AppendChild();
writer.WriteStartDocument();
//serializer.WriteObject(writer, new foo { bar = 42 });
serializer.Serialize(writer, new foo { bar = 42 });
writer.WriteEndDocument();
writer.Flush();
writer.Close();
Console.WriteLine(doc.OuterXml);
One solution is to serialize the inner object to a string and then load the string into a XmlDocument where you can find the XmlNode representing your data and attach it to the outer object.
XmlSerializer xser1 = new XmlSerializer(typeof(Config));
XmlSerializer xser2 = new XmlSerializer(typeof(MyConfig));
MyConfig myConfig = new MyConfig();
myConfig.data = "My special data";
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlWriter xw = new XmlTextWriter(sw);
xser2.Serialize(xw, myConfig);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
Config config = new Config();
config.data = "some new info";
config.element = doc.LastChild;
xser1.Serialize(fs, config);
However, this solution is cumbersome and I would hope there is a better way, but it resolves my problem for now.
Now if I could just find the mythical XmlNodeWriter referred to on several blogs!
At least one resource points to this as an alternative to XmlNodeWriter: http://msdn.microsoft.com/en-us/library/5x8bxy86.aspx. Otherwise, you could write MS using that form they have on the new MSDN Code Library replacement for GotDotNet looking for XmlNodeWriter.

Categories