Fundamental Books on Software Development

There is a huge amount of different books on software development. Most of them are like “Building applications using XYZ and ABC”, with many pages of code inside, examples and directions. They may be useful, but you may manage to do without them, just by using some articles, tutorials and examples.

And there are books which give you concepts, ideas and deeper understanding of things, which form you as a developer and professional, and help you in many projects and many positions, whatever technology you use. These books you remember forever and sometimes read them again and again.

So, here I will give my list (partial, what I remember) of such fundamental books I recently read and recommend any software developer to read.

Continue reading

Advertisements

Visual Studio 2017 + Node.JS + TypeScript

Why node.js? https://www.toptal.com/nodejs/why-the-hell-would-i-use-node-js

Why typescript? https://www.typescriptlang.org/ , https://basarat.gitbooks.io/typescript/docs/why-typescript.html

Why Visual Studio? https://www.visualstudio.com/vs/node-js/

Below I explain how to install and configure all these things together.

1.     Install Visual Studio 2017

Install Visual Studio 2017 (Community Edition is free for personal use!): https://www.visualstudio.com/free-developer-offers/

Select the Node.js development option during the setup:

VSSetupNode

2.     Install Node.js and NPM

Download node from https://nodejs.org/en/download/

Update npm by the following command in the command line:


npm install npm@latest -g

Continue reading

Service scalability, redundancy and load-balancing options

Introduction

Imagine you have developed a service. Any service – Web Service, Web API, WCF, UDP – technology and protocol do not matter. Then your service should be used by other components of some system or project (I will call them “clients” here). In many cases running just single instance of your service will not be enough due to different reasons:

  1. Availability/redundancy. The whole system may fail if your single service instance fails. So, you will need to run multiple instances of your service on different servers. Some instances may be passive.
  2. Performance and load balancing. Single instance of your service may not be able to deal with all the requests it gets, and you will need to distribute the load between multiple active instances hosted on different servers. In other words, your service should be scalable.
  3. Both reasons 1 and 2.

In this post I will try to overview available options for running multiple instances of the same service, and I wish to have a design which covers all reasons from the list above –redundancy, load balancing, scalability, high availability. I will not use any special technologies or frameworks dedicated to this problem – just general ideas and plain old programming languages, databases and communication protocols.

The problems we meet here are obvious: if there are multiple services and multiple clients, somebody should tell the client what is the address for sending requests, somebody should take a decision which service instance will process a request, somebody should monitor the state of the services, somebody should solve concurrency conflicts between the services etc.

blog_scalableservices_0

So, let’s start with the options.

Continue reading

Android/Xamarin GPS Location Tracking

This short post is about the easiest way to get GPS Location Tracking with your Android Phone,  Xamarin and C#.

Imagine you have a navigation/tracking application and you need to get the GPS position of the device with real-time accuracy (and not periodically, each 5-15 minutes, like Google Location History does).

In this case you may find useful the following class:

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

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Locations;

namespace LocationTrackerTest
{
    /// <summary>
    /// Class provides GPS location.
    /// Note: Requires permission ACCESS_FINE_LOCATION.
    /// Usage: 
    ///   1. Create the class instance. 
    ///   2. Call InitializeLocationManager(). 
    ///   3. Check "CurrentLocation" when you wish or 
    ///      subscribe to "LocationChanged" event to be notified.
    ///   4. When you do not need it any more - call Dispose().
    /// </summary>
    public class GPSLocationTracker : Java.Lang.Object, ILocationListener, IDisposable
    {
        /// <summary>
        /// Current location
        /// </summary>
        public Location CurrentLocation { get; set; }

        /// <summary>
        /// Current location (if available) or status message if not available
        /// </summary>
        public string CurrentLocationString { get; set; }

        public Availability CurrentGPSProviderStatus = Availability.Available;

        /// <summary>
        /// Tracker Status - true if ok, false if no GPS location
        /// </summary>
        public bool IsGettingLocation { get; set; }

        /// <summary>
        /// True if GPS provider is enabled in settings, otherwise false
        /// </summary>
        public bool IsGPSProviderEnabled { get; set; }

        // Event handlers
        public event EventHandler<Location> LocationChanged;
        public event EventHandler GPSProviderDisabled;
        public event EventHandler GPSProviderEnabled;
        public event EventHandler<Availability> GPSStatusChanged;

        public LocationManager _locationManager = null;
        Context _context;
        bool _isGiveToastsOnStatusChanges;
        bool _isFirstLocationReported = false;

        // The minimum distance to change Updates in meters
        long _minDistanceChangeForUpdatesMeters = 10; // 10 meters

        // The minimum time between updates in milliseconds
        long _minTimeBetweenUpdatesMs = 1000 * 30; // 30 seconds

        public GPSLocationTracker(Context context, bool giveToastsOnStatusChanges = true, long minDistanceChangeForUpdatesMeters = 10, long minTimeBetweenUpdatesMs = 30000)
        {
            this._context = context;
            this._isGiveToastsOnStatusChanges = giveToastsOnStatusChanges;
            _minDistanceChangeForUpdatesMeters = minDistanceChangeForUpdatesMeters;
            _minTimeBetweenUpdatesMs = minTimeBetweenUpdatesMs;
            IsGettingLocation = false;
            IsGPSProviderEnabled = false;
        }

        /// <summary>
        /// Initialize location services and request getting location updates and events.
        /// Run this methid after construction of the class instance.
        /// Run it in the UI thread if you wish the GPS settings alert to be automatically displayed.
        /// </summary>
        public void InitializeLocationManager(bool isShowGPSSettingsAlert = true)
        {
            // Get location manager
            _locationManager = (LocationManager)_context.GetSystemService(Context.LocationService);

            // Check if GPS is enabled, If not - display alert with shortcut to GPS settings
            IsGPSProviderEnabled = _locationManager.IsProviderEnabled(LocationManager.GpsProvider);
            if (IsGPSProviderEnabled)
                CurrentGPSProviderStatus = Availability.Available;
            else
                CurrentGPSProviderStatus = Availability.OutOfService;
            if (!IsGPSProviderEnabled && isShowGPSSettingsAlert)
                ShowGPSSettingsAlert();

            // Subscibe to getting location updates with the desired treshold
            _locationManager.RequestLocationUpdates(LocationManager.GpsProvider, _minTimeBetweenUpdatesMs, _minDistanceChangeForUpdatesMeters, this);
            CurrentLocation = _locationManager.GetLastKnownLocation(LocationManager.GpsProvider);
        }

        /// <summary>
        /// Display GPS disabled alert with shortcut to GPS settings
        /// </summary>
        public void ShowGPSSettingsAlert()
        {
            // See http://stacktips.com/tutorials/xamarin/alertdialog-and-dialogfragment-example-in-xamarin-android

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(_context);

            // Setting Dialog Title
            alertDialog.SetTitle("GPS settings");

            // Setting Dialog Message
            alertDialog.SetMessage("GPS is not enabled. Do you want to go to settings menu?");

            // On pressing Settings button
            alertDialog.SetPositiveButton("Settings", (senderAlert, args) => {
                Intent intent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
                _context.StartActivity(intent);
            });

            // On pressing cancel button
            alertDialog.SetNegativeButton("Cancel", (senderAlert, args) => { });

            // Showing Alert Message (note - do it only on UI thread, or use Activity.RunOnUiThread method)
            Dialog dialog = alertDialog.Create();
            dialog.Show();
        }


        /// <summary>
        /// LocationListener will call this method when updates come from LocationManager
        /// </summary>
        /// <param name="location"></param>
        public void OnLocationChanged(Location location)
        {
            if (location == null)
            {
                CurrentLocationString = "No location";
                _isFirstLocationReported = false;
                IsGettingLocation = false;
                if (_isFirstLocationReported && _isGiveToastsOnStatusChanges)
                {   // if after we had location, we lost it and got null
                    Toast.MakeText(_context, String.Format("Location update: null", CurrentLocation.Latitude, CurrentLocation.Longitude), ToastLength.Short).Show();
                }
            }
            else
            {
                CurrentLocation = location;
                IsGettingLocation = true;
                CurrentLocationString = String.Format("{0}:{1}", CurrentLocation.Latitude, CurrentLocation.Longitude);
                if (!_isFirstLocationReported && _isGiveToastsOnStatusChanges)
                {
                    Toast.MakeText(_context, String.Format("Location update: {0}:{1}", CurrentLocation.Latitude, CurrentLocation.Longitude), ToastLength.Short).Show();
                    _isFirstLocationReported = true;
                }
            }
            // Fire event
            if (LocationChanged != null)
                LocationChanged(this, location);
        }

        public void OnProviderDisabled(string provider)
        {
            if (provider == LocationManager.GpsProvider)
            {
                if (_isGiveToastsOnStatusChanges)
                    Toast.MakeText(_context, "GPS provider disabled.", ToastLength.Short).Show();
                CurrentLocationString = "GPS provider disabled.";
                IsGettingLocation = false;
                _isFirstLocationReported = false;
                IsGPSProviderEnabled = false;
                // Fire event
                if (GPSProviderDisabled != null)
                    GPSProviderDisabled(this, null);
            }
        }

        public void OnProviderEnabled(string provider)
        {
            if (provider == LocationManager.GpsProvider)
            {
                if (_isGiveToastsOnStatusChanges)
                    Toast.MakeText(_context, "GPS provider enabled", ToastLength.Short).Show();
                CurrentLocationString = "GPS provider enabled.";
                _isFirstLocationReported = false;
                IsGPSProviderEnabled = false;
                // Fire event
                if (GPSProviderEnabled != null)
                    GPSProviderEnabled(this, null);
            }
        }

        public void OnStatusChanged(string provider, Availability status, Bundle extras)
        {
            if (provider == LocationManager.GpsProvider)
            {
                if (CurrentGPSProviderStatus != status)
                {
                    if (_isGiveToastsOnStatusChanges)
                        Toast.MakeText(_context, "GPS Status changed: " + status.ToString(), ToastLength.Short).Show();
                    CurrentLocationString = "GPS Status " + status.ToString();
                    CurrentGPSProviderStatus = status;
                    if (status != Availability.Available)
                    {
                        IsGettingLocation = false;
                        _isFirstLocationReported = false;
                    }
                    // Fire event
                    if (GPSStatusChanged != null)
                        GPSStatusChanged(this, status);
                }
            }
        }


        /// <summary>
        /// Stop location services and unsubscribe from getting events
        /// </summary>
        public void StopLocationManager()
        {
            if (_locationManager != null)
            {
                _locationManager.RemoveUpdates(this);
            }
        }

        public void Dispose()
        {
            StopLocationManager();
        }
    }
}

This class initializes the LocationManager, Checks if the GPS data provider is enabled (if not, it optionally displays a message box with shortcut to GPS settings), and starts listening to location updates with given threshold in meters and timeout.

To illustrate the usage of this class, I’ve created a sample and simple application which displays the GPS position from GPSLocationTracker class on the screen:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace LocationTrackerTest
{
    [Activity(Label = "LocationTrackerTest", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        GPSLocationTracker gpsLocationTracker = null;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Create and initialize the GPSLocationTracker,
            // subscribe to location changed event
            gpsLocationTracker = new GPSLocationTracker(this, true);
            gpsLocationTracker.InitializeLocationManager(true);
            gpsLocationTracker.LocationChanged += GpsLocationTracker_LocationChanged;
        }

        /// <summary>
        /// gpsLocationTracker.LocationChanged event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GpsLocationTracker_LocationChanged(object sender, Android.Locations.Location e)
        {
            // Just show current location in a text field
            TextView tv = FindViewById<TextView>(Resource.Id.txtLocation);
            tv.Text = gpsLocationTracker.CurrentLocationString;
        }
    }
}

There are just 3 lines of code required to initialize this class and subscribe to LocationChanged event. Then you need to create your LocationChanged handler and there perform all the actions you need – like update the position on the map, send the device location update to the server etc.

Note that you should add ACCESS_FINE_LOCATION permission to your application manifest:

androidmanifest

LinQ to Objects Performance Test

I had a discussion with my friend and colleague on LinQ to Objects and its usability and performance. Clearly in case of some simple conditions, the LinQ (especially its method syntax) may simplify your code. But what about performance – is it faster?

I’ll create a couple of tests to figure it out. I’ll query a collection of objects. Collection will contain 10,000,000 “Employee” class objects which will be generated automatically. Below is the code for the Employee class and collection generation method:

Continue reading

Run Processes Reliably (Process Watchdog Service)

Introduction

There are cases where you have one or multiple processes running on the computer and you need to ensure that these processes are running all the time and that they are restarted if they crash. And we are talking specifically about Windows OS.

Usually the scenario is that you have an application server which runs proxy server, mail server, self-hosted web services, web crawler – whatever application providing some API without GUI. And you need these applications to run all the time since the server startup.

The second scenario example is PC running in “kiosk” mode or presentation mode running GUI applications which should be executed on startup after automatic login and kept running, and restarted immediately when crashed.

Imagine also that your applications are developed as stand-alone EXE applications, and you do not wish or can’t convert them to Windows services.

So, the requirements for some tool which will help us in this situation are:

  • In scenario of server running applications without GUI, It must be able to start one or multiple applications with specified paths and command line arguments immediately after computer startup, without user interaction and user login (this way, in case of restart or power interruption, the server will reboot and your applications will be restarted).
  • In another scenario of “kiosk” mode or presentation mode PC running GUI applications, it must be able to run on startup after automatic login.
  • In both scenarios, it must monitor all the started applications and restart each one of them if it exits unexpectedly as soon as possible.

Continue reading

Handling Corrupted State Exceptions (e.g. StackOverflow or AccessViolation) in C#

Application exceptions are handled by your code, usually according to the Exception handling best practices – MSDN – which means that you catch the exception at some level of your application, gracefully finish failed tasks, write to log, give message to the user and continue running.

It is good practice also to create an application-level unhandled exception handler, for example AppDomain.UnhandledExceptionHandler which will catch all exceptions you may miss on other levels of your application.

Let’s see an example (console application, C#):

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Console.WriteLine("Now we will simulate regular exception.");
            try
            {
                int i = 1;
                i--;
                int j = 1 / i;
            }
            catch(Exception ex)
            {
                Console.WriteLine("Exception occured: "+ex.Message);
            }
            Console.WriteLine("The execution continues.");
            Console.ReadKey();
        }
    } 

catch1

We see that the try/catch block successfully caught an exception in managed code.

But if our .NET code performs some unmanaged resources handling, marshaling or PInvoke to unmanaged code, we may get another type of exceptions like StackOverflowException or AccessViolationException (called Corrupted State Exceptions, Article, CSE ) which are not handled by default by regular .NET exception handlers.

Continue reading