Dynamical web pages with sql - c#

I am trying to build a dynamic web page with changing controls using an SQL database.
I can't insert in to a sql per control cause that doesn't add up on the SQL tables since I also need the tables and divs. Basically I tried to copy the whole html and putting it in a row but that doesn't seem to work and I can't get it out as pure text. Maybe some suggestions for this?
I am looking in to any Object SQL so I can just insert the whole form as bytes or any other way.
Is there any library for OSQL on C#?(I want to do this server side) Or any tips on how to do this properly?
I was trying to insert the HTML code to SQL for future use but this gave me errors
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
Form1.RenderControl(w);
string s = sw.GetStringBuilder().ToString();
string command = "INSERT INTO `htmltables`(`Company`, `Type`, `HTML`) VALUES ('TestCompany','TestType','" + s + "')";
In any case I'd really want to insert Objects instead of pure HTML cause this will ease my work in the future.
Thank you in advance.

Try to fix your query:
"INSERT INTO `htmltables`(`Company`, `Type`, `HTML`) VALUES
('TestCompany','TestType','" + s + "')"
Try to remove the characters from the string.
"INSERT INTO htmltables(Company, Type, HTML) VALUES ('TestCompany','TestType','" + s +
"')"
and try using Parameters such as:
"INSERT INTO htmltables(Company, Type, HTML) VALUES (#0,#1,#2)", "The Company", "TestType", s
And make the query up.
For me there is only this error.
Adding the divs to the database
This is isn't an issue, the issue might be that the server isn't allowing such characters thinking they might be potential. For this you can try this:
Request.Unvalidated["name"];
This way, the server would get the div or any other HTML markup being inserted.
Basically I tried to copy the whole html and putting it in a row but that doesn't seem to work and I can't get it out as pure text.
It should work when you will use the term I suggested, but wait, you're saying it doesn't seem to work so how can you get the text? Nothing would be provided unless there is some data. Your question is a bit confusing. Sorry for this.
Reference:
http://technet.microsoft.com/en-us/library/aa214012(v=sql.80).aspx
MSDN would be your best buddy in this issue! :)

Your html text may include improper characters for Sql. Safest way is to use parameters.
For Example:
string connectionString = "";
string html = "<div id=\'loremIpsum\'><div/>";
using (SqlCommand command = new SqlConnection(connectionString).CreateCommand())
{
command.CommandText = "insert into YourTable (YourColumn) values(#yourParameter)";
command.Parameters.Add(new SqlParameter("yourParameter", html));
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
finally
{
command.Connection.Close();
}
}

Serialise your class and put the xml object in the database, here is an example of a serialised class and functions for serialisation to and from the object/xml:
VB.net
Imports System.Runtime.Serialization
Imports System.Xml
Imports System.IO
Imports System.Text
Namespace NamespaceGoesHere
<DataContract()> _
Public Class ClassNameGoesHere
'All your properties go here, for example:
<DataMember> Property PropertyName As String = "test"
'Note the use of <DataMember> and <DataContract()>
#Region "Serialisation"
Public Function Serialise() As String
Dim s As New System.IO.MemoryStream
Dim x As New DataContractSerializer(GetType(ClassNameGoesHere))
x.WriteObject(s, Me)
s.Position = 0
Dim sw As New StreamReader(s)
Dim str As String
str = sw.ReadToEnd()
Return str
End Function
Public Shared Function DeSerialise(xmlDocument As String) As ClassNameGoesHere
Dim doc As New XmlDocument
Dim ser As New DataContractSerializer(GetType(ClassNameGoesHere))
Dim stringWriter As New StringWriter()
Dim xmlWriter As New XmlTextWriter(stringWriter)
doc.LoadXml(xmlDocument)
doc.WriteTo(xmlWriter)
Dim stream As New MemoryStream(Encoding.UTF8.GetBytes(stringWriter.ToString()))
stream.Position = 0
Dim reader As XmlDictionaryReader = XmlDictionaryReader.CreateTextReader(stream, New XmlDictionaryReaderQuotas())
Return DirectCast(ser.ReadObject(reader, True), ClassNameGoesHere)
End Function
#End Region
End Class
End Namespace
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Xml;
using System.IO;
using System.Text;
namespace NamespaceGoesHere
{
[DataContract()]
public class ClassNameGoesHere
{
//All your properties go here, for example:
[DataMember()]
public string PropertyName { get; set; }
//Note the use of [DataMember()] and [DataContract()]
#region "Serialisation"
public string Serialise()
{
System.IO.MemoryStream s = new System.IO.MemoryStream();
DataContractSerializer x = new DataContractSerializer(typeof(ClassNameGoesHere));
x.WriteObject(s, this);
s.Position = 0;
StreamReader sw = new StreamReader(s);
string str = null;
str = sw.ReadToEnd();
return str;
}
public static ClassNameGoesHere DeSerialise(string xmlDocument)
{
XmlDocument doc = new XmlDocument();
DataContractSerializer ser = new DataContractSerializer(typeof(ClassNameGoesHere));
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
doc.LoadXml(xmlDocument);
doc.WriteTo(xmlWriter);
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(stringWriter.ToString()));
stream.Position = 0;
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
return (ClassNameGoesHere)ser.ReadObject(reader, true);
}
#endregion
}
}
Once you have created your class you can serialise it into an xml string using the serialise function. Store this in the database (I would use an XML datatype but you can store it as NVARCHAR(MAX).
When returning from the database simply call the deserialise function passing in the string and you'll get your object back again.

Related

Can I add a CustomXmlPart to my presentation without storing the XML for it in a file?

TLDR; Please either confirm that the 2nd code snippit is the accepted method for creating a CustomXmlPart or show me another less tedious method.
So I'm trying to embed some application data in some of the elements in a .pptx that I'm modifying using the OpenXmlSDK.
To explain briefly, I need to embed an chart code into each image that is loaded into the presentation. It's so that the presentation can be re-uploaded and the charts can be generated again then replaced using the newest data.
Initially I was using Extended Attributes on the OpenXmlElement itself:
//OpenXmlDrawing = DocumentFormat.OpenXml.Drawing
// there's only one image per slide for now, so I just grab the blip which contains the image
OpenXmlDrawing.Blip blip = slidePart.Slide.Descendants<OpenXmlDrawing.Blip>().FirstOrDefault();
//then apply the attribute
blip.SetAttribute(new OpenXmlAttribute("customAttribute", null, customAttributeValue));
The issue with that being, when the .pptx is edited in PowerPoint 2013, it strips out all the Extended Attributes.
SO.
I've read in multiple places now that the solution is to use a CustomXmlPart.
So I was trying to find how to do it.. and it was looking like it would require me to have a separate file for each CustomXmlPart to feed into the part. Ex/
var customXmlPart = slidePart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
customXmlPart.FeedData(stream);
}
^ and that would need to be repeated with a different file for each CustomXmlPart. Which then means I'd likely just have to have a template file containing a skeleton custom XML part, and then dynamically fill in its contents for each individual slide before feeding it into the custom xml part.
It seems like a heck of a lot of work just to put in a little custom attribute. But I haven't been able to find any alternative methods.
Can anyone please either confirm that this is indeed the way I should do it, or point me in another direction? Greatly appreciated.
The answer is yes! :)
public class CustomXMLPropertyClass
{
public string PropertyName { get; set; }
public string PropertyValue { get; set; }
}
private static void AddCustomXmlPartCustomPropertyToSlidePart(string propertyName, string propertyValue, SlidePart part)
{
var customXmlPart = part.AddCustomXmlPart(CustomXmlPartType.CustomXml);
var customProperty = new CustomXMLPropertyClass{ PropertyName = propertyName, PropertyValue = propertyValue };
var serializer = new System.Xml.Serialization.XmlSerializer(customProperty.GetType());
var stream = new MemoryStream();
serializer.Serialize(stream, customProperty);
var customXml = System.Text.Encoding.UTF8.GetString(stream.ToArray());
using ( var streamWriter = new StreamWriter(customXmlPart.GetStream()))
{
streamWriter.Write(customXml);
streamWriter.Flush();
}
}
and then to get it back out:
private static string GetCustomXmlPropertyFromCustomXmlPart(CustomXmlPart customXmlPart)
{
var customXmlProperty = new CustomXMLPropertyClass();
string xml = "";
using (var stream = customXmlPart.GetStream())
{
var streamReader = new StreamReader(stream);
xml = streamReader.ReadToEnd();
}
using (TextReader reader = new StringReader(xml))
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(customXmlProperty));
customXmlProperty = (CustomXMLPropertyClass)serializer.Deserialize(reader);
}
var customPropertyValue = customXmlProperty.PropertyValue;
return customPropertyValue;
}
You could also try custom properties. Custom XML files are meant for complex objects, and it sounds like you only need to store simple information.

Weird character encoded characters (’) appearing from a feed

I've got a question regarding an XML feed and XSL transformation I'm doing. In a few parts of the outputted feed on an HTML page, I get weird characters (such as ’) appearing on the page.
On another site (that I don't own) that's using the same feed, it isn't getting these characters.
Here's the code I'm using to grab and return the transformed content:
string xmlUrl = "http://feedurl.com/feed.xml";
string xmlData = new System.Net.WebClient().DownloadString(xmlUrl);
string xslUrl = "http://feedurl.com/transform.xsl";
XsltArgumentList xslArgs = new XsltArgumentList();
xslArgs.AddParam("type", "", "specifictype");
string resultText = Utils.XslTransform(xmlData, xslUrl, xslArgs);
return resultText;
And my Utils.XslTransform function looks like this:
static public string XslTransform(string data, string xslurl)
{
TextReader textReader = new StringReader(data);
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Ignore;
XmlReader xmlReader = XmlReader.Create(textReader, settings);
XmlReader xslReader = new XmlTextReader(Uri.UnescapeDataString(xslurl));
XslCompiledTransform myXslT = new XslCompiledTransform();
myXslT.Load(xslReader);
StringBuilder sb = new StringBuilder();
using (TextWriter tw = new StringWriter(sb))
{
myXslT.Transform(xmlReader, new XsltArgumentList(), tw);
}
string transformedData = sb.ToString();
return transformedData;
}
I'm not extremely knowledgeable with character encoding issues and I've been trying to nip this in the bud for a bit of time and could use any suggestions possible. I'm not sure if there's something I need to change with how the WebClient downloads the file or something going weird in the XslTransform.
Thanks!
Give HtmlEncode a try. So in this case you would reference System.Web and then make this change (just call the HtmlEncode function on the last line):
string xmlUrl = "http://feedurl.com/feed.xml";
string xmlData = new System.Net.WebClient().DownloadString(xmlUrl);
string xslUrl = "http://feedurl.com/transform.xsl";
XsltArgumentList xslArgs = new XsltArgumentList();
xslArgs.AddParam("type", "", "specifictype");
string resultText = Utils.XslTransform(xmlData, xslUrl, xslArgs);
return HttpUtility.HtmlEncode(resultText);
The character â is a marker of multibyte sequence (’) of UTF-8-encoded text when it's represented as ASCII. So, I guess, you generate an HTML file in UTF-8, while browser interprets it otherwise. I see 2 ways to fix it:
The simplest solution would be to update the XSLT to include the HTML meta tag that will hint the correct encoding to browser: <meta charset="UTF-8">.
If your transform already defines a different encoding in meta tag and you'd like to keep it, this encoding needs to be specified in the function that saves XML as file. I assume this function took ASCII by default in your example. If your XSLT was configured to generate XML files directly to disk, you could adjust it with XSLT instruction <xsl:output encoding="ASCII"/>.
To use WebClient.DownloadString you have to know what the encoding the server is going use and tell the WebClient in advance. It's a bit of a Catch-22.
But, there is no need to do that. Use WebClient.DownloadData or WebClient.OpenReader and let an XML library figure out which encoding to use.
using (var web = new WebClient())
using (var stream = web.OpenRead("http://unicode.org/repos/cldr/trunk/common/supplemental/windowsZones.xml"))
using (var reader = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse }))
{
reader.MoveToContent();
//… use reader as you will, including var doc = XDocument.ReadFrom(reader);
}

Generate xml message to send over tcp

I have classes generated from xsd that i would like to use to create an xml to send over the wire. I just want to create the document in memory, convert it to string/byte[] and send it. I was under the impression that once the classes are populated, i could just do a tostring() and it would return the entire document out. That doesn't seem to be the case... What am i doing wrong here?
#event myEvent = new #event();
myEvent.name = "AddProgram";
myEvent.version = 8.0M;
DateTime myDateTime = new DateTime();
myDateTime = DateTime.Now;
myEvent.time = myDateTime;
detail myDetail = new detail();
myDetail.name = "Program1"
myEvent.detail = myDetail;
Controller controller = new Controller();
controller.actionSpecified = true;
controller.action = ControllerAction.Create;
myDetail.Controller = controller;
String xmlString = myEvent.ToString(); //this is where i would expect a string.
all i get out of this is: "event"
I am not sure where you got your information that ToString() would give you an xml representation of the class but that is not true. What you should do is refer to this article about XML serialization.
http://msdn.microsoft.com/en-us/library/58a18dwa(v=vs.110).aspx
If you have a class of Type event then you would need to do the following to serialize it to XML, Also as a small tidbit I would stay away from using Key words as class or variable definitions if at all possible, but if you're not in control of that then your hands are tied.
#event myEvent = new #event();
myEvent.name = "AddProgram";
myEvent.version = 8.0M;
string xmlIWant= "";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(#event);
using (StringWriter writer = new StringWriter())
{
x.Serialize(writer, myEvent);
xmlIWant = writer.ToString();
}

ASP 4.0, C# Writing a DataSet as XML Data

I am simply trying to load a dataset and output it on a webpage as XML with the schema being written as well. I have been researching to find a way to achieve this without any luck.
The code I am using is:
string str =
"SELECT Name,Members,MaxLvl,Faction,Government,Score FROM dim5orgs where faction =
'Omni' order by Score DESC";
// Connection string for a typical local MySQL installation
string cnnString = "Server=xxxxxxxnet;Port=3306;Database=xxx;Uid=xxxxx;Pwd=xxxx";
// Create a connection object and data adapter
MySqlConnection cnx = new MySqlConnection(cnnString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
// Create a SQL command object
string cmdText = str;
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);
// Create a fill a Dataset
DataSet ds = new DataSet();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
StringWriter sw = new StringWriter();
ds.WriteXml(sw,XmlWriteMode.WriteSchema);
string result = sw.ToString();
Response.Write(result);
Right now I am getting output like:
Punk732220OmniRepublic1644786805740
Paradise754220OmniDepartment1633903815782
I would like the output to be in proper XML form somehow using the column names in the dataset.
Like:
<data>
<name>Punk</name>
<members>732</members>
<Maxlvl>220</MaxLvl>...etc
</data>
I would like to be in proper XML form, with the XML headers written properly.
Thank you.
Look into the documentation of the XmlSerializer Class. I think you could use it something like this:
StreamWriter streamWriter = new StreamWriter(fileLocation);
XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(ds.GetType());
xml.Serialize(streamWriter, ds);
streamWriter.Close();
I have not tried it with DataSets so I'm not sure.
When you say "I am getting output like", does that mean you are seeing that in your webpage, or that is what "result" contains when you debug the program?
If the former, you are probably missing setting the response type:
Response.ContentType = "text/xml";
and optionally the encoding:
Response.ContentEncoding = System.Text.Encoding.UTF8;
before you write your response.
EDIT: Also, make sure you are not returning any html from your page template or master page (assuming you are using .aspx files). You can check this by looking at your page source in your browser (right click and "view source" in IE). Apologies if this teaching you to suck eggs, from your question I didn't know if you have already checked these things or not.
Edit 2: I've tested your code, and if you set the response ContentType to text/xml it works for me.

XSLT Transform of XML using Xml data from a web form

There are lots of examples on the web of transforming an XML file to a different format using an XSLT file, like the following:
XslTransform myXslTransform = new XslTransform();
XsltSettings myXsltSettings = new XsltSettings();
myXsltSettings.EnableDocumentFunction = true;
myXslTransform.Load("transform.xsl");
myXslTransform.Transform("input.xml", "output.xml");
However this is only a partial answer, I would like to be able to get the XML input data from a web form and use that as the input xml data instead of an '.xml' file, but have not found any concrete examples. Using Visual Studio I see Load methods that accept XmlReader objects as parameters but I do not know how to create one of those using the data from a form and TextBox control. It would be very helpful if someone could provide an example of transforming XML using form data instead of an input file.
Create a class and populate an instance of this class during postback from your form data and serialize it ( convert it to xml)
Here is console example for you
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace Stackoverflow
{
public class Program
{
static void Main(string[] args)
{
var p = new Person
{
FirstName = "Daniel", /// in your case you get it from the form
LastName = "Endeg"
};
var x = new XmlSerializer(p.GetType());
x.Serialize(Console.Out, p);
Console.WriteLine();
Console.ReadLine();
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Please note that XslTransform is obsolete since .NET 2.0, you should use XslCompiledTransform instead. And if you want to use XslSettings then make sure you pass them in to the XslCompiledTransform's Load method (e.g. http://msdn.microsoft.com/en-us/library/ms163425.aspx), simply creating it does not make sense.
As for parsing XML you have in a string variable or property (like the Text property of a TextBox) you have lots of options, you can use an XmlReader over a StringReader e.g.
XslCompiledTransform proc = new XslCompiledTransform();
proc.Load("sheet.xsl");
using (StringReader sr = new StringReader(TextBox1.Text))
{
using (XmlReader xr = XmlReader.Create(sr))
{
proc.Transform(xr, null, Response.Output);
}
}
Or you can create an XPathDocument or XmlDocument or XDocument from the string and use an overload of the Transform method that takes an IXPathNavigable as the first argument.
Ok, with some help from Visual Studio auto-complete which lists the parameters for constructors and methods, I was able to complete a working answer to the problem above, using strings for input and output in an Xslt transform operation. Yay. The example answer below assumes you have three strings containing the Xslt text data and the input Xml text data and output Xml data:
string XsltText;
string InputXML;
string OutputXml;
// define the xslt from a string
TextReader myXsltText = new StringReader(XsltText);
XmlReader myXslt = new XmlTextReader(myXsltText);
// define the input xml from a string
TextReader myXmlText = new StringReader(InputXML);
XmlReader myInputXml = new XmlTextReader(myXmlText);
// define the output XmlWriter for the results of the transform
TextWriter myOutputXmlTextWriter = new StringWriter();
XmlWriter myOutputXml = new XmlTextWriter(myOutputXmlTextWriter);
XslCompiledTransform myXslTransform = new XslCompiledTransform();
XsltSettings myXsltSettings = new XsltSettings();
myXsltSettings.EnableDocumentFunction = true;
myXslTransform.Load(myXslt);
myXslTransform.Transform(myInputXml, myOutputXml);
// the result from the transform comes from the TextWriter object
OutputXml = myOutputXmlTextWriter.ToString();
// clean up writers
myOutputXml.Flush();
myOutputXmlTextWriter.Close();
myOutputXml.Close();
To get this code working with a web form, all you have to do is get the strings from the value (Text) of the form elements (controls), for the input XMl and Xslt you could use TextBox controls, and to display the results you could use a label, all very useful, if anyone has a better answer please feel free to let me know.

Categories