My Software Notes

Useful things I discover

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