I try to pass the CodeNum object like parameter on query from this method:
protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
annotationView.CalloutOffset = new CGPoint(0, 0);
((CustomMKAnnotationView)annotationView).Name = customPin.Name;
((CustomMKAnnotationView)annotationView).Url = customPin.Url;
((CustomMKAnnotationView)annotationView).Address = customPin.Address;
//Add First Line
((CustomMKAnnotationView)annotationView).AlertLevel = customPin.AlertLevel;
if (customPin.AlertLevel == 1)
{
annotationView.Image = UIImage.FromFile("green.png");
}
else if (customPin.AlertLevel == 2)
{
annotationView.Image = UIImage.FromFile("yellow.png");
}
else if (customPin.AlertLevel == 3)
{
annotationView.Image = UIImage.FromFile("orange.png");
}
else if (customPin.AlertLevel == 4)
{
annotationView.Image = UIImage.FromFile("red.png");
}
//Add Second Line
((CustomMKAnnotationView)annotationView).CodeNum = customPin.CodeNum;
}
annotationView.CanShowCallout = true;
configureDetailView(annotationView);
return annotationView;
}
When user clicks on some pin on the map to take a CodeNum and pass to query to get data from database. How to pass this parameter to OnDidSelectAnnotationView method ?
void OnDidSelectAnnotationView(object sender, MKAnnotationViewEventArgs e)
{
var customPin = GetCustomPin(annotation as MKPointAnnotation);
var result = DataBaseConnection(customPin.CodeNum);
MessagingCenter.Send<object, IEnumerable<AlertLevel>>(this, "PinSelected", result);
CustomMKAnnotationView customView = e.View as CustomMKAnnotationView;
customPinView = new UIView();
if (customView.Name.Equals("Xamarin"))
{
customPinView.Frame = new CGRect(0, 0, 200, 84);
customPinView.Center = new CGPoint(0, -(e.View.Frame.Height + 75));
e.View.AddSubview(customPinView);
}
}
In OnDidSelectAnnotationView method I get an error on this line of code:
var customPin = GetCustomPin(annotation as MKPointAnnotation);
Error CS0103: The name 'annotation' does not exist in the current context (CS0103)
My GetCustomPin method looks like this:
CustomPin GetCustomPin(MKPointAnnotation annotation)
{
var position = new Position(annotation.Coordinate.Latitude, annotation.Coordinate.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
return pin;
}
}
return null;
}
This is my method who make connection to database and return list:
public IEnumerable<AlertLevel> DataBaseConnection(int mapCode)
{
string ConnectionString = "server=192.168.1.2;uid=UName;port=4443;pwd=Password;database=DBName;";
MySqlConnection Conn = new MySqlConnection(ConnectionString);
var listAlert = new List<AlertLevel>();
try
{
Conn.Open();
//replace(2) with mapCode
string query = "CALL Get_Alert_levels_Station(" + mapCode + ");";
MySqlCommand myCommand = new MySqlCommand(query, Conn);
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
var currentData = new AlertLevel()
{
dateForecast = myReader.GetDateTime(0),
levelForecast = myReader.GetInt32(1)
};
listAlert.Add(currentData);
}
}
finally
{
myReader.Close();
Conn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Database Connection", "Not Connected ..." + Environment.NewLine + ex.ToString(), "OK");
}
return listAlert;
}
How to take CodeNum from clicked pin and pass to DataBaseConnection method like a variable mapCode?
example
Message can be sent by using MessagingCenter
You can use MessagingCenter through the link below
MessagingCenter
People would like to ask you for help with the following situation.
I have a monitor where I check if certain machines are online. To make this process I have a script running on the machine feeding the database with the current time. Already on the monitor, I have an asynchronous check in Infinite loop to pick up the last updated time of the bank and update my Data Grid View. However I'm having some locking problems in this loop, someone could help follow my code
private void timer1_Tick(object sender, EventArgs e)
{
if (timerExec)
{
timerExec = false;
selectStatusRobos();
}
//timer1.Enabled = false;
}
public async void selectStatusRobos()
{
String Configuracao = "server=;user=midas_Client;password=;database=;port=3306";
string query = "SELECT i.Usuario_meta, i.Nome_robo, i.Simbolo, i.Periodo, i.Status_op, i.Operacao, i.Hora_criacao, c.Id, i.Corretora FROM int00 AS i INNER JOIN cliente00 AS c ON i.Usuario_meta = c.Usuario_meta AND i.Corretora = c.Corretora";
MySqlConnection conexao = new MySqlConnection(Configuracao);
try
{
await conexao.OpenAsync();
MySqlCommand COMANDO = new MySqlCommand(query, conexao);
MySqlDataAdapter adapter = new MySqlDataAdapter(COMANDO);
DataTable status = new DataTable();
await adapter.FillAsync(status);
bool flag_find = false;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
flag_find = false;
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_exclamation_red_46014;
dataGridView1.Rows[i].Cells["Operacao"].Value = Properties.Resources.if_op_null;
dataGridView1.Rows[i].Cells["Status_op_img"].Value = Properties.Resources.if_op_null;
for (int b = 0; b < status.Rows.Count; b++)
{
if (dataGridView1.Rows[i].Cells["Id"].Value.ToString() == status.Rows[b]["Id"].ToString()
&& dataGridView1.Rows[i].Cells["Usuario_meta"].Value.ToString() == status.Rows[b]["Usuario_meta"].ToString()
&& dataGridView1.Rows[i].Cells["Corretora"].Value.ToString() == status.Rows[b]["Corretora"].ToString()
&& dataGridView1.Rows[i].Cells["Nome_robo"].Value.ToString() == status.Rows[b]["Nome_robo"].ToString()
&& dataGridView1.Rows[i].Cells["Simbolo"].Value.ToString() == status.Rows[b]["Simbolo"].ToString().Substring(0, 3)
&& dataGridView1.Rows[i].Cells["Periodo"].Value.ToString() == status.Rows[b]["Periodo"].ToString())
{
flag_find = true;
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_tick_circle_frame_27247;
dataGridView1.Rows[i].Cells["Hora_ultima"].Value = status.Rows[b]["Hora_criacao"].ToString();
if (status.Rows[b]["Operacao"].ToString() == "1") // Compra
{
dataGridView1.Rows[i].Cells["Operacao_img"].Value = Properties.Resources.if_Raise_32535_16;
dataGridView1.Rows[i].Cells["Operacao"].Value = status.Rows[b]["Operacao"].ToString();
}
else if (status.Rows[b]["Operacao"].ToString() == "2") // Venda
{
dataGridView1.Rows[i].Cells["Operacao_img"].Value = Properties.Resources.if_Fall_32468_16;
dataGridView1.Rows[i].Cells["Operacao"].Value = status.Rows[b]["Operacao"].ToString();
}
else
{
dataGridView1.Rows[i].Cells["Operacao_img"].Value = Properties.Resources.if_op_null;
dataGridView1.Rows[i].Cells["Operacao"].Value = status.Rows[b]["Operacao"].ToString();
}
if (status.Rows[b]["Status_op"].ToString() == "2") // Off
{
dataGridView1.Rows[i].Cells["Status_op_img"].Value = Properties.Resources.if_power_off_10214;
dataGridView1.Rows[i].Cells["Status_op"].Value = status.Rows[b]["Status_op"].ToString();
}
else if (status.Rows[b]["Status_op"].ToString() == "1") // On
{
dataGridView1.Rows[i].Cells["Status_op_img"].Value = Properties.Resources.if_power_on_10215;
dataGridView1.Rows[i].Cells["Status_op"].Value = status.Rows[b]["Status_op"].ToString();
}
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_tick_circle_frame_27247;
//query = "DELETE FROM `int00` WHERE Usuario_meta = #usuario_meta AND Nome_robo = #nome_robo AND Simbolo = #simbolo AND Periodo = #periodo";
//COMANDO.CommandText = query;
//COMANDO.Parameters.Clear();
//COMANDO.Parameters.Add("#usuario_meta", MySqlDbType.VarChar).Value = status.Rows[b]["Usuario_meta"].ToString();
//COMANDO.Parameters.Add("#nome_robo", MySqlDbType.VarChar).Value = status.Rows[b]["Nome_robo"].ToString();
//COMANDO.Parameters.Add("#simbolo", MySqlDbType.VarChar).Value = status.Rows[b]["Simbolo"].ToString();
//COMANDO.Parameters.Add("#periodo", MySqlDbType.VarChar).Value = status.Rows[b]["Periodo"].ToString();
//COMANDO.ExecuteNonQuery();
//break;
}
if (dataGridView1.Rows[i].Cells["Hora_ultima"].Value != null)
{
DateTime t = Convert.ToDateTime(dataGridView1.Rows[i].Cells["Hora_ultima"].Value.ToString());
// if (dataGridView1.Rows[i].Cells["Hora_ultima"].Value.ToString() != status.Rows[b]["Hora_criacao"].ToString())
if (flag_find)
{
DateTime t1 = DateTime.Now;
DateTime t2 = DateTime.Now.AddSeconds(-30);
System.TimeSpan diff2 = t1.Subtract(t);
if (diff2.TotalSeconds >= 15 && diff2.TotalSeconds <= 45)
{
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_58_62715;
}
else if (diff2.TotalSeconds < 15 && diff2.TotalSeconds >= 0)
{
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_tick_circle_frame_27247;
}
else
{
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_exclamation_red_46014;
}
}
}
}
}
//frm = this.MdiParent as frmPrincipal;
//SendMessage send = new SendMessage(frm.SetLabel);
//send(DateTime.Now.ToString("HH:mm :ss") + " - Dados Atualizados...", null, null);
conexao.Close();
}
catch (MySqlException ex)
{
frm = this.MdiParent as frmPrincipal;
SendMessage send = new SendMessage(frm.SetLabel);
send(DateTime.Now.ToString("HH:mm :ss") + " - Tempo limite excedido na seleção", ex.Message + ex.StackTrace, Properties.Resources.if_Close_Icon_Dark_1398917, 15000);
//MessageBox.Show(ex.Message + ex.StackTrace, "Detalhes Exception");
timerExec = true;
}
catch (TimeoutException ex)
{
frm = this.MdiParent as frmPrincipal;
SendMessage send = new SendMessage(frm.SetLabel);
send(DateTime.Now.ToString("HH:mm :ss") + " - Tempo limite excedido na seleção", ex.Message + ex.StackTrace, Properties.Resources.if_Close_Icon_Dark_1398917, 15000);
timerExec = true;
}
finally
{
frm = this.MdiParent as frmPrincipal;
SendMessage send = new SendMessage(frm.SetLabel);
send(DateTime.Now.ToString("HH:mm :ss") + " - Dados Atualizados...", null, null, 15000);
conexao.Close();
timerExec = true;
}
}
With below code i am facing an error message with connection " Connection property has not been initialized. ", i recognize the problem which is file extension name over ".jpg" and "JPEG", it would not go into "if ((filess.Except(extensions).Count()) <= 0)" TRUE branch. so , the SqlCommand would not get the connection object which be assigned inside the IF-TURE branch. I tried to fix it with several way but i couldn't so can you help me with solving this problem. To make sure the problem is from this side i tried this code without any images and its works. Some inform me that For some reason the OP simply will not refactor the code into smaller testable blocks, but how i can fix it.
protected void adNewdadsbtn_Click(object sender, EventArgs e)
{
string FileExtentio = System.IO.Path.GetExtension(FileUploadImg1.FileName);
string FileExtentio2 = System.IO.Path.GetExtension(FileUploadImg2.FileName);
string FileExtentio3 = System.IO.Path.GetExtension(FileUploadImg3.FileName);
string FileExtentio4 = System.IO.Path.GetExtension(FileUploadImg4.FileName);
string FileExtentio5 = System.IO.Path.GetExtension(FileUploadImg5.FileName);
HttpCookie cookie = Request.Cookies.Get("Location");
string Location = string.Empty;
var user = Session["UsrNme"];
Location = cookie.Value;
var UsrNme = Session["UsrNme"];
if (Session["UsrNme"] != null && cookie != null)
{
using (var nySqlCon = new SqlConnection(sc))
{
if (FileUploadImg1.HasFile || FileUploadImg2.HasFile || FileUploadImg3.HasFile || FileUploadImg4.HasFile || FileUploadImg5.HasFile)
{
var filess = new[] { FileExtentio, FileExtentio2, FileExtentio3, FileExtentio4, FileExtentio5 };
filess = filess.Where(s => !string.IsNullOrEmpty(s)).ToArray();
var extensions = new[] { ".jpg", ".JPEG" };
if ((filess.Except(extensions).Count()) <= 0)
{
if (DropDownList3.SelectedValue == "no")
{
AdsWrngPanel.Visible = true;
adsstutslbel.Text = "- Please select ads status";
}
else
{
}
if (DropDownList2.SelectedValue == "no")
{
AdsWrngPanel.Visible = true;
adscondlbel.Text = "- Please select ads condition";
}
else
{
}
nySqlCon.Open();
SqlCommand addadscmd = new SqlCommand(#"INSERT INTO ads (Section, Category, UID, AdsTit, AdsDesc, Country, State,AdsDate,City, AdsPrice, Img1, img2, img3, img4,img5, Wtags, Address,Condition, Status,Maker,Year,Gear,RoomNo,Space,Shower,Garage,Currency,extlink) VALUES (#Section, #Category, #UID, #AdsTit, #AdsDesc, #Country, #State,#adsDate, #City, #AdsPrice, #Img1, #img2, #img3, #img4, #img5, #Wtags, #Address,#Condition, #Status,#Maker,#Year,#Gear,#RoomNo,#Space,#Shower,#Garage,#Currency, #extlink)", nySqlCon);
addadscmd.Parameters.AddWithValue("#Section", Secdrdoads.SelectedItem.Text);
addadscmd.Parameters.AddWithValue("#Maker", makervalue);
addadscmd.Parameters.AddWithValue("#Year", Yearvalue);
addadscmd.Parameters.AddWithValue("#Gear", Gearvalue);
addadscmd.Parameters.AddWithValue("#RoomNo", RoomNum);
addadscmd.Parameters.AddWithValue("#Space", areasize);
addadscmd.Parameters.AddWithValue("#Category", Catedrdoads.SelectedItem.Text);
addadscmd.Parameters.AddWithValue("#UID", user);
addadscmd.Parameters.AddWithValue("#AdsTit", addadstittxtbx.Text);
addadscmd.Parameters.AddWithValue("#AdsDesc", NyAdsDesc);
addadscmd.Parameters.AddWithValue("#Country", cookie.Value);
addadscmd.Parameters.AddWithValue("#State", statedrdolst.SelectedItem.Text);
addadscmd.Parameters.AddWithValue("#City", citiesdrdolst.SelectedItem.Text);
addadscmd.Parameters.AddWithValue("#AdsPrice", adsaddpristxtbx.Text);
addadscmd.Parameters.AddWithValue("#Address", addadstxtbox.Text);
addadscmd.Parameters.AddWithValue("#Shower", BathNum);
addadscmd.Parameters.AddWithValue("#Garage", garageNum);
addadscmd.Parameters.AddWithValue("#Wtags", addadswtagtxtbtn.Text);
addadscmd.Parameters.AddWithValue("#Condition", DropDownList2.SelectedItem.Text);
addadscmd.Parameters.AddWithValue("#Status", DropDownList3.SelectedItem.Text);
addadscmd.Parameters.AddWithValue("#adsDate", DateTime.Now);
addadscmd.Parameters.AddWithValue("#Currency", AddAdsCurencyLBL.Text);
addadscmd.Parameters.AddWithValue("#extlink", extlinktxtbox.Text);
string imgnouser = "/images/general/nouser.jpg";
if (FileUploadImg1.HasFile)
{
addadscmd.Parameters.AddWithValue("#Img1", FileUploadImg1.FileName);
FileUploadImg1.SaveAs(Server.MapPath("~/images/AdsImgs/" + FileUploadImg1.FileName));
}
else
{
addadscmd.Parameters.AddWithValue("#Img1", imgnouser);
}
if (FileUploadImg2.HasFile)
{
addadscmd.Parameters.AddWithValue("#Img2", FileUploadImg2.FileName);
FileUploadImg2.SaveAs(Server.MapPath("~/images/AdsImgs/" + FileUploadImg2.FileName));
}
else
{
addadscmd.Parameters.AddWithValue("#Img2", imgnouser);
}
if (FileUploadImg3.HasFile)
{
addadscmd.Parameters.AddWithValue("#Img3", FileUploadImg3.FileName);
FileUploadImg3.SaveAs(Server.MapPath("~/images/AdsImgs/" + FileUploadImg3.FileName));
}
else
{
addadscmd.Parameters.AddWithValue("#Img3", imgnouser);
}
if (FileUploadImg4.HasFile)
{
addadscmd.Parameters.AddWithValue("#Img4", FileUploadImg4.FileName);
FileUploadImg4.SaveAs(Server.MapPath("~/images/AdsImgs/" + FileUploadImg4.FileName));
}
else
{
addadscmd.Parameters.AddWithValue("#Img4", imgnouser);
}
if (FileUploadImg5.HasFile)
{
addadscmd.Parameters.AddWithValue("#Img5", FileUploadImg5.FileName);
FileUploadImg5.SaveAs(Server.MapPath("~/images/AdsImgs/" + FileUploadImg5.FileName));
}
else
{
addadscmd.Parameters.AddWithValue("#Img5", imgnouser);
}
addadscmd.ExecuteNonQuery();
nySqlCon.Close();
}
else
{
AddNwAddsWrngFrmtLbl.Text = "Error: The file should have .png or .jpg format only";
AddNwAddsWrngFrmtLbl.ForeColor = System.Drawing.Color.Red;
return;
}
}
else
{
nySqlCon.Open();
SqlCommand addadscmdNoImg = new SqlCommand(#"INSERT INTO ads (Section, Category, UID, AdsTit, AdsDesc, Country, State,AdsDate,City, AdsPrice, Wtags, Address,Condition, Status,Maker,Year,Gear,RoomNo, Space,Shower,Garage,extlink) VALUES (#Section, #Category, #UID, #AdsTit, #AdsDesc, #Country, #State,#adsDate, #City, #AdsPrice, #Wtags, #Address,#Condition, #Status,#Maker,#Year,#Gear,#RoomNo,#Space,#Shower,#Garage, #extlink)", nySqlCon);
addadscmdNoImg.Parameters.AddWithValue("#Section", Secdrdoads.SelectedItem.Text);
addadscmdNoImg.Parameters.AddWithValue("#Maker", makervalue);
addadscmdNoImg.Parameters.AddWithValue("#Year", Yearvalue);
addadscmdNoImg.Parameters.AddWithValue("#Gear", Gearvalue);
addadscmdNoImg.Parameters.AddWithValue("#RoomNo", RoomNum);
addadscmdNoImg.Parameters.AddWithValue("#Space", areasize);
addadscmdNoImg.Parameters.AddWithValue("#Category", Catedrdoads.SelectedItem.Text);
addadscmdNoImg.Parameters.AddWithValue("#UID", user);
addadscmdNoImg.Parameters.AddWithValue("#AdsTit", addadstittxtbx.Text);
addadscmdNoImg.Parameters.AddWithValue("#AdsDesc", NyAdsDesc);
addadscmdNoImg.Parameters.AddWithValue("#Country", cookie.Value);
addadscmdNoImg.Parameters.AddWithValue("#State", statedrdolst.SelectedItem.Text);
addadscmdNoImg.Parameters.AddWithValue("#City", citiesdrdolst.SelectedItem.Text);
addadscmdNoImg.Parameters.AddWithValue("#AdsPrice", adsaddpristxtbx.Text);
addadscmdNoImg.Parameters.AddWithValue("#Address", addadstxtbox.Text);
addadscmdNoImg.Parameters.AddWithValue("#Shower", BathNum);
addadscmdNoImg.Parameters.AddWithValue("#Garage", garageNum);
addadscmdNoImg.Parameters.AddWithValue("#Wtags", addadswtagtxtbtn.Text);
addadscmdNoImg.Parameters.AddWithValue("#Condition", DropDownList2.SelectedItem.Text);
addadscmdNoImg.Parameters.AddWithValue("#Status", DropDownList3.SelectedItem.Text);
addadscmdNoImg.Parameters.AddWithValue("#adsDate", DateTime.Now);
addadscmdNoImg.Parameters.AddWithValue("#extlink", extlinktxtbox.Text);
addadscmdNoImg.ExecuteNonQuery();
}
MultiView1.ActiveViewIndex = 3;
ViwMyAdsPanel.Visible = true;
CheckUsrAds();
}
}
}
I am working on Windows Phone 8 project. In my project there are 10 Events with 10 EventHandlers ReverseGeocodeQuery_QueryCompleted (1 to 10). When first EventHandler is completed it turn on second event.
What should I implement to manage those Events without so much code.
code
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(0);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_1;
myReverseGeocodeQuery.QueryAsync();
private void ReverseGeocodeQuery_QueryCompleted_1(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine("Pierwszy");
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
}
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(1);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_2;
myReverseGeocodeQuery.QueryAsync();
}
}
private void ReverseGeocodeQuery_QueryCompleted_2(object sender, QueryCompletedEventArgs<IList<MapLocation>> e)
{
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = e.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine("Drugi");
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
myReverseGeocodeQuery = new ReverseGeocodeQuery();
myReverseGeocodeQuery.GeoCoordinate = mySimulationCoordinates.ElementAt(2);
myReverseGeocodeQuery.QueryCompleted += ReverseGeocodeQuery_QueryCompleted_3;
myReverseGeocodeQuery.QueryAsync();
}
}
}
Example Solution 1
public class DataContainer
{
public string Description { get; set; }
public GeoCoordinate Coordinate { get; set; }
//public List<GeoCoordinate> mySimulationCoordinates { get; set; }
public String EnterSimulation() {
StringBuilder strRet = new StringBuilder();
List<GeoCoordinate> mySimulationCoordinates = new List<GeoCoordinate>();
mySimulationCoordinates.Add(new GeoCoordinate(51.760752, 19.458216));
mySimulationCoordinates.Add(new GeoCoordinate(51.760757, 19.458356));
mySimulationCoordinates.Add(new GeoCoordinate(51.760738, 19.458442));
mySimulationCoordinates.Add(new GeoCoordinate(51.7607, 19.458501));
mySimulationCoordinates.Add(new GeoCoordinate(51.760662, 19.458533));
var descriptions = new[] { "Pierwszy", "Drugi", "Trzeci", "Czwarty", "Piąty" }; //etc
var zipped = mySimulationCoordinates.Zip(descriptions, (coord, desc) => new DataContainer { Description = desc, Coordinate = coord });
int k = zipped.Count();
foreach (var item in zipped)
{
var currentItem = item;
using (var waitHandle = new AutoResetEvent(false))
{
var geocodeQuery = new ReverseGeocodeQuery();
geocodeQuery.GeoCoordinate = item.Coordinate;
geocodeQuery.QueryCompleted += (sender, args) =>
{
if (args.Error == null)
{
if (args.Result.Count > 0)
{
MapAddress address = args.Result[0].Information.Address;
//label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine(currentItem.Description);
str.AppendLine("House Number" + address.HouseNumber);
str.AppendLine("Street " + address.Street);
strRet.AppendLine("->");
strRet.Append(str);
waitHandle.Set();
}
}
};
geocodeQuery.QueryAsync();
waitHandle.WaitOne();
}
}
return strRet.ToString();
}
It stuck on 1st item. Is inside and wait ... wait ... can't pass to next element.
Umm... Let's see, shouldn't that be easier?
Warning: untested
public class DataContainer
{
public string Description {get;set;}
public GeoCoordinate Coordinate {get;set;}
}
var descriptions = new[] {"Pierwszy" , "Drugi" , "Trzeci" }; //etc
var zipped = mySimulationCoordinates.Zip(descriptions, (coord, desc) => new DataContainer { Description = desc, Coordinate = coord });
foreach(var item in zipped)
{
var currentItem = item;
using(var waitHandle = new AutoResetEvent(false))
{
var geocodeQuery = new ReverseGeocodeQuery();
geocodeQuery.GeoCoordinate = currentItem.Coordinates;
geocodeQuery.QueryCompleted += (sender, args) => {
if (e.Error == null)
{
if (e.Result.Count > 0)
{
MapAddress address = args.Result[0].Information.Address;
label8txt.Text = address.City.ToString() + "\n" + address.Street.ToString();
StringBuilder str = new StringBuilder();
str.AppendLine(currentItem.Description);
str.AppendLine("11" + address.HouseNumber);
str.AppendLine("17" + address.Street);
MessageBox.Show(str.ToString());
waitHandle.Set();
}
}
};
geoCodeQuery.QueryAsync();
waitHandle.WaitOne();
}
}
That should guarantee you that one event is handled after another in order.
I create a project that check the sub domain and redirect to the exist subdomain ( username ) but I can't find out why when the username is in database it can't show it and show this error :
Object reference not set to an instance of an object.
My code is this in page load :
Uri MyUrl = new Uri(Request.Url.ToString());
string Url = MyUrl.Host.ToString();
//Uri MyUrl = new Uri("http://Subdomain.Mydomain.com/");
//string Url = MyUrl.Host.ToString();
string St1 = Url.Split('.')[0];
if ((St1.ToLower() == "Mydomain") || (St1.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else if (St1.ToLower() == "www")
{
string St2 = Url.Split('.')[1];
if ((St2.ToLower() == "Mydomain") || (St2.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else
{
object Blogger = ClsPublic.GetBlogger(St2);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = #fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("#fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
}
else
{
object Blogger = ClsPublic.GetBlogger(St1);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = #fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("#fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
and my class :
public static object GetBlogger(string User)
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT fUsername FROM tblMembers WHERE fUsername = #fUsername", scn);
scm.Parameters.AddWithValue("#fUsername", User);
scn.Open();
object Blogger = scm.ExecuteScalar();
if (Blogger != null)
{
SqlCommand sccm = new SqlCommand("SELECT COUNT(fId) AS Exp1 FROM tblImages WHERE (fxSender = #fxSender) AND (fxAccepted = 1)", scn);
sccm.Parameters.AddWithValue("fxSender", Blogger);
object HasQuty = sccm.ExecuteScalar();
scn.Close();
if (HasQuty != null)
{
int Count = Int32.Parse(HasQuty.ToString());
if (Count < 10)
{
Blogger = null;
}
}
}
return Blogger;
}
Which place if my code has problem ?