ESP8266 webserver doesn't communicate properly using AJAX - c++

I've recently purchased a ESP8266, and started playing around with it. I made a website, that has three buttons to control 3 LEDs with the board. The site uses XML AJAX and JavaScript to communicate with the ESP. I'm going to be honest, I have very little clue to what I am doing. The ESP successfully connects to my WiFi and serves the website, but for some reason, that I am clueless to, the ESP doesn't serve the XML file.
If this is the wrong place to post this, I apologize.
ESP Code:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "page.h"
//LED Pin defenition.
const int led1 = 14;
const int led2 = 12;
const int led3 = 13;
#define SSID "Orlando"
#define PASS "orlando123"
#define AP_SSID "ESP2866"
#define AP_PASS "password"
bool led11 = false;
bool led22 = false;
bool led33 = false;
char XML[1024];
IPAddress Actual_IP;
//Start a server at port 80.
ESP8266WebServer server(80);
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
Serial.begin(9600);
for (int i = 12;i < 15;i++){
digitalWrite(i, LOW);
}
//Initliaizes WIFI
WiFi.begin(SSID, PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("IP address: "); Serial.println(WiFi.localIP());
Actual_IP = WiFi.localIP();
server.on("/", sendWebsite);
server.on("/xml", SendXML);
//If the ESP recieves the "BUTTON_1" string, it will run the ProcessButton_1 method.
server.on("/BUTTON_1", ProcessButton_1);
server.on("/BUTTON_2", ProcessButton_2);
server.on("/BUTTON_3", ProcessButton_3);
server.begin();
}
void loop() {
server.handleClient();
}
//Method for sending the site.
void sendWebsite() {
server.send(200, "text/html", WEBSITE);
Serial.println("Sending website.");
}
//Method for sendind the XML info.
void SendXML() {
Serial.println("sending xml");
strcpy(XML, "<?xml version = '1.0'?>\n<Data>\n");
if (led1) {
strcat(XML, "<LED1>1</LED1>\n");
}
else {
strcat(XML, "<LED1>0</LED1>\n");
}
if (led2) {
strcat(XML, "<LED2>1</LED2>\n");
}
else {
strcat(XML, "<LED2>0</LED2>\n");
}
if (led3) {
strcat(XML, "<LED3>1</LED3>\n");
}
else {
strcat(XML, "<LED3>0</LED3>\n");
}
strcat(XML, "</Data>\n");
server.send(200, "text/xml", XML);
Serial.println("Sending XML");
Serial.println(XML);
}
void ProcessButton_1() {
led11 != led11;
digitalWrite(led1, led11);
server.send(200, "text/plain", "");
Serial.println("Processing button1");
}
void ProcessButton_2() {
led22 != led22;
digitalWrite(led2, led22);
server.send(200, "text/plain", "");
Serial.println("Processing button2");
}
void ProcessButton_3() {
led33 != led33;
digitalWrite(led3, led33);
server.send(200, "text/plain", "");
Serial.println("Processing button3");
}
Website code:
<!DOCTYPE html>
<html lang="en" class="js-focus-visible">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Webserver</title>
</head>
<body onload="process()">
<div class="container">
<div class="header">
<h1>Panel</h1>
<br>
</div>
<div class="controls">
<table>
<tr>
<th>
<p>BLUE LED</p>
<button type="button" class="button1" id="sw1" onclick="ButtonPress1()">
ON/OFF
</button>
</th>
<th>
<p>RED LED</p>
<button type="button" class="button2" id="sw2" onclick="ButtonPress2()">
ON/OFF
</button>
</th>
<th>
<p>GREEN LED</p>
<!--ButtonPress3() - calls to a javascript function-->
<button type="button" class="button3" id="sw3" onclick="ButtonPress3()">
ON/OFF
</button>
</th>
</tr>
</table>
</div>
</div>
</body>
<script type = "text/javascript">
// Creates XmlHttpObject
var xmlHttp=createXmlHttpObject();
function createXmlHttpObject(){
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}
else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
//All the functions are for the correspoding button on the website:
function ButtonPress1() {
var xhttp = new XMLHttpRequest();
var message;
//Opens a request, specifies type of request, data to send
//in this case a string: "BUTTON_1", and if request is synchrounous.
xhttp.open("PUT", "BUTTON_1", false);
xhttp.send();
}
function ButtonPress2() {
var xhttp = new XMLHttpRequest();
var message2;
//Opens a request, specifies type of request, data to send
//in this case a string: "BUTTON_2", and if request is synchrounous.
xhttp.open("PUT", "BUTTON_2", false);
xhttp.send();
}
function ButtonPress3() {
var xhttp = new XMLHttpRequest();
var message3;
//Opens a request, specifies type of request, data to send
//in this case a string: "BUTTON_3", and if request is synchrounous.
//xttp.open sends a string, in this case "BUTTON_3", this signals the
//ESP, that a button has been pressed.
xhttp.open("PUT", "BUTTON_3", false);
xhttp.send();
}
function ESP_response() {
var message1;
var message2;
var message3;
var xmlResponse;
//Read the XML stream.
xmlResponse=xmlHttp.responseXML;
if(message1 == 0 ) {
document.getElementById("sw1").innerHTML="OFF";
}
else {
document.getElementById("sw1").innterHTML="ON";
}
if(message2 == 0 ) {
document.getElementById("sw2").innerHTML="OFF";
}
else {
document.getElementById("sw2").innterHTML="ON";
}
if(message3 == 0 ) {
document.getElementById("sw3").innerHTML="OFF";
}
else {
document.getElementById("sw3").innterHTML="ON";
}
}
function process(){
if(xmlHttp.readyState==0 || xmlHttp.readyState==4) {
xmlHttp.open("PUT","xml",true);
xmlHttp.onreadystatechange=response;
xmlHttp.send(null);
}
setTimeout("process()",200);
}
</script>
</html>
Thanks in advance.
I expect the ESP to respond to the button presses on the site.
I haven't tried anything, as I don't have any experience to help me with this.

Related

How to integrate novnc client inside django project

I have a couple virtual machines running inside proxmox but I found out you can use the novnc client to connect to these virtual machines and use the console in a web browser. This is perfect for different clients I work with. I already have a small django project that shows the running nodes and vm's inside of them. Now I wanted to include de js library by novnc. However I can't really find a lot of information online and since my coding experience is not that high I don't really know what I am doing wrong.
I used this outdated repo and tried to see if I can find out how to get it to work. https://github.com/missuor/novnc-proxy-django
for now I have a view that call the api of proxmox. /api2/json/nodes/{node}/lxc/{vmid}/vncproxy to be precise. this returns a ticket, port, cert, user and upid. Now I am not sure if I just need to call the vncproxy or use these variable to open a websocket by /api2/json/nodes/{node}/lxc/{vmid}/vncwebsocket. The django view i currently have just call the vncproxy and sends the values to the rendered template.
This template I used from the repo metioned above, but I just don't know why I keep ketting a Server Disconnected(code 1006 error). If you have any tips for me that would be of great help.
this is the view I currently use which receives all the correct values.
def vnc(request, node, vmid):
vncproxy = proxmox_vnc().vncproxyVirtualMachine(node, vmid)
token = vncproxy['data']['ticket']
port = vncproxy['data']['port']
host = 'Settings.vnxproxy'
password = ''
print(token)
return render(request, 'vnc_auto.html', {'token': token, 'host': host, 'port': port, 'password': password})
And this below is the vnc.html I use to render and uses the novnc client.
{% load static %}
<!DOCTYPE html>
<html>
<head>
<!--
noVNC example: simple example using default UI
Copyright (C) 2012 Joel Martin
Copyright (C) 2013 Samuel Mannehed for Cendio AB
noVNC is licensed under the MPL 2.0 (see LICENSE.txt)
This file is licensed under the 2-Clause BSD license (see LICENSE.txt).
Connect parameters are provided in query string:
http://example.com/?host=HOST&port=PORT&encrypt=1&true_color=1
-->
<title>noVNC</title>
<meta charset="utf-8">
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<!-- Apple iOS Safari settings -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<!-- App Start Icon -->
<link rel="apple-touch-startup-image" href="{% static 'novnc/images/screen_320x460.png' %}" />
<!-- For iOS devices set the icon to use if user bookmarks app on their homescreen -->
<link rel="apple-touch-icon" href="{% static 'novnc/images/screen_57x57.png' %}">
<!--
<link rel="apple-touch-icon-precomposed" href="{% static 'novnc/images/screen_57x57.png' %}" />
-->
<script>var INCLUDE_URI='/static/novnc/include/'</script>
<!-- Stylesheets -->
<link rel="stylesheet" href="{% static 'novnc/include/base.css' %}" title="plain">
<!--
<script type='text/javascript'
src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
-->
<script src="{% static 'novnc/include/util.js' %}"></script>
</head>
<body style="margin: 0px;">
<div id="noVNC_screen">
<div id="noVNC_status_bar" class="noVNC_status_bar" style="margin-top: 0px;">
<table border=0 width="100%"><tr>
<td><div id="noVNC_status" style="position: relative; height: auto;">
Loading
</div></td>
<td width="1%"><div id="noVNC_buttons">
<input type=button value="Send CtrlAltDel"
id="sendCtrlAltDelButton">
<span id="noVNC_xvp_buttons">
<input type=button value="Shutdown"
id="xvpShutdownButton">
<input type=button value="Reboot"
id="xvpRebootButton">
<input type=button value="Reset"
id="xvpResetButton">
</span>
</div></td>
</tr></table>
</div>
<canvas id="noVNC_canvas" width="640px" height="20px">
Canvas not supported.
</canvas>
</div>
<script>
/*jslint white: false */
/*global window, $, Util, RFB, */
"use strict";
// Load supporting scripts
Util.load_scripts(["webutil.js", "base64.js", "websock.js", "des.js",
"keysymdef.js", "keyboard.js", "input.js", "display.js",
"jsunzip.js", "rfb.js", "keysym.js"]);
var rfb;
function passwordRequired(rfb) {
var msg;
msg = '<form onsubmit="return setPassword();"';
msg += ' style="margin-bottom: 0px">';
msg += 'Password Required: ';
msg += '<input type=password size=10 id="password_input" class="noVNC_status">';
msg += '<\/form>';
$D('noVNC_status_bar').setAttribute("class", "noVNC_status_warn");
$D('noVNC_status').innerHTML = msg;
}
function setPassword() {
rfb.sendPassword($D('password_input').value);
return false;
}
function sendCtrlAltDel() {
rfb.sendCtrlAltDel();
return false;
}
function xvpShutdown() {
rfb.xvpShutdown();
return false;
}
function xvpReboot() {
rfb.xvpReboot();
return false;
}
function xvpReset() {
rfb.xvpReset();
return false;
}
function updateState(rfb, state, oldstate, msg) {
var s, sb, cad, level;
s = $D('noVNC_status');
sb = $D('noVNC_status_bar');
cad = $D('sendCtrlAltDelButton');
switch (state) {
case 'failed': level = "error"; break;
case 'fatal': level = "error"; break;
case 'normal': level = "normal"; break;
case 'disconnected': level = "normal"; break;
case 'loaded': level = "normal"; break;
default: level = "warn"; break;
}
if (state === "normal") {
cad.disabled = false;
} else {
cad.disabled = true;
xvpInit(0);
}
if (typeof(msg) !== 'undefined') {
sb.setAttribute("class", "noVNC_status_" + level);
s.innerHTML = msg;
}
}
function xvpInit(ver) {
var xvpbuttons;
xvpbuttons = $D('noVNC_xvp_buttons');
if (ver >= 1) {
xvpbuttons.style.display = 'inline';
} else {
xvpbuttons.style.display = 'none';
}
}
window.onscriptsload = function () {
var host, port, password, path, token;
$D('sendCtrlAltDelButton').style.display = "inline";
$D('sendCtrlAltDelButton').onclick = sendCtrlAltDel;
$D('xvpShutdownButton').onclick = xvpShutdown;
$D('xvpRebootButton').onclick = xvpReboot;
$D('xvpResetButton').onclick = xvpReset;
WebUtil.init_logging(WebUtil.getQueryVar('logging', 'warn'));
document.title = unescape(WebUtil.getQueryVar('title', 'noVNC'));
// By default, use the host and port of server that served this file
host = WebUtil.getQueryVar('host', '{{host}}'?'{{host}}':window.location.hostname);
port = WebUtil.getQueryVar('port', {{port}}?{{port}}:window.location.port);
// if port == 80 (or 443) then it won't be present and should be
// set manually
if (!port) {
if (window.location.protocol.substring(0,5) == 'https') {
port = 443;
}
else if (window.location.protocol.substring(0,4) == 'http') {
port = 80;
}
}
// If a token variable is passed in, set the parameter in a cookie.
// This is used by nova-novncproxy.
token = WebUtil.getQueryVar('token', null);
if (token) {
WebUtil.createCookie('token', token, 1)
}
password = WebUtil.getQueryVar('password', '{{password}}'?'{{password}}':'');
path = WebUtil.getQueryVar('path', '{{path}}'?'{{path}}':'');
path += '?token='+token;
if ((!host) || (!port)) {
updateState('failed',
"Must specify host and port in URL");
return;
}
rfb = new RFB({'target': $D('noVNC_canvas'),
'encrypt': WebUtil.getQueryVar('encrypt',
(window.location.protocol === "https:")),
'repeaterID': WebUtil.getQueryVar('repeaterID', ''),
'true_color': WebUtil.getQueryVar('true_color', true),
'local_cursor': WebUtil.getQueryVar('cursor', true),
'shared': WebUtil.getQueryVar('shared', true),
'view_only': WebUtil.getQueryVar('view_only', false),
'onUpdateState': updateState,
'onXvpInit': xvpInit,
'onPasswordRequired': passwordRequired});
console.log(host, port, password, path);
rfb.connect(host, port, password, path);
};
</script>
</body>
</html>

Xamarin binding sometimes invisible

Inside my Xamarin TicketPage.xaml the binding just shows after a change of the bindingname to notesBlobbed. So i need to change the binding name to notesBlobbed and change it back to notes for displaying the bindings. Moreover, the notes disappear when leaving the page and are not displayed at startup. The first picture shows what it looks like at startup and after leaving the page. The second picture shows how it looks like with the change. The question is how can i display the notes the whole time?
PS: notesBlobbed is needed to deserialize the list for the SQLite datebase.
How it looks like:
https://s20.directupload.net/images/220512/zjdu9nz2.jpg (cant display images because of my reputation)
How it should looks like:
https://s20.directupload.net/images/220512/p6ssqxjt.jpg
TicketPage.xaml
<ContentPage.Content>
<ScrollView>
<StackLayout Padding="10,5,10,5">
<ListView x:Name="ListViewTicket" HasUnevenRows="True" SelectionMode="None" SeparatorVisibility="None" Margin="0,0,0,0">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame CornerRadius="10" BorderColor="Black" Margin="0,5,0,5">
<StackLayout>
<Label>
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text="ID: " FontAttributes="Bold" FontSize="18"/>
<Span Text="{Binding pkid}" FontSize="18"/>
</FormattedString.Spans>
</FormattedString>
</Label.FormattedText>
</Label>
<Label>
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text="Ticketnummer: " FontAttributes="Bold" FontSize="18"/>
<Span Text="{Binding ticketNumber}" FontSize="18"/>
</FormattedString.Spans>
</FormattedString>
</Label.FormattedText>
</Label>
<Label>
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text="Status: " FontAttributes="Bold" FontSize="18"/>
<Span Text="{Binding status}" FontSize="18"/>
</FormattedString.Spans>
</FormattedString>
</Label.FormattedText>
</Label>
<BoxView HorizontalOptions="FillAndExpand" HeightRequest="3" Color="Gray"/>
<Label Text="Betreff" FontAttributes="Bold" FontSize="18"/>
<Label Text="{Binding subject}" FontSize="18" Margin="0,-5,0,0"/>
<Label TextType="Html" Text="{Binding description}" FontSize="12"/>
<Label Text="Notiz" FontAttributes="Bold" FontSize="18" Margin="0,-10,0,0"/>
<!-- here is the problem -->
<StackLayout BindableLayout.ItemsSource="{Binding notes}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label Text="{Binding .}" MaxLines="2" LineBreakMode="TailTruncation"/>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ScrollView>
</ContentPage.Content>
TicketPage.cs
public partial class TicketPage : ContentPage
{
public TicketPage()
{
InitializeComponent();
OnAppearing();
}
//Update & Delete Zeiten
const int deleteInterval = 259200000; //3 Tage
const int updateInterval = 900000; //15 Mins
protected async override void OnAppearing()
{
//lädt Tickets
var ticketList = await App.Database.GetTicket();
//lässt Tickets anzeigen
ListViewTicket.ItemsSource = ticketList;
//alle Tickets durchgehen bezüglich Updates & Delete
foreach (var ticket in ticketList)
{
//überprüft wie lange Ticket geschlossen ist (löscht bei 3 Tagen)
if (ticket.status == "closed")
{
var currentTime = DateTime.Now;
TimeSpan duration = currentTime - ticket.closed;
var result = duration.TotalMilliseconds;
if (result > deleteInterval)
{
await App.Database.DeleteTicket(ticket);
}
}
else
{
//updatet Ticket nach 15 Minuten
var currentTime = DateTime.Now;
TimeSpan duration = currentTime - ticket.updated;
var result = duration.TotalMilliseconds;
if (result < updateInterval)
{
continue;
}
//GET an API um Status & Notizen abzurufen
IsBusy = true;
var ticketId = ticket.id;
var url = "https://.../api/ticket/info/" + ticketId;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("AuthenticationToken", "Token");
HttpResponseMessage response = await client.GetAsync(url);
//updatet Status und Notizen
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Ticket update = JsonConvert.DeserializeObject<Ticket>(content);
ticket.status = update.status;
ticket.updated = DateTime.Now;
if (ticket.status == "closed")
{
ticket.closed = DateTime.Now;
}
ticket.notes = update.notes;
IsBusy = false;
}
else
{
await DisplayAlert("Alert", "Die Verbindung ist fehlgeschlagen prüfen Sie Ihre Internetverbindung und kontaktieren Sie den Support.", "Ok");
}
}
}
}
}
Firstly,the OnAppearing() method should be used directly and don't call it in the constructor again.
Secondly,like Jason suggested, you should process the ticket first and then assign ItemsSource: ListViewTicket.ItemsSource = ticketList;.
Below is the pseudo code for your reference:
public partial class TicketPage : ContentPage
{
List<String> myList = new List<String>() { "05.05.2022 09:12: Test Kommentar 1", "05.05.2022 09:12: Test Kommentar 2" };
private ObservableCollection<Ticket> ticketList;
public TicketPage()
{
InitializeComponent();
//process ticket to generate data firstly
ticketList = new ObservableCollection<Ticket>
{
new Ticket(){pkid = "3", ticketNumber = "19748",status="open",subject="Title3",description = "Beschreibung",notes=myList },
new Ticket(){pkid = "4", ticketNumber = "19749",status="close",subject="Title4",description = "Beschreibung",notes=myList }
};
}
protected override void OnAppearing()
{
//lädt Tickets
//lässt Tickets anzeigen
ListViewTicket.ItemsSource = ticketList;
}
}

Wildfly 10 session replication behind AWS ELB

I followed https://docs.jboss.org/author/display/WFLY10/Clustering+and+Domain+Setup+Walkthrough step by step.
Wildfly domain looks good.
I can read succesful registration log in both master and slave hosts.
That tutorial explains how to configure load balancing with mod_cluster. Anyway, I'd prefer takin' advantage of AWS Elastic Load Balancer service.
Then, I tried all three types of LB (application, network, classic), but none worked with me.
I wrote a simple app to test my use case:
Front servlet:
#WebServlet( urlPatterns = {"/test"} )
public class SessionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Inject SessionBean bean;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("doGet");
process(req, res, false);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("doPost");
process(req, res, true);
}
private void process(HttpServletRequest req, HttpServletResponse res, boolean post) throws ServletException, IOException {
if ( req.getParameter("name")!=null ) {
bean.setName( req.getParameter("name") );
}
req.setAttribute("name", bean.getName());
req.getRequestDispatcher( "/test.jsp" ).forward(req, res);
}
}
Session scoped bean:
#SessionScoped
public class SessionBean implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public SessionBean() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SessionBean other = (SessionBean) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
#Override
public String toString() {
return "SessionBean [name=" + name + "]";
}
}
View JSP:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="it">
<head>
<title>Session Failover Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="UTF-8" />
</head>
<body>
<h1>You are: <c:if test="${empty name}"><i>nobody</i></c:if> <font color="red">${name}</font></h1>
<br/>
<hr/>
<br/>
<form action="/session-failover-demo/test" method="post">
Who are you:
<input type="text" name="name" value="" />
<input type="submit" name="submit" value="ok" />
</form>
</body>
</html>
web.xml file has
<display-name>session-failover-demo</display-name>
<distributable/>
Finally, I make my test:
Browse the ELB endpoint /myapp/test
Set my name through the html form
Refresh a couple of time and see my name (from session)
Stop my 'master' ec-2 instance and wait a minute
The ELB notice master is down and start forwarding requests to 'slave' instance
Refresh the page and.... my name is... nobody!
The session is lost. I see in my browser dev tools that JSESSIONID cookie value has changed!
So I don't know whether I should blame Wildfly domain configuration or AWS ELB. Am I missing something?
EDIT Master stdout: https://pastebin.com/XbtVrb40

Cannot do the set off process of prepayment with spesific bill using web services in Acumatica

I have a problem in set off processing of Prepayment document with spesific Bill document. It happen only for 1 vendor, because there are a lot of prepayment documents from this vendor (it's about more than 6000 records).
this below is my code.
sCon.getLoginSettlementVoucher(context);
AP301000Content billSchema2 = context.AP301000GetSchema();
List<Command> cmds = new List<Command>();
billSchema2.DocumentSummary.Type.Commit = false;
billSchema2.DocumentSummary.Type.LinkedCommand = null;
var command2 = new Command[]
{
new Value { Value = docTypeSV,
LinkedCommand = billSchema2.DocumentSummary.Type},
new Value { Value = refNbrSV,
LinkedCommand = billSchema2.DocumentSummary.ReferenceNbr},
billSchema2.Applications.DocTypeDisplayDocType,
billSchema2.Applications.ReferenceNbrDisplayRefNbr,
billSchema2.Applications.Balance,
billSchema2.Applications.AmountPaid
};
try
{
var applications = context.AP301000Export(command2, null, 0, false, true);
int rowApp = applications.Count(); int ind = 0;
foreach (var data in applications)
{
string docTypeApp = data[0].ToString();
string refNbrApp = data[1].ToString();
string balanceApp = data[2].ToString();
decimal balApp = Convert.ToDecimal(balanceApp);
string amountPaid = data[3].ToString();
string index = ind.ToString();
if (refNbrApp == AcuRefNbr)
{
billSchema2.DocumentSummary.Type.Commit = false;
billSchema2.DocumentSummary.Type.LinkedCommand = null;
billSchema2.Applications.ReferenceNbrDisplayRefNbr.LinkedCommand = null;
cmds.Add(new Value { LinkedCommand = billSchema2.DocumentSummary.Type, Value = "Bill" });
cmds.Add(new Value { LinkedCommand = billSchema2.DocumentSummary.ReferenceNbr, Value = refNbrSV });
cmds.Add(new Value { LinkedCommand = billSchema2.DocumentSummary.Vendor, Value = vVendCode });
cmds.Add(new Key
{
ObjectName = billSchema2.Applications.DocTypeDisplayDocType.ObjectName,
FieldName = billSchema2.Applications.DocTypeDisplayDocType.FieldName,
Value = docTypeApp
});
cmds.Add(new Key
{
ObjectName = billSchema2.Applications.ReferenceNbrDisplayRefNbr.ObjectName,
FieldName = billSchema2.Applications.ReferenceNbrDisplayRefNbr.FieldName,
Value = refNbrApp
});
cmds.Add(new Value { LinkedCommand = billSchema2.Applications.ServiceCommands.RowNumber, Value = index });
if (docAmtSV == balApp)
cmds.Add(new Value { LinkedCommand = billSchema2.Applications.AmountPaid, Value = docAmountSV });
else if (docAmtSV < balApp)
cmds.Add(new Value { LinkedCommand = billSchema2.Applications.AmountPaid, Value = docAmountSV });
else if (docAmtSV > balApp)
cmds.Add(new Value { LinkedCommand = billSchema2.Applications.AmountPaid, Value = balanceApp });
cmds.Add(billSchema2.Actions.Save);
var result2 = context.AP301000Submit(cmds.ToArray());
}
else
{
continue;
}
}
}
catch (Exception ex)
{
continue;
}
And then I got an exception message like this below in Submit process.
Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.
The request failed with the error message:
--
<!DOCTYPE html>
<html>
<head>
<title>Request timed out.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
#media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
#media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/AcuInterface' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Request timed out.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
<br><br>
<b> Exception Details: </b>System.Web.HttpException: Request timed out.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[HttpException (0x80004005): Request timed out.]
</pre></code>
</td>
</tr>
</table>
<br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1098.0
</font>
</body>
--.
Since the error you are getting is indicating a time out, and that you are only getting it for the one vendor that has around or more than 6000 prepayment documents, you might want to augment the time out value before making your call.
This question here deals with augmenting the time out value for a Screen Based API call : Link.
To resume what is being said there, please use the following line to set the timer to a bigger value.
context.Timeout = 700000;
I already fix this problem, I just have to increase timeout of HttpExecution in web.config file inside of Acumatica ERP instance folder.
..............
..............
by Default Acumatica will set this timeout = 300. It's mean 300 seconds or 5 minutes

Retrieve data from list in SharePoint 2013 provider hosted App

I have developed a provider hosted app in SharePoint 2013. As you already know, Visual Studio creates web application and SharePoint app. The web application gets hosted inside IIS and the SharePoint App in SharePoint site collection. I'm trying to get data from a list hosted in SharePoint using CSOM. But I get ran insecure content error.
"[blocked] The page at 'https://localhost:44302/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fecontent&0319c41%2Eecontent%2Eelibrary%2Eapps%2Elocal%2FSharePointApp2%5Fsingeltest'
was loaded over HTTPS, but ran insecure content from 'http://apps-892db5a0319c41.econtent.elibrary.apps.local/sharepointapp2_singeltest/_layouts/15/AppWebProxy.aspx': this content should also be loaded over HTTPS."
here is my code in Default.aspx
<script type="text/javascript" src="../Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript" src="../Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript" src="../Scripts/SP.Core.js"></script>
<script type="text/javascript" src="../Scripts/INIT.JS"></script>
<script type="text/javascript" src="../Scripts/SP.Runtime.js"></script>
<script type="text/javascript" src="../Scripts/SP.js"></script>
<script type="text/javascript" src="../Scripts/SP.RequestExecutor.js"></script>
<script type="text/javascript" src="../Scripts/App.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Get title via CSOM" onclick="execCSOMTitleRequest()" /> <br />
<input id="Button2" type="button" value="Get Lists via CSOM" onclick="execCSOMListRequest()" />
</div>
<p ID="lblResultTitle"></p><br />
<p ID="lblResultLists"></p>
</form>
</body>
</html>
and App.js is:
var hostwebUrl;
var appwebUrl;
// Load the required SharePoint libraries
$(document).ready(function () {
//Get the URI decoded URLs.
hostwebUrl =
decodeURIComponent(
getQueryStringParameter("SPHostUrl")
);
appwebUrl =
decodeURIComponent(
getQueryStringParameter("SPAppWebUrl")
);
// resources are in URLs in the form:
// web_url/_layouts/15/resource
var scriptbase = hostwebUrl + "/_layouts/15/";
// Load the js files and continue to the successHandler
//$.getScript(scriptbase + "/MicrosoftAjax.js",
// function () {
// $.getScript(scriptbase + "SP.Core.js",
// function () {
// $.getScript(scriptbase + "INIT.JS",
// function () {
// $.getScript(scriptbase + "SP.Runtime.js",
// function () {
// $.getScript(scriptbase + "SP.js",
// function () { $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest); }
// );
// }
// );
// });
// });
// });
});
function execCrossDomainRequest() {
alert("scripts loaded");
}
function getQueryStringParameter(paramToRetrieve) {
var params = document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}
function execCSOMTitleRequest() {
var context;
var factory;
var appContextSite;
var collList;
//Get the client context of the AppWebUrl
context = new SP.ClientContext(appwebUrl);
//Get the ProxyWebRequestExecutorFactory
factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);
//Assign the factory to the client context.
context.set_webRequestExecutorFactory(factory);
//Get the app context of the Host Web using the client context of the Application.
appContextSite = new SP.AppContextSite(context, hostwebUrl);
//Get the Web
this.web = context.get_web();
//Load Web.
context.load(this.web);
context.executeQueryAsync(
Function.createDelegate(this, successTitleHandlerCSOM),
Function.createDelegate(this, errorTitleHandlerCSOM)
);
//success Title
function successTitleHandlerCSOM(data) {
$('#lblResultTitle').html("<b>Via CSOM the title is:</b> " + this.web.get_title());
}
//Error Title
function errorTitleHandlerCSOM(data, errorCode, errorMessage) {
$('#lblResultLists').html("Could not complete CSOM call: " + errorMessage);
}
}
function execCSOMListRequest() {
var context;
var factory;
var appContextSite;
var collList;
//Get the client context of the AppWebUrl
context = new SP.ClientContext(appwebUrl);
//Get the ProxyWebRequestExecutorFactory
factory = new SP.ProxyWebRequestExecutorFactory(appwebUrl);
//Assign the factory to the client context.
context.set_webRequestExecutorFactory(factory);
//Get the app context of the Host Web using the client context of the Application.
appContextSite = new SP.AppContextSite(context, hostwebUrl);
//Get the Web
this.web = context.get_web();
// Get the Web lists.
collList = this.web.get_lists();
//Load Lists.
context.load(collList);
context.executeQueryAsync(
Function.createDelegate(this, successListHandlerCSOM),
Function.createDelegate(this, errorListHandlerCSOM)
);
//Success Lists
function successListHandlerCSOM() {
var listEnumerator = collList.getEnumerator();
$('#lblResultLists').html("<b>Via CSOM the lists are:</b><br/>");
while (listEnumerator.moveNext()) {
var oList = listEnumerator.get_current();
$('#lblResultLists').append(oList.get_title() + " (" + oList.get_itemCount() + ")<br/>");
}
}
//Error Lists
function errorListHandlerCSOM(data, errorCode, errorMessage) {
$('#lblResultLists').html("Could not complete CSOM Call: " + errorMessage);
}
};
Any solution is appreciated.
well first off, i can tell you your decodeURIComponent logic isnt working.
Yours:https://localhost:44302/Pages/Default.aspx?SPHostUrl=http%3A%2F%2Fecontent&0319c41%2Eecontent%2Eelibrary%2Eapps%2Elocal%2FSharePointApp2%5Fsingeltest
Mine: https://localhost:44302/Pages/Default.aspx?SPHostUrl=http://econtent&0319c41.econtent.elibrary.apps.local/SharePointApp2_singeltest
Secondly, is the HostURL content supposed to be unsecure? If so, then you may want to change your browser settings. If not, then you need to see why your HostURL is in the Anonymous Zone but your AppURL is in the Secure Zone.
In either case, verify that Everyone has at least Read Access to the location your trying to pull from.
Last thing to do, is to setup a Trusted Host Location if you have access to the Admin Center.
Here is a code snippet for what i used to test:
$(document).ready(function () {
$.getScript(qsHostUrl + "/_layouts/15/SP.RequestExecutor.js", getHostInfo);
function getHostInfo() {
var ctxApp = new SP.ClientContext(qsAppUrl);
var factory = new SP.ProxyWebRequestExecutorFactory(qsAppUrl);
ctxApp.set_webRequestExecutorFactory(factory);
var ctxHost = new SP.AppContextSite(ctxApp, qsHostUrl);
var web = ctxHost.get_web();
ctxApp.load(web);
ctxApp.executeQueryAsync(
Function.createDelegate(this, getHostInfoSuccess),
Function.createDelegate(this, getHostInfoError)
);
function getHostInfoSuccess(sender, args) {
lblData.html(
'Title: ' + web.get_title() + '<br/>' +
'Description: ' + web.get_description()
);
}
function getHostInfoError(sender, args) {
lblData.html(
'Request Failed: ' + args.get_message() + '\n' +
'Stacktrace: ' + args.get_stackTrace()
);
}
}
}