struts2 jqgrid: onEditInlineErrorTopics not being called on error - struts2

On save of the jqgrid, the action catches a constraint violation exception and returns "error". However, the onEditInlineErrorTopics function is not called on the jsp. The exception needs to be translated to a user message saying "Duplicate Records"
The code is as follows:
JSP grid Code
<sjg:grid id="gridtable"
dataType="json"
href="%{remoteurl}"
loadonce="true"
pager="true"
navigator="true"
scroll="true"
navigatorAdd="false"
navigatorEdit="false"
navigatorView="false"
navigatorDelete="true"
navigatorDeleteOptions="{height:220,reloadAfterSubmit:true,url:'%{deleteurl}'}"
gridModel="gridModel"
rowList="10,15,20"
rowNum="15"
navigatorRefresh="false"
navigatorSearch="false"
editurl="%{editurl}"
editinline="true"
navigatorInlineEditButtons="true"
gridview="true"
viewrecords="false"
shrinkToFit="true"
onEditInlineErrorTopics="onediterror">
Tried these tags as well
errorElementId, errorText & onErrorTopics
Action header (annotations)
#ParentPackage(value = "basicstruts2")
#Action(value = "/editDetails",
results = {
#Result(name="success",type="json"),
#Result(name="error",type="json"),
#Result(name="none",type="json"),
#Result(name="input",type="json")
})
Action catch block
catch(Exception e){
addActionError("Duplicate Records. Please enter again.");
return "error";
}
The Json string created is:
{"JSON":"error","field1":"1","field2":3,"oper":"edit","field3":5,"field4":"9","field5":null,"field6":null,"field7":"19","field8":156}
Tried throwing exception in the catch block but it shows the stacktrace in a popup.
Tried the success topic onEditInlineSuccessTopics as mentioned in the showcase here and it works fine.

Related

exception inside of OnException

I created a custom attribute, inheriting from HandleErrorAttribute:
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
try
{
Utility.LogAndNotifyOfError(filterContext.Exception, null, true);
}
catch(Exception ex)
{
filterContext.Exception = ex;
}
}
}
, and then registered with:
filters.Add(new CustomHandleErrorAttribute());
This has always worked as intended. However a common problem with my log method is that it uses a custom event log source when writing to the event log, which the app pool account typically doesn't have the permissions to create. Creating the event log source is a simple powershell script, however I wanted to actually include that tidbit in the error:
try
{
log.WriteEntry(error, EventLogEntryType.Error);
}
catch(SecurityException ex1)
{
throw new ErrorHandlerException($"The event log could not be written to due to a SecurityExcption. The likely issue is that the '{eventLogSource}' does not already exist. Please run the following powershell command:\r\n"
+ $"New - EventLog - LogName Application - Source {eventLogSource}", ex1);
}
The problem is that the catch in the OnException is never hit. When debugging, the custom error I throw from LogAndNotifyOfError instead triggers a second call to OnException, and the detail of my ErrorHandlerException is never seen. I want the asp.net error page that comes up to be with my custom error detail rather than the SecurityException that was originally raised.
You can even see the surrounding try in the displayed error:
Edit: Entire log method listed:
public static void LogAndNotifyOfError(Exception ex, String extraInfo, Boolean sendEmail)
{
//if the error handler itself faulted...
if (ex is ErrorHandlerException)
return;
string eventLogName = "Application";
string eventLogSource = "MySourceName";
String error = ex.ToString();
if (error.Length > 28000)
error.Substring(0, 28000);//event log is limited to 32k
error += "\r\n\r\nAdditional Information: \r\n"
+ "Machine Name: " + Environment.MachineName + "\r\n"
+ "Logged in user:" + App.CurrentSecurityContext.CurrentUser?.UserId + "\r\n"
+ extraInfo + "\r\n";
EventLog log = new EventLog(eventLogName);
log.Source = eventLogSource;
try
{
log.WriteEntry(error, EventLogEntryType.Error);
}
catch(SecurityException ex1)
{//this doesn't work - for some reason, OnError still reports the original error.
throw new ErrorHandlerException($"The event log could not be written to due to a SecurityExcption. The likely issue is that the '{eventLogSource}' does not already exist. Please run the following powershell command:\r\n"
+ $"New - EventLog - LogName Application - Source {eventLogSource}", ex1);
}
//if the email-to field has been set...
if (!String.IsNullOrEmpty(App.Config.General.ErrorHandlerSendToAddresses) && sendEmail)
{
//...then send the email
MailMessage email = new MailMessage();
email.To.Add(App.Config.General.ErrorHandlerSendToAddresses);
email.IsBodyHtml = false;
email.Subject = String.Format("Error in {0}", eventLogSource);
email.Body = email.Subject + "\r\n\r\n"
//+ "Note: This error may be occuring continuously, but this email is only sent once per hour, per url, in order to avoid filling your mailbox. Please check the event log for reoccurances and variations of this error.\r\n\r\n"
+ "The error description is as follows: \r\n\r\n"
+ error + "\r\n\r\n";
SmtpClient smtp = new SmtpClient();
smtp.Send(email);
}
}
I figured it out (sort of). It would appear that when the newly throw exception has an inner exception, it is only displaying that inner exception. It does not matter what the type is on the outer or inner exception.

Unable to print error message in foreach in magento admin

Hi i have added a new mas action in the sales order grid which allow create batch invoices.
For this my controler file is
<?php
class Iclp_Batchupdate_IndexController extends Mage_Adminhtml_Controller_Action
public function batchinvoiceAction ()
{
$already = " already ";
$refererUrl = $this->getRequest()->getServer('HTTP_REFERER');
$this->loadLayout();
$this->renderLayout();
$orderIds = explode(",",$this->getRequest()->getParam('order_ids'));
foreach ($orderIds as $orderIdss) {
$order = Mage::getModel('sales/order')->load($orderIdss);
//echo $orderIdss ."<br/>";
//echo "already ".$order->getStatusLabel();
try
{
if(!$order->canInvoice())
{
echo Mage::getSingleton('core/session')->addError($orderIdss.$already.$order->getStatusLabel());
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder());
$transactionSave->save();
$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
//echo "Invoice are created";
}
catch (Mage_Core_Exception $e) {
}
}
//A Success Message
Mage::getSingleton('core/session')->addSuccess("Some success message");
//A Error Message
Mage::getSingleton('core/session')->addError("Some error message");
//A Info Message (See link below)
Mage::getSingleton('core/session')->addNotice("This is just a FYI message...");
//These lines are required to get it to work
session_write_close();
$this->getResponse()->setRedirect($refererUrl);
}
}
every thing is working fine but the problem is it is not printing the error message in foreach in above code
if(!$order->canInvoice())
{
echo Mage::getSingleton('core/session')->addError($orderIdss.$already.$order->getStatusLabel());
}
but the bottom error message are displayed properly. MOreover if i extend the class with front-action than it also prints the foreach messages. Please suggest where i am doing the mistake
You should add your errors and messages to admintml/session and not to core/session when you are in adminhtml. That should display the message correctly. You shouldn't need session_write_close();. There is also no need to echo the message, that should be handled automatically by Magento after the redirect.
There is also no need to call $this->loadLayout(); and $this->renderLayout(); because you are redirecting at the end.
Finally, regarding the redirect, you should not read the referrer yourself, Magento can to that for you more reliably. Just use the $this->_redirectReferer(); method instead of $this->getResponse()->setRedirect($refererUrl);.

return back the value of g:textfield

how can i show back the g:textfield value if the value already havebeen taken.
example :
<input type="text" name="simbol" id="simbol" value="${simbol}"/>
when input the textfield with "1A" then SAVE to database, then i input again with type "1A" again. it will be error because i protect with unique : true, when eror it will be return the input page..
and filled by "1A"
how can i do to get the "1A" when save error and return to the page?
catch(Exception E)
{
[simbol: params.simbol?: "",nama : params.nama?:""]
flash.message = "Simbol Sudah Dipakai !!! "
redirect (action:"tambah")
}
i use try cacth to throw unique save error.
and
[simbol: params.simbol?: "",nama : params.nama?:""], this line i tried to throw/get back the value when save eror or unique
You need put back data into model and `render page.
In your code you redirect without params at all.
This is the common way to do that you need. (Controller code)
def unInstance = new Un(params)
if (!unInstance.save(flush: true)) {
render(view: "create", model: [unInstance: unInstance])
return
}
....
}

Breeze.js How to display Validation Error Message

during Save changes, there are instance when validation is failing, but how do i get back and display the actual Error Message. The saveFailed function is executed, but i want more details information, about what validations failed and those individual error emssages
function saveChanges() {
if (manager.hasChanges()) {
manager.saveChanges()
.then(saveSucceeded)
.fail(saveFailed);
} else {
alert("Nothing to save");
};
};
function saveSucceeded() {
alert("changes saved successfully");
};
function saveFailed(error) {
alert("Error while saving changes" + error.message);
};
Have a look at the TODO sample that is provided with the breeze download.
The dataservice.js clearly shows you how to catch and display validation errors.
The 'error' object returned by the fail handler, should contain additional details, depending on the error. The following properties should always be there
error.message - the error message
error.status - http error code - usually a 400 or 500 code
error.detail - any details relevant to the error
error.XHR - the raw XML HttpResponse object
error.responseText
For validation errors, right now they appear in the error.message, but we are looking at breaking them out in a cleaner fashion, possibly into another property. But for now they will appear in the error.message.

Asp.net | STAThread attribute error

I want to open a FolderBrowseDialog on button click in MVC razor(VB) syntax.
For that i am calling a jquery function on "onclick" button event and through that function i am making a Post request to function in my controller that contains code to show FolderBrowseDialog.
here is my code.
Html:
<input type="button" class="btn" value="browse" onclick="SelectFolder()"/>
jquery:
<script type="text/javascript">
function SelectFolder()
{
$.post("#Url.Action("FolderPicker", "Home")", function () {
alert('sdd');
},function(ex){
alert("Error occured in AJAX");
});
}
</script>
Controller.. vb code to show FolderBrowserDialog.
<STAThreadAttribute()>
Sub FolderPicker()
Dim browser As FolderBrowserDialog = New FolderBrowserDialog()
browser.Description = "Select Folder"
browser.ShowNewFolderButton = False
browser.RootFolder = Environment.SpecialFolder.Desktop
Dim result As DialogResult = browser.ShowDialog()
If result = DialogResult.OK Then
Dim selectedPath As String = browser.SelectedPath
End If
End Sub
At
Dim result As DialogResult = browser.ShowDialog()
i am getting exception
Current thread must be set to single thread apartment (STA) mode before OLE
calls can be made. Ensure that your Main function has STAThreadAttribute
marked on it. This exception is only raised if a debugger is attached to the
process.
I also included STATreadAttribute() and STATread() but still i get this error.
Am i missing some thing?
Is there any other way to do it?
FolderBrowseDialog is not available in ASP.NET/MVC.
You can read some more stuff here.
the STATreadAttribute should be on the Main function of your program,meaning the entry point of the program

Resources