i'm developing an app for a veterinary clinic in winforms.
i have this table named "petOwner" which gives a foreign key to the table "Pets". now when im trying to register a pet i get information of both the owner and the pet from the user,enter code here the owner is saved successfully (savechanges()!=0) but when it comes to pet it gives me the entity validation err on the following code where triple starred:
if (gpbx_ownerInfo.Enabled==true)
{
objOwner.name = txt_ownerName.Text;
objOwner.family = txt_ownerFamily.Text;
objOwner.mobile = txt_ownerMobile.Text;
objOwner.tel = txt_ownerTel.Text;
objOwner.address = rtxt_ownerAdrs.Text;
objOwner.comment = rtxt_ownerCmnt.Text;
if (txt_ownerName.Text != "" & txt_ownerFamily.Text != "" & txt_ownerMobile.Text != "" & rtxt_ownerAdrs.Text != "")
{
if (objDB.Tbl_ownerInfo.Where(x => x.name == txt_ownerName.Text & x.family == txt_ownerFamily.Text & x.mobile == txt_ownerMobile.Text).ToList().Count == 0)
{
objDB.Tbl_ownerInfo.Add(objOwner);
}
else
{
MessageBox.Show("This keeper already exist\nTry finding them using the 'Keeper already Registered' link.");
}
}
else
{
MessageBox.Show("Fill the starred items please");
txt_ownerName.BackColor = Color.MistyRose;
txt_ownerFamily.BackColor = Color.MistyRose;
txt_ownerMobile.BackColor = Color.MistyRose;
rtxt_ownerAdrs.BackColor = Color.MistyRose;
}
if (objDB.SaveChanges() != 0)
{
gpbx_ownerInfo.Enabled = false;
objPet.ownerID = objDB.Tbl_ownerInfo.Max(s => s.ID);
objPet.name = txt_petName.Text;
objPet.species = txt_petSpecies.Text;
objPet.breed = txt_petBreed.Text;
objPet.birthDate = dt_petBDate.Value.Date;
if (cbox_petGender.Text == "Male")
{
objPet.gender = true;
}
else if (cbox_petGender.Text == "Female")
{
objPet.gender = false;
}
else
objPet.dominatingClr = txt_petClr.Text;
objPet.distinguishingMarks = rtxt_petMarks.Text;
if (txt_petName.Text != "" & txt_petSpecies.Text != "" & cbox_petGender.Text != "" & txt_petClr.Text != "" & cbox_petGender.Items.Contains(cbox_petGender.Text))
{
if (objDB.Tbl_Pets.Where(p => p.name == txt_petName.Text & p.species == txt_petSpecies.Text & p.breed == txt_petBreed.Text & p.dominatingClr == txt_petClr.Text).ToList().Count == 0)
{
objDB.Tbl_Pets.Add(objPet);
***if (objDB.SaveChanges() != 0)***
{
gpbx_ownerInfo.Enabled = true;
textCleaner();
MessageBox.Show("Pet registered successfully");
}
}
else
{
gpbx_ownerInfo.Enabled = false;
MessageBox.Show("This pet already exists");
}
now i know a lot of people don't get this in winforms they usually face it in asp.net
and i've searched a lot but every body has given answers on asp
here is the exception:enter image description here
Related
I have a datatable which fetches some records. So there is one column name as UPDATED_STATUS. In that column either Pre Hoto or Post Hoto value will come.
So what I want is, Either any one of those values should be their in that column then only the it should move ahead otherwise it should prompt alert as
Either Pre Hoto or Post Hoto can be their
Below is sample image for reference
Below is the code for getting the datatable with the UPDATED_STATUS column
if (strFlag == "")
{
dtStatus = GET_STATUS_FROM_SAPID_FOR_HOTO(dtExcelRows.Rows[i]["Current SAPID"].ToString());
if (dtStatus == null && dtStatus.Rows.Count < 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
}
else
{
dtExcelRows.Rows[i]["UPDATED_STATUS"] = dtStatus.Rows[0][1].ToString();
dtExcelRows.AcceptChanges();
}
}
Your current check (if (dtStatus == null && dtStatus.Rows.Count < 0)) is wrong:
when dtStatus is null, you continue checking dtStatus.Rows, which throws a nullref exception (you just found out that it was null);
Rows.Count is never less than zero.
Try if (dtStatus == null || dtStatus.Rows.Count == 0) to check whether there is no status at all (it is null) or no status rows (count is zero). The || will prevent checking for dtStatus.Rows when it was found that dtStatus is null.
&& means that both sides must be true at the same time.
|| means that at least of the sides must be true (both true is also fine).
Both don't evaluate the second test when the first already decided the outcome (false && whatever is always false, true || whatever is always true)
Are you looking for like this !
foreach (DataRow row in dtStatus.Rows)
{
if (string.IsNullOrEmpty(Convert.ToString(row["UPDATED_STATUS"])) ||
(Convert.ToString(row["UPDATED_STATUS"]).ToLower() != "pre hoto" &&
Convert.ToString(row["UPDATED_STATUS"]).ToLower() != "post hoto"))
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
break;
}
else { }
}
I have got a way to get this done.. Here I go
if (strFlag == "")
{
dtStatus = GET_STATUS_FROM_SAPID_FOR_HOTO(dtExcelRows.Rows[i]["Current SAPID"].ToString());
if (dtStatus == null && dtStatus.Rows.Count < 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('Status cannot be blank for SAP ID entered');", true);
}
else
{
dtExcelRows.Rows[i]["UPDATED_STATUS"] = dtStatus.Rows[0][1].ToString();
dtExcelRows.AcceptChanges();
}
}
}
DataTable dtGetHotoPre = null;
var rows = dtExcelRows.AsEnumerable().Where(x => x.Field<string>("UPDATED_STATUS") == "PRE HOTO");
if (rows.Any())
{
dtGetHotoPre = rows.CopyToDataTable();
}
DataTable dtGetHotoPost = null;
var rowsPost = dtExcelRows.AsEnumerable().Where(x => x.Field<string>("UPDATED_STATUS") == "POST HOTO");
if (rowsPost.Any())
{
dtGetHotoPost = rowsPost.CopyToDataTable();
}
string strFlagStatus = "";
if (dtGetHotoPre != null)
{
if (dtGetHotoPost != null)
{
strFlagStatus = "No Process";
}
else
{
strFlagStatus = "Process";
grdDvHoto.DataSource = dtGetHotoPost;
}
}
else
{
if (dtGetHotoPost != null)
{
strFlagStatus = "Process";
grdDvHoto.DataSource = dtGetHotoPre;
}
else
{
strFlagStatus = "No Process";
}
}
// if(dtGetHotoPre != null && dtGetHotoPost != null)
if (strFlagStatus == "No Process")
{
ClientScript.RegisterStartupScript(Page.GetType(), "erroralert", "alert('The sites contains both Pre and Post Hoto Status, so it cannot be uploaded');", true);
}
else
{
// will move ahead.
grdDvHoto.DataBind();
}
i am trying to update a m-to-m relation with a ListBox. My entity-model looks like this:
I have a ListBox with Checkboxes where the user can decide which Player is in the league and which is not (IsSelected-Property). There are two problems: At first i can't check and then uncheck a Player (it won't be deleted). Second Problem: the first try, everything works and when i do the selection again, i get the following exception:
_innerException {"An error occurred while updating the entries. See the inner exception for details."} System.Exception {System.Data.Entity.Core.UpdateException}
_innerException {"Violation of PRIMARY KEY constraint 'PLID'. Cannot insert duplicate key in object 'dbo.PlayerLeague'. The duplicate key value is (2, 2).\r\nThe statement has been terminated."} System.Exception {System.Data.SqlClient.SqlException}
using (BettingLeagueEntities entities = new BettingLeagueEntities())
{
foreach (PlayerCheckBoxList p in this.PlayerList)
{
if(p.IsSelected == true)
{
PlayerLeague pl = new PlayerLeague();
pl.League = this.ActiveLeague;
pl.Player = p.ActivePlayer;
var local = entities.Set<Player>().Local.FirstOrDefault(x => x.PID == p.ActivePlayer.PID);
if(local != null)
{
entities.Entry(local).State = System.Data.Entity.EntityState.Detached;
}
var localLeague = entities.Set<League>().Local.FirstOrDefault(x => x.LID == this.ActiveLeague.LID);
if (localLeague != null)
{
entities.Entry(localLeague).State = System.Data.Entity.EntityState.Detached;
}
if (entities.Entry(p.ActivePlayer).State == System.Data.Entity.EntityState.Detached)
{
entities.Player.Add(p.ActivePlayer);
entities.Entry(p.ActivePlayer).State = System.Data.Entity.EntityState.Modified;
}
if (entities.Entry(this.ActiveLeague).State == System.Data.Entity.EntityState.Detached)
{
entities.League.Add(this.ActiveLeague);
entities.Entry(this.ActiveLeague).State = System.Data.Entity.EntityState.Modified;
}
if(p.ActivePlayer.PlayerLeague.All(x => x.LID != this.ActiveLeague.LID))
{
p.ActivePlayer.PlayerLeague.Add(pl);
this.ActiveLeague.PlayerLeague.Add(pl);
}
}
else
{
PlayerLeague local = entities.Set<PlayerLeague>().Local.FirstOrDefault(x => x.LID == this.ActiveLeague.LID && x.PID == p.ActivePlayer.PID);
if(local != null)
{
entities.PlayerLeague.Attach(local);
entities.PlayerLeague.Remove(local);
}
entities.SaveChanges();
}
}
entities.SaveChanges();
}
I have no clue how to solve this, do you have any suggestions?
I have it! I tried to comment a little bit to make it understandable.
The first problem was that i checked if my PlayerLeague already exists too lately. I moved this condition in my first if(statement).
The second error was, that in my else block, my statement to find a playerleague returned alsways null. Now i check if there is any entity and if this is true, i delete it.
using (BettingLeagueEntities entities = new BettingLeagueEntities())
{
foreach (PlayerCheckBoxList p in this.PlayerList)
{
// Check if the Player is seleceted and if the ActivePlayer has the Active League
if (p.IsSelected == true && p.ActivePlayer.PlayerLeague.All(x => x.LID != this.ActiveLeague.LID))
{
// Define the new PlayerLeague
PlayerLeague pl = new PlayerLeague {PID = p.ActivePlayer.PID, LID = this.ActiveLeague.LID};
var localPlayer = entities.Set<Player>().Local.FirstOrDefault(x => x.PID == p.ActivePlayer.PID);
if (localPlayer != null)
{
entities.Entry(localPlayer).State = System.Data.Entity.EntityState.Detached;
}
if (entities.Entry(p.ActivePlayer).State == System.Data.Entity.EntityState.Detached)
{
entities.Player.Add(p.ActivePlayer);
entities.Entry(p.ActivePlayer).State = System.Data.Entity.EntityState.Modified;
}
var localLeague = entities.Set<League>().Local.FirstOrDefault(x => x.LID == this.ActiveLeague.LID);
if (localLeague != null)
{
entities.Entry(localLeague).State = System.Data.Entity.EntityState.Detached;
}
if (entities.Entry(this.ActiveLeague).State == System.Data.Entity.EntityState.Detached)
{
entities.League.Add(this.ActiveLeague);
entities.Entry(this.ActiveLeague).State = System.Data.Entity.EntityState.Modified;
}
p.ActivePlayer.PlayerLeague.Add(pl);
this.ActiveLeague.PlayerLeague.Add(pl);
}
else
{
// Check if there is a PlayerLeague for this Player and league
bool hasPlayerLeague =
entities.PlayerLeague.Any(x => x.LID == this.ActiveLeague.LID && x.PID == p.ActivePlayer.PID);
if (hasPlayerLeague && p.IsSelected == false)
{
// Find PlayerLeague
PlayerLeague pl =
entities.PlayerLeague.FirstOrDefault(
x => x.LID == this.ActiveLeague.LID && x.PID == p.ActivePlayer.PID);
// Attach and Remove PlayerLeague
entities.PlayerLeague.Attach(pl);
entities.PlayerLeague.Remove(pl);
}
entities.SaveChanges();
}
}
}
I am trying to find out that in ad, user has allowed to change password or not.
I have used SearchResponse to find out that user exists or not.
SearchResponse response = (SearchResponse)connection.SendRequest(request);
DirectoryAttribute attribute = response.Entries[0].Attributes["ntSecurityDescriptor"];
if (attribute != null)
{
const string PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}";
const int ADS_ACETYPE_ACCESS_DENIED_OBJECT = 6;
bool fEveryone = false;
bool fSelf = false;
ActiveDs.ADsSecurityUtility secUtility = new ActiveDs.ADsSecurityUtility();
ActiveDs.IADsSecurityDescriptor sd = (IADsSecurityDescriptor)secUtility.ConvertSecurityDescriptor((byte[])attribute[0], (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_RAW, (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_IID);
ActiveDs.IADsAccessControlList acl = (ActiveDs.IADsAccessControlList)sd.DiscretionaryAcl;
foreach (ActiveDs.IADsAccessControlEntry ace in acl)
{
if ((ace.ObjectType != null) && (ace.ObjectType.ToUpper() == PASSWORD_GUID.ToUpper()))
{
if ((ace.Trustee == "Everyone") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
{
fEveryone = true;
}
if ((ace.Trustee == #"NT AUTHORITY\SELF") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
{
fSelf = true;
}
break;
}
}
if (fEveryone || fSelf)
{
return Global.RequestContants.CANT_CHANGE_PASSWORD;
}
else
{
return string.Empty;
}
}
I am doing an assignment involving the creation of a simple Quiz type form application. However, whenever I run the program, only the first answer shows for a multiple question and I cannot for the life of me figure out why.
This is the contstructor:
MultipleChoice dlg =
new MultipleChoice(
new Question("What is the capital of Zimbabwe?",
new Answer("Paris", false),
new Answer("Washington D.C.", false),
new Answer("Harare", true),
new Answer("Cairo", false),
new Answer("N'Djamena", false)));
if (dlg.ShowDialog() == DialogResult.OK)
{
if (dlg.Correct) MessageBox.Show("You got something right!");
else MessageBox.Show("You couldn't be more wrong");
}
And this is the Question Form Code:
private Question Q;
public MultipleChoice (Question q)
{
Q = q;
InitializeComponent();
textPrompt.Text = Q.Prompt;
if (Q.A != null)
{
radioA.Text = Q.A.Prompt;
}
else radioA.Hide();
if (Q.B != null)
{
radioB.Text = Q.B.Prompt;
}
radioB.Hide();
if (Q.C != null)
{
radioC.Text = Q.C.Prompt;
}
radioC.Hide();
if (Q.D != null)
{
radioD.Text = Q.D.Prompt;
}
radioD.Hide();
if (Q.E != null)
{
radioE.Text = Q.E.Prompt;
}
radioE.Hide();
}
public bool Correct
{
get
{
if (Q == null) return false;
if (Q.A != null && Q.A.Correct && radioA.Checked) return true;
if (Q.B != null && Q.B.Correct && radioB.Checked) return true;
if (Q.C != null && Q.C.Correct && radioC.Checked) return true;
if (Q.D != null && Q.D.Correct && radioD.Checked) return true;
if (Q.E != null && Q.E.Correct && radioE.Checked) return true;
return false;
}
}
Where have I gone wrong?
There is no else for any option after A:
if (Q.B != null)
{
radioB.Text = Q.B.Prompt;
}
radioB.Hide(); //This is **always** going to be called - hiding radioB :)
Should be:
if (Q.B != null)
radioB.Text = Q.B.Prompt;
else
radioB.Hide();
I am using this code for datalist validation.
I am binding the image in datalist after that i am trying to give the caption to each image suppose there is 3 image is datalist then for the first image i am able to give but for the other one i am unable to.. i think there is some error in conditions help me in this. code is following..
if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images and captions for each image";
msgError.Focus();
}
else
AddCaption();
bool IsEmptyCaption = false;
Hashtable htble = (Hashtable)ViewState["imgIdCapHtbl"];
List<int> imgIds = (List<int>)ViewState["imgIds"];
if (htble != null && imgIds != null)
{
foreach (int id in imgIds)
{
if (htble[id] == "")
{
IsEmptyCaption = true;
break;
}
else
IsEmptyCaption = false;
}
}
else
IsEmptyCaption = true;
if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images";
msgError.Focus();
}
else if (IsEmptyCaption)
{
msgError.Text = "Please add captions for each image";
msgError.Focus();
}
else
{
Args[0] = "Section1";
Args[1] = "";
Args[2] = FindingId.ToString();
Args[3] = FindingIdIns.ToString();
AnotherHeading = false;
//AddCaption();
objGetBaseCase.UpdateImageCaptions((Hashtable)ViewState["imgIdCapHtbl"]);
if (AddFindingsViewerDetails != null)
AddFindingsViewerDetails(Args, e);
ClearImages();
PageContent pg = (PageContent)this.Parent.FindControl("PageContent");
if (pg != null)
pg.LoadWorkflowForCase();
if (Display != null)
Display(null, EventArgs.Empty);
}
if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images and captions for each image";
msgError.Focus();
}
else
AddCaption();
bool IsEmptyCaption = false;
Hashtable htble = (Hashtable)ViewState["imgIdCapHtbl"];
List<int> imgIds = (List<int>)ViewState["imgIds"];
if (htble != null && imgIds != null)
{
foreach (int id in imgIds)
{
if (htble[id] == "" || htble[id] == null) // New code implemented here
{
IsEmptyCaption = true;
break;
}
else
IsEmptyCaption = false;
}
}
else
IsEmptyCaption = true;
if (DataList1.Items.Count == 0)
{
msgError.Text = "Please add images";
msgError.Focus();
}
else if (IsEmptyCaption)
{
msgError.Text = "Please add captions for each image";
msgError.Focus();
}
else
{
Args[0] = "Section1";
Args[1] = "";
Args[2] = FindingId.ToString();
Args[3] = FindingIdIns.ToString();
AnotherHeading = false;
//AddCaption();
objGetBaseCase.UpdateImageCaptions((Hashtable)ViewState["imgIdCapHtbl"]);
if (AddFindingsViewerDetails != null)
AddFindingsViewerDetails(Args, e);
ClearImages();
PageContent pg = (PageContent)this.Parent.FindControl("PageContent");
if (pg != null)
pg.LoadWorkflowForCase();
if (Display != null)
Display(null, EventArgs.Empty);
}
Now its working fine...