Stop Code executing in query - c#

I am checking for duplicates and it finds them and the If(isDuplicate) all works fine.
But the code continues and does all the submit because I am not telling it to stop.
How would I do this ? to stop and throw the error panel which it does but not submit?
_db.tbl_Localities.InsertOnSubmit(locality);
bool isDuplicate = _db.tbl_Localities
.Any(x => x.Locality == txt_Locality.Text);
if (isDuplicate)
{
pnl_Message.Visible = true;
lbl_message.Text = " Duplicate entry!";
txt_Locality.Text = "";
}
// Save
// ====
_db.SubmitChanges();

You should handle else part of condition, or raise an exception if it's unexpected situation for your program:
_db.tbl_Localities.InsertOnSubmit(locality);
bool isDuplicate = _db.tbl_Localities
.Any(x => x.Locality == txt_Locality.Text);
if (isDuplicate)
{
pnl_Message.Visible = true;
lbl_message.Text = " Duplicate entry!";
txt_Locality.Text = "";
}
else
{
// Save
// ====
_db.SubmitChanges();
}

Use return; in the if statement.

Related

I wanted to create different notification message. 1. Record successfully updated, 1. Updating Record Failed, 3. No changes were made in the record

My previous codes was:
protected async void UpdateHandler(GridCommandEventArgs args)
{
iLogBlazor.Domain.Models.Project project = (iLogBlazor.Domain.Models.Project)args.Item;
if (project != null)
{
try
{
project.Pic = null;//load the correct user based on the new PicUserId
await ProjectService.UpdateForOtherTables(project);
int i = Projects.FindIndex(x => x.Id == project.Id);
var updatedProject = await ProjectService.GetByProjectIdAsync(project.Id); //project;
int i2 = OriginalProjects.FindIndex(x => x.Id == updatedProject.Id);
var currentSelectedItems = new List<iLogBlazor.Domain.Models.Project>(SelectedItems);
int selectedItemIndex = currentSelectedItems.FindIndex(x => x.Id == updatedProject.Id);
if (i != -1)
{
// update the selected items collection
currentSelectedItems[selectedItemIndex] = updatedProject;
SelectedItems = currentSelectedItems;
// The actual Update operation for the view-model data. Add your actual data source operations here
OriginalProjects[i2] = updatedProject;
Projects[i] = updatedProject;
Grid?.Rebind();
}
NotificationService.Success("Record successfully updated.");
YAOptions = OriginalProjects.Select(p => p.Ya).Distinct().ToList();
}
catch (Exception e)
{
NotificationService.Error("Updating record failed.");
}
}
}
I am trying to modify with the codes below but I am always getting the success response even when I am not updating something.
{
iLogBlazor.Domain.Models.Project project = (iLogBlazor.Domain.Models.Project)args.Item;
if (project != null)
{
bool isSuccessful = false;
bool isFailed = false;
iLogBlazor.Domain.Models.Project originalProject = project;
try
{
project.Pic = null;//load the correct user based on the new PicUserId
await ProjectService.UpdateForOtherTables(project);
int i = Projects.FindIndex(x => x.Id == project.Id);
var updatedProject = await ProjectService.GetByProjectIdAsync(project.Id); //project;
int i2 = OriginalProjects.FindIndex(x => x.Id == updatedProject.Id);
var currentSelectedItems = new List<iLogBlazor.Domain.Models.Project>(SelectedItems);
int selectedItemIndex = currentSelectedItems.FindIndex(x => x.Id == updatedProject.Id);
if (i != -1)
{
// update the selected items collection
currentSelectedItems[selectedItemIndex] = updatedProject;
SelectedItems = currentSelectedItems;
// The actual Update operation for the view-model data. Add your actual data source operations here
OriginalProjects[i2] = updatedProject;
Projects[i] = updatedProject;
Grid?.Rebind();
// Check if any changes were made to the Project
bool changesMade = !Object.ReferenceEquals(originalProject, updatedProject);
if (changesMade)
{
isSuccessful = true;
}
}
}
catch (Exception e)
{
isFailed = true;
}
if (isSuccessful)
{
NotificationService.Success("Record successfully updated.");
}
else if (isFailed)
{
NotificationService.Error("Updating record failed.");
}
else
{
NotificationService.Error("No changes were made to the record.");
}
YAOptions = OriginalProjects.Select(p => p.Ya).Distinct().ToList();
}
}
both of the above code is always returning a response to success update. even when i am just triggering the row and not changing anything. I would really want to get three different notification message based on the condition i have provided above.

CSV-injection in export functionality in asp.net application

While submitting a form, in one of the fields i am inserting vulnerable characters like =cmd|'/C calc'!A0. So in security terms it is termed as CSV-injection in export functionality
I have written code like this for above error. but its not working
[WebMethod]
public static string SaveRecord(RRSOCSaving RRSOCSaving, string Indication)
{
string strReturnId = "";
string strAppURL = ConfigurationManager.AppSettings["AppUrl"].ToString();
string strmail_Content = "";
CommonDB commonObj = new CommonDB();
try
{
// Cross site scripting issue code tag..!!
if (commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_CODE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.CITY)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_1)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_2)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SUPERVISOR_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_NAME_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_MOBNO_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_MOBNO))
{
strReturnId = "Something went wrong due to malicious script attack..!!!";
}
else
{
if (RRSOCSaving.ROLE_ASSIGNED == "SLP State Head")
{
bool blnState1 = Array.Exists(RRSOCSaving.ASSIGNED_STATE.ToString().ToUpper().Split(','), element => element == (RRSOCSaving.STATE).ToString().ToUpper());
if (blnState1)
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
}
else
{
strReturnId = "User can add data for " + RRSOCSaving.ASSIGNED_STATE + " only";
}
}
else if (RRSOCSaving.ROLE_ASSIGNED == "NHQ Admin")
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
//strReturnId = "Record Saved Succesfully";
}
}
// strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving);
}
catch (Exception)
{
throw;
}
return strReturnId;
}
public bool HackerTextExistOrNot(string Text)
{
bool flgValid = false;
Regex htmltags = new Regex(#"<.*?>");
Match chkMatch = htmltags.Match(Text);
if (chkMatch.Success)
{
flgValid = true;
}
return flgValid;
}
Please suggest how to stop this error.
Your HackerTextExistOrNot method is checking for the existance of html tags.
You should however check if the text is starting with one of the formular triggering characters.
To protect yourself against the injection attack ensure that none of the given text begins with any of the following characters:
Equals to ("=")
Plus ("+")
Minus ("-")
At ("#")
So you can check like this:
var attackChars = new char[]{'=','+','-','#'};
if(attackChars.Contains(text[0])
{
}

error in do while loop

public Login ClickGetStatus()
{
//IWebElement btnGetStatus = driver.FindElement(By.XPath("//*[contains(#id,'GetStatus')]"));
do
{
buttonName_GetStatus[0] = "abc";
Thread.Sleep(3000);
bool is_displayed =
wrapper.IsElementDisplayed(
driver.FindElement(By.XPath("//*[contains(#id,'GetStatus')]")));
//bool IsElementDisplayed = driver.FindElement(By.XPath("//*[contains(#id,'GetStatus')]")).Displayed;
if (is_displayed)
{
//wrapper.Click(btnExecute);
string getnameofbutton1 =
driver.FindElement(
By.XPath("//*[contains(#id,'GetStatus')]")).GetAttribute("id");
Console.WriteLine("Name of the button is : " + getnameofbutton1);
buttonName_GetStatus = getnameofbutton1.Split('_');
driver.FindElement(
By.XPath("//*[contains(#id,'GetStatus')]")).Click();
}
else
{
Console.WriteLine("Element is not displayed");
}
}
while (buttonName_GetStatus[0] == "GetStatus");
return this;
}
Below is the Logic for the above code
Checks for the button called Get Status
if it finds the button Get Status then clicks on it
i have used contains in the xpath as the element id for that button changes dynamically.
The above code runs fine and clicks on the Get Status button but doesn't come out from the loop when the name of the Get Status button changes to View Result and still searches for Get Status button
If the expected ID of the button after being updated is "ViewResult", then you can update your condition to use that.
while (buttonName_GetStatus[0] != "ViewResult");
This will keep looping round whilst the button does not equal "ViewResult".
Is this the behavior you're trying to achieve?
public Login ClickGetStatus()
{
//IWebElement btnGetStatus = driver.FindElement(By.XPath("//*
[contains(#id,'GetStatus')]"));
do
{
buttonName_GetStatus[0] = "abc";
Thread.Sleep(3000);
var elements = driver.FindElements(By.XPath("//*[contains(#id,'GetStatus')]"));
var is_displayed = elements.Count > 0;
//bool IsElementDisplayed = driver.FindElement(By.XPath("//*[contains(#id,'GetStatus')]")).Displayed;
if (is_displayed)
{
//wrapper.Click(btnExecute);
string getnameofbutton1 =
driver.FindElement(
By.XPath("//*[contains(#id,'GetStatus')]")).GetAttribute("id");
Console.WriteLine("Name of the button is : " + getnameofbutton1);
buttonName_GetStatus = getnameofbutton1.Split('_');
driver.FindElement(
By.XPath("//*[contains(#id,'GetStatus')]")).Click();
}
else
{
Console.WriteLine("Element is not displayed");
}
}
while (buttonName_GetStatus[0] != "ViewResult");
return this;
}
I think problem might be here, especially when you check if isDisplayed == true then this line buttonName_GetStatus = getnameofbutton1.Split('_'); overrides array so that infinitive loop appeared.

How to fix a boolean method that returns true everytime asp.net

I designed my webpage to read a data string then display the results on labels in an html table. I am attempting to highlight the row that my database reads as a current order. My only problem is only one record is set to be active but they all highlight as if they were active. I use an array to set my data and I also use the label to get the ID I need (all is in code below). I have posted my method and where I use it in the asp page load. How can I fix my method to return correctly?
The implementing of the method in page load
if (lineData.IsCurrentOrderFind(L68.Text))
{
myTable.Rows[1].Cells[0].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[1].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[2].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[3].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[4].BgColor = "#FE2E2E";
}
Here is method that label above gets passed to
public bool IsCurrentOrderFind(string itemNumber)
{
StringBuilder sqlString = new StringBuilder();
sqlString.Append("SELECT * ");
sqlString.Append("FROM WorkOrder ");
sqlString.Append("WHERE LineNumber = " + ConfigurationManager.AppSettings["Line"] + " AND LineCompleted = 0 AND (ScaleGroup LIKE '%1' OR ScaleGroup LIKE '%3') ");
sqlString.Append(" AND CaseGenNum6 = #CaseGenNum6");
SqlDataReader reader = null;
SqlConnection dbConn = App_Code.DBHelper.getConnection();
SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("#CaseGenNum6", itemNumber) };
try
{
reader = App_Code.DBHelper.executeQuery(dbConn, sqlString.ToString(), parameters);
while (reader.Read())
{
IsCurrentOrder = (reader["IsCurrentOrder"] != DBNull.Value && !string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())) ? true : false;
}
reader.Close();
reader.Dispose();
dbConn.Close();
dbConn.Dispose();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (dbConn != null)
{
try { dbConn.Close(); dbConn.Dispose(); }
catch { }
}
if (reader != null)
{
try { reader.Close(); reader.Dispose(); }
catch { }
}
}
if (IsCurrentOrder == true) I realize this is not necessary
{
return true;
}
else
{
return false;
}
}
The problem could be with this expression:
!string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())
Instead of calling ToString(), try simply casting it to a string:
!string.IsNullOrEmpty((string)reader["IsCurrentOrder"])
Possibly even better (the previous line might throw an exception if it's not really a string):
!string.IsNullOrEmpty(reader["IsCurrentOrder"] as string)
The reason being is that if the string is really null, calling ToString() will return a non-null string "null".
IsCurrentOrder is not declared locally. It seems to be declared at a higher scope. When you enter this function, nothing is initializing the variable (back to false). So, it is remaining at its last setting. Try this code instead:
public bool IsCurrentOrderFind(string itemNumber)
{
bool IsCurrentOrder = false;
//and the rest of your source code
the line
IsCurrentOrder = (reader["IsCurrentOrder"] != DBNull.Value && !string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())) ? true : false;
}
It's not actually checking the value of the field, only that it's not null or empty.
Try
if(
(reader["IsCurrentOrder"] != DBNull.Value
&&
!string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString()))
)
{
IsCurrentOrder = reader["IsCurrentOrder"];
}
else
IsCurrentOrder = false;
I think there is a lot of refactoring you could do to this method though that will simplify the logic.

Entity Framework not actually saving changes

I've just started foraying into EF, and I'm trying to get my head around it (Generally easy enough). However for some reason it's not actually saving the results, though it appears to be maybe cacheing the values for a time, and then rolling back to the previous values?
using (IAPlayerEntities IAPE = new IAPlayerEntities()) {
ObjectSet<Player> Players = IAPE.Players;
if (Players.Count() > 0) {
Player currentPlayer = new Player();
bool LoggedIn = false;
Players.DefaultIfEmpty(null);
while (!LoggedIn) {
Console.WriteLine("Please enter your Username:");
string username = Console.ReadLine();
Console.WriteLine("Please enter your Password:");
string password = MaskLine();
currentPlayer = Players.FirstOrDefault(r => r.Password == password && r.Name == username);
LoggedIn = (currentPlayer != null);
if (!LoggedIn) {
Console.WriteLine("{0}Invalid combination, please try again.", Environment.NewLine);
}
}
Console.WriteLine("{0}Please choose your colony.", Environment.NewLine);
foreach (Colony col in currentPlayer.Colonies) {
Console.WriteLine(#"{0}{1}:{0}{2}{0}Level {3}", Environment.NewLine, col.ID, col.Name, col.Level);
}
Console.WriteLine();
int colID = -1;
string colStr = Console.ReadLine();
while (!int.TryParse(colStr, out colID) || !currentPlayer.Colonies.Any(e => e.ID == colID)) {
if (colStr.ToLower() == "q") {
Console.WriteLine("Goodbye!");
return;
}
Console.WriteLine("{0}Invalid Colony. Please try again.", Environment.NewLine);
colStr = Console.ReadLine();
}
Console.WriteLine("Please enter a new name for the colony:");
string colName = Console.ReadLine();
bool b = IAPE.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified).Any();
currentPlayer.Colonies.First(e => e.ID == colID).Name = colName;
int change = IAPE.SaveChanges();
if (change >= 1) {
Console.WriteLine("{0}Colony has been renamed.", Environment.NewLine);
} else {
Console.WriteLine("{0}Colony could not be renamed.", Environment.NewLine);
}
} else {
Console.WriteLine("No Registered users");
}
}
Ignore the über secure login, it's only in there to get a player entity from it for testing.
the bool b is set to true before the save, and then if I use the debugger to run the same line in the "Immediate Window" pane then it shows false. Which to me, means it saved? And If I re-run the application after it's closed then the changed value is in place. But eventually it will return to the previous value, and if I check the database straight after it still shows the original name, so I'm not quite sure what's going on here?
It's running on VCS2010, so Framework 4.
Thanks, Psy
Checked the SQL going over to the database, and it's fine, after some investigation, turned out that I had a copy of the database within the project, which was over-riding the one in the output everytime I rebuilt it.
IAPE.Savechanges() at some point.

Categories

Resources