EasyNetQ - how can I include the original queue name in the EasyNetQ_Default_Error_Queue message? - easynetq

When using the Publisher/Subscriber pattern and an exception is throwed during a subscriber handling, EasyNetQ, by default, put a message in the EasyNetQ_Default_Error_Queue.
The problem is I only have the original exchange name in the error message. What I really need is the original queue name, so I can republish the message to the queue, not to the exchange.
How can I include the queue name in the error message?
Sample error message in the EasyNetQ_Default_Error_Queue:
{
   "RoutingKey": "",
   "Exchange": "EiHD.Application.Restaurant.Events.RestaurantDeliveryMailChanged:EiHD",
   "Exception": "System.AggregateException: Um ou mais erros. ---> System.NullReferenceException: Referência de objeto não definida para uma instância de um objeto.\r\n em EiHD.Infrastructure.Mailing.EmailSender.OnEvent(RestaurantDeliveryMailChanged evt) na d:\\Projetos\\EatInHouseDelivery\\sln\\Infrastructure\\Mailing\\EmailSender.cs:linha 136\r\n em EiHD.Infrastructure.EventDispatching.EasyNeqQEventDispatcher.<>c__DisplayClass5`1.<RegisterListener>b__4(T evt) na d:\\Projetos\\EatInHouseDelivery\\sln\\Infrastructure\\EventDispatching\\EasyNeqQEventDispatcher.cs:linha 68\r\n em EasyNetQ.RabbitBus.<>c__DisplayClass6`1.<Subscribe>b__5(T msg)\r\n --- Fim do rastreamento de pilha de exceções internas ---\r\n---> (Exceção Interna N° 0) System.NullReferenceException: Referência de objeto não definida para uma instância de um objeto.\r\n em EiHD.Infrastructure.Mailing.EmailSender.OnEvent(RestaurantDeliveryMailChanged evt) na d:\\Projetos\\EatInHouseDelivery\\sln\\Infrastructure\\Mailing\\EmailSender.cs:linha 136\r\n em EiHD.Infrastructure.EventDispatching.EasyNeqQEventDispatcher.<>c__DisplayClass5`1.<RegisterListener>b__4(T evt) na d:\\Projetos\\EatInHouseDelivery\\sln\\Infrastructure\\EventDispatching\\EasyNeqQEventDispatcher.cs:linha 68\r\n em EasyNetQ.RabbitBus.<>c__DisplayClass6`1.<Subscribe>b__5(T msg)<---\r\n",
   "Message": "{\"FromEmail\":\"someemail#gmail.com\",\"ToEmail\":\"anotheremail#gmail.com\",\"RestaurantName\":\"SomeRestaurant\"}",
   "DateTime": "2015-10-25T19:20:17.2317949Z",
   "BasicProperties": {
      "ContentType": null,
      "ContentEncoding": null,
      "Headers": {},
      "DeliveryMode": 2,
      "Priority": 0,
      "CorrelationId": "f212f734-6cd7-41fe-ac71-09335f44bb2c",
      "ReplyTo": null,
      "Expiration": null,
      "MessageId": null,
      "Timestamp": 0,
      "Type": "EiHD.Application.Restaurant.Events.RestaurantDeliveryMailChanged:EiHD",
      "UserId": null,
      "AppId": null,
      "ClusterId": null,
      "ContentTypePresent": false,
      "ContentEncodingPresent": false,
      "HeadersPresent": true,
      "DeliveryModePresent": true,
      "PriorityPresent": false,
      "CorrelationIdPresent": true,
      "ReplyToPresent": false,
      "ExpirationPresent": false,
      "MessageIdPresent": false,
      "TimestampPresent": false,
      "TypePresent": true,
      "UserIdPresent": false,
      "AppIdPresent": false,
      "ClusterIdPresent": false
   }
}

I figured out a solution.
I had to register an extended version of the DefaultConsumerErrorStrategy class to IConsumerErrorStrategy of my bus:
this.bus = RabbitHutch.CreateBus(this.connectionString, (serviceRegister) => {
serviceRegister.Register<IConsumerErrorStrategy>((sp) => new ExtendedConsumerErrorStrategy(sp.Resolve<IConnectionFactory>(), sp.Resolve<ISerializer>(), sp.Resolve<IEasyNetQLogger>(), sp.Resolve<IConventions>(), sp.Resolve<ITypeNameSerializer>()));
});
public class ExtendedConsumerErrorStrategy : DefaultConsumerErrorStrategy
{
public ExtendedConsumerErrorStrategy(IConnectionFactory connectionFactory, ISerializer serializer, IEasyNetQLogger logger, IConventions conventions, ITypeNameSerializer typeNameSerializer)
: base(connectionFactory, serializer, logger, conventions, typeNameSerializer)
{
}
public override AckStrategy HandleConsumerError(ConsumerExecutionContext context, Exception exception)
{
context.Properties.Headers.Add("OriginalQueue", context.Info.Queue);
return base.HandleConsumerError(context, exception);
}
}
Now I have the original queue name in my message Headers property. Works for me.

Related

React-pdf frame proportions

I want to use react-pdf to generate PDF and just followed the exact same steps provided by its official documentation. However when the pdf renders it doesnt occupy the whole screen, and i dont know if im doing sth wrong or there's some property to define that. This is how it looks like:
Code:
import React from 'react';
import { Page, Text, View, Document, StyleSheet } from '#react-pdf/renderer';
import ReactPDF from '#react-pdf/renderer';
// Create styles
// Create Document Component
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.body}>
<Text style={styles.header} fixed>
~ Created with react-pdf ~
</Text>
<Text style={styles.title}>Don Quijote de la Mancha</Text>
<Text style={styles.author}>Miguel de Cervantes</Text>
<Text style={styles.subtitle}>
Capítulo I: Que trata de la condición y ejercicio del famoso hidalgo D.
Quijote de la Mancha
</Text>
<Text style={styles.text}>
En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha
mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga
antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que
carnero, salpicón las más noches, duelos y quebrantos los sábados,
lentejas los viernes, algún palomino de añadidura los domingos,
consumían las tres partes de su hacienda. El resto della concluían sayo
de velarte, calzas de velludo para las fiestas con sus pantuflos de lo
mismo, los días de entre semana se honraba con su vellori de lo más
fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina
que no llegaba a los veinte, y un mozo de campo y plaza, que así
ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro
hidalgo con los cincuenta años, era de complexión recia, seco de carnes,
enjuto de rostro; gran madrugador y amigo de la caza. Quieren decir que
tenía el sobrenombre de Quijada o Quesada (que en esto hay alguna
diferencia en los autores que deste caso escriben), aunque por
conjeturas verosímiles se deja entender que se llama Quijana; pero esto
importa poco a nuestro cuento; basta que en la narración dél no se salga
un punto de la verdad
</Text>
<Text style={styles.pageNumber} render={({ pageNumber, totalPages }) => (
`${pageNumber} / ${totalPages}`
)} fixed />
</Page>
</Document>
);
App.js
export class App extends Component {
render(){
return (
<PDFViewer>
<MyDocument />
</PDFViewer>
)
}
}
try adding some css styles to your PDFViewer component, in your css file try adding:
.ClassName {
width: 99%;
height: 99vh;
}

ZAPIER CODE STEP HTTP REQUEST

I need generate the following request in zapier with a code step. I use webhook function but for some reason the answer is a separated comma value and i need the full json. I try in postman and works perfect. But i dont unterstand so fine how i can do with code. I use postman to format the code in nodejs the code run but dont geck back anything. Somebody can help so fin the problem? thans so much. (i´m a basic user for that reason i dont untersant all)
The request:
curl -X POST \
'https://gateway.watsonplatform.net/personality-insights/api/v3/profile?version=2017-10-13&consumption_preferences=false&raw_scores=true' \
-H 'accept: application/json' \
-H 'accept-language: es' \
-H 'authorization: Basic here is the token' \
-H 'cache-control: no-cache' \
var http = require("https");
var options = {
"method": "POST",
"hostname": "gateway.watsonplatform.net",
"port": null,
"path": "/personality-insights/api/v3/profile?version=2017-10-13&consumption_preferences=false&raw_scores=false",
"headers": {
"content-type": "application/json",
"accept": "application/json",
"authorization": "Basic HEREISTHETOKEN==",
"accept-language": "es",
"cache-control": "no-cache",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(JSON.stringify({ contentItems:
[ { content: 'Wow, I liked #TheRock before, nowLa evaluada aseguró que no adulteró, falsificó u omitió intencionalmente alguna información en su solicitud de empleo, dice que toda la información suministrada en este proceso de selección es completamente legal y en cualquier momento se puede validar. I really SEE how special he is. The daughterIndicó que consume licor solo en ocasiones especiales, las bebidas que acostumbra a consumir son: cerveza, teniendo un consumo máximo por ocasión de 5 cervezas. Aseguró no haber tenido dependencia de las sustancias alcohólicas e indicó no tener antecedentes de alcoholismo en la familia. Agregó no haber tenido incumplimientos o problemas laborales a causa del licor. story was IT for me. So great! #MasterClass So great! #MasterClasWow, I liked #TheRock before, nowLa evaluada aseguró que no adulteró, falsificó u omitió intencionalmente alguna información en su solicitud de empleo, dice que toda la información suministrada en este proceso de selección es completamente legal y en cualquier momento se puede validar. I really SEE how special he is. The daughterIndicó que consume licor solo en ocasiones especiales, las bebidas que acostumbra a consumir son: cerveza, teniendo un consumo máximo por ocasión de 5 cervezas. Aseguró no haber tenido dependencia de las sustancias alcohólicas e indicó no tener antecedentes de alcoholismo en la familia. Agregó no haber tenido incumplimientos o problemas laborales a causa del licor. story was IT for me. So great! #MasterClasss',
contenttype: 'text/plain',
created: 1447639154000,
id: '666073008692314113',
language: 'es' } ] }));
req.end();
return {DATA: http.text};

Datatables change interface language

I am currently using angular-datatables.
How can I see the interface of the table in other languages?
I mean the "Show entries", "Search:", "Showing 1 to 10 of 20 entries" literals fore example in Spanish.
You need to define a language struct like this (danish implementation, what I am using in my angular-datatables apps) :
var language = {
"sEmptyTable": "Ingen tilgængelige data (prøv en anden søgning)",
"sInfo": "Viser _START_ til _END_ af _TOTAL_ rækker",
"sInfoEmpty": "Viser 0 til 0 af 0 rækker",
"sInfoFiltered": "(filtreret ud af _MAX_ rækker ialt)",
"sInfoPostFix": "",
"sInfoThousands": ",",
"sLengthMenu": "Vis _MENU_ rækker",
"sLoadingRecords": "Henter data...",
"sProcessing": "Processing...",
"sSearch": "Filter:",
"sZeroRecords": "Ingen rækker matchede filter",
"oPaginate": {
"sFirst": "Første",
"sLast": "Sidste",
"sNext": "Næste",
"sPrevious": "Forrige"
},
"oAria": {
"sSortAscending": ": activate to sort column ascending",
"sSortDescending": ": activate to sort column descending"
}
}
There is a bunch of languages here -> https://www.datatables.net/plug-ins/i18n/
And then you include the language using the withLanguage() option method
.withLanguage(language)
demo -> http://plnkr.co/edit/RCrqM3z7qwsUfFwy8HE6?p=preview
I created a .ts file like this:
export class LanguageApp {
public static spanish_datatables = {
processing: "Procesando...",
search: "Buscar:",
lengthMenu: "Mostrar _MENU_ &elementos",
info: "Mostrando desde _START_ al _END_ de _TOTAL_ elementos",
infoEmpty: "Mostrando ningún elemento.",
infoFiltered: "(filtrado _MAX_ elementos total)",
infoPostFix: "",
loadingRecords: "Cargando registros...",
zeroRecords: "No se encontraron registros",
emptyTable: "No hay datos disponibles en la tabla",
paginate: {
first: "Primero",
previous: "Anterior",
next: "Siguiente",
last: "Último"
},
aria: {
sortAscending: ": Activar para ordenar la tabla en orden ascendente",
sortDescending: ": Activar para ordenar la tabla en orden descendente"
}
}
}
Then in the component that was loading the DataTable just put that config inside dtOptions:
this.dtOptions = {
language: LanguageApp.spanish_datatables
};
In Angular2+ what worked for me is quite the same as mentioned by #davidkonrad, but without the starting letters (s and o), and adding the language as an attribute of the dtOptions. I.e.:
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 10,
dom: 'Bfrtip',
buttons: [
/*'print',
'csv'*/
],
responsive: true,
/* below is the relevant part, e.g. translated to spanish */
language: {
processing: "Procesando...",
search: "Buscar:",
lengthMenu: "Mostrar _MENU_ éléments",
info: "Mostrando desde _START_ al _END_ de _TOTAL_ elementos",
infoEmpty: "Mostrando ningún elemento.",
infoFiltered: "(filtrado _MAX_ elementos total)",
infoPostFix: "",
loadingRecords: "Cargando registros...",
zeroRecords: "No se encontraron registros",
emptyTable: "No hay datos disponibles en la tabla",
paginate: {
first: "Primero",
previous: "Anterior",
next: "Siguiente",
last: "Último"
},
aria: {
sortAscending: ": Activar para ordenar la tabla en orden ascendente",
sortDescending: ": Activar para ordenar la tabla en orden descendente"
}
}
};

FB.UI callback with scopes on Backbone

var obj={
method: 'feed',
name: 'Je viens de créer son premier domaine : "' + this.model.attributes.name + '"',
caption: 'Entrez dans l\'univers du vin avec Vinoga',
description: (
'Ayez un domaine plus grand, plus beau ou plus prestigieux que vos amis. Challengez vos amis à travers de nombreux mini-jeux et rendez-leur visite '
),
link: 'http://www.vinoga.com',
picture: 'https://twimg0-a.akamaihd.net/profile_images/3095682321/79e5bb5014d6b118b08c5b11bd2a81e8.jpeg'
};
function callback(response)
{
this.model.setActivation(); // HERE
alert('toto');
}
FB.ui(obj, callback);
},
I got an error about this.model.setActivation is undefined ...
Do you have any idea how to solve this?
Thanks in Advance
Pierre
You can use underscore's bind helper to set the context for the callback.
FB.ui(obj, _.bind(callback, this));

Cakephp Data validation - This field cannot be left blank

I'm using cakephp and I get a strange behavior with it.
Here is my validation rule in the Model:
public $validate = array(
'flyer' => array(
'rule' => array('fileValidation', 'flyer', array('image/jpeg', 'image/pjpeg'), NULL, TRUE)
)
// Other rules...
);
Here is the fileValidation method (yes I'm french =) )
public function fileValidation(array $check, $field, array $allowedMimeTypes = NULL, $maxFileSize = NULL, $allowEmpty = FALSE)
{
$file = array_shift($check);
$message = NULL;
if($file['error'] === UPLOAD_ERR_OK){
// checking uploaded file
if(empty($file['tmp_name']) || empty($file['tmp_name']) || $file['tmp_name'] === 'none' || !is_uploaded_file($file['tmp_name'])){
$message = "Une erreur est survenue lors de l'envoi du fichier, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
// checking mimeTypes if required
elseif(!empty($allowedMimeTypes) && !in_array($file['type'], $allowedMimeTypes)){
$message = "Le type de fichier envoyé n'est pas celui attendu.";
}
// checking file size if required
elseif(!empty($maxFileSize) && $file['size'] > $maxFileSize){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
else{
return TRUE;
}
}
elseif($file['error'] === UPLOAD_ERR_NO_FILE){
// validates if no upload is allowed
if(!$allowEmpty){
$message = "Une erreur est survenue lors de l'envoi du fichier, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
else{
return TRUE;
}
}
elseif($file['error'] === UPLOAD_ERR_INI_SIZE){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
elseif($file['error'] === UPLOAD_ERR_FORM_SIZE){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
elseif($file['error'] === UPLOAD_ERR_PARTIAL){
$message = "Une erreur est survenue lors de l'envoi du fichier, le serveur n'a reçu qu'une partie du fichier, veuillez réessayer à nouveau.";
}
elseif($file['error'] >= UPLOAD_ERR_NO_TMP_DIR){
$message = "Une erreur interne est survenue, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
// Here is the problem
$this->validationErrors[$field][] = $message;
return FALSE;
}
So far so good, my Validation rule seems to work correctly but when à get an error, I have two messages: "My custom message" and "This file cannot be left blank".
How to remove this message, where am I wrong?
Thanks in advance.
May be it will works for you
$this->validationErrors[$field][] = $message; // comment this Line
return FALSE // comment this Line
And Add the following line at last of your fileValidation function
return implode("\n", $message);
Cakephp.Saint's solution doesn't work because $message is a string, not an array but this works fine:
return $message;

Resources