Tuesday, March 8, 2016

SQL Query Optimization Tips

After spending the past few months working in a SQL heavy application I've discovered there is a lot you can do as a developer to ensure your application stays optimized when calling stored procedures and running queries against your database. 

Definitely, these optimization tips don’t guarantee that your queries won't become your system bottleneck. It will require more bench-marking and profiling to further optimize your SQL queries. However, the below optimizations can be utilized by anyone and are good practices to know when writing queries. 

These have been a good learning experience for me and have helped eliminate a few pesky issues in my own application.

Wildcard

In SQL, wildcard is provided for us with '%' symbol. Using wildcard 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.

#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';
That column must be indexed for such optimize to be applied.

*Doing a full wildcard in a few million records in a table is equivalent to killing the database.

COUNT VS EXIST

Some of us might use COUNT operator to determine whether a particular data exist

SELECT COLUMN FROM TABLE WHERE COUNT(COLUMN) > 0
Similarly, this is very bad query since count will search for all record exist on the table to determine the numeric value of field 'COLUMN'. The better alternative will be to use the EXIST operator where it will stop once it found the first record. Hence, it exist.

Wildcard VS Substr

Most developer practiced Indexing. Hence, if a particular COLUMN has been indexed, it is best to use wildcard instead of substr.

#BAD
SELECT * FROM TABLE WHERE  substr ( COLUMN, 1, 1 ) = 'value'.
The above will substr every single row in order to seek for the single character 'value'. On the other hand,

#BETTER
SELECT * FROM TABLE WHERE  COLUMN = 'value%'.
Wildcard query will run faster if the above query is searching for all rows that contain 'value' as the first character. Example,

#SEARCH FOR ALL ROWS WITH THE FIRST CHARACTER AS 'E'
SELECT * FROM TABLE WHERE  COLUMN = 'E%'.

Data Types

Use the most efficient (smallest) data types possible. It is unnecessary and sometimes dangerous to provide a huge data type when a smaller one will be more than sufficient to optimize your structure. Example, using the smaller integer types if possible to get smaller tables. MEDIUMINT is often a better choice than INT because a MEDIUMINT column uses 25% less space. On the other hand, VARCHAR will be better than longtext to store an email or small details.

Indexes

Index your column is a common way to optimize your search result. Nonetheless, one must fully understand how does indexing work in each database in order to fully utilize indexes. On the other hand, useless and simply indexing without understanding how it work might just do the opposite.

Symbol Operator

Symbol operator such as >,<,=,!=, etc. are very helpful in our query. We can optimize some of our query with symbol operator provided the column is indexed. For example,

SELECT * FROM TABLE WHERE COLUMN > 16
Now, the above query is not optimized due to the fact that the DBMS will have to look for the value 16 THEN scan forward to value 16 and below. On the other hand, an optimized value will be

SELECT * FROM TABLE WHERE COLUMN >= 15
This way the DBMS might jump straight away to value 15 instead. It's pretty much the same way how we find a value 15 (we scan through and target ONLY 15) compare to a value smaller than 16 (we have to determine whether the value is smaller than 16; additional operation).



NOT Operator

Try to avoid NOT operator in SQL. It is much faster to search for an exact match (positive operator) such as using the LIKE, IN, EXIST or = symbol operator instead of a negative operator such as NOT LIKE, NOT IN, NOT EXIST or != symbol. Using a negative operator will cause the search to find every single row to identify that they are ALL not belong or exist within the table. On the other hand, using a positive operator just stop immediately once the result has been found. Imagine you have 1 million record in a table. That's bad.
  
Index Unique Columns

Some databases such as MySQL search better with column that are unique and indexed. Hence, it is best to remember to index those columns that are unique. And if the column is truly unique, declare them as one. However, if that particular column was never used for searching purposes, it gives no reason to index that particular column although it is given unique.

Max and Min Operators

Max and Min operators look for the maximum or minimum value in a column. We can further optimize this by placing a indexing on that particular column, We can use Max or Min on columns that already established such Indexes. But if that particular column is frequently use, having an index should help speed up such searching and at the same time speed max and min operators. This makes searching for maximum or minimum value faster. Deliberate having an index just to speed up Max and Min is always not advisable. It’s like sacrifice the whole forest for a merely a tree.


Primary Index

The primary column that is used for indexing should be made as short as possible. This makes identification of each row easy and efficient by the DBMS.

String indexing

It is unnecessary to index the whole string when a prefix or postfix of the string can be indexed instead. Especially if the prefix or postfix of the string provides a unique identifier for the string, it is advisable to perform such indexing. Shorter indexes are faster, not only because they require less disk space, but because they also give you more hits in the index cache, and thus fewer disk seeks.

Limit The Result

Another common way of optimizing your query is to minimize the number of row return. If a table have a few billion records and a search query without limitation will just break the database with a simple SQL query such as this.

SELECT * FROM TABLE
Hence, don't be lazy and try to limit the result turn which is both efficient and can help minimize the damage of an SQL injection attack.

SELECT * FROM TABLE WHERE 1 LIMIT 10
Use Default Value

If you are using MySQL, take advantage of the fact that columns have default values. Insert values explicitly only when the value to be inserted differs from the default. This reduces the parsing that MySQL must do and improves the insert speed.

In Subquery

Some of us will use a subquery within the IN operator such as this.

SELECT * FROM TABLE WHERE COLUMN IN (SELECT COLUMN FROM TABLE)
Doing this is very expensive because SQL query will evaluate the outer query first before proceed with the inner query. Instead we can use this instead.

SELECT * FROM TABLE, (SELECT COLUMN FROM TABLE) as dummytable WHERE dummytable.COLUMN = TABLE.COLUMN;
Using dummy table is better than using an IN operator to do a subquery. Alternative, an exist operator is also better.

Utilize Union instead of OR

Indexes lose their speed advantage when using them in OR-situations in MySQL at least. Hence, this will not be useful although indexes is being applied

SELECT * FROM TABLE WHERE COLUMN_A = 'value' OR COLUMN_B = 'value'
On the other hand, using Union such as this will utilize Indexes.

SELECT * FROM TABLE WHERE COLUMN_A = 'value'
UNION
SELECT * FROM TABLE WHERE COLUMN_B = 'value'

Hence, run faster.

Thursday, December 10, 2015

IoT: Open Sourcing My Aquaponics / Greenhouse Monitoring Platform






It's been a while now since I started working on my AquaCulture Monitor project and today it's been released onto GitHub as an open source project for all the IoT developers out there.
I started the project some time ago after getting myself a raspberry pi and looking to find something fun and challenging to do with it beyond the standard basic tutorials out there.

My wife Jean had started her aquaponic greenhouse and seeing she was spending a great deal of time checking various things such as pH levels in her tank and temperature/humidity levels inside the greenhouse I thought why not build a device that can stream the data in real-time to her iPad and provide her with something that could help her make informed decisions about what her greenhouse was doing.
It was a great project to work on and allowed me to dive into programming with Python. 

Sunday, July 12, 2015

HOW TO POST TO YOUR PAGE USING FACEBOOK C# SDK


1) Create a Facebook App at: developers.facebook.com and get yourself an APPID and APPSECRET. (there are a lot of tutorials online for doing this so I will skip repeating it)
2) Go to: http://developers.facebook.com/tools/explorer and choose your app from the dropdown and click "generate access token".
3) After that do the following steps here: http://stackoverflow.com/questions/17197970/facebook-permanent-page-access-token to get yourself a permanent page token. (I can not stress this enough, follow the steps carefully and thoroughly)*
*I have tool I built that does this for me, all I enter is the APPID, APPSECRET and ACCESSTOKEN which the tool then generates a permanent page token for me. Anyone is welcomed to use it and help make it better,
=======================================================================
Ok at this point you should have your APPIDAPPSECRET and a PERMANENT PAGE TOKEN.
=======================================================================
In your Visual Studio solution:
4) Using Nuget:Install-Package Facebook
5) Implement the Facebook client:
public void PostMessage(string message)
        {
            try
            {
                var fb = new FacebookClient
                {
                    AppId = ConfigurationManager.AppSettings.Get("FacebookAppID"),
                    AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
                    AccessToken = ConfigurationManager.AppSettings.Get("FacebookAccessToken")
                };

                dynamic result = fb.Post("me/feed", new
                {
                    message = message
                });
            }
            catch (Exception exception)
            {
                // Handle your exception
            }
        }  

Saturday, January 3, 2015

Remove Malware From Your WordPress Site

This step-by-step guide can be used by practically anyone to remove malware from WordPress. However, you must be willing to get your hands a little dirty, and be comfortable with FTP and File Manager.

Step 1: Scan Your Computer

When malware infects your WordPress site it is actually quite common if you don't stay on top the game and update regularly as well monitor your logs. So first things first is to make sure your computer is virus-free. We recommend scanning at least with Malware Bytes, and to be doubly safe, another anti-virus such as NOD32 or Kaspersky.

Step 2: Change Your Password

Now that your computer is virus free, you should change your cPanel and FTP password. Make sure it is something random, with at least 1 special character like ! # & %, a mix of lower and uppercase letters plus numbers. We recommend using a password manager tool such as LastPass to not only generate secure passwords but store and manage them for you too.

Step 3: Download WordPress

Download the latest fresh WordPress package from the official site.

Step 4: Extract Files

Extract the files from the zip or tar.gz that you have just downloaded onto your computer. Leave those files there for now. We will come back to them later.

Step 5: Removing The Malware Infection

Login to your FTP or cPanel > File Manager.
Your WordPress installation files on your web host should look like this:
wp-admin
wp-content
wp-includes
index.php
license.txt
readme.html
wp-activate.php
wp-blog-header.php
wp-comments-post.php
wp-config.php
wp-config-sample.php
wp-cron.php
wp-links-opml.php
wp-load.php
wp-login.php
wp-mail.php
wp-settings.php
wp-signup.php
wp-trackback.php
xmlrpc.php
Delete everything you see there except for the wp-content folder, and the wp-config.php file.
Now your installation should look like:
wp-content
wp-config.php
In your cPanel > File Manager, click on and edit the wp-config.php file. Make sure there are no strange codes or anything unusual. If there is malware in this file, it will generally look like a long string of random text. You can compare it to the wp-config-sample.php file to be sure.
Now go into the wp-content folder. It should look like:
plugins
themes
uploads
index.php
Make a list of the plugins you are currently using, then remove the plugins folder and index.php file. You will need to re-install your plugins after the cleaning process.
Go into the themes folder, and remove any theme which you are not using. You will then need to individually check each file in your current theme to make sure there is no malware or strange codes in them. If you have a clean backup of your theme somewhere (like on your computer), then to be safe you should just delete the entire themes folder.
Check every directory inside your uploads folder to make sure there are no php files or anything that you may not have uploaded.

Step 6: Re-upload WordPress

The fresh WordPress files that you extracted earlier in Step 4 can now be uploaded via FTP.
If you removed your theme you should also re-upload your clean backup theme files.

Step 7: Change WordPress Admin Password and Re-install Plugins

You should now be able to access your dashboard, and change your admin password. Always use a random hard to guess password. Don’t be tempted to use something basic like welcome or ilovekittens(actual passwords used by some of our clients). You will get hacked this way.
If you don’t want to use a random password like xSpM82!#3&W, then pick an uncommon phrase with 3 or more words like MyKitten<3sMe. A strong password is one with uncommon words, at least 1 number, 1 special character and a mix of upper and lower case characters.

Step 8: Remove Google Warning

Now that your site is free of malware, you can submit your site to Google to get the warning “This site may harm your computer” removed. Login or create an account at Google Webmaster Tools, add your site, click Health, and then click Malware. and finally Request A Review.
Disclaimer: While these steps may help remove malware from your site it is not a complete guide and therefore we are not responsible for any damage or data loss that could happen from attempting to remove malware. We always encourage you to consult a professional who can ensure the correct measures are taken to negate any further damage already caused from a malware infected website.

For professional malware removal services visit http://www.thinkmonkey.ca


ThinkMonkey - Web Design Company | Software Company

Tuesday, December 16, 2014

Taking Ownership Of What You Deliver

Taking Ownership Of What You Deliver.

Almost a year ago I started a software development company as a way of creating and delivering projects outside of my full-time job with the desire to keep any intellectual property separate from what I delivered through my 9-to-5.
One of my favourite things about software development is being able to put an emphasis on creating working software instead of obsessing over intermediate progress gates and deliverables.
Over the past year I've learned a few things along the way, personally these observations have helped myself personally grow towards being more aware of what I am producing and delivering.
Quit being lazy! For many organizations the process has become one where you take the requirements from somebody else perhaps a business analyst, do your best to deliver and make deadlines, and then throw it over the fence for QA, testing, or whoever. In my experience, this makes many people less accountable for what gets pushed to production.
Own your work. Some of the best quality I have ever personally and professionally provided was in an environment where I was the one in charge of understanding the problem, coming up with the appropriate solution, and watching it all the way to production and eventually, the user.
The key ingredients to this recipe for success:
  1. Good unit tests – the benefits of testing are endless, I'll leave this for a future blog post.
  2. Do Not Fear Refactor! – if you’re afraid to change code because it might break something, you have problems. Follow SOLID principles as best as you responsibly can and you’ll have fewer problems here.
  3. Continuous Integration – make sure everything is working all the time. It helps in the long run (and by long run, I mean tomorrow). don't commit broken builds, take the time to keep your own house in order.
  4. Code Ownership – everybody owns this feature; it’s not just my own. a.k.a. Stop putting yourselves into silos. Also, your victories must be shared, but your failures are also not your own.
  5. Deploy As Often As Possible – The best time to deploy a feature is the moment it’s declared “Done”. The longer you wait between this time and delivery, the more likely it is to fail.
Your experience may vary, but these have worked really well for me and I would suggest you try them if you’re having challenges moving quality from concept to deliverables.


ThinkMonkey - Web Design Company | Software Company

Tuesday, October 22, 2013

Setting Up NUnit Testing With Azure Deployments From Git

A few days ago while deploying my latest build to Windows Azure and looking through the deployment logs I noticed that the deployment wasn't running any of my unit tests.

So I began with a simple question to someone I respect very much and figured would know the answer better than anyone else I knew. (I'll admit I am a fan and wanted an opinion) 


If you haven't heard of Scott than definitely go check out his site http://www.hanselman.com (perhaps wait till after the article). Scott has done many tutorials on .net topics and I am sure he will have a post in no time on this topic too.

Most of the skills and knowledge I've learned now in my first year as a developer have come from Scott and others like him, as well the Virtual Academy. 
http://www.microsoftvirtualacademy.com/#fbid=6c6vaptZwtl if you're new to development like me than take a moment to check these resources out. (Don't worry I will wait)

Alright to be honest his answer didn't surprise me at all given that if Azure had offered the support it would be in one of the many settings or features it offers. 

Azure is already an amazingly simple and easy to use platform with one of the most intuitive user experiences ever, given the amount of content and feature rich options it has. 

Moving along...

A quick Google search revealed well... this, http://blog.amitapple.com/post/51576689501/testsduringazurewebsitesdeployment and it looked fairly straight forward so I grabbed a coffee and started to learn.

After a few hours and various Azure deployment errors that sometimes made no sense at all it wasn't looking too good for me.

Another few tweets to Scott and he pointed me into the direction of 

Once I had logged in and taken a look around I went into the deployments\tools folder and saw the deploy.cmd file Azure uses. (At least when you don't provide one)

The guide showed me how to output the deploy.cmd file from the Azure command line tool onto my local machine and that was great except one thing... it wouldn't deploy.

Why would the generated deploy.cmd not deploy? I mean it was generated by the tool and intended to give you a working deployment. So I compared it to the one in the deployment\tools folder and noticed the project folder was wrong.

I looked at my local folder structure and discovered that the solution (.sln) wasn't at the root or top level folder. The assumption would be that the deploy file would still work considering every deployment up to this point had.

Either way a few quick moves and re-organizing of the solution folder and I tried again... and again... and again.

Now what! I thought, seriously this was going into the night and my caffeine intake was depleted as was my patience. The issue now was my nuget packages were not deploying and once more I didn't understand why, because up to this point I had not even modified the deploy file once.

Looking inside my nuget.targets file I saw "restore packages" and "download nuget if missing" were both set to false, quick edit to true and... they started to load.

Ok at this point the deployment was working and after one full day of work just to get the auto generated deployment file working it... I added the unit testing commands and watched as Azure deployed with unit tests. 

So after all this there are a few things to consider that could cause issues.
- Azure does not seem to work ideally if your solution isn't in the root or top level folder. This was the case with my first issue.

- If you are using package restore in your project as I am, make sure your nuget targets file in the .nuget folder has "restore-packages" and "download-nuget-if-missing" set to true. It's not required, as you can check in nuget.exe instead (up to you)

- Make sure your tests are working, also if any are ignored tried commenting them out completely. (I had one deployment fail because I ran an ignored test)


WHAT I AM USING
- Visual Studio 2012
- BitBucket (Git Repository)
- ASP.Net MVC4 Application
- NUnit Testing Framework

HOW TO:
Begin by deploying a clean working deployment to Azure. 


It's important that you have an active deployment as this indicates the Azure deploy.cmd is working on the server. So with an active deployment we can begin.

== STEP 1 ======
Grab the Azure Command Line Tool

After the Azure CLI is installed open a command prompt and navigate to your solution folder then run this command,
azure site deploymentscript --aspWAP {PROJECT-FOLDER}\{PROJECT-NAME}.csproj -s {SOLUTION-NAME}.sln

Make sure you replace {PROJECT-FOLDER} {SOLUTION-NAME} and {PROJECT-NAME} with the correct names. 

Verify the files were generated in the solution folder (.deployment & deploy.cmd)

== STEP 2 ======
Let's verify the deploy.cmd matches what Azure uses (mine ended up being different and caused a few headaches). 

Go to    and login using your deployment credentials. If you experience issues logging in, go to your Azure Website dashboard and reset your deployment credentials.





Once you've successfully logged into the debug console navigate to  deployments\tools and click on the edit icon for the deploy.cmd file.

== STEP 3 ======
Copy this into a text editor on your machine and look at the Deployment section of the script to verify the paths match the ones inside the  deploy.cmd in the project folder which we generated earlier using the Azure CLI.

At this point I recommend you check-in the file to your git repository and verify it deploys. This will save many headaches and ensure any further errors truly are the developers'. 

== STEP 4 ======
Now that we know the deployment works, hopefully... we can continue onto the important step and the that is setting up your build for the test project and deploying the test runner.

Find This Line.
:: 1. Build to the temporary path
Copy the following and paste it a few lines below after the IF !ERRORLEVEL! NEQ 0 goto error
:: 2. Building test project
echo Building test project
"%MSBUILD_PATH%" "%DEPLOYMENT_SOURCE%\{TEST-PROJECT-FOLDER}\{TEST-PROJECT-NAME}.csproj"
IF !ERRORLEVEL! NEQ 0 goto error

:: 3. Running tests
echo Running tests
vstest.console.exe "%DEPLOYMENT_SOURCE%\{TEST-PROJECT-FOLDER}\bin\Debug\{TEST-PROJECT-NAME}.dll"
IF !ERRORLEVEL! NEQ 0 goto error
Make sure again of course that you replace the placeholder  {TEST-PROJECT-FOLDER} and {TEST-PROJECT-NAME} respectively to the correct values.

Your %DEPLOYMENT_SOURCE% folder usually points to the location of your solution file so use this as a reference in where you are in the folder tree. 

The vstest.console.exe is the test runner supplied in VS 2012 and will run most testing frameworks mstest, xunit or nunit which we are using.


vstest.console.exe will recognize any test that exists in the supplied test assembly and will run it whether the test is mstest, xunit or nunit, and they could all be in the same assembly.
You're done, commit your modified deploy scripts into your git repository and try your deployment.

Azure is always updating with new features and the efforts from the Azure team are amazing. I know one day deploying a TDD application will be a much easier task than it currently is.

It's a lot of work I know and I'll admit many junior developers may not want to challenge themselves with a task like this, for me personally it's becoming a passionate mindset.

Tired of Waiting for your Website to Load? $1/ mo Hosting + Free domain!

ThinkMonkey - Web Design Company | Software Company