Oledbcommand with date in the where clause - oledbconnection

I am using oledbconnection to read dbf files. I am trying to search all data from a specific dbf database. I am doing it well when there is no date in where clause. But when I am using date as a where I am having zero result.
String constr = #"Provider=VFPOLEDB.1;Data Source=" + Directory.GetParent(cashierPath).FullName +
";Exclusive=false;Nulls=false";
DataTable dt = new DataTable();
OleDbConnection con= new OleDbConnection(constr);
con.Open();
using (OleDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = "select id from " + Path.GetFileName(cashierPath) + " where todate=#todate";
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#todate", "2016-07-21")
});
using(OleDbDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
String data = reader.GetString(0);
MessageBox.Show(data);
}
}
}
I don't really know what the problem.

Related

An unhandled exception in the designer

I've created a project in Visual Studio 2019 which has several user controls in a form called Home.
All goes right until today. After rebuilding my project Home form shows an error saying
The control system.windows.forms.form has thrown an unhandled exception in the designer and has been desabled.
Exception :
An attempt to attach an auto-named database for file c:\program files(x86)\Microsoft Visual Studio\2019\Enterprise\common7\ide\database\pharmacy.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on unc share.
I checked the connection code, and it looks ok. But still the error isn't solved.
Code:
SqlConnection con = new SqlConnection(#"Data Source=LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Final Project BCA\PharmacyManagementSystemCSharp\Database\pharmacy.mdf;Integrated Security=True");
con.Open()
String str = "Select max(id) from supp;";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
String val = dr[0].ToString();
if (val == "")
{
.....
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source= (LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Final Project BCA\PharmacyManagementSystemCSharp\Database\pharmacy.mdf;Integrated Security=True");
con.Open();
try
{
String str = "Insert into supp(name,email,mobile,addr,s_code) values('" + Sup_Name.Text + "','" + Sup_Email.Text + "','" + Sup_Mobile.Text + "','" + Sup_Add.Text + "','" + Sup_Code.Text + "');";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
String str1 = "select max(ID) from supp;";
SqlCommand cmd1 = new SqlCommand(str1, con);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Inserted Supplier Data SuccessFully..");
using (SqlConnection con1 = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Final Project BCA\PharmacyManagementSystemCSharp\Database\pharmacy.mdf;Integrated Security=True"))
{
String str2 = "Select * from supp";
SqlCommand cmd2 = new SqlCommand(str2, con1);
SqlDataAdapter sda = new SqlDataAdapter(cmd2);
DataTable dt = new DataTable();
sda.Fill(dt);
SupplierDataGV.DataSource = new BindingSource(dt, null);
}
Sup_Name.Text = "";
Sup_Code.Text = "";
Sup_Email.Text = "";
Sup_Mobile.Text = "";
Sup_Add.Text = "";
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}

retrieve checkbox values and mark as checked

i'm trying to retrieve options from database to checkbox and if it has the same product ID it has to be checked by default
this is the insert code to database
for (int i = 0; i < ddlcaroptions.Items.Count; i++)
{
if (ddlcaroptions.Items[i].Selected == true)
{
Int64 PCarOptionID = Convert.ToInt64(ddlcaroptions.Items[i].Value);
SqlCommand cmd2 = new SqlCommand("insert into tblCarOptionQuant values('" + PID + "','" + PCarOptionID + "')", con);
cmd2.ExecuteNonQuery();
}
}
it works fine now i want to edit this checkbox and update database
now i bind the checkbox from another table that has name and values
SqlCommand cmd = new SqlCommand("select * from tblCarOption", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count != 0)
{
ddlcaroptions.DataSource = dt;
ddlcaroptions.DataTextField = "CarOptionNameAR";
ddlcaroptions.DataValueField = "CarOptionID";
ddlcaroptions.DataBind();
}
now i have all the options but i want the selected values to be the ones that user already checked before and saved in tblCarOptionQuant table,
i tried to get the values by this command
using (SqlCommand getselectedop = new SqlCommand("select PCarOptionID from tblCarOptionQuant where PID = " + PID + "", con))
its okay but now what can i do to set selected values from this command result !??
you can use FindByValue to get the specific item and set it to selected, refer the code below
string value = "SomeValue";
var item = ddlcompany.Items.FindByValue(value);
if (item != null)
item.Selected = true;
the problem is when you retrieve data and convert to string you get only 1st row so i used StringBuilder to build 1 string has all rows in table :)
!! Attention !!
before you use this code make sure you bind your checkbox with all the values that user checked or not ,, then use this code to get the options that selected before (by the user)
using (SqlCommand getselectedop = new SqlCommand("RetrieveCarOptions", con))
{
getselectedop.CommandType = CommandType.StoredProcedure;
getselectedop.Parameters.AddWithValue("#PID", Convert.ToInt64(Request.QueryString["PID"]));
con.Open();
using (SqlDataReader reader = getselectedop.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
if (reader.HasRows)
{
if (sb.Length > 0) sb.Append("___");
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
if (reader.GetValue(i) != DBNull.Value)
sb.AppendFormat("{0}-", Convert.ToString(reader.GetValue(i)));
SelectCheckBoxList(reader["PCarOptionID"].ToString(), ddlcaroptions);
}
}
}
}
now split and check if it has the same value to mark as checked
private void SelectCheckBoxList(string valueToSelect, CheckBoxList ddlcaroptions)
{
string[] aray = valueToSelect.Split(',');
foreach (string listItem2 in aray)
{
ListItem listItem = ddlcaroptions.Items.FindByValue(valueToSelect);
listItem.Selected = true;
}
}
i hope this answer is clear and help someone else :)

ASP MVC Return SP result to View

Using VS 2013 and writing my first ASP MVC app. I have a controller:
// GET: CreateBundlesAndCartons
public ActionResult CreateBandC(Int32 id)
{
string ReturnMessage;
ReturnMessage = "";
using (SqlConnection connection = new SqlConnection())
{
//string connectionStringName = this.DataWorkspace.CooperData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings["PSAContext"].ConnectionString;
string procedure = "PSA.dbo.CreateBundlesAndCartons";
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = 300;
command.Parameters.Add(
new SqlParameter("#JobID", id));
SqlParameter ErrorString = new SqlParameter("#ErrorString", ReturnMessage);
ErrorString.Direction = ParameterDirection.Output;
ErrorString.Size = 4000;
command.Parameters.Add(ErrorString);
connection.Open();
command.ExecuteNonQuery();
// Save Outout Param
ReturnMessage = ErrorString.Value.ToString();
}
}
return Content("You requested the to create bundles and cartons for job ID " + id.ToString() + "<br />Result: " + ReturnMessage + "<br /> ");
}
I want to display the results to the user and them give them ability to return to the jobs view.
I tried this as my return value:
return Content("You requested the to create bundles and cartons for job ID " + id.ToString() + "Result: " + ReturnMessage + " Return to Jobs");
This displays the results and the link:
But the link points to http://localhost:59971/Jobs/CreateBandC/~/Jobs/ instead of http://localhost:59971/Jobs/
How can I fix that?
Is there a better way to return the results?
I'm under some time pressure, so this approach would do for now, but I'd like to actually figure out how to return a more complex type and nicer view
Thanks
mark
Looks like this requires database changes to fix the link. This is typically a result of poor design and tight coupling. So, go in the database and change the a tag in your stored procedure to get the desired result.

mvc 4 asp.net - export data to .csv from a local .xls file

I would be grateful if you could please help me with the code below: I am fairly new to C# and Razor. I am trying to get data from an excel sheet and displaying it on the screen using a jQuery Jtable. I can get it to be displayed but its not exporting the data to CSV file. I am using MVC 4 Razor ASP.NET
here's my controller action code:
private void ExportToCsv(object sender, System.EventArgs e)
{
string Path = #"C:\\5Newwithdate.xls";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
con.Close();
System.Data.DataTable data = new System.Data.DataTable();
da.Fill(data);
SQLDBBillingProvider sql = new SQLDBBillingProvider();
// var billingList = sql.GetAllBilling(jtStartIndex, jtPageSize, jtSorting);
// data.Rows.OfType<DataRow>().Select(dr => dr.Field<MyType>(columnName)).ToList();
List<TopPlayed> daa = new List<TopPlayed>();
foreach (DataRow p in data.Rows)
{
//daa.Add(p.Field<string>("Track Statistics"));
//daa.Add(p.Field<string>("Track Name"));
TopPlayed top = new TopPlayed()
{
TrackID = p.Field<double>("ID").ToString(),
TrackName = p.Field<string>("Track Name"),
ArtistName = p.Field<string>("Artist Name"),
Times = p.Field<double>("NoOfPlays").ToString()
};
daa.Add(top);
}
var toptracks = new List<TopPlayed>();
// toptracks.Add(GetHeader());
int k = -5;
for (int i = 0; i < 5; i++)
{
//static data
var trackInfo = new TopPlayed();
trackInfo.TrackID = "abc" + i;
trackInfo.TrackName = "xyz" + i;
trackInfo.ArtistName = "" + i;
trackInfo.Times = "" + i;
toptracks.Add(trackInfo);
}
System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
gridvw.DataSource = toptracks.ToList().Take(7); //bind the datatable to the gridview
gridvw.DataBind();
Response.ClearContent();
Response.ContentType = "application/vnd.ms-excel;name='Excel'";
Response.AddHeader("content-disposition", "attachment;filename=TopTracks.csv");
StringWriter swr = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(swr);
gridvw.RenderControl(tw);
Response.Write(swr.ToString());
Response.End();
}
Thanks in advance.
From an existing, working, project:
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
var sw = new StreamWriter(new MemoryStream());
// Write the strings here..
sw.WriteLine(...) etc
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
Just tweak the variables to suit your filename and data writing method.
e.g.
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
var sw = new StreamWriter(new MemoryStream());
// Write the data here..
HtmlTextWriter tw = new HtmlTextWriter(sw);
gridvw.RenderControl(tw);
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
In the context of your original question it will look something like:
public ActionResult ExportToCsv()
{
string Path = #"C:\\5Newwithdate.xls";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= '" + Path + "';Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;" + (char)34 + "");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con);
con.Close();
System.Data.DataTable data = new System.Data.DataTable();
da.Fill(data);
SQLDBBillingProvider sql = new SQLDBBillingProvider();
// var billingList = sql.GetAllBilling(jtStartIndex, jtPageSize, jtSorting);
// data.Rows.OfType<DataRow>().Select(dr => dr.Field<MyType>(columnName)).ToList();
List<TopPlayed> daa = new List<TopPlayed>();
foreach (DataRow p in data.Rows)
{
//daa.Add(p.Field<string>("Track Statistics"));
//daa.Add(p.Field<string>("Track Name"));
TopPlayed top = new TopPlayed()
{
TrackID = p.Field<double>("ID").ToString(),
TrackName = p.Field<string>("Track Name"),
ArtistName = p.Field<string>("Artist Name"),
Times = p.Field<double>("NoOfPlays").ToString()
};
daa.Add(top);
}
var toptracks = new List<TopPlayed>();
// toptracks.Add(GetHeader());
int k = -5;
for (int i = 0; i < 5; i++)
{
//static data
var trackInfo = new TopPlayed();
trackInfo.TrackID = "abc" + i;
trackInfo.TrackName = "xyz" + i;
trackInfo.ArtistName = "" + i;
trackInfo.Times = "" + i;
toptracks.Add(trackInfo);
}
System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
gridvw.DataSource = toptracks.ToList().Take(7); //bind the datatable to the gridview
gridvw.DataBind();
HttpContext.Response.ClearContent();
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=filename=TopTracks.csv");
HttpContext.Response.AddHeader("Expires", "0");
var sw = new StreamWriter(new MemoryStream());
// Write the data here..
HtmlTextWriter tw = new HtmlTextWriter(sw);
gridvw.RenderControl(tw);
// Flush the stream and reset the file cursor to the start
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.Begin);
// return the stream with Mime type
return new FileStreamResult(sw.BaseStream, "text/csv");
}

OleDbConnection to Excel File in MOSS 2007 Shared Documents

I need to programmatically open an Excel file that is stored in a MOSS 2007 Shared Documents List. I’d like to use an OleDbConnection so that I may return the contents of the file as a DataTable. I believe this is possile since a number of articles on the Web imply this is possible. Currently my code fails when trying to initialize a new connection (oledbConn = new OleDbConnection(_connStringName); The error message is:
Format of the initialization string does not conform to specification starting at index 0.
I believe I am just not able to figure the right path to the file. Here is my code:
public DataTable GetData(string fileName, string workSheetName, string filePath)
{
// filePath == C:\inetpub\wwwroot\wss\VirtualDirectories\80\MySpWebAppName\Shared Documents\FY12_FHP_SPREADSHEET.xlsx
// Initialize global vars
_connStringName = DataSource.Conn_Excel(fileName, filePath).ToString();
_workSheetName = workSheetName;
dt = new DataTable();
//Create the connection object
if (!string.IsNullOrEmpty(_connStringName))
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
oledbConn = new OleDbConnection(_connStringName);
try
{
oledbConn.Open();
//Create OleDbCommand obj and select data from worksheet GrandTotals
OleDbCommand cmd = new OleDbCommand("SELECT * FROM " + _workSheetName + ";", oledbConn);
//create new OleDbDataAdapter
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dt);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
finally
{
oledbConn.Close();
}
});
}
return dt;
}
public static OleDbConnection Conn_Excel(string ExcelFileName, string filePath)
{
// filePath == C:\inetpub\wwwroot\wss\VirtualDirectories\80\MySpWebAppName\Shared Documents\FY12_FHP_SPREADSHEET.xlsx
OleDbConnection myConn = new OleDbConnection();
myConn.ConnectionString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0");
return myConn;
}
What am I doing wrong, or is there a better way to get the Excel file contents as a DataTable?
I ended up using the open source project Excel Data Reader

Resources