My Software Notes

Useful things I discover

Archive for the ‘.NET’ Category

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

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;


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


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:



just after the line:



You should end up with something like this:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">


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

Hope that helps.

Written by gsdwriter

July 28, 2014 at 11:39 am

Entity Framework Generates Weird SQL

leave a comment »

If you ever see Entity Framework code that looks something like this:

1 AS [C1],
CAST(NULL AS int) AS [C2],
CAST(NULL AS int) AS [C3],
CAST(NULL AS varchar(1)) AS [C4]
FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]
WHERE 1 = 0

and your EF LINQ query was nothing like it (and who’s would be?), then you probably have a


in your query and the collection “somelist” is empty.

I hit this today and was scratching my head until I found this:  

LINQ to Entity Framework submits meaningless query to SQL Server for Contains(empty array)

Hope that helps someone.


Written by gsdwriter

July 17, 2014 at 5:14 pm

log4net – Quick and Dirty set up

leave a comment »

I do this infrequently enought that I have to keep going back to old projects to see the steps.  So, I’m putting them here to save me the hunting.

  1. Use NuGet to pull in the Log4Net binaries, etc. to your project.
  2. Add to your web.config <configSections> element:
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
  3. Add to your web.config under the root <configuration> element (modify the appender as you wish):
      <log4net threshold="All">
        <appender name="LogFile" type="log4net.Appender.FileAppender" >
          <file value="c:\logs\MyLog.log" />
          <appendToFile value="true" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %-5level %-40logger{2} - %message%newline" />
          <level value="All" />
          <appender-ref ref="LogFile" />
  4. Add to your AssemblyInfo.cs file:
    [assembly: log4net.Config.XmlConfigurator(Watch = true)]
  5. In the file where you want to use it:
    using log4net;
  6. Example of use:
    var log = LogManager.GetLogger(System.Reflection.MethodBase
    log.Error("This is a test log message with an exception", 
        new Exception("Test Exception"));

That should do it.

Examples of config: log4net Config Examples

Written by gsdwriter

January 31, 2013 at 1:07 pm

Posted in .NET, Logging, Tools

Adding PowerShell Automation to a .NET Application

with 3 comments

So I want to add PowerShell automation to my .NET app and according to MSDN (How to Write a Simple Host Application) I have to use the “Browse” feature of the “Add Reference” dialog in Visual Studio.  The location for the System.Management.Automation.dll is given as “Windows\assembly\GAC_MSIL\System.Management.Automation”.  But that may not always be correct.  See my note at the end.

Another, and I think better, way to do it is to open your project file and in the first “<ItemGroup>” section, add:

    <Reference Include="System.Management.Automation" />

This worked great for me.

Something to watch out for if you use the “Browse” method and you are using the Powershell 3 CTP: The dll is in a different location:


When I used the “Reference” method, Visual Studio referenced it without me having to do anything more.  Now that’s what I call service.

Written by gsdwriter

August 28, 2012 at 3:46 pm

Posted in .NET, Powershell, Visual Studio

Tagged with ,