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

Monday, July 16, 2018

C# Logging: Where To Setup The Logger

Applications need logging. In C#, you will typically log various types of events like exceptions, debug, and informational. Your logs will contain valuable information which you'll use to tune your application and understand user behavior.

It's easiest to either pass an enum value to a single Log method or call a specific method to write different types of events. It's typical to write to different logs depending on the context. The problem is, where and how do we access the logging API from our methods?

Dependency Injection


Dependency Injection is one possible approach. If you go this route, you have to pass around a logger to all your classes as a dependency. You can use constructor injection and take the logger in as a constructor parameter. For a User class, you would pass it in along with the UserRepository as follows:


public class User
{
  private readonly IRepository<UserData> _userRepo;
  private readonly ILogger _logger;

  public User(IRepository<UserData> userRepo, ILogger logger)
  {
    _userRepo = userRepo;
    _logger = logger;
  }
}


The User class takes in the logger along with any other dependencies.

Via IoC Container

Even if you use an IoC container like Ninject or Unity, you have to add the logging interface to all the constructors and make a class member. With the IoC container approach, you can also ask the container for the implementation.

Container.Get<ILogger>()?.LogError(...);

Results and specific approach may vary according to the container, but this will at least allow you to fetch the logger whenever you need it without having to pass it around.

The .NET Core Way

In .NET Core 2.1, there are two ways to go about it as written by Luke Latham. Luke recommends using the LoggerMessage class over the LoggerExtensions for high-performance applications.

The Problem With DI

But let's suppose that you're not using core and you don't like the idea of adding the logger dependency EVERYWHERE! It isn't a dependency of the class that has anything to do with the business logic of the class. It's an implied dependency of all classes in the application. If you first design the class without the logging dependency, then you have to add it when you need to use logging.

IoC containers make this easier, but what if you have static methods from which you need to log (it happens)? In that case, you don't have constructor variables. You could pass the logger in the method params, but then you're passing around a logger. That's not a particularly elegant pattern! For one thing, you end up with more parameters. Another, you get into the habit of passing things around you may or may not need.

As Global

If it's a dependency everywhere, it's a global dependency. I don't like globals for many things. They are for configuration and that's really about it. It's beneficial to have a global logger too!

I also don't recommend statics for most things. Well, the logger could be a static global so long as it doesn't have mutable state. In other words, so long as you set the logging configuration once and leave it along throughout the entire application lifetime.

Log.LogError(...);

And in your implementation of the static method, you can get it from the container or some other global context.


public static void LogError(params object[] logParams)
{
  Container.Get<ILogger>()?.LogError(logParams);
}

This is actually a better practice since you only have to change your Log class if you change IoC containers and the interface doesn't match. It's better separation of concerns (SOC). The place to change the logging is in the Log class rather than everywhere else!

Concluding


Most of the methods discussed here are fine and dandy. I'm just not a huge of fan of having to pass things around in every class. I wouldn't extend this idea to something like a repository though, those are business logic specific dependencies that actually have meaning to the class at hand. A User class taking a UserRepository is meaningful. Every class taking an ILogger has no meaning and actually distracts from the purpose of the classes.

In sum, global is the place for the logger!

Wednesday, January 20, 2016

C# to JavaScript: Namespacing

Namespacing is one of the most important things you can do when using js. While namespaces are built-in constructs in C#, they are not an official part of the js language. That doesn't mean that you can't or shouldn't use them, on the contrary. In this post, I'm going to show you how to create namespaces and how to add your code to the namespace to not only avoid polluting the global context, but also to avoid potential collisions with variables and functions from other js libraries.

If you are foggy on what exactly a namespace is - my definition is that it's a logical container used to provide identity and scope to related code. If a class "Languages" in C# is defined in a namespace "TDLL.Countries", the class would be accessible from code in other namespaces via TDLL.Countries.Languages or Languages if the code file is has the "using TDLL.Countries" statement outside the class definition. Now that a baseline has been established, let's take a look at some common namespaces in js.

JQuery is definitely one of those libraries that is ubiquitous. I'd say it's the most commonly used js library in the world, but then again I don't have the numbers but I bet you've used it in some capacity. The JQuery library has a namespace - 'jQuery'. Also, that namespace has an alias '$'.

Click each "Say Hello" button in the jsbin demo below to see that both jQuery and $ are the same.


jQuery Namespace on jsbin.com

JQuery has some interesting documentation on the jQuery global namespace and the $ alias here.

And this snippet from the jQuery source code on GitHub is exactly how the global namespaces are assigned:


define( [...], function( jQuery ) {
    return ( window.jQuery = window.$ = jQuery );
});

in this case "define" is a function from RequireJS which is out of scope for this post. There's a lot that goes into the "jQuery" arg that is passed to the define callback function. It is defined in the files that are omitted in the sample shown then passed into define during build time to eventually add the function to the window object (global). jQuery gives you an option to release '$' in case there is a namespace collision with other libraries - also a good practice if you are aliasing.

Another way to create a namespace is to create the namespace first, then add everything to the namespace.


window.TDLL = {};
TDLL.learnSomething = function(){ ... };

Also you could do it using object notation like this:


window.TDLL = {
    learnSomething : function(){ ... },
};


One of the challenges in defining a namespace in either of those ways is that if the namespace is already defined, you'd basically overwrite it in subsequently loaded files. To avoid that you can do the following:


window.TDLL = window.TDLL || {};
TDLL.everyDay = function(){ ... };

This neat trick evaluates the first operand of the OR (||) expression as false if it is undefined.

Another way to do this is to use jQuery to merge your new object with the existing one.


window.TDLL = $.extend(window.TDLL, {
    everyDay : function(){ ... },
});

https://api.jquery.com/jquery.extend/

jQuery Merge Demo on jsbin.com

Using your namespace is simple (once you know it has been loaded anyways).


TDLL.learnSomething();
TDLL.everyDay();

There are ways to ensure that your namespace has been loaded (by packaging all of your javascript together), but those are beyond the topic of this post and will be a topic for a future post.

Tuesday, January 5, 2016

Abtracting Service Calls Using the Adapter Pattern

Consider the following scenario:

Given an environment which contains the following:

UserResource - a service which allows clients to lookup users and user information.
AdminResource - a service which allows clients to lookup admin details.
TaskApplication - an application which consumes the UserResource.
DocumentApplication - an application which consumes the UserResource.
AdminApplication - an application which consumes the UserResource and AdminResource.

And each of these applications have variances in their domain specific usage of the data provided by the UserResource.

When the applications are developed
Then you may want to build domain specific classes to represent the data you are using in each application.


For Example:

Suppose the AdminApplication needs to make a distinction between SystemAdminUser and User such that it would be appropriate to create a subtype of User for the SystemAdminUser (with additional detail) which the UserResource does not provide, the additional data would come from the AdminResource.

It may be better to create a new type rather than a subtype, I'll get into why in a bit. For now let's create a subtype from the UserResource like so...


namespace AdminApplication.Objects
{
    public class SystemAdminUser : User
    {
        public int[] SystemIds { get; set; }
    }
}
.
.
.
namespace AdminApplication.Adapters
{
    public interface ISystemUserResource
    {
        SystemAdminUser GetSystemAdminUser(int id);
    }

    public class SystemUserResource : ISystemUserResource
    {
        IUserResource _userResource;
        IAdminResource _adminResource;
        public SystemUserResource(IUserResource userResource, IAdminResource adminResource)
        {
            _userResource = userResource;
            _adminResource = adminResource;
        }

        public SystemAdminUser GetSystemAdminUser(int id)
        {
             var user = _userResource.GetUser(id);
             var admin = _adminResource.GetSystemAdmin(id);
             return Mapper.MergeMap(user, admin);
        }
    }
}

And when this adapter is consumes in the application, the application code no longer will need to have the dependency on the IUserResource and IAdminResource interfaces (assume this example uses DI/IoC to inject the concrete classes) but only on the one ISystemUserResource interface. There is an added benefit to the simplicity and reuse that will make the rest of the application code flow more naturally.

However, we do have a deeper issue with this choice. To illustrate, note the following consumer of ISystemUserResource:



using AdminApplication.Adapters;
using AdminApplication.Objects;
using UserResource.Proxies;

namespace AdminApplication.Web
{
    public class HomeController
    {
        ...
    }
    ...
}

See how we have the dependency on the UserResource library due to the class being derived from one of its types? This dependency will bleed all over the application code, the test code, etc. Additionally, we may also be passing quite a bit of information around the application that we do not need by way of properties on the User instances. Additionally, though not likely in this specific scenario, there may be differences in terminology in different domains for the same thing. It would be confusing to have an EmployeeId when in the context it is always referred to as the UserId.

In order to minimize the bleeding of dependencies through consumer code, it would serve well to abstract the services behind a domain specific adapter using an Adapter pattern, Façade pattern, or a combination of both.




namespace AdminApplication.Objects
{
    public class SystemAdminUser
    {
        public int UserId { get; set; }
        public string UserName{ get; set; }
        public int[] SystemIds { get; set; }
    }
}
.
.
.
namespace AdminApplication.Adapters
{
    public interface ISystemUserResource
    {
        SystemAdminUser GetSystemAdminUser(int id);
    }

    public class SystemUserResource : ISystemUserResource
    {
        IUserResource _userResource;
        IAdminResource _adminResource;
        public SystemUserResource(IUserResource userResource, IAdminResource adminResource)
        {
            _userResource = userResource;
            _adminResource = adminResource;
        }

        public SystemAdminUser GetSystemAdminUser(int id)
        {
             var user = _userResource.GetUser(id);
             var admin = _adminResource.GetSystemAdmin(id);
             return Mapper.MergeMap(user, admin);
        }
    }
}


There will be a slight increase in code complexity at first. But the long-term benefits of being able to upgrade services without much change, testability, and the reduction of the reference bleeding will be a future asset worth investing in.

Thursday, December 31, 2015

Lambda, Lambda, Lambda - How To Use a Lambda Expression

Many programming languages use lambda expressions: Python, Ruby, C#, JavaScript, and GO to name a few modern examples. Lambdas can be extremely expressive and save several lines of code when you just need a function without the need for reuse. I and others use Lambdas to create greater readability. On the flip side, if you don't understand how they work l, the syntax can be confusing and the code will be impossible to understand. My goal in this post is to help you understand what Lambdas are all about so you can understand them next time you see one and even add Lambdas to your tool set to improve your ability to be more expressive.


Here are some examples of adding 1 to x using Lambdas in various languages:

Python:
lambda x: x + 1;

Ruby:
lambda { |x| x + 1 }

C#:
x => x + 1;

js (ES6):
x => x + 1;

GO and js (<ES6):
This is where it gets interesting. These languages treat functions as first class and so a function can be passed as an argument to a function, which is really the point of lambda. This works the same way in PHP too. The syntax really doesn't matter in terms of understanding what a lambda is. Syntax is just to make things cleaner and gives you a way to declare the Lambda inline.

Let me explain by example:


Lets say we have a js function that expects a function:


function foo(bar){
    return bar();
}


This is a root form of the lambda.


In a strongly typed language like C#, it will look something like this:


int Foo(Func<int> bar)
{
    return bar():
}

Notice how the input is a Func? A Func is an anonymous method that returns a value (specified by the type in angled brackets <int>. There's also an Action which expects void.

Here is a more useful example:


public int OperateOnX(Func<int, int> expression)
{
    return expression(this._x);
}

and we call the method like this:


var a = intance.OperateOnX(x => x+1);
//or
var b = instance.OperateOnX((x) => x*x);


or if we use the C# Linq library:


var c = list.Where(x => x > 3);


In this example, the Func returns int and expects int as the first argument. Mulitple arguments can be specified as Func<int, int, string> (Action<int> expects one int argument, and Action<int, string> expects an int and a string argument):

var b = instance.OperateOnXY((x, y) => x*y); //Func<long, int, int>


The Where extension method iterates over the list and passes each item to your Lambda and returns items for which the expressions evaluates to true. The Lambda Expression is a filter.

For more advanced operations, you can encapsulate like this:



var c = list.Select(x => 
{
    var y = x.Name;
    if(y == "")
    {
        x.Name = "Phil";
    }
    return x;
});


Lambdas can take multiple arguments, after all they should behave just like a regular method or function. In fact you can pass a method to a Linq Where like this:


var d = list.Where(Filters.GreatFilter);


so long as GreatFilter matches the expected delegate type - its signature should look like this:


bool GreatFilter(ListItem item);


Since Where is an extension method in C# Linq (it Extends IEnumerable<T>) the input argument to the generic function will be T, or in this case whatever type "list" items are.


Hopefully, you understand what Lambdas are all about by now, if not feel free to ask and I will do my best to explain a bit further.


Wednesday, December 30, 2015

Extension Methods in C#

If you've ever used Extension methods in C# but don't really understand what they are about this post will hopefully help you understand them a bit and even how to create your own. If you haven't used them this should serve as a good foray into expanding your toolset.



Here's what I've learned:

Make a static class and add a static method (this is the extension method).

The extension method takes in the object it is extending as the first argument in the following format:

public static class BakerExtensions
{
    public static Cake MakeCake(this Baker baker)
    {
        //make that cake
    }
}

If we have a baker instance we would call the extension method as if it belonged to the Baker class.

Baker baker = new Baker();
Cake mmmCake = baker.MakeCake();

I recommend keeping your extension classes at a 1:1 ratio to the classes they are extending. If you have a Baker and a CandleStickMaker you should have a BakerExtensions and a CandleStickMakerExtensions class. This is not required, but it will help with organization.

You may also want to namespace your extension classes the same as the classes they extend, but if you do remember that the extensions will automatically be brought in with the class if it is in the same namespace. You could go with <original namespace>.Extensions if you want more control over when to bring them in and when not to, but it may end up adding confusion in the end.

So why on earth would you want to use extension methods? Why not create subclasses and just add the methods to those?

Ok, so let's say you have some existing code with the Baker class all over the place. You might have some subclasses already and you don't want to change the base class OR you want to add functionality to built-in types like string or int.

public static class StringExtensions
{
    public static string Shuffle(this string inputString)
    {
         //shuffle that string
    }
}


var shuffled = "something".Shuffle();

//shuffled  == "emogsinht"

It's a pretty neat way to keep in line with the Open/Closed Principle if you don't need to access instance members.

Word of caution: be careful about side effects when it comes to extensions. Side effects are a code smell in any case. Thogh it may be tempting to have them in extension methods, you should treat them just like you would if they we a normal class method.

There are a couple of drawbacks - You wouldn't get access to internal members of the class; and your extension methods won't be called if they have the same name and signature of a class method.

Here's an msdn article on the topic for more detail: https://msdn.microsoft.com/en-us/library/bb383977.aspx

Friday, August 28, 2015

Battle of the Languages

One great thing about the challenges offered on CodeEval.com is that they can be solved in so many languages - e.g. choose the language of your choice and go at it! As a side benefit, one can easily compare run-times and memory footprints of languages by solving a challenge in many languages and viewing the results. As an experiment I did just that with the following challenge.

Here is the description of the challenge, as it can be seen on the site:



And the basic solution, which I implemented using the same basic algo in five languages (JavaScript, Java, PHP, C#, and C).

The test data is supplied via a file passed to args during execution, the same file is used in every execution run. JavaScript is run on Node. Execution takes place server side on a Linux based server (more details on the CodeEval site).

Basic algo is: for each line, split line on comma, parse each val to an int, run computation, print results to standard output.



Drum roll please....









As expected, C has the smallest mem usage and the fastest run-time, and by far at that. But I didn't expect Java to be that bad. Granted this is a trivial example. It would be interesting to see if the gap closes when the C program needs more supporting code. Educated guess is yes but not by much. The Java code for is below, I wonder if I'm doing anything wrong here or if it really is that less efficient in all ways.


import java.io.*;
public class Main {
    public static void main (String[] args) throws IOException {
        File file = new File(args[0]);
        BufferedReader buffer = new BufferedReader(new FileReader(file));
        String line;
        while ((line = buffer.readLine()) != null) {
            line = line.trim();
            String[] vals = line.split(",");
            int x = Integer.parseInt(vals[0]);
            int n = Integer.parseInt(vals[1]);
            compute(x,n);
        }
    }
    
    static void compute(int x, int n)
    {
        int m = n;
        while(m<x){
            m+=n;
        }
        System.out.print(m+"\n");
    }
}

I plan on doing this same test in Ruby, Python, and GO to do an even broader comparison, when I have some time. Results will follow if I do.