using the .Net As operator

The as operator is similar to cast, if the conversion isn’t possible null is returned instead of raising an exception.

using System;

namespace CSharpASoperator
{
    class Program
    {
        static void Main(string[] args)
        {
            var objArray = new object[6];

            objArray[0] = new WithFields();
            objArray[1] = new WithProperties();
            objArray[2] = "A String";
            objArray[3] = 123456789;
            objArray[4] = 1234.5678;
            objArray[5] = null;

            foreach (var t in objArray)
            {
                var s = t as string;

                Console.WriteLine(s ?? "not a string: ");
            }

            Console.ReadKey();

        }

        private class WithFields
        {
            private string _name;

        }

        private class WithProperties
        {
            private string Name { get; set; }
        }
    }
}

From: http://msdn.microsoft.com/en-us/library/vstudio/cscsdfbt.aspx

.Net Timer callback with a delegate

A timer using a delegate.

using System;
using System.Threading;

namespace TimerCallbacks
{
    class Program
    {
        static void Main(string[] args)
        {
            var tb = new TimerCallback(PrintTime);

            var t = new Timer(tb,
               null,
               0,
               1000
            );

            Console.ReadKey();

        }

        static void PrintTime(object state)
        {
            Console.WriteLine("{0}", DateTime.Now.ToLocalTime());
        }
    }
}

.Net Adding Elmah, Log4Net and Glimpse to an MVC 4 application.

From the package manager console:

Install-Package Glimpse.Mvc4
Install-Package Log4Net
Install-Package Elmah

The web.config should look something like this:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
    </sectionGroup><section name="glimpse" type="Glimpse.Core.Configuration.Section, Glimpse.Core" /></configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-InstrumentationDemo-20130907170337;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-InstrumentationDemo-20130907170337.mdf" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
  <!-- Glimpse: This can be commented in to add additional data to the Trace tab when using WebForms
        <trace writeToDiagnosticsTrace="true" enabled="true" pageOutput="false"/> --><httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
    <add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" /></httpModules><httpHandlers>
            <add path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" />
        </httpHandlers></system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
  <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    <add name="Glimpse" path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" preCondition="integratedMode" /></handlers><modules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
    <add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" preCondition="integratedMode" /></modules></system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" />
        <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" />
        <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
  <log4net>
    <!-- A1 is set to be a ConsoleAppender -->
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="mylogfile.txt" />
      <appendToFile value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="DEBUG" />
        <levelMax value="FATAL" />
      </filter>
    </appender>
    <!-- Set root logger level to DEBUG and its only appender to A1 -->
    <root>
      <level value="ALL" />
      <appender-ref ref="FileAppender" />
    </root>
  </log4net>
<elmah>
    <!--
        See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for 
        more information on remote access and securing ELMAH.
    -->
    <security allowRemoteAccess="false" />
  </elmah>
  <location path="elmah.axd" inheritInChildApplications="false">
    <system.web>
      <httpHandlers>
        <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
      </httpHandlers>
      <!-- 
        See http://code.google.com/p/elmah/wiki/SecuringErrorLogPages for 
        more information on using ASP.NET authorization securing ELMAH.

      <authorization>
        <allow roles="admin" />
        <deny users="*" />  
      </authorization>
      -->  
    </system.web>
    <system.webServer>
      <handlers>
        <add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
      </handlers>
    </system.webServer>
  </location>
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
      <!-- If you are having issues with Glimpse, please include this. It will help us figure out whats going on. 
      <logging level="Trace" />-->
      
      <!-- Want to use Glimpse on a remote server? Ignore the LocalPolicy by removing this comment.
      <runtimePolicies>
        <ignoredTypes>
          <add type="Glimpse.AspNet.Policy.LocalPolicy, Glimpse.AspNet"/>
        </ignoredTypes>
      </runtimePolicies>-->
    </glimpse></configuration>

Elmah and Log4Net can be called from your code e.g.

 public class HomeController : Controller
    {
        private static readonly
           ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public ActionResult Index()
        {
             // For Log4Net testing
            Log.Debug("Debug message");
            Log.Info("Info message");
            Log.Warn("Warning message");
            Log.Error("Error message");
            Log.Fatal("Fatal message");

            // For Elmah testing
            throw new Exception("Broken!");
            ...
        }

.Net using Func<> and Action<>

An example of how to use Func<> and Action<>.

using System;
using System.Collections.Generic;
using System.Linq;

namespace FuncAndActionDemo
{
    /// <summary>
    /// Class to test Func and Action
    /// </summary>
    public static class FuncAndActionDemo
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        static void Main(string[] args)
        {
            const string name = "Test name";

            for (var i = 0; i < 10; i++)
            {
                var result = IsValid(new TestClass(string.Concat(name,i.ToString())));
                Action<String> print = PrintResults;
                new List<String> { result.ToString() }.ForEach(print);
            }
  
            Console.ReadKey();
        }

        private static void PrintResults(string results)
        {
            Console.WriteLine(results);
        }

        /// <summary>
        /// Determines whether the specified test is valid.
        /// </summary>
        /// <param name="test">The test.</param>
        /// <returns></returns>
        private static bool IsValid(TestClass test)
        {
            // Declare a func
            Func<TestClass, bool>[] rules =
                {
                    m => bool.Parse(m.IsTrue.ToString()),
                    m => !bool.Parse(m.IsFalse.ToString()),
                    m => !string.IsNullOrEmpty(m.HasName)
                };

            return rules.All(rule => rule(test));
        }
    }

    /// <summary>
    /// Class to demonstrate rule testing
    /// </summary>
    public class TestClass
    {

        public bool IsTrue { get; set; }
        public bool IsFalse { get; set; }
        public string HasName { get; set; }

        private readonly string _name;

        /// <summary>
        /// Initializes a new instance of the <see cref="TestClass"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        public TestClass(string name)
        {
            _name = name;
            IsOn();
            IsOff();
            CheckHasName(_name);
        }

        /// <summary>
        /// Determines whether this instance is on.
        /// </summary>
        private void IsOn()
        {

            IsTrue = true;
        }

        /// <summary>
        /// Determines whether this instance is off.
        /// </summary>
        private void IsOff()
        {
            IsFalse = false;

        }

        /// <summary>
        /// Checks the name of the has.
        /// </summary>
        /// <param name="name">The name.</param>
        private void CheckHasName(string name)
        {
            HasName = name;
        }
    }
}