Azure Functions .Net 5: Is it possible to implement POCO binding somehow? - azure

When moving my functions to .net5 I faced the fact that POCO binding that worked fine with 3.1 is not applicable with .net 5 anymore for some reason. They say it will be implemented at some point maybe, but for the certain reasons I need it now. Tried to find some hacky way to implement this, but failed. The best thought I had was to implement explicit operator in my DTO object which will cast HttpRequestData to it's type, but the problem is that HttpRequestData is an abstract type, and it's concrete implementation type is internal. After that I tried to cast the input parameter to HttpRequestData in middleware with reflection, but parameters are stored in IReadOnlyDictionary which is immutable. So I ran out of ideas now. Maybe someone found workaround to this and can kindly share, would be much appreciated.

I suppose you're using the "dotnet-isolated" mode (only way to run on .NET 5).
I'm trying to find a more elegant solution to this as well.
Meanwhile, what I did was to deserialize the data myself, inside the function.
var body = await new StreamReader(request.Body).ReadToEndAsync();
var myobject = JsonSerializer.Deserialize<MyPocoClass>(json);
I would really prefer if the runtime did it by itself, but I couln't find a way yet. I read somewhere that it is possible to create our own binding code, but I haven't tried it.
I noticed that I could bind to individual properties of the json payload, but not to an object...
I hope this arrives in Azure Functions v4 + .NET6, since it is right around the corner.

Related

How to mock calls made to Durable Entities in Azure durable functions?

I'm using MOQ to mock a durable entity, but seeing this error:
Extension methods (here: DurableContextExtensions.CallEntityAsync) may
not be used in setup / verification expressions.
Here's how I'm doing it:
mockContext.Setup(e => e.CallEntityAsync<List<string>>(It.IsAny<EntityId>(), "EntityFunctionName"))
.ReturnsAsync(new List<string>() {"one", "two", "three" });
Is there any way I can mock calls to my durable entity?
As of Durable Functions 2.3.0, all of our extension methods are now baked directly into the interface, so it should be substantially easier to use Moq with all of these methods and their overloads.
Edit: The previous answer below covers why the previous extension method approach made this dificult.
So this is an inherent limitation of how Moq works with extension methods.
Unfortunately, in the meantime, you will need to find out the core method on IDurableOrchestrationContext that is called by the extension method that provides the overload you are using.
For instance, in this case, DurableContextExtension.CallEntityAsync(EntityId entityId, string operationName) is calling IDurableOrchestrationContext.CallEntityAsync(EntityId entityId, string operationName, object operationInput), with a value of null for operationInput. You can find this by looking at the source code.
This is obviously not an ideal way for mocking, as without looking at our source code, it is difficult to tell if you are attempting to mock an extension method or not at the time of writing your tests. You can use a Moq analyzer to at least catch these errors at compile time, but it still won't tell you which method signature to mock to get rid of the error.
We are proposing getting rid of extension methods altogether for this reason, and just putting all of these signature overloads as interface methods directly, so you can mock any of them safely. This is a breaking change for customers who write their tests by directly implementing the interface, so we are trying to keep this change out of a patch release, and only in a minor release with clear guidance of how to fix those broken by these changes. Look for this to be fixed in version 2.3.0 of the extension.

What do I use to replace ToNullSafeString() removed from AutoMapper 3?

I have code using AutoMapper 3.2.1.0 that uses the method ToNullSafeString().
I upgraded the NUGet package to 4.1.1.0, and I can no longer find the method in their package.Does anyone know the recommended approach to replacing the function? Is there a new construct that is functionally equivalent? If so, I cannot figure what it is. Nor can I find any mention of why it was removed.
This question has actually been answered pretty well in a couple of comments below it. For completeness, here are a couple of actual implementations of solutions.
Short answer
Probably both the simplest and the best solution: Replace all instances of .ToNullSafeString() with ?.ToString(). This does the same, but uses functionality built into newer versions of .Net instead of relying on an external extension method.
Alternative answer
If you've got a bunch of calls to the ToNullSafeString() method from the earlier version Automapper, and for some reason or other you can't or don't want to go through all your code and edit it away right now, you can use this instead.
Add the following class to your project, and make sure it can be reached from any classes that previously called the Automapper-method. Those calls will then automatically point to this instead.
public static class NullSafeStringHelper
{
public static string ToNullSafeString(this object value)
{
return value?.ToString();
}
}

ServiceStack ProtoBuff Serialization to custom stream

a few days ago i posted a question about Serializing the ResponseStatus property with BinaryFormatter. Mythz pointed out it wasnt the fastest way to go, so i decided to switch to another formatter. Tried ProtoBuff and MsgPack, and am on ProtoBuf now.
My real question is: im trying to grasp how Protobuf knows how ServiceStack Dto's should be serialized. I tried adding all the possible attributes to my existing dto, ProtoContract and ProtoMember(0,1,2,3,etc), but also DataContract and DataMember.
On top of that i dont use ServiceStack's own client, but try to serialize the request to an existing stream.
If i dont do this:
ServiceStack.ProtoBuf.ProtoBufFormat.Model.Add (typeof(NameSpacePlaceholder.Service.Dto.GetNodes), false);
i get an error about Types and Contracts that cannot be infered,
If i do add that piece of code, all continues great, but the deserialized object is empty.
Im using this to Serialize:
ServiceStack.ProtoBuf.ProtoBufFormat.Model.Serialize (ms, myObject);
and to Deserialize:
ServiceStack.ProtoBuf.ProtoBufFormat.Model.Deserialize (ms, null, deserializationType);
I think im missing something here. Could it have something to do with namespaces? I looked into some code from ServiceStack.ProtoBuff, it isnt so hard to understand, but i cannot get it going.
Things that are unclear to me now:
Is there a need to add Attributes to the existing DTO's ? (in ProtoBuf V2 i can also do it in code, i read, but for now i can also alter the existing DTO's)
Do i need to initialize the Request(and response) DTO's, in my Client(Serialize) as wel in my Server(Deserialize)
Is there some reason why i should not be serializing to my own Stream ?
Many thanks,
I hate it to post an answer myself, it means i havent searched enough in the first place
I learned the following attributes are very important:
[ProtoContract]
[ProtoMember(X)]
[ProtoInclude(X,typeof(DerivingClass))]
For now i learned something new: why class inheritance in DTO's is not advisable.
I've got it going now, and will try to make it real-life friendly..

Ignore certain TypeScript compile errors?

I am wondering if there is a way to ignore certain TypeScript errors upon compilation?
I basically have the same issues most people with large projects have around using the this keyword, and I don't want to put all my classes methods into the constructor.
So I have got an example like so:
TypeScript Example
Which seems to create perfectly valid JS and allows me to get around the this keyword issue, however as you can see in the example the typescript compiler tells me that I cannot compile that code as the keyword this is not valid within that scope. However I don't see why it is an error as it produces okay code.
So is there a way to tell it to ignore certain errors? I am sure given time there will be a nice way to manage the this keyword, but currently I find it pretty dire.
== Edit ==
(Do not read unless you care about context of this question and partial rant)
Just to add some context to all this to show that I'm not just some nut-job (I am sure a lot of you will still think I am) and that I have some good reasons why I want to be able to allow these errors to go through.
Here are some previous questions I have made which highlight some major problems (imo) with TypeScript current this implementation.
Using lawnchair with Typescript
Issue with child scoping of this in Typescript
https://typescript.codeplex.com/discussions/429350 (And some comments I make down the bottom)
The underlying problem I have is that I need to guarantee that all logic is within a consistent scope, I need to be able to access things within knockout, jQuery etc and the local instance of a class. I used to do this with the var self = this; within the class declaration in JavaScript and worked great. As mentioned in some of these previous questions I cannot do that now, so the only way I can guarantee the scope is to use lambda methods, and the only way I can define one of these as a method within a class is within the constructor, and this part is HEAVILY down to personal preference, but I find it horrific that people seem to think that using that syntax is classed as a recommended pattern and not just a work around.
I know TypeScript is in alpha phase and a lot will change, and I HOPE so much that we get some nicer way to deal with this but currently I either make everything a huge mess just to get typescript working (and this is within Hundreds of files which I'm migrating over to TypeScript ) or I just make the call that I know better than the compiler in this case (VERY DANGEROUS I KNOW) so I can keep my code nice and hopefully when a better pattern comes out for handling this I can migrate it then.
Also just on a side note I know a lot of people are loving the fact that TypeScript is embracing and trying to stay as close to the new JavaScript features and known syntax as possible which is great, but typescript is NOT the next version of JavaScript so I don't see a problem with adding some syntactic sugar to the language as people who want to use the latest and greatest official JavaScript implementation can still do so.
The author's specific issue with this seems to be solved but the question is posed about ignoring errors, and for those who end up here looking how to ignore errors:
If properly fixing the error or using more decent workarounds like already suggested here are not an option, as of TypeScript 2.6 (released on Oct 31, 2017), now there is a way to ignore all errors from a specific line using // #ts-ignore comments before the target line.
The mendtioned documentation is succinct enough, but to recap:
// #ts-ignore
const s : string = false
disables error reporting for this line.
However, this should only be used as a last resort when fixing the error or using hacks like (x as any) is much more trouble than losing all type checking for a line.
As for specifying certain errors, the current (mid-2018) state is discussed here, in Design Meeting Notes (2/16/2018) and further comments, which is basically
"no conclusion yet"
and strong opposition to introducing this fine tuning.
I think your question as posed is an XY problem. What you're going for is how can I ensure that some of my class methods are guaranteed to have a correct this context?
For that problem, I would propose this solution:
class LambdaMethods {
constructor(private message: string) {
this.DoSomething = this.DoSomething.bind(this);
}
public DoSomething() {
alert(this.message);
}
}
This has several benefits.
First, you're being explicit about what's going on. Most programmers are probably not going to understand the subtle semantics about what the difference between the member and method syntax are in terms of codegen.
Second, it makes it very clear, from looking at the constructor, which methods are going to have a guaranteed this context. Critically, from a performance, perspective, you don't want to write all your methods this way, just the ones that absolutely need it.
Finally, it preserves the OOP semantics of the class. You'll actually be able to use super.DoSomething from a derived class implementation of DoSomething.
I'm sure you're aware of the standard form of defining a function without the arrow notation. There's another TypeScript expression that generates the exact same code but without the compile error:
class LambdaMethods {
private message: string;
public DoSomething: () => void;
constructor(message: string) {
this.message = message;
this.DoSomething = () => { alert(this.message); };
}
}
So why is this legal and the other one isn't? Well according to the spec: an arrow function expression preserves the this of its enclosing context. So it preserves the meaning of this from the scope it was declared. But declaring a function at the class level this doesn't actually have a meaning.
Here's an example that's wrong for the exact same reason that might be more clear:
class LambdaMethods {
private message: string;
constructor(message: string) {
this.message = message;
}
var a = this.message; // can't do this
}
The way that initializer works by being combined with the constructor is an implementation detail that can't be relied upon. It could change.
I am sure given time there will be a nice way to manage the this keyword, but currently I find it pretty dire.
One of the high-level goals (that I love) in TypeScript is to extend the JavaScript language and work with it, not fight it. How this operates is tricky but worth learning.

Kohana helper attribute

I have a question that keeps bothering me. Currently, I have started using Kohana 3.2 Framework. I've written a helper to handle some functionality - I have a number of methods, which are (as it should be) declared STATIC. But, all of these methods are somehow working with the database, so I need to load a model. Currently, every method has a non-static variable like this:
$comment = new Model_Comments;
$comment->addComment("abc");
OK, it seems to be working, but then I wanted to get rid of this redundancy by using class attribute to hold the instance of the model (with is class as well).
Something like this:
private static $comment; // Declaring attribute
self::$comment = new Model_Comment; // This is done within helper __constuct method
self::$comment->addComment("abc"); // And call it within the method.
But, I got failed with: Call to a member function addComment() on a non-object
Question is: is it possible to do it ? Maybe there are some other approaches ?
Sorry for a long story and, thanks in advice! :P
A static method cannot call a non-static method without operating on an instance of the class. So, what you're proposing won't work. There may be a way do accomplish something similar, but what about trying the following:
You could implement the singleton or factory pattern for your "helper" class. Then, you could create the model (as an attribute) as you instantiate/return the instance. With an actual instance of your "helper" class, you won't have to worry about the static scope issues.
In other words, you can create a helper-like class as a "normal" class in your application that, upon creation, always has the necessary model available.
I'd be happy to help further if this approach makes sense.
David

Resources