Simple client server to send XML information to CRUD database - c#

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);
​

Related

Add (xml) file to a .xlsx file and keep after 'save as'

Hi I have a need to store some data in a excel file (.xlsx) so I can send the file to our customers and extract data from it again later when they send us the file back to update some content.
The customer should not be able to see the data we store in the file, and certainly not be able to remove it (accidentally). In fact he should not be aware of it in any way. Also we want to add this info from a service on a system that doesn't have Excel installed.
I know that a .xlsx file is basicaly a zip file so I can extract the data and add a file to it, zip it again and have a valid file that can be opened by Excel. Only problem here is that after saving that file in Excel my custom xml file is removed from the package. So I need to know how to fix this.
What I have:
XNamespace MyNamespace = "http://stackoverflow.com/questions/ask";
XNamespace ExcelNamespace = "http://schemas.openxmlformats.org/package/2006/relationships";
string ExtractionPath = #"C:\temp\test\";
string ExcelFile = #"C:\temp\example.xlsx";
Directory.CreateDirectory(ExtractionPath);
System.IO.Compression.ZipFile.ExtractToDirectory(ExcelFile, ExtractionPath);
var Root = new XElement(MyNamespace + "tracker",
new XAttribute("version", "1.0.0.1"),
new XElement("connections"));
var file = Path.Combine(ExtractionPath, "connectioninfo.xml");
if (!File.Exists(file))
{
var relsPath = Path.Combine(ExtractionPath, "_rels", ".rels");
var rels = XElement.Load(relsPath);
rels.Add(new XElement(ExcelNamespace + "Relationship",
new XAttribute("Id", "XXXX"),
new XAttribute("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml"),
new XAttribute("Target", "connectioninfo.xml")));
rels.Save(relsPath);
}
Root.Save(file);
if (File.Exists(ExcelFile)) File.Delete(ExcelFile);
System.IO.Compression.ZipFile.CreateFromDirectory(ExtractionPath, ExcelFile, System.IO.Compression.CompressionLevel.NoCompression, false);
When I run this code I end up with a file that contains my connectioninfo.xml file and that I can open in Excel. But when I save that file in excel and unzip the package again, then the connectioninfo.xml file is gone.
So question -> what am I missing to keep the file in the package after saving?
PS: I have also tried following code, but same problem ...
(using System.IO.Packaging;)
using (Package package = Package.Open(ExcelFile, FileMode.Open, FileAccess.ReadWrite))
{
Uri uriPartTarget = new Uri("/customXml/example.xml", UriKind.Relative);
if (!package.PartExists(uriPartTarget))
{
PackagePart customXml = package.CreatePart(uriPartTarget,
"application/vnd.openxmlformats-officedocument.customXmlProperties+xml");
using (Stream partStream = customXml.GetStream(FileMode.Create,
FileAccess.ReadWrite))
{
var doc = new XElement("test", new XElement("content","Hello world!"));
doc.Save(partStream);
}
}
}

Maximum size on Json serialized StorageFile in UWP appdata

I am trying to save a file to the local appdata in a UWP app using Json.
The code creates a file in the folder and then writes the data object to it using Json. Here is the code i use:
StorageFile file = await localstorage.CreateFileAsync("filename.json", CreationCollisionOption.ReplaceExisting)
var filestream = await file.OpenStreamForWriteAsync();
var writer = new StreamWriter(filestream);
var jsonwriter = new JsonTextWriter(writer);
var serializer = new JsonSerializer();
serializer.TypeNameHandling = TypeNameHandling.All;
serializer.Serialize(jsonwriter, DataObject);
Immediately this seems to work and the file seems to be saved successfully, however opening the file manually reveals that it is exactly 16KB and stopped in the middle of an object.
I have been unable to find any mention of a size limitation on any of these objects (streams, StorageFile, Json serializer etc.)
Can anyone explain why the serialization stops at 16KB?
Using the using statement as Romasz suggested and thereby disposing the filestream, writer etc. seems to have fixed my issue.
New code:
StorageFile file = await createFile("filename.json");
using (JsonTextWriter jsonwriter =new JsonTextWriter(new StreamWriter(await file.OpenStreamForWriteAsync())))
{
var serializer = new JsonSerializer();
serializer.TypeNameHandling = TypeNameHandling.All;
serializer.Serialize(jsonwriter, DataObject);
}
Thank you for your answer.

Serialization between different domains

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.

How to create Xml file in memory to upload on the server

I want to transfer XML from client to some server using FTP. What I get is the XmlElement object. I know that I can create the File and upload it to appropriate location (FTP).
However, I think it's better to create File in memory (to avoid file saving on the local disk).
Can someone guide me how can i achieve this?
I am using C# 4.0.
You can use FtpWebRequest.GetRequestStream() to write directly to the request stream without first saving the file on disk
Retrieves the stream used to upload data to an FTP server.
XmlElement.OuterXml returns a String representation of the XmlElement.
string xml = myXmlElement.OuterXml;
byte[] bytes = Encoding.UTF8.GetBytes(xml);
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
Ling2Xml is easier to use:
stream = ftpRequest.GetRequestStream();
XElement xDoc = new XElement("Root",
new XElement("Item1", "some text"),
new XElement("Item2", new XAttribute("id", 666))
);
xDoc.Save(stream);
or you can use serialization
XmlSerializer ser = new XmlSerializer(typeof(SomeItem));
ser.Serialize(stream, new SomeItem());
public class SomeItem
{
public string Name;
public int ID;
}
#L.B. gave the hint to use XDocument and it solved my problem.
Here is the solution:
Write a code to create XDocument object out of the XmlElement object.
StringBuilder stringBuilder = new StringBuilder();
XmlWriter xmlWriter = new XmlTextWriter(new StringWriter(stringBuilder));
xmlElement.WriteTo(xmlWriter);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(new StringReader(stringBuilder.ToString()));
XDocument doc = XDocument.Load(xmlDocument.CreateNavigator().ReadSubtree(), LoadOptions.PreserveWhitespace);
Then use the FTP's stream like this.
Stream ftpstream = ((FtpWebRequest)WebRequest.Create(path)).GetRequestStream();
doc.Save(ftpstream);
ftpstream.Close();

Generate XML and HTML from MemoryStream

Need to generate an html report from XML and corresponding XSL butI have to use memorystream instead of IO File write on server directories. For the most part I managed to create an xml
MemoryStream ms = new MemoryStream();
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.Indent = true;
using(XmlWriter writer = XmlWriter.Create(ms,wSettings))
{
/**
creating xml here
**/
writer.Flush();
writer.Close();
}
return ms; // returning the memory stream to another function
// to create html
// This Function creates
protected string ConvertToHtml(MemoryStream xmlOutput)
{
XPathDocument document = new XPathDocument(xmlOutput);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xmlOutput);
StringWriter writer = new StringWriter();
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(reportDir + "MyXslFile.xsl");
transform.Transform(xDoc, null, writer);
xmlOutput.Position = 1;
StreamReader sr = new StreamReader(xmlOutput);
return sr.RearToEnd();
}
Somewhere along the line I am messing up with creating the HTML Report and cant figure out how to send that file to client end. I dont have much experience working with memorystream. So, any help would be greatly appreciated. Thank you.
You're completely bypassing your transform here:
// This Function creates
protected string ConvertToHtml(MemoryStream xmlOutput)
{
XPathDocument document = new XPathDocument(xmlOutput);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xmlOutput);
StringWriter writer = new StringWriter();
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(reportDir + "MyXslFile.xsl");
transform.Transform(xDoc, null, writer);
// These lines are the problem
//xmlOutput.Position = 1;
//StreamReader sr = new StreamReader(xmlOutput);
//return sr.RearToEnd();
return writer.ToString()
}
Also, calling Flush right before you call Close on a writer is redundant as Close implies a flush operation.
It is not clear to me what you want to achieve but using both XmlDocument and XPathDocument to load from the same memory stream does not make sense I think. And I would set the MemoryStream to Position 0 before loading from it so either have the function creating and writing to the memory stream ensure that it sets the Position to zero or do that before you call Load on the XmlDocument or before you create an XPathDocument, depending on what input tree model you want to use.

Categories