C# SqlBulkCopy miss a row - c#

I'm using SqlBulkCopy to import data from excel and from another database into 2 different SQL tables.
Everything goes good until I managed that every time a row is missing in the target tables, either the source from the excel or from the other database.
Here is the code snippet for importing data from excel:
public void ImportDataFromExcel(string excelFilePath)
{
string ssqltable = "szip_IncomingAssetData";
string myexceldataquery = "SELECT * FROM ["+ GetExcelSheetNames(excelFilePath)+"]";
try
{
string sexcelconnectionstring = GetExcelConnectionString(excelFilePath);
Logger.Log("Excel Connection String: " + sexcelconnectionstring, false);
OpenDatabaseConnection(1, "ImportDataFromExcel");
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(hpamConnection)
{
DestinationTableName = ssqltable
};
SqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping(System.Configuration.ConfigurationManager.AppSettings["szip_AssetID"], "szip_IncomingAssetID");
SqlBulkCopyColumnMapping mapName = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetName"], "szip_IncomingAssetName");
SqlBulkCopyColumnMapping mapSerial = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetSerial"], "szip_IncomingAssetSerial");
SqlBulkCopyColumnMapping mapRI = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetRI"], "szip_IncomingAssetRI");
SqlBulkCopyColumnMapping mapModel = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetModel"],"szip_IncomingAssetModel");
SqlBulkCopyColumnMapping mapVendor = new SqlBulkCopyColumnMapping(System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetVendor"],"szip_IncomingAssetVendor");
SqlBulkCopyColumnMapping mapFRU = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetFirstRU"], "szip_IncomingAssetFirstRU");
SqlBulkCopyColumnMapping mapLRU = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetLastRU"], "szip_IncomingAssetLastRU");
SqlBulkCopyColumnMapping mapLocation = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetLocation"], "szip_IncomingAssetLocation");
SqlBulkCopyColumnMapping mapRack = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetRack"], "szip_IncomingAssetRack");
SqlBulkCopyColumnMapping mapStatus = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetStatus"], "szip_IncomingAssetStatus");
SqlBulkCopyColumnMapping mapConfig = new SqlBulkCopyColumnMapping(System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetConfig"], "szip_IncomingAssetConfig");
SqlBulkCopyColumnMapping mapIPDNS = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetIP_DNSname"], "szip_IncomingAssetIP_DNSname");
SqlBulkCopyColumnMapping mapArea = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetArea"], "szip_IncomingAssetArea");
SqlBulkCopyColumnMapping mapContact = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetContact"], "szip_IncomingAssetContact");
SqlBulkCopyColumnMapping mapExtension = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetExtension"], "szip_IncomingAssetExtension");
SqlBulkCopyColumnMapping mapHWType = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetHardwareType"], "szip_IncomingAssetHardwareType");
SqlBulkCopyColumnMapping mapConnections = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetCurrentConnections"], "szip_IncomingAssetCurrentConnections");
SqlBulkCopyColumnMapping mapMaxConnections = new SqlBulkCopyColumnMapping( System.Configuration.ConfigurationManager.AppSettings["szip_IncomingAssetMaxConnections"], "szip_IncomingAssetMaxConnections");
bulkcopy.ColumnMappings.Add(mapID);
bulkcopy.ColumnMappings.Add(mapName);
bulkcopy.ColumnMappings.Add(mapSerial);
bulkcopy.ColumnMappings.Add(mapRI);
bulkcopy.ColumnMappings.Add(mapModel);
bulkcopy.ColumnMappings.Add(mapVendor);
bulkcopy.ColumnMappings.Add(mapFRU);
bulkcopy.ColumnMappings.Add(mapLRU);
bulkcopy.ColumnMappings.Add(mapLocation);
bulkcopy.ColumnMappings.Add(mapRack);
bulkcopy.ColumnMappings.Add(mapStatus);
bulkcopy.ColumnMappings.Add(mapConfig);
bulkcopy.ColumnMappings.Add(mapIPDNS);
bulkcopy.ColumnMappings.Add(mapArea);
bulkcopy.ColumnMappings.Add(mapContact);
bulkcopy.ColumnMappings.Add(mapExtension);
bulkcopy.ColumnMappings.Add(mapHWType);
bulkcopy.ColumnMappings.Add(mapConnections);
bulkcopy.ColumnMappings.Add(mapMaxConnections);
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
dr.Close();
oledbconn.Close();
CloseDatabaseConnection(1, "ImportDataFromExcel");
Logger.Log("Data Imported from Excel to Database", false);
}
catch (Exception e)
{
Logger.Log("Cannot Read Excel File: " + e.Message.ToString(), true);
}
connection string is as follows:
private string GetExcelConnectionString(string excelfile)
{
Dictionary<string, string> props = new Dictionary<string, string>
{
["Provider"] = "Microsoft.ACE.OLEDB.12.0",
["Extended Properties"] = "'Excel 12.0 XML;HDR=YES'",
["Data Source"] = excelfile
};
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> prop in props)
{
sb.Append(prop.Key);
sb.Append('=');
sb.Append(prop.Value);
sb.Append(';');
}
return sb.ToString();
}
In the case of the import from other database into my application database:
public void ImportSmartZoneAssetData()
{
SqlConnection hpamConnection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["hpamConnectionString"]);
SqlConnection smartZoneConnection = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["szConnectionString"]);
string sqlCommand = "select i.pa_deviceid as DeviceID, " +
"i.pa_displayname as DeviceName, " +
"j.PA_MATERIALIZEDSTRPATH as [Location], " +
"k.PA_CONTAINERTYPEID as ContainerTypeID, " +
"l.PA_CONTAINERTYPEDESCRIPTION as ContainerType, " +
"k.PA_DISPLAYNAME as ContainerName, " +
"i.PA_CONTAINERPOSITION as FirstRU, " +
"(select pa_assetvalue from PA_ASSETLIST where PA_PARENTID = i.PA_DEVICEID and PA_ASSETATTRIBUTEID = 24) as SerialNumber, " +
"(select pa_assetvalue from PA_ASSETLIST where PA_PARENTID = i.PA_DEVICEID and PA_ASSETATTRIBUTEID = 25) as BarCode " +
"from pa_device i " +
"left join PA_LOCATION j on i.pa_locationid = j.PA_LOCATIONID " +
"left join PA_CONTAINER k on i.PA_CONTAINERID = k.PA_CONTAINERID " +
"left join PA_CONTAINERTYPE l on k.PA_CONTAINERTYPEID = l.PA_CONTAINERTYPEID";
string ssqltable = "szip_SmartZoneAssetData";
SqlBulkCopy bulkcopy = new SqlBulkCopy(hpamConnection)
{
DestinationTableName = ssqltable
};
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(sqlCommand, smartZoneConnection);
hpamConnection.Open();
smartZoneConnection.Open();
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
bulkcopy.WriteToServer(myReader);
}
Logger.Log("Imported Records from SmartZone: " + GetRowsCopied(bulkcopy), false);
myReader.Close();
hpamConnection.Close();
smartZoneConnection.Close();
Logger.Log("Data Imported from SmartZone to Database", false);
}
}
I want to know if there is something wrong in the code and the reason why I always loose one and only one record in both cases.
/**************************
Got rid of the "while (myReader.Read())" on both cases and now it works perfect. New code is:
myReader = myCommand.ExecuteReader();
try
{
bulkcopy.WriteToServer(myReader);
}
catch (Exception e)
{
Logger.Log("Cannot Import SmartZone Device Data: " + e.Message, true);
}
Thanks :-)

As suggested, the while (myReader.Read()) was advancing one register.
I got rid of the "while (myReader.Read())" on both cases and now it works perfect. New code is:
myReader = myCommand.ExecuteReader();
try
{
bulkcopy.WriteToServer(myReader);
}
catch (Exception e)
{
Logger.Log("Cannot Import SmartZone Device Data: " + e.Message, true);
}
Thanks :-)

Related

need a quicker way to select data and paste it in an excel sheet

It took me a while to just find a way to select data from my database and then paste it in an excel spreadsheet. Now that I've found it, it runs dirt slow. Like I said before, I've looked at a lot of different ways to accomplish this but have not been able to correctly implement any of them except for this. I'm not married to this option but it is the only one I could get to work. Could someone help me out by suggesting a quicker way to accomplish this simple task? Please see my code below.
Record850 rec850 = new Record850();
List<Record850> lst850records = new List<Record850>();
//SqlConnection connStr = new SqlConnection("Server = 172.18.211.76; Database = Processstage; User Id = brendon.davies; Password = mypassword;");
SqlConnection conn = new SqlConnection("Server = 172.18.211.76; Database = Processstage; User Id = brendon.davies; Password = mypassword;");
//SqlConnection sqlConnection1 = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = Select_850;
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
conn.Open();
Record850 reco850 = new Record850();
string strComplete = "";
reader = cmd.ExecuteReader();
while (reader.Read())
{
try
{
reco850.OrgName = reader.GetString(0);
reco850.WholeSalerAccountDivisionCode = reader.GetString(1);
reco850.File_Process_Name = reader.GetString(2);
reco850.Pur_Ord_Num_BEG03 = reader.GetString(3);
reco850.File_Process_ID = reader.GetInt64(4);
reco850.CECode = reader.GetString(5);
reco850.CEName = reader.GetString(6);
reco850.Modified_Date = reader.GetDateTime(7);
lst850records.Add(reco850);
reco850 = new Record850();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
conn.Close();
eWorkSheet = (Excel.Worksheet)oSheets.get_Item("850_Template");
eWorkSheet.Activate();
int int850counter = 0;
int int850RowCounter = 3;
foreach (Record850 r850 in lst850records)
{
strComplete = lst850records[int850counter].OrgName + "\t" +
lst850records[int850counter].WholeSalerAccountDivisionCode + "\t" +
lst850records[int850counter].File_Process_Name + "\t" +
lst850records[int850counter].Pur_Ord_Num_BEG03 + "\t" +
lst850records[int850counter].File_Process_ID + "\t" +
lst850records[int850counter].CECode + "\t" +
lst850records[int850counter].CEName+ "\t" +
lst850records[int850counter].Modified_Date;
CR = (Excel.Range)eWorkSheet.Cells[int850RowCounter,3];
Clipboard.SetText(strComplete);
CR.Select();
eWorkSheet.Paste(CR, false);
Clipboard.Clear();
int850RowCounter++;
int850counter++;
strComplete = ""
}
Here's an answer that also runs quickly, just about the same as the use of EPPlus above. Do not attempt the cell by cell approach (commented out below) as that indeed runs at a snail's pace by comparison.
[STAThread]
static void Main(string[] args)
{
Excel.Application xl = null;
try {
xl = new Excel.Application();
xl.ScreenUpdating = false;
xl.Visible = false;
xl.UserControl = false;
var wb = xl.Workbooks.Open(SOURCE_PATH);
var ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets.Item["850_Template"];
StringBuilder sb = new StringBuilder();
//int row = 3;
// var a1 = ws.Range["A1", Missing.Value];
using (SqlConnection cn = new SqlConnection(CN_STR)) {
cn.Open();
using (SqlCommand cmd = new SqlCommand(SQL, cn)) {
cmd.CommandType = CommandType.Text;
using (SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
sb.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\r\n",
(string)dr["OrgName"],
(string)dr["WholeSalerAccountDivisionCode"],
(string)dr["File_Process_Name"],
(string)dr["Pur_Ord_Num_BEG03"],
(long)dr["File_Process_ID"],
(string)dr["CECode"],
(string)dr["CEName"],
(DateTime)dr["Modified_Date"]
);
//a1.Offset[row, 0].Value = (string)dr["OrgName"];
//a1.Offset[row, 1].Value = (string)dr["WholeSalerAccountDivisionCode"];
//a1.Offset[row, 2].Value = (string)dr["File_Process_Name"];
//a1.Offset[row, 3].Value = (string)dr["Pur_Ord_Num_BEG03"];
//a1.Offset[row, 4].Value = (long)dr["File_Process_ID"];
//a1.Offset[row, 5].Value = (string)dr["CECode"];
//a1.Offset[row, 6].Value = (string)dr["CEName"];
//a1.Offset[row, 7].Value = (DateTime)dr["Modified_Date"];
//row++;
}
}
}
cn.Close();
}
Clipboard.SetText(sb.ToString(),
TextDataFormat.Text);
var rng = ws.Range["A3", Missing.Value];
rng.Select();
ws.Paste(rng, Missing.Value);
Clipboard.Clear();
wb.Save();
wb.Close();
xl.Quit();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
if (xl != null) {
xl.ScreenUpdating = true;
xl.Visible = true;
xl.UserControl = true;
}
}
}
Here's an alternative that uses the EPPlus approach, much faster.
try {
var app = new ExcelPackage(new FileInfo(SOURCE_PATH));
var ws = app.Workbook.Worksheets["850_Template"];
int row = 3;
using (SqlConnection cn = new SqlConnection(CN_STR)) {
cn.Open();
using (SqlCommand cmd = new SqlCommand(SQL, cn)) {
cmd.CommandType = CommandType.Text;
using (SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
ws.SetValue(row, 1, (string) dr["OrgName"]);
ws.SetValue(row, 2, (string) dr["WholeSalerAccountDivisionCode"]);
ws.SetValue(row, 3, (string) dr["File_Process_Name"]);
ws.SetValue(row, 4, (string) dr["Pur_Ord_Num_BEG03"]);
ws.SetValue(row, 5, (long) dr["File_Process_ID"]);
ws.SetValue(row, 6, (string) dr["CECode"]);
ws.SetValue(row, 7, (string) dr["CEName"]);
ws.SetValue(row, 8, (DateTime) dr["Modified_Date"]);
row++;
}
}
}
cn.Close();
}
app.Save();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}

sap crystalreport c# add-on logonfailed

i'm too getting too stuck trying to solve this issue i try to print directly value from my sap add-on using c# in visualstudio 2010 it's return for me this error:
'logonfailed' here is my code :
try
{
DataTable matable = new DataTable();
DataSet madataset = new DataSet();
SqlConnection maconnexion = new SqlConnection();
maconnexion.ConnectionString = Menu.connectionString_formatsql;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select oitm.ItemCode ,OITM .ItemName ,OITM .CodeBars,ITM1.Price,#codebars " +
" from OITM,ITM1 where OITM .ItemCode=ITM1 .ItemCode" +
" and OITM.ItemCode =#itemCode" +
" and ITM1 .PriceList = #pricelist ";
cmd.Parameters.Clear();
//cmd.Parameters.Add("#codebars", SqlDbType.VarChar );
//cmd.Parameters["#codebars"].Value = get_codebarre_dessin();
//cmd.Parameters.Add("#itemCode", SqlDbType.VarChar);
//cmd.Parameters["#itemCode"].Value = this.EditText1.Value;
//cmd.Parameters.Add("#pricelist", SqlDbType.SmallInt);
//cmd.Parameters["#pricelist"].Value = Convert.ToInt32(this.ComboBox0.Value);
cmd.Parameters.Add("#codebars", SqlDbType.VarChar);
cmd.Parameters["#codebars"].Value = get_codebarre_dessin();
cmd.Parameters.Add("#itemCode", SqlDbType.VarChar);
cmd.Parameters["#itemCode"].Value = this.EditText1.Value;
cmd.Parameters.Add("#pricelist", SqlDbType.Int);
cmd.Parameters["#pricelist"].Value = Convert.ToInt32(this.ComboBox0.Value);
cmd.Connection = maconnexion;
if (maconnexion.State == ConnectionState.Closed)
{
maconnexion.Open();
}
SqlDataAdapter madataadapter = new SqlDataAdapter(cmd);
// SqlCommandBuilder madatabuilder = new SqlCommandBuilder(madataadapter );
matable.Load(cmd.ExecuteReader());
madataset.Tables.Add(matable);
ReportDocument report = new ReportDocument();
report.Load("BARCODE.rpt");
report.Refresh();
report.DataSourceConnections.Clear();
foreach (CrystalDecisions.CrystalReports.Engine.Table table in report.Database.Tables)
{
TableLogOnInfo tableLogOnInfo = table.LogOnInfo;
MessageBox.Show( tableLogOnInfo.ConnectionInfo.ServerName );
MessageBox.Show( tableLogOnInfo.ConnectionInfo.DatabaseName);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.UserID);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.Password.ToString());
MessageBox.Show(tableLogOnInfo.ConnectionInfo.IntegratedSecurity.ToString() );
//table.ApplyLogOnInfo(tableLogOnInfo);
//table.Location = Menu.company.CompanyDB + ".dbo." + table.Name.ToString();
}
foreach (CrystalDecisions.CrystalReports.Engine.Table table in report.Database.Tables)
{
TableLogOnInfo tableLogOnInfo = table.LogOnInfo;
tableLogOnInfo.ConnectionInfo.AllowCustomConnection = true;
tableLogOnInfo.ConnectionInfo.ServerName = Menu.company.Server;
tableLogOnInfo.ConnectionInfo.DatabaseName = Menu.company.CompanyDB;
//tableLogOnInfo.ConnectionInfo.UserID = Menu.company.UserName;
//tableLogOnInfo.ConnectionInfo.Password = Menu.company.Password;
tableLogOnInfo.ConnectionInfo.UserID = Menu .company.DbUserName;
tableLogOnInfo.ConnectionInfo.Password = Menu.company.DbPassword;
tableLogOnInfo.ConnectionInfo.IntegratedSecurity = false ;
table.ApplyLogOnInfo(tableLogOnInfo);
table.Location = Menu.company.CompanyDB + ".dbo." + table.Name.ToString();
}
foreach (CrystalDecisions.CrystalReports.Engine.Table table in report.Database.Tables)
{
TableLogOnInfo tableLogOnInfo = table.LogOnInfo;
MessageBox.Show(tableLogOnInfo.ConnectionInfo.ServerName);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.DatabaseName);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.UserID);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.Password.ToString());
MessageBox.Show(tableLogOnInfo.ConnectionInfo.IntegratedSecurity.ToString());
//table.ApplyLogOnInfo(tableLogOnInfo);
//table.Location = Menu.company.CompanyDB + ".dbo." + table.Name.ToString();
}
report.SetDataSource(matable);
report.SetDatabaseLogon(Menu.company.DbUserName, Menu.company.DbPassword);
PrinterSettings settings = new PrinterSettings();
PrintDialog pdialog = new PrintDialog();
pdialog.PrinterSettings = settings;
pdialog.AllowPrintToFile = true;
pdialog.AllowSomePages = true;
pdialog.UseEXDialog = true;
// ParameterFields parameterFields = report.ParameterFields;
//report.SetParameterValue(0, this.ComboBox0.Value);
//report.SetParameterValue(1, EditText1.Value.ToString());
//report.SetParameterValue(2, get_codebarre_dessin());
report.SetParameterValue(2, this.ComboBox0.Value);
report.SetParameterValue(1, EditText1.Value.ToString());
report.SetParameterValue(0, get_codebarre_dessin());
report.PrintOptions.PrinterName = ComboBox1.Value;
//report.PrintToPrinter(settings, new PageSettings() { }, false);
report.PrintToPrinter(1, true, 1, System.Convert.ToInt32(EditText0.Value));
maconnexion.Close();
}
catch (LogOnException engEx)
{
MessageBox.Show("Incorrect Logon Parameters. Check your user name and password." + engEx.ErrorID);
}
catch (DataSourceException engEx)
{
MessageBox.Show("An error has occurred while connecting to the database.");
}
catch (EngineException engEx)
{
MessageBox.Show(engEx.Message);
}

how to delete first field and all values of this field in .CSV file using C#

I want to load .csv file and then import to SQl database. But before I do that, I want to do something to delete first field (in header) and also all values of this field.
this below is the example of my .csv file :
> TableId|PERIODE|DATEBALANCEASOF|ACCCODE|CUSTNAME|CUSTGROUP|
> TB_001|201501|2015-01-01|11-0001|DYNAMIC EXPRESS|11|
> TB_001|201501|2015-01-01|11-0002|DYNAMIC EXPRESS|12|
> TB_001|201501|2015-01-01|11-0003|DYNAMIC EXPRESS|13|
> TB_001|201501|2015-01-01|11-0004|DYNAMIC EXPRESS|14|
before I import that .csv file, I need my .csv file willbe like this below :
PERIODE|DATEBALANCEASOF|ACCCODE|CUSTNAME|CUSTGROUP|
201501|2015-01-01|11-0001|DYNAMIC EXPRESS|11|
201501|2015-01-01|11-0002|DYNAMIC EXPRESS|12|
201501|2015-01-01|11-0003|DYNAMIC EXPRESS|13|
201501|2015-01-01|11-0004|DYNAMIC EXPRESS|14|
this below is my code :
public void readCSVManual(string pathLocalSuccess, string pathHistory, string modul)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"server=" + serverDB + "; database=" + DB + "; Trusted_Connection=" + trustedConnection + "; user=" + UserDB + "; password=" + PassDB + "";
string[] files = Directory.GetFiles(pathLocalSuccess);
if (files == null)
{
MessageBox.Show("Files not found");
}
foreach (string file in files)
{
FileInfo fileInf = new FileInfo(file);
string filename = fileInf.Name;
StreamReader reader = new StreamReader(file);
string line = reader.ReadLine();
string[] value = line.Split('|');
var list = new List<string>(value);
list.RemoveAt(0);
value = list.ToArray();
//string[] v = string(nValue.ToArray());
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!reader.EndOfStream)
{
value = reader.ReadLine().Split('|');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "ACC_004";
bc.BatchSize = dt.Rows.Count;
bc.WriteToServer(dt);
bc.Close();
con.Close();
reader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Please help me to resolve this problem..
Thanks for everyone who respons my question,
Actually I already solve this problem using a little editing in my code
this below is my code and works for me :
public void readCSVAutomatic(string pathLocalSuccess, string pathHistory, string pathLogFolderSuccess, string pathErrorLog, string modul)
{
try
{
string[] files = Directory.GetFiles(pathLocalSuccess);
foreach (string file in files)
{
FileInfo fileInf = new FileInfo(file);
string filename = fileInf.Name;
StreamReader reader = new StreamReader(file);
string line = reader.ReadLine();
string[] value = line.Split('|');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!reader.EndOfStream)
{
//value = value.
value = reader.ReadLine().Split('|');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
string xTableName = dt.Rows[0].ItemArray[0].ToString();
string xPeriode = dt.Rows[0].ItemArray[1].ToString();
dt.Columns.RemoveAt(0);
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=" + serverDB + "; Initial Catalog=" + DB + "; Trusted_Connection=" + trustedConnection + "; user=" + UserDB + "; password=" + PassDB + "";
con.Open();
SqlCommand com = con.CreateCommand();
string strDelete = "DELETE FROM " + xTableName + " WHERE PERIODE='" + xPeriode + "'";
com.CommandText = strDelete;
com.Connection = con;
com.ExecuteNonQuery();
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = xTableName;
bc.BatchSize = dt.Rows.Count;
bc.WriteToServer(dt);
bc.Close();
con.Close();
reader.Close();
moveFileAfterImported(pathLocalSuccess, filename, pathHistory);
createLogCSVSuccessImported(pathLogFolderSuccess, "File Imported","Message");
}
}
catch(Exception ex)
{
createErrorLogImportCSV(pathErrorLog, "ErrorImportCSV", ex.ToString());
}
}
This seems to do the job for me:
First start by reading in all the files:
var datatables =
Directory
.GetFiles(pathLocalSuccess)
.Select(file => File.ReadAllLines(file).Select(x => x.Split('|')).ToArray())
.Select(lines => new
{
headers = lines[0].Skip(1).ToArray(),
lines = lines.Skip(1).Select(l => l.Skip(1).ToArray()).ToArray(),
})
.Select(x =>
{
var dt = new DataTable();
foreach (var dc in x.headers)
{
dt.Columns.Add(new DataColumn(dc));
}
foreach (var line in x.lines.Skip(1).Where(y => y.Length == x.headers.Length))
{
var row = dt.NewRow();
row.ItemArray = line;
dt.Rows.Add(row);
}
return dt;
})
.ToArray();
Then it's a simple matter of loading all the data. This code only opens the connection once. It should be quite fast.
if (!datatables.Any())
{
MessageBox.Show("Files not found");
}
else
{
using (var con = new SqlConnection())
{
con.ConnectionString = #"server=" + serverDB + "; database=" + DB + "; Trusted_Connection=" + trustedConnection + "; user=" + UserDB + "; password=" + PassDB + "";
foreach (var dt in datatables)
{
var bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "ACC_004";
bc.BatchSize = dt.Rows.Count;
bc.WriteToServer(dt);
bc.Close();
}
con.Close();
}
}
The important part for skipping the first field is found in this code:
.Select(lines => new
{
headers = lines[0].Skip(1).ToArray(),
lines = lines.Skip(1).Select(l => l.Skip(1).ToArray()).ToArray(),
})

c# multiple chart error

I want to create a column chart in c#.
this is the code that i uset for that:
private void Vizualizare_profil()
{
myConn = new MySqlConnection(myConnection);
MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM `gomoku`.`informatii` WHERE `id_utilizator` = '" + id_client.ToString() + "';", myConn);
MySqlDataAdapter dataAdap = new MySqlDataAdapter(selectCommand);
DataSet ds = new DataSet();
myConn.Open();
dataAdap.Fill(ds);
myConn.Close();
DataTable dt = new DataTable();
dt.Columns.Add("Nume");
dt.Columns.Add("Meciuri castigate");
dt.Columns.Add("Meciuri pierdute");
dt.Columns.Add("Meciuri remize");
if (ds.Tables[0].Rows.Count != 0)
{
label28.Text = Username;
label29.Text = ds.Tables[0].Rows[0]["nume"].ToString();
label30.Text = ds.Tables[0].Rows[0]["prenume"].ToString();
label31.Text = ds.Tables[0].Rows[0]["varsta"].ToString();
label32.Text = ds.Tables[0].Rows[0]["adresa_email"].ToString();
dt.Rows.Clear();
dt.Rows.Add("Meciuri castigate " + Convert.ToString(ds.Tables[0].Rows[0]["meciuri_castigate"]), ds.Tables[0].Rows[0]["meciuri_castigate"], 0 , 0);
dt.Rows.Add("Meciuri pierdute " + Convert.ToString(ds.Tables[0].Rows[0]["meciuri_pierdute"]), 0, ds.Tables[0].Rows[0]["meciuri_pierdute"], 0);
dt.Rows.Add("Meciuri remize " + Convert.ToString(ds.Tables[0].Rows[0]["meciuri_remiza"]), 0, 0,ds.Tables[0].Rows[0]["meciuri_remiza"]);
chart1.DataSource = dt;
chart1.Series[0].XValueMember = "Nume";
chart1.Series[0].YValueMembers = "Meciuri castigate";
chart1.Series[1].XValueMember = "Nume";
chart1.Series[1].YValueMembers = "Meciuri pierdute";
chart1.Series[2].XValueMember = "Nume";
chart1.Series[2].YValueMembers = "Meciuri remize";
}
else
MessageBox.Show("Database error!");
}
It creates perfect the first chart but if this method is called again it shows the same data.
What is the problem and what can by done?

Loss of Data after printing my crystal report via PrintToPrinter

after printing the document using PrintToPrinter all data is lost, dont know why ????
this code had one more problem, I hve rectified the problem by adding :
rpt.SetDatabaseLogon("u","p");
and now I have empty document printed.
this is my code:
protected void btnPrintToPrinter_Click(object sender, EventArgs e)
{
int empno = Convert.ToInt32(Session["AnyVal"]);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string strQuery = "SELECT [View_EmplDetail].[Uni-Code], [View_EmplDetail].[FacultyCode], [View_EmplDetail].[EmpIDstr], [View_EmplDetail].[EngGivenName], [View_EmplDetail].[position_eng], [View_EmplDetail].[Emp_no], [View_EmplDetail].[GivenName], [View_EmplDetail].[position_name], [View_EmplDetail].[DariName], [Tbl_Dept].[EName], [View_EmplDetail].[photo] FROM [MoHEDatabase].[dbo].[View_EmplDetail] [View_EmplDetail] INNER JOIN [MoHEDatabase].[dbo].[Tbl_Dept] [Tbl_Dept] ON [View_EmplDetail].[DepCode]=[Tbl_Dept].[DepCode] WHERE [Emp_no] = #empno";
SqlCommand command = new SqlCommand(strQuery, connection);
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#empno", empno);
command.Connection = connection;
command.Connection.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
ReportDocument rpt = new ReportDocument();
string _reportPath = Server.MapPath("..\\Student\\cardFinal.rpt");
//rpt.Load(AppDomain.CurrentDomain.BaseDirectory + "\\" + #"\\Student\\CardFinal.rpt");
rpt.Load(_reportPath);
rpt.SetDataSource(dt);
emp_card_report_viewer.ReportSource = rpt;
string sq = "";
//{View_OrgStr1.Uni-Code}=0 and {View_OrgStr1.FacultyCode}=119
//sq = "{View_StudentAddNew.Student_ID}=" + Session["AnyVal"];
if (Session["AnyVal"].ToString() != "")
{
sq = "{View_EmplDetail.Emp_no}=" + int.Parse(Session["AnyVal"].ToString());
}
//emp_card_report.Report.FileName = "../Student/CardFinal.rpt";
emp_card_report_viewer.SelectionFormula = sq;
//ConnectionInfo connInfo = new ConnectionInfo();
//connInfo.ServerName = "172.16.0.15";
//connInfo.DatabaseName = "MoHEMISDatabase";
//connInfo.UserID = "hemis_admin";
//connInfo.Password = "hemis#sabir";
//TableLogOnInfos crtt = new TableLogOnInfos();
//TableLogOnInfo crtto = new TableLogOnInfo();
//Tables crtables;
//crtables = rpt.Database.Tables;
//foreach (CrystalDecisions.CrystalReports.Engine.Table crtable in crtables)
//{
// crtto = crtable.LogOnInfo;
// crtto.ConnectionInfo = connInfo;
// //crtable.ApplyLogInInfo(crtto);
//}
ConnectionInfo connInfo1 = new ConnectionInfo();
// connInfo1.ServerName = "server";
setDBLOGONforReport(connInfo1);
//emp_card_report_viewer.RefreshReport();
//ConnectionInfo connInfo = new ConnectionInfo();
//connInfo.ServerName = "server";
//connInfo.DatabaseName = "MoHEDatabase";
//connInfo.UserID = "hemis_admin";
//connInfo.Password = "hemis#sabir";
//setDBLOGONforReport(connInfo);
CrystalDecisions.Shared.PageMargins pageMargins = new
CrystalDecisions.Shared.PageMargins(0, 0, 0, 0);
rpt.PrintOptions.ApplyPageMargins(pageMargins);
rpt.PrintOptions.PrinterName = printerList.SelectedItem.Value;
emp_card_report_viewer.RefreshReport();
rpt.PrintToPrinter(1, false, 1, 1);
rpt.Close();
rpt = null;
}
THE ANSWER:
I was using Select Expert Record in the crystal report , I removed all formula in Select Expert and it worked .... :)

Categories

Resources