PlatformNotSupportedException throws when using Dapper with WP - c#

Executing a UWP application in DEBUG works perfectly.
Using exactly the same code compiled in RELEASE crashes with this error message
System.PlatformNotSupportedException:
'Dynamic code generation is not supported on this platform.'
when executing this code (it's using Dapper 1.5.1 and System.Data.SQLite 1.0.109.2)
using (var c = NewConnection())
{
var sql = #"
update settings
set
""value"" = #SetDate
where ""key"" = 'week_date'";
c.Execute(sql, new { SetDate = date }); //<= throws PlatformNotSupportedException
// only on RELEASE not in DEBUG
}
The application is UWP configured as below. Furthermore, the faulting code is a .NET Standard 2.0 Class Library
Why is it crashing on RELEASE only and how to fix it?

Dapper is very deeply based on runtime IL generation, in ways that it would be basically impossible to change. Runtime IL generation is fundamentally not compatible with UWP.
There is no simple way of making this work.
So: to do this, you'd need to use something dapper-like-but-not-dapper, with one of two alternative implementations:
reflection-based binding (relatively slow, depending on how much data access you're doing)
compile-time code-gen of the missing pieces, presumably using some kind of roslyn analysis and partial class generation
Perhaps right now, the more pragamatic approach would be: don't use dapper in this case.

Related

Can a certain piece of code be executed with a certain dll?

I have an issue where Newtonsoft.Json is loaded twice in my solution, with two different versions. This is because I am creating an Add-In in Revit, which loads by default version 9.0.0 of Newtonsoft.
The idea is that, when (de)serializing, the operation works well when I use version 11.0.0, but doesn't if I use version 12.0.0 - which I actually want to use. Hence, the option of downgrading just to make the deserialization work is excluded for now.
What I am wondering is; is there any possibility that I could execute version 11.0.0 only on a certain portion of the code? For example, something like this:
execute Newtonsoft.Json.dll version 11.0.0
{
var model = JsonConvert.Deserialize<ModelType>(json);
}
// the rest works with version 12.0.0
While the problem might not be this one, I am still curious if this is possible to achieve. Basically, I want a certain piece of code to be executed using a certain module, except for the one that is already referenced.

License error using Benchmark.NET + DevArt dotConnect for PostgreSQL

I'm working on an application consisting of several projects and using EntityFramework with dotConnect to run against PostgreSQL. I also have a license for dotConnect which successfully works in the main application.
In parallel, I'm crafting a console application(a different solution) using Benchmark.Net to measure the performance of the logic of one of the projects. But every time I run the benchmark I'm getting the error below:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> Devart.Data.PostgreSql.PgSqlException: Assembly that contains embedded dotConnect for PostgreSQL license cannot be used with this application: 0f238e83-669a-46b8-876f-40331880ee79.exe.exe.
Following this instruction, I have already generated licenses.licx through Visual Studio and <exe file>.licenses via lc.exe. But it is still producing the same error.
I'm suspecting that the fact that Benchmark.NET generates its own exe to run the benchmark causing this error but I'm not 100% sure. So I'm looking for a solution if anybody has one?
Thank you
I'm not sure it's a good idea to create a benchmark for code that does database calls etc. You're benchmarking not the code then, but your whole system instead: the file system, the database drivers, possible interop stuff, and so on.
This is not the idea of BenchmarkDotNet. It's actually created for benchmarking of relatively small CPU-bound tasks to find bottlenecks and perform optimizations based on measurements.
However, if you still want to do that, a solution might be to run the benchmark in-process of the console app you've created, without producing special benchmarking assemblies.
To do so, use the [InProcess] attribute. Just apply it to your benchmark class instead of usual job attributes:
[InProcess]
public class TypeWithBenchmarks
{
[Benchmark]
public void BenchmarkedMethod()
{
}
}

Why doesnt the .Net framework use Guard class (or equivalent) for method arguments

if one takes a look at the decompiled source of the .net framework code most of the APIs have checks like these
if (source == null)
throw Error.ArgumentNull("source");
on the method arguments instead of using a more generic class like
Guard.IsNotNull(source);
Is there a reason behind doing this explicilty every time or is this just legacy code that is been around since the framework was developed and the newer classes are moving towards this or are there any inherent advantages of having explicit checks? One reason that I could think off is probably to avoid overloading the stack with function pointers.
Adding to Matthews answer:
Your proposed syntax of Guard.IsNotNull(source); is not directly equivalent to the first code snippet. It only passes the value of the parameter but not its name, so the thrown exception can't report the name of the offending parameter. It just knows that one of the parameters is null.
You could use expression trees - like so: Guard.IsNotNull(() => source); - but analyzing this expression tree has a rather large performance impact at runtime, so this isn't an option either.
Your proposed syntax could only be used in conjunction with a static weaver. That's basically a post-compiler that changes the generated IL. That's the approach Code Contracts are using. But this comes with its own cost, namely:
That static weaver needs to be written by someone in the first place
It increases build time
The weaver also needs to patch the debug symbols
It causes all sorts of problems with Edit and Continue
Nowadays we can do this with Code Contracts so we can use:
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<MyType>() != null);
and so on, but currently we can only do this in our own code because this isn't built in to the CLR yet (it's a separate download).
The Code Contracts classes themselves have been a part of .Net since version 4, but by themselves they don't generate any checking code. To do that we need the code contracts rewriter which will be called by the C# compiler when generating your code. That's the thing that needs a separate download.
So yes we have better ways to do this now, but it hasn't been released as part of the CLR (yet) and so the CLR is currently using what you think of as a "legacy" approach.
It's certainly nothing to do with "overloading the stack with function pointers".
Even with Code Contracts, we are still doing a check of course. There's no IL command that I know of that checks an argument for null and throws if it is, so such work has to be done using several IL instructions (in all CLR languages). However, the Code Contracts code rewriter does generate inline code to check the Code Contract's predicate (e.g. value != null) rather than calling a method to do so, so it is very efficient.
There's no Guard class in the .NET framework so your proposed alternative is not feasible. Later additions to the framework do use code contracts, but rather sparingly. Not every .NET programmer at Microsoft seems that convinced that contracts are that useful, I do share the sentiment.
You are otherwise seeing the way Microsoft works. Code in the .NET framework is contributed by lots of small teams within the company. A typical team size is about 10 programmers. Otherwise a nod to what everybody in software dev business knows, large teams don't work. There's a critical mass where the amount of time spent on getting everybody to communicate starts to overwhelm the amount of time that can be spent on actually getting code produced.
Such teams are also constantly created and disbanded. Lots of parts of the framework no longer have an active team that maintains it. Typically just one guy that still knows the internals well enough to provide critical security updates and, maybe, bug fixes when necessary. The code that such a disbanded team wrote is very much in maintenance mode, changes are only made when absolutely necessary. Not just because there's no benefit to making minor stylistic changes but to reduce the odds that breaking changes are unknowingly added.
Which is a liability for the .NET framework, there are plenty of internals that have a knack for becoming externally visible, even if that code lives inside private methods. Like exceptions. And programmers using Reflection to hack around framework limitations. And the really subtle stuff, a great example is the bug in an email app widely used inside Microsoft, written by an intern. Which crashed and left everybody without email when they updated their machine from .NET 1.1 to .NET 2.0. The bug in that email app was a latent threading race that never triggered when running with .NET 1.1. But became visible by a very slight change in the timing of .NET 2.0 framework code.
It might not be a part of .NET Framework but Microsoft developers seem to be embracing the concept (notice the use of JetBrains annotations instead of Code Contracts as well):
https://github.com/aspnet/EntityFramework/blob/master/src/Shared/Check.cs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using JetBrains.Annotations;
namespace Microsoft.Data.Entity.Utilities
{
[DebuggerStepThrough]
internal static class Check
{
[ContractAnnotation("value:null => halt")]
public static T NotNull<T>([NoEnumeration] T value, [InvokerParameterName] [NotNull] string parameterName)
{
NotEmpty(parameterName, "parameterName");
if (ReferenceEquals(value, null))
{
throw new ArgumentNullException(parameterName);
}
return value;
}
...
The only thing I can think of, is that if you have a Guard class, then in the exception stacktrace, it will look as if the problem is in Guard when it's actually in the method that called Guard. You could get around this by catching and rethrowing, but then you've got boilerplate in your production code again.

String to method

Being able to create javascript code on the fly is pretty cool.
That is by using
HtmlPage.Window.Eval("alert('Hello World')");
But is there a way to do the same thing, with a C# method? Lets say something like
void MethodEval("MessageBox.Show('Hello World')");
Is it even possible, without having to recompile your code?
It's possible using tricks posted by others. However, it's usually a very bad idea.
.Net code typically runs in a more trusted context than a javascript browser sandbox, and has access to a much richer, and therefore potentially damaging, api.
Instead you use the System.Addin namespace to provide a very strict interface for extensions, plugins, and the like. If you're just trying to use a more "fluid" or functional programming environment you can use fun features like lamdba expressions and closures to pass functionality around internally.
You can do it right now. The ag DLR (Silverlight Dynamic Languages Runtime) can host javascript.
While Javascript cannot be hosted with the DLR outside the browser Ruby and Python can. Here's an example of a C# snippet using the DLR and hosting a piece of Python of code to demonstrate.
using IronPython.Hosting;
PythonEngine pythonEngine = new PythonEngine();
string script = #"import clr
clr.AddReference(""System.Windows.Forms"")
import System.Windows.Forms as WinForms
WinForms.MessageBox.Show(""Hello"", ""Hello World"")";
pythonEngine.Execute(script);
This is possible, but a little more tricky, using Microsoft's .NET framework.
The C# compiler is part of the base runtime, so you can compile an in-memory assembly, and execute code in there on the fly.
Here is a good MSDN blog post describing the basic process.
I have used this before to make a scripting engine for a C# project. With a little work wrapping this, you can make this quite easy to use. An open source project I've worked on has a project dedicated to this: Pluto.Scripting
We had examples and tests in that project which show dynamic compilation and execution of C#, VB.NET, and Boo.
If you don't mind Boo, you can use its interpreter.
Actually I kept on getting an error "unexpected indent" so changing the code to
PythonEngine pythonEngine = new PythonEngine();
string script = #"import clr; clr.AddReference(""System.Windows"");";
script += #"import System.Windows as Wins;";
script += #"Wins.MessageBox.Show(""Hello World"");";
pythonEngine.Execute(script);
Worked! interesting... Thanks
Why do you need this feature ? Shouldnt your code know its paths and include that logic ? If you cant forsee such use cases - then perhaps its not needed. The only real benefit is it opens an opportunity to be abused and attacked. It sounds like your in directly creating a potential for an exploit - its a shame because managed runtimes like Java/CLR dont allow code injection but you are bringing all that goodness back in...

Where would you use C# Runtime Compilation?

I happened upon a brief discussion recently on another site about C# runtime compilation recently while searching for something else and thought the idea was interesting. Have you ever used this? I'm trying to determine how/when one might use this and what problem it solves. I'd be very interested in hearing how you've used it or in what context it makes sense.
Thanks much.
Typically, I see this used in cases where you are currently using Reflection and need to optimize for performance.
For example, instead of using reflection to call method X, you generate a Dynamic Method at runtime to do this for you.
You can use this to add scripting support to your application. For examples look here or here.
It is quite easily possible to publish parts of your internal object framework to the scripting part, so you could with relative ease add something to your application that has the same effect as for example VBA for Office.
I've seen this (runtime compilation / use of System.Reflection.Emit classes) in generating dynamic proxies ( Code project sample ) or other means of optimizing reflection calls (time-wise).
At least one case you might use it is when generating dynamic code. For example, the framework is using this internally to generate XML serializers on the fly. After looking into a class at runtime, it can generate the code to serialize / deserialize the class. It then compiles that code and users it as needed.
In the same way you can generate code to handle arbitrary DB tables etc. and then compile and load the generated assembly.
Well, all C# code is run-time compiled, since it's a JIT (just-in-time) compiler. I assume you are referring to Reflection.Emit to create classes etc. on the fly. Here's an example I have seen recently in the Xml-Rpc.Net library.
I create a C# interface that has the same signature as an XML-RPC service's method calls, e.g.
IMyProxy : IXmlRpcProxy
{
[XmlRpcMethod]
int Add(int a, int b);
}
Then in my code I call something like
IMyProxy proxy = (IMyProxy)XmlRcpFactory.Create(typeof(IMyProxy));
This uses run-time code generation to create a fully functional proxy for me, so I can use it like this:
int result = proxy.Add(1, 2);
This then handles the XML-RPC call for me. Pretty cool.
I used runtime compiler services from .NET in my diploma thesis. Basically, it was about visually creating some graphical component for a process visualization, which is generated as C# code, compiled into an assembly and can then be used on the target system without being interpreted, to make it faster and more compact. And, as a bonus, the generated images could be packaged into the very same assembly as resources.
The other use of that was in Java. I had an application that had to plot a potentially expensive function using some numerical algorithm (was back at university) the user could enter. I put the entered function into a class, compiled and loaded it and it was then available for relatively fast execution.
So, these are my two experiences where runtime code generation was a good thing.
something I used it for was for allowing C# and VB code to bu run by the user ad-hoc. They could type in a line of code (or a couple lines) and it would be compiled, loaded into an app domain, and executed, and then unloaded. This probably isnt the best example of its usage, but an example of it none-the-less

Categories