Tuesday, February 25, 2014

Tips to become a good Coder/Programmer

I am not a great programmer, but i love coding and trying my best to become a good coder, there are few things i got to know when i made a research on how to become an efficient programmer.

1. Search for a problem that's really annoying you that's tractable to being solved by some way of automation.

 2. Made a Google search for programmatic solutions to these kind of problems. Make a research on which languages are most commonly used and scalable to satisfy your wider needs. In all ways.

  3. Start trying to solve the problem by breaking down the problem down into smaller and smaller chunks and trying to find ways of implementing a solution in the language which you have chosen from the above step

4 .Code all the time, continuous practice whenever you have time. Keep trying to solve your problem- where you get stuck, follow people who seem to know what they're doing on github,stackoverflow and post their solutions. Ask whatever questions may be even if its not practical on stack overflow(If you don’t care about vote downs). Buy and read lot of books. Get over the "monkey-see-monkey-do" approach, especially when getting issues. Learn from your issues  by going fixing the immediate issue  to learning what class of conditions the error deals with.

5. Subscribe to online education sites like Codecademy, Peepcode, Udemy, CodeSchool. Copy, imitate, fail, bang and scream the desk. Smash your keyboard if code you wrote does not work, try again. Feel the elation of getting a small chunk right.  

6. Every problem has (n+1) solutions,where n is the number of solutions that we try and 1 is that we have not tried. Every developer love that feeling when they’ve been coding something for a while, and it finally works. Yes, it is daunting. Yes, the learning curve is ridiculously steep. But you will only learn by doing and not being afraid to get it wrong.Whenever you write code always try to comment, so that other users who use your code will have an idea on what have already written. When you find a technique that works  or solve your problem generalize it and keep your own utility library.This makes yourlife and others easy.

 7. Learn to refactor your code.Whenever you get time try to improve the code.Whenever you Get confused with all your changes,  pick up git,tfs,svn or another version control system. Collaborate on others projects. Refactor again with what you've learned.  


I’ll finish with two quotes:
“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”- Brian Kernighan


“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”- Rick Osborne

Monday, February 24, 2014

SQL 2012 Built In Functions

Well, i have decided to write on technologies finally, it was one of the good sessions from SQL meetup  which was held at Microsoft srilanka on this month. I learnt some useful and simple sql functions which is present in sql server 2012.

SQL Server 2012 introduces many new rich built-in functions that offer more solutions to common T-SQL challenges.Some of the main functions which am going to write about are,

Conversion functions
  • PARSE (Transact-SQL)
  • TRY_PARSE (Transact-SQL)
  • TRY_CONVERT (Transact-SQL)
Date and time functions
  • DATEFROMPARTS (Transact-SQL)
  • DATETIMEFROMPARTS (Transact-SQL)
  • DATETIME2FROMPARTS (Transact-SQL)
  • SMALLDATETIMEFROMPARTS (Transact-SQL)
  • DATETIMEOFFSETFROMPARTS (Transact-SQL)
  • TIMEFROMPARTS (Transact-SQL)
  • EOMONTH (Transact-SQL)
Logical functions
  • CHOOSE (Transact-SQL)
  • IIF (Transact-SQL)
String functions
  • CONCAT (Transact-SQL)
  • FORMAT (Transact-SQL)
In sql 2008 , in order to find a trend we were using CTE functions,  For example to find the trend in 2008,

WITH CTE AS (
SELECT rownum = ROW_NUMBER() OVER (order by WorkOrderID),OrderQtyFROM
[AdventureWorks].[Production].[WorkOrder])
SELECT CASEWHEN CTE.OrderQty-PREVCTE.OrderQty >0 THEN 'UP'
 WHEN CTE.OrderQty-PREVCTE.OrderQty <0 p="" then="">  ELSE 'NA'
  END AS Trand
FROM CTELEFT OUTER JOIN CTE AS PREVCTE ON PREVCTE.rownum = CTE.rownum – 1

but SQL 2012 made it more easier, I have used AdventureWorkds2012 database,



LAG and LEAD
No longer need to use a self-join or CTE.
LAG: Access data from previous rows in the result set.
LEAD: Access data from future rows in the result set
Advantage:
Increase in performance

Paging Data:
Again in order to do paging with sql 2008 we have to write a cte function, for example to get the first 20 rows from a table, the function will be as follows,
Start with 0, Page Size:20
WITH Paging_CTE AS ( SELECT TransactionID , ProductID , TransactionDate , Quantity , ActualCost , ROW_NUMBER() OVER (ORDER BY TransactionDate DESC) AS RowNumber FROM Production.TransactionHistory ) SELECT TransactionID , ProductID , TransactionDate , Quantity , ActualCost FROM Paging_CTE WHERE RowNumber > 0 AND RowNumber <= 20

SQL 2012


OFFSET & FETCH
OFFSET provides a starting row from which to display the result set.
FETCH instructs the query to display the number of rows you want in your result set from the OFFSET point

FIRST_VALUE and LAST_VALUE

FIRST_VALUE: Retrieves the first value in a partition.
LAST_VALUE: Retrieves the last value in a partition.


PARSE:
Parse a value and returns the result of an expression, translated to specified data type. It will raise error if translation isn’t possible. Since this  function relies on CLR. It has better performance.


Syntax:
PARSE ( string_value AS data_type [ USING culture ] )
PARSE(), expects three parameters,
string_value – String value to parse into the specified data type.
data_type – Return data type, numeric or datetime type
culture – A language (English, Japanese, Spanish, Danish, French etc.) which will used by SQL Server to interpret data.
example 
SELECT PARSE('18/02/2014' AS datetime2 USING 'en-GB') AS [Using PARSE Function]
GO
OUTPUT
2012-02-18 00:00:00.000

TRY_PARSE   – TRY_PARSE() function is similar to PARSE() with only difference is that it returns NULL if the conversion is not possible.
Syntax:
TRY_PARSE ( string_value AS data_type [ USING culture ] )
TRY_PARSE(), expects three parameters,
string_value – String value to parse into the specified data type.
data_type – Return data type, numeric or datetime type
culture – A language (English, Japanese, Spanish, Danish, French etc.) which will used by SQL Server to interpret data.
SELECT TRY_PARSE(’10.30′ AS INT) AS [Using TRY_PARSE Function]
GO
OUPUT:
NULL
Since 10.20 is not an integer value PARSE() fails, and TRY_PARSE() returns NULL.

TRY_CONVERT – Checks whether conversion from one type to other is possible or not. It transforms the source data into the target type if the conversion is possible. Returns NULL if the conversion is not possible.
Syntax:
TRY_CONVERT ( data_type [ ( length ) ], expression [, style ] )
TRY_CONVERT(), expects three parameters,
data_type – The data type into which to cast expression.
expression – The value to be cast.
style – Optional integer expression that specifies how the TRY_CONVERT function is to translate expression.

Example,
SELECT TRY_CONVERT(datetime2, ’02/18/2012′, 103) AS [Using TRY_CONVERT Function];
GO
OUTPUT:
NULL
As you can see the both queries fail conversion but only first query that is using COVERT function throws error whereas query that is using TRY_CONVERT returns NULL indicating that conversion fails.

Date and time functions
These functions are mainly to manipulate data related to dates.
DATEFROMPARTS – The DATEFROMPARTS function, returns a date value with the date part set to the specified year, specified month and the specified day, and the time portion set to the default.
DATEFROMPARTS ( year, month, day )
DATEFROMPARTS(), expects three parameters,
Year – Integer expression specifying a year.
Month – Integer expression specifying a month, from 1 to 12.
Day – Integer expression specifying a day.

DATETIMEFROMPARTS – The DATETIMEFROMPARTS function, returns full datetime value with the date time part set to the specified year, specified month, specified day, specified hour, specified minute, specified second and the specified milliseconds.
Syntax:
DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )

DATETIMEFROMPARTS – The DATETIMEFROMPARTS function, returns full datetime value with the date time part set to the specified year, specified month, specified day, specified hour, specified minute, specified second and the specified milliseconds.
Syntax:
DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
DATETIMEFROMPARTS(), expects seven parameters,
Year – Integer expression specifying a year.
Month – Integer expression specifying a month, from 1 to 12.
Day – Integer expression specifying a day.
Hour – Integer expression specifying hours.
Minute – Integer expression specifying minutes.
Seconds – Integer expression specifying seconds.
Milliseconds – Integer expression specifying milliseconds.

DATETIME2FROMPARTS – The DATETIME2FROMPARTS function, returns full datetime2 value with the date time part set to the specified year, specified month, specified day, specified hour, specified minute, specified second and the specified precision.
Syntax:
DATETIME2FROMPARTS ( year, month, day, hour, minute, seconds, fractions, precision )
DATETIME2FROMPARTS(), expects eight parameters,
Year – Integer expression specifying a year.
Month – Integer expression specifying a month, from 1 to 12.
Day – Integer expression specifying a day.
Hour – Integer expression specifying hours.
Minute – Integer expression specifying minutes.
Seconds – Integer expression specifying seconds.
Fractions – Integer expression specifying fractions.
Precision – Integer literal specifying the precision of the datetime2 value to be returned.

SMALLDATETIMEFROMPARTS – The SMALLDATETIMEFROMPARTS function, returns full datetime value with the date time part set to the specified year, specified month, specified day, specified hour and the specified minute.
Syntax:
SMALLDATETIMEFROMPARTS ( year, month, day, hour, minute )
SMALLDATETIMEFROMPARTS(), expects five parameters,
Year – Integer expression specifying a year.
Month – Integer expression specifying a month, from 1 to 12.
Day – Integer expression specifying a day.
Hour – Integer expression specifying hours.
Minute – Integer expression specifying minutes.

DATETIMEOFFSETFROMPARTS – The DATETIMEOFFSETFROMPARTS function returns a full datetimeoffset. The OFFSET argument is basically used to represent the time zone offset value hour and minutes.
Syntax:
DATETIMEOFFSETFROMPARTS ( year, month, day, hour, minute, seconds, fractions, hour_offset, minute_offset, precision )
DATETIMEOFFSETFROMPARTS(), expects ten parameters,
Year – Integer expression specifying a year.
Month – Integer expression specifying a month, from 1 to 12.
Day – Integer expression specifying a day.
Hour – Integer expression specifying hours.
Minute – Integer expression specifying minutes.
Seconds – Integer expression specifying seconds.
Fractions – Integer expression specifying fractions.
Hour_offset – Integer expression specifying the hour portion of the time zone offset.
Minute_offset – Integer expression specifying the minute portion of the time zone offset.
Precision – Integer literal specifying the precision of the datetimeoffset value to be returned.

TIMEFROMPARTS – The TIMEFROMPARTS function, returns a full time value as shown in the below query result. It is important to note that the fractions argument actually depends on the precision argument.
When fractions have a value of 5 and precision has a value of 1, then the value of fractions represents 5/10 of a second. When fractions have a value of 50 and precision has a value of 2, then the value of fractions represents 50/100 of a second. When fractions have a value of 500 and precision has a value of 3, then the value of fractions represents 500/1000 of a second.
Syntax:
TIMEFROMPARTS ( hour, minute, seconds, fractions, precision )
TIMEFROMPARTS(), expects five parameters,
Hour – Integer expression specifying hours.
Minute – Integer expression specifying minutes.
Seconds – Integer expression specifying seconds.
Fractions – Integer expression specifying fractions.
Precision – Integer literal specifying the precision of the time value to be returned.

EOMONTH –
This is very handy function with sql server 2012. This function takes two parameters first being start_date which is mandatory and the second one is Month_to_add which is optional. This function will return the last day of the month (also termed as EOM or end of the month) for the given date.

EOMONTH ( start_date [, month_to_add ] )
EOMONTH(), expects two parameters,
Start_date – Date expression specifying the date for which to return the last day of the month.
Month_to_add – Optional integer expression specifying the number of months to add to start_date.


Example:
Execute the following:
DECLARE @STARTDATE DATETIME = GETDATE()
SELECT EOMONTH (@STARTDATE, 1) AS [Using EOMONTH Function]
GO
Here is the result set:
Using EOMONTH Function
2014-02-28

Logical Functions:
CHOOSE – This function can be used to return the value out of a list based on its index number (Note: Index no. here starts from 1).
Syntax:
CHOOSE ( index, val_1, val_2 [, val_n ] )
CHOOSE(), expects two parameters,
Index – Is an integer expression that represents a 1-based index into the list of the items following it.
Value – List of values of any data type.

IIF – Conditional function which will return the value based on the condition you specified as the first argument. This is similar to SSRS IIF expression.
Syntax:
IIF ( boolean_expression, true_value, false_value )
IIF(), expects three parameters,
Boolean_expression – A valid Boolean expression.
True_value – Value to return if boolean_expression evaluates to true.
False_value – Value to return if boolean_expression evaluates to false.

String Functions:
CONCAT – It’s the same concatenate function that we use in excel, it will concatenate two or more strings to make it single string. It implicitly converts all arguments to string types.
example,
select CONCAT(NULL,'Yahoo') AS NullYahoo

FORMAT – Function for locale-aware formatting of date/time and number values as strings.
Syntax:
FORMAT ( value, format [, culture ] )
FORMAT(), expects at three parameters,
Value – Expression of a supported data type to format.
Format – nvarchar format pattern.
Culture – Optional nvarchar argument specifying a culture.

THROW -
Raises an exception and transfers execution to a CATCH block of a try/catch statement.
Reduces the need to use RAISERROR in TRY/CATCH blocks.

Can provide custom error messages.

Example,
BEGIN TRY
   SELECT CONVERT(INT,'A1000')
END TRY
BEGIN CATCH
THROW 51000, 'Can not convert this string(Throw an error by Asanka)', 1;
END CATCH;

These are the various SQL built in functions that are quite useful for any SQL lovers!

Monday, January 6, 2014

Love your Job ! But.. Not your Company!

Well, I am back here after a year, reasons why i have chose this topics are many. One of the reason could be One fine day i got a call from my childhood friend who was working for a reputed company in India and was shocked to hear that he was fired from the company. He was frustrated , but i was laughing and asking myself "is this guy kidding me?" because he was such an asset to any company. But after one year of his resignation he was not able to find a job. absolutely, sometime you are doing better than others but company throw you for any other reason, "boss is always right" try to break this rule & you will find yourself out of the company very soon without proper reason, while your sales is good, your working is good, your relation with other is good.

When i made a  call to mind about this incident, i decided to write a post on this.

Yes, Especially in India where job changeovers across segments despite talent.It takes two hands to clap! What then happens really depends on the confidence and ability of the organisation's leadership to embrace and mold differences. It takes a keen leader to successfully manage different personalities and abilities and knit these into a very successful and performing team.Loving your job helps you perform better and enjoy whatever task you are assigned to do! Loving your company motivates you and fuels the love you have for your job.

These days with global market, relationship and interest that companies have for global market, it is hard to predict how your employer would react to such fluctuating market! For them designing a work-force that can produce more profit is a big agenda. Some companies consider you as important asset to reach that goal, but many others feel you are replaceable. It all comes to one principle, find a right company if you can and be smart when you apply for a job. Once you find the right company be loyal to them, help them grow and be a part of their journey.

In today's environment where restructuring is seen as part of doing business, howsoever effective, loyal or honest you may be, it comes down heavy when the company wants to get the organization in shape. Loyalty has become a rare quality in this day and age. Having said that, one should still remain as loyal as possible while with an organisation, but it never hurts to keep feelers out. One can wind up on the sidewalk in an awful rush.

Love yourself first. Love what you do. Propose your ideas to the Company. Make a few friends, or not, with your co workers. Completely choose to separate your business life/personal life, it's up to you. Isn't it better when your Happy with who you are? There will be people, in our lives, that bring us down. Ultimately, you have the power to love, be loved and to choose your path. We all need POSITIVE in our lives, as our world leaders are confronted, with these exact feelings. It has saturated, the persons, in charge of our great world. So I say, "Love Yourself, Love Who You Are, Be the Best You can Be. But, remember you too can be replaced, at any given time.



Here's a non-sugar-coated, not touchy-feely, un-politically-correct, not evolved, non-progressive perspective:

Companies are neither good nor bad. They simply are a collection of people recruited to deliver value to shareholders. Let that sink in a moment before continuing. The people in companies create the culture. The culture fits for the individual or it doesn't. If it doesn't, the individual can:
1) Leave (easiest option)
2) Change to fit the culture (a big task)
3) Change the culture (usually impossible).

Managers have personalities / styles. If the employee does not fit with the manager's personality or style, there choices mirror the three in the paragraph above. None of this makes the company good or bad. You fit your culture and can work with your manager's style, or you don't. Quit whining, make your choice, and get on with it. If you really think the company is plotting against you with nefarious intent, you have delusions of grandeur. Fact is, you just are not that important. You, like everybody else

 will, be replaced when the value you deliver falls below what the company can receive from a competitor (somebody else who wants your job).

It's healthy and good for your emotional and professional well-being to love the work, and respect the company, but not expect the company to love or protect you back. I think all of us have been there, especially those of us who are over 23. We put a lot of passion and creativity in our work, and then the company makes a switchback, and you are no longer so loved. You then become marginalized, which is the neon sign that you should be on your way to another position. It's also natural to feel betrayed and angry, and those feelings shouldn't sandbag you, they should prompt you to get moving.a