File from Response not updating data after each request - c#

I am very new to C#, I am working in a program than downloads a file data with data from SQL Server database, the issue the query it always brings the same old now nonexistent data in the file.
This is the services BORA.asmx.cs:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Text;
using LST.Enums;
using LST.Extensions;
using LST.Global;
using LST.Methods;
using Newtonsoft.Json;
using System.Diagnostics.Tracing;
namespace BORA
{
[WebMethod(EnableSession = true)]
public byte[] generateReport()
{
var vUser = Session["rep-users"];
var vCat = Session["rep-categories"];
var vStatus = Session["rep-status"];
var vAreas = Session["rep-areas"];
string strWhere = "";
if (vUser.fwEmpty() != "")
strWhere += (strWhere == "" ? "" : " AND ") + "P.Owner IN (" + vUser.ToString().fwSqlFilterIn() + ")";
if (vCat.fwEmpty() != "")
strWhere += (strWhere == "" ? "" : " AND ") + "Category IN (" + vCat.ToString().fwSqlFilterIn() + ")";
if (vStatus.fwEmpty() != "")
strWhere += (strWhere == "" ? "" : " AND ") + "P.Status IN (" + vStatus.ToString().fwSqlFilterIn() + ")";
if (vAreas.fwEmpty() != "")
strWhere += (strWhere == "" ? "" : " AND ") + "Area IN (" + vAreas.ToString().fwSqlFilterIn() + ")";
if (strWhere != "") strWhere = " WHERE " + strWhere;
System.Diagnostics.Debug.WriteLine("strWhere = " + strWhere);
LST.Methods.clsMethodsWeb fw = new clsMethodsWeb();
string strPathOrigin = fw.appGetPath + "excel\\template.xlsx";
string strPathDest = fw.appGetPath + "excel\\{0}.xlsx".fwFormat(Session["User"].ToString().ToLower().Replace(".", ""));
string strTable = "";
string strPID = "";
strPID = "WHERE PID IN (" +
#"SELECT P.PID
FROM tbl_Project_Tasks P
LEFT OUTER JOIN tbl_Project_Details D
ON P.PID = D.PID {0}"
.fwFormat(strWhere)
.fwSqlFillDataTable()
.fwDistinctValues("PID")
.fwSqlFilterIn() + ")";
if (strPID.fwEmpty() == "") return null;
fw.fileCopy(strPathOrigin, strPathDest);
DataTable dt = #"SELECT *
FROM tbl_Project_Tasks {0}"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Tasks";
strTable = "tblTasks";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt },
strPathDest, strTable: strTable, blnSave: true);
// ** Tasks
dt = #"SELECT *
FROM tbl_Project_Details D
LEFT OUTER JOIN tbl_Project_SavingType S
ON D.PID = S.PID
{0}"
.fwFormat(strPID.Replace(" PID ", " D.PID "))
.fwSqlFillDataTable();
dt.TableName = "Projects";
strTable = "tblProjects";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt }, strPathDest, strTable: strTable, blnSave: true);
// ** Projects
dt = #"SELECT REPLACE(REPLACE(SavingType, '(', ''), ')', '') Project, SUM(Saving) Projected, SUM(SavingFinal) Confirmed
FROM tbl_Project_SavingType
{0}
GROUP BY SavingType"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Project consolidate";
strTable = "tblProjectConsolidate";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt }, strPathDest, strTable: strTable, blnSave: true);
// ** Project consolidate
// ** tblProjectConsolidate
dt = #"SELECT Status, Count(Status) Count
FROM tbl_Project_Tasks
{0}
AND ISNULL(Status, '') <> ''
GROUP BY Status"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Task status";
strTable = "tblTaskStatus";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt },
strPathDest, strTable: strTable, blnSave: true);
// ** Task status
// ** tblTaskStatus
dt = #"Select Status, COUNT(Status) Count
FROM tbl_Project_Details
{0}
GROUP BY Status"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Project status";
strTable = "tblProjectStatus";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt },
strPathDest, strTable: strTable, blnSave: true);
// ** Project status
// ** tblProjectStatus
dt = #"Select Category, COUNT(Category) Count
FROM tbl_Project_Details
{0}
GROUP BY Category
ORDER BY Count"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Project categories";
strTable = "tblProjectCategories";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt },
strPathDest, strTable: strTable, blnSave: true);
// ** Poject categories
// ** tblProjectCategories
dt = #"Select Area, Count(Area) Count
FROM tbl_Project_Details
{0}
GROUP BY Area
ORDER BY Count"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Project areas";
strTable = "tblProjectAreas";
return LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt },
strPathDest, strTable: strTable);
// ** Project areas
// ** tblProjectAreas
}
[WebMethod(EnableSession = true)]
public string getReportOptions()
{
string dtArea = ("SELECT DISTINCT AREA FROM tbl_Maint_Area").fwSqlFillDataTable().fwDistinctValues();
string dtCategory = ("SELECT DISTINCT CATEGORY FROM tbl_Maint_Category").fwSqlFillDataTable().fwDistinctValues();
string dtStatus = ("SELECT DISTINCT STATUS FROM tbl_Maint_Status").fwSqlFillDataTable().fwDistinctValues();
string dtUsers = ("SELECT DISTINCT USERNAME FROM tbl_Maint_User").fwSqlFillDataTable().fwDistinctValues();
return JsonConvert.SerializeObject(new
{
Areas = dtArea,
Categories = dtCategory,
Status = dtStatus,
Users = dtUsers
});
}
[WebMethod(EnableSession = true)]
public string fillParams(string users, string categories, string status, string areas)
{
Session["rep-users"] = users;
Session["rep-categories"] = categories;
Session["rep-status"] = status;
Session["rep-areas"] = areas;
return "";
}
}
}
This is the .aspx.cs of export: export.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BORA
{
public partial class export : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
byte[] arr = null;
try
{
clsBORA report = new clsBORA();
arr = report.generateReport();
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=\"BORA Scorecard.xlsx\"");
Response.SetCookie(new HttpCookie("fileDownload", "true"));
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(arr);
//Response.End();
}
catch { /* DO NOTHING */ }
finally
{
if (arr != null) Array.Clear(arr, 0, arr.Length);
GC.Collect();
}
}
}
}
The aspx file named: export.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="export.aspx.cs" Inherits="BORA.export" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Queries are correct, html part is ok, works correctly but it keeps downloading wrong data, aside that, how can I print a byte array?
Anything else I should add?
Also, how can I print that ".fwswlfilldata".
Again, I am new to programming, love it, wanna learn, but sometimes I need help with these things.
Thank you very much

Related

Turn csv stream parser sql insert into bulk insert

I have this specific way of getting a CSV where a web service generates the CSV file in the web browser and I then grab all of the data and parse it and stream it into variables and do an SQL insert for each row. Now the problem is this takes to long and I am not sure how to convert this to do a bulk insert.
my code is below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.ComponentModel;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.FileIO;
using System.IO;
using System.Data.SqlClient;
using System.Data.Sql;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
WebClient client = new WebClient();
Uri ur = new Uri("http://1.1.1.1/portal/FEDE?ORGANIZATION_ID=96&SERVLET_ACTION=getItemsList");
public void scrapeCSV()
{
Stream myStream = client.OpenRead(ur);
StreamReader stream = new StreamReader(myStream);
//Parse the stream
using (TextFieldParser parser = new TextFieldParser(stream))
{
parser.TextFieldType = FieldType.Delimited;
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
int rowCount = 1, colCount = 1;
string strInsert = "";
string rowName = "";
string itemCode = "", description = "", barcode = "";
int boxQty = 0, palletQty = 0;
double weight = 0.0;
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["casi"].ConnectionString);
conn.Open();
SqlCommand cmd1 = new SqlCommand("delete from itemslist", conn);
cmd1.ExecuteNonQuery();
while (!parser.EndOfData)
{
//Processing row
string[] row = parser.ReadFields();
rowName = row[0].ToString();
if (rowCount > 2) //Skip header row
{
foreach (string field in row)
{
if (colCount == 1)
{
itemCode = field;
}
else if (colCount == 2)
{
description = field.Replace("'", "''"); ;
}
else if (colCount == 3)
{
if (field != "")
{
boxQty = Convert.ToInt32(field);
}
else
{
boxQty = 0;
}
}
else if (colCount == 4)
{
if (field != "")
{
palletQty = Convert.ToInt32(field);
}
else
{
palletQty = 0;
}
}
else if (colCount == 5)
{
if (field != "")
{
weight = Convert.ToDouble(field);
}
else
{
weight = 0.0;
}
}
else if (colCount == 6)
{
barcode = field;
}
colCount++;
}
colCount = 1;
strInsert = #"INSERT INTO ItemsList (ItemCode, Description, BoxQty, PalletQty,Weight,Barcode)
VALUES ('" + itemCode + "', '" + description + "', '" + boxQty + "', '" + palletQty + "', '" + weight + "', '" + barcode + "')";
SqlCommand cmd2 = new SqlCommand(strInsert, conn);
try
{
cmd2.ExecuteNonQuery();
}
catch (Exception ex)
{
//put code trace log here such as write a txt file content ex.tostring;
if (ex is FormatException || ex is OverflowException)
{
Response.Write(strInsert);
continue;
}
//continue;//will run code bellow cmd.ExecuteNonQuery(); or you can put any code running if
Response.Write(strInsert);
continue;
}
}
this.Label1.Text = Convert.ToString(rowCount);
rowCount++;
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
scrapeCSV();
Response.Write("Download finished!");
}
}
If someone is able to help me figure this out that would be very appreciated.
You need to create a DataTable and then add a mapping to the datatable so the columns of the DataTable are mapped to the columns of the database. I got you started by creating and filling the datatable. Now search web for info on bulk copy datatable to database.
DataTable dt = new DataTable();
dt.Columns.Add("ItemCode", typeof(string));
dt.Columns.Add("Description", typeof(string));
dt.Columns.Add("BoxQty", typeof(int));
dt.Columns.Add("PalletQty", typeof(int));
dt.Columns.Add("Weight", typeof(decimal));
dt.Columns.Add("Barcode", typeof(string));
//inside while loop
dt.Rows.Add(new object[] {itemCode, description, boxQty, palletQty, weight, barcode});

How to increase timeout when import data into Acumatica using webservices API

I have a problem when trying to import some data from client application into Acumatica system using web Services API. I try to send data in screen Bill And Adjusment (AP301000) and use much data in detail transactions. Data in transaction are about 235 rows. The error message when I try to import data is "The Operation Has Timeout".
I have tried to change web.config file like this below :
<httpRuntime
executionTimeout="36000".../>
<compilation
debug="false".../>
<sessionState
timeout="360".../>
This below is my code,
I used button to do the process and then call method in another class :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using JADEACCU.services;
using System.Data.SqlClient;
namespace JADEACCU
{
public partial class frmTest : Form
{
ServicesConnection con = new ServicesConnection();
COMClass comClass = new COMClass();
services.Screen context = new services.Screen();
servicesUntyped.Screen contextUntyped = new servicesUntyped.Screen();
public frmTest()
{
InitializeComponent();
}
private void btnSendBill_Click(object sender, EventArgs e)
{
string type, refNbr, dtdate, customerOrder, customer, terms, currency, dtDueDateString, dtCashDiscDateString, description, jadeRefNbr;
type = cmbType.Text;
refNbr = txtRefNbr.Text;
dtdate = dtDate.Text.ToString();
customerOrder = txtCustomerOrder.Text;
customer = txtCustomer.Text;
terms = cmbTerms.Text;
currency = cmbCurrency.Text;
dtDueDateString = dtDueDate.Text.ToString();
dtCashDiscDateString = dtCashDiscDate.Text.ToString();
description = txtDescription.Text;
jadeRefNbr = txtJadeRefNbr.Text;
comClass.InsertBill(jadeRefNbr, dtdate, customerOrder, description, customer, terms, currency, dtDueDateString, dtCashDiscDateString);
}
}
}
call this method :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Windows.Forms;
using JADEACCU.services;
namespace JADEACCU
{
public class COMClass
{
ServicesConnection sCon = new ServicesConnection();
services.Screen context = new services.Screen();
servicesUntyped.Screen contextUntyped = new servicesUntyped.Screen();
public string InsertBill(string vBillNo, string vBillDate, string vVendorRef, string vDesc, string vVendCode, string vTerms, string vCcy, string vDueDate, string vCashDiscDate)
{
//sCon.getLogin(context);
sCon.getLoginBill(context);
AP301000Content konten = context.AP301000GetSchema();
List<Command> oCmds = new List<Command>();
//Create Header.
//oCmds.Add(konten.Actions.Insert);
oCmds.Add(new Value { Value = "Bill", LinkedCommand = konten.DocumentSummary.Type });
oCmds.Add(new Value { Value = "0000", LinkedCommand = konten.DocumentSummary.ReferenceNbr });
oCmds.Add(new Value { Value = vBillNo, LinkedCommand = konten.DocumentSummary.JadeRefNbr });
oCmds.Add(new Value { Value = vBillDate, LinkedCommand = konten.DocumentSummary.Date });
oCmds.Add(new Value { Value = vVendorRef, LinkedCommand = konten.DocumentSummary.VendorRef });
oCmds.Add(new Value { Value = vDesc, LinkedCommand = konten.DocumentSummary.Description });
oCmds.Add(new Value { Value = vVendCode, LinkedCommand = konten.DocumentSummary.Vendor });
oCmds.Add(new Value { Value = vTerms, LinkedCommand = konten.DocumentSummary.Terms });
oCmds.Add(new Value { Value = vCcy, LinkedCommand = konten.DocumentSummary.Currency });
oCmds.Add(new Value { Value = vDueDate, LinkedCommand = konten.DocumentSummary.DueDate });
oCmds.Add(new Value { Value = vCashDiscDate, LinkedCommand = konten.DocumentSummary.CashDiscountDate });
//oCmds.Add(konten.Actions.Save);
string serverDb, userDb, passDb, databaseDb;
serverDb = Properties.Settings.Default.serverDB;
databaseDb = "SGL";
userDb = "jade";
passDb = "jade1234";
SqlConnection con = new SqlConnection();
con.ConnectionString = #"server=" + serverDb + "; database=" + databaseDb + "; user=" + userDb + "; password=" + passDb + ";";
//con.ConnectionString = "Provider = SQLOLEDB.1; Persist Security Info = False; Server = 192.168.10.7; Initial Catalog = SGL; User ID = jade; Password = jade1234";
con.Open();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
cmd = new SqlCommand("select case when a.branchid = '0102' then 'KARAWANG' else 'CIKARANG' end as BranchID, " +
"BookingNo, b.RAccount as ICharges, BCostUnit, IQty, BCost, " +
"case when TaxSts = 'Y' and c.TaxRate = 10 then 'PPN' when TaxSts = 'Y' and c.TaxRate = 1 then 'PPN1' end as TaxID, " +
"case when isnull(WhseCode,'') = 'WH01' and a.branchid = '0101' then left(rcontcode,4) + 'C1' + right(rcontcode,2) when isnull(WhseCode, '') = 'WH02' and a.branchid = '0101' then left(rcontcode, 4) + 'C2' + right(rcontcode, 2) when isnull(WhseCode, '') = 'WH03' and a.branchid = '0101' then left(rcontcode, 4) + 'C3' + right(rcontcode, 2) when isnull(WhseCode, '') = 'WH04' and a.branchid = '0101' then left(rcontcode, 4) + 'C4' + right(rcontcode, 2) when isnull(WhseCode, '') = 'KLC' and a.branchid = '0102' then left(rcontcode, 4) + 'K1' + right(rcontcode, 2) when isnull(WhseCode, '') = 'GIIC' and a.branchid = '0105' then left(rcontcode, 4) + 'GL' + right(rcontcode, 2) when isnull(WhseCode, '') = 'TLC' and a.branchid = '0106' then left(rcontcode, 4) + 'TL' + right(rcontcode, 2) when isnull(WhseCode, '') = '' and a.branchid = '0101' then left(rcontcode, 4) + 'HO' + right(rcontcode, 2) when isnull(WhseCode, '') = '' and a.branchid = '0102' then left(rcontcode, 4) + 'KO' + right(rcontcode, 2) when isnull(WhseCode, '') = '' and a.branchid = '0103' then left(rcontcode, 4) + 'CO' + right(rcontcode, 2) when isnull(WhseCode, '') = '' and a.branchid = '0104' then left(rcontcode, 4) + 'PO' + right(rcontcode, 2) end as SubAccount from BookRates as a inner join revcodes as b on a.icharges = b.rcode inner join billmaster as c on a.billno = c.billno where a.BillNo = '" + vBillNo + "'", con);
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(dt);
foreach (DataRow dR in dt.Rows)
{
oCmds.Add(konten.DocumentDetails.ServiceCommands.NewRow);
oCmds.Add(new Value { Value = dR["BranchID"].ToString(), LinkedCommand = konten.DocumentDetails.Branch });
oCmds.Add(new Value { Value = dR["BookingNo"].ToString(), LinkedCommand = konten.DocumentDetails.JobOrderNbr });
oCmds.Add(new Value { Value = dR["ICharges"].ToString(), LinkedCommand = konten.DocumentDetails.InventoryID });
oCmds.Add(new Value { Value = dR["BCostUnit"].ToString(), LinkedCommand = konten.DocumentDetails.UnitCost });
oCmds.Add(new Value { Value = dR["SubAccount"].ToString(), LinkedCommand = konten.DocumentDetails.Subaccount });
oCmds.Add(new Value { Value = dR["IQty"].ToString(), LinkedCommand = konten.DocumentDetails.Quantity });
oCmds.Add(new Value { Value = dR["BCost"].ToString(), LinkedCommand = konten.DocumentDetails.Amount });
oCmds.Add(new Value { Value = dR["TaxID"].ToString(), LinkedCommand = konten.DocumentDetails.TaxCategory, Commit = true });
}
oCmds.Add(konten.Actions.Save);
try
{
context.AP301000Submit(oCmds.ToArray());
return "ACUMATICA - Save Bill SUCCESS";
}
catch (Exception ex)
{
return ex.Message;
//return "ACUMATICA - Save Bill FAILED";
}
}
}
}
But it still doesn't work.
Please give some reference how to solve this case.
Thanks
when you create the screen object, there is an option to set the timeout. Try setting that value to infinite.
sample
context = new Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.Url = "http://blah blah";
context.Timeout = System.Threading.Timeout.Infinite;

C# pass a DataRow[] variable from code behind to .netpage

I am trying to pass a protected DataRow[] msgArray; from code-behind to the .net page.
msgArray contains rows from a DB table that I selected, when I do Response.Write(msgArray[0]["comment"]) it outputs correctly what I have stored in the comment column in my DB.
The problem is that I cannot do the same in my .net page when I load the page where I do this:
<asp:Panel ID="commentSection" runat="server">
<%= msgArray[0]["comment"] %>
</asp:Panel>
I get a Object reference not set to an instance of an object.
What am I doing wrong ?
This is my code-behind(.cs) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MySql.Data.MySqlClient;
namespace Groups
{
public partial class Group : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String queryStr;
String gname;
String gtype;
String uname;
DataTable group = new DataTable();
DataTable msg = new DataTable();
protected DataRow[] msgArray;
protected void Page_Load(object sender, EventArgs e)
{
String id = Request.QueryString["id"];
if (id != null)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT g.*, (SELECT COUNT(id) FROM app_groups.users_groups_leg ugl WHERE ugl.id_group = g.id) as member_count FROM app_groups.groups g WHERE g.id = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
group.Load(reader = cmd.ExecuteReader());
var groupArray = group.AsEnumerable().ToArray();
reader.Close();
int member_count = 0;
int.TryParse(groupArray[0]["member_count"].ToString(), out member_count);
Panel grInfo = new Panel();
grInfo.Controls.Add(new LiteralControl("<br/><div class='panel panel-primary'><div class='panel-heading'><h2>" + groupArray[0]["group_name"] + "</h2></div><div class='panel-body'><span>Categorie: <span class='title'>" + groupArray[0]["group_type"] + "</span></span><br/><span class='membrii'>" + (member_count == 1 ? member_count + " membru" : member_count + " membri") + "</span><br/><span>Fondat pe: " + ConvertUnixTimeStamp(groupArray[0]["founded"].ToString()) + "</span><br/></div></div>"));
groupInfo.Controls.Add(grInfo);
conn.Close();
showComments();
}
}
public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
return new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(unixTimeStamp) + 3600*2);
}
public DataRow[] showComments()
{
String id = Request.QueryString["id"];
if (id != null)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT gc.* FROM app_groups.group_comments gc WHERE gc.id_group = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
msg.Load(reader = cmd.ExecuteReader());
msgArray = msg.AsEnumerable().ToArray();
reader.Close();
Response.Write(msgArray[0]["comment"]);
/*Panel grComments = new Panel();
grComments.Controls.Add(new LiteralControl(""));
groupInfo.Controls.Add(grComments);*/
}
return msgArray;
}
}
}
Create a new class dataAccess.cs
using System;
using System.Data;
namespace Groups
{
public class dataAccess
{
public List<string> GetComments()
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
try
{
MySql.Data.MySqlClient.MySqlDataReader reader;
DataTable msg = new DataTable();
conn.Open();
List<string> comments = new List<string>();
queryStr = "SELECT gc.* FROM app_groups.group_comments gc WHERE gc.id_group = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
msg.Load(reader = cmd.ExecuteReader());
foreach(DataRow dr in msg.Rows)
{
comments.Add(dr["comment"]);
}
reader.Close();
return comments;
}
catch (Exception ex)
{
//throw ex;
}
}
}
}
In the ASPX page
<asp:Panel ID="commentSection" runat="server">
<%
var data = Groups.dataAccess.GetComments();
foreach(string c in data)
{
Response.Write("<p>" + c + "</p>");
}
%>
</asp:Panel>
According to ASP.NET Page Life cycle, your method showComments() will be called after the <%= msgArray[0]["comment"] %> part. Hence it won't be available there.
Best way is to have a control like Label in your .aspx page and update the text property from showComments() method.

Convert code from BGW to Async and Await for DataTabale/MySQLDataAdapter

How can I abandon BGW and use async/wait tasking thing, I am willing to learn the technique as I am using VS 2013.
I looked at the examples online, but still I am unable to do it myself because the examples I came across were using existing functions in .NET which already return a task. I tried to separate the code inside BGW DoWork and create a task, but the compiler kept asking me about await and I could not call the task anyway, I noticed that the lines taking time are:
SQLDataAdapter = new MySqlDataAdapter(SQLcmd);
SQLDataAdapter.Fill(dt);
What I need is: inside a button click to start the task of reading from the database, and then relieve the Form from hanging (suppose I am not using BGW), and then read the result and displaying them in the datagridview.
// code starts here
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
namespace MySQLProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string stdNo = File.ReadAllText("stdNo.txt").Replace(Environment.NewLine, ",");
const string cs = #"what ever";
MySqlConnection conn = new MySqlConnection(cs);
MySqlDataAdapter SQLDataAdapter = new MySqlDataAdapter(); ;
DataSet ds = new DataSet();
conn.Open();
this.InvokeEx(x => x.textBox1.AppendText(string.Format("MySQL version : {0};", conn.ServerVersion)));
DataTable dt = new DataTable("StudentNamesAndNumbers");
dt.Columns.Add("Student Name", typeof(string));
dt.Columns.Add("Student ID", typeof(string));
dt.Columns.Add("First", typeof(float));
dt.Columns.Add("Second", typeof(float));
dt.Columns.Add("Section", typeof(string));
ds.Tables.Add(dt);
try
{
MySqlCommand SQLcmd = new MySqlCommand();
SQLcmd = conn.CreateCommand();
SQLcmd.CommandText = String.Format(#"Select u.firstname as 'Student Name', u.username as 'Student ID'"
+ ",( select score from gradebook_result g , gradebook_evaluation e "
+ "where g.user_id = u.user_id "
+ "and name = 'First' "
+ "and g.evaluation_id = e.id "
+ "and e.course_code = c.course_code) as 'First' "
+ ",( select score from gradebook_result g , gradebook_evaluation e "
+ "where g.user_id = u.user_id "
+ "and name = 'Second' "
+ "and g.evaluation_id = e.id "
+ "and e.course_code = c.course_code) as 'Second' "
+ ", c.course_code as 'Section'"
+ "from user u, course_rel_user c "
+ "where "
+ "u.username in ({0}) "
+ "and u.username REGEXP '[0-9]+' "
+ "and c.course_code like 'IT102CPLUS%' "
+ "and u.user_id = c.user_id ;", stdNo);
this.InvokeEx(x => x.textBox1.AppendText(SQLcmd.CommandText));
SQLDataAdapter = new MySqlDataAdapter(SQLcmd);
SQLDataAdapter.Fill(dt);
dt.DefaultView.Sort = "Section ASC, Student Name ASC";
this.InvokeEx(x => x.dataGridView1.Columns.Clear());
this.InvokeEx(x => x.dataGridView1.DataSource = ds.Tables["StudentNamesAndNumbers"]);
this.InvokeEx(x => x.dataGridView1.AutoResizeColumns());
this.InvokeEx(x => x.label1.Text = dt.Rows.Count.ToString() + " Students");
// =======================================================
var lines = new List<string>();
string[] columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
var header = string.Join(",", columnNames);
lines.Add(header);
var valueLines = dt.AsEnumerable().Select(row => string.Join(",", row.ItemArray));
lines.AddRange(valueLines);
File.WriteAllLines("Export.csv", lines, Encoding.UTF8);
}
catch (MySqlException ex)
{
this.InvokeEx(x => x.textBox1.AppendText(string.Format("Error: {0}\n\n", ex.ToString())));
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Enabled = true;
}
}
}
I have a series on my blog that shows how BackgroundWorker compares to Task.Run.
In general, you should not be using either of these approaches for I/O-bound operations. However, there are some older APIs that have not been upgraded to expose TAP methods. I believe the "data adapter" and "data table" APIs are considered too old to be upgraded, hence there's no "FillAsync" you could use.
So - assuming you want to keep the "data table" approach - you can just use Task.Run as a replacement for BackgroundWorker directly. Note that IProgress<T> is a more modern way of doing any kind of cross-thread invoking for progress updates:
private async void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
var progress = new Progress<string>(update => textBox1.AppendText(update));
var ds = await Task.Run(() => BackgroundWork(progress));
dataGridView1.Columns.Clear();
dataGridView1.DataSource = ds.Tables["StudentNamesAndNumbers"];
dataGridView1.AutoResizeColumns();
label1.Text = dataGridView1.Rows.Count.ToString() + " Students";
button1.Enabled = true;
}
private DataSet BackgroundWork(IProgress<string> progress)
{
string stdNo = File.ReadAllText("stdNo.txt").Replace(Environment.NewLine, ",");
const string cs = #"what ever";
MySqlConnection conn = new MySqlConnection(cs);
MySqlDataAdapter SQLDataAdapter = new MySqlDataAdapter(); ;
DataSet ds = new DataSet();
conn.Open();
if (progress != null)
progress.Report(string.Format("MySQL version : {0};", conn.ServerVersion));
DataTable dt = new DataTable("StudentNamesAndNumbers");
dt.Columns.Add("Student Name", typeof(string));
dt.Columns.Add("Student ID", typeof(string));
dt.Columns.Add("First", typeof(float));
dt.Columns.Add("Second", typeof(float));
dt.Columns.Add("Section", typeof(string));
ds.Tables.Add(dt);
try
{
MySqlCommand SQLcmd = new MySqlCommand();
SQLcmd = conn.CreateCommand();
SQLcmd.CommandText = String.Format(#"Select u.firstname as 'Student Name', u.username as 'Student ID'"
+ ",( select score from gradebook_result g , gradebook_evaluation e "
+ "where g.user_id = u.user_id "
+ "and name = 'First' "
+ "and g.evaluation_id = e.id "
+ "and e.course_code = c.course_code) as 'First' "
+ ",( select score from gradebook_result g , gradebook_evaluation e "
+ "where g.user_id = u.user_id "
+ "and name = 'Second' "
+ "and g.evaluation_id = e.id "
+ "and e.course_code = c.course_code) as 'Second' "
+ ", c.course_code as 'Section'"
+ "from user u, course_rel_user c "
+ "where "
+ "u.username in ({0}) "
+ "and u.username REGEXP '[0-9]+' "
+ "and c.course_code like 'IT102CPLUS%' "
+ "and u.user_id = c.user_id ;", stdNo);
if (progress != null)
progress.Report(SQLcmd.CommandText);
SQLDataAdapter = new MySqlDataAdapter(SQLcmd);
SQLDataAdapter.Fill(dt);
dt.DefaultView.Sort = "Section ASC, Student Name ASC";
var lines = new List<string>();
string[] columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
var header = string.Join(",", columnNames);
lines.Add(header);
var valueLines = dt.AsEnumerable().Select(row => string.Join(",", row.ItemArray));
lines.AddRange(valueLines);
File.WriteAllLines("Export.csv", lines, Encoding.UTF8);
return ds;
}
catch (MySqlException ex)
{
if (progress != null)
progress.Report(string.Format("Error: {0}\n\n", ex.ToString()));
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
You should mark the method as async and await async method when you can.
If there is no async method and you want to run the synchronous method on another thread, await on Task.Run.
private async void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
try
{
//Use an async method when there is one available
string stdNo;
using (var reader = File.OpenText("Words.txt"))
{
stdNo = await reader.ReadToEndAsync();
}
stdNo = stdNo.Replace(Environment.NewLine, ",");
const string cs = #"what ever";
MySqlConnection conn = new MySqlConnection(cs);
MySqlDataAdapter SQLDataAdapter = new MySqlDataAdapter(); ;
DataSet ds = new DataSet();
//Use Task.Run to call a long running code on another thread
//If available you should use await conn.OpenAsync();
await Task.Run(() => conn.Open());
//You don't need invoke, after an await you are back to the synchronization context
textBox1.AppendText(string.Format("MySQL version : {0};", conn.ServerVersion));
DataTable dt = new DataTable("StudentNamesAndNumbers");
dt.Columns.Add("Student Name", typeof(string));
dt.Columns.Add("Student ID", typeof(string));
dt.Columns.Add("First", typeof(float));
dt.Columns.Add("Second", typeof(float));
dt.Columns.Add("Section", typeof(string));
ds.Tables.Add(dt);
//...
}
finally
{
button1.Enabled = true;
}
}

c# Multiple Sql results and session values

I have an SQL DB which is filled with users (id,First_Name,Surname,Email_Account,etc..).
Im Searching the DataBase based on Name and i show links , If that link is clicked then it redirects you to the users page.
My problem is when i try to pass the session variables, so when the link gets clicked then pageload is loading from the Session variables.
So when i have multiple search results , with the way i do it the last result session variables pass.
Here's the code! :)
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DisplayingImages
{
public partial class WebForm7 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=MPAPASYMEON;Server=mpapasymeon;Database=LOGIN;Initial Catalog=LOGIN; User ID=nikolaossts; Password=aaa;Connect Timeout=240");
string PID2;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
DataTable PassRecord = new DataTable();
String str = "select First_Name,Email_Account,Surname,id from ID where (First_Name like '%'+ #search +'%' ) OR (Surname like '%'+ #search +'%') OR (Email_Account like '%'+ #search +'%')";
SqlCommand Srch = new SqlCommand(str, con);
Srch.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox1.Text;
if (TextBox1.Text != "")
{
con.Open();
Srch.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = Srch;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
da.Fill(dt);
DataTable Results = new DataTable;
PID =(int)( Session["id"]);
int SaveTheFirst = PID;
foreach (DataRow dr in dt.Rows)
{
PID2 = dr["id"].ToString();
if (PID.ToString() != PID2 )
{
var field = "<a href='" + Page.ResolveUrl("~/PageView.aspx?Email=" + dr["id"].ToString()) + "'>" + (dr["First_Name"] + "").ToString() + "</a>";
Session["SurnameView"] = dr["Surname"];
string check1 = dr["Surname"].ToString();
Session["idView"] = dr["id"];
string check2 = dr["id"].ToString();
Session["EmailView"] = dr["Email_Account"];
string check3 = dr["Email_Account"].ToString();
Response.Write(field);
HttpContext context = HttpContext.Current;
Response.Write("<br/>");
}
}
con.Close();
}
else
{
string display = " Not Valid Search Criteria!";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);
}
}
public string SN { get; set; }
public string PS { get; set; }
public string EM { get; set; }
public int PID { get; set; }
}
}
Why not put an identifier to each session? Like for instance, the ID of your user or something else that you can map to? That way you will be able to associate each session, with a user - after creating the sessions. Otherwise, if you don't use a unique identifier that does not match your business logic, you would not be able to associate the session...
foreach (DataRow dr in dt.Rows)
{
PID2 = dr["id"].ToString();
if (PID.ToString() != PID2 )
{
var field = "<a href='" + Page.ResolveUrl("~/PageView.aspx?Email=" + dr["id"].ToString()) + "'>" + (dr["First_Name"] + "").ToString() + "</a>";
Session["SurnameView_" + PID2 ] = dr["Surname"];
string check1 = dr["Surname"].ToString();
Session["idView_" + PID2] = dr["id"];
string check2 = dr["id"].ToString();
Session["EmailView_" + PID2] = dr["Email_Account"];
string check3 = dr["Email_Account"].ToString();
Response.Write(field);
HttpContext context = HttpContext.Current;
Response.Write("<br/>");
}
}
Have a look at these links to get a better idea of how to create unique sessions per user
Creating unique sessions per user on Webforms ASP.net
how safe is it to use session variables - asp.net / c#
One way to save it in the session
int counter = 0;
foreach (DataRow dr in dt.Rows)
{
PID2 = dr["id"].ToString();
if (PID.ToString() != PID2 )
{
counter+=1;
//do stuff
Session["Email_" + counter] = dr["Surname"];
}
}
But in this case you should add the counter to the url parameters.
var field = "<a href='" + Page.ResolveUrl("~/PageView.aspx?Email=" + dr["id"].ToString()) + "&counter=" + counter "'>" + (dr["First_Name"] + "").ToString() + "</a>";
In this case when you open the page you will know which session parameter is needed.
The other way is just to write all of your values in the Url and take them after that.
I suggest using a HiddenField to store the data in which you want to pass. Session is not really reliable for multiple instances

Categories

Resources