100 Days Of Code

Last night I read about the 100DaysOfCode by Alexander Kallaway and I was pretty interested with the concept. So here is the guidelines I would be following for my challenge.

  • I will dedicate atleast one hour for Side Projects every day.
  • This would be outside my core work.
  • This will not include any time I spend in reading tutorials.
  • At end of the day’s effort, I would tweet my updates with hashtag ‘#100DaysOfCode ‘ under my handle anuviswan.
  • I am not allowed to take any break from this 100 day challenge, unless it is unavoidable as I am away from my system whole day.
  • The code base would be stored in either my public GIT account or personal VS Online account depeding on the side project am working.
Advertisements

Private Transport to Personalized Transport

Living in an urban area and planning to take your car out to another corner of town on an evening? What would the first that cross your mind?

Where do I Park my car!!!

Quite honestly that’s what many of us think while taking out car these days. The urban landscape has changed so much over the recent years that even the parking space provided by malls are flooding.  Entering this scenario are two different, yet connected concepts which could change the way people look at transportation. 

The recent surge in investment and interest in the area of autonomous cars are surely gathering momentum. Players like Tesla and Alphabet are not leaving any stones unturned in their quest to rule the autonomous car market. Alphabet recently hired Tesla’s former head of hardware engineering to lead Waymo’s initiatives. It wouldn’t far when fully automated cars ply the public roads.

On other side of the coin are the initiatives by Companies such as Uber promoting online taxi service that never quite rests, on other words require a parking lot. They ply 24×7,literally living on road. Their large fleet of cars allows them to attend customer call within minutes.

Now if we were to step back a bit and wonder why many depend on personal transport over public transport, there are many possibilities we could think of.

First, the ability to reach doorstep of your destination, and second, need for private space which public transport doesn’t provide. Taxis and services like Uber provide solution to the former, but falls short ever so slightly on the latter. The stranger in this scenario would be the driver himself.

This is where autonomous cars can join in provide you a completely personalized transportation service. In fact, Uber on its part has already started investing on autonomous cars.

May be people might still want to use their private cars, but it does open up possibilities of a tomorrow that relies on driver-less personalized public transportation that doesn’t require your to scratch your head over parking.

API based Custom FormValidation using SemanticUI/Jquery

In the last post, we discussed on how to implement form validation and subsequent submit using the Semantic UI and JQuery. In this follow up post, we discuss how we can enhance the validation capabilities further, by having a custom validation that depends on an external API call.

For the sake of example, let’s focus on an mock User Sign Up page, where we would be checking if the username exists prior to form submit.

Let’s write down our basic form first.

<form class="ui form" method='post' id="RegisterUser">
  <h4 class="ui dividing header">User Sign Up</h4>
  <div class="field">
    <div class="two fields">
      <div class="eight wide field">
        <label>UserName</label>
        <input type="text" placeholder="Username" id="username">
      </div>
    </div>
  </div>
  <button class="ui button" tabindex="0">Sign Up</button>
  <div class="ui hidden negative message" id="formresult"></div>
  <div class="ui error message" id="formvalidation"></div>
</form>

Now, let’s create our Validation Script.

var formvalidationrules = {
    on: 'submit',
    fields: {
      username: {
        identifier: 'username',
        rules: [{
          type: 'custom',
          prompt: 'username already exists'
        }]
      },
    },
    onSuccess: function(event) {
      event.preventDefault();
    }
  };

  $('#RegisterUser').form(formvalidationrules);

As you can see, the rule type has been specified as ‘custom’. The next obvious task is to write down the method to do the custom validation itself.

$.fn.form.settings.rules.custom = function() {
    var result;
    $.ajax({
      type: 'POST',
      url: '/echo/html/',
      async: false,
      data: {
        'html': $('#username').val()
      },
      success: function(data) {
        result = !(data == 'test');

      },
    });
    return result;

  };

Couple of things to note here.
a) The rule method has been added to form.settings.rules.
b) Now this is very important, your ajax calls needs to be synchronous.

That’s it, you are ready to roll. Check out the script in action in Fiddle Link

Workaround for MySql 5.7 EF DbFirst Issue

Anyone working on .Net application with MySql 5.7 and EF in Db First Approach would have come across what is an officially confirmed bug.  This bug rises when you attempt to generate/update your Entity Model after changes to the Database.

“Unable to generate the model because of the following exception: ‘System.Data.StrongTypingException: The value for column ‘IsPrimaryKey’ in table ‘TableDetails’ is DBNull. —> System.InvalidCastException:”

The workaround you need to do to fix this one

  1. Open your Workbench and execute following commands on your Db.
set global optimizer_switch='derived_merge=off';
set optimizer_switch='derived_merge=off';
  1. Close your workbench ( you might have to restart your visual studio as well ).
  2. Generate/Update your model.
That should work.

Form Validation and Submit using Semantic UI and JQuery

Bootstrap, despite all the effort to make it easily understandable, always relied heavily on its short hand notations for css classes. This seemed okay, until Semantic UI entered the race with its near perfect usage of natural language. The fact that it is well integrated with jQuery makes it a good choice for web developers.

One of the most common tasks in any web development has to do with form. The following code illustrates how to validate the form and submit it using the Semantic UI APIs.

 

                <form class="ui large form" method="POST" role="form" id="ValidateUser">
                    <section class="ui stacked segment">
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="user icon"></i>
                                @Html.TextBoxFor(a => a.UserName, new { placeholder = "UserName",id="username" })
                                @Html.ValidationMessageFor(a => a.UserName)
                            </div>
                        </div>
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="lock icon"></i>
                                @Html.PasswordFor(a => a.Password, new { placeholder = "Password",id="password" })
                                @Html.ValidationMessageFor(a => a.Password)
                            </div>
                        </div>

                        <input id="submitbutton" class="ui submit fluid large green button" type="submit" value="Login"/> 
                        <!-- <div class="ui blue submit button">Submit</div> -->
                        <div class="ui hidden negative message" id="formresult"></div>
                        <div class="ui error message" id="formvalidation"></div>
                    </section>
                </form>
$(document).ready(function () {

            var urllink = '@Url.Action("Login", "Validation")';


            $('#ValidateUser').form(
                                     {
                                         on: 'blur',
                                         fields: {
                                             username: {
                                                 identifier: 'username',
                                                 rules: [{
                                                     type: 'empty',
                                                     prompt: 'Username cannot be empty'
                                                 }]
                                             },
                                             password: {
                                                 identifier: 'password',
                                                 rules: [{
                                                     type: 'empty',
                                                     prompt: 'Password cannot be emtpy'
                                                 }]
                                             }
                                         },
                                         onSuccess: function (event) {
                                             $('#formresult').hide();
                                             $('#formresult').text('');
                                             event.preventDefault();
                                             return false;
                                         }

                                     }
                                   )
                                 .api({
                                     url: urllink,
                                     method:'POST',
                                     serializeForm: true,
                                     data: new FormData(this),
                                     onSuccess: function (result) {
                                        $('#formresult').show();
                                        if (result.Success) {
                                            window.location = "/Dashboard/Dashboard";
                                        }
                                        else {

                                            $('#formresult').append(result.Msg);
                                        }
                                        return false;
                                    }
                    });


        });

Adapter Pattern

There is already a large amount of literature on the Internet which discusses Adapter Pattern. However, the purpose of article is to showcase the implementations of the Adapter Pattern, rather than discussing the application of the pattern. In this post, adapter class is implemented using

1. Inheritance
2. Dependency Injection
3. Generics

Consider your old legacy code, which has a single method, GetEmployeeList.

public interface IHRSoftware
    {
        List<string> GetEmployeeNameList();
    }
    public class HRSoftware : IHRSoftware
    {
        public List<string> GetEmployeeNameList()
        {
            return new List<string>() { "Jia", "Anu", "Sreena" };
        }
    }

Client, consumes the class as follows.

            IHRSoftware hrsoft = new HRSoftware();
            foreach (var item in hrsoft.GetEmployeeNameList())
            {
                Console.WriteLine(item);
            }

Now, it so happened that the Client has gone through an overhaul and is now looking to use a new contract (interface), namely INewAgeSoftware, which exposes a property EmployeeList, replacing the GetEmployeeNameList Method. The interface declaration is as shown below.

    public interface INewAgeHRSoftware
    {
        List<string> EmployeeList { get;  }
    }

You however, would like to use your old existing code, without actually going ahead and making the changes in your legacy code. This is where adapter pattern come in handy. Following are different implementations of Adapter Class

1. Using Inheritance.

    public class AdapterWithInheritence : HRSoftware, INewAgeHRSoftware
    {
       
        public List<string> EmployeeList
        {
            get
            {
                return this.GetEmployeeNameList();
            }
        }
    }

2. Using Dependency Injection

    public class AdapterWithDI : INewAgeHRSoftware
    {
        private IHRSoftware _HRInstance;
        public AdapterWithDI(IHRSoftware HRSoftInstance)
        {
            _HRInstance = HRSoftInstance;
        }
        public List<string> EmployeeList
        {
            get
            {
                return _HRInstance.GetEmployeeNameList();
            }
        }
    }

3. And Finally, using Generics

    public class AdapterWithGenerics<T> : INewAgeHRSoftware where T : HRSoftware
    {
        private T _HRInstance;
        public AdapterWithGenerics(T Instance)
        {
            _HRInstance = Instance;
        }
      
        public List<string> EmployeeList
        {
            get
            {
                return _HRInstance.GetEmployeeNameList();
            }
        }
    }

Your new Client class would now look as follows

 Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via Inheritence");
            INewAgeHRSoftware newhrsoftInheritence = new AdapterWithInheritence();
            foreach (var item in newhrsoftInheritence.EmployeeList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via DI");
            INewAgeHRSoftware newhrsoftDI = new AdapterWithDI(new HRSoftware());
            foreach (var item in newhrsoftInheritence.EmployeeList)
            {
                Console.WriteLine(item);
            }
           
           
            Console.WriteLine("Fetching from NewAgeHRSoftware - Adapter via Generics");
            INewAgeHRSoftware newhrsoftGenerics= new AdapterWithGenerics<HRSoftware>(new HRSoftware());
            foreach (var item in newhrsoftGenerics.EmployeeList)
            {
                Console.WriteLine(item);
            }

360 Degree Evaluation

360 Degree Feedback/Review System is a much abused term in many companies these days. While many Organizations and Managers effectively use the ‘jargon’ on a day to day basis, it makes me wonder how many actually perform a complete 360 Degree Review System, particularly in Performance Appraisals.

Ideally, an effective 360 Degree Review System should include 6 major parties

  1. Senior Management
  2. Immediate Supervisor
  3. Peers
  4. Subordinates.
  5. Clients
  6. Self.

Together, this 6 parties provide a complete 360 Degree view of an employees performance. It is quite disheartening to see some of the companies that boosts of a 360 Degree Performance Review System, often, conveniently forgets some of the major links in the chain, including Peers and Subordinates, and while some might even forget taking Immediate Supervisors feedbacks. What it leads to is some of the better traits of employees gets unnoticed.

Instead, if the companies were to focus on all the 6 parties, there is whole lot they could achieve. There are certain traits or skills which is more visible to certain groups more than others and that’s what makes the 360 Degree Evaluation such an effective practice if done well.

For example, Peers are in better position than anyone else to access a coworker’s skills such as team work and communication. They also probably know more about the person’s knowledge due to day to day interaction at work. In fact, studies reveal that peers are more often than not excellent predictors of future performances.

On other hand, the immediate supervisor would be an effective observer for accessing a wide range of skills including Job Knowledge, Approach to work and Quality of work. This might not be as effectively observable for members of Senior Management, whose vision would be more on metrics such as On Time Delivery Index and Quality Metrics.

Similarly, a subordinate would be in the best position to review a supervisor’s leadership and mentoring skills. Most often than not, it is the supervisor’s management skills (or lack of it) which makes the team member either an active participator or pushes him to resign.

Studies also reveal that there is a direct relation between on for how long the reviewers know the person and the rating they give. It has been observed that if the reviewer knows the employee for 1-3 years, the probability of the rating is being more accurate is high. Whereas, the chances of favoritism or personal affection influencing the review increasing as the years go by. On other hand, a person whom the reviewer knows for less than an year would not be in a position to understand the skills correctly. In short, the reviewer should have known the employee long enough to go past first impression and not long enough to generalize favorably.

One of the points held against 360 Degree Evaluation is how the employee could manipulate the feedbacks and conflicting opinions creating doubts on the accuracy. However, if practiced well, a confidential 360 Degree Evaluation program with weighted rating according to role played by the reviewer in the cycle would work much better than any other system. The key to success lies to in the companies approaching the method as a tool for positive feedback, rather than an instrument to criticize the employee.