Save serial number in Excel using WPF (OLEDB) - excel

My application in WPF allows user to save some data from text boxes into Excel file (using OLEDB connection). I wish to add feature that every time new row is saved into Excel file a sequence number is added into EventID column in that Excel file.
But I'm getting an error while running the application related to parameter #EventId saying: 'parameter has no default value'.
I expect I have written wrong sql1 command to generate the serial number.
I'd appreciate your help.
private void btnSaveNewEvent1_Click_1(object sender, RoutedEventArgs e)
{
object eventName = txtEventName.Text;
object typeValue = txtEventType.Text;
object nameValue = txtAttributeName.Text;
object attribvValue = txtAValue.Text;
object descValue = txtEventDescrip.Text;
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
System.Data.OleDb.OleDbCommand myCommand1 = new System.Data.OleDb.OleDbCommand();
String sql = null;
String sql1 = null;
MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source='excel_file\\events2.xlsx'; " +
"Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"");
try
{
//SQL STATEMENT TO SAVE INSERTED BY THE USER VALUES FROM THE TEXT BOXES
//SQL1 STATEMENT TO GENERATE EVENTID NUMBER EACH TIME THE USER SAVES NEW ROW OF DATA
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Insert into [events$] (EventID,EventName, Type, Name, [Value], Description) values(#EventID,#EventName,#Type,#Name,#Val,#Desc)";
myCommand.CommandText = sql;
myCommand.Parameters.AddWithValue("#EventID",sql1);
myCommand.Parameters.AddWithValue("#EventName", eventName ?? DBNull.Value);
myCommand.Parameters.AddWithValue("#Type", typeValue ?? DBNull.Value);
myCommand.Parameters.AddWithValue("#Name", nameValue ?? DBNull.Value);
myCommand.Parameters.AddWithValue("#Val", attribvValue ?? DBNull.Value);
myCommand.Parameters.AddWithValue("#Desc", descValue ?? DBNull.Value);
myCommand1.Connection = MyConnection;
sql1= "DECLARE #i int = 0 while #i < EventID BEGIN SET #i = EventID + 1 END";
myCommand1.CommandText = sql1;
myCommand.ExecuteNonQuery();
myCommand1.ExecuteNonQuery();
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
MyConnection.Close();
Events eventsWindow = new Events();
eventsWindow.dgData.Items.Refresh();
}
}

Since your command is running before command1 sql1 = null, That is what your problem is.
You need to set the value of sql1 before executing the command. If you really want the value to be null you need to use DBNull.Value as you have for the other parameters.

Related

Visual Studio - Windows Form - CheckedListBox not inserting correctly. C#

I am working on a Windows Form that has a CheckedListBox control (cbIntendedMajor) that I am attempting to insert into an Access database. I am not returning any errors, however when I select more than one check box item only the first one selected inserts into the table with a comma. Any pointers on what I am missing here? Below is my code:
private void button1_Click(object sender, EventArgs e)
{
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Interest.accdb";
OleDbConnection con = new OleDbConnection(conString);
OleDbCommand cmd = con.CreateCommand();
string text = "INSERT INTO InterestCard (FirstName, LastName, StreetAddress, City, State, ZipCode, Phone, Email, DOB, Gender, HighSchool, GraduationYear, PlannedTerm, IntendedMajor) VALUES (#FName, #LName, #SAddress, #City, #State, #Zip, #Phone, #Email, #DOB, #Gender, #HSchool, #GradYear, #PTerm, #IMajor)";
cmd.CommandText = text;
con.Open();
cmd.Parameters.AddWithValue("#FName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LName", txtLastName.Text);
cmd.Parameters.AddWithValue("#SAddress", txtAddress.Text);
cmd.Parameters.AddWithValue("#City", txtCity.Text);
cmd.Parameters.AddWithValue("#State", txtState.Text);
cmd.Parameters.AddWithValue("#Zip", txtZipCode.Text);
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#DOB", dtpDOB.Value);
cmd.Parameters.AddWithValue("#Gender", rbFemale.Checked);
cmd.Parameters.AddWithValue("#HSchool", txtHighSchool.Text);
cmd.Parameters.AddWithValue("#GradYear", txtGraduationYear.Text);
cmd.Parameters.AddWithValue("#PTerm", txtTermofEnrollment.Text);
foreach (string s in cbIntendedMajor.CheckedItems)
{
cmd.Parameters.AddWithValue("#IMajor", s + ",");
}
cmd.ExecuteNonQuery();
}
I think that your parameter can only be added once. You might consider instead, iterating over the .CheckedItems, creating a single string with each item added with a comma. Then outside of the foreach() loop you can cmd.Parameters.AddwithValue("#IMajor", fullString

How to save image to the database after it is scanned

I have developed a windows application to scan images.After the image is scanned i want to save it directly to the database not in local machine...The code which i have used is as follows
try
{
String str = string.Empty;
WIA.CommonDialogClass scanner;
ImageFile imageObject;
scanner = new CommonDialogClass();
imageObject = scanner.ShowAcquireImage
(WiaDeviceType.ScannerDeviceType,
WiaImageIntent.ColorIntent,
WiaImageBias.MinimizeSize,
ImageFormat.Jpeg.Guid.ToString("B"),
false,
true,
true);
str = DateTime.Now.ToString();
str = str.Replace("/", "");
str = str.Replace(":", "");
Directory.CreateDirectory("D:\\scanned1");
// MessageBox.Show(string.Format("File Extension = {0}\n
//\nFormat = {1}", imageObject.FileExtension, imageObject.FormatID));
imageObject.SaveFile(#"D:\scanned1\lel" + str + ".jpg");
MessageBox.Show("Scanning Done");
}
catch (Exception ex)
{
MessageBox.Show("Please check if the scanner is connected properly.");
}
Instead of saving it to D drive i want to save it to database.....How can i do it?Plz reply...
I've got no idea what "ImageFile" is really, but there should be a way to transform it into the byte array (byte[]). Afterwards you would need to insert that array to varbinary field in your sql.
something like this:
using(SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (myvarbinarycolumn) VALUES (#myvarbinaryvalue)", conn))
{
cmd.Parameters.Add("#myvarbinaryvalue", SqlDbType.VarBinary, myarray.length).Value = myarray;
cmd.ExecuteNonQuery();
}
ofc sqlcommand should be opened and valid.
myarray is of type byte[]

GetDeleteCommand DataAdapter with a temporary table in Sybase

Porting MSSQL Application to Sybase (ASE 15.0), and experiencing a problem when I call GetDeleteCommand.
The error reported is:
Dynamic SQL generation for the DeleteCommand is not supported against
a SelectCommand that does not return any key column information.
The problem only occurs for temporary table, identical non-temporary table works fine.
Table contains a primary key.
Reproduced using test program below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;
namespace DataAdapterTempTable
{
class Program
{
static void Main(string[] args)
{
String ConnectionString = "Provider=ASEOLEDB;Data Source=devsun3:5003;Initial Catalog=ctc;User ID=aigtac12;Password=aigtac12;"; // sybase connection string
//String ConnectionString = "Provider=SQLOLEDB;Data Source=fiji;Persist Security Info=False;Initial Catalog=nxgn0811;Integrated Security=SSPI"; // mssql connection string
String TableName = "#alex_temporary_table_test"; // does not work for sybase
//String TableName = "alex_real_table_test"; // works for sybase + mssql
String CreateStatement = "create table " + TableName + " (currency_id varchar(4) primary key, rate decimal(25,6), format char(1))";
String SelectStatement = "select * from " + TableName;
try
{
OleDbConnection con = null;
con = new OleDbConnection(ConnectionString);
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = CreateStatement;
int count = cmd.ExecuteNonQuery();
OleDbCommand cm1 = con.CreateCommand();
cm1.CommandType = CommandType.Text;
cm1.CommandText = SelectStatement;
OleDbDataAdapter DA2 = new OleDbDataAdapter(cm1);
DataTable DT2 = new DataTable();
DA2.FillSchema(DT2, SchemaType.Mapped);
OleDbCommandBuilder cmdbldr = new OleDbCommandBuilder(DA2);
DA2.InsertCommand = cmdbldr.GetInsertCommand();
DA2.DeleteCommand = cmdbldr.GetDeleteCommand(); // this line fails in sybase for temporary table
DA2.UpdateCommand = cmdbldr.GetUpdateCommand();
DA2.Fill(DT2);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}
In the select statement, instead of * use the column names.
Contacted Sybase support, turns out I had to update some system stored procedures. There is a folder that ends with "oledb\sp", and I had to run a .bat file from the folder. I got the latest ebf and ran the batch file install_oledb_sprocs.bat, the problem went away. Worth mentioning, that sybase 15.5 did not have the issue without patching.
P.S. Thank you to 'aF' for your time looking into the issue.

EntityDataReader to ToList()

my code :
public List<Book> GetBook(string Field, object Value)
{
using (EntityConnection conn = new EntityConnection("name=Entities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select VALUE b FROM Entities.Book as b where Cast(b." + Field + " as Edm.String) like '%" + Value.ToString() + "%'";
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
conn.Close();
var s = from d in rdr.OfType<Book>().AsEnumerable()
select d;
return (s.ToList());
}
}
}
return (null);
}
why The result is always empty???
What is the correct code?
Why are you closing connection before you started to read from the reader? Reader is like cursor - it doesn't buffer all results to memory when you open it but it loads them incrementally so you could easily terminate connection (and reading functionality as well) before you read any result. You don't have to close the connection explicitly - that is responsibility of using block.
You can also use SQL profiler to validate the it really builds the query you expect.
using (EntityConnection conn = new EntityConnection("name=Entities"))
{
conn.Open();
// Create an EntityCommand.
using (EntityCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Select VALUE b FROM Entities.Book as b where Cast(b." + Field + " as Edm.String) like '%" + Value.ToString() + "%'";
// Execute the command.
using (EntityDataReader rdr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
var s = from d in rdr.OfType<Book>().AsEnumerable()
select d;
return (s.ToList());
}
}
}
s.ToList().Count returns 0 because rdr.OfType<Book> is always empty collection. EntitDataReader doesn't materialize entities - it is just wrapper about database related DataReader and it works in the same way. You must read columns and fill them to properties of your entity.
If you don't want to do it you can use objectContext.Translate method but once you start to work with ObjectContext you don't need EntityCommand and EntityDataReader at all.

importing of data from Excel To Access database by c#.net

I am working on a windows application in c#.net where I need to import an excel sheet into an Access database by the use of code in c#. I found the following code on the net and tried to use :
string path = #"D:\project_excel";
OleDbConnection con;
System.Data.DataTable dt = null;
//Connection string for oledb
string conn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + "; Extended Properties=Excel 8.0;";
con = new OleDbConnection(conn);
try
{
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelsheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
excelsheets[i] = dr["TABLE_NAME"].ToString();
i++;
}
// here i manaually give the sheet number in the string array
DataSet ds = new DataSet();
foreach (string temp in excelsheets)
{
// Query to get the data for the excel sheet
//temp is the sheet name
string query = "select * from [" + temp + "]";
OleDbDataAdapter adp = new OleDbDataAdapter(query, con);
adp.Fill(ds, temp);//fill the excel sheet data into a dataset ds
}
}
catch (Exception ex)
{
}
finally
{
con.Close();
}
However it gives an exception which is mentioned below :
The Microsoft Jet database engine cannot open the file 'D:\project_excel'. It is already opened exclusively by another user, or you need permission to view its data.
Further I don't know the meaning of Extended Properties. I am using Microsoft Office 2007 package.If I set Extended Properties = 7.0 it gives following error :
Could not find installable ISAM.
Please help by providing some code sample.
Thanks in advance..
Check to see if the connection string is correct for your Access database version.
For details Visit ConnectionString.com
by
Mohamed Inshafudeen J.
For the error : Could not find installable ISAM.
1: save your excel file as "Excel 97-2003 wrokbook "
2: and also include the reference "Microsoft.Office.Interop.Excel"
best of luck!

Resources