C# image extension and fill in connection - c#

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();
}
}
}

Related

How to fill entry with missing when nothing was writte in in xamarin app?

I am doing Import page and if user leave some entry blank and click on import button I want to fill blank entries with Missing. I have tried that like this:
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
But sometimes it works and fill it with Missing, sometimes it doesnt work. What is wrong or is there another way to do that?
Here is full code of method:
private async void buttonImport_Clicked(object sender, EventArgs e)
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<Airplane>();
collectionPlane.IsVisible = false;
collectionAirline.IsVisible = false;
collectionLivery.IsVisible = false;
collectionRegistration.IsVisible = false;
collectionAirport.IsVisible = false;
try
{
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
if (planeEntry.Text != null && airlineEntry.Text != null)
{
var url = PhotoPick();
int i = 1;
int same = 0;
string fileName = registrationEntry.Text;
for (int b = 1; b <= GetNumberPhotos(); b++)
{
if (db.Table<Airplane>().FirstOrDefault(d => d.Id == b) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(d => d.Id == b);
string match = rowData.Registration;
if (fileName == match)
{
same++;
}
}
}
i = 1 + same;
fileName = registrationEntry.Text + "-" + i;
var thumbUrl = CreateThumbnail(await url, fileName);
var maxPK = db.Table<Airplane>().OrderByDescending(c => c.Id).FirstOrDefault();
Airplane airplane = new Airplane()
{
Id = (maxPK == null ? 1 : maxPK.Id + 1),
SearchId = planeEntry.Text + airlineEntry.Text + liveryEntry.Text + registrationEntry.Text + airportEntry.Text + datePicker.Date.ToString() + commentEntry.Text,
Plane = planeEntry.Text.ToUpper(),
Airline = airlineEntry.Text,
Livery = liveryEntry.Text,
Registration = registrationEntry.Text.ToUpper(),
Airport = airportEntry.Text.ToUpper(),
Date = datePicker.Date,
Comment = commentEntry.Text,
Url = await url,
ThumbnailUrl = thumbUrl
};
db.Insert(airplane);
await DisplayAlert("Saved", planeEntry.Text + " of " + airlineEntry.Text + " is saved.", "OK");
planeEntry.Text = "";
airlineEntry.Text = "";
liveryEntry.Text = "";
registrationEntry.Text = "";
airportEntry.Text = "";
commentEntry.Text = "";
}
else
await DisplayAlert("Fill all needed fields", "You have to fill all fields except livery and comment", "OK");
}
catch
{
await DisplayAlert("Error", "Something went wrong", "Try again");
}
}
It is probably some kind of bug or missunderstanding #Cfun have solved with if ( string.IsNullOrEmpty(liveryEntry.Text)) and it works as expected.

asynchronous datagrid view c#

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;
}
}

How to login browser based user in c#?

I designed login page by using simple asp textboxes and button.
so now i can login on the browser and restrict if user not logged in.
so issue is if i copy the home page link and paste it another browser then its going to that page where as have to go to login page so how to prevent this
Actually I want a requirement, if user logged in one browser then login and same user trying to logging in another browser then login the application and should logout previous browser's application.
below is my code
public void empLogin()
{
try
{
//open the db connection if it is closed...
if (connection.State == ConnectionState.Closed)
connection.Open();
string userName = txtUName.Text;
string password = txtPwd.Text;
command = new SqlCommand();
command.CommandText = "sp_Emplogin";
command.CommandType = CommandType.StoredProcedure;
SqlParameter outRegistrationId = command.Parameters.Add("#CompRegId", SqlDbType.Int);
outRegistrationId.Direction = ParameterDirection.Output;
outRegistrationId.Size = 7;
SqlParameter outUserType = command.Parameters.Add("#userType", SqlDbType.VarChar);
outUserType.Direction = ParameterDirection.Output;
outUserType.Size = 7;
SqlParameter outversions = command.Parameters.Add("#versions", SqlDbType.VarChar);
outversions.Direction = ParameterDirection.Output;
outversions.Size = 10;
command.Parameters.AddWithValue("#userName", userName);
command.Parameters.AddWithValue("#password", password);
command.Connection = connection;
int usercount = (Int32)command.ExecuteScalar();// for taking single value
Session["userName"] = userName;
Session["RegistrationId"] = (command.Parameters["#CompRegId"].Value).ToString();
//lblLoginMessage.Text = (command.Parameters["#CompRegId"].Value).ToString(); //Convert.ToString(Session["RegistrationId"]);
string userType = (command.Parameters["#userType"].Value).ToString();
string versions = (command.Parameters["#versions"].Value).ToString();
if (usercount == 1) // comparing users from table
{
if (chkRemember.Checked == true)
{
Response.Cookies["userName"].Value = txtUName.Text;
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["password"].Value = txtPwd.Text;
Response.Cookies["password"].Expires = DateTime.Now.AddDays(1);
}
else
{
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["password"].Expires = DateTime.Now.AddDays(-1);
}
StudentInfo _objStudentInfo = new StudentInfo(txtUName.Text, txtPwd.Text);
Session["objStudentInfo"] = _objStudentInfo;
string sKey = txtUName.Text + txtPwd.Text;
string UKey = txtUName.Text + txtPwd.Text;
string UOneKey = txtUName.Text + txtPwd.Text;
string AdminUser = Convert.ToString(Cache["sKey"]);
string User = Convert.ToString(Cache["UKey"]);
string UserOne = Convert.ToString(Cache["UOneKey"]);
if (AdminUser == null || AdminUser == String.Empty)
{
if (userType == "Admin")
{
TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
HttpContext.Current.Cache.Insert("sKey", sKey, null, DateTime.MaxValue, SessTimeOut,
System.Web.Caching.CacheItemPriority.NotRemovable, null);
if (versions == "Version2") {
Response.Redirect("~/AdminWithVersionTwo/AdminDashBoardVTwo.aspx");
}
else if (versions == "Version3")
{
}
else if (versions == "Version1")
{
Response.Redirect("~/Admin/DashBoard.aspx");
}
}
}
if (User == null || User == String.Empty)
{
if (userType == "User")
{
TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
HttpContext.Current.Cache.Insert("UKey", UKey, null, DateTime.MaxValue, SessTimeOut,
System.Web.Caching.CacheItemPriority.NotRemovable, null);
if (versions == "Version2")
{ Response.Redirect("~/UserVTwo/userDashBoardVTwo.aspx");
}
else if (versions == "Version3")
{
}
else if (versions == "Version1")
{
Response.Redirect("~/User/UserDashBoard.aspx");
}
}
}
if (UserOne == null || UserOne == String.Empty)
{
if (userType == "User1")
{
TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
HttpContext.Current.Cache.Insert("UOneKey", UOneKey, null, DateTime.MaxValue, SessTimeOut,
System.Web.Caching.CacheItemPriority.NotRemovable, null);
if (versions == "Version2")
{ Response.Redirect("~/User1VTwo/DashBoardUser1VTwo.aspx");
}
else if (versions == "Version3")
{
}
else if (versions == "Version1")
{ Response.Redirect("~/User1/User1DashBoard.aspx");
}
}
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('This User Alredy logged in');", true);
//lblDisplay.Text = "<Marquee><h1><font color=red>Already Logged IN</font></h1></marquee>";
}
}
else
{
lblLoginMessage.Text = "Invalid User Details"; //for invalid login
lblLoginMessage.Visible = true;
}
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Exception Message: " + ex.Message.Replace("'", "").Replace("\"", "") + "');", true);
}
finally //Close db Connection if it is open....
{
if (connection.State == ConnectionState.Open)
connection.Close();
command.Dispose();
}
}

Loop and List logic

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.

virtual sub domains has error

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 ?

Categories

Resources