Include Data In A Response/Reply From A Primefaces Push - jsf

Is there a way to include data from the front-end to send to the back end, perhaps in the reply.completed argument, such that if a condition was not met, the front end can inform the backend of the status and the backend and do something with that data? And if so, how?
From the back-end:
Reply reply = new Reply() {
#Override
public void completed(String arg0) {
System.out.println("Reply received: " + arg0);
}
};
summary = this.getText("report.ready.view").replace("{0}", reportName);
reportLink = this.getExternalContextRoot() + reportLink + (!reportLink.contains("?") ? "?reportId=" : "&reportId=") + savedReportStatus.getSavedReportStatusId();
detail = "<a href='" + reportLink + "'>" + this.getText("click.to.view") + "</a>";
facesMessage = new FacesMessage(severity, summary, detail);
eventBus.publish(channel, facesMessage, reply);
From the front-end:
<p:socket onMessage="handleMessage" channel="/reports/#{userSessionBean.userID}" autoConnect="true"/>
<script type="text/javascript">
function handleMessage(message) {
if (DO SOME CHECK) {
if (message.severity == 'INFO 0') {
message.severity = 'info';
} else if (message.severity == 'WARN 1') {
message.severity = 'warn';
} else if (message.severity == 'ERROR 2') {
message.severity = 'error';
} else if (message.severity == 'FATAL 3') {
message.severity = 'fatal';
}
PF('reportsGrowl').show([message]);
updateViewedReports();
} else {
SEND THE BACK-END INFORMATION INDICATING THE CHECK FAILED AND THE MESSAGE WAS NOT SHOWN
}
}
$(document).ready(function () {
updateViewedReports();
});
</script>

Related

Workflow C# string function error in Docusign

I have an code issue in docusign.
In my calculation step I have created and input and output code.
When I run the template and checking the "incoming data" xml in the workflow I have an error message displayed:
<In_80_stackTrace>Exception: at ADEXS.DynamicCode.DynamicClassD_3447d8ccd49f4631b91c31df53e249e7.DynamicMethodD_dcb572b7876d400683579290c5918f06(DynamicContext _context)</In_80_stackTrace>
I don't know how to fix this that it will show only the
logError("In_80_error", "Data node //CategoryName is missing");
when no data is in the node.
Below are the details - my input code:
//In_80 - ESP_CategoryName_Description
string In_80 = "";
{
try
{
if (incomingDataRoot.SelectSingleNode("//CategoryName[node()]").InnerText == null)
{
logError("In_80_error", "Data node //CategoryName is missing");
}
else if (incomingDataRoot.SelectSingleNode("//CategoryName[node()]").InnerText != null)
{
In_80 = incomingDataRoot.SelectSingleNode("//CategoryName[node()]").InnerText;
}
}
catch (Exception e)
{
//logError("In_80_error", "Exception: Message:" + e.Message +" Inner Exception: "+ e.InnerException +" StackTrace: "+ e.StackTrace +" Source: "+ e.Source +" Data: "+ e.Data);
logError("In_80_stackTrace", "Exception: " + e.StackTrace);
}
}
Here is the output code:
//OUT_92 - ESP_CategoryName_Description
var OUT_92 = In_80;
if (In_80 == "")
{
logError("OUT_92_error", "Error reading In_80");
} else {
XmlElement elem = incomingDataRoot.OwnerDocument.CreateElement("OUT_92");
string p_category = "";
int i = 1;
foreach (char item in In_80)
{
if (Char.IsLetter(item))
{
if (i == 1)
{
p_category += item.ToString().ToUpper();
}
else
{
p_category += item.ToString().ToLower();
}
i++;
}
else
{
if (item == ' ')
{
i = 1;
}
p_category += item.ToString();
}
}
OUT_92 = p_category;
elem.InnerText = OUT_92.ToString();
elem.SetAttribute("Name", "ESP_CategoryName_Description");
incomingDataRoot.SelectSingleNode("/Root/Params/TemplateFieldData/Calculation_Results").AppendChild(elem);
}
In incoming data OUT part I'm getting
<OUT_92_error>Error reading In_80</OUT_92_error>
where I assume that its because something is wrong with the input code part?
Thank you for your help!

page.evaluate doesn't work

I want page.evaluate to run when my onLoadFinished is complete. But the following error is coming
MESSAGE: ReferenceError: Can't find variable: page
my code is:
page.property('onLoadFinished', function(status) {
if(status==="success")
{
try{
console.log('==== onLoadFinished()'+status);
page.evaluate(function () {
console.log("++++++++++++++++++"+document);
var Import = document.getElementById("Import");
if (Import){
console.log("+"+Import);
document.getElementById("start").value = "somedate";
document.getElementById("Import").click();
}else{console.log("Import not found");}
})
}catch(ex){
var fullMessage = "\nJAVASCRIPT EXCEPTION";
fullMessage += "\nMESSAGE: " + ex.toString();
for (var p in ex) {
fullMessage += "\n" + p.toUpperCase() + ": " + ex[p];
}
console.log(fullMessage);
}
}
})
page isn't a global variable as far as I know. You could use windows.onload instead.
It fires when the entire page is loaded. So this is what you need!

CSJS addCallback always runs SSJS

Can someone please shed some light on why this CSJS code is always running my SSJS code regardless of the CSJS seeming to return true or false?
CSJS code
message = "Starting Settle ATM Process..."
$(".infoMessage").text(message);
atmID = $("input.atmID").val(); //pull from hidden input
var deferred = atmRPC.closeATMFirstSettle();
deferred.addCallback(function(result){
if (result == "false") {
alert("Close command failed during 1st Settle ATM process. System will retry...");
var insideDeferred = atmMRPC.closeATMSecondSettle();
insideDeferred.addCallback(function(result) {
if (result == "false") {
message = "Close command failed during Settle ATM process. Please try again later."
$(".infoMessage").text(message);
atmRPC.updateInfoMsg(message);
return false;
} else if(result == "true"){
var deferred = atmRPC.settleATMFirst();
deferred.addCallback(function(result){
if (result == "false") {
alert("Settlement failed during 1st attempt. System will retry...");
var insideDeferred = atmMRPC.settleATMSecond();
insideDeferred.addCallback(function(result) {
if (result == "false") {
message = "Settlement failed. Please try again later."
$(".infoMessage").text(message);
atmRPC.updateInfoMsg(message);
return false;
} else if(result == "true"){
message = atmID + " has been successfully Settled."
$(".infoMessage").text(message);
atmRPC.updateInfoMsg(message);
// return true;
}
})
} else if(result == "true"){
message = atmID + " has been successfully Settled."
$(".infoMessage").text(message);
atmRPC.updateInfoMsg(message);
// return true;
}
})
}
})
} else if(result == "true"){
var deferred = atmRPC.settleATMFirst();
deferred.addCallback(function(result){
if (result == "false") {
alert("Settlement failed during 1st attempt. System will retry...");
var insideDeferred = atmMRPC.settleATMSecond();
insideDeferred.addCallback(function(result) {
if (result == "false") {
alert("Settlement failed during 1st attempt. System will retry...");
message = "Settlement failed. Please try again later."
$(".infoMessage").text(message);
atmRPC.updateInfoMsg(message);
return false;
} else if(result == "true"){
message = atmID + " has been successfully Settled."
$(".infoMessage").text(message);
atmRPC.updateInfoMsg(message);
// return true;
}
})
} else if(result == "true"){
message = atmID + " has been successfully Settled."
$(".infoMessage").text(message);
atmRPC.updateInfoMsg(message);
// return true;
}
})
}
})
closeATMFirsSettle and closeATMSecondSettle are identical with exception of the boolean variable
if(atmBean.atmStatus == "OPEN" || atmBean.atmStatus == "WOUNDED") {
var firstTry:boolean = atmBean.closeATM(atmBean.atmID, userBean.userID);
return firstTry.toString();
} else if(atmBean.atmStatus == "CLOSED") {
return "true";
} else {
return "false";
}
settleATMFirst and settleATMSecond are identical with exception of the boolean variable
sessionScope.infoMsg = null;
try {
if(atmBean.atmAmountReceived == null) {
var settleAmt:Integer = Integer.parseInt(atmBean.atmTodaySettlementAmt);
} else {
var settleAmt:Integer = Integer.parseInt(atmBean.atmAmountReceived);
}
} catch(e) {
message:String = "1st Settle ATM Amount Error: " + e;
logInfo(message);
return sessionScope.infoMsg = message;
}
var firstTry:boolean = atmBean.settleATM(atmBean.atmID, userBean.userID, settleAmt);
return firstTry.toString();
atmBean.settleATM
public boolean settleATM(String atmId, String employeeId, Integer settlementAmount, String attempt){
//This method called by RPC control from client JS
AtmOperationSettlementResult result = null;
boolean returnValue = false;
try {
result = AtmTerminalUtil.settleAtm(atmID, employeeId, settlementAmount);
returnValue = result.getSuccess();
if(attempt.equals("Second")) {
System.out.println("ATM Bean - Second Attempt");
if(!returnValue) {
handleATMError(result);
}
}
} catch(Exception e) {
System.out.println(e);
}
//saveATMHistory();
return returnValue; //return status of operation to UI
}
I know the SSJS in the Server tab is always being ran because the log entries show the value of a viewScope that is set if the atmBean.settleATM returns a false.
Sorry, didn't realize until the last comment that everyone may be thinking the SSJS code I'm talking about is in the RPC, but I'm referring to the Server tab.

Error while adding entity object to DBContext object called from Parallel.Foreach loop

Error :
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
Object reference not set to an instance of an object. at
System.Data.Objects.ObjectStateManager.DetectConflicts(IList1
entries) at System.Data.Objects.ObjectStateManager.DetectChanges()
at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean
force) at
System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action,
EntityState newState, Object entity, String methodName) at
System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity)
at System.Data.Entity.DbSet1.Add(TEntity entity) at
ESHealthCheckService.BusinessFacade.BusinessOperationsLayer.AddErrorToDbObject(Exception
ex, Server serverObj, Service windowsServiceObj)
the message resource is present but the message is not found in the string/message table
public void CheckForServerHealth()
{
businessLayerObj.SetStartTimeWindowsService();
List<ServerMonitor> serverMonitorList = new List<ServerMonitor>();
serverList = businessLayerObj.GetServerList();
Parallel.ForEach(
serverList,
() => new List<ServerMonitor>(),
(server, loop, localState) =>
{
localState.Add(serverStatus(server, new ServerMonitor()));
return localState;
},
localState =>
{
lock (serverMonitorList)
{
foreach (ServerMonitor serverMonitor in localState)
{
serverMonitorList.Add(serverMonitor);
}
}
});
businessLayerObj.SaveServerHealth(serverMonitorList);
}
public ServerMonitor serverStatus(Server serverObj, ServerMonitor serverMonitorObj)
{
if (new Ping().Send(serverObj.ServerName, 30).Status == IPStatus.Success)
{
serverMonitorObj.Status = true;
try
{
PerformanceCounter cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total", serverObj.ServerName);
serverMonitorObj.CPUUtlilization = (cpu.NextValue());
}
catch (Exception ex)
{
businessLayerObj.AddErrorObjectToStaticList(ex, serverObj);
}
serverMonitorObj.ServerID = serverObj.ServerID;
try
{
string[] diskArray = serverObj.DriveMonitor.ToString().Split(':');
if (diskArray != null && diskArray.Contains("NA"))
{
serverMonitorObj.DiskSpace = "NA";
}
else
{
serverMonitorObj.DiskSpace = ReadFreeSpaceOnNetworkDrives(serverObj.ServerName, diskArray);
}
}
catch (Exception ex)
{
businessLayerObj.AddErrorObjectToStaticList(ex, serverObj);
}
serverMonitorObj.CreatedDateTime = DateTime.Now;
}
else
{
serverMonitorObj.Status = false;
serverMonitorObj.ServerID = serverObj.ServerID;
//return serverMonitorObj;
}
return serverMonitorObj;
}
public void AddErrorObjectToStaticList(Exception ex, Server serverObj = null, Service windowsServiceObj = null)
{
EShelathLoging esLogger = new EShelathLoging();
esLogger.CreateDatetime = DateTime.Now;
if (ex.InnerException != null)
{
esLogger.Message = (windowsServiceObj == null ? ex.InnerException.Message : ("Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.InnerException.Message));
//esLogger.Message = "Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.InnerException.Message;
esLogger.StackTrace = (ex.InnerException.StackTrace == null ? "" : ex.InnerException.StackTrace);
}
else
{
esLogger.Message = (windowsServiceObj == null ? ex.Message : ("Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.Message));
//esLogger.Message = "Service Name : " + windowsServiceObj.ServiceName + "-->" + ex.Message;
esLogger.StackTrace = ex.StackTrace;
}
if (serverObj != null)
{
esLogger.ServerName = serverObj.ServerName;
}
try
{
lock (lockObject)
{
esHealthCheckLoggingList.Add(esLogger);
}
}
catch (Exception exe)
{
string logEntry = "Application";
if (EventLog.SourceExists(logEntry) == false)
{
EventLog.CreateEventSource(logEntry, "Windows and IIS health check Log");
}
EventLog eventLog = new EventLog();
eventLog.Source = logEntry;
eventLog.WriteEntry(exe.Message + " " + exe.StackTrace, EventLogEntryType.Error);
}
}
And then the below function is called to add objects from static list to the db object.
public void AddErrorToDbObject()
{
try
{
foreach (EShelathLoging eslogObject in esHealthCheckLoggingList)
{
lock (lockObject)
{
dbObject.EShelathLogings.Add(eslogObject);
}
}
}
catch (DbEntityValidationException exp)
{
string logEntry = "Application";
if (EventLog.SourceExists(logEntry) == false)
{
EventLog.CreateEventSource(logEntry, "Windows and IIS health check Log");
}
EventLog eventLog = new EventLog();
eventLog.Source = logEntry;
eventLog.WriteEntry(exp.Message + " " + exp.StackTrace, EventLogEntryType.Error);
}
catch (Exception exe)
{
string logEntry = "Application";
if (EventLog.SourceExists(logEntry) == false)
{
EventLog.CreateEventSource(logEntry, "Windows and IIS health check Log");
}
EventLog eventLog = new EventLog();
eventLog.Source = logEntry;
eventLog.WriteEntry(exe.Message + " " + exe.StackTrace, EventLogEntryType.Error);
}`enter code here`
}
DbSet<T> is not thread-safe, so you can't use it from multiple threads at the same time. It seems you're trying to fix that by using a lock, but you're doing that incorrectly. For this to work, all threads have to share a single lock object. Having separate lock object for each thread, like you do now, won't do anything.
Please note that I received the same exception with the application I was working on, and determined that the best way to resolve the issue was to add an AsyncLock, because of what #svick mentioned about how DbSet is not threadsafe. Thank you, #svick!
I'm guessing that your DbContext is inside your businessLayerObj, so here is what I recommend, using Stephen Cleary's excellent Nito.AsyncEx (see https://www.nuget.org/packages/Nito.AsyncEx/):
using Nito.AsyncEx;
// ...
private readonly AsyncLock _dbContextMutex = new AsyncLock();
public void CheckForServerHealth()
{
using (await _dbContextMutex.LockAsync().ConfigureAwait(false))
{
await MyDbContextOperations(businessLayerObj).ConfigureAwait(false);
}
}
private async Task MyDbContextOperations(BusinessLayerClass businessLayerObj)
{
await Task.Run(() =>
{
// operations with businessLayerObj/dbcontext here...
});
}

How to make a Sharepoint Survey window open on page load

I've been working on looking for an answer to this issue for several days. I've created a survey on a Sharepoint 2010 site, and the person who I made it for wants it to open in a modal window on page load, instead of having to click "Respond to Survey" for this to happen.
I've tried multiple javascript based solutions, and so far I've gotten nothing. Is there any way to do this? And, if there is, is it possible that this solution could be ported to other pages, so that I can make other surveys or other sharepoint pages open in a modal window (on page load) instead of on a separate page?
Use .../yoursite/lists/yoursurvey/NewForm.aspx - It seems the Advanced setting "use open forms in dialog" doesn't work.
I have made this for a policy window. I made the whole thing inside of a content editor webpart which basically in invisible because the code has no appearence and I set the chrome type to none.
The other option is a feature which would replace the masterpage which is also not hard but requires a developement system for VS2010.
For the first method mentioned. You may have to strip the cookie stuff if you want it to load every time.
Create a new Content Editor Web Part with this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="disclaimer.js"></script>
Then create disclaimer.js:
_spBodyOnLoadFunctionNames.push("initialDisclaimerSetup");
var dialogTitle = "";
var dialogBody = "";
var dialogReturn = "";
var userID = _spUserId;
function initialDisclaimerSetup() {
if(getCookie("DisclaimerShown" + userID) == "Yes") {
return;
} else {
setCookie("DisclaimerShown" + userID, "No", 365);
}
getDisclaimerListItems();
}
function setCookie(cookieName, cookieValue, numExpireDays) {
var expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + numExpireDays);
document.cookie = cookieName + "=" + cookieValue + ";" +
"expires=" + ((numExpireDays == null) ? "" : expirationDate.toUTCString());
}
function getCookie(cookieName) {
if(document.cookie.length > 0) {
return document.cookie.split(";")[0].split("=")[1];
} else {
return "";
}
}
function getDisclaimerListItems() {
var listName = "Disclaimer";
var soapEnv = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\/\">"
+ "<soap:Body>"
+ "<GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">"
+ "<listName>" + listName + "</listName>"
+ "<query><Query><Where><IsNotNull><FieldRef Name=\"Title\" /></IsNotNull></Where></Query></query>"
+ "<ViewFields><ViewFields>"
+ "<FieldRef Name=\"Title\"/><FieldRef Name=\"Disclaimer\"/>"
+ "</ViewFields></ViewFields>"
+ "</GetListItems>"
+ "</soap:Body>"
+ "</soap:Envelope>";
$.ajax({
url: "_vti_bin/Lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
contentType: "text/xml; charset=\"utf-8\"",
complete: processResult
});
}
function processResult(xData, status) {
$(xData.responseXML).find("z\\:row").each(function() {
dialogTitle = $(this).attr("ows_Title");
dialogBody = $(this).attr("ows_Disclaimer");
launchModelessDialog();
if(dialogReturn == 0) {
return false;
} else if(dialogReturn == 1) {
} else if(dialogReturn == 2) {
return false;
}
});
if(dialogReturn == 0) {
getDisclaimerListItems();
} else if(dialogReturn == 1) {
setCookie("DisclaimerShown" + userID, "Yes", 365);
} else if(dialogReturn == 2) {
window.close();
}
}
function GetRootUrl() {
var urlParts = document.location.pathname.split("/");
urlParts[urlParts.length - 1] = "";
return "https://" + document.location.hostname + urlParts.join("/");
}
function launchModelessDialog(){
if (window.showModalDialog) {
window.showModalDialog("./disclaimer.htm", window, "dialogWidth:700px;dialogHeight:700px");
} else {
objPopup = window.open("./disclaimer.htm", "popup1", "left=100,top=100,width=800,height=800,location=no,status=yes,scrollbars=yes,resizable=yes, modal=yes");
objPopup.focus();
}
}
Then create disclaimer.htm:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<script type="text/javascript">
function initialRun() {
//var allArgs = dialogArguments;
var dialogTitle = dialogArguments.dialogTitle;
var dialogBody = dialogArguments.dialogBody;
dialogArguments.dialogReturn = "0";
document.getElementById('mainWrapper').innerHTML = "<h1>" + dialogTitle + "</h1>"
+ "<br/>" + dialogBody + "<br/><br/>";
}
function returnYes() {
dialogArguments.dialogReturn = 1;
window.close();
}
function returnNo() {
dialogArguments.dialogReturn = 0;
window.close();
}
function returnClose() {
dialogArguments.dialogReturn = 2;
window.close();
}
</script>
</head>
<body onload="initialRun()">
<div id="mainWrapper">
</div>
<div align="center">
<input name="acceptTOS" type="button" value="I Accept" onClick="returnYes();" />
<input name="acceptTOS" type="button" value="I Do NOT Accept" onClick="returnNo();" />
<input name="acceptTOS" type="button" value="Close" onClick="returnClose();" />
</div>
</body>
</html>
Then create a new Custom List called 'Disclaimer' and add a new column called 'Disclaimer' which allows for free text.

Resources