so I have 3 fields that combines into 1 string and I'm currently fixing the validation so the question is how can i identify a certain textbox that is empty and the user needs to fill it up before he/she can proceed i tried this
if(string.IsNullOrEmpty(txtEYear.Text) || string.IsNullOrEmpty(txtECat.Text) || string.IsNullOrEmpty(txtEID.Text))
{
MessageBox.Show("Please fill in the missing fields");
}
Try this one.When any filed is empty focus the required field.
string message = string.empty;
message = "Please fill the ";
if(string.IsNullOrEmpty(txtEYear.Text))
{
message = message + " txtEYear ";
txtEYear.Focus();
}
if(string.IsNullOrEmpty(txtECat.Text))
{
message = message + " txtECat";
txtECat.Focus();
}
if(string.IsNullOrEmpty(txtEID.Text))
{
message = message + " txtEID";
txtEID.Focus();
}
MessageBox.Show(message+" Fields");
For that you have to use separate loop and form the message something like this:
bool isValidated = true;
StringBuilder message= new StringBuilder("Please fill the following fields: ");
if(string.IsNullOrEmpty(txtEYear.Text)
{
message.Append("Year");
isValidated = false;
}
if(string.IsNullOrEmpty(txtECat.Text))
{
message.Append("txtECat");
isValidated = false;
}
if(string.IsNullOrEmpty(txtEID.Text))
{
message.Append("ID");
isValidated = false;
}
// check all fields are valid
if(isValidated)
{
// Continue
}
else
{
MessageBox.Show(message.ToString());
}
Related
This is my logic to prevent duplicate values in the controller
public ActionResult ProviderType_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProviderTypeMasterViewModel> ProviderTypeMasterList)
{
var results = new List<ProviderTypeMasterViewModel>();
try
{
_logger.LogInformation("ProviderTypeMastersController ProviderType_Create Start");
foreach (var ProviderTypeMaster in ProviderTypeMasterList)
{
TblProviderTypeMaster ptm = new ProviderTypeMasterViewModel().ToModel(ProviderTypeMaster);
var provd = _context.TblProviderTypeMasters.Where(p => p.ProviderTypeName == ProviderTypeMaster.ProviderTypeName).ToList();
if (provd != null && provd.Count() == 0)
{
if (ProviderTypeMasterList != null && ModelState.IsValid)
{
string userID = GetUserID();
providerTypeMasterService.SaveProviderTypeMaster(ProviderTypeMaster, userID);
}
}
else
{
duplicate = true;
return this.Json(new DataSourceResult
{
Errors = "my custom error"
});
}
}
_logger.LogInformation("ProviderTypeMastersController ProviderType_Create Complete");
}
catch (Exception e)
{
_logger.LogError("ProviderTypeMastersController ProviderType_Create Failed - " + e.Message);
}
return Json(results.ToDataSourceResult(request, ModelState));
}
I show the error in an alert message using the error event of the kendo grid in my view. Now I need help on these two things.
1.) Is there any other way I could show the error message without an alert message. Like a label? If so where should I hide the label after the duplicate is removed?
2.) I want to highlight the particular value of the grid in which the user has entered the duplicate value. A change like changing the particular grid value to red when id is duplicate and remove the red color when the user changes the duplicate value to a unique value.
I am a beginner and I am stuck here. Can anyone help me with this? Thanks
Just add your error to ModelState:
public JsonResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProviderTypeMasterViewModel> ProviderTypeMasterList)
{
if (ModelState.IsValid)
{
foreach (var ProviderTypeMaster in ProviderTypeMasterList)
{
TblProviderTypeMaster ptm = new ProviderTypeMasterViewModel().ToModel(ProviderTypeMaster);
if (_context.TblProviderTypeMasters.Any(p => p.ProviderTypeName == ProviderTypeMaster.ProviderTypeName))
{
ModelState.AddModelError("ProviderTypeName", "ProviderType already exists");
}
else
{
if (ProviderTypeMasterList != null)
{
string userID = GetUserID();
providerTypeMasterService.SaveProviderTypeMaster(ProviderTypeMaster, userID);
}
}
}
}
}
return Json(results.ToDataSourceResult(request, ModelState));
In order to format Kendo Grid Column value with conditionally chosen action you can use one of the suitable examples below. For more information: How Do I Have Conditional Logic in a Column Client Template?.
UI for Javascript:
{
field: "EmployeeName", type: "string", width: "55px", title: "Employee Name",
template: "#= GetEditTemplate(data) #"
}
UI for MVC:
...
columns.Bound(t => t.EmployeeName).Title("Status Name").Template(#<text></text>)
.ClientTemplate("#= GetEditTemplate(data)#").Width("55px");
...
Here is the method used in the example:
<script>
//Change the color of the cell value according to the given condition
function GetEditTemplate(data) {
var html;
if (data.StatusID == 1) {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit1", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-success'>" +
data.EmployeeName
+ "</span>"
);
}
else {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit2", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-danger'>Cancel</span>"
);
}
return html;
}
</script>
Basically on the master page I have a method which returns a "campaign" with the params of a unique Id and a user Id. Which works fine until I click a button in a derived page.
The problem is when I click a button in a derived page the method in the master page returns "null". Even when debugging I see the correct params.
EDIT// The Method that returns null:
var campaign = campaignRepository.GetCampaignById(convertedCampaignId, user.UserId);
Master page code:
protected void Page_Load(object sender, EventArgs e)
{
string securityToken = "";
if (HttpContext.Current.Request.Cookies["SecurityToken"] != null)
{
securityToken = HttpContext.Current.Request.Cookies["SecurityToken"].Value.ToString();
}
var user = User.GetLoggedInUser(securityToken);
if (user != null)
{
var convertedCampaignId = Request.QueryString["cid"];
//If the querystring exists process ELSE force
if (!string.IsNullOrWhiteSpace(convertedCampaignId))
{
using (var campaignRepository = new CampaignRepository())
{
var campaign = campaignRepository.GetCampaignById(convertedCampaignId, user.UserId);
//Does the campaign exist from the passed in query string,
if (campaign != null)
{
ccid = "'" + campaign.ConvertedCampaignId + "'";
//Build Navigation
StringBuilder sbNav = new StringBuilder();
string nav = KTO.Common.Reader.ReadFile("/templates/html/side-nav.html");
sbNav.AppendLine(nav.Replace("{convertedCampaignId}", campaign.ConvertedCampaignId));
ltlNavItems.Text = sbNav.ToString();
ltlCampaignName.Text = "Campaign: " + "<strong>" + campaign.Name + "</strong>";
//Get campaigns for dropdown
IEnumerable<Campaign> campaigns = campaignRepository.GetCampaigns(user.UserId);
StringBuilder sbCampaigns = new StringBuilder();
string strCampaigns =
"<li title='{campaignName}' data-cid='{convertedCampaignId}' class='js-campaign-item'>" +
"<p class='name-message'><a href='/panel/c/{convertedCampaignId}/' class='campaign-lnk'>{campaignName}</a>" +
"</p>" +
"</li>";
foreach (var c in campaigns)
{
sbCampaigns.AppendLine(strCampaigns.Replace("{convertedCampaignId}", c.ConvertedCampaignId)
.Replace("{campaignId}", c.CampaignId.ToString())
.Replace("{campaignName}", c.Name));
}
}
else
{
Response.Redirect("/notifications/404/");
}
}
}
else
{
Response.Redirect("/notifications/404/");
}
}
else
{
Response.Redirect("/login/");
}
}
Derived page logic:
protected void btnInviteUsers_Click(object sender, EventArgs e)
{
if (txtEmail.Text.Trim() != "")
{
if (txtEmail.Text.Trim().Length < 75)
{
if (Common.Email.IsValidEmail(txtEmail.Text.Trim()) == true)
{
string securityToken = "";
if (HttpContext.Current.Request.Cookies["SecurityToken"] != null)
{
securityToken = HttpContext.Current.Request.Cookies["SecurityToken"].Value.ToString();
}
var user = Business.Entity.User.GetLoggedInUser(securityToken);
if (user != null)
{
try
{
using (var userRepo = new UserRepository())
{
var userInSystem = userRepo.UserExists(txtEmail.Text.Trim().RemoveHtml());
if (userInSystem == true)
{
ltlReturnMessage.Text = "Unfortunately we cannot send the request, as the user already exists.";
}
else
{
//Craft querystring
string encryptedEmail = user.EncryptedEmail;
int uid = user.UserId;
string userInviteHTML = Common.Reader.ReadFile("/templates/emails/user-invite.html");
StringBuilder sb = new StringBuilder();
sb.AppendLine(userInviteHTML.Replace("{link}", "http://localhost:52447/_user-invite/?inor-t-em=" + encryptedEmail + "&inor-d=" + uid.ToString()));
Common.Email.SendMail(txtEmail.Text.Trim(), "", "", user.FirstName + " " + user.LastName + " invited you to join x", sb.ToString());
ltlReturnMessage.Text = "Invite sent!";
}
}
}
catch
{
ltlReturnMessage.Text = "Problem sending invite, please try again.";
}
}
}
else
{
ltlReturnMessage.Text = "Are sure that's an email address? Please try again.";
}
}
else
{
ltlReturnMessage.Text = "Email Address must not exceed 75 characters.";
}
}
else
{
ltlReturnMessage.Text = "Email Address required.";
}
}
Please consider the method does return a "campaign" on any page but just not when the page posts back.
After scrutinising every last line, I noticed that my query string was duplicated. When the button click event fired from my derived page it would post back thus running my logic on the master page. I would assume it played havoc with url-rewriting.
I fixed this by adding
frmInviteUser.Action = Request.RawUrl;
within the page_load of my derived page, which would force the request of the url and not postback to the master.
This is why I was getting a null on the method, the param passed was duplicated.
Regards,
I have this in my button click event:
protected void btn_login_Click(object sender, EventArgs e)
{
authentication auth = new authentication();
bool emailExists = auth.checkEmail(System.Convert.ToString(txt_email.Text));
if (emailExists == true)
{
btn_create.Text = "Email doesnt exist";
}
else
{
btn_create.Text = "Email exists";
}
}
It sends the email to my checkEmail method which is in my authentication class:
public bool checkEmail(string email)
{
bool emailExists = false;
usersTableAdapters.UsersTableAdapter user = new usersTableAdapters.UsersTableAdapter();
users.UsersDataTable userDataTable = user.checkEmail(email);
if (userDataTable.Rows.Count == 0)
{
emailExists = false;
}
else
{
emailExists = true;
}
return emailExists;
}
The checkEmail query is "SELECT COUNT(email) AS email FROM People WHERE (email = ?)"
However when I debug, it always falls through the if(emailExists == true) statement even when the email already exists in my DB, does anyone know why?
your query you entered will always have 1 result. If you want to continue using that query, you should check the first column ("email") of the first result and check to see if that is == 0 or not.
can't add code markup in comments, so reposting how I would rewrite the checkEmail method: (assuming the how the UsersTableAdapter type is setup)
public bool checkEmail(string email)
{
usersTableAdapters.UsersTableAdapter user = new usersTableAdapters.UsersTableAdapter();
users.UsersDataTable userDataTable = user.checkEmail(email);
return userDataTable.Rows[0][0] > 0;
}
I figured out I would have to check the index of the row which in this case is 0 and then retrieve and store the value from the email column into an int
DataRow row = userDataTable.Rows[0];
int rowValue = System.Convert.ToInt16(row["email"]);
I need to know how I could handle my problem in a efficient and smart way:
I want an error-handling for user's input; I have 2 fields CustomerID and Company:
if (customerIDExists)
{
errorMessage = "...";
}
if (companyInvalid)
{
errorMessage = "...";
}
else
{
// Add user to DB
}
There could be 3 errors:
CustomerID already exists
Company has an invalid name
CustomerID AND Company is invalid at the same time
With the example above the else is for the last if (companyInvalid). How can I deal with the else that this only executes when the 1 and 2 if doesn't match?
Else if is not right because I have to check all opportunities.
Well, you could make it very explicit:
if (customerIDExists)
{
...
}
if (companyInvalid)
{
...
}
if (!customerIDExists && !companyInvalid)
{
// Add user to DB
}
Or just use the fact that you haven't got an error message:
string errorMessage = null;
if (customerIDExists)
{
errorMessage = ...;
}
if (companyInvalid)
{
errorMessage = ...; // Don't forget it could already be non-null!
}
if (errorMessage == null)
{
// No error message, so we must be fine
// Add user to DB
}
If I understand your problem the else will fire if customerIDExists is true.
Try this
if(customerIDExists)
{
errorMessage = "...";
}
else if(companyInvalid)
{
errorMessage = "...";
}
else
{
// Add user to DB
}
I've added an else if to the second condition. Now your application will check if the customerIDExists, if it doesn't it will check if the companyInvalid if it doesn't it will add the user to the database.
Now, what happens if both of these are incorrect? You'll only present on error message to your user, this will be annoying when they fix that issue and discover they have another you didn't tell them about! My suggestion would be to use a list of errors, if there aren't any then save to the database:
var errors = new List<string>();
if(customerIDExists)
{
errors.Add("Customer exists");
}
if(companyInvalid)
{
errors.Add("Company invalid");
}
if(!errors.Any())
{
// Add user to DB
}
return errors;
You can use a variable:
bool isValid = true;
if(customerIDExists)
{
errorMessage = "...";
isValid = false;
}
if(companyInvalid)
{
errorMessage = "...";
isValid = false;
}
if(isValid)
{
// Add user to DB
}
You can try old technique:
do {
if(customerIDExists)
{
errorMessage = "...";
break;
}
if(companyInvalid)
{
errorMessage = "...";
break;
}
// All is ok.
} while (false);
If you want to show all messages and don't break the proof after first error, you could use something like this:
List<string> errorMessages = new List<string>();
if (customerIDExists)
{
errorMessages.Add("...");
}
if (companyInvalid)
{
errorMessages.Add("...");
}
if (errorMessages.Count == 0) //Valid
{
}
else //Invalid
{
}
I assume you'd want to report all errors, not just the first that's encountered.
var errors = new List<string>();
if (customerIDExists)
{
errors.Add("customer id exists");
}
if (companyInvalid)
{
errors.Add("company is invalid");
}
if(errors.Any())
{
// display all error messages
}
else
{
// Add user to DB
}
I have a sample code I got from a documentation provided by a merchant. I think the code is in C#. I need to write a code for PHP but I don't have any idea about C# so I'm having a problem with this. I've tried to write a PHP code for this but it doesn't seem right.
By the way, this is a webservice kind of setup and it uses WCF to expose various endpoints. Here's the endpoint they've provided to me: http://services.scorpion.biz/Public/Leads/ExternalLead.svc
Here's the C# code:
public bool SubmitLead(string contactName, string contactNumber) {
bool outcome = false;
string message = string.Empty;
if (contactNumber.Length <= 9) {
message = "Telephone number is too short";
outcome = false;
} else if (contactNumber.Length > 11) {
message = "Telephone number is too long";
outcome = false;
} else if (contactNumber.Length == 10 && contactNumber[0] != '0') {
message = "Telephone must start with a ZERO";
outcome = false;
} else if (contactNumber.Length == 11 && contactNumber.Substring(0, 2) != "27") {
message = "Telephone must start with a 27";
outcome = false;
} else {
WSExternalLead.LeadRequestMessage request = new
WSExternalLead.LeadRequestMessage();
request.Message = “Your Keyword” + ". Contact Name: " + contactName + ".
Contact Number: " + contactNumber;
request.TelephoneNumber = contactNumber;
request.Network = “IMU”;
request.ReceivedTime = DateTime.Now;
using (WSExternalLead.ExternalLeadClient client = new WSExternalLead.ExternalLeadClient()) {
try {
WSExternalLead.LeadResponseMessage response = null;
response = client.GenerateLead(request);
if (response.Result != true) {
message = "We were unable to process your request at this
time. Error: " + response.ErrorMessage;
outcome = false;
} else {
message = "Thank you for your interest in Scorpion Legal
Protection. We will get back to you shortly.";
outcome = true;
}
} catch (FaultException fx) {
message = "We were unable to process your request at this time.
Fault: " + fx.Message;
outcome = false;
} catch (Exception ex) {
message = "We were unable to process your request at this time.
Exception: " + ex.Message;
outcome = false;
}
}
}
HttpContext.Current.Session["OUTCOME"] = outcome;
HttpContext.Current.Session["MESSAGE"] = message;
return outcome;
}
Here's the PHP code that I've written:
// Read values to variables
$username = $_GET['un'];
$usersurname = $_GET['ul'];
$phonesubmit= $_GET['up'];
$useremail = $_GET['ue'];
$aff_id = $_GET['aff'];
$unique_id = $_GET['uid'];
$rdate = date('m/d/Y G:i:s');
$rdate = date("c", strtotime($rdate));
$wsdlFile = "http://services.scorpion.biz/Public/Leads/ExternalLead.svc?WSDL";
$client = new SoapClient($wsdlFile);
$variables->TelephoneNumber = $phonesubmit;
$variables->Message = "IMU. Name: $username $usersurname. Contact Number: $phonesubmit";
$variables->Network = "IMU";
$variables->ReceivedTime = $rdate;
$result = $client->GenerateLead($variables);
$returnMessage = $result->Result;
$returnMessage = trim($returnMessage);
if ($returnMessage == ""){
$returnMessage = $result->ErrorMessage;
}
Any idea on how to solve this would be greatly appreciated. Thanks.