How to read ToggleSwitch value in WinJS - winjs

I want to read if one value is selected or another (1 or 0, TRUE or FALSE) in WinJS by using a ToggleSwitch:
Code HTML:
<div id="toggleSwitchDocFormat" class="toggleSwitchDocFormat" data-win-control="WinJS.UI.ToggleSwitch" data-win-options="{labelOn:'Guardar Documento Como: TIFF', labelOff:'Guardar Documento Como: PDF', checked:true}"></div>
Code Javascript:
app.onloaded = function () {
getDomElements();
toggleSwitchDocFormat = document.getElementById("toggleSwitchDocFormat").winControl;
console.log("the value of the ToggleSwitch: " + toggleSwitchDocFormat.checked);
}
Message:
El código de biblioteca de JavaScript está a punto de detectar la
excepción. en línea 119, columna 9 en
ms-appx://.../js/default.js
0x800a138f - Error en tiempo de ejecución de JavaScript: No se puede
obtener la propiedad 'toString' de referencia nula o sin definir
Si hay un controlador para esta excepción, el programa puede continuar
de forma segura.
when I hover the ToggleSwitch code I found "undefined" value, what am I doing wrong??
without the console.log line the ToggleSwitch is shown properly on screen, but I also want to get it's value, any help I'll appreciate

try this code:
args.setPromise(WinJS.UI.processAll().then(function () {
document.getElementById("toggleSwitchDocFormat").winControl.addEventListener("change", function switchChanged(e) {
var _toggleSwitchDocFormat = e.target.winControl;
console.log("is it active??: " + _toggleSwitchDocFormat.checked);
});
}));

Related

Getting finished with status code: 204 on Firebase Function and nothings happened

I am developing a function to send email to customers.
exports.sendRestockingNotification = functions.https.onCall((data) => {
try {
console.log("Sending confirmation email to the customer...");
sendEmailRestocking(data.numero, data.nombre, data.emails);
} catch (error) {
console.error("Unexpected error: ", error);
}
});
function sendEmailRestocking (numero, nombre, emails) {
console.log("Sending Email...");
return transport.sendMail({
from: "XXXXX <xxxxxxxxxxxxx#gmail.com>",
to: emails,
subject: "El artículo " + nombre + " (" + numero + ") vuelve a estar disponible.",
html:
`
<div class="container rounded" style="padding: 10px 30px;">
<div class="container rounded" style="background-color: #0bbe83;">
<h1 style="color: white; padding: 5px;">TejidosPulido</h1>
</div>
<div class="row" style="padding: 10px 50px;">
<h5 style="color: #0bbe83;">Hola, </h5>
<p>
El artículo ${nombre} (${numero}) vuelve a estar disponible. ¡Date prisa antes de que se termine!
</p>
</div>
<br>
<p style="padding: 10px 30px;">
Un saludo,
<br>
Tu equipo TejidosPulido
</p>
</div>
`,
});
}
But I am always getting the same in the Firebase Functions console and any mail is sent and the debug message console.log("Sending a confirmation email to the customer..."); is not showed neither:
sendRestockingNotification -> Function execution started
sendRestockingNotification -> Function execution took 14 ms, finished with status code: 204
Have a look at the doc for Callable Cloud Functions. You need to return data that can be JSON encoded.
So you need to wait for the asynchronous sendEmailRestocking() function to terminate before sending a response. For example with the following adaptations:
exports.sendRestockingNotification = functions.https.onCall(async (data) => { // See async
try {
console.log("Sending confirmation email to the customer...");
await sendEmailRestocking(data.numero, data.nombre, data.emails);
return {result: "mail send"}; // For example
} catch (error) {
// See https://firebase.google.com/docs/functions/callable#handle_errors
console.error("Unexpected error: ", error);
}
});

PHPMailer and specific characters in subject (UTF-8?)

I'm trying to send email with PHPMailer. Everythings work except UTF-8 encoding in Subject.
I still get html code (commancé and has to be "commancé") in my mail client.
$mail = new PHPMailer(true);
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
try {
//Server settings
//Recipients
$mail->setFrom('kevin#expl.com', 'Kevin de Exple');
$mail->addAddress($email, $name); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$subject = 'RE: La plantation de votre arbre a commancé';
$sub = '=?UTF-8?B?'.base64_encode($subject).'?=';
$mail->Subject = $sub;
...
Could you help me? I tried everything on the web :)
Have a good day!
I'm not sure why you're trying to do things the hard way! The first step is setting the CharSet property to UTF-8, which you've done. For the subject, you have this:
$subject = 'RE: La plantation de votre arbre a commancé';
$sub = '=?UTF-8?B?'.base64_encode($subject).'?=';
$mail->Subject = $sub;
There's a lot of unnecessary stuff going on in there. All you need to do is:
$mail->Subject = 'RE: La plantation de votre arbre a commancé';
PHPMailer takes care of all the encoding for you. The only thing to be careful of here is to be sure that you are actually working in UTF-8 in your editor. If you're using ISO-8859-1 or similar, it won't work – though it will look identical in your code.
As for spelling mistakes, I'm going to have to leave them up to you...
Do it this way
function correct_encoding($text) {
$current_encoding = mb_detect_encoding($text, 'auto');
$text = iconv($current_encoding, 'UTF-8', $text);
return $text;
}
$mail = new PHPMailer(true);
$mail->CharSet = 'utf-8';///<-- use lowercase
//$mail->Encoding = 'base64';//usually it is not necessary
try {
//Server settings
//Recipients
$mail->setFrom('kevin#expl.com', 'Kevin de Exple');
$mail->addAddress($email, $name); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$subject = 'RE: La plantation de votre arbre a commancé';
//$sub = '=?UTF-8?B?'.base64_encode($subject).'?=';
$mail->Subject = correct_encoding($subject);

How to add several embedded image in the body?

I am trying to send several images in the body of the email. When I send one it works. But as soon as I want to send several it does not work anymore.
I tried doing a for loop but without result. I have also tried adding addEmbeddedImage several times with a different cid for each image.
if(array_key_exists('submit', $_POST)){
if (array_key_exists('userfile', $_FILES)) {
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name']));
$uploadfile2 = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile2']['name']));
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile) ) {
require './vendor/autoload.php';
$prenom = $_POST['prenom'];
$nom = $_POST['nom'];
$q1 = $_POST['q1'];
$q1_2 = $_POST['q1_2'];
$q2 = $_POST['q2'];
$q2_2 = $_POST['q2_2'];
$mail = new PHPMailer;
$mail->isHTML(true);
// $mail->isSMTP();
// $mail->SMTPDebug = 2;
$mail->Host = 'ssl0.ovh.net';
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
$mail->SMTPAuth = true;
$mail->CharSet = 'UTF-8';
$mail->setFrom('lol#example.com', $prenom);
$mail->addAddress('info#nicolaspoulain.be', 'Jessica');
$mail->Subject = 'Formulaire de sécurité VCA';
$mail->AddEmbeddedImage($uploadfile, "my-attach");
$mail->AddEmbeddedImage($uploadfile2, "my-attach2");
$mail->Body =
'<h1 style= "text-align: center;" margin-bottom:"100px;"> Formulaire de visite sécurité</h1>
<h4>Prénom: </h4>' . strip_tags($prenom) .
'<h4>Nom: </h4>' . strip_tags($nom) .
'<table rules="all" style="border-color: #666;" cellpadding="10">
<tr><th style="width: 40%;">Question</th><th style="width: 10%;">Réponse</th><th style="width: 50%;">Commentaires</th></tr>
<tr style="background: #eee;"><td><strong>Y a-t-il un permis de travail?</strong> </td><td>' . strip_tags($q1) . "</td><td>" . strip_tags($q1_2) . '<img src="cid:my-attach">' . "</td></tr>
<tr style='background: white;'><td><strong>La description de la tâche et les mesures de sécurité sont-elles suffisamment claires?</strong> </td><td>" . strip_tags($q2) . "</td><td>" . strip_tags($q2_2) . '<img src="cid:my-attach2">' . "</td></tr>";
if (!$mail->send()) {
$msg .= "Mailer Error: " . $mail->ErrorInfo;
} else {
$msg .= "L'audit a bien été transmis!";
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
}
Good afternoon,
To be able to add multiple images in the body of the email. You should use CID's.
$imgPath = "\images\Progressiva_Itaipu.jpg";
$cid = md5($imgPath);
$mail->AddEmbeddedImage($imgPath,$cid,'Progressiva_Itaipu.jpg');
Calling so in the body of the message
$message .= "<img src='cid:$cid'>";
If it is multiple images, you can do the foreach or even a for

How to get the applicationContext or context-root name on PrimeFaces 7.0 [duplicate]

This question already has an answer here:
Get the web application context path from META-INF/context.xml to produce an outcome for navigating
(1 answer)
Closed 3 years ago.
I'm trying to get the applicationContext of my web app which is defined on jboss-web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
<context-root>/Tesoreria-WEB</context-root>
<max-active-sessions>300</max-active-sessions>
</jboss-web>
Is there a way to get that String Tesoreria-WEB? I need it because my menus aren't adding that part of the url anymore after upgrading from 3.5 to 7.0, so im gonna get that context and add it before they are created. I had tried with:
System.out.println("Application name: "+ PrimeRequestContext.getCurrentInstance(FacesContext.getCurrentInstance()).getApplicationContext());
but no success, is there a way or should I add it manually? thanks!
By the way I think they stopped adding correctly the url after upgrading to 7.0 from 3.5 because of https://github.com/primefaces/primefaces/wiki/Migration-Guide breaking changes from 6.2 to 7.0 says "Button/Link/MenuItem: The url/href attribute isn't automatically prepended by contextPath anymore. Use the outcome attribute for referencing JSF views in the same application or manually prepend url/href with #{request.contextPath}. See https://github.com/primefaces/primefaces/issues/3506." But I don't understand what does that mean.
how I expect my url to be built (notice Tesoreria-WEB on the url):
http://10.13.44.48:8483/Tesoreria-WEB/XHTML/boxes/boxesMassive.xhtml
how they are being built since I upgraded to 7.0 (this brings 404):
http://10.13.44.48:8483/XHTML/boxes/boxesMassive.xhtml
I dynamically made my menuBar on the ManagedBean and on the xhtml I call reference it like this, that's all no menuItems no things like that all is made on the ManagedBean:
<p:menubar id="menuBar" binding="#{menuMB.menuBar}"
autoDisplay="false" styleClass="cds-menu-mainmenu"
rendered="#{plantillaGeneralMB.habilitarMenu}" />
This is how we dynamically make the menu, while debugging I found where exactly they get their url, its a bit down there I commented where in English:
this Node objects are from org.w3c.dom.Node
private List<SubMenuItem> cargarSubmenus(Node pNodeMenu,
List<String[]> lJerarquiaTemp, String[] tituloPadre) {
Node nodeSubMenu = null;
// Obtener la lista de hijos de este nodo.
NodeList childNodes = pNodeMenu.getChildNodes();
int sizeList = childNodes.getLength();
List<SubMenuItem> lSubmenus = new ArrayList<>();
SubMenuItem subMenu = null;
lJerarquiaTemp.add(tituloPadre);
for (int i = 0; i < sizeList; i++) {
// Obtener el hijo de este nodo correspondiente al indice indicado.
nodeSubMenu = childNodes.item(i);
// Verificar que efectivamente este nodo sea un Submenu
if (nodeSubMenu.getNodeName().equals("SUBMENU")) {
// Verificar que el nodo tenga atributos.
if (nodeSubMenu.hasAttributes()) {
NamedNodeMap map = nodeSubMenu.getAttributes();
// Obtener codigo.
Node codigo = map.item(0);
// Obtener titulo
String titulo = nodeSubMenu.getChildNodes().item(1)
.getTextContent();
// THIS IS THE URL **********************
String url = nodeSubMenu.getChildNodes().item(3)
.getTextContent();
// Im having to add "/Tesoreria-WEB" + url to make my urls well constructed, no idea what changed so much from 3.5 to 7.0 here if someone knows how to make it work without adding this manually its appreciated
subMenu = new SubMenuItem(codigo.getTextContent(), titulo,
"/Tesoreria-WEB"+url);
System.out.println("Application name: "+ PrimeRequestContext.getCurrentInstance(FacesContext.getCurrentInstance()).getApplicationContext());
subMenu.setlJerarquia(lJerarquiaTemp);
String[] menuInfo = { codigo.getTextContent(), titulo, url };
// Si esta nodo tiene mas hijos llamar recursivamente este
// metodo.
if (nodeSubMenu.getChildNodes().item(5) != null
&& nodeSubMenu.getChildNodes().item(5)
.getNodeName().equals("SUBMENU")) {
subMenu.setlSubmenus(cargarSubmenus(nodeSubMenu,
subMenu.getlJerarquia(), menuInfo));
}
if (nodeSubMenu.getChildNodes().item(5) != null
&& nodeSubMenu.getChildNodes().item(5)
.getNodeName().equals("TABS")) {
subMenu.setlTabs(cargarTabs(nodeSubMenu.getChildNodes()
.item(5)));
}
// Adicionar este submenu y sus hijos a la lista de submenus
// del nodo original.
lSubmenus.add(subMenu);
}
}
}
return lSubmenus;
}
The way to get that context-root of the application in JSF is:
FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
For more info see Get the web application context path from META-INF/context.xml to produce an outcome for navigating
Yes what they mean is do this...
<p:menuitem value="my URL" url="#{request.contextPath}/boxes/boxesMassive.xhtml" />

Nodejs and Jade rendered my submit button as a text field

In a nodejs application, with Jade templating, I can't manage to render a submit button.
This is my app.js code :
var express = require('express');
var app = express();
app.get('/todo', function(req,res){
res.set({
"Content-Type" : "text/html",
"charset" : "utf-8"
});
res.render('todo_list.jade', {list : [
"Lire un livre", "Jouer de la musique", "Apprendre la programmation", "Jouer au dé pipé !"
]});
});
// app.post('/todo/ajouter', function(req, res){
//
// });
//
// app.post('/todo/supprimer/:id', function(req, res){
//
// });
app.listen(8080);
This is my view/todo_list.jade :
doctype html
head
title Ma todo list
body
h1 Ma todo list
ul
- for (var i = 0; i < list.length; i++)
li #{list[i]}
form
label(for=new_task) Que dois-je faire ?
input(type=text, id=new_task, name=new_task, size=15)
input(type=submit, value=Ajouter)
So why I am getting two text fields instead of a text field and a button ?
In my application root folder, I've installed (with a package.json file) express ~4.3.2, cookie-session ~1.0.2, body ~4.4.2, and jade ~1.3.1
The cause of your problem is that you are not properly assigning attributes to your tags. In Jade, attribute values are evaluated as JavaScript expressions. This means that leaving your attribute values unquoted will use the variable's value rather that the literal value.
Here is the fixed Jade template that will give you the desired output:
doctype html
head
title Ma todo list
body
h1 Ma todo list
ul
- for (var i = 0; i < list.length; i++)
li #{list[i]}
form
label(for='new_task') Que dois-je faire ?
input(type='text', id='new_task', name='new_task', size=15)
input(type='submit', value='Ajouter')

Resources