Access FitBit HeartRate Data using C#

Advertisements

5 considerations to save your sql database from bottleneck

We all write sql queries and fetch the data from the database. Many a times, an inefficient query may pose a bottleneck on the production database’s resources, and cause slow performance for other users if the query contains errors. Most time, we write blind queries and get all the possible data, which is not even required or to be shown to the end user on the form or GRID. In most scenarios, there are few tweaks you can do to your sql queries to optimize for better good.

  1. Indexes

Database novices often find indexes mysterious or difficult. They either index nothing or they try to index everything.

2. Less is more, so select * [STAR] carefully

A common way of retrieving the desired columns is to use the * symbol even though not all the columns are really needed. If you only need a limited number of rows you should use the LIMIT clause (or your database’s equivalent). Take a look at the following code:

SELECT name, price FROM products;

SELECT name, price FROM products LIMIT 10;

3. Say no to correlated subqueries

A correlated subquery is a subquery which depends on the outer query. It uses the data obtained from the outer query in its WHERE clause. Suppose you want to list all users who have made a donation. You could retrieve the data with the following code:

SELECT user_id, last_name FROM users WHERE EXISTS (SELECT * FROM donationuser WHERE donationuser.user_id = users.user_id);

SELECT DISTINCT users.user_id FROM users INNER JOIN donationuser ON users.user_id = donationuser.user_id;

4. Avoid Wildcards

In SQL, wildcard is provided for us with ‘%’ symbol. We should be considerate for using wildcard, which will definitely slow down your query especially for table that are really huge. We can optimize our query with wildcard by doing a postfix wildcard instead of pre or full wildcard. Below are few examples.

#Full wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE ‘%hello%’;
#Postfix wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE ‘hello%’;
#Prefix wildcard
SELECT * FROM TABLE WHERE COLUMN LIKE ‘%hello’;
5. COUNT VS EXIST, you decide

Some of us might use COUNT operator to determine whether a particular data exist. There are many instances where we can make use of Exists. Example below:-

SELECT COLUMN FROM TABLE WHERE COUNT(COLUMN) > 0

This is a very bad query since count will search for all record exist on the table to determine the numeric value of field ‘COLUMN’.

JSON Serialization/Deserialization using C#.NET

Many a times, we have a need to call third party API or web services and these apis and web services return us data in xml format or JSON format.
The .NET Framework doesn’t give you the tools to do it out-of-the-box.

We can implement JSON Serialization/Deserialization in the three ways:

  • Using JavaScriptSerializer class
  • Using DataContractJsonSerializer class
  • Using JSON.NET library 

This demo would highlight how can we deserialize these objects using
JSON.NET package in nuget package manager.

Json.NET is a package which helps conversion between JSON text and .NET object using the JsonSerializer. It converts .NET objects into their JSON equivalent text and back again by mapping the .NET object property names to the JSON property names.

We will install this package in our project.

Go to Tools Menu -> Choose Library Package Manager -> Package Manager Console. It opens a command window to put the following command.

Install-Package Newtonsoft.Json

In our project we are calling fitbit api and getting heart rate data as httpwebresponse in JSON format. Screenshots below.


More information on Newtonsoft Json – https://www.newtonsoft.com/json

C# – why Dictionary is ahead of lists(look ups)

A quick example to demonstrate why the difference between dictionary “look up” versus lists.

The list of list of students and grades in memory, they have StudentId in common.
In a first way I tried to find Grade of a student using LINQ on a list that takes near 7 seconds on my machine and in another way first I converted List into a dictionary then finding grades of the student from the dictionary using a key.

internal class Program
{
    private static void Main(string[] args)
    {
        var stopwatch = new Stopwatch();
        List<Grade> grades = Grade.GetData().ToList();
        List<Student> students = Student.GetStudents().ToList();

        stopwatch.Start();
        foreach (Student student in students)
        {
            student.Grade = grades.Single(x => x.StudentId == student.Id).Value;
        }
        stopwatch.Stop();
        Console.WriteLine("Using list {0}", stopwatch.Elapsed);
        stopwatch.Reset();
        students = Student.GetStudents().ToList();
        stopwatch.Start();
        Dictionary<Guid, string> dic = Grade.GetData().ToDictionary(x => x.StudentId, x => x.Value);
        foreach (Student student in students)
        {
            student.Grade = dic[student.Id];
        }
        stopwatch.Stop();
        Console.WriteLine("Using dictionary {0}", stopwatch.Elapsed);
        Console.ReadKey();
    }
}

public class GuidHelper
{
    public static List<Guid> ListOfIds=new List<Guid>();

    static GuidHelper()
    {
        for (int i = 0; i < 10000; i++)
        {
            ListOfIds.Add(Guid.NewGuid());
        }
    }
}


public class Grade
{
    public Guid StudentId { get; set; }
    public string Value { get; set; }

    public static IEnumerable<Grade> GetData()
    {
        for (int i = 0; i < 10000; i++)
        {
            yield return new Grade
                             {
                                 StudentId = GuidHelper.ListOfIds[i], Value = "Value " + i
                             };
        }
    }
}

public class Student
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Grade { get; set; }

    public static IEnumerable<Student> GetStudents()
    {
        for (int i = 0; i < 10000; i++)
        {
            yield return new Student
                             {
                                 Id = GuidHelper.ListOfIds[i],
                                 Name = "Name " + i
                             };
        }
    }
}

The Magic Console-

Capture1

Make your singleton class thread safe

In this post, we try to get an idea about making thread-safe singleton.

A singleton is a class which only allows a single instance of itself to be created. This class usually gives simple access to that instance. Most commonly, singletons don’t allow any parameters to be specified when creating the instance. Now, in order to make singleton class thread-safe, we can apply to the double-check locking algorithm. In this algorithm, we can put two if conditions to check object is null or not.
First, if condition checks if the object is not null then return the already created object. The second condition we put inside the lock to check if the object is null then only create a new object. The benefit of putting inside condition is to check if multiple threads bypass the first condition at the same time and waiting for their turn to take the lock. Then, in this case, both threads will create a new object. For stopping the above issue, we have to put the second condition.
Below is the example of double-checking locking.
 public class Singleton
    {
        private static readonly Object s_lock = new Object();
        private static Singleton singleton = null;
        private Singleton() { }
        public static Singleton GetSingleton()
        {
            //check 1
            if (singleton != null)
                return singleton; Monitor.Enter(s_lock);
            //check 2
            if (singleton == null)
            {
                Singleton temp = new Singleton();
            }
            Monitor.Exit(s_lock);
            return singleton;
        }
    }