How to use Microsofts WPL / Anti-XSS as default HTTPEncoder? - asp.net

I want to use Microsofts WPL AntiXSS Library as default HTTPEncoder as described at haacked but this documentation is for WPL 3.1 and I've read that there is a change regarding HTTPEncoder with latest WPL 4.0. What is the best way to implement it so that all input fields are automatically encoded?
Thanks!

The most inportant change in this context seems to be that if you pass a null as the value for encoding function the function will return null (previous behavior was to return String.Empty). The System.IO.TextWriter will handle nulls properly, so everything should work as expected.

The only change is in the class names, they were renamed to Encoder.whatever in 4.0. If you use Phil's code you'll get a bunch of obsolete warnings.
In 4.1 I will finally have a built in class to allow use as a default encoder, but I don't have a ship date yet I'm afraid.

Related

Web API method parameter considered required when using [CanBeNull]

After migrating one of our apps to .NET 6.0, I've noticed a strange behavior. Here's my method signature (all parameters are passed through query string parameters):
[HttpGet("search")]
public async Task<ActionResult<Paginated<Worker>>> SearchAsync(string? name, ...) {...
Now, I was using resharper and it was automatically replacing the ? with the CanBeNullAttribute:
[HttpGet("search")]
public async Task<ActionResult<Paginated<Worker>>> SearchAsync([CanBeNull]string name, ...) {...
I've also had nullable references enabled on the project (<Nullable>enable</Nullable>) and I'm using NewsoftJson as my json converter.
After publishing the project, I've noticed that I was getting a 400 when name was not set to valid string (ex.: when the url looks like /search?otherparameter=hhh&... or /search?name=&otherparameter=lll): The name field is required..
Now, I've noticed that:
Disabling nullable reference types at the project level makes everything work out
Disabling r# replacement of ? with [CanBeNull] while enabling nullable references at the project makes everything work out too.
I always thought that nullable reference types were a static thing, ie, would only be used by the compiler to ensure that null exceptions were a thing of the past. However, the previous behavior disproves that theory, though, since it seems like it's being used my the converter when checking the parameters' values.
Btw, why does resharper insists in replacing the ? with the [CanBeNull] if the results aren't the same?
edit: I've found this link that confirms the behavior but still no official doc which explain how a static analysis feature ends up changing the runtime behavior..
Thanks.

CodeFluent Entities Add Runtime Design Attribute to False

Now that the site blog.codefluententities.com is down, there is no place to get answers to frequent questions.
Even the FAQ's and blog at their main website is poor and lacks of any search tool.
At the "knowledge center" you can try to search some basic questions but you'll need to custom search at google using the website: key.
I've finally found a clue about my last failure using this old promising tool at:
https://www.softfluent.com/product/codefluent-entities/knowledge-center/json-serialization-D2715E9D140C-A6080529C80C
but the key link is pointing to a lost domain and that's the end of the road.
My question is solved at:
CodeFluent Entities adds a TypeConverterAttribute that allows to convert an entity to string using the EntityDisplayName property. Json.NET detects this attribute and wrongly uses it to serialize the entity to JSON. There are 2 solutions:
Remove this attribute if you don't use it by setting Add Runtime Design Attribute to False
Use the Json.NET aspect to generate specific Json.NET attribute on generated classes and properties
but there's no information about how to do it.
As SoftFluent states, questions can be post to SO adding the codefluent tag, but user's community is poor at knowledge of the product and developer team #meziantou is overloaded
I really hope this project does not fail as it was one of my last bets to a hidden-source company and pray at every out-of-date free-license internet connection dependent renewal for their server not being closed.
CodeFluent Entities adds a TypeConverterAttribute that allows to convert an entity to string using the EntityDisplayName property. Json.NET detects this attribute and wrongly uses it to serialize the entity to JSON. There are 2 solutions:
Remove this attribute if you don't use it by setting Add Runtime Design Attribute to False
The following configuration will prevent CodeFluent Entities from generating [System.ComponentModel.TypeConverterAttribute(typeof(CodeFluent.Runtime.Design.NameTypeConverter))] on generated classes:
<cf:producer name="Business Object Model (BOM)" typeName="CodeFluent.Producers.CodeDom.CodeDomProducer, CodeFluent.Producers.CodeDom">
<cf:configuration addRuntimeDesignAttributes="false" ... />
</cf:producer>
You can also use the modeler to set this attribute.
Use the Json.NET aspect to generate specific Json.NET attribute on generated classes and properties
If you need to preserve the TypeConverter, you can instruct CodeFluent Entities to add custom JSON.Net attributes on generated classes and properties using the following aspect. The code and usage sample is available on GitHub: https://github.com/SoftFluent/CodeFluent-Entities/tree/master/Extensions/SoftFluent.Json.NET/
To make you more confident : yes this SO tag is still monitored at SoftFluent. There is also the support[at]softfluent.com mailbox that allows to contact the support team directly. The product is still supported and fixes are published when bugs are reported to us. We are preparing a new version targeting .Net Standard 2.0 but will still support the existing version as is. I can not provide yet any timeline though for this new version.

Revit API: 'Hidden' methods?

While using Revit API and browsing the "RevitAPI.chm" file (and browsing examples on the internet), I have noticed that some methods exist while not being listed neither in the "RevitAPI.chm" file nor suggested when using RevitPythonShell.
I explain. Let's say for instance that I have a "Space" Object, obtained with
s = FilteredElementCollector(doc).OfClass(SpatialElement).ToElements()
If I do, let's say (assuming s[0] is a valid Space object):
s[0].Geometry
I got an 'indexer object':
<indexer# object at 0x0000000000000049>
But if I do:
s[0].get_Geometry(Options())
Then I got my GeometryElement object. The same behavior goes with get_BoundingBox, for instance.
Now, that's fine, but the only way I could know about these get_something methods is by seeing examples (either on the "RevitAPI.chm", or on forums etc.). So that's kind of strange, isn't it? In the sense that these methods aren't actually listed.
So I guess my questions would be:
Is it the normal behavior? (or should I normally just get a GeometryElement object by using s[0].Geometry, for instance?)
If yes, ... why ? :D
What are these 'indexers' ?
Thanks!
Arnaud.
PS: Using Revit 2017, tests made with RevitPythonShell and pyRevit
The methods prefixed by a lowercase get_ are automatically generated getter methods. The official Revit API provides and documents the BoundingBox property on the Element class. Rather inelegantly, this so-called property takes an argument. Therefore, the C# .NET implementation generates a property getter function for it.

ASP.net Core Entity Framework CurrentValues.SetValues() best current alternative

As those of you working with Entity Framework Core may know, the current version does not have an implementation for CurrentValues.SetValues() for Entities. It looks like support for this will come in the next release v1.1 as this issue states. Until then, does anybody have a solution that works for updating entity entries?
For context, the SetValues function in the past entity framework takes an entity and updates it properties to the values of an entity passed as a parameter i.e.:
var updatedEntity = currentEntity.CurrentValues.SetValues(newValues);
_dbContext.SaveChanges();
I've found some implementations using PropertyInfo to make a generic update function but haven't found anything that looks to be a nice clean solution. Might just have to take what I can get though :)
p.s. I realize this function only worked for simple entities that don't have complex object graphs that would require updating other related entities. My use case is simple. It's just annoying to have to manually map properties right now.
EDIT: Now that EF Core v1.1.0 has been released, CurrentValues.SetValues() will work.
See the following code snippet
var currentEntity = dbSetEntity.Find(id);
_dbContext.Entry(currentEntity).CurrentValues.SetValues(newValues);

Functionality change while upgrading to Castle Windsor 3.3.0 from 3.2.0

I am attempting to migrate from version 3.2.0 to 3.3.0. I am getting a compile error. I could not find an entry in the "Breaking Changes" section but here are my two errors in hope someone can guide me to a workable alternative.
public void RegisterTypeSingleton<T>(Type component, string name)
{
if (_container.Kernel.HasComponent(name))
_container.Kernel.RemoveComponent(name);
_container.Register(Component.For<T>().ImplementedBy(component).Named(name).LifeStyle.Singleton);
}
It seems Kernel.RemoveComponent() function has been depreciated. What has replaced this?
The second compiler error is at _container.Register(Component.For<T>().ImplementedBy(component).Named(name).LifeStyle.Singleton);
I am getting "The Type 'TService' must be a reference type in order to use it as a parameter.
I think you might be upgrading from an older version than 3.2.0. See below.
The removal of IKernel.RemoveComponent() is documented in the Breaking Changes document with v3.0.0. Here is the extract where Krzysztof explains why it was removed:
change - Removed the following methods:
GraphNode.RemoveDepender,
GraphNode.RemoveDependent,
IKernel.RemoveComponent,
IKernelEvents.ComponentUnregistered,
INamingSubSystem.this[Type service],
INamingSubSystem.GetHandler,
INamingSubSystem.GetService2Handler,
INamingSubSystem.GetKey2Handler,
INamingSubSystem.UnRegister(String key),
INamingSubSystem.UnRegister(Type service)
Also INamingSubSystem.Register now takes only IHandler as its argument
impact - low
fixability - none
description - The methods were implementation of "remove component from the container" feature
which was flawed and problematic, hecen was scraped.
fix - Working around is quite dependant on your specific usage. Try utilizing IHandlerSelectors.
For changed Register method, just update your calling code not to pass the name.
handler.ComponentModel.Name is now used as the key, as it was happening in all places so far
anyway, so this change should have no real impact.
RegisterComponent() won't overwrite an existing service registration, it'll just register another component for the same service, unless you specify the same name where it'll throw an exception informing you there is another component registered with that name. If your application doesn't replace components very often you could use the IsDefault() method on the registration to get Windsor to resolve the new component by default, just note the other component is still registered.
If your application replaces components often and you don't want the other registrations left there, you'd be best using a custom IHandlerSelector or ISubDependencyResolver so Windsor will ask you each time what component you want used for a specific service.
Also in v3.0.0 a change was made to ensure that value types cannot be passed to the registration methods. You'll need to add a generic constraint to your method that accepts a generic parameter so that it also only accepts reference types:
public void RegisterTypeSingleton<T>(Type component, string name)
where T : class
{
...
}

Resources