ASp.net c# sql

May 7, 2008

– Fetch XML (xmldatadocument) from database

Filed under: asp.net c#, sql, xml — Tags: , , , , — Admin @ 1:19 pm

This post shows you how to return XmlDataDocument from the database.
This helps you to fetch the xml data created in sql and use in asp.net.
If you are familiar how to get xml data from sql then this post helps you to fetch the xml data in XmlDataDocument.

//Code Starts Here

// http://helpindotnet.blogspot.com/
// https://helpindotnet.wordpress.com

public XmlDataDocument getauditnames(string prefixText, int count)
{

XmlDataDocument xml = new XmlDataDocument();
SqlConnection con = new SqlConnection(” <<Connection String >>”);
SqlCommand com = new SqlCommand(“<<Query>> For XML PATH (‘Path’), root(‘Root’)”, con);
//The key to this step is the FOR XML PATH(###), ROOT(###) part. This tells SQL Server to return XML with each row having the element name //”Path” of and the root of the XML document to be ROOT
con.Open();
XmlReader xdr = com.ExecuteXmlReader();
xml.Load(xdr);
xdr.Close();
con.Close();
return xml;
}
//Code Ends Here

May 6, 2008

– GZIP Compress a file using Asp.net and C#.

Filed under: asp.net c# — Tags: , , , — Admin @ 8:58 am

<span style=”font-weight:bold;”>Here I will show you the easiest way to compress and Decompress (Gzip) a file using Asp.net with c#.
You can compress any file with this method.</span>

//Code Starts here

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;

/*
* http://helpindotnet.blogspot.com/
*/

namespace ConsoleApplication1
{
class GZipTest
{
private const int buffer_size = 100;

public static int ReadAllBytesFromStream(Stream stream, byte[] buffer)
{
// Use this method is used to read all bytes from a stream.
int offset = 0;
int totalCount = 0;
while (true)
{
int bytesRead = stream.Read(buffer, offset, buffer_size);
if (bytesRead == 0)
{
break;
}
offset += bytesRead;
totalCount += bytesRead;
}
return totalCount;
}

public static bool CompareData(byte[] buf1, int len1, byte[] buf2, int len2)
{
// Use this method to compare data from two different buffers.
if (len1 != len2)
{
Console.WriteLine(“Number of bytes in two buffer are different {0}:{1}”, len1, len2);
return false;
}

for (int i = 0; i < len1; i++)
{
if (buf1[i] != buf2[i])
{
Console.WriteLine(“byte {0} is different {1}|{2}”, i, buf1[i], buf2[i]);
return false;
}
}
Console.WriteLine(“All bytes compare.”);
return true;
}

public static void GZipCompressDecompress(string filename)
{
Console.WriteLine(“Test compression and decompression on file {0}”, filename);
FileStream infile;
try
{
// Open the file as a FileStream object.
infile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] buffer = new byte[infile.Length];
// Read the file to ensure it is readable.
int count = infile.Read(buffer, 0, buffer.Length);
if (count != buffer.Length)
{
infile.Close();
Console.WriteLine(“Test Failed: Unable to read data from file”);
return;
}
infile.Close();
FileStream fs = new FileStream(filename+”.gz”, FileMode.Append);
MemoryStream ms = new MemoryStream();
// Use the newly created memory stream for the compressed data.
GZipStream compressedzipStream = new GZipStream(fs, CompressionMode.Compress, true);
Console.WriteLine(“Compression”);
compressedzipStream.Write(buffer, 0, buffer.Length);
// Close the stream.
compressedzipStream.Close();
Console.WriteLine(“Original size: {0}, Compressed size: {1}”, buffer.Length, fs.Length);

ms.WriteTo(fs);

// Reset the memory stream position to begin decompression.
ms.Position = 0;
GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress);
Console.WriteLine(“Decompression”);
byte[] decompressedBuffer = new byte[buffer.Length + buffer_size];
// Use the ReadAllBytesFromStream to read the stream.
int totalCount = GZipTest.ReadAllBytesFromStream(zipStream, decompressedBuffer);
Console.WriteLine(“Decompressed {0} bytes”, totalCount);

if (!GZipTest.CompareData(buffer, buffer.Length, decompressedBuffer, totalCount))
{
Console.WriteLine(“Error. The two buffers did not compare.”);
}
zipStream.Close();
} // end try
catch (InvalidDataException)
{
Console.WriteLine(“Error: The file being read contains invalid data.”);
}
catch (FileNotFoundException)
{
Console.WriteLine(“Error:The file specified was not found.”);
}
catch (ArgumentException)
{
Console.WriteLine(“Error: path is a zero-length string, contains only white space, or contains one or more invalid characters”);
}
catch (PathTooLongException)
{
Console.WriteLine(“Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.”);
}
catch (DirectoryNotFoundException)
{
Console.WriteLine(“Error: The specified path is invalid, such as being on an unmapped drive.”);
}
catch (IOException)
{
Console.WriteLine(“Error: An I/O error occurred while opening the file.”);
}
catch (UnauthorizedAccessException)
{
Console.WriteLine(“Error: path specified a file that is read-only, the path is a directory, or caller does not have the required permissions.”);
}
catch (IndexOutOfRangeException)
{
Console.WriteLine(“Error: You must provide parameters for MyGZIP.”);
}
}

public static void Main(string[] args)
{

Console.WriteLine(“Start”);

GZipCompressDecompress(“c:\\Test1.txt”);

}
}
}

//Code Ends Here

– How to Dynamically Insert Javascript And CSS

<span style=”font-weight:bold;”>This is a short and sweet little tutorial to show you how to dynamically insert a new Javascript (or style sheet) into your web pages</span>

FOR CSS…
var headID = document.getElementsByTagName(“head”)[0];
var cssNode = document.createElement(‘link’);
cssNode.type = ‘text/css’;
cssNode.rel = ‘stylesheet’;
cssNode.href = ‘FireFox.css’;
cssNode.media = ‘screen’;
headID.appendChild(cssNode);

FOR JAVASCRIPT…
var headID = document.getElementsByTagName(“head”)[0];
var newScript = document.createElement(‘script’);
newScript.type = ‘text/javascript’;
newScript.src = ‘http://www.somedomain.com/somescript.js&#8217;;
headID.appendChild(newScript);

– Send mail using System.Net..Mail

<span style=”font-weight:bold;”>Send Mail Messages Using System.Net.Mail namespace (new in .net Framework Version 2.0) which provides classes that enable you to easily create and transmit e-mail messages.</span>

Asp.net c#:
// Create a MailMessage object
MailMessage mm = new MailMessage();

// Define the sender and recipient
mm.From = new MailAddress(fromEmailAddress.Text, fromDisplayName.Text);
mm.To.Add(new MailAddress(toEmailAddress.Text, toDisplayName.Text));

// Define the subject and body
mm.Subject = subjectTextBox.Text;
mm.Body = bodyTextBox.Text;
mm.IsBodyHtml = htmlRadioButton.Checked;

// Configure the mail server
SmtpClient sc = new SmtpClient(serverTextBox.Text);
sc.EnableSsl = sslCheckBox.Checked;
if (!String.IsNullOrEmpty(usernameTextBox.Text))
sc.Credentials = new NetworkCredential(usernameTextBox.Text, passwordTextBox.Text);

// Send the message
sc.Send(mm);
//DONE

– Encode Decode XML Name

Filed under: xml — Tags: , , , , — Admin @ 8:52 am

<span style=”font-weight:bold;”>While coding with XML Files, Sometimes you need to Encode and Decode the Xml Name.
Here is the simplest method to encode the name XmlConvert.EncodeName(string).
</span>

using System.Xml;
namespace ConsoleApplication1
{
class classEncodeDecodeXMLName
{
static void encodedecode()
{
// Encode and decode a name with spaces.
Console.WriteLine(XmlConvert.ToByte(“Some Name”));
string name1 = XmlConvert.EncodeName(“Order Detail”);
Console.WriteLine(“Encoded name: ” + name1);
Console.WriteLine(“Decoded name: ” + XmlConvert.DecodeName(name1));

// Encode and decode a local name.
string name2 = XmlConvert.EncodeLocalName(“a:book”);
Console.WriteLine(“Encoded local name: ” + name2);
Console.WriteLine(“Decoded local name: ” + XmlConvert.DecodeName(name2));
}
public static void Main()
{
encodedecode();
}
}
}

– Unicode Characters

ASCII does’nt recognizes the unicode character. Unicode code character are different from special character. For Ex: scientific characters like pi, pmu,…

Unicode Character is :  Pi : Π
Try out with different unicode characters

//Code starts here
static void convertunicode()
{
string unicodeString = “This string contains the unicode character Pi(\u03a0)”;

// Create two different encodings.
Encoding ascii = Encoding.ASCII;
Encoding unicode = Encoding.Unicode;

// Convert the string into a byte[].
byte[] unicodeBytes = unicode.GetBytes(unicodeString);

// Perform the conversion from one encoding to the other.
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting to illustrate
// the use of GetCharCount/GetChars.
char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
string asciiString = new string(asciiChars);

// Display the strings created before and after the conversion.
Console.WriteLine(“Original string: {0}”, unicodeString);
Console.WriteLine(“Ascii converted string: {0}”, asciiString);
}
//Code Ends Here

May 2, 2008

– Validate XML against Schema

Filed under: xml — Tags: , , — Admin @ 6:34 am

Here I will show you how to “Validate Xml against the provided Schema xsd”.
This is the simplest method to validate the xml from the given Schema xsd
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Data;
using System.Web;
namespace ConsoleApplication1
{
class clsValidateXml
{
public static string ErrorMessage=””;
static void validatexml()
{
//Physical path of the XML File
string XmlFilePath = @”c:\Test.xml”;
//Physical path of the XSD File
string XSDFilePath = @”c:\Test.xsd”;

XmlDocument ObjXmlDocument = new XmlDocument();
ObjXmlDocument.Load(XmlFilePath);

XmlNodeList list = null;
list = ObjXmlDocument.GetElementsByTagName(“ProductPageUrl”);
string tags = null;
foreach (XmlNode node1 in list)
{
//do something with tags
}
ObjXmlDocument.Save(@”c:\final.xml”);

try
{
// Load the schema definition
XmlReaderSettings ObjXMLSettings = new XmlReaderSettings();
ObjXMLSettings.ValidationType = ValidationType.Schema;
ObjXMLSettings.ValidationEventHandler += new ValidationEventHandler(ObjXMLSettings_ValidationEventHandler);
ObjXMLSettings.Schemas.Add(null, XmlReader.Create(XSDFilePath));

XmlNodeReader ObjXmlNodeReader = new XmlNodeReader(ObjXmlDocument);
System.Xml.XmlReader ObjXMLReader,asd = null;
ObjXMLReader = XmlReader.Create(ObjXmlNodeReader, ObjXMLSettings);

// If there XML file does not match the XSD file
//then Validation event handler is fired in this statement
while (ObjXMLReader.Read())
{
}
if (!String.IsNullOrEmpty(ErrorMessage.ToString()))
{
Console.WriteLine(ErrorMessage.ToString());
}
}

catch (XmlException ObjXMLException)
{
Console.WriteLine(“Not a Well Formed XML Document” + ObjXMLException.Message);
}
}
public static void ObjXMLSettings_ValidationEventHandler(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Error)
{
ErrorMessage+=args.Message;
}
}
public static void Main()
{
validatexml();
}
}
}

In the Next post I will Show you how to encode and decode the xml Name……

Blog at WordPress.com.