This question already has an answer here:
Asp.net losing values of variables
(1 answer)
Closed 4 years ago.
I am running a web Form where I call a new thread on a button press to execute an Rdotnet snippet of code ( I needed the thread because the current thread kept sending stack overload errors ).
In the Rdotnet function , I have it access a global class variable and put data into it. Once the function completes and the button submit function is over I try to access that global class on another button click ( separate button ), however it is empty. I assume that the thread ends so all data in it ends to, so I tried returning the class and putting it into the global variable in the buttonclick function itself,same result.
I need help.
public partial class BTForm : Page
{
List<DirectorDetail> Details = new List<DirectorDetail>();
BindingList<string> Test = new BindingList<string>();
List<string> Line = new List<string>();
List<string> output = new List<string>();
WebDetails BTlibrary;
OpenFileDialog ofd = new OpenFileDialog();
List<string> Months = new List<string>();
List<string> Year = new List<string>();
BTBill Billfile = new BTBill();
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
addMonth();
addyear();
foreach (var x in Months)
{
DropDownList1.Items.Add(x);
}
foreach (var y in Year)
{
DropDownList2.Items.Add(y);
}
}
try
{
ListBox4.DataSource = Test;
ListBox4.DataBind();
}
catch(Exception x)
{
Console.Write(x);
}
}
protected void Submit_Click(object sender, EventArgs e)
{
Thread current = Thread.CurrentThread;
WebDetails BTlibrary2 =BTlibrary;
Thread t = new Thread(() => { BTlibrary2 = processes(BTlibrary2); }, 2500000);
t.Start();
t.Join();
BTlibrary = BTlibrary2;
// Thread.Sleep(10000);
}
public WebDetails processes(WebDetails library)
{
if (FileUpLoad1.HasFile)
{
string location = #"C:/BTBill/" + FileUpLoad1.FileName;
Billfile.Tablename = FileUpLoad1.FileName;
try
{
Billfile.Month = DropDownList1.SelectedItem.ToString();
Billfile.Year = DropDownList2.SelectedItem.ToString();
Billfile.Filename = Cleaning.PathCleaning(location);
Billfile.Limit = TextBox3.Text.ToString();
string fpath = Billfile.Month + " " + Billfile.Year + " Query " + "Limit -£ " + Billfile.Limit + "\\";
string filename = Billfile.Month + " " + Billfile.Year + " Query " + "Limit -£ " + Billfile.Limit;
Billfile.Savelocation = "//lonvmfs01/commonwealth_Data/BT BILL Alert/" + filename;
Billfile.Sfilename = "//lonvmfs01/commonwealth_Data/BT BILL Alert/" + filename;
}
catch (Exception x)
{
Error1.Text = "Please Select Month and year\nERROR : " + x;
}
FileUpLoad1.SaveAs(#"C:\BTBill\" + FileUpLoad1.FileName);
library = Executable.executable(Billfile);
// FileUpLoad1.
// = "File Uploaded: " + FileUpLoad1.FileName;
}
else
{
Label1.Text = "No File Uploaded.";
}
DataFrame Director = library.Director;
DataFrame bill = library.Query;
DataFrame limit = library.Btlim;
int colcount = Director.RowCount;
for (int x = 0; x < colcount; x++)
{
string cost_centre = Director[x, 0].ToString();
string director = Director[x, 1].ToString();
string email_address = Director[x, 2].ToString();
double total = SendMail.calculatetotal(bill, limit, cost_centre);
if (total > 0)
{
Line.Add(x + " )\t" + cost_centre + "\t" + director + "\t\t" + email_address + "\t" + total);
Test.Add(x + " )\t" + cost_centre + "\t" + director + "\t\t" + email_address + "\t" + total);
}
}
ListBox4.DataSource = Test;
ListBox4.DataBind();
//foreach (var x in getline().ToArray())
// {
// ListBox4.Items.Add(x);
// }
// ListBox4.DataBind();
return library;
}
protected void Sendmail(object sender, EventArgs e)
{
DataFrame Director = BTlibrary.Director;
DataFrame bill = BTlibrary.Query;
DataFrame limit = BTlibrary.Btlim;
string test;
foreach (Object selecteditem in ListBox4.GetSelectedIndices() )
{
test = ListBox4.Items[(int)selecteditem].Text;
System.Diagnostics.Debug.WriteLine(test);
test = test.Substring(0, 1);
output.Add(test);
}
List<int> index = new List<int>();
for (int y = 0; y < output.Count; y++)
{
index.Add(Convert.ToInt32(output[y]));
}
for (int y = 0; y < index.Count; y++)
{
DirectorDetail temp = new DirectorDetail();
temp.cost_centre = Director[index[y], 0].ToString();
temp.director = Director[index[y], 1].ToString();
temp.email_address = Director[index[y], 2].ToString();
for (int count = 0; count < limit.RowCount; count++)
{
if (limit[count, 0].ToString() == temp.cost_centre)
{
temp.limit = limit[count, 1].ToString();
}
}
Details.Add(temp);
}
SendMail.Mailing(BTlibrary.Query, BTlibrary.Deplist, BTlibrary.Btlim, BTlibrary.Bill, Details);
//Session["Details"] = Details;
// this.Close();
}
private void addyear()
{
DateTime time = System.DateTime.UtcNow;
int baseyear = time.Year - 3;
for (int x = baseyear; x < (baseyear + 10); x++)
{
Year.Add(x.ToString());
}
}
// returns the list of years
public List<string> getYear()
{
return Year;
}
// returns the list of months
public List<String> getMonth()
{
return Months;
}
//adds months to a list
private void addMonth()
{
Months.Add("January");
Months.Add("February");
Months.Add("March");
Months.Add("April");
Months.Add("May");
Months.Add("June");
Months.Add("July");
Months.Add("August");
Months.Add("September");
Months.Add("October");
Months.Add("November");
Months.Add("December");
}
public List<string> getline()
{
return Line;
}
}
public static WebDetails executable(BTBill bill)
{
StartupParameter rinit = new StartupParameter();
rinit.Quiet = true;
rinit.RHome = #"C:\Program Files\R\R-3.4.4\";
rinit.Home = #"C:\R";
REngine.SetEnvironmentVariables();
REngine engine = REngine.GetInstance(null,true,rinit);
// engine.Initialize();
//install and make connection to Postgres
// engine.Evaluate("install.packages('RPostgreSQL') \n install.packages('gridExtra')");
engine.Evaluate("require('RPostgreSQL')" + "\n" +
"pw <- {'admin'}" + "\n" +
"drv <- RPostgreSQL::PostgreSQL()" + "\n" +
"drv <- dbDriver('PostgreSQL')" +"\n"+
"con <- dbConnect(drv, dbname = 'postgres'," +"\n"+
"host = 'localhost', port = 5432," +"\n"+
"user = 'postgres', password = pw)");
engine.Evaluate("postgresmfile<- dbGetQuery(con,'select * from masterfile')" + "\n" +
"Contact <- dbGetQuery(con, 'select * from contact')"+"\n"+
"btlim<- dbGetQuery(con, ' select * from bt_departmentlimit')"+"\n"+
"dbDisconnect(con)");
engine.Evaluate("BTBill = read.csv(file<-'"+bill.Filename+"', header=TRUE, sep=',',skip=1)");
// building dataframes and queries
DataFrame BTBill = engine.Evaluate("BTBill").AsDataFrame();
DataFrame MasterFile = engine.Evaluate("postgresmfile").AsDataFrame();
DataFrame BTLim = engine.Evaluate("btlim").AsDataFrame();
DataFrame Contact= engine.Evaluate("Contact ").AsDataFrame();
DataFrame Query = engine.Evaluate("Merged <- merge(BTBill,postgresmfile,by.x='SERVICE.NO',by.y = 'service_number')" + "\n"+ "Merged_2 <- merge(Merged,Contact,by.x='cost_centre',by.y='cost_centre') " + "\n"+
"query <- Merged_2[c('SERVICE.NO','username','cost_centre','job_post','USAGE.CHARGES','TOTAL.COST','USAGE.START.DATE','USAGE.END.DATE','director','email_address')]").AsDataFrame();
DataFrame Merge2 = engine.Evaluate("Merged_2").AsDataFrame();
DataFrame maillist = engine.Evaluate("data.frame(query)" +"\n"+
"test <-subset(query, TOTAL.COST >= "+bill.Limit+ ", select = c(SERVICE.NO,username,cost_centre,job_post, TOTAL.COST, USAGE.START.DATE, USAGE.END.DATE,director,email_address,USAGE.CHARGES))").AsDataFrame();
DataFrame DepList = engine.Evaluate("x<-test[c('cost_centre','director','email_address')]" + "\n" +
"ux<-unique(x) ").AsDataFrame();
DataFrame DepList2=engine.Evaluate("y <-query[c('cost_centre', 'director', 'email_address')]" + "\n" +
"uy<-unique(y) ").AsDataFrame();
engine.Evaluate("dir.create(file.path('" + bill.Savelocation + "'))");
//creating pdf files for each department head
engine.Evaluate("write.csv(Merged_2, file = '" + bill.Savelocation + "/MasterFile.csv');");
for (int count = 0; count < DepList.RowCount; count++)
{
DataFrame temp = engine.Evaluate("data.frame(query);" +
"test2 <-subset(query, USAGE.CHARGES >= " + bill.Limit + " & cost_centre=='"+DepList[count,0]+"', select = c(SERVICE.NO,username,cost_centre,job_post, USAGE.CHARGES, USAGE.START.DATE, USAGE.END.DATE,director,email_address))").AsDataFrame();
engine.Evaluate("library(gridExtra);");
engine.Evaluate("pdf('" + bill.Sfilename +"/"+ DepList[count, 0] + ".pdf', height=20, width=20);" );
try
{
engine.Evaluate("grid.table(test2); dev.off() ;");
}
catch (Exception e)
{
}
}
SendMailForm form = new SendMailForm();
WebDetails web = new WebDetails(DepList2, Query, BTLim);
web.Deplist = DepList;
web.Bill = bill;
engine.Evaluate("write.csv(test, file = '" + bill.Savelocation + "/Users over threshold.csv')");
engine.Dispose();
return web;
// form.Director=DepList2;
//form.bill = Query;
//form.limit = BTLim;
List<DirectorDetail> output = form.Details;
SendMail.Mailing(Query, DepList,BTLim, bill,output);
// to filter by department
// DataFrame maillist = engine.Evaluate("data.frame(query)" + "\n" +
// "test <-subset(query, TOTAL.COST >= " + bill.Limit + "& Cost.Centre=='"+bill.Dep+"', select = c(SERVICE.NO, User.Name, Cost.Centre, ROLE.JOB.POST, TOTAL.COST, USAGE.START.DATE, USAGE.END.DATE,DIRECTOR,EMAIL.ADDRESS))").AsDataFrame();
//engine.Evaluate("install.package('dplyr')");
}
}
}
It seems my problem turned out to be unrelated to variable sharing through threads, but instead to deal with the way button click instances worked.
long story short, in order to share a variable between two event instances, the easiest way to do it is through Sessions.
I needed to put the BTlibrary in a session and access it in the second button click event for it to get the value saved from the previous.
protected void Submit_Click(object sender, EventArgs e)
{
Thread current = Thread.CurrentThread;
WebDetails BTlibrary2 =BTlibrary;
Thread t = new Thread(() => { BTlibrary2 = processes(BTlibrary2); }, 2500000);
t.Start();
t.Join();
Session["BTLib"] = BTlibrary2;
// Thread.Sleep(10000);
}
protected void Sendmail(object sender, EventArgs e)
{
List<DirectorDetail> Details = new List<DirectorDetail>();
BTlibrary = (WebDetails) Session["BTLib"];
this worked
Related
The file name is generated by Po+Invoice in the sql table. When user attach a pdf it overwrites the existing file name that has same po+invoice. Is there anyway i could create the unique id filename.
public partial class upload : System.Web.UI.Page
{
string mID;
DataBaseDataContext dataBaseDataContext = new DataBaseDataContext();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnExit_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void SUbmit(object sender, EventArgs e)
{
try
{
var ext = FileUploadtoServer.FileName.Substring(FileUploadtoServer.FileName.IndexOf('.') + 1, 3);
if (ext.ToLower() != "pdf")
{
Response.Write("<script>alert('Please select a pdf File!')</script>");
return;
}
}
catch (Exception ex)
{
Response.Write("<script>alert('Please select a pdf File!')</script>");
return;
}
if (PO_Number.Text.Equals("") || HeadCode.Text.Equals("") || Manufacture.Text.Equals("") || Description.Text.Equals("") || Invoice.Text.Equals(""))
{
Response.Write("<script>alert('Please Fill All Fields!')</script>");
}
TPT tPT = new TPT();
tPT.Invoice_No = Invoice.Text;
tPT.PO_Number = PO_Number.Text;
tPT.Item_Code = Manufacture.Text;
tPT.Heat_Code = HeadCode.Text;
tPT.Description = Description.Text;
tPT.FileName = PO_Number.Text + Invoice.Text + ".pdf";
dataBaseDataContext.TPTs.InsertOnSubmit(TPT);
dataBaseDataContext.SubmitChanges();
String path = Server.MapPath("Attachments/" + PO_Number.Text + Invoice.Text + ".pdf");
FileUploadtoServer.SaveAs(path);
Response.Write("<script>alert('Successfully Inserted!')</script>");
Invoice.Text = "";
Manufacture.Text = "";
HeadCode.Text = "";
Description.Text = "";
PO_Number.Text = "";
}
}
I have tried
Guid.NewGuid() + ".pdf";,
it still does the same thing.
The simple way would be to just take the file name, and add -1, then -2, then -3
So,
mydoc.pdf
mydoc-1.pdf
mydoc-2.pdf
etc. etc.
So, then say a function like this:
Edit: Updated code
string GetServerFilenext(string strFileFullPath)
{
string strFileToCheck = "";
for (int i = 0; i < 100; i++)
{
if (i == 0)
strFileToCheck = strFileFullPath;
else
strFileToCheck =
Path.GetDirectoryName(strFileFullPath) +
#"\" + Path.GetFileNameWithoutExtension(strFileFullPath) +
"-" + i.ToString() + Path.GetExtension(strFileFullPath);
if (!File.Exists(strFileToCheck))
break;
}
return strFileToCheck;
}
So, now your code becomes this:
string sFileToSave =
Server.MapPath(#"~/Attachments/" + PO_Number.Text + Invoice.Text + ".pdf");
sFileToSave = GetServerFileNext(sFileToSave);
tPT.FileName = Path.GetFileName(sFiletoSave);
So, you setup the full path and file name.
You then check if it exists, and if not, then add -1, then -2 etc. etc.
Edit2: So, code would look like this (warning: air code)
string sFileToSave =
Server.MapPath(#"~/Attachments/" + PO_Number.Text + Invoice.Text + ".pdf");
sFileToSave = GetServerFileNext(sFileToSave);
TPT tPT = new TPT();
tPT.Invoice_No = Invoice.Text;
tPT.PO_Number = PO_Number.Text;
tPT.Item_Code = Manufacture.Text;
tPT.Heat_Code = HeadCode.Text;
tPT.Description = Description.Text;
tPT.FileName = Path.GetFileName(sFileToSave);
dataBaseDataContext.TPTs.InsertOnSubmit(TPT);
dataBaseDataContext.SubmitChanges();
FileUploadtoServer.SaveAs(sFileToSave);
Instead of adding -1,-2, i was able to upload it by adding date stamp
`tPT.FileName = PO_Number.Text + Invoice.Text + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";`
I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.
im having problems with this function. so basically a user will upload an excel file .xls (2003 version) then once the import button is clicked it will read the excel file and import it into the sql database.
here is my code
protected void btnImport_Click(object sender, EventArgs e)
{
Business.Student student = new Business.Student();
int errorCount = 0;
int successCount = 0;
string successTotal;
int missinglastname = 0;
int missingfirstname = 0;
int missingmiddlename = 0;
if (filebiometrics.HasFile == false)
{
}
else
{
string pathToExcelFile = filebiometrics.FileName;
var excelFile = new ExcelQueryFactory(pathToExcelFile);
IEnumerable<string> worksheetnames = excelFile.GetWorksheetNames();
string worksheetName = excelFile.GetWorksheetNames().ToArray()[0];
var import = from a in excelFile.Worksheet<Business.Student.StudentList>(worksheetName) select a;
//var emptyfield = excelFile.Worksheet<Business.Employees.EmployeeImport>().Where(x => x.Surname != null).ToList();
excelFile.AddMapping<Business.Student.StudentList>(x => x.studentnumber, "Student Number");
excelFile.AddMapping<Business.Student.StudentList>(x => x.firstname, "Firstname");
excelFile.AddMapping<Business.Student.StudentList>(x => x.lastname, "Lastname");
excelFile.AddMapping<Business.Student.StudentList>(x => x.middlename, "Middlename");
string missing = "Missing!";
foreach (var a in import)
{
if (a.studentnumber == 0)
{
}
if (a.lastname == null)
{
a.lastname = missing;
missinglastname = missinglastname + 1;
}
if (a.firstname == "")
{
a.firstname = missing;
missingfirstname = missingfirstname + 1;
}
if (a.middlename == null)
{
missingmiddlename = missingmiddlename + 1;
}
else if (student.CheckExistingStudentNumber(a.studentnumber))
{
errorCount = errorCount + 1;
}
else
{
student.Create(a.studentnumber, a.firstname, a.lastname, a.middlename);
successCount = successCount + 1;
successTotal = "Total imported record: " + successCount.ToString();
}
}
txtLog.InnerText = "Total duplicate record: " + errorCount.ToString() +
Environment.NewLine +
"Total missing data on Firstname column: " + missingfirstname.ToString() +
Environment.NewLine +
"Total missing data on Lastname column: " + missinglastname.ToString() +
Environment.NewLine +
"Total missing data on middlename column: " + missingmiddlename.ToString() +
Environment.NewLine +
Environment.NewLine +
"Total imported record: " + successCount.ToString();
filebiometrics.Attributes.Clear();
}
}
im always getting this error
the error is in this line 'IEnumerable worksheetnames = excelFile.GetWorksheetNames();'
can somebody help me with this?
Your error message is self explanatory. Error is at this line:-
var excelFile = new ExcelQueryFactory(pathToExcelFile);
ExcelQueryFactory expects the full file path but you are just passing the excel file name using string pathToExcelFile = filebiometrics.FileName; and obviously it is not able to read the file.
You need to read the excel file which user is uploading and save it to the server and then read it like this:-
string filename = Path.GetFileName(filebiometrics.FileName);
filebiometrics.SaveAs(Server.MapPath("~/") + filename);
var excelFile = new ExcelQueryFactory(Server.MapPath("~/") + filename);
I try to import the records from csv and binding into grid.Then every records process for other details. In this case I need to update the UI after every record completed.
WebscrapeSettings objweb = new WebscrapeSettings();
var dtcontact = GetDataTableFromCsv(#"D:\\(1-5) DEN.csv", true);
if (dtcontact.Rows.Count > 0)
{
string starttime = DateTime.Now.ToString();
for (int ic = 0; ic < dtcontact.Rows.Count; ic++)
{
objweb.SearchType = "Company Linked In";
objweb.ContactName = dtcontact.Rows[ic]["Contact"].ToString();
objweb.Location = dtcontact.Rows[ic]["LinkedInLocation"].ToString();
objweb.Title = dtcontact.Rows[ic]["Title"].ToString();
objweb.SearchString = "";
objweb.EmailDomain = "";
objweb.Company = dtcontact.Rows[ic]["Company"].ToString();
string result = "";
var t = WebScrape(objweb);
if (t.Count > 0)
{
foreach (var pair in t)
{
divnormal.InnerHtml = ic + "-" + Thread.CurrentThread.ManagedThreadId + "-" + "<br/> <br/> <br/>" + divnormal.InnerHtml;// +"<br/> <br/> <br/>" + pair.Value;
}
}
//I want to rebind the Grid Here
BindImportfileDetails();
BindImportrecordsdetails(ImportFileID);
}
string endtime = DateTime.Now.ToString();
im writing a code in C# that watches a folder and when a file gets created the code makes some actions and writes the results to a log file.
im having this very strange behaviour. when i file gets created in the watched folder the function that handles the change is executed twise! even if it is only one change event.
initially i used FileSystemWatcher. but i after looking it up, i saw that it has meny stability issued so i switched to MyFileSystemWatcher which is a much more stable impliminatation. but im still getting duplications in my log file. i have no idea why the code that is in chanrge for looking up the change runs twise. here is the code sample
protected void Folder_Watch(string path)
{
if (!Directory.Exists(path))
{
try
{
System.IO.Directory.CreateDirectory(path);
}
catch (Exception ex)
{
File.AppendAllText(logPath + "\\SSHErrorLog.log", "[]*******" + DateTime.Now + " Error: " + ex.Message.ToString() + Environment.NewLine);
}
}
MyFileSystemWatcher m_Watcher = new MyFileSystemWatcher(path);
//m_Watcher.Path = path;
m_Watcher.Filter = "*.*";
m_Watcher.NotifyFilter = NotifyFilters.FileName;
m_Watcher.Created += new FileSystemEventHandler(OnChanged);
m_Watcher.EnableRaisingEvents = true;
}
here is the onChange function
private void OnChanged(object source, FileSystemEventArgs e)
{
File.AppendAllText(logPath + "\\SSHConnectionLog.log", "[]*******" + DateTime.Now + " OnChanged function: " + Environment.NewLine);
// Decrypt the file.
DecryptFile(keyPath + "\\id_rsa_Encrypted", keyPath + "\\id_rsa", sSecretKey);
// Remove the Key from memory.
//PKey = new PrivateKeyFile(keyPath + "\\id_rsa");
keyResult.Text = "RSA keys Were Generated at:" + keyPath;
//ScpClient client = new ScpClient("remnux", "adi", PKey);
Chilkat.SFtp client = new Chilkat.SFtp();
string[] tempPath = e.FullPath.Split('\\');
string fullPathNew = string.Empty;
for (int i = 0; i < tempPath.Length - 1; i++)
{
fullPathNew += tempPath[i];
}
if (Directory.Exists(fullPathNew))
{
sshConnect(client);
File_Upload(e.FullPath, client);
}
else
{
try
{
sshConnect(client);
System.IO.Directory.CreateDirectory(fullPathNew);
File_Upload(e.FullPath, client);
}
catch (Exception ex)
{
File.AppendAllText(logPath + "\\SSHErrorLog.log", "[]*******" + DateTime.Now + " Error in OnChanged function: " + ex.Message.ToString() + Environment.NewLine);
}
}
}
any help would be very much appriciated!
handled the onChange function. added time and file name to handle duplicate hits
private void OnChanged(object source, FileSystemEventArgs e)
{
string[] temp = new string[3];
string[] tempNow = new string[3];
string[] tempSeconds = new string[2];
string[] tempNowSeconds = new string[2];
int temp1 = 0;
int temp2 = 0;
if(string.IsNullOrEmpty(changeName))
{
changeName = e.Name;
}
if (string.IsNullOrEmpty(changeTime))
{
changeTime = DateTime.Now.ToString();
temp = this.changeTime.Split(':');
tempNow = DateTime.Now.ToString().Split(':');
tempSeconds = temp[2].Split(' ');
tempNowSeconds = temp[2].Split(' ');
temp1 = Convert.ToInt16(tempSeconds[0]);
temp2 = Convert.ToInt16(tempNowSeconds[0]);
// Decrypt the file.
DecryptFile(keyPath + "\\id_rsa_Encrypted", keyPath + "\\id_rsa", sSecretKey);
// Remove the Key from memory.
PKey = new PrivateKeyFile(keyPath + "\\id_rsa");
keyResult.Text = "RSA keys Were Generated at:" + keyPath;
ScpClient client = new ScpClient("remnux", "adi", PKey);
string[] tempPath = e.FullPath.Split('\\');
string fullPathNew = string.Empty;
for (int i = 0; i < tempPath.Length - 1; i++)
{
fullPathNew += tempPath[i];
}
if (Directory.Exists(fullPathNew))
{
sshConnect(client);
File_Upload(e.FullPath, client);
}
else
{
try
{
sshConnect(client);
System.IO.Directory.CreateDirectory(fullPathNew);
File_Upload(e.FullPath, client);
}
catch (Exception ex)
{
File.AppendAllText(logPath + "\\SSHErrorLog.log", "[]*******" + DateTime.Now + " Error in OnChanged function: " + ex.Message.ToString() + Environment.NewLine);
}
}
}
if (!this.changeTime.Equals(DateTime.Now.ToString()))
{
temp = this.changeTime.Split(':');
tempNow = DateTime.Now.ToString().Split(':');
tempSeconds = temp[2].Split(' ');
tempNowSeconds = temp[2].Split(' ');
temp1 = Convert.ToInt16(tempSeconds[0]);
temp2 = Convert.ToInt16(tempNowSeconds[0]);
if (temp[2] != tempNow[2])
{
if ((temp1 < temp2 + 10 || temp1 > temp2 +40) && e.Name != changeName)
{
// Decrypt the file.
DecryptFile(keyPath + "\\id_rsa_Encrypted", keyPath + "\\id_rsa", sSecretKey);
// Remove the Key from memory.
PKey = new PrivateKeyFile(keyPath + "\\id_rsa");
keyResult.Text = "RSA keys Were Generated at:" + keyPath;
ScpClient client = new ScpClient("remnux", "adi", PKey);
string[] tempPath = e.FullPath.Split('\\');
string fullPathNew = string.Empty;
for (int i = 0; i < tempPath.Length - 1; i++)
{
fullPathNew += tempPath[i];
}
if (Directory.Exists(fullPathNew))
{
sshConnect(client);
File_Upload(e.FullPath, client);
}
else
{
try
{
sshConnect(client);
System.IO.Directory.CreateDirectory(fullPathNew);
File_Upload(e.FullPath, client);
}
catch (Exception ex)
{
File.AppendAllText(logPath + "\\SSHErrorLog.log", "[]*******" + DateTime.Now + " Error in OnChanged function(second if): " + ex.Message.ToString() + Environment.NewLine);
}
}
}
}
}
}