Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, June 22, 2025

.NET Middleware

Inline
app.Use(async (context, next) =>
{
    var logger = app.Services.GetRequiredService<ILoggerFactory>()
        .CreateLogger("RequestLogger");

    logger.LogInformation("inline HTTP {Method} {Path}{Query}",
        context.Request.Method,
        context.Request.Path,
        context.Request.QueryString);
    
    await next();
});
Function
app.Use(MyFuncMiddleware);
async Task MyFuncMiddleware(HttpContext context, Func<Task> next)
{
    var logger = app.Services.GetRequiredService<ILoggerFactory>()
        .CreateLogger("RequestLogger");

    logger.LogInformation("func HTTP {Method} {Path}{Query}",
        context.Request.Method,
        context.Request.Path,
        context.Request.QueryString);
    
    await next();
}
HOC
app.Use(MyHocMiddleware());
Func<HttpContext, Func<Task>, Task> MyHocMiddleware()
{
     var logger = app.Services.GetRequiredService<ILoggerFactory>()
         .CreateLogger("RequestLogger");
     
    return async (context, next) =>
    {
        logger.LogInformation("hoc HTTP {Method} {Path}{Query}",
            context.Request.Method,
            context.Request.Path,
            context.Request.QueryString);
    
        await next();
    };
}
Fluent HOC
app.UseMyFluentHocMiddleware();

public static class MyFluentHocMiddlewareExtensions
{
    // Extension method for IApplicationBuilder to register our custom middleware
    public static IApplicationBuilder UseMyFluentHocMiddleware(this IApplicationBuilder builder)
    {
        var logger = builder.ApplicationServices.GetRequiredService<ILoggerFactory>()
          .CreateLogger("RequestLogger");
        
        return builder.Use(async (context, next) => 
        {
            logger.LogInformation("fluent HTTP {Method} {Path}{Query}",
                 context.Request.Method,
                 context.Request.Path,
                 context.Request.QueryString);

             await next();
        });
    }
}
Fluent Class
app.UseMyFluentClassMiddleware();

// Constructor: The RequestDelegate representing the next middleware MUST be the first parameter.
// Other dependencies (like ILogger) are injected by the DI container.

public class MyClassMiddleware(RequestDelegate next, ILogger<MyClassMiddleware> logger)
{
    // Invoke or InvokeAsync method: This is where the actual middleware logic resides.
    // It must return Task and take HttpContext as the first parameter.
    public async Task InvokeAsync(HttpContext context)
    {
        logger.LogInformation("myClass HTTP {Method} {Path}{Query}",
            context.Request.Method,
            context.Request.Path,
            context.Request.QueryString);
        
        await next(context);

        // logger.LogInformation($"[Class Middleware] Outgoing response status: {context.Response.StatusCode}");
    }
}

// Optional: An extension method to make registering the class middleware more fluent
public static class MyClassMiddlewareExtensions
{
    public static IApplicationBuilder UseMyFluentClassMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyClassMiddleware>();
    }
}

Sunday, June 3, 2018

Ternary all the things with C# 7




This code:
object NHibernate.UserTypes.IUserType.NullSafeGet(
    System.Data.Common.DbDataReader rs, string[] names,
    NHibernate.Engine.ISessionImplementor session, 
    object owner
)
{
    if (names.Length != 1)
        throw new System.InvalidOperationException("Only expecting one column...");

    object value = rs[names[0]];

    if (value is System.DateTime)
        return ((System.DateTime)value).ToUniversalTime();
    else
        return null;
}

Can be rewritten with C# 7's pattern matching:
object NHibernate.UserTypes.IUserType.NullSafeGet(
    System.Data.Common.DbDataReader rs, string[] names,
    NHibernate.Engine.ISessionImplementor session, 
    object owner
)
{
    if (names.Length != 1)
        throw new System.InvalidOperationException("Only expecting one column...");

    if (rs[names[0]] is System.DateTime value)
        return value.ToUniversalTime();
    else
        return null;
}

Nice, the variable declaration is inlined. It only means one thing, ternary!
object NHibernate.UserTypes.IUserType.NullSafeGet(
    System.Data.Common.DbDataReader rs, string[] names,
    NHibernate.Engine.ISessionImplementor session, 
    object owner
)
{
    if (names.Length != 1)
        throw new System.InvalidOperationException("Only expecting one column...");

    return rs[names[0]] is System.DateTime value ? value.ToUniversalTime() : (System.DateTime?) null;
}


And now that exceptions can be thrown inside of ternary statement? Ternary all the things!
object NHibernate.UserTypes.IUserType.NullSafeGet(
    System.Data.Common.DbDataReader rs, string[] names,
    NHibernate.Engine.ISessionImplementor session, 
    object owner
)
{            
    return 
        names.Length != 1 ? 
            throw new System.InvalidOperationException("Only expecting one column...")
        : rs[names[0]] is System.DateTime value ? 
            value.ToUniversalTime() 
        : 
            (System.DateTime?) null;
}


And who uses return statement in the 21st century? Use lambda expression syntax!
object NHibernate.UserTypes.IUserType.NullSafeGet(
    System.Data.Common.DbDataReader rs, string[] names,
    NHibernate.Engine.ISessionImplementor session, 
    object owner
)
=>
    names.Length != 1 ? 
        throw new System.InvalidOperationException("Only expecting one column...")
    : rs[names[0]] is System.DateTime value ? 
        value.ToUniversalTime() 
    : 
        (System.DateTime?) null;        

Tuesday, May 3, 2016

Inlined if-else assignment

This if-else statement:
AssignmentEnum assignment;
if (loggedUser == onboard.Employee)
    assignment = AssignmentEnum.Employee;
else if (loggedUser == onboard.CreatedBy)
    assignment = AssignmentEnum.Manager;
else
    assignment = 0;

Can be shortened to:
AssignmentEnum assignment = 
    loggedUser == onboard.Employee ?
        AssignmentEnum.Employee
    :loggedUser == onboard.CreatedBy ?
        AssignmentEnum.Manager 
    :
        0;


Here's how to allow the above code structure in ES6:


 
https://stackoverflow.com/questions/32289340/alternative-to-nested-ternary-operator-in-js/72654443#72654443
Happy Coding!

Wednesday, April 20, 2016

Secure Amazon Download using Query String Authentication

// https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html#RESTAuthenticationQueryStringAuth

using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace ConsoleApplication1
{
    class Program
    {
        static string CreateSignatureAsBase64(string secretKey, string stringToSign)
        {
            byte[] dataToSign = Encoding.UTF8.GetBytes(stringToSign);
            using (var crypt = new HMACSHA1(Encoding.UTF8.GetBytes(secretKey)))
            {
                return Convert.ToBase64String(crypt.ComputeHash(dataToSign));
            }
        }
        

        /// <summary>
        /// Returns date expiration in seconds since 1970
        /// </summary>
        /// <param name="minutesExpiration"></param>
        /// <returns></returns>
        public static long GetExpiration(int minutesExpiration)
        {
            DateTime date   = DateTime.UtcNow;
            DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            TimeSpan diff   = date.ToUniversalTime() - origin + new TimeSpan(0, minutesExpiration, 0);
            return (long) Math.Floor(diff.TotalSeconds);
        }

        static void Main(string[] args)
        {
            long expiration = GetExpiration(minutesExpiration: 1);
            
            string fileToDownload = "ice-bucket/someFilenameHere.pdf";
            
            var stringToSign = 
                "GET" + "\n" +
                "\n" +
                "\n" +
                expiration + "\n" +
                "/" + fileToDownload;

            string secretAccessKey       = "blah/meh";
            string signature64           = CreateSignatureAsBase64(secretAccessKey, stringToSign);            
            string urlEncodedSignature64 = HttpUtility.UrlEncode(signature64);

            string accessKey = "developerId";
			
            string url = 
                string.Format(@"https://s3-us-west-2.amazonaws.com/{0}?AWSAccessKeyId={1}&Expires={2}&Signature={3}", 
                    fileToDownload, 
                    accessKey,
                    expiration, 
                    urlEncodedSignature64);

            Process.Start(url);

        }
    }
}

Wednesday, March 30, 2016

Highfalutin code #4. With great power, comes great responsibility.

No matter how powerful our programming language is..

foreach (var item in 
    documentFields.SelectMany(
        documentField => documentField.Options, 
        (documentField, option) => new { documentField, option }
    )
)
{
   item.option.DocumentField = item.documentField;
}


..we still have a great responsibility to make our code readable and maintainable:
foreach (var documentField in documentFields)
    foreach (var option in documentField.Options)
    {
        option.DocumentField = documentField;
    }


SelectMany's intent is to flatten *ALL* the option collection from all fields, and then assign each option item in collection to their parent field.

Though the objective of the first code is to make the program's intent obvious, its verbosity blurs the intent of the code.

In fact, if we want to make it appear we are flattening the collection, we can also do it as follows:

foreach (var documentField in documentFields) foreach (var option in documentField.Options)
{
    option.DocumentField = documentField;
}


If we look at the two for loops as projecting a table with two columns, the projected options will now look like flattened rows.

We just have to tilt our perspective sometimes :)


Disclaimer: I won't use the last code.

Monday, October 20, 2014

Registering runtime types on DryIoc

DryIoc is missing an API for registering a runtime type

Hence we can't automate this WCF registration..

_container.RegisterDelegate<TheServiceContracts.IProductService>(x => 
    (TheServiceContracts.IProductService) ServiceModelHelper.CreateService(
        typeof(TheServiceContracts.IProductService),  
        System.ServiceModel.BasicHttpBinding(), 
        new System.ServiceModel.EndpointAddress("http://localhost:1337/ProductService.svc")
    )
, Reuse.InResolutionScope);
    
_container.RegisterDelegate<TheServiceContracts.IMemberService>(x => 
    (TheServiceContracts.IMemberService) ServiceModelHelper.CreateService(
        typeof(TheServiceContracts.IMemberService), 
        new System.ServiceModel.BasicHttpBinding(), 
        new System.ServiceModel.EndpointAddress("http://localhost:1337/MemberService.svc")
    )
, Reuse.InResolutionScope);

_container.RegisterDelegate<TheServiceContracts.IOrderService>(x => 
    (TheServiceContracts.IOrderService) ServiceModelHelper.CreateService(
        typeof(TheServiceContracts.IOrderService), 
        new System.ServiceModel.BasicHttpBinding(), 
        new System.ServiceModel.EndpointAddress("http://localhost:1337/OrderService.svc")
    )
, Reuse.InResolutionScope);


..into this:

_container.Register<System.ServiceModel.BasicHttpBinding>(DryIoc.Reuse.Singleton, x => x.GetConstructor(new Type[] { }));

foreach (var contractType in typeof(TheServiceContracts.IMemberService).Assembly.GetTypes())
{
    _container.RegisterDelegate(contractType,
        r =>
        {
            var binding = r.Resolve<System.ServiceModel.BasicHttpBinding>();

            var svcAddress = "http://localhost:1337/" + contractType.Name.Substring(1) + ".svc";
            var endpointAddress = new System.ServiceModel.EndpointAddress(svcAddress);


            return ServiceModelHelper.CreateService(contractType, new System.ServiceModel.BasicHttpBinding(), endpointAddress);
        }, Reuse.InResolutionScope);

}   


And this available API in DryIoc can't be used, parameters in generics and casting must be determined at compile-time. Hence we can't pass the runtime type contractType variable as a parameter to generics and casting
_container.Register<System.ServiceModel.BasicHttpBinding>(DryIoc.Reuse.Singleton, x => x.GetConstructor(new Type[] { }));

foreach(var contractType in typeof(TheServiceContracts.IProductService).Assembly.GetTypes())
{
    var binding = new System.ServiceModel.BasicHttpBinding();
    var endpointAddress = new System.ServiceModel.EndpointAddress("http://localhost:1337/" + contractType.SubString(1) + ".svc"); // removes the first letter I
    _container.RegisterDelegate<contractType>(r => 
        {
            var binding = r.Resolve<System.ServiceModel.BasicHttpBinding>();

            var svcAddress = "http://localhost:1337/" + contractType.Name.Substring(1) + ".svc";
            var address = new System.ServiceModel.EndpointAddress(svcAddress);
            
            return (contractType) ServiceModelHelper.CreateService(contractType, binding, endpointAddress)
        }, Reuse.InResolutionScope);
}


To fix that, we need to simulate RegisterDelegate<T> during runtime


First step, we should design how the additional API should look like. It should feel as close as possible to the convention of the original API:
_container.RegisterDelegate<TheServiceContracts.IOrderService>(x => 
    (TheServiceContracts.IOrderService) ServiceModelHelper.CreateService(
        typeof(TheServiceContracts.IOrderService), 
        new System.ServiceModel.BasicHttpBinding(), 
        new System.ServiceModel.EndpointAddress("http://localhost:1337/OrderService.svc")
    )
, Reuse.InResolutionScope);


The additional API should be like this:
_container.RegisterDelegate(contractType, x => 
    ServiceModelHelper.CreateService(
        contractType, 
        new System.ServiceModel.BasicHttpBinding(), 
        new System.ServiceModel.EndpointAddress("http://localhost:1337/OrderService.svc")
    )
, Reuse.InResolutionScope);


Then our API should be an extension method of the DryIoc.IResolver:
public static class ResolverExtensionHelper
{
    public static void RegisterDelegate(this DryIoc.IResolver resolver,
         Type contractType,
         Func<DryIoc.IResolver, object> objectConstructor,
         DryIoc.IReuse reuse = null, DryIoc.FactorySetup setup = null, string named = null)
    {
        ResolverBuilder.Build(container, contractType, objectConstructor, reuse, setup, named);
    }
}


You maybe wondering why we need to use two classes, ResolverBuilder and ResolverExtensionHelper, why not just do everything in ResolverExtensionHelper?

We need to have the following code, we need to cast the objects generated(e.g., WCF proxy objects) in a delegate back to its dependency-injected type(e.g., is an interface) during runtime, which is not possible with the original RegisterDelegate<contractTypeHere>. So we need to have a mechanism that can cast runtime types:
TService ConstructObjectThenCast<TService>(IResolver resolver)
{
    var svc = (TService) this._objectConstructorDelegate(resolver);
    return svc;
}


And we cannot add lambda parameter (any parameter for that matter) on that method:
TService ConstructObjectThenCast<TService>(IResolver resolver, 
    Func<IResolver, object> objectConstructorDelegate)
{
    var svc = (TService) objectConstructorDelegate(resolver);
    return svc;
}


Adding that parameter would cause runtime error when doing a reflection call on original RegisterDelegate method. ConstructObjectThenCast method is the substitute method for the original RegisterDelegate's lambda parameter
Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.


Looking at the original RegisterDelegate method signature shows why:
public static void RegisterDelegate<TService>(
     this IRegistrator registrator, Func<IResolver, TService> lambda, 
     IReuse reuse = null, FactorySetup setup = null, string named = null);

The lambda delegate we want to hook on has one parameter only, IResolver only. Hence if Func<IResolver, object> objectConstructorDelegate is added to parameters of ConstructObjectThenCast, it results to the error above


However, since we cannot add another parameter on the substitute method(ConstructObjectThenCast) to the lambda, the only way to pass the user-defined lambda to the original RegisterDelegate is to create a class instance, which is not possible on static class, hence the need for two classes. So when the original RegisterDelegate method calls our substitute method for original RegisterDelegate's lambda, we can still call the user-defined lambda in turn. The user-defined lambda is stored in a non-static class, it's a field on that class: Func<DryIoc.IResolver,object> _objectConstructorDelegate;


ConstructObjectThenCast is the method that will cast an object to its dependency-injected type(e.g., in an interface), that's the method we will substitute to RegisterDelegate's lambda parameter. In order for that substitute method to be able to call our user-defined lambda, we will call the user-defined lamba from the class instance. this._objectConstructorDelegate is where the user-defined lambda is stored
TService ConstructObjectThenCast<TService>(IResolver resolver)
{
    var svc = (TService) this._objectConstructorDelegate(resolver);
    return svc;
}




Here's the complete code of the additional API. This also shows how to use DryIoc on ASP.NET MVC and WCF:
using System;
using System.Linq;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;

using DryIoc;
using AspNetMvcUseWcf.Controllers;

namespace AspNetMvcUseWcf
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            
            ControllerBuilder.Current.SetControllerFactory(new DryIocDependencyResolver());   
        }
    }

    class DryIocDependencyResolver : System.Web.Mvc.DefaultControllerFactory
    {
        DryIoc.Container _container;

        public DryIocDependencyResolver()
        {
            _container = new DryIoc.Container();
            RegisterTheIocs();
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            System.Web.Mvc.IController ic = controllerType == null
                ? null
                : (System.Web.Mvc.IController)_container.Resolve(controllerType);

            // _container.ResolvePropertiesAndFields(ic);  // uncomment this if you want to use DI on controller's properties

            return ic;
        }

        void RegisterTheIocs()
        {
            RegisterMvcControllers();
            RegisterWcfServices();
        }

        void RegisterWcfServices()
        {
            _container.Register<System.ServiceModel.BasicHttpBinding>(DryIoc.Reuse.Singleton, x => x.GetConstructor(new Type[] { }));


            foreach (var contractType in typeof(TheServiceContracts.IMemberService).Assembly.GetTypes())
            {                
                _container.RegisterDelegate(contractType,
                    r =>
                    {
                        var binding = r.Resolve<System.ServiceModel.BasicHttpBinding>();

                        var svcAddress = "http://localhost:1337/" + contractType.Name.Substring(1) + ".svc";
                        var endpointAddress = new System.ServiceModel.EndpointAddress(svcAddress);


                        return ServiceModelHelper.CreateService(contractType, binding, endpointAddress);
                    }, Reuse.InResolutionScope);

            }
        }

        void RegisterMvcControllers()
        {
            System.Reflection.Assembly assembly = typeof(HomeController).Assembly;

            foreach (var controller in assembly.GetTypes().Where(t => typeof(Controller).IsAssignableFrom(t)))
            {
                _container.Register(controller, DryIoc.Reuse.InResolutionScope);
            }
        }


    } // class DryIocDependencyResolver






    public static class ResolverExtensionHelper
    {
        public static void RegisterDelegate(this DryIoc.IResolver container,
             Type contractType, Func<DryIoc.IResolver, object> objectConstructorDelegate,
             DryIoc.IReuse reuse = null, DryIoc.FactorySetup setup = null, string named = null)
        {
            ResolverBuilder.Build(container, contractType, objectConstructorDelegate, reuse, setup, named);
        }
    }

    public class ResolverBuilder
    {
        
        Func<DryIoc.IResolver,object> _objectConstructorDelegate;


        public static void Build(DryIoc.IResolver container, Type contractType, Func<IResolver, object> objectConstructor, IReuse reuse, FactorySetup setup, string named)
        {
            new ResolverBuilder(container, contractType, objectConstructor, reuse, setup, named);
        }

        ResolverBuilder(
            DryIoc.IResolver resolver, Type contractType, Func<DryIoc.IResolver, object> objectConstructorDelegate,
            DryIoc.IReuse reuse = null, DryIoc.FactorySetup setup = null, string named = null
            )
        {
            _objectConstructorDelegate = objectConstructorDelegate;

            Delegate lambda;
            {
                System.Reflection.MethodInfo constructObjectThenCastMethodInfo = Create_ConstructObjectThenCast_MethodInfo_For_ContractType(contractType);
                lambda = Create_ConstructObjectThenCast_Lambda_For_ContractType(this, constructObjectThenCastMethodInfo, contractType);
            }


            // Invoke the original RegisterDelegate<TService>            
            {
                // public static void RegisterDelegate<TService>(this DryIoc.IRegistrator registrator, Func<DryIoc.IResolver, TService> lambda, 
                //                                                     DryIoc.IReuse reuse = null, DryIoc.FactorySetup setup = null, string named = null);

                // obj is null, means RegisterDelegate is a static method
                // resolver comes from _container
                // contractType is the TService in the original _container.RegisterDelegate<TService>
                System.Reflection.MethodInfo registerDelegateMethodInfo = typeof(DryIoc.Registrator).GetMethod("RegisterDelegate").MakeGenericMethod(contractType);
                registerDelegateMethodInfo.Invoke(/*obj*/ null, new object[] { resolver, lambda, reuse, setup, named });
            }
        }

        static System.Reflection.MethodInfo Create_ConstructObjectThenCast_MethodInfo_For_ContractType(Type contractType)
        {

            System.Reflection.MethodInfo constructObjectThenCastMethodInfo =
                // typeof(IResolver) is the resolver parameter of: TService ConstructObjectThenCast<TService>(IResolver resolver)
               typeof(ResolverBuilder).GetMethod(
                   name: "ConstructObjectThenCast",
                   types: new[] { typeof(IResolver) },
                   bindingAttr: System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance,
                   binder: null,
                   modifiers: null
                   )
                // contractType is the TService of ConstructObjectThenCast<TService>
               .MakeGenericMethod(contractType);
            return constructObjectThenCastMethodInfo;
        }


        // Create a lambda out of this class method: TService ConstructObjectThenCast<TService>(IResolver resolver)
        static Delegate Create_ConstructObjectThenCast_Lambda_For_ContractType(ResolverBuilder resolverBuilder,  System.Reflection.MethodInfo constructObjectThenCastMethodInfo, Type contractType)
        {
            // Create a Func<IResolver,TService> delegate type
            // This will be used as the lambda parameter on the original RegisterDelegate static method.                                          
            Type lambdaDelegateType = typeof(Func<,>).MakeGenericType(typeof(DryIoc.IResolver), contractType);
            // The above corresponds to this example: Func<IResolver, TheServiceContracts.IProductService>


            // Cannot use Activator.CreateInstance on delegate type as delegates don't have constructor
            // ConstructObjectThenCast method has a signature same as lambdaDelegateType 
            // Create a lambda out of ConstructObjectThenCast method info
            Delegate lambda = Delegate.CreateDelegate(lambdaDelegateType, resolverBuilder, constructObjectThenCastMethodInfo);

            return lambda;
        }

     
        TService ConstructObjectThenCast<TService>(IResolver resolver)
        {
            var svc = (TService) this._objectConstructorDelegate(resolver);
            return svc;
        }


    }// class ResolverBuilder


    public static class ServiceModelHelper
    {
        public static object CreateService(
            Type contractType,
            System.ServiceModel.BasicHttpBinding basicHttpBinding,
            System.ServiceModel.EndpointAddress endpointAddress
            )
        {
            var binding = new System.ServiceModel.BasicHttpBinding();
            //Get the address of the service from configuration or some other mechanism - Not shown here

            //dynamic factory generation
            object factory =
                Activator.CreateInstance(typeof(System.ServiceModel.ChannelFactory<>)
                .MakeGenericType(contractType), binding, endpointAddress);

            System.Reflection.MethodInfo createFactory = factory.GetType().GetMethod("CreateChannel", new Type[] { });
            //now dynamic proxy generation using reflection
            return createFactory.Invoke(factory, null);
        }
    }
    
}//namespace



Happy Coding!

Sunday, October 19, 2014

C# var abuse

What happened to programming to an interface?



You have this DLL that contains this interface and implementation:
namespace UnitTestFriendlyDal
{
    public interface IDomainAccess : IDisposable
    {
        object Save(object transientObject);
        IQueryable<T> Query<T>();
        T Get<T>(object id);
        T Load<T>(object id);
        void Evict<T>(object id);
    }

    public class DomainAccess : IDomainAccess
    {

        NHibernate.ISessionFactory _sessionFactory;
        NHibernate.ISession _session;
        NHibernate.ITransaction _transaction;


        public DomainAccess(NHibernate.ISessionFactory sessionFactory)
        {
            _sessionFactory = sessionFactory;
            _session = _sessionFactory.OpenSession();
            _transaction = _session.BeginTransaction();
        }

        // IDomainAccess implementation...
        


        public Save(object transientObject)
        {
            return _session.Save(transientObject);
        }

        
        IQueryable<T> Query<T>()
        {
            return _session.Query<T>();
        }


        public T Get<T>(object id)
        {
            return _session.Get<T>(id);
        }

        public T Load<T>(object id)
        {
            return _session.Load<T>(id);
        }



        public void Evict<T>(object id)
        {
            _sessionFactory.Evict(typeof(T), id);
        }
        

        
        // Because transaction is a cross-cutting concern. It should be automated
        void IDisposable.Dispose()
        {
             // http://www.hibernatingrhinos.com/products/nhprof/learn/alert/donotuseimplicittransactions
                    
            _transaction.Commit();
            _transaction.Dispose();
            _session.Dispose();
        }


        //... IDomainAccess implementation
    }
}


Developers will use DomainAccess directly instead:
using (var da = new DomainAccess(_sessionFactory))
{    
    var c = Customer.Get(domainAccess: da, id: 1);
}


So what happen now to programming to an interface principle? Prior to C# version 3, you can still convince your colleagues to use variable declaration that adheres to programming to an interface principle: IDomainAccess da = new DomainAccess(), instead of: DomainAccess da = new DomainAccess(). interface variable declaration is just one letter away from its concrete class variable declaration :-)


Now, some developers will steadfastly refuse to type the type anymore. Code's obviousness to other developers is not given an attention, worse yet most won't care anymore if the code is not adhering to programming to an interface principle anymore


Another problem with var, when you generate method stub using the da variable from a var declaration, Visual Studio will generate the method stub based on da's concrete class, not based on its interface:
public static Get(DomainAccess domainAccess, int id)
{
}

When it should ideally be interface-based instead:
public static Customer Get(IDomainAccess domainAccess, int id) 
{
}


What you wanted your fellow colleagues to practice:
using (IDomainAccess da = new DomainAccess(_sessionFactory))
{    
    var c = Customer.Get(domainAccess: da, id: 1);    
}


There's a slim chance that you can convince your colleagues who are fans of var to declare variables based on their interface

Surely, most C# developers didn't heed this Microsoft warning:
However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required


Another good argument against var abuse. Bradley Smith wrote:
var encourages Hungarian Notation

If the ommission of type names from variable declarations forces us to more carefully name our variables, it follows that variable names are more likely to describe not only their purpose, but also their type:

var dtIndividuals = GetContacts(ContactTypes.Individuals);

This is precisely the definition of Hungarian Notation, which is now heavily frowned upon as a practice, especially in type-safe languages like C#.


dtIndividuals is DataTable individuals. Imagine when there was no var, variable declaration like DataTable dtIndividuals are frowned upon; but now there's var, it's ok to use Hungarian notation again?


var is the most abused language feature


How I wish that compilers could at least advise the developer to use the concrete class' interface instead when declaring variables


To solve the problem above without incurring friction with var everything camp, you can make your concrete classes implement interfaces explicitly, thereby hiding the concrete class' implemented interface methods.
public class DomainAccess : IDomainAccess
{
.
.
. 
    // Implement interfaces explicitly. This will make Save not available on DomainAccess instance
    IDomainAccess.Save(object transientObject)
    {
        return _session.Save(transientObject);
    }
.
.
.
}


So when using the DomainAccess directly (via var), accessing its method will result to compile error..
using (var da = new DomainAccess(_sessionFactory))
{        
    da.Save(new Company{ ... }); // this will result to compile error, Save is inaccessible from concrete class DomainAccess
}


..so that would compel the developer to program to an interface instead::
using (IDomainAccess da = new DomainAccess(_sessionFactory))
{       
    da.Save(new Company{ ... }); // this will compile, Save is accessible from the IDomainAccess interface
}


Problem solved, that's programming to an interface. Using EIMI as a solution to this problem still has wrinkles in it, programming to an interface can be enforced but it's still easy to accidentally use the DomainAccess concrete class directly via the var keyword, the developer shall then have to change the variable declaration to use the interface instead, wasting time


There's a better approach, we can make the DomainAccess non-public, then just give the user an instance of IDomainAccess implementation from a factory
// remove the public keyword
class DomainAccess : IDomainAccess
{
    // implement interface methods
}


When used outside of DomainAccess project, this will not compile:
var da = new DomainAccess(_sessionFactory); // DomainAccess is not visible to other projects



So to give the user an IDomainAccess object, the dev shall use this pattern instead:
public class CompaniesController : Controller
{
    IDomainAccessFactory _daf;
    
    public CompaniesController(IDomainAccessFactory daf)
    {
        _daf = daf;
    }
    
    public JsonResult CompanySave(CompanyDto dto)
    {
        int savedId = 0;
        // OpenDomainAccess returns IDomainAccess instead of returning DomainAccess
        using (var da = _daf.OpenDomainAccess())
        {
            savedId = da.Save(new Company{...});            
        }                
        return Json(new { savedId = savedId });
    }        
}


DomainAccess cannot be instantiated directly anymore, it shall be built from a factory instead and return it through interface. Here's an implementation:
namespace UnityTestFriendlyDal
{
    public interface IDomainAccessFactory
    {
        IDomainAccess OpenDomainAccess();
    }
    
    public class DomainAccessFactory : IDomainAccessFactory
    {
        NHibernate.ISessionFactory _sessionFactory;

        public DomainAccessFactory(NHibernate.ISessionFactory sessionFactory)
        {
            _sessionFactory = sessionFactory;
        }
        
        // return through DomainAccess concrete class through IDomainAccess interface
        public IDomainAccess OpenDomainAccess()
        {
            return new DomainAccess(_sessionFactory);
        }
    }

    public interface IDomainAccess : IDisposable
    {
        object Save(object transientObject);
        IQueryable<T> Query<T>();
        T Get<T>(object id);
        T Load<T>(object id);
        void Evict<T>(object id);
    }
    
    // Don't make this public
    class DomainAccess : IDomainAccess
    {
        // Though you can use public/internal on method implementations (as long as you don't make the class DomainAcess public), 
        // it's advisable to use explicit interface method implementation instead

        // interface implementations here
    }
}


When you generate a method stub from a variable declaration using var that receives an interface, the generated method stub will naturally generates a method with a parameter of interface. You can reap the benefit of using interfaces when you can properly enforce the use of interfaces everywhere



Good read on "To var or not to var" :

http://shahinalborz.se/2011/01/to-var-or-not-to-var-c-implicit-variable-declaration/

http://www.brad-smith.info/blog/archives/336

http://weblogs.asp.net/stevewellens/can-the-c-var-keyword-be-misused

Good read on Programming To An Interface:

http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface/384067#384067

http://www.codeproject.com/Articles/392516/Why-I-use-explicit-interface-implementation-as-a-d




Happy Coding!

Sunday, October 5, 2014

Just because you can, doesn't mean you should

Or to put it another way, just because it compiles doesn't mean it's ok

Don't do this:
public DataStore(NHibernate.ISessionFactory sessionFactory)
{
    _transaction = (_session = (_sessionFactory = sessionFactory).OpenSession()).BeginTransaction();
}


Do this:
public DataStore(NHibernate.ISessionFactory sessionFactory)
{
    _sessionFactory = sessionFactory;
    _session = _sessionFactory.OpenSession();
    _transaction = _session.BeginTransaction();
}

Saturday, September 13, 2014

Interface Magic (at least to me)

Didn't know that interface could intercept the method of the base class even that base class is not implementing the interface

using System;
                    
public class Program
{
    public static void Main()
    {
        IRobot r = new Robot();

        r.SaySomething();
    }
}


public class Machine
{
    public void SaySomething()
    {
        Console.WriteLine("Hello");
    }
}

public interface IRobot
{
    void SaySomething();
}


public class Robot : Machine, IRobot
{
// and we don't have to implement IRobot here    
}




Live Code: https://dotnetfiddle.net/cqdt8z


Output:
Hello

I still have to find a use for that code found somewhere



Happy Coding!

Tuesday, June 17, 2014

How to avoid the expensive ToList on generic list? Generics' OOPness redux

Have you questioned C# generics’ OOPness? Why is C# is not allowing us to return List<Autobot> to List<ITransformer> despite Autobot and Decepticon is an ITransformer?

This won't compile even Autobot implements ITransformer:



Can fix it with ToList, but it's an expensive operation, as it creates a copy:
public static List<ITransformer> GetTransformers(TransformerType t)
{
    if (t == TransformerType.Autobot)
        return GetAutobots().ToList<ITransformer>();
    else if (t == TransformerType.Decepticon)
        return GetDecepticons().ToList<ITransformer>();
         
    return null;
}   


To cut to the chase, return the List<ConcreteClass> to IEnumerable<Interface>:
public static IEnumerable<ITransformer> GetTransformersOop(TransformerType t)
{
    if (t == TransformerType.Autobot)
        return GetAutobots();
    else if (t == TransformerType.Decepticon)
        return GetDecepticons();
         
    return null;
}

Live code: https://dotnetfiddle.net/K3IcR5

For further information why List<ConcreteClass> is not compatible to List<Interface> even the concrete class implements the interface, read about covariance

Tuesday, April 29, 2014

Imagine there's no country

"Imagine there's no country..." – John Lennon

But alas, humans are subjected to suffer, especially the kind of humans called programmers and what have you


Having said that, sorting across cultures is one of things we must take into account when making our app locale-aware.


As of the time of this writing, it's not possible to use JavaScript for localization. We have to use server-side languages

using System;
using System.Linq;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        var list = new[] {
            "honesty", "courage", "integrity", "character"
        };
         
                 
        list.OrderBy(x => x).Dump();    
        list.OrderBy(x => x, StringComparer.Create(new CultureInfo("cs-CZ"), true)).Dump();
    }
}



English sorting:
1. character
2. courage
3. honesty
4. integrity

Czech sorting:
1. courage
2. honesty
3. character
4. integrity

"...I wonder if you can" – John Lennon

Sunday, March 30, 2014

High-falutin Code #1

"By the time you've got multiple joins, query expressions almost always win" -- Jon Skeet


But.. there are coders who simply love to write more code, perhaps they feel that the more convoluted-looking their code are the smarter they are. Hence most of them even when the code can sometimes use and be made more readable with Linq, will still use lambda instead. They feel they have elite skills just by using lambda.


var itemsOwner = 
    items
        .Join (people, i => i.OwnerId, p => p.PersonId, (i, p) => new { Item = i, Person = p })
        .Join (countries, ip => ip.Person.CountryId, c => c.CountryId, (ip, c) => new { ItemPerson = ip, Country = c })
        .Select (x => new { x.ItemPerson.Item.ItemName,  x.ItemPerson.Person.PersonName, x.Country.CountryName });



Those coders need to be in the movie Crank, let's see how they can write multiple joins in no time, let's see if they can still breath after two joins.


Then the continent name needed be shown on the output:

var itemsOwner = 
    items
        .Join (people, i => i.OwnerId, p => p.PersonId, (i, p) => new { Item = i, Person = p })
        .Join (countries, ip => ip.Person.CountryId, c => c.CountryId, (ip, c) => new { ItemPerson = ip, Country = c })
        .Join (continents, ipc => ipc.Country.CountryId, z => z.ContinentId, (ipc, z) => new { ItemPersonCountry = ipc, Continent = z })
        .Select (x => new { 
            x.ItemPersonCountry.ItemPerson.Item.ItemName, 
            x.ItemPersonCountry.ItemPerson.Person.PersonName, 
            x.ItemPersonCountry.Country.CountryName,
            x.Continent.ContinentName
        });


That's the problem with lambda joins, the aliases of multiple lambda joins cascades to the aliases of the subsequent joins. The aliases become unwieldy and deeply nested.



And there's too many variations of that lambda join, some would prefer the code below, deciding early what properties to project during lambda join. Ironically, though Linq and lambda promotes the use of deferred execution, but here we are, we have a coder deciding upfront that it's better to project user-shown properties right there in the lambda joins.


var itemsOwner = 
    items
        .Join (people, i => i.OwnerId, p => p.PersonId, (i, p) => new { i.ItemName, p.PersonName, p.CountryId })
        .Join (countries, ipc => ipc.CountryId, c => c.CountryId, (ipc, c) => new { ipc.ItemName, ipc.PersonName, c.CountryName });




And then you need to include the brand, oh the DRY headache!

var itemsOwner = 
    items                   
        .Join (people, i => i.OwnerId, p => p.PersonId, (i, p) => new { i.ItemName, p.PersonName, p.CountryId, i.BrandId })
        .Join (brands, ipcb => ipcb.BrandId, b => b.BrandId, (ipcb, b) => new { ipcb.ItemName, ipcb.PersonName, ipcb.CountryId, b.BrandName })
        .Join (countries, ipcb => ipcb.CountryId, c => c.CountryId, (ipcb, c) => new { ipcb.ItemName, ipcb.PersonName, c.CountryName, ipcb.BrandName });


See the problem with lambda joins? Aside from too many variations (deciding upfront to project the user-shown properties during joinings vs deferring that decision on final join or select), there's also the hard problem of giving a proper alias for the subsequent joins.



Then there's a change in the requirement to show the brand name after the item name, you feel the aliases should reflect that fact, so you got to change the alias too:

var itemsOwner = 
    items                   
        .Join (people, i => i.OwnerId, p => p.PersonId, (i, p) => new { i.ItemName, i.BrandId, p.PersonName, p.CountryId })
        .Join (brands, ibpc => ibpc.BrandId, b => b.BrandId, (ibpc, b) => new { ibpc.ItemName, b.BrandName, ibpc.PersonName, ibpc.CountryId })
        .Join (countries, ibpc => ibpc.CountryId, c => c.CountryId, (ibpc, c) => new { ibpc.ItemName, ipcb.BrandName, ibpc.PersonName, c.CountryName });




The highfalutin coder experiences the problems with unwieldy alias names cascading to subsequent joins, nested aliases, and giving good names for aliases, he decided to wise up; he decided he can avoid all the headaches above just by giving a generic (e.g., src) name for all aliases:


var itemsOwner = 
    items                   
        .Join (people, src => src.OwnerId, p => p.PersonId, (src, p) => new { src.ItemName, src.BrandId, p.PersonName, p.CountryId })
        .Join (brands, src => src.BrandId, b => b.BrandId, (src, b) => new { src.ItemName, b.BrandName, src.PersonName, src.CountryId })
        .Join (countries, src => src.CountryId, c => c.CountryId, (src, c) => new { src.ItemName, src.BrandName, src.PersonName, c.CountryName });


By the time all the original developers in the project are replaced, new developers will be left scratching their heads why the old developers didn't bother to give self-describing names for aliases.



Let's say you want to switch the join order (MySQL is notorious on requiring certain order on joins to gain performance) of people and brands..
var itemsOwner = 
    items                   
        .Join (people, src => src.OwnerId, p => p.PersonId, (src, p) => new { src.ItemName, src.BrandId, p.PersonName, p.CountryId })
        .Join (brands, src => src.BrandId, b => b.BrandId, (src, b) => new { src.ItemName, b.BrandName, src.PersonName, src.CountryId })
        .Join (countries, src => src.CountryId, c => c.CountryId, (src, c) => new { src.ItemName, src.BrandName, src.PersonName, c.CountryName });


..you cannot nilly-willy re-order the joins without incurring changes on code, you can not just cut-and-paste the code, this doesn't compile:
var itemsOwner = 
    items                   
        .Join (brands, src => src.BrandId, b => b.BrandId, (src, b) => new { src.ItemName, b.BrandName, src.OwnerId })
        .Join (people, src => src.OwnerId, p => p.PersonId, (src, p) => new { src.ItemName, src.BrandName, p.PersonName, p.CountryId })
        .Join (countries, src => src.CountryId, c => c.CountryId, (src, c) => new { src.ItemName, src.BrandName, src.PersonName, c.CountryName });




Now contrast the humble developer's Linq join code to codes above. The code is very readable:

var itemsOwner = 
    from i in items
    join p in people on i.OwnerId equals p.PersonId
    join b in brands on i.BrandId equals b.BrandId
    join c in countries on p.CountryId equals c.CountryId    
    select new { i.ItemName, b.BrandName, p.PersonName, c.CountryName };


Then switch the join order of people and brands, the changes in Linq-using code is not invasive compared to lambda-using code, you can just cut-and-paste the code, this compiles:

var itemsOwner = 
    from i in items
    join b in brands on i.BrandId equals b.BrandId
    join p in people on i.OwnerId equals p.PersonId    
    join c in countries on p.CountryId equals c.CountryId    
    select new { i.ItemName, b.BrandName, p.PersonName, c.CountryName };



If the coder doesn't see problems with lambda joins and still prefer to write joins using it instead of Linq, he need to star in the movie Crank. I would hazard a guess he would die by the time he is in the third or fourth join; or worse yet was required to insert another join between the existing joins, good luck breathing with that task!


Another lambda join variation, not compounding objects in one alias, giving each joined object their own alias. Drawback is, subsequent joins must repeat the objects from the previous joins, a WET code:
var itemsOwner = 
    items
        .Join (people, src => src.OwnerId, p => p.PersonId, (src, p) => new { Item = src, Person = p })
        .Join (brands, src => src.Item.BrandId, b => b.BrandId, (src, b) => new { src.Item, src.Person, Brand = b })
        .Join (countries, src => src.Person.CountryId, c => c.CountryId, (src, c) => new { src.Item, src.Person, src.Brand, Country = c })
        .Select (x => new { x.Item.ItemName, x.Person.PersonName, x.Brand.BrandName, x.Country.CountryName });


The coder forgot he is using MySQL, it's optimal to join on brands first, then people. As an exercise, try switching the join order of people and brands of the code above, good luck breathing! http://dotnetfiddle.net/3bvQDy



Another variation, this requires investing another class to assist you in your adventure on joining using lambda, this also requires you to violate DRY principle:
var itemsOwner = 
    items
    .Join (people, src => src.OwnerId, p => p.PersonId, (src, p) => new JoinHelper { Item = src, Person = p  } )
    .Join (brands, src => src.Item.BrandId, b => b.BrandId, (src, b) => new JoinHelper { Item = src.Item, Person = src.Person, Brand = b })
    .Join (countries, src => src.Person.CountryId, c => c.CountryId, (src, c) => new JoinHelper { Item = src.Item, Person = src.Person, Brand = src.Brand, Country = c } )
    .Select (x => new { x.Item.ItemName, x.Person.PersonName, x.Brand.BrandName, x.Country.CountryName });



Do you still want to showboat your lambda join skills?



Time to repent your perceived superiority, use Linq to avoid highfalutin lambda code.



The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague -- Edsger Dijkstra


There are cases that lambda is an unnecessary trick, just showboating.

Friday, January 3, 2014

Want to try out some piece of .NET code yet you don't want to accumulate clutters of solutions in your recent projects in Visual Studio?

I saw some answer on stackoverflow I need to try out:

static void Main() {
 
    string s1 = Regex.Replace("abcdefghik", "e",
        match => "*I'm a callback*");
 
    string s2 = Regex.Replace("abcdefghik", "c", Callback);
}
static string Callback(Match match) {
    return "*and so am i*";
}

But I don't want to create a new solution just for that smallish code. .NET fiddle to the rescue!
Example: http://dotnetfiddle.net/FSqLmM

And what's cooler with .NET Fiddle, is that it has auto-complete, unlike ideone

If only I can try snippets of NHibernate, Entity Framework, ASP.NET MVC or SignalR on .NET Fiddle, my folders will be a lot more tidy :D



Happy Coding! ツ

Tuesday, April 2, 2013

Null References, A Billion Dollar Mistake

And ADO.NET promotes that billion dollar mistake ;-)



Given this code:

DateTime? periodBeginDate = null;
DateTime? periodEndDate = null;
 
var person = m_db.ExecuteScalar(CommandType.Text, "select * from person where CreatedDate between @periodBeginDate and @periodEndDate",
            new SqlParameter("@periodBeginDate", periodBeginDate),
            new SqlParameter("@periodEndDate", periodEndDate)
            );


That would result to this SQL:

exec sp_executesql N'
select * from person where CreatedDate between @periodBeginDate and @periodEndDate
',N'@periodBeginDate nvarchar(4000),@periodEndDate nvarchar(4000)',@periodBeginDate=default,@periodEndDate=default


And that gives this error:

Msg 8178, Level 16, State 1, Line 0
The parameterized query '(@periodBeginDate nvarchar(4000),@periodEndDate nvarchar(4000))
' expects the parameter '@periodBeginDate', which was not supplied.


Passing default is as good as not passing a parameter, to force passing NULL values as parameter, use DBNull.Value:

DateTime? periodBeginDate = null;
DateTime? periodEndDate = null;
 
var person = m_db.ExecuteScalar(CommandType.Text, "select * from person where CreateDate between @periodBeginDate and @periodEndDate",
            new SqlParameter("@periodBeginDate", periodBeginDate ?? (object) DBNull.Value),
            new SqlParameter("@periodEndDate", periodEndDate ?? (object) DBNull.Value)
            ); 


That would result to this SQL:

exec sp_executesql N'
select * from person where CreatedDate between @periodBeginDate and @periodEndDate
',N'@periodBeginDate nvarchar(4000),@periodEndDate nvarchar(4000)',@periodBeginDate=null,@periodEndDate=null


Answer from here: http://forums.asp.net/t/1611162.aspx/1



Happy Coding! ツ


Wednesday, March 20, 2013

Safe Navigation Operator

C# is lacking a safe navigation operator, so we are forced to write this kind of code...

Console.WriteLine("Winner's zipcode: {0}", lottery.LastDrawnWinner.Address.Street.ZipCode.Value);


...to this code pattern:

string zipCode = null;

// Too much guard clause...
if (lottery != null &&
        lottery.LastDrawnWinner != null &&
        lottery.LastDrawnWinner.Address != null &&
        lottery.LastDrawnWinner.Address.Street != null &&
        lottery.LastDrawnWinner.Address.Street.ZipCode != null) 
// ...too much.
{
    zipCode = lottery.LastDrawnWinner.Address.Street.ZipCode.Value;
}
 
Console.WriteLine("Winner's zip code: {0}", zipCode)



C# team hinted safe navigation operator will be available on future version of C#, which didn't materialized in C# 5 though, otherwise it looks like the following, neat!

Console.WriteLine("Winner's zip code: {0}", lottery.?LastDrawnWinner.?Address.?Street.?ZipCode.?Value);


For now what we can do is introduce a safe navigation design pattern by using extension method:

Console.WriteLine("Winner's zip code: {0}", lottery.NullSafe(l => l.LastDrawnWinner).NullSafe(w => w.Address).NullSafe(a => a.Street).NullSafe(s => s.ZipCode).NullSafe(z => z.Value));


Not as pretty as the real one (safe navigation operator), but it's tidier than doing nested ifs. You'll see the importance of having safe navigation operator / design pattern when you have some deep object graph or you have some repeated code, e.g.

g.Include(x =>
                    {                                   
                        if (x.PayrollExcelExportItemVariableBovms == null) return null;
 
                        var varPay =
                            x.PayrollExcelExportItemVariableBovms.SingleOrDefault(v => v.VariablePayPeriodStepId == param.PeriodStepId);
 
                        if (varPay != null)
                            return varPay.VariablePayBonus;
                        else
                            return null;
                    }
    ).Label(i18nVarPay_VariablePayBudget + "\n(" + param.PeriodStepLabel + ")");


g.Include(x =>
                    {                                   
                        if (x.PayrollExcelExportItemVariableBovms == null) return null;
 
                        var varPay =
                            x.PayrollExcelExportItemVariableBovms.SingleOrDefault(v => v.VariablePayPeriodStepId == param.PeriodStepId);
 
                        if (varPay != null)
                            return varPay.VariablePayBonus;
                        else
                            return null;
                    }
    ).Label(i18nVarPay_EquityPayBonus + "\n(" + param.PeriodStepLabel + ")");



I'm not gonna write my code that way if I can write it in a more robust and conciser way:

g.Include(x => x.PayrollExcelExportItemVariableBovms.?SingleOrDefault(v => v.VariablePayPeriodStepId == param.PeriodStepId).?VariablePayBudget)
        .Label(i18nVarPay_VariablePayBudget + "\n(" + param.PeriodStepLabel + ")");

g.Include(x => x.PayrollExcelExportItemVariableBovms.?SingleOrDefault(v => v.VariablePayPeriodStepId == param.PeriodStepId).?VariablePayBonus)
        .Label(i18nVarPay_VariablePayBonus + "\n(" + param.PeriodStepLabel + ")");



Oops, that's not possible in C# 5 yet, NullSafe extension method would do the trick for now:

g.Include(x => x.PayrollExcelExportItemVariableBovms.NullSafe(x => x.SingleOrDefault(y => y.VariablePayPeriodStepId == param.PeriodStepId)).NullSafe(z => z.VariablePayBudget))
        .Label(i18nVarPay_VariablePayBudget + "\n(" + param.PeriodStepLabel + ")");

g.Include(x => x.PayrollExcelExportItemVariableBovms.NullSafe(x => x.SingleOrDefault(y => y.VariablePayPeriodStepId == param.PeriodStepId)).NullSafe(z => z.VariablePayBonus))
        .Label(i18nVarPay_VariablePayBonus + "\n(" + param.PeriodStepLabel + ")");



NullSafe extension method:

namespace NullSafeExtension
{
     
    public static class NullSafeHelper
    {
        public static U NullSafe<T, U>(this T t, Func<T, U> fn)
        {
            return t != null ? fn(t) : default(U);
        }
    }
}


Technique source: http://qualityofdata.com/2011/01/27/nullsafe-dereference-operator-in-c/



Happy Coding! ツ


UPDATE

Why using safe navigation is better than doing try-catch

When using a try catch, the code won't be able to run the next lines after of the line that has a null. Using a guard clause can prevent nulls from interfering on running all the lines in your code, but that will bloat or increase the noise in code.

I would rather use safe navigation than to use guarded clause. If we rather use catching null reference exception, it will prevent the code from running the next lines.

An example, a lottery winner won on a specific year, yet he has no address:

// Let's say a lottery winner has no registered address,
// hence this line will cause a null exception. So if we are catching exception...
Console.WriteLine("Winner's zipcode: {0}", lottery.LastDrawnWinner.Address.Street.ZipCode.Value); 

// ...this line won't execute:
Console.WriteLine("Year won: {0}", lottery.LastDrawnWinner.YearWon); 

Thursday, March 7, 2013

Clay, the power of JavaScript within C#

The code:

using System;
using System.Linq;
using System.Collections.Generic;
 
using System.Dynamic;
 
using ClaySharp;
 
 
 
namespace TheDynamic
{
    class Program
    {
        static void Main(string[] args)
        {
            // SampleExpando();
            SampleClay();
        }
 
        static void SampleExpando()
        {
            dynamic d = new ExpandoObject();
           
            d["LoremIpsum"] = "World"; // ExpandoObject limitation, dictionary-property duality is not possible
            Console.WriteLine("Hello {0}", d.LoremIpsum);
           Console.ReadLine();
        }
 
 
        // Clay: The power of JavaScript within C#
        // http://www.hanselman.com/blog/NuGetPackageOfTheWeek6DynamicMalleableEnjoyableExpandoObjectsWithClay.aspx
        static void SampleClay()
        {
           
            dynamic New = new ClayFactory();
           
            
            var great = New.Blah();
         
            // just to prove Clay is more dynamic than ExpandoObject, you can add things at runtime, and access them as property:
            // string s = Console.ReadLine(); // Enter this: LoremIpsum
            // great[s]
 
 
            // You can set things via dictionary approach
            great["LoremIpsum"] = "World";         
            // And access them through both property or dictionary approach, just like in JavaScript
            Console.WriteLine("Hello: {0} {1}", great.LoremIpsum, great["LoremIpsum"]);
 
 
            // And vice versa, you can set things using property approach
            great.Awe = "Some";
            // And access them through both dictionary or property approach, just like in JavaScript
            Console.WriteLine("Feelings: {0} {1}", great["Awe"], great.Awe);
 
           
            var props = new Dictionary<string, object>();
 
 
            Func<object> nullFunc = () => null;
 
            var clayBehaviorProvider = great as IClayBehaviorProvider;
            clayBehaviorProvider.Behavior.GetMembers(nullFunc, great, props);
 
 
            Console.WriteLine("\n\nLaugh the problems: \n");
 
            foreach (KeyValuePair<string, object> kv in props.Skip(1))
            {
                Console.WriteLine("{0} {1}", kv.Key, kv.Value);
            }
 
            Console.ReadLine();
        }
    }
 
    // Good read, Clay in action, in ASP.NET MVC! http://orchard.codeplex.com/discussions/406947
}
 

The output:

Hello: World World
Feelings: Some Some
 
 
Laugh the problems:
 
LoremIpsum World
Awe Some 

Wednesday, January 23, 2013

ReSharper always reminds us how pampered we .NET developers are


class Program
{
 static void Main(string[] args)
 {
  var list = new List<Person>();
  
  // ReSharper suggests to convert this code...
  var people = Mate.Create<Person>(list);
  
  // ...to the following code. .NET can infer the type, thus <Person> can be removed:
  var people = Mate.Create(list);
 }
}

public static class Mate
{
 public static IEnumerable<T> Create<T>(IEnumerable<T> list)
 {
  var ee = new ExcelExport<T>();

  return list;
 }
}

public class Person
{
   
}

public class ExcelExport<T>
{       
}

Wednesday, August 29, 2012

Multiple inheritance with C#

It's not possible to do multiple inheritance in C#

public partial class A : FirstConcreteClass, SecondConcreteClass
{
}

public class FirstConcreteClass
{
 public void Hello()
 {
  Console.WriteLine ("Hello");
 }
}


public class SecondConcreteClass
{
 public void World()
 {
  Console.WriteLine ("World");
 }

 public string Yo()
 {
  return "POCO";
 }
}


But what you can possibly do is to isolate the SecondConcreteClass' APIs to an interface and implement it separately:


public class SecondConcreteClass : ISecondConcreteClass
{
 public void World()
 {
  Console.WriteLine ("World");
 }

 public string Yo()
 {
  return "POCO";
 }
}

public interface ISecondConcreteClass
{
 void World();
 string Yo();
}

Then change class A to this implementation, note the partial keyword and the implementation of ISecondConcreteClass:

public partial class A : FirstConcreteClass, ISecondConcreteClass
{
 public A()
 {
    this.SC = new SecondConcreteClass();
 }
}


The second piece of the puzzle. Put the stub class for ISecondConcreteClass implementation on a partial class. The stub class merely pass-the-buck the actions to the instance of ISecondConcreteClass.

public partial class A 
{
 ISecondConcreteClass SC { get; set; }
 
 public void World() { SC.World(); }
 public string Yo() { return SC.Yo(); }
}


To use:

var a = new A();
a.Hello();

a.World();
Console.WriteLine (a.Yo ());


Output:
Hello
World
POCO


The gist is, if you have a class(say B) that already extends another class and yet it need to extend another concrete class, just make that class B implement the other concrete's interface instead, and instantiate an object for the interface


public partial class B : WhateverClassThatMaybe, ISecondConcreteClass
{
 public B()
 {
    // instantiate SecondConcreteClass
    this.SC = new SecondConcreteClass();
 }
}


To shift the burden of manually coding the partial stub classes from the developer to the computer, use T4 (Text Template Transformation Toolkit) to automate the generation of those partial stub classes, that's how useful the computer is ツ


<#@ template language="C#v3.5" #>
  
  
<# var a = new[] { "A", "B" }; #>

namespace TestMultipleInheritance
{

<# foreach(string s in a) { #>

 public partial class <#=s#> 
 {
  ISecondConcreteClass SC { get; set; }
  
  public void World() { SC.World(); }
  public string Yo() { return SC.Yo(); }
 }


<# } #>


}


An aside, I'm using Mono .NET Framework version 4.0 and can use C# 4 features(e.g. dynamic), though for some reasons unknown to me, Mono's templating language is C# 3.5


The topic of OOP and inheritance is not complete without the capability to polymorph the object's functionality. So how can we achieve polymorphism with a simulated concrete class? In a normal class or abstract class, you have a virtual or abstract method that you can override. With multiple inheritance simulation using interface implementation, just implement the interface the usual way, so don't include the class(class C in following example) that polymorphs its concrete base class(simulated concrete base class ISecondConcreteClass) in T4:


public partial class C 
{
 ISecondConcreteClass SC { get; set; }
 
 public void World() // think of this as an overriding function? Well it is
 { 
  SC.World();  // think of SC.World() as base.World();

  System.Console.WriteLine ("Long Live!");
 }
 public string Yo() { return SC.Yo(); }
}

Or better yet, copy-paste existing class stub to new partial class file, then delete string "C" from T4's iterated string array, T4 will automatically re-generate A and B class, and shall not generate C class. Then customize your overrides in that partial C class file.


If you want the World method to be overridable further down the inheritance chain, just add the virtual keyword to the method signature:


public partial class C 
{
 ISecondConcreteClass SC { get; set; }
 
 // virtual will make the World overridable down the inheritance chain
 public virtual void World() 
 { 
  SC.World();  // think of SC.World() as base.World();

  System.Console.WriteLine ("Long Live!");
 }
 public string Yo() { return SC.Yo(); }
}



That's multiple inheritance for us C# folks!


Happy Computing! ツ

Wednesday, August 1, 2012

Use components that uses yield return

When to use yield return?

You were given a task to shop for a component you cannot make by yourself, say fibonacci number generators.

You found two vendors. Both of their components produces correct output, both of them can generate up to fifty fibonaccis, and both of them are priced the same.

All things being equal, you are left with one qualifier, a good qualifier, you want to choose the component with a better quality. But for some reasons, these two vendors don't want to give you their source codes, hence you cannot see how they implement things. They just want to give you the DLL only.

But those vendors still have some kindness left in their hearts, they at least give you a clue how their components work.

Vendor A told you they uses eager loading(i.e. uses IList)
Vendor B told you they uses lazy loading(i.e. uses yield return)

In case like this, you need to purchase vendor B's component.

Vendor A's approach uses too much memory, they put elements to an allocated memory. Vendor B generates elements on-the-fly.


Desirability of vendor B's approach is more apparent if for example you just want the 8th fibonacci.

Using vendor A's component, your code still need to wait a long time in order to get the 8th element. Why it is so? Even you just want the 8th element, your code still need for vendor A's component to generate the whole 50 elements, after doing so, then that's the only time you can pick the 8th element.


Using vendor B's component, if you just want to get the 8th element, it will stop generating on the 8th element. Your code don't need vendor B's component to generate all the 50 elements in order for your code to get the 8th element. Vendor B's component has some smart on it.


To contrast the difference between IList and yield return, check the output of this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ChooseLesserOfTheTwoEvils
{
    class Program
    {
        static void Main(string[] args)
        {
            TestLoopOnEvilA();
            Console.WriteLine("------");
            TestLoopOnEvilB();
            Console.WriteLine("------");
 
            Console.ReadKey();
             
            TestPick8thOnEvilA();
            Console.WriteLine("------");
            TestPick8thOnEvilB();
            Console.WriteLine("------");
 
            Console.ReadKey();
        }
 
        static void TestPick8thOnEvilA()
        {
            Console.WriteLine("TestPick8thOnEvilA");
            long eighth = EvilCompanyA.MathProvider.Fibonacci().Skip(7).Take(1).Single();
            Console.WriteLine("\nEvil A's 8th fibonacci is {0}", eighth);
        }
 
        static void TestPick8thOnEvilB()
        {
            Console.WriteLine("TestPick8thOnEvilB");
            long eighth = EvilCompanyB.MathProvider.Fibonacci().Skip(7).Take(1).Single();
            Console.WriteLine("\nEvil B's 8th fibonacci is {0}", eighth);
        }
 
        static void TestLoopOnEvilA()
        {
            Console.WriteLine("Test Loop On Evil A");
            IEnumerable<long> bucket = EvilCompanyA.MathProvider.Fibonacci();
            Console.WriteLine("\nTest start");
 
            foreach (var item in bucket)
            {
                Console.WriteLine("Evil A's Fib: {0}", item);
            }
            Console.ReadLine();
        }
 
         
        static void TestLoopOnEvilB()
        {
            Console.WriteLine("Test Loop On Evil B");
            IEnumerable<long> bucket = EvilCompanyB.MathProvider.Fibonacci();
            Console.WriteLine("\nTest start");
 
            foreach (var item in bucket)
            {               
                Console.WriteLine("Evil B's Fib: {0}", item);
            }
            Console.ReadLine();
        }
    }
 
     
}
 
 
namespace EvilCompanyA
{
    public static class MathProvider
    {
        public static IEnumerable<long> Fibonacci()
        {           
            IList<long> il = new List<long>();
 
            long a = 0, b = 1;
 
            for (int i = 1; i <= 50; ++i)
            {
                Console.Write("eager{0} ",i);
                il.Add(a);
                long n = a;
                a += b;
                b = n;
            }
                   
 
             
            return il;
        }
    }
}
 
namespace EvilCompanyB
{
    public static class MathProvider
    {
        public static IEnumerable<long> Fibonacci()
        {
            long a = 0, b = 1;
 
            for (int i = 1; i <= 50; ++i)
            {
                Console.Write("lazy{0} ",i);
                yield return a;
                long n = a;
                a += b;
                b = n;
            }
        }
    }
}

Output:

Test Loop On Evil A
eager1 eager2 eager3 eager4 eager5 eager6 eager7 eager8 eager9 eager10 eager11 eager12 eager13 eager14 eager15 eager16 eager17 eager18 eager19 eager20 eager21 eager22 eager23 eager24 eager25 eager26 eager27 eager28 eager29 eager30 eager31 eager32 eager33 eager34 eager35 eager36 eager37 eager38 eager39 eager40 eager41 eager42 eager43 eager44 eager45 eager46 eager47 eager48 eager49 eager50 
Test start
Evil A's Fib: 0
Evil A's Fib: 1
Evil A's Fib: 1
Evil A's Fib: 2
Evil A's Fib: 3
Evil A's Fib: 5
Evil A's Fib: 8
Evil A's Fib: 13
Evil A's Fib: 21
Evil A's Fib: 34
Evil A's Fib: 55
Evil A's Fib: 89
Evil A's Fib: 144
Evil A's Fib: 233
Evil A's Fib: 377
Evil A's Fib: 610
Evil A's Fib: 987
Evil A's Fib: 1597
Evil A's Fib: 2584
Evil A's Fib: 4181
Evil A's Fib: 6765
Evil A's Fib: 10946
Evil A's Fib: 17711
Evil A's Fib: 28657
Evil A's Fib: 46368
Evil A's Fib: 75025
Evil A's Fib: 121393
Evil A's Fib: 196418
Evil A's Fib: 317811
Evil A's Fib: 514229
Evil A's Fib: 832040
Evil A's Fib: 1346269
Evil A's Fib: 2178309
Evil A's Fib: 3524578
Evil A's Fib: 5702887
Evil A's Fib: 9227465
Evil A's Fib: 14930352
Evil A's Fib: 24157817
Evil A's Fib: 39088169
Evil A's Fib: 63245986
Evil A's Fib: 102334155
Evil A's Fib: 165580141
Evil A's Fib: 267914296
Evil A's Fib: 433494437
Evil A's Fib: 701408733
Evil A's Fib: 1134903170
Evil A's Fib: 1836311903
Evil A's Fib: 2971215073
Evil A's Fib: 4807526976
Evil A's Fib: 7778742049
------
Test Loop On Evil B

Test start
lazy1 Evil B's Fib: 0
lazy2 Evil B's Fib: 1
lazy3 Evil B's Fib: 1
lazy4 Evil B's Fib: 2
lazy5 Evil B's Fib: 3
lazy6 Evil B's Fib: 5
lazy7 Evil B's Fib: 8
lazy8 Evil B's Fib: 13
lazy9 Evil B's Fib: 21
lazy10 Evil B's Fib: 34
lazy11 Evil B's Fib: 55
lazy12 Evil B's Fib: 89
lazy13 Evil B's Fib: 144
lazy14 Evil B's Fib: 233
lazy15 Evil B's Fib: 377
lazy16 Evil B's Fib: 610
lazy17 Evil B's Fib: 987
lazy18 Evil B's Fib: 1597
lazy19 Evil B's Fib: 2584
lazy20 Evil B's Fib: 4181
lazy21 Evil B's Fib: 6765
lazy22 Evil B's Fib: 10946
lazy23 Evil B's Fib: 17711
lazy24 Evil B's Fib: 28657
lazy25 Evil B's Fib: 46368
lazy26 Evil B's Fib: 75025
lazy27 Evil B's Fib: 121393
lazy28 Evil B's Fib: 196418
lazy29 Evil B's Fib: 317811
lazy30 Evil B's Fib: 514229
lazy31 Evil B's Fib: 832040
lazy32 Evil B's Fib: 1346269
lazy33 Evil B's Fib: 2178309
lazy34 Evil B's Fib: 3524578
lazy35 Evil B's Fib: 5702887
lazy36 Evil B's Fib: 9227465
lazy37 Evil B's Fib: 14930352
lazy38 Evil B's Fib: 24157817
lazy39 Evil B's Fib: 39088169
lazy40 Evil B's Fib: 63245986
lazy41 Evil B's Fib: 102334155
lazy42 Evil B's Fib: 165580141
lazy43 Evil B's Fib: 267914296
lazy44 Evil B's Fib: 433494437
lazy45 Evil B's Fib: 701408733
lazy46 Evil B's Fib: 1134903170
lazy47 Evil B's Fib: 1836311903
lazy48 Evil B's Fib: 2971215073
lazy49 Evil B's Fib: 4807526976
lazy50 Evil B's Fib: 7778742049
------
TestPick8thOnEvilA
eager1 eager2 eager3 eager4 eager5 eager6 eager7 eager8 eager9 eager10 eager11 eager12 eager13 eager14 eager15 eager16 eager17 eager18 eager19 eager20 eager21 eager22 eager23 eager24 eager25 eager26 eager27 eager28 eager29 eager30 eager31 eager32 eager33 eager34 eager35 eager36 eager37 eager38 eager39 eager40 eager41 eager42 eager43 eager44 eager45 eager46 eager47 eager48 eager49 eager50 
Evil A's 8th fibonacci is 13
------
TestPick8thOnEvilB
lazy1 lazy2 lazy3 lazy4 lazy5 lazy6 lazy7 lazy8 
Evil B's 8th fibonacci is 13
------



Live Code: http://ideone.com/QxU7Sn

Sunday, July 29, 2012

From raw parameters to structured data

To avoid stringly-typed processing, convert string-based parameters to structured data. Then do further processing on that internal data structure, where the information can be easily processed.


public class Node
{
    public Node ChildOf { get; set; }
    public string Path { get; set; }

    public IList<Node> Children { get; set; }

}



public static class Helper
{

    public static Node ArrayToTree(params string[] paths)
    {
        Node root = new Node
        {
            ChildOf = null,
            Path = null,
            Children = new List<Node>()
        };

        

        foreach (string path in paths)
        {
            string[] subPaths = path.Split('.');

            Node addTo = root;

            foreach (string subPath in subPaths)
            {
                Node child = addTo.Children.FirstOrDefault(x => x.Path == subPath);

                if (child == null)
                {
                    child = new Node
                    {
                        ChildOf = addTo,
                        Path = subPath,
                        Children = new List<Node>()
                    };

                    addTo.Children.Add(child);
                }//if

                addTo = child;
            }//foreach

        }//foreach


        return root;
    }
}


Unit test:


public void TestStructuredData()
{
    Node n = Helper.ArrayToTree(
        new[]
        { 
            "Answers", 
            "Answers.Comments", 
            "Answers.Greats", 
            "Answers.Balls.Of.Fire", 
            "Comments" 
        
        });


    Assert.AreEqual(2, n.Children.Count);
    Assert.AreEqual(3, n.Children[0].Children.Count);


    Assert.AreEqual("Answers", n.Children[0].Path);

    Assert.AreEqual("Comments", n.Children[0].Children[0].Path);
    Assert.AreEqual("Greats", n.Children[0].Children[1].Path);
    Assert.AreEqual("Balls", n.Children[0].Children[2].Path);
    Assert.AreEqual("Of", n.Children[0].Children[2].Children[0].Path);
    Assert.AreEqual("Fire", n.Children[0].Children[2].Children[0].Children[0].Path);

    Assert.AreEqual("Comments", n.Children[1].Path);
}


Avoid stringly-typed programming, use proper data structure.

http://www.google.com/search?q=stringly-typed+programming+-strongly