Checklist For Xamarin Forms Development

Here’s a list to help you get started with cross-platform mobile app development using Xamarin Forms.

  1. Xamarin
  2. Visual Studio 2015
  3. Android SDK
  4. Windows 10 OS
    1. While you can work with Windows 8 as well, you will need Windows 10 operating system if you are going to develop for Windows 10 Universal App.
  5. Mac with Xcode and Xamarin installed
    1. Again this is not a mandatory to get started with Xamarin but without a Mac you will not be able to develop applications for iPhone.

If you have all the items on this list installed/setup then you are ready to get started with Xamarin Forms Development!

Upwork Sucks Big Time!

I am not much of a hater and I hardly say these kind of stuff about anyone (specially in public), but this time I have to make an exception.

Yes guys, like the title says:

UPWORK sucks !!

Yes www.upwork.com, the freelancing site for freelancers, just sucks!

Why?

Ok the main reason for my hatred is this email that I got from them today:

Hello Sovit,

We are contacting you to let you know we have suspended your access to Upwork indefinitely.

Our decision is based on a careful review and the fact that you have submitted a high number of proposals for jobs on our site without many contracts or earnings. Unfortunately, this means the jobs posted by clients are not a good match for your skills.

I know this news is likely disappointing to you. But our goal at Upwork is to enable freelancers to successfully connect and collaborate with clients who need their skills and expertise. Unfortunately, this means we must part ways with freelancers whose skills are not in demand in our marketplace.

If you want to appeal this decision, you can email us at marketplace-appeals@upwork.com. Please note each case will be manually reviewed by our Trust & Safety team to decide if your account can be reinstated.

Please know we don’t make decisions like these lightly and wish you the best of luck in your future endeavors.

Regards,

Upwork Trust & Safety

At first when I saw the email, I just took it casually because to me Upwork had already lost its charm because of their high commission rate that they charge with Freelancers and almost close to impossible possibility of landing a job there because of the overly crowded competition.

But as I thought about the absurdity of their reason and unprofessional action taken from their side I just couldn’t take it.

First of all, Upwork has never stated any such policies regarding account getting suspended/deactivated. I have been using Upwork for over a year now and I haven’t seen any Disclaimers like this one.

If there were policies like this where too many proposals could lead to user being kicked out from Upwork, why did they have maximum number of allowed proposals to be 30 for a month? Does it make sense?

I mean on one hand they give freelancers to apply up to maximum of 30 jobs and on the other hand if they do, they get kicked out from the site?

Furthermore, given the amount of competition at Upwork to get any single project, freelancers are bound to apply to more than one project at once. Now if they aren’t lucky enough they are all surely to get their accounts deactivated isn’t it?

You don’t trust me?

Well, either you have never been to Upwork or you are probably the CEO at Upwork.

Anyways, why don’t you go ahead and read the comments from 449 other Freelancers (this number is as of today and probably is growing exponentially every minute) who are simply pissed with Upwork then you will know it for yourself. Here’s a link to a post by someone who completely agrees with me and have similar thoughts about Upwork and also have a growing number of complaints on the comments section for Upwork.

Conclusion?

UPWORK sucks !!

And they better authorize me the payments for the work that I previously done at Upwork which I haven’t cashed yet.

SQL: String Format Function

Here’s a handy SQL function that allows to insert string(s) inside a larger string. This function is similar to String.Format() function in C#.

Typical Usage:

Have a string like below:

%s is a. %s and %s does %s

with as many ” %s ” as required to dynamically insert values.

Insert desired string objects using the function.

SQL Function


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION DBO.FN_SPRINTF
(
@STRING VARCHAR(MAX),
@PARAMS VARCHAR(MAX),
@PARAM_SEPARATOR CHAR(1) = ','
)
RETURNS VARCHAR(MAX)
AS
BEGIN

DECLARE @P VARCHAR(MAX)
DECLARE @PARAM_LEN INT

SET @PARAMS = @PARAMS + @PARAM_SEPARATOR
SET @PARAM_LEN = LEN(@PARAMS)
WHILE NOT @PARAMS = ''
BEGIN
SET @P = LEFT(@PARAMS+@PARAM_SEPARATOR, CHARINDEX(@PARAM_SEPARATOR, @PARAMS)-1)
SET @STRING = STUFF(@STRING, CHARINDEX('%S', @STRING), 2, @P)
SET @PARAMS = SUBSTRING(@PARAMS, LEN(@P)+2, @PARAM_LEN)
END
RETURN @STRING

END

The function has three required parameters:

  1. @STRING VARCHAR(MAX) : This is the main string to format
  2. @PARAMS VARCHAR(MAX) : List of objects to insert
  3. @PARAM_SEPARATOR CHAR(1)  : Identifier to parameter separator

Demo:


declare @test varchar(400)

select @test = [dbo].[FN_SPRINTF] ('I am %s and you are %s', '1,0', ',') --param separator ','

print @test -- result: I am 1 and you are 0

select @test = [dbo].[FN_SPRINTF] ('I am %s and you are %s', '1#0', '#') --param separator '#'

print @test -- result: I am 1 and you are 0

Reducing Cyclomatic Complexity Using Delegates

In the previous post we looked at what Cyclomatic Complexity is and why it is important to write programs with low Cyclomatic Complexity. Here I would like to show an example of reducing Cyclomatic Complexity with the use of Delegates.

This post is going to be extremely code intensive so buckle up guys!

Let’s start.

Say we have a few Math functions as below:


private static void Add(int x, int y)
{

}

private static void Subtract(int x, int y)
{

}

private static void Divide(int x, int y)
{

}

private static void Multiply(int x, int y)
{

}

And based on our user’s input, we would like to make proper requests to these methods:


private void Execute()
{
Console.WriteLine("Basic Math Operations");

Console.WriteLine("Enter value 1: ");
var x = Console.ReadLine();

Console.WriteLine("Enter value 2: ");
var y = Console.ReadLine();

Console.WriteLine("Enter operation type: ");
Console.WriteLine("Type A for Add, S for Subtract, D for Divide, M for multiply");

var operationRequested = Console.ReadLine();

if (operationRequested != null)
{
switch (operationRequested.ToUpper())
{
case "A":

break;
case "S":

break;
case "D":

break;
case "M":

break;
}
}
}

This “Execute” function already has Cyclomatic Complexity of 6 because of the 4 switch statements and 1 if condition.

Let’s add some more complexities to this code now.

First to check whether user inputs are proper data type of integer or not I have introduced validation “IsNumeric” which gets executed once.

I have also introduced another validation to check whether user is authorized to make a request or not with “IsUserAuthorized“. This has to be called for each switch case scenario.

So, our code looks like this:


private static void Execute()
{
Console.WriteLine("Basic Math Operations");

Console.WriteLine("Enter value 1: ");
var x = Console.ReadLine();

Console.WriteLine("Enter value 2: ");
var y = Console.ReadLine();

if (!IsNumeric(x) || !IsNumeric(y))
{
Console.WriteLine("Error!! Please enter integer values");
Execute();
}

Console.WriteLine("Enter operation type: ");
Console.WriteLine("Type A for Add, S for Subtract, D for Divide, M for multiply");

var operationRequested = Console.ReadLine();

if (operationRequested != null)
{
switch (operationRequested.ToUpper())
{
case "A":
if (IsUserAuthorized("A"))
{
Add(Convert.ToInt32(x), Convert.ToInt32(y));
}
else
{
Console.WriteLine("User not authorized");
}
break;
case "S":
if (IsUserAuthorized("S"))
{
Add(Convert.ToInt32(x), Convert.ToInt32(y));
}
else
{
Console.WriteLine("User not authorized");
}
break;
case "D":
if (IsUserAuthorized("D"))
{
Add(Convert.ToInt32(x), Convert.ToInt32(y));
}
else
{
Console.WriteLine("User not authorized");
}
break;
case "M":
if (IsUserAuthorized("M"))
{
Add(Convert.ToInt32(x), Convert.ToInt32(y));
}
else
{
Console.WriteLine("User not authorized");
}
break;
}
}
}

These additions have increased the Cyclomatic Complexity level for our code to 12! If we had more switch statements, the complexity would have grown much more higher.

Let’s try to bring down the complexity with the use of Delegates now.

As per MSDN,

“A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.”

Basically, a delegate allows us to pass a method as a parameter to another function which is very useful as we can see below:

Since all of our math functions have same signature, we can create a delegate for them like this:


private delegate void HandleRequest(int x, int y);

Next, let’s add a generic request handler function:


private static void CallRequestHandler(HandleRequest request, string requestType, int x, int y)
{
if (IsUserAuthorized(requestType))
{
request(x, y);
}
else
{
Console.WriteLine("User not authorized");
}
}

The “CallRequestHandler” takes a delegate and request type along with “x” and “y” values as parameters for executing the user requests.

Now all we need to do is use this function in our switch statements by passing proper Math functions as parameters:


switch (operationRequested.ToUpper())
{
case "A":
CallRequestHandler(Add, operationRequested.ToUpper(), Convert.ToInt32(x), Convert.ToInt32(y));
break;
case "S":
CallRequestHandler(Subtract, operationRequested.ToUpper(), Convert.ToInt32(x), Convert.ToInt32(y));
break;
case "D":
CallRequestHandler(Divide, operationRequested.ToUpper(), Convert.ToInt32(x), Convert.ToInt32(y));
break;
case "M":
CallRequestHandler(Multiply, operationRequested.ToUpper(), Convert.ToInt32(x), Convert.ToInt32(y));
break;
}

This drops down the Cyclomatic Complexity of the Execute function to 8 from 12.

Benefit? We are left with much cleaner and easily testable code!

Alright. That’s about it for this post. I hope you guys found it useful and hope to see you incorporate this kind of practice on your coding.

Please pass the comments/feedback/queries as comments below.

Thanks!

Cyclomatic Complexity

Cyclomatic Complexity is a software metric used to calculate the complexity of a program.

It is a measure of number of possible use case flows for a given program’s source code and is directly dependent upon the number of control flow statements (if/else statements and switch cases) within the code.

For example, a method with no control flow statements would have Cyclomatic Complexity  value of 1.

Cyclomatic Value as calculated by Visual Studio for a method that has no control flow statements:

And if we add one control flow statement, the Cyclomatic Complexity value will increase by 1.


private static void Divide(int x, int y)
{
if (x > y)
{

}
else
{

}
}

The code above has Cyclomatic Complexity of 2.

Basically, the Cyclomatic Complexity tells us how much complex our code is.

Since the more complex a code is, the more difficult it becomes to write a Test Case and validate it and so the higher value for Cyclomatic Complexity is usually associated with higher error prone code.

Hence, it is generally considered a good practice for software developers to write programs with low Cyclomatic Complexity.

Scraping Data From Wikipedia

Web Scraping Data For Hollywood Actors/Actresses Info

A friend of mine and I were discussing about the divorce rate/trends of Hollywood actors. Basically she was claiming that most of the actors have multiple wives and have gone through divorce in Hollywood. I was not so much in agreement and so came this project.

I created a project using Scrapy, a web scraping framework in Python to browse through each actors/actresses wiki link and look up info about their marital statuses.

Just for fun only 🙂

Here’s the link to the project codes if anyone else is interested in scraping and getting similar data from wikipedia.

Git

Do let me know if you are interested and need help in running the scripts.

Wonderful Opportunity for Software Engineers around the world

Are you ready to work as a SQL Developer?

A SQL Developer is responsible for managing data in a relational database. Database Providers like Microsoft, Oracle and MySql have their own IDE for managing data. For example Microsoft has SQL Server Management Studio for this purpose and Oracle has Oracle Developer Studio. A SQL Developer makes use of these IDEs for managing data.

Today I would like to list down the most common tasks that every SQL Developer must be familiar with as these will often come up as a requirement in the course of their day to day to work. This list will also serve as a guideline for anyone who wishes to advance their career towards becoming a SQL Developer.

In no particular order, here’s the list of tasks:

  1. Connecting to different SQL Servers using Windows and SQL Server Authentication.
  2. Creating  new databases in many different ways.
  3. Backing up and restoring databases.
  4. Designing and Normalizing Tables as per need.
  5. Using Primary Keys, Identity Columns and Foreign Keys for table creation.
  6. Altering Tables and Columns.
  7. Properly using Data Types and Column Size Limits.
  8. Writing basic to advanced level queries for SELECT, UPDATE, INSERT and DELETE.
  9. Writing table JOIN statements.
  10. Filtering Rows using WHERE clauses and JOIN statements.
  11. String manipulation using functions like Replace, Stuff, Trim and Substring.
  12. Creating tables on the fly.
  13. Using Cursors for looping.
  14. Writing Stored Procedures.
  15. Writing Functions.
  16. Writing Triggers.
  17. Using Linked Servers.
  18. Adding Indexes on tables.
  19. Using aggregator functions like Sum, Count, Group By, Order By, Row_Number and Distinct.
  20. Accessing table and column information across databases using Information_Schema.
  21. Generating Scripts to re-create database objects like tables and functions.
  22. Importing Data from external sources (mainly csv files sand excel sheets).
  23. Creating and authorizing  Database Users.

Note: Many of these tasks can be completed in two different ways i.e. either using the GUI or using Structured Query Language.

Using the GUI

Writing Queries

While it may be easier to operate through a User Interface for a newbie as he doesn’t have to remember the necessary queries, but on the long run it is better and also important to be fluent in performing these tasks writing queries.

Once you get the hang of it, you will find that writing query is more easier and faster than operating through UI as you no longer have to worry about where a particular function is located to perform a task. You just have to write the query on the query editor window.

Conclusion

The intention for this post was to identify the common operations that a SQL Developer must be fluent with in order to work in any professional environment. While this is not an an inclusive list of tasks and I may have left out a few other essential tasks, but nevertheless, if you are familiar with the tasks listed above, surely you can call yourself a SQL Developer ;).

Notes on Spring.NET DAO Code Configuration

In this short article, we will look at how Dependency Injection for Data Access Objects can be implemented using Spring.NET.

“Data Access support in Spring is aimed at making it easy to work with data access technologies like ADO.NET and Nhibernate in a standardized way.”- Spring.NET

First an interface that exposes the methods that can act on a database.


public interface IShapeDao
{
   DataTable GetShape();
}

Then some implementations for this interface.


// Implementation 1
public class CircleDao: AdoDaoSupport, IShapeDao
{
   public DataTable GetShape()
   {
       var sql = " Select * from tblCircle";
       return AdoTemplate.DataTableCreate(CommandType.Text, sql);
   }
}

// Implementation 2
public class RectangleDao: AdoDaoSupport, IShapeDao
{
   public DataTable GetShape()
   {
       var sql = " Select * from tblRectangle";
       return AdoTemplate.DataTableCreate(CommandType.Text, sql);
   }
}

Notice that no connection strings or database context are provided here.

Now, the Configuration class. Each dependent object will have its own virtual method as below:


[Configuration]

public class MyConfiguration: IApplicationContextAware
{
    public IApplicationContext ApplicationContext { get; set; }

   [Definition(Names="circle"]
   [Lazy]
   [Scope(ObjectScope.Singleton)]
   public virtual IShapeDao CircleDao()
   {
      return new CircleDao();
   }

   [Definition(Names="rectangle"]
   [Lazy]
   [Scope(ObjectScope.Singleton)]
   public virtual IShapeDao RectangleDao()
   {
      return new RectangleDao();
   }
}

Next, all we need to do is initialize the ApplicationContext by passing the required dependency.In the program main process i.e. where the app begins and all the action starts, we initialize the ApplicationContext.


private IApplicationContext context;

public void InitContext()
{
   // Configure Spring programmatically
   var ctx = new CodeConfigApplicationContext();
   ctx.ScanWithAssemblyFilter(a => a.FullName.StartsWith("My.Assemble.Name.Path"));
   ctx.Refresh();
   context = ctx;
}

Finally, we can ask for our object from this context like this:


IShapeDao circleDao = context.GetObject<IShapeDao>("circle");
IShapeDao rectangleDao = context.GetObject<IShapeDao>("rectangle");

This is pretty much all the needed fundamentals for using Spring.NET DAO.

Happy Programming!

Connecting to SQL Server using RODBC package in R

RODBC is a useful package for making SQL queries to SQL Server database for R users.

To start using this package, first we need to make sure it is loaded into R studio.


is.installed <- function(mypkg) is.element(mypkg, installed.packages()[,1])

if(!is.installed('RODBC'))
{
install.packages("RODBC")
}

library(RODBC)

Now that the package is installed/loaded into our environment, let’s start making SQL queries.

First we will need to provide credentials for accessing our SQL Server Database for R. Mainly we will need to have correct info for:

  1. Server name
  2. Database name
  3. Login Id
  4. Password

Providing connection info:


conn <- odbcDriverConnect('driver={SQL Server};
server=SOVITHOME-PC\\RAY;
database=EmergencyRMDb;
uid=sa;
pwd=myPwd***')

Now the “conn” object holds connection for SQL Server. Using this object we can make different kinds of queries supported by RODBC. Let’s perform some common queries like:

  • SELECT statements
  • SELECT statements with WHERE Clause
  • UPDATE statements
  • SQL JOIN statements

# print row count of tables
sqlQuery(conn, "select count(*) from EQData", as.is=T)

# print name of columns
colnames(tblData)

# select all data from a table
tblData &lt;- sqlQuery(conn, "select * from EQData", as.is=T)
#preview data
head(tblData)

<img class="wp-image-542" src="http://sovitpoudel.com.np/wp-content/uploads/2017/03/result1-300x68.png" alt="" width="850" height="193"> Result from query


# Viewing columns and rows

# [x,y] -> x represents the row number and y represents the column number

tblData[,1:5] # view columns 1 through 5

tblData[2,] # view first two rows

tblData$Latitude[2] # view second value for specified column
# finding by matching row(s) value
tblData[tblData$Epicentre == "Kathmandu",]

# update tables
sqlQuery(conn, "update EQData set latitude = '27.75' where epicentre = 'kathmandu'")

SQL JOIN statements can also be easily performed using “merge” function.


# perform inner join
newT <- merge(tblA, tblB, by = "key_id")
dim(newT)

# perform outer join
newOuterT <- merge(tblA, tblB, by = "key_id", all = TRUE)
dim(newOuterT)

# perform left join
newLeftT <- merge(tblA, tblB, by = "key_id", all.x = TRUE)
dim(newLeftT)

# perform right join
newRightT <- merge(tblA, tblB, by = "key_id", all.y = TRUE)
dim(newRightT)

These are some common operations that we can easily perform using R and RODBC on SQL Server tables. As you can see, most of the common operations can be performed using built-in R functions for Data Frames on R. I am just making use of “sqlQuery” function provided by RODBC for making queries on the Server.

Please find the full list of RODBC supported queries at: https://cran.r-project.org/web/packages/RODBC/RODBC.pdf

Hope this was helpful. If you got stuck on any of the steps, above please do not hesitate to leave comments below.

Thanks!