i have a 4 textboxes on my webpage, one of which is populated using a javascript calender control...the problem is that all of these textboxes lose their value after a postback (clicking an asp.net button control). the textboxes are not readonly so i cant figure out why this is so...please help...and thanks
protected void Page_Load(object sender, EventArgs e)
{
BindProdTopDetails();
BindProdTable();
// BindProdComment();
}
protected void BtnProdUpdate_Click(object sender, EventArgs e)
{
//saveProdDetails();
bool success = saveProdDetails();
if (success)
{
string strScript96 = "<script language=JavaScript>";
strScript96 += "javascript:alert('Update Successful');";
strScript96 += "</script>";
if (!ClientScript.IsStartupScriptRegistered("clientScript"))
ClientScript.RegisterClientScriptBlock(this.GetType(), clientScript", strScript96);
}
}
public bool saveProdDetails()
{
string prodLine = DDProdLine.SelectedValue;
string stock1 = DDMaterial.SelectedValue;
string stock2 = TextBoxMaterial.Text.Trim().ToString();
string supplier = TextBoxSupplier.Text.Trim().ToString();
string billet = RBBillet.SelectedValue;
string matTime1 = TextBoxMatTime.Text.Trim().ToString();
string matTime2 = DDMatTime.SelectedValue;
string prodTime1 = TextBoxProdTime.Text.Trim().ToString();
string prodTime2 = DDProdTime.SelectedValue;
string shipTime1 = TextBoxShipTime.Text.Trim().ToString();
string shipTime2 = DDShipTime.SelectedValue;
CultureInfo cultureInfo = CultureInfo.CurrentCulture;
string format = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString();
string cmr = cmrDue.Value.ToString();
string kc = kcDue.Value.ToString();
string x = cmr.Substring(3, 2);
string y = cmr.Substring(0, 2);
string z = cmr.Substring(6, 4);
string x1 = kc.Substring(3, 2);
string y1 = kc.Substring(0, 2);
string z1 = kc.Substring(6, 4);
string finalCmr = x + "/" + y + "/" + z;
string finalKC = x1 + "/" + y1 + "/" + z1;
DateTime dt = DateTime.ParseExact(finalCmr, format, cultureInfo);
DateTime cr = DateTime.ParseExact(finalKC, format, cultureInfo);
string custDate = dt.ToString("dd/mm/yyyy");
string kcDate = cr.ToString("dd/mm/yyyy");
string id = Request.QueryString["id"];
bool success = true;
TextBoxProdComment1.Text = stock2 + "," + supplier + matTime1 + "," + prodTime1 + "," + shipTime1 + "," + custDate
+ "," + kcDate;
try
{
success = CRTopButtons.SaveProdTable(id, prodLine, stock1, supplier, billet, matTime1, matTime2, prodTime1,
prodTime2, shipTime1, shipTime2, custDate, kcDate);
}
catch (Exception e)
{
System.Diagnostics.Trace.Write(e.StackTrace);
}
return success;
}
I doubt you are assigning/clearing textbox value in page load event...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TextBox1.Text = "";
}
}
you need to put condition if (!Page.IsPostBack) before doing so
Update with your sample code, agree about the IsPostBack flag.
if (!IsPostBack)
{
BindProdTopDetails();
BindProdTable();
// BindProdComment();
}
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";`
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
I have a hiddenfield titled hdn_ven_id that is populated with the primary key value (integer) when a row in a grid is selected.
protected void rg_vendors_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridDataItem item in rg_vendors.SelectedItems)
{
hdn_ven_id.Value = item["venId"].Text;
}
}
Then I use the value from hdn_ven_id to populate #venIdFk in a SqlCommand.
protected void newDocUpldBtn_Click(object sender, EventArgs e)
{ ...
new_doc_cmd.Parameters.AddWithValue("#venIdFk", hdn_ven_id.Value);
...}
I get the following error:
Conversion failed when converting the nvarchar value '81,' to data type int.
81 is the correct primary key value, so I know that the correct value is being captured by the hidden field.
I have reviewed several threads like this one (Convert HiddenField to Integer) on how to convert the value of the hiddenfield from an nvarchar to an integer. However, I can't get the value of the hidden field to go into the database. If I add
int venidfk = int.Parse(hdn_ven_id.Value);
to newDocUpldBtn_Click I get the error "Input string was not in a correct format".
How can I convert the hiddenfield value to an integer?
Here is all of newDocUpldBtn_Click:
protected void newDocUpldBtn_Click(object sender, EventArgs e)
{
int venidfk = int.Parse(hdn_ven_id.Value);
//Save the file to the server and set the full path
int i = 0;
FileUpload fu = docFU;
string filename = fu.FileName;
string fnnnoext = System.IO.Path.GetFileNameWithoutExtension(fu.FileName);
string fnnextonly = System.IO.Path.GetExtension(fu.FileName);
if (fu.HasFile)
{
while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))
{
i++;
filename = (fnnnoext + "(" + i.ToString() + ")" + fnnextonly);
}
fu.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);
hdn_doc_path.Value = (Server.MapPath("~/Data/") + filename);
hdn_doc_path_no_ext.Value = (fnnnoext + "(" + i.ToString() + ")" + fnnextonly);
SqlConnection drap_cnxn = new SqlConnection("Data Source=WDBSVCPRD01\\SVCDB;Initial Catalog=drap;Integrated Security=True");
{
SqlCommand new_doc_cmd = new SqlCommand("Insert Into docs(docTitle, docType, docContractType, docOrg, docDept, docDesc, PriorContCd, LegCompContId, docUpldDt, docPath, docStat, venIdFk) Values(LTRIM(RTRIM(#docTitle)), LTRIM(RTRIM(#docType)), LTRIM(RTRIM(#docContractType)), LTRIM(RTRIM(#docOrg)), LTRIM(RTRIM(#docDept)), LTRIM(RTRIM(#docDesc)), LTRIM(RTRIM(#PriorContCd)), LTRIM(RTRIM(#LegCompContId)), LTRIM(RTRIM(#docUpldDt)), LTRIM(RTRIM(#docPath)), LTRIM(RTRIM(#docStat)), LTRIM(RTRIM(#venIdFk)))", drap_cnxn);
new_doc_cmd.Parameters.AddWithValue("#docTitle", docTitleTextBox.Text);
new_doc_cmd.Parameters.AddWithValue("#docType", docTypeDdl.SelectedValue);
new_doc_cmd.Parameters.AddWithValue("#docContractType", docContractTypeDdl.SelectedValue);
new_doc_cmd.Parameters.AddWithValue("#docOrg", docOrgDdl.SelectedValue);
new_doc_cmd.Parameters.AddWithValue("#docDept", docDeptDdl.SelectedValue);
new_doc_cmd.Parameters.AddWithValue("#docDesc", docDescTextBox.Text);
new_doc_cmd.Parameters.AddWithValue("#PriorContCd", priorContCdTextBox.Text);
new_doc_cmd.Parameters.AddWithValue("#LegCompContId", legCompContIdTextBox.Text);
new_doc_cmd.Parameters.AddWithValue("#docUpldDt", DateTime.Now.ToString());
new_doc_cmd.Parameters.AddWithValue("#docPath", hdn_doc_path.Value);
new_doc_cmd.Parameters.AddWithValue("#docStat", "4");
new_doc_cmd.Parameters.AddWithValue("#venIdFk", venidfk);
drap_cnxn.Open();
new_doc_cmd.ExecuteNonQuery();
drap_cnxn.Close();
if (IsPostBack)
{
ven_doc_det_upld_status_lbl.Text = "Your document was successfully uploaded.";
docTitleTextBox.Text = "";
docTypeDdl.Text = "";
docContractTypeDdl.SelectedValue = "";
docOrgDdl.Text = "";
docDeptDdl.Text = "";
docDescTextBox.Text = "";
priorContCdTextBox.Text = "";
legCompContIdTextBox.Text = "";
hdn_doc_path.Value = "";
rg_vendors.DataBind();
fv_ven_docs.DataBind();
}
else
{
ven_doc_upld_fail_lbl.Text = "Your document failed to upload. Please contact Compliance for assistance.";
}
}
}
}
It looks like your hidden field includes a comma. Either figure out where that's coming from and remove it, or use
new_doc_cmd.Parameters.AddWithValue("#venIdFk", hdn_ven_id.Value.Replace(",",""));
I'm using google map API. I have 4 destinations and I want to get their locations ordered by nearest location first followed by second nearest. I have to show on Google Map which location is 1st being the nearest and then the next nearest and so on. So far I have only successfully calculated the distance between 2 locations by using below code:
private void button1_Click(object sender, EventArgs e)
{
getDistance("DECATUR FARM ROAD CHICHESTER PO20 8JT", "UNIT 01 CLIFF REACH GREENHITHE DA9 9SW");
}
public int getDistance(string origin, string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = 0;
//string from = origin.Text;
//string to = destination.Text;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;
//string requesturl = #"http://maps.googleapis.com/maps/api/directions/json?origin=" + from + "&alternatives=false&units=imperial&destination=" + to + "&sensor=false";
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
try
{
distance = (int)o.SelectToken("routes[0].legs[0].distance.value");
return distance;
}
catch
{
return distance;
}
return distance;
//ResultingDistance.Text = distance;
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("http:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
How do I show the destinations according to their distance on google map. Any tip or pointers will be appreciated.
Please see the image, this is what I am trying to accomplish
Happy :) Enjoy Coding..
ArrayList arraylist;
List<string> adddistance = new List<string>();
List<string> getfinallist = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
string s = "UNIT 01 CLIFF REACH GREENHITHE DA9 9SW,PINETOP BIRKLANDS LANE ST ALBANS AL1 1EE,HOLYWELL HILL ST ALBANS AL1 1BT,OLD RECTORY HOLYWELL HILL ST ALBANS AL1 1BY";
button("DECATUR FARM ROAD CHICHESTER PO20 8JT", s);
}
public void button(string orign , string destination)
{
string[] words = destination.Split(',');
foreach (string word in words)
{
getDistance(orign, word);
}
sorting();
}
public int getDistance(string origin, string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = 0;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
string strdistance = (string)o.SelectToken("routes[0].legs[0].distance.value") + " , " + destination + " , ";
adddistance.Add(strdistance);
return distance;
}
public void sorting()
{
adddistance.Sort();
string getfirststring = adddistance.FirstOrDefault().ToString() ;
var vals = getfirststring.Split(',')[1];
getfinallist.Add(getfirststring.Split(',')[1]);
StringBuilder builder = new StringBuilder();
adddistance.RemoveAt(0);
foreach (string cat in adddistance) // Loop through all strings
{
builder.Append(cat); // Append string to StringBuilder
}
adddistance.Where((wors, index) => index % 2 == 0);
string result = builder.ToString();
string[] words = result.Split(',');
string[] even = words.Where((str, ix) => ix % 2 == 1).ToArray();
adddistance.Clear();
foreach (string word in even)
{ //string get = Regex.Match(word, #"^[" + numSet + #"]+$").ToString();
if (word != " ")
{
getDistance(vals, word);
}
}
sorting();
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("http:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
This is my code, I know it isn't optimal, but it works for me.
private void textBox_title1_TextChanged(object sender, EventArgs e)
{
string title1 = textBox_title1.Text;
string currentDirectory = Directory.GetCurrentDirectory();
DateTime folderDate = DateTime.Today;
string workingFolder = folderDate.ToString("ddMMMyy");
string mailingDir = ("mailingdir\\");
string indexPage = (mailingDir + "\\" + workingFolder + "\\" + "index.html");
String appdir = Path.GetDirectoryName(Application.ExecutablePath);
String title1open = Path.Combine(appdir, mailingDir, workingFolder, "index.html");
string str = File.ReadAllText(title1open, Encoding.UTF8);
str = str.Replace("[title1]", title1);
File.WriteAllText(title1open, str);
}
However, this only saves the first character that is entered into textBox_title1