My Software Notes

Useful things I discover

Solving Time for Browsers and Servers

leave a comment »

The person using the browser is in time zone A and the server is in time zone B. How do we display the time and how do we save the time so we don’t end up with a Doctor Who style time distortion?

Here is a quick list of the methods I’ve come across.

(NOTE: always save dates and times to your database in UTC, never in local time)

  1. Pass the time-zone offset on each call:
    1. Put it in a cookie using JavaScript then read the cookie on the server

    2. Put it in a header

    3. Put it in a query string parameter

  2. Allow user to set the time zone as a preference and save it in the database
  3. Use moment.js or a similar library to convert the time to UTC each time before you pass it back
  4. Put the time-zone offset into a hidden field in a form so it is part of the POST back to the server

I prefer the cookie and the user preference methods.  I also use the moment.js method where it is applicable.

References – these contain details of how to do the things mentioned above:

How to get the time zone offset in the browser:

var d = new Date()
var timezoneOffset = d.getTimezoneOffset();

 

Written by gsdwriter

July 1, 2020 at 10:53 am

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>.

 

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")]
 .

For .NET Core, there is no AssemblyInfo.cs file, so you will need to put the attribute in a file of your choice, on the namespace. For executable assemblies the Program.cs file is probably best.

[assembly: InternalsVisibleTo("MyAssembly.Tests")] 
namespace My.Example.App
{
    // etc.

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

Entity Framework: Is Contains() (aka ‘Like’) case insensitive for SQL Server queries?

with 3 comments

Just a note to self.

The Contains method on String when used in an Entity Framework “where” clause is case insensitive (if the server is set to ignore case).

Example:

Assume the “NoteContent” column on the table “Notes” is a varchar column. If I run the following Linq query against the database where db is a DbContext then I get the same result every time.

var¬†num = db.Notes.Where(n => n.NoteContent.Contains(“NoTe”)).Count();

var¬†num = db.Notes.Where(n => n.NoteContent.Contains(“NOTE”)).Count();

var¬†num = db.Notes.Where(n => n.NoteContent.Contains(“note”)).Count();

All produce the same value for “num”.

I’m making this note to self because I keep forgetting and because I keep seeing people do this:

var someString = “whatever”;

var num = db.Notes.Where(n => n.NoteContent.ToUpper().Contains(someString.ToUpper())).Count();

You will need to do this if the underlying SQL Server has been set to be case sensitive.

Thanks to the people who added comments, correcting my original post that said it didn’t matter.

Written by gsdwriter

December 2, 2014 at 9:53 am

Posted in .NET, Database, LINQ

Forcing Visual Studio to produce an XML Serializers DLL

leave a comment »

A friend needed the Xml Serializers dll, the one named something like “ClassLibrary1.XmlSerializers.dll”, so he went into the project properties in¬†VS and set “Build > Generate serialization assembly” to “On”.¬† But nothing happened.¬† No XmlSerializers dll was created.

We hunted round for an answer and came across this: Generating an Xml Serialization assembly as part of my build.

Quick answer:

After setting the above project property you must go into the project file in your favorite text editor and add this:

<SGenUseProxyTypes>false</SGenUseProxyTypes>

 

just after the line:

<GenerateSerializationAssemblies>On</GenerateSerializationAssemblies>

 

You should end up with something like this:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <GenerateSerializationAssemblies>On</GenerateSerializationAssemblies>
    <SGenUseProxyTypes>false</SGenUseProxyTypes>
  </PropertyGroup>

 

Do that for every build configuration where you need the serializer.

Hope that helps.

Written by gsdwriter

July 28, 2014 at 11:39 am