My Software Notes

Useful things I discover

Why does the compiler choose the IEnumerable “Where” instead of the IQueryable “Where”?

leave a comment »

I hit a problem last week that took me a little while to figure out and I wanted to make a note of it while it’s still fresh in my mind.

I wrote a very simple LINQ query against a DbSet<T> that was in a derived DbContext. The query worked fine and returned what I wanted, but then I converted the method to an async method and the query to an async query at which point I started getting an exception:

InvalidOperationException: The source IQueryable doesn’t implement IAsyncEnumerable. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations.

It boiled down to the fact that the compiler was deciding to treat my query as an IEnumerable instead of an IQueryable, but why?

Turns out it was my error – imagine that ūüôā

My method looked like this:

    public async Task<IEnumerable<Movie>> GetListAsync(<Func<Movie, bool> predicate, 
                                                          int start, int take)
    {
        using (var db = GetDbContext())
        {
            var movies = await db.Movies
                .Where(predicate)
                .Skip(start)
                .Take(take)
                .ToArrayAsync();
            return movies;
        }
    }

 
Seems pretty straightforward, right? But there was a red line under “.ToArrayAsync” and when I hovered the mouse over “.Where”, it shows me the signature of the Where extension method for IEnumerable<T> and not for IQueryable<T>.¬† Huh?

The reason is in the type of the “predicate” parameter.¬† Let’s compare the extension method signatures for the IEnumerable<T>.Where() and the IQueryable<T>.Where():

    IEnumerable<T>.Where<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)

    IQueryable<T>.Where<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)

 
DbSet<T> implements both interfaces so the compiler has to figure out which “Where” method is should use. Because I was passing a Func<TSource, bool>, the compiler, quite correctly, matched the “Where” clause for IEnumerable<T>.

The fix was to change the type of “predicate”, so the signature for the method became:

    public async Task<IEnumerable<Movie>> GetListAsync(Expression<Func<Movie, bool>> predicate, 
                                                          int start, int take)

 
Then everything worked perfectly and I didn’t need to change the code that was calling GetListAsync because a lambda expression works for both Expression<Func<T, bool>> and plain Func<T, bool>.

 

Advertisements

Written by gsdwriter

October 16, 2018 at 12:49 pm

Posted in .NET, Entity Framework, LINQ

Unit Testing Non-Public Methods in .NET

leave a comment »

Just a note to self on how to test non-public methods.

Internal methods can be accessed using the InternalsVisibleTo attribute in AssemblyInfo.cs.

        [assembly: InternalsVisibleTo("MyAssembly.Tests")]

There is a little more needed for signed assemblies. Check out this reference: Unit Test Non-Public Methods and Classes.

For private (not sure if this applies to protected or not) use the PrivateObject Class.

Example: test a method that reverses a string. Method signature:

        private string ReverseIt(string forward)

Example code:

            var expected = "drawroF";
            var testValue = "Forward";
            var example = new ExampleClass();
            var testObj = new PrivateObject(example);
            var actual = testObj.Invoke("ReverseIt", testValue);
            Assert.AreEqual(expected, actual);

A protected method is easy to test by creating a subclass of the class.

Written by gsdwriter

November 28, 2017 at 1:59 pm

Posted in .NET, Testing

IValidatableObject for Complex Custom Validation

leave a comment »

Just a note to help me remember the IValidatableObject interface that is used in ASP.NET MVC for adding complex custom validation to a view model.

You can put data annotations on a view model so when the data comes back from a request (e.g., a form post) and the data is being bound to the model, the data annotations can be used to validate that the data coming in is correct.

Example: the property on the view model is a string and you put the StringLengthAttribute on it to specify that the length must be from 5 to 10 characters. If the value in the property is 12 characters then that will be caught and an entry will be added to the ModelState.

But what if your validation is complex? For example, you have property X that is a date that can’t be in the future and can’t be later than the date in property Y, but the date in property X is only required if the item has not been discontinued (a value of false in property Z).

You could write a custom data annotation, but it’s unlikely you’ll ever reuse it, so instead use the IValidatableObject interface. ¬†Implement it on your view model and a Validate() method is added to your model that you can use to run your custom validations.

Rather than reinvent the wheel, here are some useful references on how to do it:

 

 

Written by gsdwriter

June 20, 2017 at 11:59 am

Dispatching and Binding

leave a comment »

This is just a quick note on definitions:

Binding – determining which signature (method name + parameters) should be called.

Dispatching – Figuring out which implementation of a signature to call.

Example:

    public interface IFoo
    {
        void MyMethod(int id);
    }

    public class Foo : IFoo
    {
        public virtual void MyMethod(int id)
        {
            //whatever
        }
    }

    public class Bar : Foo
    {
        public override void MyMethod(int id)
        {
            //whatever else
        }
    }

    public class Tester
    {
        public void TestMe()
        {

            var array = new IFoo[] { new Foo(), new Bar() };

            foreach(var item in array)
            {
                item.MyMethod(42);
            }
        }
    }

How do you determine which MyMethod in the foreach loop is  to be called?

Binding –¬†match the signatures – MyMethod(int)

Dispatching Рfigure out which implementation (Foo.MyMethod or Bar.MyMethod) to call

Static Binding or Dispatching – figure it out at compile time.

Dynamic Binding or Dispatching – figure it out at run time.

 

Written by gsdwriter

November 2, 2016 at 7:42 am

git push hangs for no apparent reason

leave a comment »

Out of the blue, I got a hang when I did a push to a git repo.¬† I’ve no idea what caused it because it had never happened before and, of course, this time I was in a hurry.

The good news: I found the solution. Thanks to Pedro Liska who hit the same problem and found a solution:  git push hangs when windows git client pushes to TeamFoundation Git Server

The most recent version of git, as I write this, is 2.5. So, what are you waiting for? Go install it: git Downloads

Written by gsdwriter

August 27, 2015 at 10:38 am

Posted in git

Encrypting and Decrypting web.config sections

leave a comment »

Another thing I do infrequently is encrypt and decrypt web.config sections. I end up going back to a script I wrote ages ago to find the command lines.

So just to save time, here they are:

Encrypt a web.config section

“c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe” -pef sectionName sitePath

E.g.,

“c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe” -pef “connectionStrings” “c:\websites\mysite”

Decrypt a web.config section

“c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe” -pdf sectionName sitePath

E.g.,
“c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe” -pdf “connectionStrings” “c:\websites\mysite”

These command lines must be run on the web server and must be run in a console with admin privileges.

Written by gsdwriter

February 19, 2015 at 11:55 pm

Posted in IIS

Covariance and Contravariance. What do they mean again?

with one comment

I don’t have to deal with covariance and contravariance very often, so every time I do I forget which is which. So, just for my own benefit, here is a note describing them:

Covariance and contravariance are terms that refer to the ability to use a less derived or more derived type than originally specified.

Covariance – Enables you to use a more specific type than originally specified

E.g., in generics

We have a base type called “Feline” and we have a derived type called “HouseCat”.

IEnumerable<HouseCat> cats = new List<HouseCat>();
IEnumerable<Feline> gods = cats;
//Note: felines have a very high opinion of themselves :)


Contravariance – Enables you to use a less derived type than originally specified.

E.g., in generics

Using the same base and derived types as above.

IEnumerable<Feline> gods = new List<Feiline>();
IEnumerable<HouseCat> cats = gods;


References:

Covariance and Contravariance (C# and Visual Basic)

Covariance and Contravariance in Generics

 

Written by gsdwriter

January 19, 2015 at 12:05 pm

Posted in .NET, Languages