I have code to take data from stored procedure.
I just want record from stored procedure. But now I am getting error with this code in class with DataAccess code:
SelectCommand.Connection property has not been initialized. fill data adapter
I just want to track all rows with pagination:
namespace SpidiWeb.App_Code.Helper
{
public class DataAccess
{
public string mstr_ConnectionString;
public SqlConnection mobj_SqlConnection;
public SqlCommand mobj_SqlCommand;
public int mint_CommandTimeout = 30;
public void GetConnection(string cnn_type, string dbname)
{
try
{
if (cnn_type == "W")
{
string Cnn_Str = "";
//string ServerName = "SHREE-PC";
//string DBUserName = string.Empty;
//string DBPassword = string.Empty;
string ServerName = ConfigurationManager.AppSettings["SERVER"];
string DBUserName = ConfigurationManager.AppSettings["UID"] ?? string.Empty;
string DBPassword = ConfigurationManager.AppSettings["PASSWORD"] ?? string.Empty;
string Database = dbname;
DBPassword += "c#" + Convert.ToChar(49);
//Cnn_Str = "Server=" + ServerName + ";User Id=" + DBUserName + ";Password=" + DBPassword + ";Initial Catalog=" + Database;
Cnn_Str = "Server=" + ServerName + ";Initial Catalog=" + Database +";Integrated Security=True";
mstr_ConnectionString = Cnn_Str;
}
else if (cnn_type == "S")
{
string Cnn_Str = "";
//string ServerName = "SHREE-PC";
//string DBUserName = string.Empty;
//string DBPassword = string.Empty;
string ServerName = ConfigurationManager.AppSettings["SERVER"];
string DBUserName = ConfigurationManager.AppSettings["UID"] ?? string.Empty;
string DBPassword = ConfigurationManager.AppSettings["PASSWORD"] ?? string.Empty;
string Database = "NEWSMSLOG_" + dbname;
DBPassword += "c#" + Convert.ToChar(49);
//Cnn_Str = "Server=" + ServerName + ";User Id=" + DBUserName + ";Password=" + DBPassword + ";Initial Catalog=" + Database;
Cnn_Str = "Server=" + ServerName + ";Initial Catalog=" + Database + ";Integrated Security=True";
mstr_ConnectionString = Cnn_Str;
}
mobj_SqlConnection = new SqlConnection(mstr_ConnectionString);
mobj_SqlCommand = new SqlCommand();
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlConnection.Open();
}
catch (Exception ex)
{
throw new Exception("Error initializing data class." + Environment.NewLine + ex.Message);
}
and this code is from my page :
DataAccess obj_con = new DataAccess();
protected void Get_Data()
{
try
{
DataTable dt = new DataTable();
int intUserId = ddl_users.SelectedItem.Text.ToString() == "All" ? 0 : Convert.ToInt32(ddl_users.SelectedValue.ToString());
string strCampaignName = string.IsNullOrEmpty(txt_CompaignName.Text.Trim()) ? string.Empty : txt_CompaignName.Text.Trim();
string mobileNo = string.IsNullOrEmpty(txt_mobileno.Text.Trim()) ? string.Empty : txt_mobileno.Text.Trim();
int intSenderId = ddl_sender.SelectedItem.Text.ToString() == "All" ? 0 : Convert.ToInt32(ddl_sender.SelectedValue.ToString());
string strDeliveryId = ddl_delevery.SelectedItem.Text.ToString() == "All" ? "-1" : ddl_delevery.SelectedItem.Text.ToString();
using (var con = obj_con.mobj_SqlConnection)
{
//if (con.State == ConnectionState.Closed)
// con.Open();
var cmd = new SqlCommand();
cmd.Parameters.AddWithValue("intUserID", intUserId);
cmd.Parameters.AddWithValue("strCampaignName", strCampaignName);
cmd.Parameters.AddWithValue("strMobileNo", mobileNo);
cmd.Parameters.AddWithValue("intSenderId", intSenderId);
cmd.Parameters.AddWithValue("strDeliveryId", strDeliveryId);
if (ddl_account.SelectedItem.Text.ToString() == "All")
{
cmd.Parameters.AddWithValue("intAccType", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("intAccType", Convert.ToInt32(ddl_account.SelectedValue.ToString()));
}
if (chk_date.Checked == true)
{
DateTime dateValue = Convert.ToDateTime(CommonLogic.Get_Date_From_String(txt_date_from.Text.Trim(), 1));
cmd.Parameters.AddWithValue("strdbNM ", dateValue.ToString("yyyy_MM"));
}
else
{
cmd.Parameters.AddWithValue("strdbNM ", DateTime.Now.Date.ToString("yyyy_MM"));
}
if (!string.IsNullOrEmpty(txt_date_from.Text.Trim()))
{
DateTime date = Convert.ToDateTime(txt_date_from.Text.Trim());
cmd.Parameters.AddWithValue("strTBNM", date.ToString("ddMMyy"));
}
else
{
cmd.Parameters.AddWithValue("strTBNM", DateTime.Now.Date.ToString("ddMMyy"));
}
cmd.Parameters.AddWithValue("PageIndex", 1);
cmd.Parameters.AddWithValue("PageSize", 1000);
cmd.Parameters.Add("RecordCount", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.Connection = con;
cmd.CommandText = "dbo.Report_ViewCombineReport";
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.SelectCommand = cmd;
ad.Fill(dt); // Error Occurs here Fill: SelectCommand.Connection property has not been initialized.
egrd.DataSource = dt;
egrd.DataBind();
}
}
catch (Exception ex)
{
CommonLogic.SendMailOnError(ex);
}
}
You didn't pass Connection to SqlCommand object, pass it in parameter like below
var cmd = new SqlCommand("Your query", con);
Or you can also set it by
cmd.Connection = con;
Related
Does anyone know to fix the error? I would like to create the OR statement but it does not function in my code. The code is shown below. I have removed the OR to see the code function or not, it can function if I remove the or statement. So I desperately want to know what the real problem with my code is.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class updateform : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=test;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select * FROM [EMP] WHERE Serial_Num='" + TextBox2.Text + "' or Equipment_ID ='" + TextBox1.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
TextBox3.Text = dt.Rows[0][2].ToString();
TextBox4.Text = dt.Rows[0][6].ToString();
DropDownList1.Text = dt.Rows[0][7].ToString();
TextBox5.Text = dt.Rows[0][18].ToString();
TextBox6.Text = dt.Rows[0][11].ToString();
TextBox11.Text = dt.Rows[0][8].ToString();
TextBox7.Text = dt.Rows[0][20].ToString();
TextBox12.Text = dt.Rows[0][17].ToString();
DropDownList2.Text = dt.Rows[0][23].ToString();
TextBox9.Text = dt.Rows[0][14].ToString();
TextBox10.Text = dt.Rows[0][13].ToString();
TextBox13.Text = dt.Rows[0][12].ToString();
TextBox2.Text = dt.Rows[0][5].ToString();
TextBox1.Text = dt.Rows[0][4].ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source =.\\sqlexpress; Initial Catalog = test; Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand(#"UPDATE EMP SET Model='" + TextBox3.Text + "' ,Description= '" + TextBox4.Text + "' ,Location='" + DropDownList1.Text + "',Manufacturer_or_Vendor= '" + TextBox5.Text + "',NCR_or_OOT_History='" + TextBox6.Text + "',Due_date= '" + TextBox11.Text + "' ,Year_of_Manufacturing='" + TextBox12.Text + "',Asset_No= '" + TextBox7.Text + "' ,Status='" + DropDownList2.Text + "',Responsible_Person= '" + TextBox9.Text + "',Available_in_Sapphire= '" + TextBox10.Text + "',Last_OOT_issuance_Date= '" + TextBox13.Text + "' WHERE (Serial_Num = '" + TextBox2.Text + "' or Equipment_ID = '" + TextBox1.Text + "' )", con);
cmd.ExecuteNonQuery();
con.Close();
}
protected void Page_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Calendar1.Visible = false;
Calendar2.Visible = false;
Calendar3.Visible = false;
}
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (Calendar1.Visible)
{
Calendar1.Visible = false;
}
else
{
Calendar1.Visible = true;
}
}
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
if (Calendar2.Visible)
{
Calendar2.Visible = false;
}
else
{
Calendar2.Visible = true;
}
}
protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
{
if (Calendar3.Visible)
{
Calendar3.Visible = false;
}
else
{
Calendar3.Visible = true;
}
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox11.Text = Calendar1.SelectedDate.ToString("dd/MM/yyyy");
Calendar1.Visible = false;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
TextBox12.Text = Calendar2.SelectedDate.ToString("dd/MM/yyyy");
Calendar2.Visible = false;
}
protected void Calendar3_SelectionChanged(object sender, EventArgs e)
{
TextBox13.Text = Calendar1.SelectedDate.ToString("dd/MM/yyyy");
Calendar3.Visible = false;
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsOtherMonth)
{
e.Day.IsSelectable = false;
}
}
protected void Calendar2_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsOtherMonth)
{
e.Day.IsSelectable = false;
}
}
protected void Calendar3_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsOtherMonth)
{
e.Day.IsSelectable = false;
}
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
}
It is not clear from your description whether it fails at compile time or execution time, or what the error is. But a wild guess of what could be the problem, try the followings:
Instead of Select * try specifying the actual columns (like select col1, col2, ..
Instead of:
sda.Fill(dt);
Declare a dataset and fill the dataset and see if it works.
DataSet ds = new DataSet ();
sda.Fill (ds);
If this works, check and see how many tables are created in your dataset and what records are in each table.
Page script keeps on running, doesn't shows message "Your request has been submitted successfully" as mentioned in my below. Can anyone please help what I am missing here?
protected void Button1_Click1(object sender, EventArgs e)
{
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["GerpConnStr"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
string name = System.Web.HttpContext.Current.User.Identity.Name;
string domain = name.Substring(+13);
try
{
con.Open();
SqlCommand cmd = con.CreateCommand();
SqlCommand cmd1 = new SqlCommand("SELECT max(ID) as maxReq FROM request", con);
cmd1.CommandType = CommandType.Text;
int result = ((int)cmd1.ExecuteScalar());
int req = result + 1;
if (FileUpload1.HasFile)
{
string extension1 = Path.GetExtension(FileUpload1.PostedFile.FileName);
string attachment = (FileUpload1.FileName + '_' + req + extension1);
cmd.CommandType = CommandType.Text;
string dt2 = DateTime.Now.ToString("yyyyMMddHHmmss");
DateTime time = DateTime.Now;
cmd.CommandText = "insert into request (request_type,request_area,subject,description,requestor,req_status,attachment,request_time) values('" + DropDownList1.SelectedValue + "','" + DropDownList2.SelectedValue + "','" + TextBox1.Text + "','" + TextArea1.InnerText + "','" + Label3.Text + "','" + "Open" + "','" + attachment + "','" + time + "')";
string saveDir = #"\upload\" + Server.HtmlEncode(FileUpload1.FileName);
string dt = DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss") + "_";
string appPath = Request.PhysicalApplicationPath;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string savePath = appPath + saveDir +
Server.HtmlEncode(FileUpload1.FileName);
string saveSess = saveDir + dt +
Server.HtmlEncode(FileUpload1.FileName);
FileUpload1.SaveAs(saveDir + '_' + req + extension);
// Label4.Text = "Your request has been submitted successfully";
string message = "Your request has been submitted successfully";
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += Request.Url.AbsoluteUri;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
Session["sessimage1"] = saveSess;
// CreateMailItem();
} //if
else
{
// string extension1 = Path.GetExtension(FileUpload1.PostedFile.FileName);
// string attachment = (FileUpload1.FileName + '_' + req + extension1);
// SqlCommand cmd1 = con.CreateCommand();
cmd.CommandType = CommandType.Text;
DateTime time = DateTime.Now;
// string dt1 = DateTime.Now.ToString("yyyyMMddHHmmss");
cmd.CommandText = "insert into request (request_type,request_area,subject,description,requestor,req_status,request_time) values('" + DropDownList1.SelectedValue + "','" + DropDownList2.SelectedValue + "','" + TextBox1.Text + "','" + TextArea1.InnerText + "','" + Label3.Text + "','" + "Open" + "','" + time + "')";
// Label4.Text = "Your request has been submitted successfully";
string message = "Your request has been submitted successfully";
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += Request.Url.AbsoluteUri;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
// Response.Redirect(Request.Url.AbsoluteUri);
// EmptyTextBoxes(TextBox1.Text);
// this.Controls.Clear();
// this.InitializeComponent();
} //else
// SaveFile(FileUpload1.PostedFile);
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
con.Close();
} //try
catch
{
Console.WriteLine("Insert failed");
Console.Read();
}
finally
{
con.Close();
}
CreateMailItem();
} //button1
Its solved now. Its was getting error at Console.Read() in CreateMailItem(). Thats why it was never going back to Button1_Click1(object sender, EventArgs e) to post the message of successful submission. I have omitted Console.Read() and now the execution of CreateMailItem() gets completed and control gets back to Button1_Click1(object sender, EventArgs e) to post the message of successful submission.
Updated part:
catch
{
Console.WriteLine("Insert failed");
//Console.Read();
}
I am uploading excel from xls file in mvc5 i have following method
public ActionResult Importexcel()
{
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string fileExtension =
System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
// Create a folder in App_Data named ExcelFiles because you need to save the file temporarily location and getting data from there.
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
Request.Files["FileUpload1"].SaveAs(path1);
string sqlConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(sqlConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
//excel data saves in temp file here.
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(sqlConnectionString);
DataSet ds = new DataSet();
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
SqlConnection sqlc = new SqlConnection();
sqlc.ConnectionString = #"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Planetskool-20140309125429.mdf;Initial Catalog=aspnet-Planetskool-20140309125429;Integrated Security=True";
SqlCommand cmd2 = new SqlCommand("INSERT INTO UserInfo (UserInfoID, GraphID, UserCreatorId,UserLevelEnumId,Birthdate,Zipcode,UserLevel,UserID) VALUES(#UserInfoID, #GraphID, #UserCreatorId,#UserLevelEnumId,#Birthdate,#Zipcode,#UserLevel,#UserID)", sqlc);//#OB_ID is indentity primary key
cmd2.Parameters.Add("#UserInfoID", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserInfoID"].ToString());
cmd2.Parameters.Add("#GraphID", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["GraphID"].ToString());
cmd2.Parameters.Add("#UserCreatorId", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserCreatorId"].ToString());
cmd2.Parameters.Add("#UserLevelEnumId", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserLevelEnumId"].ToString());
// cmd2.Parameters.Add("#Birthdate", SqlDbType.DateTime).Value = DateTime.UtcNow.ToLocalTime();
cmd2.Parameters.Add("#Zipcode", SqlDbType.NVarChar).Value = (ds.Tables[0].Rows[i]["Zipcode"].ToString());
cmd2.Parameters.Add("#UserLevel", SqlDbType.NVarChar).Value = (ds.Tables[0].Rows[i]["Zipcode"].ToString());
cmd2.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserID"].ToString());
sqlc.Open();
cmd2.ExecuteNonQuery();
sqlc.Close();
//db.StudentRecords.Add(model);
//db.SaveChanges();
}
return RedirectToAction("Index");
}
}
when i am uploading the file i am getting only 1 rows in my database i have debug the rows count in visual studio i am geeting total rows but not able to get it in my database
Use Microsoft.Office.Interop.Excel your may as like below... it may help you
public void ImportXLX()
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(#"C:\Users\Vipin\Desktop\Sheets\MyXL6.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
int workSheetCounts = wb.Worksheets.Count;
for (int sheetCounter = 1; sheetCounter <= workSheetCounts; sheetCounter++)
{
Microsoft.Office.Interop.Excel.Worksheet workSheet = wb.Sheets[sheetCounter];
Range excelRange = workSheet.UsedRange;
Range objRange = null;
int rowCountForHeight = 0;
double totalColHeight = 0;
double totalRowWidth = 0;
foreach (Microsoft.Office.Interop.Excel.Range row in excelRange.Rows)
{
rowCountForHeight++;
int colCount = 0;
foreach (Microsoft.Office.Interop.Excel.Range c in row.Cells)
{
colCount++;
objRange = workSheet.Cells[rowCountForHeight, colCount];
double height = 0;
if (objRange.MergeCells)
{
Debug.Write("CellsMerged \n");
height = ((Range)objRange.MergeArea[1, 1]).Height;
}
else
{
Debug.Write("CellsMergedNot \n");
height = objRange.Height;
}
totalColHeight = totalColHeight + height;
}
}
int rowCount = 0;
foreach (Microsoft.Office.Interop.Excel.Range row in excelRange.Rows)
{
rowCount++;
totalRowWidth = row.Width;
int colCount = 0;
foreach (Microsoft.Office.Interop.Excel.Range c in row.Cells)
{
colCount++;
objRange = workSheet.Cells[rowCount, colCount];
double width = 0;
double height = 0;
string colVal = null;
if (objRange.MergeCells)
{
colVal = Convert.ToString(((Range)objRange.MergeArea[1, 1]).Text).Trim();
width = objRange.MergeArea.Width;
height = objRange.MergeArea.Height;
}
else
{
colVal = Convert.ToString(objRange.Text).Trim();
width = objRange.Width;
height = objRange.Height;
}
Debug.Write("objRange = " + objRange + " rowCount = " + rowCount + " Width = " + width + " height = " + height + "TotalColumnWidth = " + totalRowWidth + "TotalRowHeight = " + totalColHeight + " \n ");
}
}
}
app.Quit();
}
I have a HR web application which includes organization structure within workplaces.
The client is sending a .docx file with workplace name and its description. I need to make a C# application to get data from the .docx file and update some database tables with it.
I already tried .docx conversion to XML but I have no idea how to pick up data from that XML and insert it into the database.
Is there a easier way to update this database directly from a .docx file or what mechanics should I use to find data in the XML file.
Try this..
Below is the connection string to the database. You can modify it to suit yours
<connectionStrings>
<add name="conString" connectionString="Data Source=.\SQLEXPRESS;database=dbFiles; Integrated Security=true"/>
</connectionStrings >
To start with I have added a FileUpload control, a button and a Label to show messages
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="btnUpload_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" Text=""
Font-Names = "Arial"></asp:Label>
And here is the snippet which is called on the Upload Button Click event
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch(ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data)" +
" values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value
= contenttype;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Image/Word/PDF/Excel formats";
}
}
VB.Net
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
' Read the file and convert it to Byte Array
Dim filePath As String = FileUpload1.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
'Set the contenttype based on File Extension
Select Case ext
Case ".doc"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".docx"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".xls"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".xlsx"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
Case ".gif"
contenttype = "image/gif"
Exit Select
Case ".pdf"
contenttype = "application/pdf"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "insert into tblFiles" _
& "(Name, ContentType, Data)" _
& " values (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value _
= contenttype
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." _
& " Upload Image/Word/PDF/Excel formats"
End If
End Sub
The above code simply reads the uploaded File as Stream and then converts the Stream to Byte array using Binary Reader and then the finally the byte arrays is saved to the database InsertUpdateData method executes the query to save the data in database
The InsertUpdateData function is given below
C#
private Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
I have this simple code to test that a DB is ready:
Function testlocalcon() As Boolean
Dim constr As String = _clconstr
Try
Using t As New SqlConnection()
constr = constr & " ; Connect Timeout=1"
If Not t.State = Data.ConnectionState.Open Then
t.ConnectionString = constr
t.Open()
If t.State = Data.ConnectionState.Open Then
Return True
Else
Return False
End If
Else
Return True
End If
End Using
Catch ex As Exception
Return False
End Try
End Function
I do not want to execute a query, just to check the connection, but no matter what the time out parameter is ignored. I search here (Stackoverflow) and internet and found nothing in how to fix this.
Any one else have this problem? Or, are there any other ideas on how to let the application know that the DB is ready?
I appologize for the code differenc but this is C# and I have used it in the past. Its pretty simple and should be readable.
private SQLServerConnection
private SqlConnection _SQLServerConnection;
public SqlConnection SQLServerConnection
{
get
{
return _SQLServerConnection;
}
set
{
_SQLServerConnection = value;
}
}
private void SetSQLServerConnectionString (string sqlServerName, string databaseName, string saPassword, int connectTimeout)
{
SQLServerConnection = new SqlConnection("Password=" + saPassword + ";Persist Security Info=True;User ID=sa;Initial Catalog=" + databaseName + ";Data Source=" + sqlServerName + ";connection timeout=" + connectTimeout.ToString(CultureInfo.InvariantCulture));
}
internal bool TestSQLServerConnection(string sqlServerName, string databaseName, string saPassword, int connectTimeout)
{
try
{
SetSQLServerConnectionString(sqlServerName, databaseName, saPassword, connectTimeout);
SQLServerConnection.Open();
return true;
}
catch (SqlException e)
{
return false;
}
finally
{
SQLServerConnection.Close();
}
}