Releases: riganti/dotvvm
DotVVM 4.3.4 bugfix release
DotVVM 4.3.3 bugfix release
- PostBack Handlers
- Fix references to _parent (and higher) view models in the postback handler properties
- GridView Columns
- Fix
resource
binding in the FormatString property
- Fix
Sec-Fetch-Dest
validation- Include info about issues with site prefetching
DotVVM 4.3.2 bugfix release
DotVVM 4.3.1 bugfix release
- Validation
- ValidationContext (used in IValidatableObject) has an initialized IServiceProvider (#1869)
- Analyzers
- DotvvmCapabilityProperty
DotVVM 4.3
DotVVM 4.3 includes two new built-in controls — ModalDialog and AddTemplateDecorator; a major upgrade of the routing system — route localization; better system for warnings; a dozen of new JS translations; and a number of bug fixes and performance improvements, such as the postback request compression.
Potential breaking changes
First, we present to you the bad news. Although we try to limit the number of breakages in minor versions, it if often impossible to fix serious glitches without changing the behavior of some components:
- Client-side
dotvvm.state
object is now frozen. Its modification will throw an exception when in JS strict mode (#1782). Previously, the modification was silently ignored. - Newtonsoft.Json was updated to 13.0.3
- Removed a redundant Microsoft.CodeAnalysis.CSharp dependency from DotVVM.AspNetCore. You might need to explicitly add it back if your application needs the package.
- If two
@property
directives define a property with the same name, an error is issued. - Controls registered using
AutoDiscoverControls
now use relative file paths instead of absolute paths in theSrc
property (#1817)
If you encounter any other regressions, please let us know, as they would most likely be accidental.
dot:ModalDialog
- wrapper for the HTML <dialog>
element (#1776)
DotVVM now includes a dot:ModalDialog
control which wraps the new native HTML <dialog>
element. It does not replace the dialogs in Bootstrap or BusinessPack, as it isn't styled.
<dot:ModalDialog Open={value: ShowDialog} CloseOnBackdropClick>
content
</dot:ModalDialog>
dot:ModalDialog
only supports the modal version of <dialog>
, as the non-modal version is accessible through basic HTML with a bidning in the open
attribute - <dialog open={value: ShowInlineDialog}>
New dot:AddTemplateDecorator
control (#1760)
dot:AddTemplateDecorator
is a new decorator which can prepend or append content to the decorated element. For example, you might use it to add an additional row to each entry in a grid view. In the following snippet, we use this to add a separate row for a description field, which is otherwise too long to fit into a table column.
<dot:GridView DataSource={value: MyTable}>
<RowDecorators>
<dot:AddTemplateDecorator>
<AfterTemplate>
<tr> <td colspan="8">{{value: Description}}</td> </tr>
</AfterTemplate>
</dot:AddTemplateDecorator>
</RowDecorators>
<Columns>
...
</Columns>
</dot:GridView>
Localizable routes (#1824, #1840)
DotVVM now has a mechanism for localizing the route URLs. First, you need to apply a middleware which sets the correct CurrentCulture based on url prefix or the Accept-Language header.
Based on CurrentCulture, DotVVM will decide to which language should the route URL match. By default, DotVVM does not consider alternative languages. You can reconfigure it to accept alternative URL languages or to redirect to the "correct" language variant.
In the following example, we register a localized route and configure DotVVM to redirect if the route language does not match the selected language. If we take requested culture from Accept-Language or a cookie, we probably want to redirect users to the URL language of their preference:
config.RouteTable.Add("MyLocalizableRoute", "localizable-route", "Views/LocalizableRoute.dothtml",
localizedUrls: [
new("cs", "lokalizovana-routa"),
new("de", "lokalisierte-route"),
]);
// redirect to a matching language based on CultureInfo.CurrentCulture
config.RouteTable.AddPartialMatchHandler(new CanonicalRedirectPartialMatchRouteHandler());
Related to route localization, we have added the dot:AlternateCultureLinks
control which automatically generates <link rel=alternate>
elements pointing to the alternative language variants.
Warnings
The Compilation Status Page normally available at _dotvvm/diagnostics/compilation
now lists the warnings and errors of all compiled views. We strongly recommend you to examine the compilation page after upgrading, as it might uncover many mistakes in the application. Thanks to these warnings, we have fixed tens of small UI glitches on one of our systems, which were caused by wrong usage of some DotVVM properties. (related forum post, #1762)
The Control usage validation API now allows controls to emit custom warnings (#1751). For instance, you might want the user about a potential issue, such as specifying a redundant property:
[ControlUsageValidator]
public static IEnumerable<ControlUsageError> ValidateUsage(ResolvedControl control)
{
if (control.Properties.ContainsKey(LabelProperty) && control.Properties.ContainsKey(SomeTemplateProperty))
{
var propertyNode = control.GetValue(LabelProperty).DothtmlNode;
yield return new ControlUsageError("Label is ignored when SomeTemplate is also specified.", DiagnosticSeverity.Warning, propertyNode);
}
}
POST compression (#1766)
DotVVM 4.3 will use gzip to compress the command
and staticCommand
request bodies. As the requests are in JSON, the performance gain is quite significant if you aren't on gigabit Ethernet.
However, accepting compressed requests carries a risk of exposing the web server to "compression bomb" DOS attacks. To limit the potential impact, DotVVM now limits the maximum (uncompressed) postback size to 128 MiB, and the limit may be configured in config.Runtime.MaxPostbackSizeBytes
(it doesn't affect file upload). Postback compression may also be disabled using the config.Runtime.CompressPostbacks
option.
Note that request compression is only enabled in Production environment, because browsers are currently unable to display the uncompressed JSON in devtools.
Other improvements
- Markup file recompilation can be enabled in Production mode using the
DotvvmConfiguration.Runtime.ReloadMarkupFiles
option. - Changed operation name in DotVVM.Tracing.ApplicationInsights to the current route URL template (#1807, thanks to @mirecad)
- JS translations now avoid throwing exception even when the .NET equivalent does throw.
- New JS translations
IEnumerable.Last
,IEnumerable.First
Dictionary.GetValueOrDefault
TimeOnly.Hour
,Minute
,Second
,Millisecond
,FromDateTime
DateOnly.Year
,Month
,Date
,FromDateTime
DateTime.Now
,UtcNow
,Today
GridViewColumn.Visible
now accepts aresource
binding (#1826)- Added methods for compiling
command
andresource
bindings from string toBindingCompilationService.Cache
(#1839) - Client-side DotVVM logging may be configured using the
dotvvm.logging.setLogger
function. Note that the exact wording of log messages is not stable and may even differ in Development and Production environments. - Performance improvements, mainly HTML encoding in
HtmlWriter
thanks for the vectorizedIndexOfAny
implementation (#1851) InlineScriptResource
can now produce<script type=module
whenmodule
parameter is specified.- Prevent double postbacks after redirect in Deny or Queue
PostBack.Concurrency
mode by pretending that the redirect takes 5 seconds. Before those 5s pass, the page most likely unloads and the user does not get the chance to submit the duplicate postback (#1853) - Improved error messages (#1731, #1748, #1763, #1772, #1804, #1806)
Bugs/glitches fixed
- The client-side ViewModel is now restored on back/forward navigation (fixed in Chrome) and not restored on page reload (fixed in Firefox) (#1848)
- DotVVM.AspNetCore does not depend on Microsoft.CodeAnalysis.CSharp (#1743)
- Lambda argument type inference works for custom delegates (#1752)
- The "Force recompile all" button in the Compilation Status Page now actually forces rebuild of all pages (#1759)
- Fixed overload resolution of generic methods with default arguments (#1761)
- Fixed support for client-side property names which are not valid JS identifiers (#1790)
- Client-side validation is now correctly performed on typed objects inside a untyped object (#1803)
- (#1816)
- Controls registered using
AutoDiscoverControls
now use relative file paths (#1817) - Remove
defer
attribute from<script type=module
element as it is redundant and invalid HTML - Limit the number of queued
Task
s when doing pre-compilation to avoid stalling the ThreadPool (#1843) - Fixed the
CopyProperty
method to work with inherited properties containing bindings (#1850)
Thanks to @tomasherceg, @Mylan719, @mirecad, @exyi for contributing to this release
DotVVM 4.2
Potential breaking changes
DotVVM 4.2 should generally be source compatible with the previous 4.1 version. We did not preserve binary compatibility, so please make sure all other DotVVM packages are at 4.2 version (especially if you see a MissingMethodException
or similar error). Please let us know if we forgot to update some of our packages. We also had to change the behavior in ways which could in theory break something
- The type hashes (the client-side type metadata id) might be different. You might need to adjust if you have it hardcoded somewhere. (see #1614, should only affect generic types)
- HtmlGenericControl and RadioButton now attempts to render both the server-side value and client-side binding regardless of RenderSettings.Mode. If you relied on the value not being pre-rendered on the server, please explicitly use
_page.EvaluatingOnServer ? null : OriginalExpression
. To render value server-side only, switch to aresource
binding. - Using a non-DotvvmProperty defined on a markup control is now a compile-time error (in value bindings). It used to only fail client-side
- DotVVM does not reload dothtml files when run in
Production
environment (whenDotvvmConfiguration.Debug=false
). JsComponent
is always initialized asynchronously (see #1684)- View Modules are always initialized after dotvvm is initialized
- Operator precedence of
&&
and||
now behaves the same as in C# - Unopened closing tag used to close all currently open elements -- for example in
<a></b>
theb
tag closed thea
tag. This glitch caused all sorts of problems, so we changed it to not close any elements. RadioButton.Checked
is deprecated, please useCheckedValue
andCheckedItem
properties (the property never worked, but now it might fail compile-time if used incorrectly)
staticCommand
validation
Server-side validation now works in staticCommand
methods. The validation has to be enabled using [AllowStaticCommand(StaticCommandValidation.Manual)]
or [AllowStaticCommand(StaticCommandValidation.Automatic)]
attribute. In the Automatic
case, all arguments will be recursively validated using DataAnnotations attributes and IValidatableObject.Validate will be called. In both cases, additional validation errors can be returned using the StaticCommandModelState
class:
[AllowStaticCommand(StaticCommandValidation.Manual)]
public string MyMethod(MyModel model)
{
var modelState = new StaticCommandModelState();
modelState.AddArgumentError(() => model.Property, "Property is invalid");
modelState.FailOnInvalidModelState();
}
Enabling the validation will make the staticCommand invocation clear all validation errors currently being shown client-side. Note that client-side validation isn't currently implemented, so all invocation will round-trip to the server.
See related forum post for more examples.
Custom primitive types
In order to better support typed IDs, DotVVM now has support for custom primitive types. These types are always represented as a string client-side, which makes them allowed in places only for primitive types - notably SelectedValue
property on selector components, but also in route parameters, and html attributes.
The custom primitive type must have ToString()
and static TryParse(string, out T)
methods. It must also implement the IDotvvmPrimitiveType
interface. It's only a marker interface, since ToString
method present on all types, and TryParse
method is static and we can't use interface static methods due to support for the old framework. The type can be a class, a struct or a record.
A simple typed ID type could look like the following:
public struct OrderId: IDotvvmPrimitiveType
{
public int Value { get; }
public OrderId(int value)
{
this.Value = value;
}
public override string ToString() => Value.ToString();
public static bool TryParse(string value, out OrderId result)
{
if (int.TryParse(value, out var resultValue))
{
result = new OrderId(resultValue);
return true;
}
result = default;
return false;
}
}
WebForms adapters
We have made a new package which helps in the process of migrating Web Forms apps to the new .NET using DotVVM - DotVVM.Adapters.WebForms. It currently contains HybridRouteLink
control and RedirectToRouteHybrid
extension method.
- The
<webforms:HybridRouteLink>
control has the same functionality as theRouteLink
control, but it falls back to Web Forms routes when a requested DotVVM route doesn't exist (which means that the page hasn't been migrated yet). - The
RedirectToRouteHybrid
extension method of theIDotvvmRequestContext
also falls back to the Web Forms route in case the DotVVM route doesn't exist.
The package also works on .NET Core, where these fallbacks are disabled (because of the absence of System.Web
). This allows to keep using the API even after the migration is finished.
state
, patchState
, setState
, updateState
in JS View Modules
We have added the state property and the following methods to the global dotvvm
object, viewmodel knockout observables and JS module context (DotvvmModuleContext
)
state
- returns the current value of the view modelsetState(newValue)
- replaces the current valuepatchState(newValues)
- replaces only the specified properties, for examplepatchState({ UserName: "new-user" })
updateState(currentValue => computeNewValue(currentValue))
- applies the specified function onto the current view model
See simplified view model API in JS Modules on forum.dotvvm.com for more details and some context.
Knockout deferred updates (experimental feature)
DotVVM uses knockout.js to immediately synchronize the view model into the HTML DOM. Knockout essentially does this by subscribing to an update event on each view model variable which is used in the binding. When any value inside the view model is changed, all bindings using the value immediately get a notification and update the bound DOM element.
This normally works well, but if the binding uses very many different variables it can get equally many notification if large part of the view model gets changed. For example, you can have a binding which enumerates an array by counting number of certain elements in an array ({value: MyArray.Count(a => a.IsSpecial)}
). Each array element is a separate viewmodel value, so the binding with get up to MyArray.Length
update notifications, each time evaluating the binding and updating the DOM element. This mean we have got O(n^2) worst case complexity for updating the view model, which can be really slow (in some cases).
Knockout has got an ko.options.deferUpdates = true
option, which makes the updates asynchronous and deduplicates the notifications. Updating all array elements will then lead to just one DOM update (with a slight delay). It was always possible to enable this option, in 4.2 we made it easier to enable and fixed a few bugs in DotVVM which occurred when delayed updates were enabled. The feature is still experimental, since we didn't thoroughly test it with all our components. You can enable/disable it for certain pages, if you encounter issues.
config.ExperimentalFeatures.KnockoutDeferUpdates.Enable().ExcludeRoute("SomePageThatOtherwiseBreaks");
Metrics
We instrumented DotVVM with System.Diagnostics.Metrics. All implemented metrics are listed in the DotvvmMetrics.cs file. We'd like to point out some of the important or interesting metrics:
dotvvm_viewmodel_size_bytes
histogram - Size of the returned viewmodel JSON in bytes.- Labels
route=RouteName
andrequest_type=Navigate/SpaNavigate/Command/StaticCommand
- Labels
dotvvm_request_duration_seconds
- Time it took to stringify the resulting JSON view model.- Labels
route
,request_type
anddothtml_file
- You can use ASP.NET Core statistics about request duration, this metric makes it possible to split the measurement by DotVVM route name.
- Labels
dotvvm_viewmodel_serialization_seconds
histogram - Time it took to serialize view model to JSON objects.- Labels
route
andrequest_type
- Labels
dotvvm_control_lifecycle_seconds
histogram - Time it took to process a request on the specific route- Labels
route
andlifecycle_type=PreInit/Init/Load/PreRender/PreRenderComplete
- Labels
dotvvm_command_invocation_seconds
- Time it took to invoke a specific command method. Compared torequest_duration_seconds
this only includes the time spent in the command method, and is labeled by the executed binding (command
)- Labels
command
andresult=Ok/Exception/UnhandledException
- Labels
dotvvm_staticcommand_invocation_seconds
- Similar tocommand_invocation_seconds
, but for staticCommand invocations- Labels
command
andresult=Ok/Exception/UnhandledException
- Labels
dotvvm_viewmodel_validation_errors_total
histogram - Number view model validation errors returned to the client.- Labels
route
andrequest_type
- Labels
dotvvm_uploaded_file_bytes
- Total size of user-uploaded filesdotvvm_returned_file_bytes
- Total size of returned files. Measured when the file is returned, not when downloaded by the client
If you are using Server-side viewmodel cache you might be also ...
DotVVM 4.1
Potentially breaking changes
While we try to keep "minor" releases free of major breaking changes, it's sometimes impossible to avoid. In general, you should not have problems updating to 4.1. If you encounter a breakage not on this list, please submit a bug report to this repository, or contact us on gitter.
- In general, we aim to be source-compatible, not binary-compatible. If you are using other DotVVM packages, make sure all are on 4.1 version; otherwise
MissingMethodException
s (or similar) might occur. - 4.0 had a bug that allowed using private members from binding. This is fixed in 4.1, so you will now get an error when a private member is used in binding expressions.
- 4.0 had a bug which treated
{ get; init; }
properties as if they had normal setter. DotVVM 4.1 will always clone the object before setting an init-only property. - We made the
ReflectionUtils.PrimitiveTypes
collection private. Please use theIsPrimitiveType
method. In case it doesn't fulfill your requirement, please contact us. We plan to add support for custom primitive types in the next release.
We recommend using the view compilation page at _dotvvm/diagnostics/compilation
after updating to check that all views still compile.
Record serialization (#1246 #1525)
DotVVM can (finally) correctly serialize and deserialize value types and records with constructor properties. F# records and single-case unions are also supported.
record UserInfo(string Name,
string Id,
string Email);
In general classes, the non-default constructor has to be marked with the constructor [JsonConstructor]
attribute. Without it, DotVVM will not automatically deserialize properties into constructor arguments, even when no other constructor is available (to avoid breaking existing code)
class C {
public string Name { get; }
[JsonConstructor]
public C(string name) {
this.Name = name;
}
}
HierarchyRepeater (#1206)
DotVVM now has a generic control for displaying hierarchies that support both client-side and server-side rendering. The following code will create a hierarchy of ul
/ li
tags from a collection of Roots
. The ItemWrapperTag (li
) only contains a template for a specific item, while LevelWrapperTag (ul
) also includes all child items.
<dot:HierarchyRepeater DataSource={value: Roots}
ItemChildrenBinding={value: Children}
LevelWrapperTagName=ul
ItemWrapperTagName=li >
{{value: Name}}
</dot:HierarchyRepeater>
Note that you can set any other attributes or classes on the wrapper tags using the Level
or Item
prefix, for example LevelClass-highlighted={value: Name == _root.HighlightedName}
.
AutoUI (#1293)
DotVVM Dynamic Data is a library that generates forms and grids automatically from your model classes. We have rewritten it using precompiled CompositeControl
s and server-side styles. This makes it much easier to extend and customize, and also eliminates performance issues the old DynamicData library had.
We renamed this new implementation as DotVVM AutoUI, as it's... an automatic UI generator, not data and not dynamic :)
The old DynamicData library still works as before, although we don't plan to develop it further.
Since there is a lot to cover, please refer to the dedicated page for more information. In short, this how the usage looks like:
<!-- create from with all the fields -->
<auto:Form DataContext="{value: EditedEmployee}" />
<!-- a table with automatic columns (we support inline editing too) -->
<dot:GridView DataSource="{value: Employees}">
<auto:GridViewColumns />
</dot:GridView>
<!-- basic form component based on data type and attributes. Includes validation -->
<auto:Editor Property="{value: Age}" />
Markup Declared Properties (#1231)
Properties of markup controls can now be defined directly in the control .dothtml
file:
@property string Name
<div class="name">
{{value: _control.Name}}
</div>
For each property, you can specify:
- A default value, for example
@property string Width = "100%"
@property string[] Classes = [ "something" ]
@property Func<int, int> GetNextId = (int i) => i + 1
- Markup options, for example
@property string Name, MarkupOptionsAttribute.Required=true
Note that @baseType
and @property
directives cannot be combined, as it could lead to ambiguities where the property is defined.
CompositeControl precompilation (#1261)
DotVVM 4.0 introduced Composite controls and made Server-Side Styles much more powerful.
DotVVM 4.1 builds on this foundation and introduces Composite control which is only evaluated once - when the page is being compiled.
This is very useful when the component needs to create and compile new bindings (like Auto UI) since that is a bit too slow to do on each request.
It also allows other server-side styles to match the generated content and customize it.
The usage is fairly simple:
[ControlMarkupOptions(Precompile = ControlPrecompilationMode.IfPossible)]
public class MyControl : CompositeControl
{
public DotvvmControl GetContents(
ValueOrBinding<string> myProperty,
string otherProperty
)
{
return ...;
}
}
This will try to create the control during page compilation, invoke the GetContents
method and replace the component with the generated control tree. The component instance won't even be created at runtime.
However, if otherProperty
contains a resource
binding, it's not possible to call GetContents
before the binding is evaluated. This is fine, the control will be evaluated at runtime normally. You might decide that for certain combinations of arguments, the precompilation is not possible and throw a SkipPrecompilationException
. Please try not to depend on cases where DotVVM automatically decides precompilation isn't possible, since we might want to add support for them in future versions. If you want to make sure the control never falls back on runtime evaluation, you can use the ControlPrecompilationMode.Always
setting.
A special mode is ControlPrecompilationMode.InServerSideStyles
which is used by AutoUI. This instructs DotVVM to build the control while server-side styles are running which allows other styles to modify the children. Normal precompiled controls are evaluated after styles are finished, in order to behave similarly to runtime controls which are also unaffected by styles.
JsComponent is stable now
DotVVM 4.0 included experimental support for integrating components written in JavaScript; as of DotVVM 4.1 we consider the React integration stable. To include a React component into a DotVVM view:
- Install the
dotvvm-jscomponent-react
npm package - Setup your favorite JS bundler (and optionally a typescript compiler) to produce ES module bundle (let's say it's called
scripts/mycomponents.js
) - Register the script for DotVVM:
config.Resources.RegisterScriptModuleFile("mycomponents-js", "script/mycomponents.js")
The module should export the components in the $controls
field
import { registerReactControl } from 'dotvvm-jscomponent-react';
import * as React from 'react';
function SampleComponent(props) {
return <span>{props.text}</span>
}
export default (context) => ({
$controls: {
SampleComponent: registerReactControl(SampleComponent),
}
})
Then you can import it in any DotVVM view or markup control using the @js
directive and use it with the <js:
tag prefix.
@js mycomponents-js
<js:SampleComponent text={value: Text} />
For more information, see the documentation page, our sample project or the sample we use as UI test.
We'd like to thank @lorencjan for thoroughly testing the dotvvm-jscomponent-react
package, many improvements have been made based on his suggestions.
We also have working Svelte integration. However, it's not published as a npm package at the moment - if you want to try it out, you can copy the integration function from our repository (yes the link correct, all the code really fits on one screen). If you'd like to try any other JS web framework, it should be quite easy to wire it into the DotVVM API. We'll definitely welcome any pull requests, but feel free to also submit an issue requesting it. If you can "only" help with testing, that's also very valuable.
Other smaller changes
- DotVVM now implements `IHeathCheck on ASP.NET Core. It checks whether all pages can be compiled. #1209
control.AddCssClass
andcontrol.AddCssStyle
extension methods now also supportValueOrBinding
as input. It will now also work when it's called multiple times with a binding. (#1274, #1354)- Control property can now be
IEnumerable<DotvvmControl>
orIEnumerable<IMyControl>
, previously it had to beList<DotvvmControl>
(#1325, #1355) - `BindingCompilationService.Cache.Creat...
DotVVM 4.0
DotVVM 4.0 Release notes
Breaking Changes
ordered by severity:
- We dropped support for IE 11. There is no workaround, except for using some better browser
- Validation API has changed, see the Validation section for more details. TL;DR: use
context.AddModelError(this, vm => vm.EditViewModel.MyProperty)
netstandard2.1
ornet472
platform is required- Some HTTP security headers are enabled by default. See HTTP Security Headers section
[Authorize]
attribute is now deprecated, please use thecontext.Authorize()
extension method instead. The Authorize attribute still works and we don't plan to remove it, but it's marked obsolete for a reason (see Authorization)- Control properties not using the
DotvvmProperty.Register
orDotvvmPropertyGroup.Register
are no longer supported and exception will be thrown. DotvvmControl.SetValue
method used to write into the value binding if it was possible. However, this behavior was unreliable so it now always replaces the binding with the new value. If you want the old behavior - to set the value to the binding, use the.SetValueToSource
method.- Some typos in the public API were fixed (see #1051)
- Method in server-side styles
.SetControlProperty<MyControl>(TheProperty)
is replaced by.SetControlProperty(TheProperty, new MyControl())
. Also additional using may be required for extension method to be found. - DotVVM Error page now only displays errors from DotVVM pages, not from subsequent middlewares. If you are using both DotVVM and other technology in your backend, add the ASP.NET Error Page too.
- Client-side
Repeater
uses a separate<template id=...>
element instead of placing the template inside. If it poses a problem, it can be configured by settingRenderAsNamedTemplate=false
. RouteLink
renders the link even in client-side mode.Literal
renders the binding even in server-side rendering mode. Use a resource binding to force it to render the value server-side without generating the Knockout binding expression.DotVVM.Diagnostics.StatusPage
is now deprecated, the page is now included in DotVVM.Framework package (at_dotvvm/diagnostics/compilation
). Please uninstall the package from your project.
New Authorization API
TL;DR: Use context.Authorize(...)
instead of [Authorize(...)]
. Place it in the OnInit
method of your view model or into the respective command/staticCommand. The IDotvvmRequestContext
can be injected from DI into your static command service constructor or directly imported in DotHTML using @service context=IDotvvmRequestContext
and put into staticCommand argument.
We deprecated the [Authorize]
attribute, because it was not called in some unexpected cases (when the command is called from another command, or when the view model class is placed inside another view model). We could fix those few issues, but there would probably always remain some weird cases, so we decided to deprecate the auto-magical invocation ofr the attribute in favor of calling the Authorize
method explicitly. It's much easier to debug why your code does not invoke the method than to debug why DotVVM won't call it. Also, when the .Authorize
call is placed right next to the logic it's supposed to guard, there is almost no way it wasn't in fact authorized. Since developers rarely write UI tests checking whether auth works properly, we decided calling a method is much safer option for such a critical task.
HTTP Security Headers
Firstly, this DOES NOT magically protect your application from all kinds of attacks. Most common attacks are related to wrongly configured authentication and insuficient user input validation, and none of these headers can help with that. Please remember that everything in your viewmodel which is not marked by the [Protect]
attribute is suddently a user input in a command or static command.
Also, we only set headers which are not likely to cause any problems to your application... which, incidentally, are the headers which are less effective 🙃. Please don't forget to set the Strict-Transport-Security
yourself and check your application using Mozilla Observatory.
-
X-Frame-Options: DENY
is used by default. It should pose no problem, since DotVVM did not work with iframes anyway due to cookie SameSite policy. When CrossSite frames are enabled, the cookie will haveSameSite=None
- Configured in
config.Security.FrameOptionsSameOrigin
andconfig.Security.FrameOptionsSameOrigin
. Please enable the cross-origin iframes only for routes where you really need it.
- Configured in
-
We also check Sec-Fetch-Dest - if it's an iframe, we validate on server that iframes are allowed. This mostly allows us to print a nicer error message, but may also in theory prevent some timing attacks using iframes
-
X-XSS-Protection: 1; mode=block
blocks some kinds of XSS attacks. Probably not super useful, but also not harmful.- Configured by
config.Security.XssProtectionHeader
- Configured by
-
X-Content-Type-Options: nosniff
disables inference of content-type based on content, this could prevent some XSS attacks. Probably also not super useful, but very unlikely to cause any problems.- Configured by
config.Security.ContentTypeOptionsHeader
- Configured by
-
When on https, we set the session cookie with __Host- prefix. This prevents it being used by subdomains. Can help only in obscure cases - for example when a system on the subdomain is compromised, the attacked can not pivot to the parent domain so easily.
We also check the Sec-Fetch-*
headers - that tells us what the browsers intends to do with the page and whether it is a cross-origin or same-origin request. Basically, we don't allow cross-origin POST and SPA requests. We also don't allow JS initiated GET requests to DotVVM pages, use the config.Security.VerifySecFetchForPages
option to disable this, if you rely on it.
If the browser does not send these Sec-Fetch-* headers, we don't check anything. You can enable strict checking by config.Security.RequireSecFetchHeaders
option. By default it's enabled on compilation page to prevent SSRF and it does not matter too much if it does not work for someone with an obsolete or broken browser.
Improved server-side styles
Server-side styles is a powerful metaprogramming feature available since the early preview versions of DotVVM. However, we have significantly refactored and improved the API in this version to allow access to strongly typed properties.
Most of previous code should remain compatible, except for the SetControlProperty<TControl>
method which should be replaced by .SetControlProperty(property, new TControl())
.
Styles.Tag
DotHTML property is introduced to allow easier matching to specific controls. For example, it may be used like this:
c.Styles.RegisterAnyControl(c => c.HasTag("prepend-icon"))
.Prepend(new HtmlGenericControl("img").SetAttribute("href", "myicon.png"));
// or this rule applies to any descenant of a tagged control
// it will use <span data-bind="text: ..."></span> instead of knockout virtual element for each literal
c.Styles.Register<Literal>(c => c.HasAncestorWithTag("literal-spans"))
.SetProperty(c => c.RenderSpanElement, true);
It is now possible to create controls in normal C# code and then put them into children, control properties or append/prepend them to the matched control. Use .PrependContent
, .AppendContent
, .SetControlProperty
, .Append
and .Prepend
. You can also replace the entire control with a different one using .ReplaceWith
which will also copy all properties onto the new control. Last but not least, you can use .WrapWith
to place a wrapper control around it.
In previous version, it was only possible to set a constant value into the properties, now it's possible to compute the value for each control using a supplied lambda function:
// this will apply a confirm postback handler to all commands and staticCommands on this control
c.Styles.RegisterAnyControl(c => c.HasTag("confirm"))
.AppendDotvvmProperty(
PostBack.HandlersProperty,
c => new ConfirmPostBackHandler(c.GetHtmlAttribute(
"data-confirm-msg") ?? "This is a default confirm message")
);
It is also possible to process a binding in the API. For example, this transforms every usage of the Visible
property into a CSS class regardless whether it's a static value or a value / resource binding.
c.Styles.Register<HtmlGenericControl>(c => c.HasProperty(c => c.Visible))
.SetPropertyGroupMember("Class-", "hide", c =>
c.Property(c => c.Visible).Negate())
.SetProperty(c => c.Visible, true); // reset the Visible property
The .Negate()
is a extension method defined on the new ValueOrBinding<bool>
type. There are many others including .Select(t => ...)
where you can supply any lambda function which can be translated to a JavaScript binding.
Validation
We completely reworked the way validation works internally. Validation property paths are now always expressed as absolute paths from the root viewmodel to the affected property. Therefore, property paths always begin with the '/'
character (expressing they are starting at the root viewmodel) and this character is also used to delimit individual path segments. Examples:
/Customer/Id
- this means that there is a property
Customer
in the root viewmodel - the error is attached to the property
Id
on theCustomer
.
- this means that there is a property
/Items/0/Price
- this means that there is a collection
Items
in the root viewmodel - the error is attached to the element with index
0
o...
- this means that there is a collection
DotVVM 3.2
New features
Added more JavaScript translations
#1059, #1062, #1100
We continued with our effort to add JavaScript translations for common .NET methods and some custom extensions. You can use these methods inside data-binding to express more complex operations and have them evaluated on the client's side.
DateTime
property getters (e.g.Year
,Month
,Day
etc.)WebUtility
methods (UrlEncode(str)
,UrlDecode(str)
)- Numerous new
string
methodsIsNullOrWhiteSpace(str)
- Many overloads for comparing strings with the
StringComparison
parameter - Many trimming and padding method overloads
Improvements and fixes
Changed type of viewmodel to any
#1069
The type of dotvvm.state
is now any
. This allows for an easier access to the underlying state of viewmodels without the need of repeated casting.
Prefer to use state
in static commands
#1078, #1113
We fixed a synchronization issue that occurred with state
, which could have been observed using a staticCommand. Changes made to state
in user code were not always correctly reflected. As a result it was possible to read old data using staticCommand.
Fixed OnPreInit
invocation on DotvvmMarkupControl
#1082
Usage of the parameterless constructor on DotvvmMarkupControl
may have previously caused weird issues in connection with the @js
directive. This was caused due to the fact that the necessary resource was not loaded.
Fixed NRE when using NamedCommand
without the @js
directive
#1083
DotVVM no longer throws a NullReferenceException
in case user specifies a NamedCommand
without the @js
directive. This use case is still not supported, however, DotVVM now throws a better and more descriptive exception that tells user what is wrong.
Improved error reporting when a function from viewmodule module fails
#1085
DotVVM now provides a better error whenever a function from a viewmodule (also known as a JavaScript module) fails.
Fixed issue with not loading assemblies with custom controls
#1087
Some users and components register controls using the config.Markup.Controls.Add(...)
method call. However, this does not update the assemblies list in config.Markup.Assemblies
and as a result DotVVM may have previously missed to load some necessary assemblies.
Fixed issue with type inferer
#1093
Type inferer for lambda parameter types no longer fails on some of the supported and more complex .NET methods.
Fixed REST API bindings generation
#1098
We fixed many issues in connection with REST API bindings generation. Generated code should now be correct and not dependent on the global Newtonsoft.Json settings. See also notes about breaking changes regarding this feature.
Fixed registration of viewmodules in markup controls
#1103
Viewmodules are now registered only for pages that have the @js
directive. Previously the property that indicates whether a module is referenced could have been inherited by a markup control.
Fixed issue with indexing expression evaluating to null
#1120
DotVVM now generates expressions that are less strict whenever a null
gets passed as an indexing expression, for example as a key to a dictionary. Instead of a compilation exception, it now propagates the null
value as a result of the whole expression.
Fixed indexer's get method translation for dictionaries
#1121
We fixed an issue in the JavaScript translation for the indexer's get method for dictionaries.
Breaking changes
Behavior change after regenerating REST API bindings
Newly generated and regenerated bindings will have some changes. This is due to the fact that we had to update underlying Nswag version that changed the way API clients are generated. Most notably, there are the following differences:
HttpClient
is now cached and passed as an argument for the API client's constructor- Generated code uses an
ApiException
instead of the previously usedSwaggerException
.
Users that do not regenerate their bindings are not affected by this change.
Tooling
Azure pipelines
#1067
Continuous integration system is now capable to run DotVVM tests both on Windows and Linux using newly defined azure pipelines.
DotVVM 3.1
New features
Added automatic detection for lambda parameter types
#936
DotVVM is now able to infer types of lambda parameters from the context the lambda function was specified in. This makes it possible to specify more concise lambda expressions. For example instead of a Customers.Where((CustomerDto c) => c.Id > 0)
it is now possible to write Customers.Where(c => c.Id > 0)
.
Added support for custom extension methods
#946
We have extended the capabilities of the @import
directive to also search for available extension methods within provided namespaces. This feature allows users to use their custom extension methods inside data-binding.
Added more JavaScript translations
#965, #1009, #1029, #1039
We added a lot of new JavaScript translations for common .NET methods and some custom extensions. You can use these methods inside data-binding to express more complex operations and have them evaluated on the client's side.
Enumerable
methods,string
methods andMath
methodsList<T>
methodsDictionary<K,V>
methods
For a full list of supported .NET methods inside data-binding, see the following page from the documentation: Supported expressions.
Added support for string interpolation
#987
String interpolation is a well-known feature from C# that allows specifying a string prefixed with a '$'
sign together with some interpolated expressions to be evaluated during runtime. Additionally, you can alter the way your interpolated expressions are converted into strings by providing optional formatting options. In DotVVM this is always a syntax sugar for calling string.Format(...)
.
Added support for dictionaries in viewmodels
#1014
It is now possible to use dictionaries in viewmodels. DotVVM now supports the usage of indexer in data-binding so that you can read values, change existing values, but also create new key-value pairs using the indexer on dictionaries.
Added support for passing AbortSignal into the postback
#1021
It is now possible to abort an in-progress postback. This can be useful to signalize if you already know that the result of postback is no longer needed.
HtmlGenericControl supports numeric and boolean values for attributes
#1028
Resource bindings previously supported only string values and collections of string in attributes. We extended this by supporting also: numeric types, bool
s, enums and Guid
s. DotVVM interprets booleans as indications whether a specific attribute exists or not. This means that an attribute is omitted when it is false
.
Improvements and fixes
Fixed issues with assigning lambda functions to some known delegates
#936
Lambda functions can now be assigned to System.Action
s and System.Predicate
s alongside with already supported System.Func
s.
Improved error reporting when a master page is corrupted
#976
Whenever a user makes a mistake while specifying a viewmodel for a specific master page, the error page no longer shows its type to be an UnknownTypeSentinel
. Users now get a more descriptive error message that provides hints on how to resolve this issue.
Fixed generics resolving and method overloads search
#978
It is now possible to call more complex generic methods. Previously there were issues with matching generic parameters owned by types instead of methods, but also applying implicit conversions in some places.
FileUpload control does not need an iframe
#988
We have got rid of the iframe for FileUpload
control. This makes it possible to use this control under more environments as we are aware that iframes can be discouraged by certain configurations.
Added helper functions for working with type metadata
#1013
We introduced a few utility functions to improve the experience when working with type metadata. You can find these functions under dotvvm.metadata
when working with JS/TS.
Fixed serialization of byte[]
#1015
Byte arrays are no longer serialized as base64-encoded strings as this caused issues with coercing during deserialization.
Fixed RouteLink control with targets in SPA
#1016
SPA-routing logic is no longer applied on RouteLink
s with targets that are specified within a SpaContentPlaceHolder
. This makes it possible to use, for example target="_blank"
to open a new tab from a SPA.
Updating non-existing array element should do nothing
#1020
Updating an array element from staticCommand after it was removed from viewmodel now does nothing. Previously it caused various issues when updating array elements with undefined values.
Warn when an uppercase attribute is used
#1022
Usage of uppercase attributes now generates a warning as it is likely a reference to a non-existing property. To silence these warnings, make sure to use all lowercase letters for standard HTML attributes.
Fixed issue with array and nullable types in lambda parameters
#1031
DotVVM compiler no longer throws whenever a user tries to create a lambda function with either a nullable type or an array type as one of its parameters.
Fixed compiler deadlock when building controls
#1035
We fixed an issue that made it possible to deadlock DotVVM compiler under special circumstances when building controls.
Better error messages for invalid resource name in @js directive
#1041
DotVVM no longer throws a NullReferenceException
when the specified JS module is not found. We also improved error message for the case when the referenced module is not of ScriptModuleResource
type.
Fixed issue with assigning to arrays and lists
#1052
DotVVM now correctly translates staticCommands that used indexer to change an element under a specific index.
Removed usage of culture-sensitive string operations
#1054
We replaced all occurrences of .ToUpper()
and ToLower()
calls with their culture-invariant alternatives. This previously caused some issues with, for example Turkish language.
Fixed compilation issues with extension methods
#1058
Repeated importing of the same namespace no longer ends with a compilation exception "Found ambiguous overloads of method ..."
. Additionally, DotVVM now correctly compiles extension methods that use default parameter values.
Fixed issue with assigning values to nullable types
#1071
Nullable properties can be assigned using either a nullable value or a non-nullable value (an implicit conversion should be used). We added the missing conversion that fixes compilation of the second case.
Tooling
Command-line interface
#872
Major rewrite of command-line interface and the stand-alone compiler executable. The compiler executable is no longer embedded in DotVVM NuGet package, but instead we introduced the DotVVM.CommandLine NuGet package.