Wednesday, 12 October 2016

JMeter Memory error

As I was running a load test on an WCF service for the first time with JMeter, once the samples reached 30k the JMeter UI froze up and I had to close JMeter abruptly. I happened to check on the JMeter logs and found that this was the last entry
jmeter.threads.JMeterThread: Test failed! java.lang.OutOfMemoryError: Java heap space

As usual I turned to google and found out that this error can be forgone by increasing the Java heap space.

This line in  jmeter.bat or jmeter.sh script which tells the launching instance of JMeter how much heap size it should use. 

JVM_ARGS="-Xms512m -Xmx512m" jmeter.sh

I changed it to -Xms1024m at both places and relaunched JMeter.  (Please Note that your system that has JMeter setup has sufficient RAM )

It FIXed the problem. 

I am able to test the application now, crossing the previous 30k sample and going beyond till I stop the test manually.

Also I found the below article with a couple of more fixes that you might need in case you are facing the above error still.

Thursday, 1 September 2016

The decoration of objects

This is an image of tree rings. As you know the rings indicate the age of the tree. 

Now coming to our example of Decorator pattern, the "first year of growth is our original object and the rest of the rings are the decorators"


Decorator pattern is used as an alternative for subclassing when we need the functionality to be extended. It is also an example of the Open- Closed Principle where we are allowed only to extend instead of modify.

When do we used decorator pattern?
When we have a set of large combination of two or more different sets of logic to be performed, instead of having a nightmare of derived classes we would rather bind the required logic dynamically.

Consider a web cam device that rotates and takes a photo everytime it senses motion of object in front of it.

Pseudo Code

InstructionCode  ActionPerformed
CC                         Check if device is awake/Powered on

SS                          Check if sensor is functional

TT                          Take a snapshot

RR                          Rotate towards object of movement

DD                          Detect motion

MM                        TimerControl

Scenario 1:
The workflow will be such as

CC- Check if device is awake  >>  SS- Check if sensor is functional  >> DD- Detect Motion  >> RR- Rotate towards motion >> TT - Take Snapshot.


So the code you would need to write would be
CC SS DD RR TT

Scenario 2:
Now if the functionality of the device is changed to take pictures at every interval of time.

The workflow will be

CC- Check if device is awake >> MM- Timer Control >> TT- Take Snapshot.

So the code you would need to write would be
CC MM TT

If you considered the above scenario writing without a decorator pattern and having derived classes etc, it would have taken a lot of time modifying the codebase to fit in scenario 2 and violating the open closed principle of SOLID. Instead on using decorator we leave the scenrario 1  code untouched while we implement the scenario 2 logic.

In the above example we have limited number of instructions, consider writing a code for a IOT device which has numerous instruction sets all that need to be constructed to interact with a device. In such a scenario you would definitely prefer writing less code and opt for decorator pattern.

Below is a basic code example of an Ice Cream Preparation using decorator pattern.

Image result for ice cream toppings display

The Ice Cream comes with a base Cone and with one scoop of ice cream.
It can be topped with chocolate sauce, sprinkles, gummy bears or all the above.

using System;

namespace IceCreamDecoration
{
    public abstract class BaseCone
    {
        protected double myPrice;

        public virtual double GetPrice()
        {
            return this.myPrice;
        }
    }

    public abstract class IceCreamToppingsDecorator : BaseCone
    {
        protected BaseCone basecone;
        public IceCreamToppingsDecorator(BaseCone baseconeToDecorate)
        {
            this.basecone = baseconeToDecorate;
        }

        public override double GetPrice()
        {
            return (this.basecone.GetPrice() + this.myPrice);
        }
    }

    class Program
    {
        
        static void Main()
        {
          
            OneScoop basecone = new OneScoop();
            Console.WriteLine("Just one scoop : " + basecone.GetPrice().ToString());

            SprinklesTopping sprinkles = new SprinklesTopping(basecone);
            SprinklesTopping moresprinkles = new SprinklesTopping(sprinkles);
            Console.WriteLine("single scoup with sprinkles: " + moresprinkles.GetPrice().ToString());

            GummyBearsTopping gummyBears = new GummyBearsTopping(moresprinkles);
            Console.WriteLine("single scoup with more sprinkles and gummy bears: " + gummyBears.GetPrice().ToString());

            ChocolateSauceTopping chocolateSauce = new ChocolateSauceTopping(gummyBears);
            Console.WriteLine("single scoup with more sprinkles and gummy bears and chocolate sauce: " + chocolateSauce.GetPrice().ToString());

            Console.ReadLine();
        }
    }

    public class OneScoop : BaseCone
    {
        public OneScoop()
        {
            this.myPrice = 6.99;
        }
    }

    public class Dessert : BaseCone
    {
        public Dessert()
        {
            this.myPrice = 7.49;
        }
    }

    public class SprinklesTopping : IceCreamToppingsDecorator
    {
        public SprinklesTopping(BaseCone baseconeToDecorate)
            : base(baseconeToDecorate)
        {
            this.myPrice = 0.99;
        }
    }

    public class GummyBearsTopping : IceCreamToppingsDecorator
    {
        public GummyBearsTopping(BaseCone baseconeToDecorate)
            : base(baseconeToDecorate)
        {
            this.myPrice = 1.49;
        }
    }

    public class ChocolateSauceTopping : IceCreamToppingsDecorator
    {
        public ChocolateSauceTopping(BaseCone baseconeToDecorate)
            : base(baseconeToDecorate)
        {
            this.myPrice = 2.49;
        }
    }
}

Tuesday, 16 August 2016

Setting up OTP Auth for your application with Google Auth

Cover art
Two factor authentication has become a necessary evil these days. Unlike the olden days where people carried a RSA token generator with them, these days we use apps such as Google Authenticator.

Below are the steps for helping you get started with it.

1. Get nugget package GoogleAuthenticator

2. Add the following code

     TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
     var setupCode = tfa.GenerateSetupCode("issuer", "accountTitle", "poiuytrewq123456", 300, 300);

            string qrCodeImageUrl = setupCode.QrCodeSetupImageUrl;
            string manualEntrySetupCode = setupCode.ManualEntryKey;
            Console.WriteLine(manualEntrySetupCode);

Use any key in place of "poiuytrewq123456"
On execution of this code you will get a Manual Entry Setup Code.

3. Install GoogleAuthenticator on your phone from Google Play.
Open App Goto
Options >> Setup Account >> Enter Provided Key >>  Enter the alphanumeric displayed by the above program and enter the same "accountTitle" given in the code above in the "Account Name" field.
Now your account is setup.

4. Add the following code to validate the OTP in your mobile.

            Console.WriteLine("Enter OTP ");
            string enteredOTP=Console.ReadLine();
          
            bool isCorrectPIN = tfa.ValidateTwoFactorPIN("poiuytrewq123456", enteredOTP);
            if (isCorrectPIN)
            {
                return true;
            }
            else
                return false;

That's it you are done.

Run the Program
Enter the OTP in the console as shown in your mobile.
If the OTP matches you will get authenticated.

Will share the Github repo link.


Thursday, 18 February 2016

Listing Dependencies of Stored Procedure in MS SQL

When you want to check the dependencies of a stored procedure as in which tables are being used,
you can use the below query

SELECT DISTINCT p.name AS proc_name, t.name AS table_name
FROM sys.sql_dependencies d 

INNER JOIN sys.tables     t ON t.object_id = d.referenced_major_id
INNER JOIN sys.procedures p ON p.object_id = d.object_id

ORDER BY proc_name, table_name

Below is the result on execution of the above query on the Northwind Database


You can also try

sp_depends Procedure_Name

Thursday, 7 January 2016

Console Application to Create and Read from Couchbase views

Creating a View

Log into Web Console

Go to Views - Development Views - Add View



Give a Design doc name and View Name can be anything.

In my case I will keep it as trial and trialView respectively.

Now Under Development Views you will find the view you have created

Click edit.







Here you can ignore the top row.
The View Code will contain the logic of your view. In sql terms , the select Query,

function (doc, meta) {
  if(doc.Name)
    emit(meta.id,{"Emp_name":doc.Name, "Emp_age": doc.Age, "Emp_salary": doc.Salary} );
}

This code checks if the documents have a property called name, if so it will return the name, age and salary. This query will be run on default DB.

The Reduce box to the right helps us with aggregate functions such as count , sum etc.

Once you have entered the MAP code hit SAVE

Go to Views page now.

 In development Views select PUBLISH against the VIEW you have CREATED.



Now to integrate it with the C# code

  private static void GetFromView()
        {
            using (var bucket = Cluster.OpenBucket())
            {
                var query = bucket.CreateQuery("trial", "trialView", false);  // trial is the Design Doc name and trialView is the View name

                var result = bucket.Query<Employee>(query);             // will be using the Employee POCO class defined below
                foreach (var row in result.Rows)
                {
                   // Console.WriteLine(row.Key+" "+row.Value);
                    Console.WriteLine(row.Key + " EmployeeName: " + row.Value.Name + " EmployeeAge:"+ row.Value.Age +" EmployeeSalary:"+ row.Value.Salary);
                }
            }


public class Employee
{
    [JsonProperty("Emp_name")]
    public string Name { get; set; }

    [JsonProperty("Emp_age")]
    public string Age { get; set; }

    [JsonProperty("Emp_salary")]
    public string Salary { get; set; }

}




Creating a Console Application for Couchbase CRUD operations

Here is a sample application for performing few CRUD operations.

Requirements: VS 2012

Steps:

Create a console Application and

1. GO to Tools > Library Package Manager > Package Console

2. Install-Package CouchbaseNetClient





Upsert - Insert new records or Update existing records


  private static void UpsertData()
        {
            using (var bucket = Cluster.OpenBucket())   // Opens "default" DB if DB name is not specified
            {
                var document = new Document<dynamic>
                {
                    Id = "Hello",
                    Content = new
                    {
                        name = "Couchbase"
                    }
                };                                                                  // Create Document/Row to be inserted

                var upsert = bucket.Upsert(document);
                if (upsert.Success)
                {
                    var get = bucket.GetDocument<dynamic>(document.Id);
                    document = get.Document;
                    var msg = string.Format("{0} {1}!", document.Id, document.Content.name);
                    Console.WriteLine(msg);
                }
  
            }
      

 private static void DeleteData()
        {
            using (var bucket = Cluster.OpenBucket())
            {
                var document = new Document<dynamic>
                {
                    Id = "Hello"

                };

                var get = bucket.GetDocument<dynamic>(document.Id);
                document = get.Document;
                var msg = string.Format("{0} {1}! Deleted", document.Id, document.Content.name);
                var remove = bucket.Remove(document); // Delete Document Using ID
                if (remove.Success)
                {
                  
                    Console.WriteLine(msg);
                }

            }
        }







Wednesday, 6 January 2016

Query Workbench Installation - N1QL - SQL type queries

Image result for n1ql
Query Workbench is when you want a SSMS / mysql client kinda interface.


  • Enables you to write queries like SQL queries. 
  • These queries are called N1QL queries pronounced as Nickel Queries

Download : 

  • Extract
  • Run the "Launch ..." bat file.
  • Command Window will popup saying Launching UI server, to use, point browser at 
  • http://localhost:8094Hit enter to stop server:
  • From Browser go to the address mentioned

Once you are done:

you can run SQL like queries ,

NOTE: if you are not able to see anything in Queryable Buckets on the left side then 

Type 
CREATE INDEX `beer-sample-type-index` ON `beer-sample`(type) USING GSI;

or

CREATE INDEX id_ix on `beer-sample`(meta().id);

These are diff types of indexes being set on beer-sample DB.

Also the DB name should be enclosed in BACK TICK and not single inverted commas



Sample N1QL queries: