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 ?
Related
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
Is there a way for me to link my module in all of my form i'm using c# app and this is my code. This is actually a notification bell that will notify users if he/she has/have notifications. I already linked it on homepage how am i able to do that in all other pages
private void systemNotificationREXS(HomePage module)
{
TextBox Username = (TextBox)module.FindControl("Hide_user");
Label Fullname = (Label)module.FindControl("userfullname");
Label notifLabel = (Label)module.FindControl("notifLabel");
using (con = new SqlConnection(EXCUSESLPCON))
{
using (cmd = new SqlCommand("SYSTEMNOTIFICATIONEXSLIP", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userfullname", Fullname.Text);
con.Open();
using(adp = new SqlDataAdapter(cmd))
{
using(dt = new DataTable())
{
adp.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++ )
{
int notifcount = int.Parse(dt.Rows[i]["notifcount"].ToString());
string modulename = dt.Rows[i]["modulename"].ToString();
string modulebody = modulename + "Body";
string moduleLabel = modulename + "Label";
Label namebox = (Label)module.FindControl(modulename);
if (notifcount > 0)
{
namebox.Visible = true;
namebox.Text = notifcount.ToString();
module.FindControl(modulebody).Visible = true;
try
{
module.FindControl(moduleLabel).Visible = true;
}
catch
{
notifLabel.Visible = false;
}
}
else
{
namebox.Visible = false;
module.FindControl(modulebody).Visible = false;
try
{
module.FindControl(moduleLabel).Visible = false;
}
catch
{
notifLabel.Visible = false;
}
}
}
}
}
con.Close();
}
}
}
internal void notificationSystemREXS(string fullname, string hide_user, HomePage modulename)
{
systemNotificationREXS(modulename);
}
Code to linked on homepage:
private void systemNotificationREXS()
{
Notification moduleacc = new Notification();
moduleacc.notificationSystemREXS(userfullname.Text, Hide_user.Text, this);
}
Your method does very simple job, but you have made it complicated and over dependent on the module and other stuff.
The method should return only the notification data for the user and let the caller of the method to decide what to do with the data.
Consider doing following.
public class NotificationData
{
public int NotificationCount {get;set;}
public int ModuleName {get;set;}
}
public class NotificationService
{
public static List<NotificationData> GetNotificationData(string username)
{
var notificationList = new List<NotificationData>();
using (con = new SqlConnection(EXCUSESLPCON))
{
using (cmd = new SqlCommand("SYSTEMNOTIFICATIONEXSLIP", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userfullname", Fullname.Text);
con.Open();
using(adp = new SqlDataAdapter(cmd))
{
using(dt = new DataTable())
{
for (int i = 0; i < dt.Rows.Count; i++ )
{
var notification = new NotificationData();
notification.NotificationCount = int.Parse(dt.Rows[i]["notifcount"].ToString());
notification.ModuleName = dt.Rows[i]["modulename"].ToString();
}
}
}
}
}
return notificationList
}
}
Now you should use this method from whichever page you want as following.
Let say you want to use it from HomePage. So you may write following code in Page_Load event of HomePage. (I am assuming here that HomePage is a web page and it has all the controls loaded before this code gets executed).
Label userNameLabel = (Label)this.FindControl("userfullname");
var userName = userNameLabelText;
var notificationList = NotificationService.GetNotificationData(userName);
foreach(var notification in notificationList)
{
var modulename = notification.ModuleName;
var notifcount = notification.Count;
string modulebody = modulename + "Body";
string moduleLabel = modulename + "Label";
Label namebox = (Label)this.FindControl(modulename);
if (notifcount > 0)
{
namebox.Visible = true;
namebox.Text = notifcount.ToString();
this.FindControl(modulebody).Visible = true;
try
{
this.FindControl(moduleLabel).Visible = true;
}
catch
{
notifLabel.Visible = false;
}
}
else
{
namebox.Visible = false;
this.FindControl(modulebody).Visible = false;
try
{
this.FindControl(moduleLabel).Visible = false;
}
catch
{
notifLabel.Visible = false;
}
}
}
I hope this should help you resolve your issue.
The following code is charging the card, however it is not creating the profile....any tips? I'm assuming I'm missing something, or using the wrong Type...
var opaqueData = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce };
//standard api call to retrieve response
var paymentType = new paymentType { Item = opaqueData };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // authorize and capture transaction
amount = paymentAmount,
payment = paymentType,
customer = new customerDataType()
{
type = customerTypeEnum.individual,
id = userID.ToString()
},
profile = new customerProfilePaymentType()
{
createProfile = true
}
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the contoller that will call the service
var controller = new createTransactionController(request);
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
UPDATE:
Since apparently OpaqueData is not allowed, I changed it to make the profile manually. I am getting the following Error: "Error: I00001 Successful."
// Add Payment method to Customer.
customerPaymentProfileType opaquePaymentProfile = new customerPaymentProfileType();
opaquePaymentProfile.payment = paymentType;
opaquePaymentProfile.customerType = customerTypeEnum.individual;
var request2 = new createCustomerPaymentProfileRequest
{
paymentProfile = opaquePaymentProfile,
validationMode = validationModeEnum.none,
customerProfileId = userID.ToString()
};
var controller2 = new createCustomerPaymentProfileController(request2);
controller2.Execute();
//Send Request to EndPoint
createCustomerPaymentProfileResponse response2 = controller2.GetApiResponse();
if (response2 != null && response2.messages.resultCode == messageTypeEnum.Ok)
{
if (response2 != null && response2.messages.message != null)
{
//Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId);
}
}
else
{
Utility.AppendTextToFile("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text, Server.MapPath("/pub/auth.txt"));
}
Update #2
Very confused as auth.net documentation says this code means success...so why don't I see the CIM payment method created??? RESPONSE CODE DOCS
Update #3
So I was printing out the main response message instead of the CIM request message, duh. The actual error was: "E00114 Invalid OTS Token."
Based on the the documentation, that error is usually from a used Key, so I am now generating 2 keys (One to process and One to store via CIM) but am now getting this error: "E00040 The record cannot be found."....Any ideas?
So the answer to this question is:
You can not auto create a payment profile using opaque card data, so the answer is to make it manually once you have a successful charge.
You can not use the same opaque card data to charge and store, as they are one time use, so for my web method I ended up passing 2 opaque data keys.
You have to make different calls for setting up a brand new customer and an existing customer just adding a new card. I have pasted an excerpt of my end solution below:
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? AuthorizeNet.Environment.PRODUCTION : AuthorizeNet.Environment.SANDBOX);
// define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? System.Configuration.ConfigurationManager.AppSettings["Authorize-LoginID"] : System.Configuration.ConfigurationManager.AppSettings["Authorize-LoginID-SandBox"]),
ItemElementName = ItemChoiceType.transactionKey,
Item = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? System.Configuration.ConfigurationManager.AppSettings["Authorize-TransactionKey"] : System.Configuration.ConfigurationManager.AppSettings["Authorize-TransactionKey-SandBox"])
};
if (paymentNonce.Trim() != "")
{
//set up data based on transaction
var opaqueData = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce };
//standard api call to retrieve response
var paymentType = new paymentType { Item = opaqueData };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // authorize and capture transaction
amount = paymentAmount,
payment = paymentType,
customer = new customerDataType()
{
type = customerTypeEnum.individual,
id = "YOUR_DB_USERID"
},
profile = new customerProfilePaymentType()
{
createProfile = false
}
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the contoller that will call the service
var controller = new createTransactionController(request);
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
//validate
if (response != null)
{
if (response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse.messages != null)
{
responseData.Success = true;
transactionID = response.transactionResponse.transId;
string merchID = "STORED AUTHORIZE.NET CUSTOMERID, return blank string if none!";
var opaqueData2 = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce2 };
//standard api call to retrieve response
var paymentType2 = new paymentType { Item = opaqueData2 };
customerPaymentProfileType opaquePaymentProfile = new customerPaymentProfileType();
opaquePaymentProfile.payment = paymentType2;
opaquePaymentProfile.customerType = customerTypeEnum.individual;
if (merchID == "")
{
// CREATE NEW AUTH.NET AIM CUSTOMER
List<customerPaymentProfileType> paymentProfileList = new List<customerPaymentProfileType>();
paymentProfileList.Add(opaquePaymentProfile);
customerProfileType customerProfile = new customerProfileType();
customerProfile.merchantCustomerId = "YOUR_DB_USERID";
customerProfile.paymentProfiles = paymentProfileList.ToArray();
var cimRequest = new createCustomerProfileRequest { profile = customerProfile, validationMode = validationModeEnum.none };
var cimController = new createCustomerProfileController(cimRequest); // instantiate the contoller that will call the service
cimController.Execute();
createCustomerProfileResponse cimResponse = cimController.GetApiResponse();
if (cimResponse != null && cimResponse.messages.resultCode == messageTypeEnum.Ok)
{
if (cimResponse != null && cimResponse.messages.message != null)
{
// STORE cimResponse.customerProfileId IN DATABASE FOR USER
}
}
else
{
for (int i = 0; i < cimResponse.messages.message.Length; i++)
Utility.AppendTextToFile("New Error (" + merchID + ") #" + i.ToString() + ": " + cimResponse.messages.message[i].code + " " + cimResponse.messages.message[i].text, Server.MapPath("/pub/auth.txt"));
}
}
else
{
// ADD PAYMENT PROFILE TO EXISTING AUTH.NET AIM CUSTOMER
var cimRequest = new createCustomerPaymentProfileRequest
{
paymentProfile = opaquePaymentProfile,
validationMode = validationModeEnum.none,
customerProfileId = merchID.Trim()
};
var cimController = new createCustomerPaymentProfileController(cimRequest);
cimController.Execute();
//Send Request to EndPoint
createCustomerPaymentProfileResponse cimResponse = cimController.GetApiResponse();
if (cimResponse != null && cimResponse.messages.resultCode == messageTypeEnum.Ok)
{
if (cimResponse != null && cimResponse.messages.message != null)
{
//Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId);
}
}
else
{
for (int i = 0; i < cimResponse.messages.message.Length; i++)
Utility.AppendTextToFile("Add Error (" + merchID + ") #" + i.ToString() + ": " + cimResponse.messages.message[i].code + " " + cimResponse.messages.message[i].text, Server.MapPath("/pub/auth.txt"));
}
}
}
else
{
responseData.Message = "Card Declined";
responseData.Success = false;
if (response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
}
}
else
{
responseData.Message = "Failed Transaction";
responseData.Success = false;
if (response.transactionResponse != null && response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
else
{
responseData.Message = response.messages.message[0].text;
}
}
}
else
{
responseData.Message = "Failed Transaction, Try Again!";
responseData.Success = false;
}
}
else
{
// RUN PAYMENT WITH STORED PAYMENT PROFILE ID
customerProfilePaymentType profileToCharge = new customerProfilePaymentType();
profileToCharge.customerProfileId = CustomerID;
profileToCharge.paymentProfile = new paymentProfile { paymentProfileId = PaymentID };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
amount = paymentAmount,
profile = profileToCharge
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the collector that will call the service
var controller = new createTransactionController(request);
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
//validate
if (response != null)
{
if (response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse.messages != null)
{
responseData.Success = true;
transactionID = response.transactionResponse.transId;
}
else
{
responseData.Message = "Card Declined";
responseData.Success = false;
if (response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
}
}
else
{
responseData.Message = "Failed Transaction";
responseData.Success = false;
if (response.transactionResponse != null && response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
else
{
responseData.Message = response.messages.message[0].text;
}
}
}
else
{
responseData.Message = "Failed Transaction, Try Again!";
responseData.Success = false;
}
}
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;
}
}
I have a program that upon loading the user control, adds graphics to a map layer (You shouldn't have to know much about map stuff to help, I believe the problem is with my loop logic.)
Here is my code:
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=USSW7DEVWS16\\DEVELOPER;Initial Catalog=acrGIS;Integrated Security=True";
con.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM arcObjects", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int ID = reader.GetInt32(0);
Object = reader.GetString(1);
OComment = reader.GetString(2);
OStreet = reader.GetString(3);
OCity = reader.GetString(4);
OState = reader.GetString(5);
OZip = reader.GetString(6);
OSpec = reader.GetString(7);
arcObjects.Add(new arcObject() { Object_Num = Object, Comments = OComment, Street = OStreet, City = OCity, State = OState, Zip = OZip, Spec = OSpec });
}
con.Close();
foreach (arcObject objects in arcObjects)
{
Locator InitialLocatorTask = new Locator("http://tasks.arcgisonline.com/ArcGIS/rest/services/Locators/TA_Streets_US_10/GeocodeServer");
InitialLocatorTask.AddressToLocationsCompleted += InitialLocatorTask_AddressToLocatonCompleted;
InitialLocatorTask.Failed += InitialLocatorTask_Failed;
AddressToLocationsParameters addressParams = new AddressToLocationsParameters();
Dictionary<string, string> address = addressParams.Address;
address.Add("Street", objects.Street);
address.Add("City", objects.City);
address.Add("State", objects.State);
address.Add("Zip", objects.Zip);
InitialLocatorTask.AddressToLocationsAsync(addressParams);
}
}
}
private void InitialLocatorTask_AddressToLocatonCompleted(object sender, ESRI.ArcGIS.Client.Tasks.AddressToLocationsEventArgs args)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=USSW7DEVWS16\\DEVELOPER;Initial Catalog=acrGIS;Integrated Security=True";
con.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM arcObjects", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int ID = reader.GetInt32(0);
Object = reader.GetString(1);
OComment = reader.GetString(2);
OStreet = reader.GetString(3);
OCity = reader.GetString(4);
OState = reader.GetString(5);
OZip = reader.GetString(6);
OSpec = reader.GetString(7);
CandidateListBox.Items.Clear();
List<AddressCandidate> returnedCandidates = args.Results;
foreach (AddressCandidate candidate in returnedCandidates)
{
if (candidate.Score >= 80)
{
CandidateListBox.Items.Add(candidate.Address);
if (OSpec == "Meter")
{
Graphic graphic = new Graphic()
{
Symbol = AddressLayout.Resources["WaterMeterRenderer"] as ESRI.ArcGIS.Client.Symbols.Symbol,
Geometry = candidate.Location
};
string address2 = OCity + ", " + OState + " " + OZip;
graphic.Attributes.Add("MeterNum", Object);
graphic.Attributes.Add("Comment", OComment);
graphic.Attributes.Add("Address1", OStreet);
graphic.Attributes.Add("Address2", address2);
if (candidate.Location.SpatialReference == null)
{
candidate.Location.SpatialReference = new SpatialReference(4326);
}
// if (!candidate.Location.SpatialReference.Equals(MyMap.SpatialReference))
//{
// if (MyMap.SpatialReference.Equals(new SpatialReference(102100)) && candidate.Location.SpatialReference.Equals(new SpatialReference(4326)))
// graphic.Geometry = _mercator.FromGeographic(graphic.Geometry);
// else if (MyMap.SpatialReference.Equals(new SpatialReference(4326)) && candidate.Location.SpatialReference.Equals(new SpatialReference(102100)))
// graphic.Geometry = _mercator.ToGeographic(graphic.Geometry);
// else if (MyMap.SpatialReference != new SpatialReference(4326))
// {
GeometryService geometryService = new
GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
geometryService.ProjectCompleted += (s, a) =>
{
graphic.Geometry = a.Results[0].Geometry;
};
geometryService.Failed += (s, a) =>
{
MessageBox.Show("Projection error: " + a.Error.Message);
};
//geometryService.ProjectAsync(new List<Graphic> { graphic }, MyMap.SpatialReference);
// }
//}
FeatureLayer graphicsLayer = MyMap.Layers["WaterMeterLayer"] as FeatureLayer;
graphicsLayer.Graphics.Add(graphic);
//return;
}
if (OSpec == "Lot")
{
Graphic graphic = new Graphic()
{
Symbol = AddressLayout.Resources["LotRenderer"] as ESRI.ArcGIS.Client.Symbols.Symbol,
Geometry = candidate.Location
};
string address2 = OCity + ", " + OState + " " + OZip;
graphic.Attributes.Add("MeterNum", Object);
graphic.Attributes.Add("Comment", OComment);
graphic.Attributes.Add("Address1", OStreet);
graphic.Attributes.Add("Address2", address2);
if (candidate.Location.SpatialReference == null)
{
candidate.Location.SpatialReference = new SpatialReference(4326);
}
//if (!candidate.Location.SpatialReference.Equals(MyMap.SpatialReference))
// {
// if (MyMap.SpatialReference.Equals(new SpatialReference(102100)) && candidate.Location.SpatialReference.Equals(new SpatialReference(4326)))
// graphic.Geometry = _mercator.FromGeographic(graphic.Geometry);
// else if (MyMap.SpatialReference.Equals(new SpatialReference(4326)) && candidate.Location.SpatialReference.Equals(new SpatialReference(102100)))
// graphic.Geometry = _mercator.ToGeographic(graphic.Geometry);
// else if (MyMap.SpatialReference != new SpatialReference(4326))
// {
GeometryService geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
geometryService.ProjectCompleted += (s, a) =>
{
graphic.Geometry = a.Results[0].Geometry;
};
geometryService.Failed += (s, a) =>
{
MessageBox.Show("Projection error: " + a.Error.Message);
};
//geometryService.ProjectAsync(new List<Graphic> { graphic }, MyMap.SpatialReference);
// }
// }
FeatureLayer graphicsLayer = MyMap.Layers["LotLayer"] as FeatureLayer;
graphicsLayer.Graphics.Add(graphic);
// return;
}
}
}
}
}
con.Close();
}
public void InitialLocatorTask_Failed(object sender, TaskFailedEventArgs e)
{
MessageBox.Show("Locator service failed: " + e.Error);
}
I know what it happening, the foreach loop in the UserControl_Loaded is adding things to the dictionary and then the while loop in the InitailTaskToAddress_Completed runs over and over again (9 times to be exact). What the problem is, is though while all of the graphics are being placed in the correct place, the attributes of those graphics are all the same...
For some reason it is not getting them. If you want me to clear anything up, just let me know. Also, if you would like to see my XAML, I can also show you that. I am using C# and WPF, as well as arcGIS. Thank you for your help.