Thursday, October 28, 2010

upload file to a database

Following is code to read a file from html Input and convert it into byte[]

byte[] imgBinaryData = null;

try
{
Stream imgStream = UploadFile.PostedFile.InputStream;
int imgLen = UploadFile.PostedFile.ContentLength;
imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData, 0, imgLen);
imgStream .Dispose ();
}
catch (Exception)
{


}


Following is the code to insert in DB

string cmdtext1 = "INSERT INTO [Info]([ID] ,[Picture],[afterpic])  values(1,@pic,@aftpic)";
SqlConnection scn = new SqlConnection(AppContext.ConnectionString);
SqlCommand scmd = new SqlCommand(cmdtext1, scn);
SqlParameter param1 = new SqlParameter("@pic", SqlDbType.Image);
SqlParameter param2 = new SqlParameter("@aftpic", SqlDbType.Image);
param1.Value = imgBinaryData;
param2.Value = imgBinaryData1;
scmd.Parameters.Add(param1);
scmd.Parameters.Add(param2);
scn.Open();
scmd.ExecuteNonQuery();
scn.Close();
imgBinaryData=null;;
imgBinaryData1=null;


Thanks,
Suman

Wednesday, October 27, 2010

xml xslt issue with html tags

If you print a dataset to a xml and if one of the values of a XML node has html tags they will be converted

for ex a "<" will be converted to a  "&lt;"  etc... when using style sheet to convert the XML use the following in XSL to
disable-output-escaping="yes"
   <xsl:value-of select="img1" disable-output-escaping="yes" />

Suman

Thursday, October 21, 2010

read excel sheet C#


Assuming txtFileName is a textbox which has the name of the excel. Make sure the sheet name is Sheet1. Please adjust the code according to your requirements.

String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtFileName .Text .ToString () + ";Extended Properties=Excel 8.0;";
OleDbConnection oleDBConn = new OleDbConnection(sConnectionString);
oleDBConn.Open();
OleDbCommand oleDBCmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oleDBConn);
OleDbDataAdapter oledbadptr = new OleDbDataAdapter();
oledbadptr.SelectCommand = oleDBCmd;
DataSet ds1 = new DataSet();
oledbadptr.Fill(ds1);
oleDBConn.Close();

Friday, October 15, 2010

Useful Code


Save stream to a file in C#


public static void saveFile(Stream stream, string FileName)
      {
          

          if (stream.Length == 0) return;

          // Create a FileStream object to write a stream to a file
          using (FileStream fileStream = System.IO.File.Create(FileName, (int)stream.Length))
          {
              // Fill the bytes[] array with the stream data
              byte[] bytesInStream = new byte[stream.Length];
              stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

              // Use FileStream object to write to the specified file
              fileStream.Write(bytesInStream, 0, bytesInStream.Length);
          }
 
      }