AdxStudio CrmEntityFormView Swallowing Microsoft.Xrm.Sdk.SaveChangesException - dynamics-crm-2011

I posted this on the AdxStudio forum and got exactly zero response, so I'm hoping ya'll can help me debug this.
I'm using a CrmEntityFormView to create a new contact in CRM, like so:
<adx:CrmDataSource ID="FormViewDataSource" runat="server" />
<adx:CrmEntityFormView runat="server" ID="UserCreateForm" EntityName="contact" FormName="User Edit Form" DataSourceID="FormViewDataSource"
RecommendedFieldsRequired="true" ValidationGroup="NewUser" ValidationText="* This field is required" EnableValidationSummaryLinks="false"
OnItemInserting="UserCreateForm_ItemInserting" OnItemInserted="UserCreateForm_ItemInserted">
<InsertItemTemplate></InsertItemTemplate>
</adx:CrmEntityFormView>
<asp:Button ID="SubmitButton" Text='Create User' CssClass="button" ValidationGroup="NewUser" runat="server" OnClick="SubmitButton_Click" />
I'm using the SubmitButton_Click handler to handle some other fields on the form at the same time like so:
protected void SubmitButton_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
return;
}
# Handle other form fields not on the FormView ...
UserCreateForm.InsertItem();
}
Nothing happens in my database when I submit a valid form. So I debugged the ItemInserted event, putting a breakpoint on the single line of the handler
protected void UserCreateForm_ItemInserted(object sender, CrmEntityFormViewInsertedEventArgs e)
{
Contact newUser = XrmContext.ContactSet.Where(c => c.ContactId == e.EntityId).FirstOrDefault();
}
Turns out, in this event, e.Exception is not null, but an instance of the SaveChangesException from the title, with the message "An error occured while processing this request." and e.ExceptionHandled == true, which I guess is why I never saw anything.
This exception has an InnerException, an instance of System.ServiceModel.FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>
with a message that always just contains the submitted value of the first field in the FormView. I have absolutely no idea why this isn't working, and I'm unclear how to debug this further and can use some pointers.

The System.ServiceModel.FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> eats the stack trace. Refer to this blog as a method to actually log the stacktrace to be able to find where your error is occurring.

Related

Primefaces trigger onerror when exception occurs

for a university project we have to create a website using primefaces and spring boot.
My problem lies in the error handling. I have a p:dialog which lets you edit user information. Once you save the user, the dialog should close. However, if the save is not successful a error message should appear and the user-edit-dialog should stay open.
This is the commandButton which triggers the save:
<p:commandButton value="Save"
action="#{userDetailController.doSaveUser()}"
ajax="true"
validateClient="true"
oncomplete="if (args && args.closeForm) PF('userEditDialog').hide()"
update=":userForm:usersTable msgs mainPanel" />
As you can see it's an ajax request so for handling exception we use the integrated PrimeExceptionHandlerFactory.
<factory>
<exception-handler-factory>org.primefaces.application.exceptionhandler.PrimeExceptionHandlerFactory</exception-handler-factory>
</factory>
We are also displaying a dialog when a exception occurs.
<p:ajaxExceptionHandler type="at.qe.sepm.skeleton.utils.GeneralExpectedException" update="exceptionDialog"
onexception="PF('exceptionDialog').show();" />
<p:dialog id="exceptionDialog"
header="#{pfExceptionHandler.exception.type}"
widgetVar="exceptionDialog"
resizable="false">
Message: #{pfExceptionHandler.message}
<p:separator rendered="#{exceptionHelperBean.displayException(pfExceptionHandler.exception)}" />
<h:outputText rendered="#{exceptionHelperBean.displayException(pfExceptionHandler.exception)}"
value="#{pfExceptionHandler.formattedStackTrace}"
escape="false" />
</p:dialog>
My problem has to do with this line oncomplete="if (args && args.closeForm) PF('userEditDialog').hide()". The user-edit-dialog will only be closed when the closeForm flag is set. Which is done on the server:
PrimeFaces.current().ajax().addCallbackParam("closeForm", true);
From my understanding from other frameworks, when a exception occurs the server returns HTTP 500 and the onerror callback on the commandButton triggers.
Is there a more elegant way to do this? Ideally i don't want the oncomplete callback to trigger in the first place. I also tried using the onsuccess callback which doesn't get triggered at all, even if the request returns HTTP 200.
edit:
This is the doSaveUser methods inside the userDetailController:
public void doSaveUser() throws Exception {
user = this.userService.saveUser(user);
PrimeFaces.current().ajax().addCallbackParam("closeForm", true);
}
It internally calls the userServices save method where i manually throw the exception:
public User saveUser(User user) throws Exception {
if (user.isNew()) {
User existingUser = userRepository.findFirstByUsername(user.getUsername());
if(existingUser != null) {
throw new GeneralExpectedException("User with name " + user.getUsername() + " already exists",
ExceptionType.WARNING);
}
I hope this makes the problem more clear. Saving a user which already exists throws a exception - so the user edit dialog should stay open, in order to make adjustments. However, I also want the Exception dialog to trigger so you can see why saving is not possible.
Thank you for your help!

how to create action url for hyperlink in liferay?

i have a requirement that when i click on hyperlink i will send one parameter course id it has to go to action method in portlet class.then i need to display the success and as well as failure message on after operation done on to browser!
public void DeleteCourses(ActionRequest request,ActionResponse response) throws IOException,PortletException
{
String cid=request.getParameter("courseId");
long courseId = Long.parseLong(cid);
try {
CourseLocalServiceUtil.deleteCourse(courseId);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
can any one tell me how to create action url for hyperlink?
You could write it on your JSP like the following:
<portlet:actionURL name="DeleteCourses" var="DeleteCoursesURL">
<portlet:param name="courseId" value="the_course_id"></portlet:param>
</portlet:actionURL>
Delete Course
And Since your portlet class inherits from MVCPortlet the name of the your method DeleteCourses should be the same as the name of the actionURL
You could check a full example here
And for the Success and Error message you could simply use liferay built-in feature for this like that:
<liferay-ui:success key="success" message="Course deleted successfully!" />
And for the errors:
<liferay-ui:error key="error" message="Course could not be deleted" />
You could check an example here

Navigate after successfull action on commandButton

I am building a JSF application using Primefaces mobile (0.9.3 with Primefaces 3.5).
I hava a login page, on this login page there is a login button defined as followed:
<p:commandButton value="#{msg['label.login']}" action="#{loginBean.login}" update="usernameMsg" />
The loginBean.login method is defined as followed:
public String login() {
try {
//do login
return "#loggedInTarget?transition=fade";
} catch (UserNotValidException e) {
//User not valid, display exception
FacesContext
.getCurrentInstance()
.addMessage(
"loginForm:username",
new FacesMessage(
FacesMessage.SEVERITY_ERROR,
"",
messageService
.getMessage("error.message.loginNotSuccessfull")));
}
return null;
}
In my main xhtml (the same in which the button is defined), I have defined the following addtional views:
<pm:view id="registerTarget">
<ui:include
src="/WEB-INF/c52bc19d58a64ae4bd12dec187a2d4b7/register.xhtml" />
</pm:view>
<pm:view id="loggedInTarget">
TEST
</pm:view>
I do it that way because I want to use transitions within Primefaces mobile. To get to the register page I use a p:button which works fine:
<p:button value="#{msg['label.register']}"
href="#registerTarget?transition=fade" />
Why is my login button not working? I also tried to put in "#loggedInTarget?transition=fade" directly as action, but this didn't work either :(
I need the action, because I have to check if the user credentials are valid. If they are valid I want to display my loggedInTarget.
How can I achieve it?
Thanks in advance!
EDIT:
The button is inside a form.
The navigation case outcome value must represent a view ID, not an URL (for sure not a hash fragment). Try with <p:button outcome="...">, and you'll see that it fails over there as well.
Your closest bet is sending a redirect.
public void login() throws IOException {
// ...
externalContext.redirect("#loggedInTarget?transition=fade");
// ...
}
This is also exactly what the <p:button href="..."> does under the covers: causing a GET request on the given URL.

How to set the exception message in a <h:message>?

I am trying to set an exception message in the <h:message>.
Here is the relevant view code:
<h:inputText id="titleId" value="#{bookController.book.title}"/>
<h:message for="titleId"/>
<h:commandButton value="Create a book" actionListener="#{bookController.doCreateBook}" action="listBooks"/>
I need a message to be displayed when the titleId is empty. My #Stateless EJB method throws an exception when the title is empty:
public Book createBook(Book book) throws CustomException {
if(book.getTitle().isEmpty()) {
throw new CustomException("Please, type a Title !");
}
else {
em.persist(book);
return book;
}
}
My backing bean catches it and sets a message:
public void doCreateBook() {
FacesContext ctx = FacesContext.getCurrentInstance();
try {
book = bookEJB.createBook(book);
bookList = bookEJB.findBooks();
} catch (CustomException e) {
ctx.addMessage("titleId", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage()));
}
}
What I except is, when the exception occurs, an error message must be displayed near the input text tag, but it isn't the case, the execution displays the page with list of books and the "Error" message displayed under the list, as shown below:
How can I get the full exception message to show up next to the input field?
Apart from the erroneous message handling which Thinksteep has already answered, your other mistake is that you're doing validation in an action method. This is not right. You should be using JSF builtin validation facilities instead. Whenever the JSF builtin validation fails, then the action method will not be invoked and the page will also not navigate. The enduser sticks to the current form and the message will appear in the therefor specified <h:message> tag.
In your particular case, you just need to set the required attribute.
<h:inputText id="titleId" value="#{bookController.book.title}" required="true" />
<h:message for="titleId" />
If you want to customize the default required message, use requiredMessage attribute.
<h:inputText id="titleId" value="#{bookController.book.title}"
required="true" requiredMessage="Please, type a Title !" />
<h:message for="titleId" />
Remove that input validation from the EJB method. It doesn't belong there. The EJB isn't responsible for that, the caller (which is in your case thus your JSF code) is responsible for that.
ctx.addMessage("titleId", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage()));
Your message text is Error and you are getting same. Change "Error" here to what ever you want.
PUT <h:messages showDetail="true" />

Custom validator fires but does not prevent postback

I've seen a lot of questions about this already, but I'm stumped! Please help!
I have a customvalidator. It's firing but it's not preventing postback. Please help me in doing so! I can see that console.log registers before the post. But, it posts back anyway. How do I prevent the postback?
I've tried adding a control to validate, and validate empty text equal to true. I also tried adding e.preventdefault, which did not work :(
How can I prevent the postback?
<script type="text/javascript">
//<![CDATA[
function validateWhyUnlikely(source, args) {
console.log(1);
args.isValid = false;
}
//]]>
<asp:TextBox ID="txtWhyUnlikely" runat="server" Rows="4" cols="20"
CssClass="surveyTextArea" />
<asp:CustomValidator runat="server" ID="cfvWhyUnlikley" ErrorMessage="Please provide a reason since you rated an item as unlikely to provide."
CssClass="surveyError surveySmallIndent" Display="Dynamic"
ClientValidationFunction="validateWhyUnlikely" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="smallSpecial" OnClick="btnSubmit_Click" />
jQuery(document).ready(function () {
jQuery('#<%= btnSubmit.ClientID %>').click(function (e) {
if (Page.IsValid == false) {
console.log(false);
e.preventDefault();
return false;
}
});
});
Everything looks ok althought I am not sure why you are attaching the Click function to your submit button. I would remove that and test it as it maybe be overriding the default behavior.
Also I think you need to capitalize the IsValid property:
args.IsValid = false;
I too faced this issue, I was trying to add a custom validator to a dropdownlist which had a selectedIndexChange event attached to it. After i gave incorrect value for dropdown, i was able to se ethe error message i gave in Custom Validator but immediately after it Postback was happening.
However on adding this property CausesValidation="true" to the dropdownlist control resolved my issue.
Postback wasn't happening on incorrect value after adding this property to my dropdown.
If it helps other people, I had a Validation group that I forgot to add the button to.
Make sure to add the button, the textbox and the validator to the same validation group for the postback to be prevented.
I experienced this problem as well.
What I did was, in the C# procedure that was called by the button, at the top I added
if (IsValid == false)
return;
I could not stop it performing the postback so this seemed to me like the only solution.
You are misssing ControlToValidate="txtWhyUnlikely"
Posting this as it might help someone that is getting the same weird behavior.
Initially I had the same issue as this post title. I checked all the suggestions here but my code seemed to be fine.
To fix this I replaced my cause validation control <asp:Button.. with a <button.. . Not sure why this is happening but happy it's working now.
hth
<button tags are missing the correct javascript code to validate.
<asp:Button does have the correct javascript rendered.
I've added this to any button tags:
btn.Attributes("onclick") = StringFmt("if(!Page_ClientValidate(''))return false;")
and that solved the post-back issue. No post-back occurs if the client-side detects an issue.
I solved this problem by creating a variable:
Boolean fieldIsValid = true;
and at the custom validating expression I would change the value if arguments weren't true:
if(args.IsValid == false)
{
fieldIsValid = false;
}
else
{
fieldIsValid = true;
}
Then, I also put that in the submit click method:
protected void submit_Click(object sender, EventArgs e)
{
if (fieldIsValid)
{
//submit my things
}
}

Resources