My Software Notes

Useful things I discover

Archive for the ‘.NET’ Category

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: Contains() (aka ‘Like’) is 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.


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();

And, to quote Led Zepplin, “It makes me wonder.”

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 ,

ASP.NET Timouts (Sessions and App Pools and Auths, Oh My)

with 4 comments

I just had to extend the timeout for an ASP.NET site and I had to look it up all over again.  I don’t extend timeouts very often but when I do I never remember all the places that I may need to make a change.  Sadly just changing sessionState in the Web.Config doesn’t always cut it.

So here, for my future use and for anyone else with the same problem, are a list of all the timeout possibilities that I know of in ASP.NET web apps.

Session State – In web.config

Session state timeout is 20 mins by default.  To increase it set the timeout attribute on the sessionState element in the web.config.

     <sessionState timeout="60" /> 


ASP.NET Session Timeouts

sessionState Element

App Pool Idle Time-out – In IIS

The Application Pool of your web app has an “Idle Time-out (in minutes)” setting in “Advanced Settings” (IIS7)  The help text says: “Amount of time (in minutes ) a worker process will remain idle before it shuts down.”


ASP.NET Session Timeouts

Configure Idle Time-out Settings for an Application Pool (IIS 7)

Forms Authentication Timeout – In web.config

Forms authentication uses it own value for timeout (30 min. by default). A forms authentication timeout will send the user to the login page even if the session is still active.  The setting is in minutes.

     <authentication mode="Forms">
           <forms timeout="50"/>


Answer to question about Session Timeout in ASP.NET

forms Element for authentication

Recycle Worker Process – in IIS

Not really a timeout but it will have that effect.  The default is 29 hours, so you will rarely need to change it.


ASP.NET Session Timeouts

Configuring Recycling Settings for an Application Pool (IIS 7)

Execution Timeout – in web.config and in code

This is the time allowed for a request to execute before it is shut down.  The default is 110 seconds, so it’s plenty long enough for most situations.  If you need to make it longer for your entire site then use web.config and if you need to lengthen it for just a specific request then do it in code.

In Web.Config:

   <httpRuntime executionTimeout="180" />

If compilation debug is true then the timeout is always about a year (really).  This is so your app doesn’t stop handling a request while you are running through the debugger in Visual Studio.


ASP.NET Session Timeouts

httpRuntime Element

In Code:

The HttpServerUtility class has a property called ScriptTimeout that allows you to set the timeout for the current request.  In ASP.NET and ASP.NET MVC you can get at this property via the Server property of your Page or Controller.

Server.ScriptTimeout = 600;  //in seconds


HttpServerUtility.ScriptTimeout Property

Timeout of an ASP.NET page

ASP.NET Session Timeouts

Security Token Handlers – In web.config and code

Here’s another one I just came across (01/20/2014).  This can be used to replace the forms authentication timeout.

In Web.Config

The “lifetime” attribute in the sessionTokenRequirement element can be used to set the timeout. It uses the format “hh:mm:ss”.

      <remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler,System.IdentityModel, 
      	Version=, Culture=neutral,PublicKeyToken=B77A5C561934E089" />
      <add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler,System.IdentityModel.Services, 
      	Version=, Culture=neutral,PublicKeyToken=B77A5C561934E089">
        <sessionTokenRequirement lifetime="00:20:00"></sessionTokenRequirement>

In Code

Classes derived from SecurityTokenHandler have a TokenLifetime property that can be set using a TimeSpan.

tokenHandler.TokenLifetime = new TimeSpan(0, 20, 0); //hh, mm, ss



SessionSecurityTokenHandler Class


I think that’s everything.  If not please leave a comment and enlighten me 🙂

If you have any other useful links on the subject please leave those too.

Written by gsdwriter

June 22, 2012 at 10:55 am