Query does not return all data from database - sql-server

I have a C# 4.0 WinForms App using SQL Server 2012 database.
On one of my forms, I select a range of dates from a MonthCalendar.
In a query using a SqlDataAdapter, the query should return 4-names of people from a table.
After filling the DataTable, the "for" loop successfully pulls the first name.
On the next iteration, it also pulls the 2nd person's name from the table.
However, on the 3rd iteration, it again pulls the 2nd person's name and does not retrieve the remaining 2-names.
Using SSMS, I can see all 4-names of the people I'm querying. If I use the query below in SSMS, I again get all 4-names.
Does anyone have an idea why the code below fails to return all 4-names, but returns a previous name?
Here is the code I'm using to query the SQL Server database.
private string ReturnPerson(string dStart, string dEnd)
{
string myPerson = "";
try
{
using (SqlConnection conn = new SqlConnection(#"..."))
{
conn.Open();
using (SqlDataAdapter adap = new SqlDataAdapter("SELECT person, scheduledDate FROM Assignments WHERE scheduledDate BETWEEN #start AND #end ORDER BY scheduledDate ASC", conn))
{
adap.SelectCommand.Parameters.Add("#start", SqlDbType.NVarChar).Value = dStart;
adap.SelectCommand.Parameters.Add("#end", SqlDbType.NVarChar).Value = dEnd;
using (DataTable dt = new DataTable())
{
adap.Fill(dt);
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
DataRow row = dt.Rows[i];
DataRow nextRow = dt.Rows[i + 1];
if (personRowCounter == 0)//rowCounter declared globaly
{
myPerson = row.Field<string>("person").ToString();
personRowCounter++;
return myPerson;
}
else if (personRowCounter > 0)
{
myPerson = nextRow.Field<string>("person").ToString();
personRowCounter++;
return myPerson;
}
}
}
}
}
}
catch (SqlException ex) { MessageBox.Show(ex.Message); }
catch (System.Exception ex) { MessageBox.Show(ex.Message); }
return myPerson;
}

If you start with personRowCounter =0
Then the first call will return row 0 as personRowCounter = 0 and i = 0 and it will set personRowCounter = 1
Then the next call will return row 1 as personRowCounter > 0 and i= 0 and it will set personRowCounter = 1
And all calls after that will return row 1 as personRowCounter > 0 and the loop always starts from 0

I'm not sure what you're intent is here. But, I believe that the problem lies with
DataRow nextRow = dt.Rows[i + 1];
That will throw an exception when i is pointing to the last row. Because [i + 1] will index beyond the end of dt.rows.

Based on the comments above, I've figured out the solution. I needed to adjust the DataRow rows, as per below. This allowed me to pull in the remaining data.
private string ReturnPerson(string dStart, string dEnd)
{
string myPerson = "";
try
{
using (SqlConnection conn = new SqlConnection(#"..."))
conn.Open();
using (SqlDataAdapter adap = new SqlDataAdapter("SELECT person, scheduledDate FROM Assignments WHERE scheduledDate BETWEEN #start AND #end ORDER BY scheduledDate ASC", conn))
{
adap.SelectCommand.Parameters.Add("#start", SqlDbType.NVarChar).Value = dStart;
adap.SelectCommand.Parameters.Add("#end", SqlDbType.NVarChar).Value = dEnd;
using (DataTable dt = new DataTable())
{
adap.Fill(dt);
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
DataRow row0 = dt.Rows[i];
DataRow row1 = dt.Rows[i + 1];
DataRow row2 = dt.Rows[i + 2];
DataRow row3 = dt.Rows[i + 3];
if (dt.Rows.Count > 4)
{
DataRow row4 = dt.Rows[4];
}
if (personRowCounter == 0)//rowCounter declared globaly
{
myPerson = row0.Field<string>("person").ToString();
personRowCounter++;
return myPerson;
}
else if (personRowCounter == 1)
{
myPerson = row1.Field<string>("person").ToString();
personRowCounter++;
return myPerson;
}
else if (personRowCounter == 2)
{
myPerson = row2.Field<string>("person").ToString();
personRowCounter++;
return myPerson;
"etc.";
}
}
}
}
}
catch (SqlException ex) { MessageBox.Show(ex.Message); }
catch (System.Exception ex) { MessageBox.Show(ex.Message); }
return myPerson;
}

Related

Syntax error at or near ( error - error code 42601

I am migrating a c# application from sql server express edition to postgresql using npgsql 4.1.3.1. However I am getting the syntax error 42601 whenever i try to add row a databound datagridview programmatically. I had a look at the update command generated by npgsqlcommandbuilder and it includes an extra parenthesis at the end. ("pfuppersalarylimit" = #p133)) of the command. Any help shall be highly appreciated.
`NpgsqlConnection con;`
NpgsqlCommand sqlcmd;
NpgsqlCommandBuilder builder;
DataSet ds;
BindingSource bs = new BindingSource();
public frmEmployee()
{
string str = Properties.Settings.Default.connectionstring; //.Settings.connectionstring2;
con = new Npgsql.NpgsqlConnection(str); //
InitializeComponent();
}
private void frmEmployee_Load(object sender, EventArgs e)
{
string sql = "Select * from employee where company_code='S00159' order by rownumber";
ds = new DataSet();
da = new NpgsqlDataAdapter(sql, con);
builder = new NpgsqlCommandBuilder(da);
da.Fill(ds);
bs.DataSource = ds;
bs.DataMember = ds.Tables[0].ToString();
DataGridView1.DataSource = bs;
}
private void addemployee_Click(object sender, EventArgs e)
{
int start_row_number;
int pos1;
try
{
if (DataGridView1.Rows.Count == 0)
{
pos1 = 0;
start_row_number = 1; // added on 15/10/2011
}
else
{
pos1 = DataGridView1.CurrentCell.RowIndex + 1;
start_row_number = Convert.ToInt32(DataGridView1.Rows[pos1 - 1].Cells["rownumber"].Value) + 1;
}
DataRow employeeRow = ds.Tables[0].NewRow();
string emplcode = companyInfo.company_code.Substring(1, 1) + classMisc.genEmployeeCodeNew(); // just a random number
employeeRow["company_code"] = companyInfo.company_code.Trim();
employeeRow["employee_code_no"] = emplcode;
employeeRow["srno"] = classMisc.getsrno();
employeeRow["flag"] = true;
employeeRow["rownumber"] = start_row_number; // pos1
employeeRow["mobile"] = 0;
employeeRow["aadhar"] = 0;
employeeRow["pfuppersalarylimit"] = 0;
ds.Tables[0].Rows.InsertAt(employeeRow, pos1);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "error 1");
}
}

Generate code with recursion

I'm having issue with creating product code in recursion.
What I want to do is:
I enter code 1000
-If code exist in database regenerateCode(string code)
-else insert into database
Code:
(...)
if(codeExist)
CodeTB.Text = regenerateCode(string toParse); //toParse = 1000
string regenerateCode(string toParse)
{
string helper = "";
int parseCode = int.Parse(toParse);
helper = new string('0', 4 - parseCode.ToString().Length);
helper += parseCode + 1;
using (SqlConnection conn = new SqlConnection(cString.c_String))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Product.productID FROM Product " +
"WHERE Product.PLU = '" + helper + "' ", conn))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
// if code still exist in database, regenerate it
regenerateCode(helper);
}
else
{
//else return code
return helper;
}
}
}
}
return helper;
}
Actually it works fine with example:
1000 (exist)
1001 (exist)
1002 (not exist, insert), but
when code = 1002, it goes into line with else {return helper;} and have no idea why going again to regenerateCode() method..
Any ideas?
It happens because you do nothing with the return value. You pass helper to the recursion, but do not place the return value anywhere. your method should look like this:
string regenerateCode(string toParse)
{
string helper = "";
int parseCode = int.Parse(toParse);
helper = new string('0', 4 - parseCode.ToString().Length);
helper += parseCode + 1;
using (SqlConnection conn = new SqlConnection(cString.c_String))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Product.productID FROM Product " +
"WHERE Product.PLU = '" + helper + "' ", conn))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// Return the next code that doesn't exist
return rdr.HasRows ? regenerateCode(helper) : helper;
}
}
}
}
Also, remember that while string are reference types, they are immutable. which means that a string that is passed as an argument would not change like a normal array. see: How are strings passed in .NET?

How to display column headers in the Exported Excel

I am following a tutorial "Export data from sql server database to excel in wpf". Now I can achieve the function successfully. But in the exported Excel file, there is no column names (database column headers like CustomerId, CustomerName, city, postcode, telephoneNo...)
.
How can I get this feature? Also, how can I open a SaveAs dialogue? Thanks. The following is my code:
private void button1_Click(object sender, RoutedEventArgs e)
{
string sql = null;
string data = null;
int i = 0;
int j = 0;
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = #"Data Source=.\sqlexpress;Initial Catalog=Client;Integrated Security=SSPI;";
cnn.Open();
sql = "select * from Customers";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
I'm not an expert in this, but I believe that you can use an underscore character (_) in a Range object to select or edit a column header:
xlWorkSheet.Range["A1", _].Value2 = "Heading for first column";

Entity Framework performance after SqlBulkCopy

I need some performance for doing some of my things. I'm trying to import excel data to my SQL Server database here is my code for doing that work but it really takes too much time for that. Could you give me some advice for that
[WebMethod]
public static string VerileriAktar(string alanlar, string gruplar, string shit)
{
ArtiDBEntities entity = new ArtiDBEntities();
string[] eslesmeler = alanlar.Split(',');
string[] grplar = gruplar.Split(',');
DataSet ds = (DataSet)HttpContext.Current.Session["ExcelVerileri"];
DataTable dt = ds.Tables["" + shit + ""];
MembershipUser gelen = (MembershipUser)HttpContext.Current.Session["kimo"];
Guid aa = (Guid)gelen.ProviderUserKey;
List<tbl_AltMusteriler> bulkliste = new List<tbl_AltMusteriler>();
List<tbl_AltMusteriler> ilkkontrol = entity.tbl_AltMusteriler.Where(o => o.UserId == aa).ToList();
List<tbl_AltMusteriler> grupicin = new List<tbl_AltMusteriler>();
List<tbl_OzelAlanlar> ensonatilacakalan = new List<tbl_OzelAlanlar>();
List<tbl_OzelTarihler> ensonalicaktarih = new List<tbl_OzelTarihler>();
// Datatable mın Kolon isimlerini değiştirdim.
foreach (string item_col_name in eslesmeler)
{
string alan = item_col_name.Split('=')[0].Split('_')[1];
string degisecek = item_col_name.Split('=')[1];
if (degisecek == "")
continue;
dt.Columns[degisecek].ColumnName = alan;
}
#region verilerde
foreach (DataRow dr in dt.Rows)
{
tbl_AltMusteriler yeni = new tbl_AltMusteriler();
foreach (DataColumn dtclm in dt.Columns)
{
string gsm1 = "";
if (dtclm.ColumnName == "gsm1")
gsm1 = dr["gsm1"].ToString();
string gsm2 = "";
if (dtclm.ColumnName == "gsm2")
gsm2 = dr["gsm2"].ToString();
string ad = "";
if (dtclm.ColumnName == "ad")
ad = dr["ad"].ToString();
string soyad = "";
if (dtclm.ColumnName == "soyad")
soyad = dr["soyad"].ToString();
if (gsm1 != "")
{
if (Tools.isNumber(gsm1) == false)
continue;
else
{
if (gsm1.Length > 10)
gsm1 = gsm1.Substring(1, 10);
yeni.Gsm1 = gsm1;
}
}
if (gsm2 != "")
{
if (Tools.isNumber(gsm2) == false)
continue;
else
{
if (gsm2.Length > 10)
gsm2 = gsm2.Substring(1, 10);
yeni.Gsm2 = gsm2;
}
}
if (ad != "")
yeni.Ad = ad;
if (soyad != "")
yeni.Soyad = soyad;
}
yeni.UserId = new Guid(aa.ToString());
if (yeni.Gsm1 != "")
grupicin.Add(yeni);
}
#endregion
bulkliste = grupicin.GroupBy(cust => cust.Gsm1).Select(grp => grp.First()).ToList();
List<tbl_AltMusteriler> yokartikin = bulkliste.Where(o => !ilkkontrol.Any(p => o.Gsm1 == p.Gsm1)).ToList();
int saybakim = yokartikin.Count();
DataTable bulkdt = new DataTable();
if (yokartikin.Count > 0)
{
Type listType = yokartikin.ElementAt(0).GetType();
PropertyInfo[] properties = listType.GetProperties();
foreach (PropertyInfo property in properties)
if (property.Name == "UserId")
bulkdt.Columns.Add(new DataColumn() { ColumnName = property.Name, DataType = typeof(Guid) });
else
bulkdt.Columns.Add(new DataColumn() { ColumnName = property.Name });
foreach (object itembulk in yokartikin)
{
DataRow drbk = bulkdt.NewRow();
foreach (DataColumn col in bulkdt.Columns)
drbk[col] = listType.GetProperty(col.ColumnName).GetValue(itembulk, null);
bulkdt.Rows.Add(drbk);
}
}
//var rowsOnlyInDt1 = bulkdt.AsEnumerable().Where(r => !bulkdt44.AsEnumerable()
// .Any(r2 => r["gsm1"].ToString() == r2["gsm1"].ToString()));
//DataTable result = rowsOnlyInDt1.CopyToDataTable();//The third table
if (bulkdt.Rows.Count > 0)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ArtiDBMemberShip"].ConnectionString))
{
SqlTransaction transaction = null;
connection.Open();
try
{
transaction = connection.BeginTransaction();
using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction))
{
sqlBulkCopy.BulkCopyTimeout = 240;
sqlBulkCopy.DestinationTableName = "tbl_AltMusteriler";
sqlBulkCopy.ColumnMappings.Add("UserId", "UserId");
sqlBulkCopy.ColumnMappings.Add("Ad", "Ad");
sqlBulkCopy.ColumnMappings.Add("Soyad", "Soyad");
sqlBulkCopy.ColumnMappings.Add("Adres", "Adres");
sqlBulkCopy.ColumnMappings.Add("Gsm1", "Gsm1");
sqlBulkCopy.ColumnMappings.Add("Gsm2", "Gsm2");
sqlBulkCopy.ColumnMappings.Add("Faks", "Faks");
sqlBulkCopy.ColumnMappings.Add("Telefonis", "Telefonis");
sqlBulkCopy.ColumnMappings.Add("Telefonev", "Telefonev");
sqlBulkCopy.ColumnMappings.Add("Eposta", "Eposta");
sqlBulkCopy.ColumnMappings.Add("DogumTarihi", "DogumTarihi");
sqlBulkCopy.ColumnMappings.Add("EvlilikTar", "EvlilikTar");
sqlBulkCopy.ColumnMappings.Add("TcNo", "TcNo");
//sqlBulkCopy.ColumnMappings.Add("Deleted", "Deleted");
sqlBulkCopy.WriteToServer(bulkdt);
}
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
}
}
entity.SaveChanges();
}
if (grplar.Length > 0)
{
List<tbl_AltMusteriler> guncelliste = entity.tbl_AltMusteriler.Where(o => o.UserId == aa).ToList();
List<tbl_KisiGrup> kisigruplari = new List<tbl_KisiGrup>();
foreach (tbl_AltMusteriler itemblkliste in bulkliste)
{
long AltMusteriIDsi = guncelliste.Where(o => o.Gsm1 == itemblkliste.Gsm1).FirstOrDefault().AltMusteriID;
// Seçili Gruplara kişileri ekleme
#region Gruplara ekleme
if (grplar.Length > 0)
{
foreach (string item_gruplar in grplar)
{
if (item_gruplar == "chkall")
continue;
if (item_gruplar == "")
continue;
if (item_gruplar == null)
continue;
tbl_KisiGrup yeni_kisi_grup = new tbl_KisiGrup()
{
AltMusteriID = AltMusteriIDsi,
GrupID = int.Parse(item_gruplar)
};
kisigruplari.Add(yeni_kisi_grup);
}
}
#endregion
}
List<tbl_KisiGrup> guncel_grup = entity.tbl_KisiGrup.Where(o => o.tbl_AltMusteriler.UserId == aa).ToList();
List<tbl_KisiGrup> kisi_grup_kaydet = kisigruplari.Where(o => !guncel_grup.Any(p => o.AltMusteriID == p.AltMusteriID && o.GrupID == p.GrupID)).ToList();
// Grupları Datatable çevirme
#region Grupları Datatable le çevirme
DataTable bulkdt2 = new DataTable();
if (kisi_grup_kaydet.Count > 0)
{
Type listType = kisi_grup_kaydet.ElementAt(0).GetType();
//Get element properties and add datatable columns
PropertyInfo[] properties = listType.GetProperties();
foreach (PropertyInfo property in properties)
bulkdt2.Columns.Add(new DataColumn() { ColumnName = property.Name });
foreach (object itembulk in kisi_grup_kaydet)
{
DataRow drbk = bulkdt2.NewRow();
foreach (DataColumn col in bulkdt2.Columns)
drbk[col] = listType.GetProperty(col.ColumnName).GetValue(itembulk, null);
bulkdt2.Rows.Add(drbk);
}
}
#endregion
//Burada bulk insert işlemini gerçekleştiriyoruz...
#region Grup Verileri BulkCopy ile birkerede yazdık
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ArtiDBMemberShip"].ConnectionString))
{
SqlTransaction transaction = null;
connection.Open();
try
{
transaction = connection.BeginTransaction();
using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction))
{
sqlBulkCopy.BulkCopyTimeout = 240;
sqlBulkCopy.DestinationTableName = "tbl_KisiGrup";
sqlBulkCopy.ColumnMappings.Add("AltMusteriID", "AltMusteriID");
sqlBulkCopy.ColumnMappings.Add("GrupID", "GrupID");
sqlBulkCopy.WriteToServer(bulkdt2);
}
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
}
}
entity.SaveChanges();
#endregion
}
return "ok";
}
EDIT
actually that codeblock takes time when if there is 70.000 or more rows data
List<tbl_AltMusteriler> yokartikin = bulkliste.Where(o => !ilkkontrol.Any(p => o.Gsm1 == p.Gsm1)).ToList();
I think the my main problem is while I'm just inserting data with sqlbulkcopy. After that I couldn't get the identity ids, for that reason I get data to a generic list and try to find that new ids and creating a new list of group. and sqlbulkcopy again. these are takes lots of time about 10 minutes to import 65.000 rows is there another way to do those things
Your question is very broad. I would recomment reading performance considerations for EF. Also keep in mind that EF is not really meant for bulk operations since it brings all data from the database to the client. This adds a lot of overhead if you want to do this for a lot of entities if you don't need to/want to process them on the client. (Note I have not really looked into your code - it's too much)

Passing the value to crystal report

I'm having a hard time to figure out how can i view or seen the values from Visual Studio 2010 C# to Crystal Report.. This is I want to be viewed my report in Crystal Report
As of ????(4:30PM): ????(December), ????(2011)
Juan Dela Cruz
Count: 10
Score: 5
Grade: ????(50.00)
The code below is my button SEARCH to find out the summary of this particular employee.
try
{
econ = new SqlConnection();
econ.ConnectionString = emp_con;
econ.Open();
float iGrade = 0;
float Grade = 0.00F;
string Log_User;
float Count, Score;
string date = DateTime.Now.ToShortTimeString();
ecmd = new SqlCommand("SELECT Log_User, Count = COUNT(Det_Score), Score = SUM(Det_Score) FROM MEMBER M,DETAILS D WHERE D.Emp_Id = M.Emp_Id AND Log_User like" + "'" + Convert.ToString(comEmployee.Text) + "'AND Month(Sched_Start) =" + "'" + Convert.ToInt32(iMonth) + "'AND Year(Sched_Start) =" + "'" + Convert.ToInt32(txtYear.Text) + "'GROUP BY Log_User", econ);
ecmd.CommandType = CommandType.Text;
ecmd.Connection = econ;
dr = ecmd.ExecuteReader();
while (dr.Read())
{
if (dr == null || !dr.HasRows)
{
MessageBox.Show("No record found.", "Error");
}
else
{
Log_User = (string)dr["Log_User"];
Count = (dr["Count"] as int?) ?? 0;
Score = (dr["Score"] as int?) ?? 0;
try
{
iGrade = Score / Count;
Grade = iGrade * 100;
}
catch (DivideByZeroException)
{
Console.WriteLine("Exception occured");
}
}
}
econ.Close();
The code below is my Crystal Report in getting the values from my database: these are included: Log_User, Month and the Year..
ParameterFields myParams = new ParameterFields();
ParameterField name = new ParameterField();
ParameterDiscreteValue valName = new ParameterDiscreteValue();
name.ParameterFieldName = "#Log_User";
valName.Value = comEmployee.Text;
name.CurrentValues.Add(valName);
myParams.Add(name);
ParameterField month = new ParameterField();
ParameterDiscreteValue valMonth = new ParameterDiscreteValue();
month.ParameterFieldName = "#Month";
valMonth.Value = Convert.ToInt32(iMonth);
month.CurrentValues.Add(valMonth);
myParams.Add(month);
ParameterField year = new ParameterField();
ParameterDiscreteValue valYear = new ParameterDiscreteValue();
year.ParameterFieldName = "#Year";
valYear.Value = Convert.ToInt32(txtYear.Text);
year.CurrentValues.Add(valYear);
myParams.Add(year);
crystalReportViewer1.ParameterFieldInfo = myParams;
crystalReportViewer1.ReportSource = CrystalReport81;
}
catch (Exception x)
{
MessageBox.Show(x.GetBaseException().ToString(), "Connection Status", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
All i want is to view my input parameters in the report and also the grade.. (all the values that have ????)
I know there is someone there can help me to figure it out. After this, I've done in my project.
TextObject yr = (TextObject)CrystalReport81.ReportDefinition.Sections["Section3"].ReportObjects["Text1"];
yr.Text = txtYear.Text;
FORM Textbox --> CRYSTAL REPORT Textbox
By adding the code above will enable you to show the value you entered in the textboxes.. but first you should have an empty Textbox in your Crystal Report because that will catch the value you throw from your FORM Textbox
I hope it can help others.. as it helped me a lot..

Resources