I have to display a validation message when a user selects a date outside the allowed range. The is the code i have to work with:
public ActionResult QuickEdit(int pk, string name, string value)
{
var freeOfChargeTime = Db.FreeOfChargeTime.Find(pk);
freeOfChargeTime.ProjectExtension = freeOfChargeTime.ProjectExtension ?? Db.ProjectExtensions.Find(freeOfChargeTime.ProjectExtensionId);
if ((name == "StartDate" && DateTime.Parse(value) > freeOfChargeTime.EndDate) || (name == "EndDate" && DateTime.Parse(value) < freeOfChargeTime.StartDate))
{
ModelState.AddModelError("StartDate", "the end date must be after the start date");
}
if (name == "NumberOfDays" && double.Parse(value) <= 0)
{
ModelState.AddModelError("NumberOfDays", "Number of days must be > 0");
}
if (name == "StartDate" && DateTime.Parse(value) < freeOfChargeTime.ProjectExtension.StartDate)
{
ModelState.AddModelError("StartDate", "the free of charge period start date must be after the project extension start date");
}
if (freeOfChargeTime.ProjectExtension is IPextWithEndDate)
{
var poWithEndDate = (IPextWithEndDate)freeOfChargeTime.ProjectExtension;
if (name == "EndDate" && DateTime.Parse(value) > poWithEndDate.EndDate)
{
ModelState.AddModelError("EndDate", "the free of charge period end date must be before the project extension end date");
}
}
if (freeOfChargeTime.ProjectExtension.StatusId == ProjectExtensionStatus.Cancelled ||
freeOfChargeTime.ProjectExtension.StatusId == ProjectExtensionStatus.Disabled)
{
ModelState.AddModelError("Status", "the project extension is cancelled or disabled");
}
if (ModelState.IsValid) return XEditableUpdate(Db.FreeOfChargeTime, pk, name, value);
Response.StatusCode = 400;
var error = new Error { Message = "Error: " + ModelState.Errors() };
return Json(error.Message, JsonRequestBehavior.AllowGet);
}
This displays "Error: the free of charge period start date must be after the project extension start date\n"
I have tried:
#*#1*#
error.Message = error.Message.Split('\\').First();
#*#2*#
error.Message = error.Message.Replace("\\n", " ");
#*#3*#
string validationMessage = error.Message.Split('\\').First();
#*#4*#
string validationMessage = error.Message.Replace("\\n", " ");
#*#5*#
string validationMessage = error.Message;
validationMessage = validationMessage.Split('\\').First();
#*#6*#
string validationMessage = error.Message;
validationMessage = validationMessage.Replace("\\n", " ");
I still get the same result. Is there any way to get rid of the "\n", or work around the problem?
validationMessage.Replace("\r\n", string.Empty).Replace("\n", string.Empty).Replace("\r", string.Empty);
Use this code.
Related
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])
{
}
I'm trying to build an integration with our account termination process. On termination, set out of office it has not been set yet.
What to I put in the public main() to run - if IsOutOfOfficeSet is not set, then do nothing and it set then run SetOutofOffice.
Otherwise, if anyone has better codes to check if out of office is set, if set then ignore, otherwise set it?
class Script : ScriptBase
{
const bool bTest = false; //set to true to not set OOF
const bool bDebug = false; //set to true for more logging
ExchangeResource2010 exchange = ProvisioningSystem.Organisation.Resources["Exchange Servers"] as ExchangeResource2010;
public void main()
{
}
public bool IsOutOfOfficeSet(UserDirectoryEntry user)
{
StringBuilder sb = new StringBuilder();
try
{
foreach (PSObject o in exchange.Exec("Get-MailboxAutoReplyConfiguration", "Identity", user.DomainName, "DomainController", user.ServerName))
{
string autoReplyState = o.Properties["AutoReplyState"].Value.ToString();
DateTime startTime = Convert.ToDateTime(o.Properties["StartTime"].Value);
DateTime endTime = Convert.ToDateTime(o.Properties["EndTime"].Value);
if (bDebug)
{
sb.AppendLine(String.Format("AutoReplyState={0}", autoReplyState));
sb.AppendLine(String.Format("StartTime={0}", startTime));
sb.AppendLine(String.Format("EndTime={0}", endTime));
if (Job != null)
Job.LogAudit("AutoReplyConfiguration", sb.ToString());
else
Trace.WriteLine("AutoReplyConfiguration\r\n" + sb.ToString());
}
if (String.Compare(autoReplyState, "Disabled") == 0)
return false;
if (String.Compare(autoReplyState, "Enabled") == 0)
return true;
if (String.Compare(autoReplyState, "Scheduled") == 0)
{
//If scheduled OOO has not ended then return true
if (endTime > DateTime.Now)
return true;
}
}
}
catch (Exception ex)
{
throw new Exception("Error retrieving auto reply configuration for " + user.DomainName, ex);
}
return false;
}
public void Setoutofoffice(UserDirectoryEntry user)
{
//Out of office should be termination date plus 30 days
DateTime fromDate = DateTime.Now;
DateTime toDate = DateTime.Now.AddDays(30); //end out of office within 30 days from today
string message = Evaluator.GetString(Job, "=//Job/Task/OOOMessage");
LogAudit("Scheduling out of office for {0} from {1} to {2}", user, fromDate, toDate);
ExchangeResource exchange = ProvisioningSystem.Organisation.Resources["Exchange Servers"] as ExchangeResource;
if (exchange == null) throw new Exception("Exchange resource is NULL");
((ExchangeResource2010)exchange).ExecNoResults("Set-MailboxAutoReplyConfiguration", "Identity", user.EmailAddress, "AutoReplyState", "Scheduled", "StartTime", fromDate.ToString("MM/dd/yyyy"), "EndTime", toDate.ToString("MM/dd/yyyy"), "Confirm", false, "-InternalMessage", message, "ExternalMessage", message, "ExternalAudience", "All", "DomainController", user.ServerName);
}
}
Do you just want to write?
public void main()
{
if(!IsOutOfOfficeSet(user)){
Setoutofoffice(user);
}
}
Where user is a valid UserDirectoryEntry object
I'm having issues with displaying the variable within a Message box. What I want to do is display in a messagebox which Combobox hasn't been filled in, it will display this in a list within the messagebox and then stop the user from saving to the database. The error is stating that it is a use of an unassigned variable but I have assigned it at the top of the 'if' statement.
private void btnSaveDB_Click(object sender, EventArgs e)
{
if (cmbPolType.SelectedItem == null ||
cmbPolNum.SelectedItem == null ||
cmbTPReg.SelectedItem == null ||
cmbLossType.SelectedItem == null ||
cmbLossDesc.SelectedItem == null ||
cmbInsdFault.SelectedItem == null)
{
string polType, polNum, lossType, lossDesc, tpReg, insdFault = null;
if (cmbPolType.SelectedItem==null)
{
polType = "Policy Type";
}
if (cmbPolNum.SelectedItem==null)
{
polNum = "Policy Number";
}
if (cmbLossType.SelectedItem==null)
{
lossType = "Loss Type";
}
if (cmbLossDesc.SelectedItem ==null)
{
lossDesc = "Loss Description";
}
if (cmbTPReg.SelectedItem==null)
{
tpReg = "TP Reg";
}
if (cmbInsdFault.SelectedItem==null)
{
insdFault = "Insd at Fault";
}
MessageBox.Show("You have not selected options for the following: " + lossDesc );
}
No lossDesc is not initialized in that way as well as the other strings variables but the insdFault. (The error message points to lossDesc because is the only one used in the remainder of the code).
Instead of initializing each one, I suggest to use a simple List<string> where you add your error messages and type all of them at the end of the test
List<string> missingData = new List<string>();
if (cmbPolType.SelectedItem == null)
missingData.Add("Policy Type");
if (cmbPolNum.SelectedItem == null)
missingData.Add("Policy Number");
if (cmbLossType.SelectedItem == null)
missingData.Add("Loss Type");
if (cmbLossDesc.SelectedItem == null)
missingData.Add("Loss Description");
if (cmbTPReg.SelectedItem == null)
missingData.Add("TP Reg");
if (cmbInsdFault.SelectedItem == null)
missingData.Add("Insd at Fault");
if(missingData.Count > 0)
{
MessageBox.Show("You have not selected options for the following: " +
Environment.NewLine +
string.Join(Environment.NewLine, missingData.ToArray()));
}
else
{
... save to database ? ....
}
This removes the need to use and initialize a bunch of string variables and uses the string.Join method to get the whole error message in a single string with each error on a separate line.
I have developed text boxes to add date range to pick specific records within that date range.
I have written IF ELSE for that if Both text boxes are empty then SHOW ERROR MESSAGE but problem is that when i first time call page then it shows same error. I know why because in first attempt text boxes are empty but how to control this ?
public ActionResult ShowMyAtdByDate(String DateFrom, String DateTo)
{
int empId = 0;
int.TryParse((string)Session["Employee"], out empId); // parse variable to int and saves the result in empId
// IEnumerable<GetMyAtd_DateResult> MyAtdRecord = DataContext.GetMyAtd_Date(DateFrom,DateTo,empId).ToList();
if (DateFrom != "" && DateTo == "" && empId > 0)
{
IEnumerable<GetMyAtd_DateResult> MyAtdRecord = DataContext.GetMyAtd_Date(DateFrom,null, empId).ToList();
ViewBag.Dates = "Records for" + " " + DateFrom;
return View(MyAtdRecord);
}
else if (DateFrom == "" && DateTo != "" && empId > 0)
{
IEnumerable<GetMyAtd_DateResult> MyAtdRecord = DataContext.GetMyAtd_Date( null, DateTo, empId).ToList();
ViewBag.Dates = "Records for" + " " + DateTo;
return View(MyAtdRecord);
}
else if (DateFrom != "" && DateTo != "" && empId > 0)
{
IEnumerable<GetMyAtd_DateResult> MyAtdRecord = DataContext.GetMyAtd_Date(DateFrom, DateTo, empId).ToList();
ViewBag.Dates = "Records from" + " " + DateFrom + " " + "to" + " " + DateTo;
return View(MyAtdRecord);
}
else if (DateFrom == "" && DateTo == "" && empId > 0)
{
IEnumerable<GetMyAtd_DateResult> MyAtdRecord = DataContext.GetMyAtd_Date(null, null, empId).ToList();
ViewBag.Dates = "No dates selection";
return View(MyAtdRecord);
}
else if(empId <=0 )
{
return RedirectToAction("IsAuth_Page","Home");
}
return View();
}
View:
#{
var grid = new WebGrid(ViewData.Model, rowsPerPage: 25);
}
#if (Model.Count > 0)
{
<div id="AllMyAtd_ByDate">
#grid.GetHtml(columns: grid.Columns(
grid.Column("EmplID", "Employee ID"),
grid.Column("EmplName", "Employee Name"),
grid.Column("ShiftID", "Shift ID"),
grid.Column("DateVisited", "Date of Visit"),
grid.Column("InTime", "In Time"),
grid.Column("TimeOut", "Time Out"),
grid.Column("OverTime", "Over Time"),
grid.Column("TotalWorkingTime", "Total Working Time")
))
</div>
}
else
{
<h4 class="error">Sorry Record Doesn't Exist for selected date(s)</h4>
}
When i first browse to this page then this appears which actually should appear only if i leave both text boxes empty.
The first time an user enters this page, it will be as a GET-request. You could remove this logic out of the GET-method (because it doesn't need to be executed when it is the first time) and put it in the POST-method, since this is the HTTP-method that will be used when the user has submitted the form.
[HttpGet]
public ActionResult ShowMyAtdByDate()
{
int empId = 0;
int.TryParse((string)Session["Employee"], out empId);
if (empId <= 0)
{
return RedirectToAction("IsAuth_Page", "Home");
}
return View();
}
[HttpPost]
public ActionResult ShowMyAtdByDate(string dateFrom, string dateTo)
{
if (dateFrom != "" && dateTo == "" && empId > 0)
{
...
}
else if (dateFrom == "" && dateTo != "" && empId > 0)
{
...
}
etc...
}
And make sure in your view your form has the method POST
I have the following code which creates a Task in Salesforce and then tracks a user's browsing history and stores it in SalesForce. Currently, it displays each and every page the user has browsed as an individual entry. I want to group all those entries together in the Browsing_History__c object instead of task being created every time a user visits a page.
Any help would be appreciated..I am not familiar with SF very much. :)
private void CreateTaskInSF(string id, string type, string details, string description)
{
// if there's a similar Event in the past 2 hours, don't add it
QueryResult qr = null;
try // get events from past 2 hours
{
qr = Binding.query("Select Details__c from Task WHERE WhoId='" + id + "' and Type__c='" + type + "' and CreatedDate > " + DateTime.UtcNow.AddHours(-2).ToString("s") + "Z");
}
catch (Exception e)
{
return;
}
bool logged = false;
if (qr != null) // if there are Tasks in past 2 hours
{
sforce.sObject[] browsing = qr.records;
if (browsing != null)
{
// iterate through events to make sure the new Task isn't logged
for (int i = 0; i < browsing.Length; i++)
{
Task currTask = (Task)browsing[i];
if (currTask.Details__c == details)
{
if (description != "") // is there a description to check for?
{
string oldTaskDescription = "";
if (currTask.Description != null)
oldTaskDescription = currTask.Description;
if (oldTaskDescription == description) // if there is a description match
logged = true;
}
else
logged = true; // there's no description, so check only on details field
}
}
}
}
if (logged == true)
{
return; // if Activity is already logged, don't log it again
}
else if (type == "Browsing")
{
QueryResult browsingQuery = null;
try // get events from past 2 hours
{
browsingQuery = Binding.query("Select Web_Browsing__c from Task WHERE WhoId='" + id + "' and Subject='" + type + "' and Details__c='" + details + "' and CreatedDate > " + DateTime.UtcNow.AddHours(-2).ToString("s") + "Z");
}
catch
{
}
Boolean createNewBrowsing = false;
if (browsingQuery != null) // if there are Tasks in past 2 hours
{
sforce.sObject[] webBrowsing = browsingQuery.records;
if (webBrowsing != null)
{
//find correct object and update Browsing_History__c
//Binding.update
}
else
{
createNewBrowsing = true;
}
}
else
{
createNewBrowsing = true;
}
if (createNewBrowsing)
{
Web_Browsing__c newTask = new Web_Browsing__c();
newTask.Lead__c = id;
newTask.Browsing_History_255__c = details;
newTask.Type__c = type;
newTask.Browsing_History__c = details;
newTask.CreatedDate = DateTime.Now;
//if(type == "Browsing") newTask. = details;
//SaveResult[] createResult = Binding.create(new sObject[] { newTask });
try
{
SaveResult[] createResult = Binding.create(new sObject[] { newTask });
}
catch (Exception e)
{
return;
}
}
}
else
{
// if this new Activity isn't logged, then create a new Activity Task
sforce.Task newTask = new sforce.Task();
newTask.WhoId = id;
newTask.Subject = type;
newTask.Details__c = details;
if (description != "") newTask.Description = description;
newTask.Status = "Completed";
newTask.Priority = "Normal";
newTask.ActivityDate = DateTime.Now;
newTask.ActivityDateSpecified = true;
// insert it
try
{
SaveResult[] createResult = Binding.create(new sforce.sObject[] { newTask });
}
catch (Exception e)
{
return;
}
}
}
You'll need to update your query to ask for the browsing history object and update the code to create a browsing history object instead of a task.
If you haven't already, review the Web Services API docs, it has examples for querying and creating in java/c#.