Back to Basics #001

Welcome to first post on ‘Back to basics’. Yeah, as you guessed right, this series attempt to check minor differences in our understanding of basic concepts.

Predict the output of following.


public class FirstType
{

}
public class SecondType
{
private FirstType _mType;

public static implicit operator FirstType(SecondType t)
{
return t._mType;
}
}

static void Main(string[] args)
{
object objectInstance = new SecondType();

FirstType attempt1 = objectInstance as FirstType;
if (attempt1 != null)
{
Console.WriteLine("'As' Conversion Succeeded");
}
else
{
Console.WriteLine("'As' Conversion Failed");
}

try
{
FirstType attempt2 = (FirstType)objectInstance;
Console.WriteLine("Cast Succeeded");
}
catch (Exception)
{
Console.WriteLine("Cast Failed");
}

}

Ideally, One would expect the first attempt to fail, but would feel the second would succeed considering we have implemented implicit conversion. But unfortunately, that’s not the case. The output would be

‘As’ Conversion Failed.
Cast Failed.

The reason for this is that, the compiler generates code based on the compile time type of the objectInstance, which in this case is ‘object’. It then checks if there is any conversion declared to convert object to FirstType, which doesn’t exist. The compiler doesn’t check the type of the objectInstance during runtime, which results in the above output.

The reason for this is that, the compiler generates code based on the compile time type of the objectInstance, which in this case is ‘object’. It then checks if there is any conversion declared to convert object to FirstType, which doesn’t exist. The compiler doesn’t check the type of the objectInstance during runtime, which results in the above output.

Advertisements

Revamping Interview Strategies.

One of the things which bothers me with the current interview process relevant in most companies if the focus on measuring candidate’s capabilities on the basis of his knowledge of particular sub-technology. There might be wrong with this approach, but what if the Candidate is a strong programmer who unfortunately hadn’t got the opportunity to work on the particular technology/framework ?

Programming or analytical skills, according to me, is something which is heart and soul of a software programmer. He might or might not have worked in a particular technology, but that doesn’t mean he cann’t do good when given a chance. After all, none has worked in every technology under sun. What matters is his ability to solve a problem.

Recently I saw an article in Medium and was quite fascinated by the thought. What if ask something very familiar to candidate, but prompting him to think outside the box.

For example, counting the odd numbers in an array of integers or checking if a given day is weekday or weekend is something we would have done when we learn the first steps in programming. What if we ask the candidate to accomplish the same without any form of conditional operators ?

Now that would get his thought process reset. He would have think, which is more important than remembering something and answering. So, revisit your interview strategies and allow the candidate on put on his thinking cap on

Here is my 2 cents on accomplishing the above mentioned questions in C#

public int CountNonConditional(int[] Arr)
{
     var sum = 0;
     Array.ForEach(Arr, (x) => sum+= x % 2);
     return sum;
}
public bool IsWeekDayNonConditional(DayOfWeek Day)
{
     return Convert.ToBoolean(((int)Day % 6));
}

MongoDb 002 : CRUD – Part 1

We will continue with our exploration of MongoDb in this second part of tutorial, working our CRUD examples.

Let’s beging with the ‘C’. In order to create a document, you would need to use, as you can guess, the Insert command.

db.subject.insert({"title":"maths"})

Notice that we are using a new collection named subject here. MongoDb would automatically create the collection if it doesn’t exist. As you would have rightly guessed by now, we would be relying on JSON for passing any parameters for commands.

Let’s now do the same using C#. The first step you need to do is to install the MongoDB.Driver official Nuget package. Once the nuget is installed for our project, let’s start pushing some code in to our collection.

Following Commands gives us access to

string ConnectionString = "mongodb://localhost:27017";
var Client = new MongoClient(ConnectionString);
var Database = Client.GetDatabase("testdb");

The next step is to create the Data Structure which would be serialized and pushed into the DB.

public class SubjectEntity
{
public ObjectId Id { get; set; }

[BsonElement("title")]
public string Title { get; set; }
}

If you look closely, I have decorated each of the elements with BsonElement Attribute. This tells the compiler the literal it should use as key while creating the JSON document. Also if you notice, I have a property called Id of type ObjectId. This is a special type which would hold the unique ID which would be generated by MongoDb. This value is similiar to a GUID and unlike relational Db, we cannot use an autoincrement key, unless we do that bit of logic within our C# code. Honestly I wouldn’t recommend that.

Since I would like to use the ID generated by MongoDb, I have not decorated the Id field with BsonElement attribute, however I would still need in my Data Structure so that I could use it while retrieving data.

Okay, fine then. Let’s push some data to the Db now.

var subjectCollection = Database.GetCollection("subject");
subjectCollection .InsertOne(SubjectEntityInstance);

The above code inserts a object of type SubjectEntity to the Db. Once executed, hit our Console again and check if the Document is added to the SubjectCollection using the find command we learned in the first part of tutorial. Looks good right ?

Let’s try finding it with a find command from C# now.

var nameFilter = Builders.Filter
.Eq(x => x.Title,'maths');
var result = subjectCollection
.FindSync(nameFilter).First();

As you can understand from the code, we are first creating an instance of the filter we would like to use. In this case, we are using an Equality Filter (Subject title should be “maths”). We finally pass the filter to our FindSync Method.

We would be exploring part two of CRUD, Update and Delete in the second part of the tutorial.

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

MongoDb 001 : 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.