MongoDb : Basic Commands

Before we actually get into MongoDb, let’s begin by importing a Test Db. You can access the JSON file here. Once you have downloaded the file, use following command to import the document into mongodb.

mongoimport --db testdb --collection students --drop --students.json

Let’s break it down, the command tells you to import a file students.json into a database called testdb and collection called students. Let’s go ahead verify if our import is good.

show dbs
use students
show collections

We first checked if the db named students has been created by checking the list of dbs. ‘show dbs’ command displays list of all dbs in the server. We followed it up with ‘use students’ command, which is similiar to the ‘use ‘ command in MySql. Finally, we issued ‘show collection’ command to view the collections in the db. Remember collections are analogous to tables in relational database.

We will now go ahead check out data. In relational database, data is saved as a row in the table. When it comes to Nosql databases, each row is represented as a document.
To view contents of a collection, we issue a find command
db..find()
In our case, it would be

db.students.find()

This would show our 3 documents within the collection. Let’s explore the find command a bit. We could give a specific search filter as arguement, in case we need to find a particular document, similiar to the ‘where’ condition in relational database. Instead of the customary “=” syntax, MongoDb relies on JSON for passing the argument.

db.students.find({"name":"jia anu"})

In case you want to pass more than one arguement, things don’t change much. Yes, you guess right, you pass more data in json.

db.students.find({"name":"jia anu","age":1})

If we need to search use a comparison operator ‘greater than’ or ‘less than’, you would need to use the ‘$gte and $lte commands.
Let’s go ahead and issue a command, say, we need to find all students who age is ‘less than or equal to 1’

db.students.find({"name":"jia anu","age":{$lte:1}})

A comprehensive list of comparison operator can be found in here

The complete list of beginners guide in this series can be found in here

Circular Button Using Xamarin (Custom Renderer)

The shift to appcompat has affected Android developers, while developing cross platform xamarin application. The first difference you would notice is the buttons are no longer having rounded corner despite assigning the radius. That is a define roadblock when you consider you need a perfect circular button.

However things aren’t actually that bad as it sounds to be. You cannot discount the power custom renderering brings in. What we need to do is write a custom Renderer and ensure shape is set to Oval. Let’s get hands dirty and do some coding.

class CircularButtonRender : Xamarin.Forms.Platform.Android.ButtonRenderer
{
private GradientDrawable _NormalState, _PressedState;

protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);

if (Control != null)
{
var button = e.NewElement;

// Create a drawable for the button's normal state
_NormalState = new Android.Graphics.Drawables.GradientDrawable();
_NormalState.SetColor(button.BackgroundColor.ToAndroid());
_NormalState.SetStroke((int)button.BorderRadius, button.BorderColor.ToAndroid());
_NormalState.SetShape(ShapeType.Oval);

_PressedState = new Android.Graphics.Drawables.GradientDrawable();
_PressedState.SetColor(button.BackgroundColor.ToAndroid());
_PressedState.SetStroke((int)button.BorderRadius, button.BorderColor.ToAndroid());
_PressedState.SetShape(ShapeType.Oval);

// Add the drawables to a state list and assign the state list to the button
var sld = new StateListDrawable();
sld.AddState(new int[] { Android.Resource.Attribute.StatePressed }, _PressedState);
sld.AddState(new int[] { }, _NormalState);
Control.SetBackground(sld);
}
}

}

 The entire source can be found in my Git project here [GitHub].

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.

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.