I am trying to save a guid to a database from a populated dropdown.
The data in the class is fine but when i save the guid back to the database for reference i get the error: "guid is not in recognized format".
When i look at the value attribtute it is empty
I am using the following to standardize my lookups
/// <summary>
/// Gets the days of week.
/// </summary>
/// <returns></returns>
public List<StandardLookup> GetStandardLookups(Guid lookkupCode)
{
List<StandardLookup> lookups = new List<StandardLookup>();
try
{
var q = from lookup in fhsNetEntities.fhsLookUps.Where(a => a.lookup_type == lookkupCode).OrderByDescending(o => o.colOrder)
orderby lookup.lookup_description
select new
{
LookLookupValue = lookup.lookup,
LookupDescription = lookup.lookup_Code.Trim(),
Order = lookup.colOrder
};
if (q != null)
{
Array.ForEach(q.ToArray(), l =>
{
lookups.Add(new StandardLookup(l.LookLookupValue, l.LookupDescription, l.Order));
});
}
}
catch (Exception ex)
{
string inner = string.Empty;
if (ex.InnerException != null)
{
inner = ex.InnerException.ToString();
}
logger.Error("Error in GetDaysOfWeek function aperturenetdal " + ex.ToString() + " " + inner);
return null;
}
return lookups;
}
rdSaluation.DataSource = rdSaluations;
rdSaluation.DataValueField = "LookupValue";
rdSaluation.DataTextField = "LookupDescription";
rdSaluation.DataBind();
But when i got to my save event and debug I am getting the following error
And here you can see its grabbing the name value instead by mistake.
Put the whole code on Page_Load inside !IsPostBack. You are re-initializing your _fhsPersonal otherwise. Also you are using a variable by the same name in your btn_Click event. Change that too.
Related
I have a project that uses Entity Framework. While calling SaveChanges on my DbEntityValidationException, I get the following exception:
System.Data.Entity.Validation.DbEntityValidationException: 'Validation
failed for one or more entities. See 'EntityValidationErrors' property
for more details.'
This is all fine and dandy, but I don't want to attach a debugger every time this exception occurs. More over, in production environments I cannot easily attach a debugger so I have to go to great lengths to reproduce these errors.
How can I see the details hidden within the DbEntityValidationException?
private void btnCreateLetter_Click(object sender, EventArgs e)
{
using (TransactionScope TS = new TransactionScope())
{
try
{
Letter TblLetter = new Letter();
TblLetter.Subject = txtSubject.Text.Trim();
TblLetter.Abstract = txtAbstract.Text.Trim();
TblLetter.Body = ckeCKEditor.TextEditor.Text.Trim();
{
var LastLetterID = (from Letter in Database.Letters orderby Letter.LetterID descending select Letter).First();
TblLetter.LetterNO = PublicVariable.TodayDate.Substring(0, 4).Substring(2, 2) + PublicVariable.gDetermineJobLevel + "/" + (LastLetterID.LetterID + 1);
}
TblLetter.CreateDate = lblCreateDate.Text;
TblLetter.UserID = PublicVariable.gUserID;
if (rdbClassification.Checked == true)
{
TblLetter.SecurityType = 1;
}
else if (rdbConfidential.Checked == true)
{
TblLetter.SecurityType = 2;
}
else if (rdbSeries.Checked == true)
{
TblLetter.SecurityType = 3;
}
if (rdbActionType.Checked == true)
{
TblLetter.UrgencyType = 1;
}
else if (rdbInstantaneous.Checked == true)
{
TblLetter.UrgencyType = 2;
}
else if (rdbAnnie.Checked == true)
{
TblLetter.UrgencyType = 3;
}
TblLetter.ArchivesType = 1;
if (rdbFollowHas.Checked == true)
{
TblLetter.FollowType = 1;
}
else if (rdbFollowHasnoot.Checked == true)
{
TblLetter.FollowType = 2;
}
if (rdbAttachmentHas.Checked == true)
{
TblLetter.AttachmentType = 1;
}
else if (rdbAttachmentHasnot.Checked == true)
{
TblLetter.AttachmentType = 2;
}
TblLetter.ReadType = 1;
TblLetter.LetterType = 1;
TblLetter.DraftType = 1;
if (rdbResponseDeadlineHas.Checked == true)
{
TblLetter.AnswerType = 1;
TblLetter.AnswerReadLine = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(pdpSetResponseDeadline.Value.Year.ToString() +
"/" + pdpSetResponseDeadline.Value.Month.ToString() + "/" + pdpSetResponseDeadline.Value.Day.ToString()));
}
else if (rdbResponseDeadlineHasnot.Checked == true)
{
TblLetter.AnswerType = 2;
}
Database.Letters.Add(TblLetter);
Database.SaveChanges();
if (rdbAttachmentHas.Checked == true)
{
if (lblPath.Text != "")
{
FileStream ObjectFileStream = new FileStream(lblPath.Text, FileMode.Open, FileAccess.Read);
int Lenght = Convert.ToInt32(ObjectFileStream.Length);
byte[] ObjectData;
ObjectData = new byte[Lenght];
string[] strPath = lblPath.Text.Split(Convert.ToChar(#"\"));
ObjectFileStream.Read(ObjectData, 0, Lenght);
ObjectFileStream.Close();
AttachFile TableAttachFile = new AttachFile();
TableAttachFile.FileSize = Lenght / 1024;
TableAttachFile.FileName = strPath[strPath.Length - 1];
TableAttachFile.FileData = ObjectData;
TableAttachFile.LetterID = TblLetter.LetterID;
Database.AttachFiles.Add(TableAttachFile);
Database.SaveChanges();
}
}
TS.Complete();
MessageBox.Show("saved", "ok", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (InvalidCastException ex)
{
MessageBox.Show(ex.ToString());
MessageBoxIcon.Error);
return;
}
}
}
You have to get the validation errors from the db.SaveChanges() method of the DatabaseContext object -- you can't get them where you are.
You can either modify the SaveChanges() method of your database context and wrap it in a try-catch block, or (since the class is partial) you can extend the partial class within your application and just override the SaveChanges() method.
There is a nice blog post about this called Easy way to improve DbEntityValidationException of Entity Framework here.
The essence of it is something like this:
public partial class NorthwindEntities
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
}
The blogger explains:
That’s it! The rest of your code will automatically use the overridden
SaveChanges so you don’t have to change anything else. From now on,
your exceptions will look like this:
System.Data.Entity.Validation.DbEntityValidationException: Validation
failed for one or more entities. See 'EntityValidationErrors' property
for more details. The validation errors are: The field PhoneNumber
must be a string or array type with a maximum length of '12'; The
LastName field is required.
The DbEntityValidationException also contains the entities that caused
the validation errors. So if you require even more information, you
can change the above code to output information about these entities.
As mention, you need to check on your EntityValidationError when it throws the exception.
You should fix that validation error, instead of asking bypass this exception.
Normally these errors are table allow length, data type, column does not allow null and etc. There will be exact fiend name mention in your exception too.
I have a list in a view with values that need to be updated.
When calling the http method, I am going thru the list components and looking into the database for a item with the right Id and updating the Grade value. My problem is that I can't return the right item from the database, it always returns null. I have checked with debugging, the item from the list with the Id that I am looking for has the right value, but I can't return the item from db.
I have also tried with the sql raw query and it gives me the same error.
This is my code - the var exam is always null :
public ActionResult UpdateExams(ExamsList examList)
{
var examVM = new ExamViewModel
{
Professor = _context.Professor.ToList()
};
examVM.ExamsList = examList;
if (!ModelState.IsValid)
{
var GradesList = new List<int>();
for (int i = 5; i <= 10; i++)
{
GradesList.Add(i);
}
var GradesListSL = new SelectList(GradesList);
return PartialView("ExamsTable", examList);
}
try
{
for (int i = 0; i < examList.ExamDetails.Count; i++)
{
var exam = _context.Exam.Single(e => e.Id == examList.ExamDetails[i].Id);
// var exam = _context.Database.SqlQuery<Exam>(#"SELECT Id as Id,Grade as Grade
//FROM Exam
//WHERE Id={0})
//", examList.ExamDetails[i].Id).ToList();
exam.Grade = examList.ExamDetails[i].Grade == 0 ? exam.Grade : examList.ExamDetails[i].Grade;
}
// _context.SaveChanges();
TempData["InsertingExam"] = "Success!";
// return RedirectToAction("Create", "Exams");
return Json(new { redirectTo = Url.Action("Edit", "Exams") });
}
catch (System.Data.Entity.Infrastructure.DbUpdateException ex) //DbContext
{
string exception = ex.StackTrace + ex.Message;
ModelState.AddModelError("Error", exception);
return View(examVM);
throw;
}
catch (Exception ex)
{
string exception = ex.StackTrace + ex.Message;
ModelState.AddModelError("Error", exception);
return View(examVM);
throw;
}
finally
{
_context.SaveChanges();
}
}
The problem was that I was trying to do the database operation with the view model class.
After I added creating the model class from the view model everything worked just fine.
I knew that I am re-inventing the wheel. But still, I have to do it as I am instructed to do so :D.
I have to log all unhandled exception of my asp.net website. I am able to dynamically catch all exceptions but I am not able to retrieve the actual class and method name.
Everytime I got Global_asax as class name and Application_Error as the method name. Below is my code.
/// <summary>
/// Determines the log type and saves log to database. Use logtype 1 for exception logging
/// and 2 for normal audit trail.
/// </summary>
/// <param name="obj">Type of object. Accepts exception or audit log string.</param>
/// <param name="logType">Type of logging. Use LogTypes.Exception for Exception and LogTypes.Audit for Normal Logging</param>
/// <param name="fileName"></param>
/// <param name="userId">optional parameter. Accepts userid as integer</param>
/// <param name="userName">optional parameter. Accepts username as string</param>
/// <param name="memberName"></param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void Log( LogTypes logType, object obj, string memberName,string fileName, int userId = 0, string userName = "")
{
var appLog = new ApplicationLog();
var stackFrame = new StackFrame(2,true);
try
{
var isHosted = HostingEnvironment.IsHosted;
appLog.UserId = userId;
appLog.UserName = userName;
appLog.InstanceName = ConfigurationSettingsHelper.InstanceName;
appLog.LoggedOn = DateTime.UtcNow;
if (isHosted)
{
appLog.ProjectName = HostingEnvironment.ApplicationHost.GetSiteName();
appLog.FilePath = HttpContext.Current.Request.RawUrl;
}
else
{
appLog.ProjectName= Assembly.GetCallingAssembly().GetName().Name;
appLog.FilePath = fileName;
}
if (logType == LogTypes.Exception)
{
appLog.LogType = 1;
if (obj is Exception ex)
{
var declaringType = ex.TargetSite.DeclaringType;
if (declaringType != null)
{
appLog.ClassName = declaringType.FullName;
appLog.MethodName = ex.TargetSite.Name;
}
appLog.LogDetails = ex.ToString();
appLog.Message = ex.Message;
}
else
{
appLog.ClassName = stackFrame.GetMethod().DeclaringType.AssemblyQualifiedName;
appLog.MethodName = memberName;
appLog.LogDetails = obj.ToString();
appLog.Message = "User defined custom exception";
}
}
else
{
appLog.LogType = 2;
appLog.ClassName = stackFrame.GetMethod().DeclaringType.AssemblyQualifiedName;
appLog.MethodName = memberName;
appLog.LogDetails = obj.ToString();
appLog.Message = "User defined custom exception";
}
}
catch (Exception ex)
{
//In case of unhandled exceptions.Try logging internal exception once.
//If failed, pass by silently.
try
{
appLog = new ApplicationLog
{
UserId = userId,
UserName = userName,
FilePath = new StackFrame(1).GetFileName(),
Message = ex.Message,
InstanceName = ConfigurationSettingsHelper.InstanceName,
ProjectName = Assembly.GetCallingAssembly().GetName().Name,
LoggedOn = DateTime.UtcNow,
LogType = 1,
LogDetails = ex.ToString()
};
if (ex.TargetSite.DeclaringType != null)
appLog.ClassName = ex.TargetSite.DeclaringType.FullName;
appLog.MethodName = ex.TargetSite.Name;
}
finally
{
HttpWebMethods.PostAsync(ConfigurationSettingsHelper.LoggerApiBaseAddress,
ConfigurationSettingsHelper.SaveLogEndpoint, appLog);
} // intentionally eating exception}
}
finally
{
HttpWebMethods.PostAsync(ConfigurationSettingsHelper.LoggerApiBaseAddress,
ConfigurationSettingsHelper.SaveLogEndpoint, appLog);
}
}
It's logging all good at all places. But for the case of any unhandled exceptions, I need to capture the class name and method name. But instead, its giving me the global.asax details.
Its a class library and i want it work as same as Global.asax works. Automatically recognizes all errors.
Please help.
I have a C# program that manages Sharepoint lists using the Sharepoint Client Object Model. Occasionally we will have server issues which will prevent the program from accessing the sharepoint server. I am using a helper class to run the ExecuteQuery method and have exception handling to continue to execute until there is no exception.
private void ExecuteContextQuery(ref ClientContext siteContext)
{
int timeOut = 10000;
int numberOfConnectionErrors = 0;
int maxNumberOfRetry = 60;
while (numberOfConnectionErrors < maxNumberOfRetry)
{
try
{
siteContext.ExecuteQuery();
break;
}
catch (Exception Ex)
{
numberOfConnectionErrors++;
Service.applicationLog.WriteLine("Unable to connect to the sharepoint site. Retrying in " + timeOut);
Service.applicationLog.WriteLine("Exception " + Ex.Message + " " + Ex.StackTrace);
System.Threading.Thread.Sleep(timeOut);
if (numberOfConnectionErrors == maxNumberOfRetry)
{
throw Ex;
}
}
}
}
However I getting an error messages
The property or field 'LoginName' has not been initialized.
and
collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
The error messages seem to be related to methods where I call the Load method. here is an example of my code that calls the method above.
List sharepointList = siteContext.Web.Lists.GetByTitle(this._listName);
CamlQuery query = CamlQuery.CreateAllItemsQuery();
items = sharepointList.GetItems(query);
siteContext.Load(items);
//siteContext.ExecuteQuery();
ExecuteContextQuery(ref siteContext);
Do I need to reload the site context with every call to ExecuteQuery? Is that why I am seeing the error message above?
Here is the function I am using for getting the Login ID which is generating the error
public String getLoginIDbyUserId(int userID)
{
ClientContext siteContext = getClientContextObject();
User _getUser = siteContext.Web.SiteUsers.GetById(userID);
siteContext.Load(_getUser);
//siteContext.ExecuteQuery();
ExecuteContextQuery(ref siteContext);
String loginID = String.Empty;
String formatedLoginID = String.Empty;
loginID = _getUser.LoginName;
if (loginID.Contains('|'))
{
formatedLoginID = loginID.Substring(loginID.IndexOf('|') + 1);
}
siteContext.Dispose();
return formatedLoginID;
}
Please try to load LoginName property of user while loading user object. And after excutequery method, try to consume LoginName property of User
siteContext.Load(_getUser, u => u.LoginName);
And after this change your code should look like this
public String getLoginIDbyUserId(int userID)
{
ClientContext siteContext = getClientContextObject();
User _getUser = siteContext.Web.SiteUsers.GetById(userID);
siteContext.Load(_getUser, u => u.LoginName);
//siteContext.ExecuteQuery();
ExecuteContextQuery(ref siteContext);
String loginID = String.Empty;
String formatedLoginID = String.Empty;
loginID = _getUser.LoginName;
if (loginID.Contains('|'))
{
formatedLoginID = loginID.Substring(loginID.IndexOf('|') + 1);
}
siteContext.Dispose();
return formatedLoginID;
}
My issue is the following: i'm trying to build a function to which i could pass a list of items, which would then go to the db with each of those items and update them. I believe the issue is within the way datacontexts are being used but i cannot figure out this issue.
Here is my function that builds the list of items that were changed:
protected void btnSave_Click(object sender, EventArgs e)
{
List<AFF_CMS_FMA> fmasToSave = new List<AFF_CMS_FMA>();
AFF_CMS_FMA newFmaItem = new AFF_CMS_FMA();
foreach (AFF_CMS_FMA fmaItem in FmaLib.fetchAllActiveAssetsInFMA())
{
if (fmaItem.SortOrder != Convert.ToInt32(Request.Form["fmaItem_" + fmaItem.ID + "_SortOrder"]))
{
newFmaItem = fmaItem;
newFmaItem.Name = SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_Name"]);
newFmaItem.AssetID = Convert.ToInt32(Request.Form["fmaItem_" + fmaItem.ID + "_AssetID"]);
newFmaItem.SortOrder = Convert.ToInt32(Request.Form["fmaItem_" + fmaItem.ID + "_SortOrder"]);
newFmaItem.ImagePathEn = SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_ImagePathEn"]);
newFmaItem.ImagePathCh = SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_ImagePathCh"]);
newFmaItem.StartDate = DateTime.Parse(SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_StartDate"]));
newFmaItem.EndDate = DateTime.Parse(SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_EndDate"]));
newFmaItem.ClickToUrl = SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_ClickToUrl"]);
fmasToSave.Add(newFmaItem);
}
}
FmaLib.saveEditedFmas(fmasToSave);
}
here is the function that the foreach loops calls to get all the items that are in the db:
public static List<AFF_CMS_FMA> fetchAllActiveAssetsInFMA()
{
List<AFF_CMS_FMA> results = null;
using (fmaDataContext db = new fmaDataContext())
{
using (TransactionScope ts = new TransactionScope())
{
try
{
if (HttpContext.Current.Cache["fmaActiveList"] == null)
{
db.LoadOptions = loadAll;
results = clsCompiledQuery.getAllActiveFmas(db).ToList();
HttpContext.Current.Cache["fmaActiveList"] = results;
}
else
results = (List<AFF_CMS_FMA>)HttpContext.Current.Cache["fmaActiveList"];
ts.Complete();
}
catch (Exception ex)
{ Transaction.Current.Rollback(); }
}
return results;
}
}
here are the queries being used:
protected static class clsCompiledQuery
{
public static Func<DataContext, IOrderedQueryable<AFF_CMS_FMA>>
getAllActiveFmas = CompiledQuery.Compile((DataContext db)
=> from fma in db.GetTable<AFF_CMS_FMA>()
where fma.IsArchived == false
orderby fma.SortOrder ascending
select fma);
public static Func<DataContext, int,IQueryable<AFF_CMS_FMA>>
getFmaById = CompiledQuery.Compile((DataContext db, int ID)
=> from fma in db.GetTable<AFF_CMS_FMA>()
where fma.ID == ID
select fma);
}
and finally this were im trying to get the save to happen to the db but no exeptions are throwns, yet the db does not change
public static bool saveEditedFmas(List<AFF_CMS_FMA> fmaToSaveList)
{
using (fmaDataContext db = new fmaDataContext())
{
using (TransactionScope ts = new TransactionScope())
{
try
{
foreach (AFF_CMS_FMA fmaItemToSave in fmaToSaveList)
{
AFF_CMS_FMA fmaItemToUpdate = clsCompiledQuery.getFmaById(db, fmaItemToSave.ID).ToList()[0];
fmaItemToUpdate = fmaItemToSave;
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Transaction.Current.Rollback();
return false;
}
}
}
}
I have checked and the table does contain a primary key in the designer. If i do the save from the btnSave_click function by passing a datacontext to the fetchAllActiveAssetsInFMA() then doing submitchanges on that context it works .. but im trying to abstract that from there.
thanks all in advance
Your not calling ts.Complete in function saveEditedFmas.
Also I would recommend calling db.SubmitChanges(); outside of the for loop. And why do you have a transaction in function fetchAllActiveAssetsInFMA? It's only fetching data right? And I'm not quite sure whats happening inside the for loop in save function, looks strange.
I think you should map the properties from fmaItemToSave to fmaItemToUpdate
foreach (var fmaItemToSave in fmaToSaveList)
{
var fmaItemToUpdate = clsCompiledQuery.getFmaById(db, fmaItemToSave.ID).First();
fmaItemToUpdate.Name = fmaItemToSave.Name;
fmaItemToUpdate.AssetID = fmaItemToSave.AssetID;
//And the rest of the properties
}
db.SubmitChanges();