Serilog conditional template headers - serilog

Is there a way to conditionally include strings in a Serilog template?
For example,
_logger.Information("Event: {evt} Description: {dsc}", evt, dsc}
How do I omit the "Description:" string if dsc is null or empty?

The message template is definitely a fixed point in the equation.
If the description is an ancillary field for you, you could do
_logger.ForContext("Description",dsc).Information("Event: {evt}", evt}
... if you do this, be sure to include {Properties} in log rendering format string to include context fields such as this which are not used in the actual message template.
Other than that, you're left with a humble if:
if(desc!=null)
_logger.Information("Event: {evt} Description: {dsc}", evt, dsc}
else
_logger.Information("Event: {evt}", evt);
Note, this will yield a different message template id in the message under the hood for obvious reasons, which may be a reason to prefer the former.
(Also not possible is the ternary operator instead of if - that will run you into trouble with the Serilog Analyzer)

Related

Are There Any Rails Modules or Classes Which Provide Frozen HTML Content Type Strings?

Ive been searching through source for a while, and it appears to me that there are no given Rails tools for retrieving the String representation of various HTML content types. Ive also found this to be a very difficult concept to search for in general.
What I want is something like this:
Mime::Mimes::CONTENT_TYPE_JSON = 'application/json'.freeze
or, Mime::Mimes::CONTENT_TYPES[:json] etc.
...because I want to do a lot of things like some_value == 'application/json' or some_value = 'application/json' etc.
I want to use the expression "application/json" often, and I dont want to create new String instances for something that is pretty well within the domain of web application development. Ive thought of creating my own app consts or vars so I dont have to allocate HTML Content Type strings more than once, but also feel this should just be available for me in any web application framework (at least, those written in languages where every string is a new memory allocation).
Is there a better tool or resource within the Rails 5 source that I am missing that allows easy retrieval of content type strings? Do I have to get a gem / create my own for this?
Note: Im away of how heavy of an "optimization" this may appear to be. Let's then entertain this query from a position of being pragmatic about organizational style, for a project that requires elimination of any duplication of domain-specific string literals, and to keep them symbolized or as some frozen const. Let's pretend its a personal project for the sheer joy of experimenting with such style!
There is a shorthand for it:
Mime[:json]
Mime#[] -
https://github.com/rails/rails/blob/e2efc667dea886e71c33e3837048e34b7a1fe470/actionpack/lib/action_dispatch/http/mime_type.rb#L41
which uses
Mime::Type#lookup_by_extension -
https://github.com/rails/rails/blob/e2efc667dea886e71c33e3837048e34b7a1fe470/actionpack/lib/action_dispatch/http/mime_type.rb#L149
If you want to get the actual content type you might need to call a #to_s on it:
Mime[:json].to_s
Creating a new module to facilitate simple storage and retrieval using the ActionPack Mime::Type system would work as follows:
# Build hash of type name to value, e.g., { xml: "application/xml" }
CONTENT_TYPES = {}.tap do |simple_content_types_hash|
# Get each registered Mime Type
Mime::EXTENSION_LOOKUP.each do |mime|
simple_content_type_hash[mime.first.to_sym] = mime.last.instance_variable_get("#string").freeze
end
end.freeze
Note: the above is untested, its just a generalization of what I am looking for. Thanks to #Fire-Dragon-DoL for the tip.
This could be added via an initializer, patched into an existing module, or into a new helper module.

How to make Thymeleaf rendering fail when binding failure occurs?

In Thymeleaf, when binding failure by absence of a property,
the property is replaced with empty string.
How to make Thymeleaf fail to render in the case?
UPDATE:
This is a sample project I'm working on:
https://github.com/izeye/samples-spring-boot-branches/tree/thymeleaf
When I run the HomeControllerTests.test(),
I expect I've got an exception
because I did not provide the age property in the model.
But it's rendered with an empty string.
I agree it's a nice behavior in general
but in my current situation,
I hope to be certain that there's no missing property when rendering.

How to protect against XSS attacks in Grails app

In my grails app I'm extracting text from the params and using that as parameters in my Domain queries:
Example:
def color = Colors.findByName(params.colorname)
I imagine someone could fiddle with the params.colorname parameter to run bad queries against my mysql database.
What are some of the good practices to protect against things like these?
When you render a field in your view that could potentially contain an XSS attack, you need to encode it as HTML. You should make all fields that contain user input are encoded. All of the standard Grails tags encode as HTML. If you use ${} in a view though, that's where you can run into trouble. You need to either manually encode it like ${colorname.encodeAsHTML()} or use a tag like fieldValue if it's a bean property.
You can also set the global default codec with grails.views.default.codec = "html" in Config.groovy.
Watch out for double encoding and making sure you encode as HTML in your custom tags.
You also reference SQL injection attacks, which are different from XSS attacks. You're only at risk of SQL injection if you're writing your own SQL or HQL and directly interpolating user input into the SQL/HQL. That means do Colors.executeQuery("from Colors where name like ?", params.colorname) instead of Colors.executeQuery("from Colors where name like $params.colorname").

Meaning of empty from, empty create etc. in expression language

I came across some .xhtml files where for some components the expression language used was like rendered="#{empty from}", rendered="#{empty create}" etc.
I know that empty is an operator in EL, used to check whether a value is null or empty, but I did not understand the meaning of above mentioned ELs.
Can somebody explain to me what above EL's mean?
The rendered attribute is a signal whether JSF should generate HTML for the component or not. If it evaluates false, then it won't generate HTML for the component (nor for its children). The #{empty form} will evaluate false when the #{form} is not null nor empty.
Simple as that. You can find another examples of boolean expressions here: Conditionally displaying JSF components

remove conversion validation message in struts 2 or make it general

In my struts2 application I have field named carrierNo that accepts integer, when i put string in it gives me this validation error message:
*Invalid field value for field "carrierNo".*
i can customize this error message in the properties file like this
invalid.fieldvalue.carrierNo=this field does not accept characters
but i don't want to write a customized message for every non String field in my web application, i want to make it general, i tried the following but it did not work
invalid.fieldvalue.%{getText(fieldName)}=this field does not accept characters
if there is no way to make general, please help me disable this message at all.
then i will use converstion field validator with single message that i define in the properties file.
so my request is to help me make this invalid.fieldvalue.carrierNo general something like this form invalid.fieldvalue.%{getText(fieldName)}
or disable the display of this error message Invalid field value for field "carrierNo".
You could create your own implementation of ConversionErrorInterceptor which finds out the class of failed field and gets your custom message.
Edit:
See source code for ConversionErrorInterceptor. For example you could do something like this in your custom interceptor inside intercept method
// get field by name from action
Field f = invocation.getAction().getClass().getDeclaredField(propertyName);
// get type of field
Class clz = f.getType();
String message = LocalizedTextUtil.findDefaultText(XWorkMessages.DEFAULT_INVALID_FIELDVALUE + "." + clz,
invocationContext.getLocale());
And in your messages.properties file put xwork.default.invalid.fieldvalue.int, xwork.default.invalid.fieldvalue.float, etc.
The easiest way to remove conversion messages is to remove the "conversionError" interceptor from your default stack. One problem with removing it, however, is that IIRC it's also responsible for putting the original (non-converted) value back into fields instead of having them replaced by the value of the failed conversion. This can lead to an unpleasant user experience, IMO.
Making a "... does not accept characters" conversion error message doesn't feel right: conversion errors encompass the entire application, and characters may not be the reason for a conversion error.

Resources