Profile Picture

Sirwan Afifi

Stories from a web developer.

© 2017. Sirwan Afifi All rights reserved.

My first experiences with Linux

Running Window 98 on my PC was my first experience with Windows. in fact, for the last 11 years or so, Windows has been the dominant operating system that I’ve been using. So, up until now, I have been an avid fan of Windows.

Disclaimer: I’m not going to say that I’m not interested in Windows anymore, I just want to explain my experience with Ubuntu

Windows just works fine for the most part. But, as a developer, I have always felt something is missing. For solving this problem, Microsoft has tried its best bringing in tools like PowerShell and Bash to Windows. But again, with all these great features and tools, as a developer, you think something is missing.

Two weeks ago, I decided to give Linux a try, So I chose Ubuntu because it’s user-friendly and its community is huge. Actually, my goal was to do some experiments with new version of .NET called .NET Core. The experience was great. First, I created a very simple console application on Windows and deployed it as a SCD (Self-Contained Deployment):

Then, I copied the publish folder on my USB stick and finally, I could run my .NET Core application without installing the .NET runtime on the target machine:

As a .NET developer I have been waiting voraciously for such opportunity. So, I think it’s the best time to migrate to Linux.

Actually, I was amazed at the first impression because Linux has everything a developer needs out of the box. Python is already installed on the OS. This is great because there are times you want to write simple scripts, scrap a page or something like that.

Other cool features of Linux are commands like sed and grep. These tools are great whether you are a developer or a network administrator. for example, suppose that you have following content within a file named test.json:

{
   "AppName": "Simple App",
   "Website": "sirwan.info",
   "UseSqlite": false,
}

Now you want to replace all occurrence of "UseSqlite": false, to "UseSqlite": true, you can do that simply by typing this command:

cat text.json | sed 's/"UseSqlite": false,/"UseSqlite": true,/'

You can definitely do wide varaity of things using these tools, I just wanted to tell you how much I am excited about these cool stuff.

Development on Ubuntu

The good news is that .NET Core runs on Windows, Mac and Linux. In order to install .NET Core on Ubuntu you just simply need to navigate to dot.net site and download the appropriate version. after installing .NET Core, it gives you a CLI called dotnet so you can simply create, build and publish your applications using this command, for example:

dotnet new
dotnet restore
dotnet run

You can also use the editor of your choice for developing .NET Core application, personally I prefer to use Visual Studio Code or VSCode for short. because it has all great features you need:

VSCode is great, But I think using an IDE like Visual Studio gives you the power you need when are developing applications, Unfortunately, there’s no official version of Visual Studio for Linux at this time. I hope Microsoft release it for Linux users The only reason that I can’t abandon Windows is the lack of Visual Studio So I have to keep using Windows on my main machine.

Conclusion

As I mentioned Visual Studio is the only reason to not completely abandon Windows, But I will use Ubuntu for sure. This was my first attempt to use Ubuntu and I am very happy about the experience, I would like to hear your ideas about your journey.

Happy Coding :))

Environments in ASP.NET Core

In ASP.NET Core we can have different hosting environments, this is supported by an environment variable called ASPNETCORE_ENVIRONMENT. You can see this value is already set to Development:

This value is active as long as you run your application inside Visual Studio, So when you deploy your application you must change this value. Actually, this value comes from a file called launchSettings.json:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:13880/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "ProjectName": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

You can determine what the environment is by using IHostingEnvironment:

public void Configure(IApplicationBuilder app, 
	IHostingEnvironment env, ILoggerFactory loggerFactory)
{
	loggerFactory.AddConsole();

	if (env.IsDevelopment())
	{
		app.UseDeveloperExceptionPage();
	}
	else
	{
		app.UseExceptionHandler(new ExceptionHandlerOptions
		{
			ExceptionHandler = context => context.Response.WriteAsync("Opps!")
		});
	}

	// other configurations
}

This object also has a method called IsEnvironment for using custom environment:

if (env.IsEnvironment("envName"))
{
    // some config
}

One interesting thing is that the Startup class itself supports different environments, it means that for each environment you can have both Configure and ConfigureServices:

public void ConfigureDevelopment(IApplicationBuilder app, .....
public void ConfigureServicesDevelopment(IServiceCollection services)

public void ConfigureStaging(IApplicationBuilder app, .....
public void ConfigureServicesStaging(IServiceCollection services)

public void ConfigureProduction(IApplicationBuilder app, .....
public void ConfigureServicesProduction(IServiceCollection services)

Now you might ask how we can set this environment variable, well there are several ways that you can use, this great post explains them in details.

Getting to know Singleton pattern in C#

This pattern helps us to ensure a class has only one instance. The term comes from the mathematical concept of a singleton:

In mathematics, a singleton, also known as a unit set,[1] is a set with exactly one element. For example, the set {0} is a singleton.

Eventually we must have a class that only gives us a single instance:

var sigleInstance = MySingletonClass.GetInstance();

As you can see the only way to access the instance is by calling a public static method called GetInstance(), the single object instance under consideration is created only for the first time it is requested. suppose the following class:

public class MySingletonClass
{
    public MySingletonClass()
    {
	
    }
}

Now I want to make this class singleton, So the first step is to ensure that no one can instantiate our class for doing so we must make the constrauctor private:

public class MySingletonClass
{
    private MySingletonClass()
    {
	
    }
}

Now whenever you want to create a new instance of MySingletonClass using new keyword, Visual Studio gives you this error:

But we can still instantiate it from within the class. So next step is to create a new variable of type MySingletonClass inside the class, this class is going to be the only instance of the class:

public class MySingletonClass
{
	private static MySingletonClass _instance;

	private MySingletonClass() { }
}

So we are getting close to implementing the pattern. Now we need a way to get access the single instance. So we need a method like this:

public static MySingletonClass GetInstance()
{
	if (_instance == null)
	{
		_instance = new MySingletonClass();
	}
	return _instance;
}

This method instantiates MySingletonClass if an instance doesn’t already exist, otherwise it return the existing instance. To demonstrate the object lifetime we can print value of GetHashCode() fo these objects:

var mySingleInstance   = MySingletonClass.GetInstance();
var mySingleInstance_2 = MySingletonClass.GetInstance();
var mySingleInstance_3 = MySingletonClass.GetInstance();
var mySingleInstance_4 = MySingletonClass.GetInstance();

Console.WriteLine($"obj1: {mySingleInstance.GetHashCode()}");
Console.WriteLine($"obj2: {mySingleInstance_2.GetHashCode()} ");
Console.WriteLine($"obj3: {mySingleInstance_3.GetHashCode()} ");
Console.WriteLine($"obj4: {mySingleInstance_4.GetHashCode()} ");

As you can see all of the objects are the same and share the same instance. The problem with this implementation is that, it’s not thread-safe; it means that if seperate threads of execution access the _instance at the same time, more that one instance of the MySingletonClass object may be created. One of the solution is by using .NET 4’s Lazy<T> type:

public class MySingletonClass
{
	private static readonly Lazy<MySingletonClass> _instance = 
		new Lazy<MySingletonClass>(() => new MySingletonClass());

	private MySingletonClass() { }

	public static MySingletonClass GetInstance()
	{
		return _instance.Value;
	}
}