I am trying to add some validation on my code to show if there is any data or not in the database:
This is my code
public PartsRequestL SavModal(int Pk, string partNum)
{
M9Lib.Models.PartsRequest PR = new PartsRequest("new", string.Empty);
double price = 0.00;
string PartCode = PR.getAltPartCode(partNum, ref price);
PartsRequestL partListModel = _partsRequestLRepository.Get(c => c.Pk == Pk);
partListModel.PartNum = PartCode;
Save();
return partListModel;
}
getAltPartCode checks if the partNum is available in the database.
partListModel.PartNum = PartCode
"PartCode" is sometimes empty because it doesn't match the PartNum
I need a validation to show if partCode has any data then carry on as normal, if not show an error before submitting (save).
Try this:
string PartCode = PR.getAltPartCode(partNum, ref price);
if(String.IsNullOrEmpty(PartCode))
{
//do whatever needs to happen when no partcode is returned
}
if(PartCode != null)
{
PartsRequestL partListModel = _partsRequestLRepository.Get(c => c.Pk == Pk);
partListModel.PartNum = PartCode;
Save();
}
Related
I am trying to design a credential retrieval process. I tried using HttpRequestBase. However, I am unable to move further. HttpRequestBase only takes string but, I have to pass int. The database has 'EmailID as string' and 'TaxID as int' Following are the two scenarios I am having trouble with.
Scenario 1:
string EmailID = Request["EmailID"];
int TaxID = Request[TaxID];
//Tax ID is having following errors
//Error CS1503: Argument 1: cannot convert from 'int' to 'string'
//Error CS0165: Use of unassigned local variable 'TaxID'
SUPRTestingDBEntities2 dbcontrol = new SUPRTestingDBEntities2();
var userAuth = (from data in dbcontrol.SUPRTesting where data.EmailID == EmailID
&& data.TaxID == TaxID
select data).FirstOrDefault();
if (userAuth != null)
{
Session["EmailID"] = userAuth.EmailID;
Session["LoginID"] = userAuth.LoginID;
return RedirectToAction("LIDAuthentication", "Corporation");
}
else if (userAuth == null)
{
return View();
}
Scenario 2, here I changed TaxID type to string (line 2), which throws the error in line 5:
string EmailID = Request["EmailID"];
string TaxID = Request[TaxID];
SUPRTestingDBEntities2 dbcontrol = new SUPRTestingDBEntities2();
var userAuth = (from data in dbcontrol.SUPRTesting where data.EmailID == EmailID
&& data.TaxID == TaxID
/*Error CS0019: Operator '==' cannot be applied to operands of type 'int' and 'string'*/
select data).FirstOrDefault();
if (userAuth != null)
{
Session["EmailID"] = userAuth.EmailID;
Session["LoginID"] = userAuth.LoginID;
return RedirectToAction("LIDAuthentication", "Corporation");
}
else if (userAuth == null)
{
return View();
}
Can someone help me with this.
What you need is converting your TaxId request to int and then your Scenario 1 should works fine, something like this:
int TaxID = Convert.ToInt32(Request[TaxID]);
However I would do this to better handle all of the possible errors:
string taxID = Request["TaxID"];
if (!String.IsNullOrEmpty(taxID) && int.TryParse(taxID, out int TaxID))
{
//Your code here, use TaxID in your query
}
Unless I've misunderstood what you're trying to do, you shouldn't need to use Request at all. You can obtain this information by adding parameters to the controller method:
public ActionResult MyMethod(string EmailID, int TaxID) // query string parameters moved to method parameters
{
SUPRTestingDBEntities2 dbcontrol = new SUPRTestingDBEntities2();
var userAuth = (from data in dbcontrol.SUPRTesting
where data.EmailID == EmailID
&& data.TaxID == TaxID
select data).FirstOrDefault();
if (userAuth != null)
{
Session["EmailID"] = userAuth.EmailID;
Session["LoginID"] = userAuth.LoginID;
return RedirectToAction("LIDAuthentication", "Corporation");
}
else if (userAuth == null)
{
return View();
}
}
protected void gv_card_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int result = 0;
CreditCard prod = new CreditCard();
GridViewRow row = gv_card.Rows[e.RowIndex];
string id = gv_card.DataKeys[e.RowIndex].Value.ToString();
string tid = ((TextBox)row.Cells[0].Controls[0]).Text;
string tnumber = ((TextBox)row.Cells[1].Controls[0]).Text;
string texpirydate = ((TextBox)row.Cells[2].Controls[0]).Text;
string tcvv = ((TextBox)row.Cells[3].Controls[0]).Text;
string tcardtype = ((TextBox)row.Cells[4].Controls[0]).Text;
string tholdername = ((TextBox)row.Cells[5].Controls[0]).Text;
result = prod.CardUpdate(int.Parse(tid), tholdername, tnumber,texpirydate, int.Parse(tcvv), tcardtype );
if (result > 0)
{
Response.Write("<script>alert('Product updated successfully');</script>");
}
else
{
Response.Write("<script>alert('Product NOT updated');</script>");
}
gv_card.EditIndex = -1;
bind();
}
}
Above is my Code but it just cant seem to update my gridview
That message is likely coming from your call to int.Parse(string), which expects the string to be a valid integer. To handle this, you can instead use int.TryParse(string, out int), which will return true or false if it is able to parse the string. If it's successful, the out parameter will contain the parsed integer value.
So you would first try to parse the integer fields. If that fails you could return an error message, and if it succeeds then you can use the integers directly in your call to CardUpdate:
int tidValue;
int tcvvValue;
if (!int.TryParse(tid, out tidValue))
{
Response.Write("<script>alert('The value specified for TID is not an integer.');</script>");
}
else if (!int.TryParse(tcvv, out tcvvValue))
{
Response.Write("<script>alert('The value specified for TCVV is not an integer.');</script>");
}
else
{
result = prod.CardUpdate(tidValue, tholdername, tnumber, texpirydate, tcvvValue, tcardtype);
if (result > 0)
{
Response.Write("<script>alert('Product updated successfully');</script>");
}
else
{
Response.Write("<script>alert('Product NOT updated');</script>");
}
}
I have build a web service with web api in c#.
I have created a method to retrieve some record from database. One column of it, is datetime. I want format it.
So I have this method to retrieve the records from database:
[NonAction]
private IQueryable<WSOmniacare.Models.AAHome.ImmaginiSecSoc.ImmaginiSecSocDTO> getSecSocImages(int? id)
{
var strItem = from u in db_data.CAMERA_SEC_SOC
where u.ID == id
select u.Image;
String imageBas64 = GetString(strItem.First());
if (id != null)
{
return from u in db_data.CAMERA_SEC_SOC
where u.ID == id
select new WSOmniacare.Models.AAHome.ImmaginiSecSoc.ImmaginiSecSocDTO()
{
image = imageBas64,
image_width = u.image_width,
image_height= u.image_height,
type = u.type,
timestamp =u.timestamp.ToString(),
dateTime = u.timestamp,
rectangle = new WSOmniacare.Models.AAHome.ImmaginiSecSoc.ImmaginiSecSocDTO.Rectangle()
{
rects = from pi in db_data.CAMERA_SEC_SOC_Rectangles
where pi.ID_SecSoc == id
select new WSOmniacare.Models.AAHome.ImmaginiSecSoc.ImmaginiSecSocDTO.Rectangle.Rect()
{
height= pi.height,
width = pi.width,
x = pi.x,
y=pi.y
}
}
};
}
return null;
}
This is the method to create a response:
public HttpResponseMessage getSecSocData(int? id = null)
{
try
{
IQueryable<ImmaginiSecSoc.ImmaginiSecSocDTO> lista = getSecSocImages(id);
List<ImmaginiSecSoc.ImmaginiSecSocDTO> listaModificata = new List<ImmaginiSecSoc.ImmaginiSecSocDTO>();
foreach (ImmaginiSecSoc.ImmaginiSecSocDTO a in lista)
{
a.timestamp = a.dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff");
listaModificata.Add(a);
}
return Request.CreateResponse(HttpStatusCode.OK, new RCamera((short)status_code.Success, "Ok", listaModificata));
}
catch (Exception e)
{
e = e.GetBaseException();
log.Error(string.Format("{0} {1}", e.Message, e.StackTrace));
return Request.CreateResponse(HttpStatusCode.InternalServerError, new RMessage((short)status_code.Exception, HttpStatusCode.InternalServerError.ToString()));
}
}
As you can see, I must cycle the list and formatting the field timestamp.
Now my question is, how can I change the code o the parse JSON to formatting my date?
You're already doing
timestamp =u.timestamp.ToString(),
in getSecSocImages method,
If the format is always the same, change it to
timestamp =u.timestamp.ToString("MM/dd/yyyy HH:mm:ss.fff"),
please help me in Linq. i am completely new in linq. please see my code below.
public Entities.ServiceResult<Customer> CustomerChangePassword(string CustomerId, string OldPassword, string NewPassword)
{
long _customerId = Convert.ToInt32(CustomerId);
byte _oldPassword = Convert.ToByte(OldPassword);
var _result = (from c in context.customers where (c.CustomerId == _customerId && c.Password == _oldPassword) select c.Password.Single).SingleOrDefault();
if (_result != null)
{
string newpassword;
newpassword = Convert.ToString(_result.Password);
newpassword = NewPassword;
context.SaveChanges();
return new Entities.ServiceResult<Customer>
{
ErrorState = 0,
Message = "Password Changed Successfully."
};
}
else
{
return new Entities.ServiceResult<Customer>
{
ErrorState = 1,
Message = "Old Password Is Wrong."
};
}
}
the above code i am doing a change password functionality. in this code c.Password is byte column, and i am passing from mobile as string. in this case how to handle this. please help me to do this
there is no need to check the password in finding the customer. That's because your are dealing with an IQueriable and you can not do this kind od job easily there. Also you should change the password in place to tell the context to save it for you.
Consider the code for Converting string to byte array as well.
With SequenceEqual method you check the equality of two arrays.
I hope the following code helps :
public Entities.ServiceResult<Customer> CustomerChangePassword(string CustomerId, string OldPassword, string NewPassword)
{
long _customerId = Convert.ToInt32(CustomerId);
byte[] _oldPassword = Encoding.ASCII.GetBytes(OldPassword);
var _result = from c in context.customers where (c.CustomerId == _customerId) select c;
if (_result == null || _result.Count() == 0)
{
return new Entities.ServiceResult<Customer>
{
ErrorState = 1,
Message = "User does not exists."
};
}
var customer = _result.First();
if (!customer.Password.SequenceEqual(_oldPassword))
{
return new Entities.ServiceResult<Customer>
{
ErrorState = 1,
Message = "Old Password Is Wrong."
};
}
customer.Password = Encoding.ASCII.GetBytes(NewPassword);
context.SaveChanges();
return new Entities.ServiceResult<Customer>
{
ErrorState = 0,
Message = "Password Changed Successfully."
};
}
Good Luck.
I have a class called Line that stores bunch of information including the ID of the Line(I have a list of lines). I am writing this information in a CSV file and I want to check if the first character of my ID has changed (hopefully to a greater number). This change signifies a new folder.
Here is what I have tried:
public bool IsNewFile (Line ln)
{
int newID = ln.getID()[0];
int oldID = 0;
if (newID != oldID)
{
oldID = newID;
return true;
}
else
{
oldID = newID;
return false;
}
}
Here is my store to csv method:
public void csvWriter (Line ln, StreamWriter stream)//Writes List to CSV
{
//some code here
if (IsNewFile(ln))
{
//MAGICAL LINE
}
else
{
//NOT MAGICAL LINE
}
stream.WriteLine(printLine);
}
here is getID()
public string getID()
{
return id;
}
With the current code I print MAGICAL LINE every time! What am I doing wrong?
You're always checking if the newID is != 0 because you always initialize oldID to 0. You should store the oldID in your Line class because as of now, setting oldID = newID will do nothing as those variables will get destroyed when the function returns its boolean.
public bool IsNewFile (Line ln)
{
int newID = ln.getID()[0];
int oldID = ln.getOldID()[0];
if (newID != oldID)
{
ln.oldID = newID;
return true;
}
else
{
ln.oldID = newID;
return false;
}
}
I'm not sure you are giving us enough information but oldID is always 0. You need to store oldID and compare it to newID somewhere.