I'm getting an error from GlassMapper on certain pages in my Sitecore solution.
public override void Execute(ObjectConstructionArgs args)
{
// check that no other task has created an object and that this is a dynamic object
if (args.Result != null || args.Configuration.Type.IsAssignableFrom(typeof(IDynamicMetaObjectProvider))) return;
// create instance using your container
var obj = ServiceLocator.ServiceProvider.GetService(args.Configuration.Type);
// map properties from item to model
args.Configuration.MapPropertiesToObject(obj, args.Service, args.AbstractTypeCreationContext);
// set the new object as the returned result
args.Result = obj;
}
The error is occurring on args.Configuration.MapPropertiesToObject(obj, args.Service, args.AbstractTypeCreationContext); - System.FormatException: Unrecognized Guid format.. This error is only occurring on pages of a particular template, but not ALL pages of that template and I'm not sure how to track down which field is causing the guid error
I experienced the same error when a General Link field didn't contain any id="{xxx}" attribute or had it empty like id="". So, I suggest to check the raw value of the link fields on the failing pages.
Related
In my Vaadin (v.23.2.6) application I have a form tied up to Filter class which has 5 attributes.
All of them are optional, i.e. user can leave the blank.
public FilterPanel(ApiBookUtils api) {
this.api = api;
this.authorField = new ComboBox<Author>("Author Name");
this.countryField = new ComboBox<>("Country");
this.countryField.setReadOnly(true);
this.fromYear = new IntegerField ("From");
this.fromYear.setWidth("60px");
this.toYear = new IntegerField ("To");
this.toYear.setWidth("60px");
this.binder = new Binder(Filter.class);
this.setModal(true);
this.setCloseOnOutsideClick(false);
this.setCloseOnEsc(true);
buildDialog();
}
private void buildDialog() {
bindFields();
addFields();
setDialogListeners();
setDialogItems();
}
private void bindFields() {
this.binder.bind(authorField, Filter::getAuthor, Filter::setAuthor);
this.binder.forField(countryField).bind(Filter::getCountry, Filter::setCountry);
this.binder.forField(fromYear).bind(Filter::getFromYear, Filter::setFromYear);
this.binder.forField(toYear).bind(Filter::getToYear, Filter::setToYear);
this.binder.forField(postingDateField).bind(Filter::getPostingDate, Filter::setPostingDate);
this.binder.forField(tagField).bind(Filter::getTags, Filter::setTags);
}
I am getting getting exception if IntegerField is left blank.
com.vaadin.flow.data.binder.BindingException: An exception has been thrown inside binding logic for the field element [label='From']
at com.vaadin.flow.data.binder.Binder$BindingImpl.execute(Binder.java:1570) ~[flow-data-23.2.5.jar:23.2.5]
at com.vaadin.flow.data.binder.Binder$BindingImpl.writeFieldValue(Binder.java:1427) ~[flow-data-23.2.5.jar:23.2.5]
at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
Caused by: java.lang.NullPointerException: null
at com.vaadin.flow.data.binder.Binder$BindingImpl.lambda$writeFieldValue$5169480d$1(Binder.java:1431) ~[flow-data-23.2.5.jar:23.2.5]
Does anybody know how to make binder to accept empty field and set up default value in the bean?
I found the workaround the bug in the Binder. Apparently, it does not process primitive types correctly. I have replaced int fields in my bean with Integer object and exception was gone.
If IntegerField is empty, the value is by definition null. If your business logic throws NPE due this, Binder will fail. You can set the binding to convert null value to your presentation by using withNullPresentation(defaultValue).
this.binder.forField(fromYear)
.withNullPresentation(0) // e.g. interpret null as zero
.bind(Filter::getFromYear, Filter::setFromYear);
In My MVC project, I am using session values like
var empId = Convert.ToInt32(Session["EmpId"].ToString());
I am getting Exception:
"An exception of type 'System.NullReferenceException' occurred in Project.Web.dll but was not handled in user code.
Additional information: Object reference not set to an instance of an object."
This error occurs when you call a method on the null object. In your case the value of Session["EmpId"] is NULL.
Which means you are calling NULL.ToString(), which is invaild hence it throws error.
You can avoid the error using null coaleascing operator or simply check null before performing any opearation on it.
Solution:
if(Session["EmpId"] == null)
//do something
else
var empId = Convert.ToInt32(Session["EmpId"].ToString());
Alternatively you can check my blog post on it
Before use first check is it null or not.
var empId = Session["EmapId"] != null ? Convert.ToInt32(Session["EmapId"]) : 0;
You have to check null as shown below :-
var empId = Convert.ToInt32((Session["EmpId"] ?? 0).ToString());
A more efficient way to accomplish your requirement :-
int temp = 0;
var empId = int.TryParse( Convert.ToString( Session["EmpId"] ),out temp );
I am using ASP.NET WebAPI 2 with Breeze. I want to be able to return meaningful error messages when saving changes using SaveChanges() method. This is in case there is an error.
The current implementation returns SaveResult. How can return message e.g
var cardDetail = _membershipContextProvider.Context.Database.SqlQuery<CardDetail>("IssuedCardsGetVerificationDetails #CardNo", parameter).FirstOrDefault();
if (cardDetail == null)
{
HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("The beneficiary with Card No. {0} was found in the NHIF database", CardNo)),
ReasonPhrase =string.Format("Card No. {0} Not Found in the NHIF Database!",CardNo)
};
throw new HttpResponseException(msg);
}
return cardDetail;
You need to throw an EntityErrorsException within the custom save method. This exception lets you both specify a top level message as well as a custom message for each failed entity.
[HttpPost]
public SaveResult MyCustomSaveMethod(JObject saveBundle) {
ContextProvider.BeforeSaveEntitiesDelegate = SaveThatMightThrow;
return ContextProvider.SaveChanges(saveBundle);
}
private Dictionary<Type, List<EntityInfo>> SaveThatMightThrow(Dictionary<Type, List<EntityInfo>> saveMap) {
List<EntityInfo> orderInfos;
// if this save tries to save ANY orders throw an exception.
if (saveMap.TryGetValue(typeof(Order), out orderInfos)) {
var errors = orderInfos.Select(oi => {
return new EFEntityError(oi, "WrongMethod", "Entity level detail error - Cannot save orders with this save method", "OrderID");
});
var ex = new EntityErrorsException("Top level error - Orders should not be saved with this method", errors);
// if you want to see a different error status code use this.
// ex.StatusCode = HttpStatusCode.Conflict; // Conflict = 409 ; default is Forbidden (403).
throw ex;
}
return saveMap;
}
Note that there is a bug in Breeze 1.4.16 where the top level error is not being propagated properly (it returns to the client as an empty string), however the entity level error messages will come thru just fine. This bug has been fixed in the latest GitHub repos, but you will need to get the fixed code from both the breeze.js and the breeze.server.net repos because the fix was to both the breeze.js client as well as the ContextProvider class in breeze.server.net. Or you can wait for the next breeze release in about a week.
I am passing my model errors via the ViewBag. In my controller I am passing a List<string> that does contain values (_modelErrors) to the ViewBag and then I am trying to display this in my view. When I debug in the view, my ViewBag does contain a _modelErrors dictionary with values, but my errors are not being rendered.
From my controller:
ViewBag._modelErrors = _modelErrors;
In my view I have tried all of these methods and yet no markup is rendered.
#try
{
foreach (string er in ViewBag._modelErrors)
{
Response.Write(er.ToString());
#Html.DisplayText(er)
#Html.DisplayText(er.ToString())
#er.GetType()
#er.ToString();
er.ToString();
}
}
catch(Exception e){}
That's a dirty code, dude! Take a look at #Html.ValidationSummary and #Html.ValidationMessageFor
Well, some codes here to clarify stuff:
[HttpPost]
public ActionResult MyAction(ModelClass inputModel)
{
if (ModelState.IsValid)
{
//for example we're trying to save our data to db
var result = _myRepository.saveStuff(inputModel);
if (result)
return RedirectToAction("someAction");
ModelState.AddModelError(string.Empty, "An error occured, check input data");
}
return View(inputModel);
}
Also you can specify key (which is your model field name) instead of string.Empty -> so you'l see error message under specified field (as default), but basically what people do is exluding property errors from validation summary (#Html.ValidationSummary(true)) - so you get just general errors in that field. Hope it'l help
Use this:
(string er in (List<string>)(ViewBag._modelErrors))
But was said this is bad practice. Also catching exceptions this way is so wrong...
I have method with code:
using (var cc = new MyDBContext())
{
var myList = (from user in cc.Users
where user.UserGroup.Name == "smth"
orderby user.ID ascending
select user);
if (startIndex != null)
return View(myList.Skip((int)startIndex).Take(50));
else
return View(myList);
}
In view I catch exception The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
Some people says that .ToList() must solve problem, but it throws an exception with myList.ToList() too. What is my problem?
P.S. in debug mode I have exception at #item.FullName in view, but if I move mouse on FullName property I can see correct value.
Sorry for my bad english.
Take the "return View()" statements outside of the "using" block completely. That will ensure you have retrieved the complete data sets before your DbContext object is disposed. Like this:
using (var cc = new MyDBContext())
{
var myList = (linq).ToList();
}
return View(myList);
I'm pretty sure the problem is that you are returning an IEnumerable to the View, which means the items haven't actually been retrieved yet. But when you return the object to your View, the DbContext is getting disposed before the view has a chance to retrieve the rows.
The problem was in lazy loaded sub property of User entity. I add to link statement Include("PropName") and it works good.