connection string property has not been initialized - c#

I don't know why this code gives me an error.
I am trying to put the sql commands into a transaction.
This code gives me this error.
I can't fill int anything else at the source than this.
This is the error I get
Additional information: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
using (SQLiteConnection cn = new SQLiteConnection(string.Format("Data Source={0};")))
{
cn.Open();
using (SQLiteTransaction tr = cn.BeginTransaction())
{
sqlTarget = sqlInsert1 + columnList + ") VALUES (";
object[] sourceVal = new object[nCol];
rdrSourceTable.GetValues(sourceVal);
string strMsg = string.Empty;
int iCol = 0;
foreach (object col in sourceVal)
{
string columnName = rdrSourceTable.GetName(iCol++);
sqlTarget += objDbTarget.ObjectForSql(col, ref strMsg, false, columnName) +
comma;
}
if (strMsg.Length > 0)
{
msg = string.Format(
"The input values are wrong, strMsg = {0}\r\nThe composed sql = {1}",
strMsg, sqlTarget);
if (m_interactive)
{
DialogResult res = MessageBox.Show(msg, GetType().ToString(),
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (res == DialogResult.Cancel)
{
throw new CopyDbContentsException(msg);
}
}
if (errorCount++ < 5)
{
RadFile.WriteLogMsg("FillTableWithInsertCommands. " + msg +
"\r\n\r\nContinue?");
}
//Skip the insert action because of the error and go to next row.
continue;
}
sqlTarget = sqlTarget.Substring(0, sqlTarget.Length - comma.Length) + ")";
objDbTarget.ExecuteActionQuery(sqlTarget);
iRow++;
int remainder = iRow%250;
if (remainder == 0)
{
WriteStatusLabel(string.Format(
"Copy the rows of table {0}. {1:N0} written.", Name,
iRow));
}
remainder = iRow%nMsgMod;
if (remainder == 0)
{
msg = string.Format("{0:N0} rows of table {1} copied.",
iRow, Name);
RadFile.WriteLogMsg(msg, withHeader: false);
if (nMsgMod < 100000 && iRow == 10*nMsgMod)
{
nMsgMod *= 10;
}
}
tr.Commit();
}
cn.Close();
}
}
msg = string.Format("Table {0} is copied, {1:N0} rows. ", Name, iRow);
if (errorCount > 0)
{
msg += errorCount;
msg += (errorCount == 1) ? " row is" : " rows are";
msg += " skipped because of errors in the input";
}
RadFile.WriteLogMsg(msg, withHeader: false);
}
}

you expect this to work?
SQLiteConnection cn = new SQLiteConnection(string.Format("Data Source={0};"))
here is a good explaination about SQLite ConnectionStrings
https://www.connectionstrings.com/sqlite/
i assume you want to do something like
var cn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", #"c:\mydb.db"))
And the Error
Additional information: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
says that string.Format("Data Source={0};") want's to access the first item at index 0, which is not provided by you

Its at the 1st line:
string.Format("Data Source={0};"
you must provide argument for string format , for example :
string.Format("Data Source={0};","my data source")
where "my data source" will be your database data source name.

Man, you should refactor all this code. But for you problem, this is the solution:
using (SQLiteConnection cn = new SQLiteConnection("put your entire connection string here"))
see this for more information on how to use string.Format method.

Related

Updating members details in the DB from CSV files

I have small exec(old one) that treat adding members to a table in the DB. if the member not exist in the DB, it will insert new member in AllMember table. If the member already exists in the DB, it will update the values that are different. What exists already in the code is not updating all the members as I want. I want to code it efficiently now. For every update, I am taking all of the members from the DB(6000) and if I have excel with 4000 members it will make the comparison 24000000 and will increase with time.
Getting all the members:
public static IEnumerable<AllMember> GetAllMembersList()
{
string connection = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
using (var dataAccess = new DataAccessDataContext(connection))
{
var v = (from row in dataAccess.AllMembers
//where row.PremiumType.HasValue && row.PremiumType.Value == 100
select row);
return v.ToList();
}
//#TODO fun
}
Handle the file of new\update members
internal override void ProcessFile()
{
StringBuilder CheckMembersList = new StringBuilder();
CheckMembersList.Clear();
ErrorFounds = false;
UpdateQuery = new StringBuilder();
if (!System.IO.File.Exists(InputFile))
{
Mail.InsertNewMail("שגיאה בתהליך קליטת פרטי משתמשים ", "הקובץ " + InputFile + " לא נמצא ");
return;
}
CsvReader fileReader = new CsvReader(InputFile, FileEncoding, false, false);
DataTable fileContentTable = fileReader.ReadFile();
FileInfo fileInfo = new FileInfo(InputFile);
UpdateDB(fileContentTable, CheckMembersList);
WriteResponseFile(fileContentTable);
}
Updating the DB:
private void UpdateDB(DataTable inputTable, StringBuilder CheckMembersList)
{
IEnumerable<AllMember> allMembersList = Utilities.GetAllMembersList();
DBUpdateStatus updateStatus = DBUpdateStatus.NO_CHANGE;
bool x;
bool newMember;
int rowIndex=0 ;
for (int i = 1; i < inputTable.Rows.Count; i++)
{
rowIndex = i;
DataRow fileRow = inputTable.Rows[i];
newMember = true;
foreach (AllMember membersRow in allMembersList)
{
if (!(String.IsNullOrEmpty(membersRow.TZ))) /*&& (fileRow[ConstDBRow.TZ].ToString().Trim().PadLeft(9, '0') == membersRow.TZ.ToString().Trim().PadLeft(9, '0')))*/
{
newMember = false;
updateStatus = UpdateMemberDetails(fileRow, membersRow);
break;
}
}
if (newMember == true)
updateStatus = InsertNewMember(fileRow);
var memberId = GetMemberId(fileRow[ConstDBRow.TZ].ToString().Trim().PadLeft(9, '0'));
if (updateStatus != DBUpdateStatus.NO_CHANGE)
QueryBuilder.InsertRequest(memberId, updateStatus);
fileRow["UPDATE_STATUS"] = Utilities.GetStatusString(updateStatus);
//append to CheckMembersList for sending members list through email
CheckMembersList.AppendLine("Row Index: " + Convert.ToString(rowIndex + 1) +", Identification number: " + (fileRow[ConstDBRow.TZ].ToString().Trim().PadLeft(9, '0')) + ", First Name: " + fileRow[ConstDBRow.FIRST_NAME].ToString().Replace("'","''") + ", Last Name: " + fileRow[ConstDBRow.LAST_NAME].ToString().Replace("'","''") + ", Update Status: " + fileRow["UPDATE_STATUS"].ToString().Replace("'", "''") + "<br/>");
}
}
How can I do this effectively? Is EntityFramework a good option or taking the list of All-Members differently?
I would leave it on DB to compare the records and insert/update using Merge SQL statement.
There is Merge in SQL Server, hope it is available on other DB servers too https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-2017
As a note: Are you doing insert/update request for each of your record? Try to perform one DB call

I am trying to add data from word doc to access database but it give me operator missing syntax

I am reading word file and add data after it find Favour. Just wont to add data after favour. First record using this code added perfect record but second time it give Syntax error(operator missing). Please help me to correctly add all records
private void button1_Click(object sender, EventArgs e)
{
try
{
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
object nullobj = System.Reflection.Missing.Value;
object file = openFileDialog1.FileName;
Document doc = app.Documents.Open(#"C:\Users\juilee Raut\Downloads\ITCL-CAES 1 (1).docx");
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
IDataObject da = Clipboard.GetDataObject();
string text = da.GetData(DataFormats.Text).ToString();
richTextBox1.Text = text;
string data = string.Empty;
string[] data1 = richTextBox1.Lines;
List<string> Info = new List<string>();
int i = 0;
int j = 0;
int m = 0;
while (i < data1.Length)
{
if (data1[i].StartsWith("FAVOUR:"))
{
j++;
if (m == 0)
{
data = data + data1[i].ToString() + Environment.NewLine;
string inf = string.Join(Environment.NewLine, Info.ToArray());
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into AllData(FullJud) VALUES('" + inf + "')";
cmd.ExecuteNonQuery();
con.Close();
Info.Clear();
inf = string.Empty;
m = 1;
}
}
else
{
m = 0;
if (data1[i] != "")
{
if (data1[i].EndsWith("2017") && data1[i].Length == 10 || data1[i].EndsWith("2016") && data1[i].Length == 10)
{
data = data + data1[i].ToString() + Environment.NewLine + "##ln##" + Environment.NewLine;
Info.Add(data1[i]);
Info.Add("##ln##");
}
else if(data1[i].StartsWith("SECTION:") || data1[i].StartsWith("Section:") || data1[i].StartsWith("SECTION-") || data1[i].Contains("SUBJECT:") || data1[i].StartsWith("Subject:") || data1[i].StartsWith("SUBJECT-") || data1[i].StartsWith("SUBJECTS:"))
{
data = data + data1[i].ToString() + Environment.NewLine;
}
else if(data1[i].EndsWith("Respondent.") || data1[i].EndsWith("Petitioner.") || data1[i].EndsWith("Appellant.") || data1[i].EndsWith("Appellant") || data1[i].EndsWith("Respondent") || data1[i].EndsWith("Counsel,"))
{
data = data + data1[i].ToString() + Environment.NewLine;
}
else
{
data = data + data1[i].ToString() + Environment.NewLine;
Info.Add(data1[i]);
}
}
}
i++;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is the error I get:
"Syntax error (missing operator) in query expression ''391 ITR 382 (BOM): 88 TAXMANN.COM 556\r\nHIGH COURT OF BOMBAY \r\nM.S. SANKLECHA AND A.K. MENON, JJ.\r\nMalay N. Sanghvi v/s. Income Tax Officer\r\nIT APPEAL NO. 1342 OF 2014\r\n31.01.2017\r\n##ln##\r\nSection 80-IB of the Income-tax Act, 1961 - Deductions - Profits a'."
What if Info contains several values, let's say:
Info = { "value1", "value2" }
Then, inf would be:
inf = "value1\r\nvalue2"
Therefore, cmd.CommandText would be:
cmd.CommandText = "INSERT into AllData(FullJud) VALUES('value1\r\nvalue2')";
and I'm quite sure this is not the wanted behaviour.
Edit
What if one value in Info contained a ' character?
Info = { "val'ue" }
Then, inf would be:
inf = "val'ue"
Therefore, cmd.CommandText would be:
cmd.CommandText = "INSERT into AllData(FullJud) VALUES('val'ue')";
// SQL won't understand that part --------------------------|||
and that's where you get an error.
Moreover, what if Info had the following value instead:
Info = { "value1');DROP TABLE [anytable];--" }
That's typical SQL Injection.
Some questions/comments:
What is j used for?
What is the purpose of inf = string.Empty;? It is a local variable and will be garbage collected.
What is the purpose of data? Will you even use it at some point?
You are using a while loop when you could be using a for(int i=0;i<data1.Length;i++) loop.
What if data1 contains two consecutive strings starting with "FAVOUR:"? Why would you insert only the first one, and not the second one?
else
{
data.Replace("'", "/");
data1[i] = data1[i].Replace("'","/");
Info.Add(data1[i]);
data = data + data1[i].ToString() + Environment.NewLine;
}
In else part I just replace the ' to / and my problem is solve

How do I create a csv file with the output of sql query?

How do I create a CSV file with the output of a SQL (SQLServer) query in C#?
Here is the code I have tried so far:
public static void CreateManifestFile(string SQLFileToExecute, string ConnectionString, StreamWriter logfile) {
int success = 0;
List<string> results = new List<string>();
string script = File.ReadAllText(#SQLFileToExecute);
Logging.WriteToLog(" ", logfile);
Logging.WriteToLog(" ", logfile);
Logging.WriteToLog("=== Processing file: [" + SQLFileToExecute + "] ===", logfile);
// split script on GO command
IEnumerable<string> commandStrings = Regex.Split(script, # "^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
SqlConnection Connection = new SqlConnection(ConnectionString);
Connection.Open();
Connection.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e) {
Logging.WriteToLog("Msg: " + e.Message, logfile);
success = 1;
};
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.Connection = Connection;
foreach(string commandString in commandStrings) {
if (commandString.Trim() != "") {
success = 0;
Console.WriteLine(commandString.ToString());
logfile.WriteLine(commandString.ToString());
results.Add(sqlcmd.ExecuteReader(commandString));
if (success == 0) {
Logging.WriteToLog("Command executed successfully.", logfile);
}
}
}
Connection.Close();
int length = results.Count;
string delimter = ",";
using(System.IO.TextWriter writer = File.CreateText("manifest.csv")) {
Logging.WriteToLog("manifest count:" + length, logfile);
for (int index = 0; index < length; index++) {
writer.WriteLine(string.Join(delimter, results[index]));
}
}
}
But I am getting errors on the line:
results.Add(sqlcmd.ExecuteReader(commandString));
Errors:
Error 1 The best overloaded method match for
'System.Collections.Generic.List.Add(string)' has some invalid
arguments
Error 2 Argument 1: cannot convert from
'System.Data.SqlClient.SqlDataReader' to 'string'
Error 3 The best overloaded method match for
'System.Data.SqlClient.SqlCommand.ExecuteReader(System.Data.CommandBehavior)'
has some invalid arguments
Error 4 Argument 1: cannot convert from 'string' to
'System.Data.CommandBehavior'
I followed this post to do this.
public string ExportToCSVFile(DataTable dtTable)
{
StringBuilder sbldr = new StringBuilder();
if (dtTable.Columns.Count != 0)
{
foreach (DataColumn col in dtTable.Columns)
{
sbldr.Append(col.ColumnName.Replace(",", "") + ',');
}
sbldr.Append("\r\n");
foreach (DataRow row in dtTable.Rows)
{
foreach (DataColumn column in dtTable.Columns)
{
sbldr.Append(row[column].ToString().Replace(",", "").Trim() + ',');
}
sbldr.Append("\r\n");
}
}
return sbldr.ToString();
}
You havent tried anything so here is a little motivation to get you started.
SqlServerStorage storage = new SqlServerStorage(typeof(Order));
string sqlConnectionString ="Server=SqlServer;Database=SqlDataBase;Trusted_onnection=True";
storage.ConnectionString = sqlConnectionString;
storage.SelectSql = "select * from Yourtable";
storage.FillRecordCallback = new FillRecordHandler(FillRecordOrder);
FileDataLink link = new FileDataLink(storage);
link.FileHelperEngine.HeaderText = headerLine;
link.ExtractToFile("file.csv");
This is give you timeout for tables containing large data but hey i am little less lazy than you. So figure it out. Hope it helps good luck.

How to have a message box pop up only once in a loop?

I have this small method that pops up a message box warning , problem is that it pops up 3 message box instead of one!
I've tried several ways to counter this issue (including the bool variables in the code and using Distinct in the sql query , though the database doesn't contain any repeatable rows).
The idea is to have the messagebox pop up once for each row that violates my if condition and not 3 times for each row.
So , why is this message box pops up 3 times instead of once? and how to fix it?
void msds_update()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=(local);database=PhilipsMaterials;Integrated Security=SSPI;";
con.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string sql = "Select * from [PhilipsMaterials].[dbo].[Materials]";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds);
dt = ds.Tables[0];
DateTime longupdate;
DateTime shortupdate;
foreach (DataRow row in dt.Rows)
{
longupdate = Convert.ToDateTime(dt.Rows[0]["Long MSDS Update"]);
shortupdate = Convert.ToDateTime(dt.Rows[0]["Short MSDS Update"]);
TimeSpan longsince = DateTime.Now.Subtract(longupdate);
int longyears = (int)(longsince.Days / 365.25);
TimeSpan shortsince = DateTime.Now.Subtract(shortupdate);
int shortyears = (int)(shortsince.Days / 365.25);
bool flag = false ;
bool shown = false;
if (longyears > 4.5) { flag = true; }
if (flag && !shown)
{
string longmsdsname = Convert.ToString(dt.Rows[0]["Name"]);
string msg = "Long Msds " + longmsdsname + " must be updated";
MessageBox.Show(msg);
shown = true;
}
flag = false;
shown = false;
if (shortyears > 4.5) { flag = true; }
if (flag && !shown)
{
string shortmsdsname = Convert.ToString(dt.Rows[0]["Name"]);
string msg = "Short Msds " + shortmsdsname + " must be updated";
MessageBox.Show(msg);
shown = true;
}
}
con.Close();
}
The values used to perform the if tests and to build the error message always are the values from the row at index zero, you should use the current row indexer used in the foreach loop
Also, do not react immediatly to the error condition, instead build up an error message, wait to end one loop and show the message only if there is an error. No need to use and keep updated two status variables.
StringBuilder sb = new StringBuilder();
int rowCounter = 0;
foreach (DataRow row in dt.Rows)
{
rowCounter++;
longupdate = Convert.ToDateTime(row["Long MSDS Update"]);
shortupdate = Convert.ToDateTime(row["Short MSDS Update"]);
TimeSpan longsince = DateTime.Now.Subtract(longupdate);
int longyears = (int)(longsince.Days / 365.25);
TimeSpan shortsince = DateTime.Now.Subtract(shortupdate);
int shortyears = (int)(shortsince.Days / 365.25);
if (longyears <= 4.5)
{
string longmsdsname = Convert.ToString(row["Name"]);
sb.AppendFormat("Long Msds {0} must be updated\r\n", longmsdsname);
}
if (shortyears <= 4.5)
{
string shortmsdsname = Convert.ToString(row["Name"]);
sb.AppendFormat("Short Msds {0} must be updated\r\n", shortmsdsname);
}
// If we have errors, show them and reset the builder for the next loop
if(sb.Length > 0)
{
string msg = string.Format("Error in row {0}\r\n{1}",
rowCounter.ToString(), sb.ToString());
MessageBox.Show(msg);
sb.Length = 0;
}
}
In this way you have just one message for each wrong row also if there are 2 or more wrong values.
You set the variable shown to false before the if statement, move shown outside of the for-loop.
use "break;" after your messagebox. Your program will come out of the loop.

If row doesn't exist in datareader

The data reader named eventreader can be empty and i'm trying to work out an appropriate statement to detect if the datareader contains rows and if the require record exists.
oledbexecute("SELECT [Unit No] FROM UnitOpenAtEvent WHERE [Event ID]='" + strDate + "'");
eventReader = dbcommand.ExecuteReader();
for (int i = 0; i < checkboxEvent.Items.Count; i++)
{
if (checkboxEvent.GetItemCheckState(i) == CheckState.Checked)
{
if (eventReader["Unit No"] != DBNull.Value)
{
while (eventReader.Read())
{
if (eventReader["Unit No"].ToString() == checkboxEvent.Items[i].ToString())
{
oledbexecute("INSERT INTO UnitOpenAtEvent ([Event ID],[Unit No]) VALUES ('" + strDate + checkboxEvent.Items[i].ToString() + "'");
intReader = dbcommand.ExecuteNonQuery();
}
}
}
else
{
oledbexecute("INSERT INTO UnitOpenAtEvent ([Event ID],[Unit No]) VALUES ('" + strDate + checkboxEvent.Items[i].ToString() + "'");
intReader = dbcommand.ExecuteNonQuery();
}
}
else if (checkboxEvent.GetItemCheckState(i) == CheckState.Unchecked)
{
// this is effectively a copy of above
}
}
You can check if the DataReader has any rows using e.g.
if (eventReader.HasRows)
Update:
Following from comment below re: IDataReader...
You could do something like this (shortened to include the most relevant bits for conciseness)
eventReader = dbcommand.ExecuteReader();
bool hasRow = eventReader.Read();
if (hasRow)
{
for (int i = 0; i < checkboxEvent.Items.Count; i++)
{
...
...
while (hasRow)
{
// Code in here to deal with each row
hasRow = eventReader.Read();
}
}
}
You may be misunderstanding how IDataReader.Read() works.
From that help page:
Return Value
Type: System.Boolean
true if there are more rows; otherwise, false.
and
The default position of the IDataReader is prior to the first record.
Therefore you must call Read to begin accessing any data.
So when you first get a datareader it won't be pointing to any data. If you call .Read() it will return true if there is a row to move to and move to it and if there are no rows it will return false.

Categories

Resources