My journey towards DevOps implementation

Posted: May 26, 2016 in Uncategorized

Nowadays, you will find most the peoples belonging to IT industry speaking about DevOps. To the peoples, who do not know the power of the DevOps, is merely the simple term. But the peoples, who knows that, its really a boon to relieve them from the lot of the boring tasks they had been performing, regardless of their interest.

When i elaborate DevOps term technically then,

DevOps is a culture, movement or practice that emphasizes the collaboration and communication of both software developers and other information-technology (IT) professionals while automating the process of software delivery and infrastructure changes.It aims at establishing a culture and environment where building, testing, and releasing software, can happen rapidly, frequently, and more reliably.

In a layman language, DevOps is a mechanism via which using the list of tools, you can automatize the routine  software development related tasks. e.g. Compile, test, package, release etc.

In my recent job role, i got an opportunity to implement the DevOps for a company, where the peoples were used to follow the legacy software development practices. The company was using the Microsoft based stack (.Net) for their development purpose. The goal i had to achieve was to implement the DevOps technology successfully here and also make the peoples aware and educated for the benefits of the same.

This article is the first article from the next series of articles i am going to write, to share the knowledge, i have gained during my efforts for an implementation of DevOps.

How did i do it ?

When it comes to automate the development environment, it is really important that which list of tools you have chosen in your development practices.

My primary aim in DevOps implementation was to achieve the below things.

  • Continuous Build
  • Continuous Test
  • Continuous Packaging
  • Continuous Delivery

In order to achieve the above goals, first i had to opt the better version control system. My first aim was to stabilize the way the application is developed. While SVN is the most widely used version control system, when it comes to branching and merging, it becomes harder for the new bees to get into it. I was looking for a tool, which all the developers can easily learn, even though being the most robust. My search ended with Git. The Git-flow concept supported by Git charmed me a lot and convinced me to include Git in my bucket.

Now after choosing the Git, my next hurdle was to build the changes committed by developers continuously. I required to build both the changes of develop branch and master branch continuously. For this purpose, now i had to choose the best Continuous Integration tool available in a market. Initially, i put my hands on Go Server, but after sometime i found that the Go Server is not capable of serving the goals i am looking for (due to some plugins limitations and other reasons). Hence, i tried the other tool, which i can say the best tool available in the market named Jenkins. In Jenkins i setup the build jobs for both the develop and master branch, which will run continuously upon detection of any new changes into the repository.

After setting up Continuous Build, the next thing i had to implement was Continuous Test. When it comes to the unit testing, i prefer NUnit being a fan of an open source technologies. So, for the Continuous Testing i configured few jobs in Jenkins, to run after the successful build of an application (Setup as a part of Continuous Build).

Next thing came up after the Continuous Test was the Continuous Packaging. For a tracked release, each of the artifacts should be properly versioned. In order to do so, i choose a Nuget approach. But in order to have some more capability, i opted Chocolatey, which uses the nuget packages, but can be used for having the apt-get(available in Ubuntu) functionality in Windows environment. Once the automated test passes in a previous step, i configured packaging the artifacts with proper versioning and uploading them to the Chocolatey Server  via Jenkins.

Finally, in order to take care of automating the release of a database changes, i used and followed the practice suggested by them. I also configured the job in Jenkins to release the database changes automatically, to avoid human intervention.

So, based on the configuration done up to now, i was able to have the artifacts based on the latest changes carried out to any application. The next step, i took was, to create some batch script to deploy the above artifacts onto the UAT and Production servers to make it available to the final audience. This can also be automated using Jenkins to deploy the packages on the server based on your preferred configuration.

So, at this stage, i was able to successfully implement to automate the process from development to release using the DevOps technology.

How did it benefited to me?

After reading such a big article, definitely you guys should be thinking that, what would be the benefit to walk on such a big path?

In my case, earlier before this, i and my colleague, used to spend our weekend to the office for the application release. We used to release near by 7 applications every week. So from the morning, we were staring compiling the applications, publishing them, uploading them to the server, backing up the previous version of application on server, install the latest version, and then test the deployment. If any release error or other error are found during the above exercise, we used to repeat the process again. You can understand, how boring and worst our situation was.

Now, after implementation of DevOps , it takes only 20 minutes to release all the applications on the server. So, i an my colleague now better spend our time with our family..!!


I hope, this article would give the enthusiastic people an enough guidance to start their journey towards the  DevOps implementation.

Please note, this article is the first article from the next series of articles i am going to write, to share the knowledge, i have gained during my efforts for an implementation of DevOps. I would also try my best to share the video tutorial for the same with you my friends.



How to be a good leader..!!

Posted: May 19, 2016 in Uncategorized

At certain level of experience, every person wants to be a leader. For few peoples,leading skills are god gifted, while for others, they needs to develop it.

As per my view, there are few things,which needs to be taken care of, for being a good leader.

1)Keep proper balance between the management and your team. : Most of the times, leaders are failing to maintain a proper balance between their team and the expectation from the upper management. It should be noted that, being a leader, you are the bridge between the management and your team. So, if bridge is weak then definitely, it would be tough to keep the things rolling properly. I have seen that,many leaders just pass the same information or the executable from the upper management to their team. This way, sometimes, it becomes very tough for the team members, to execute it in a proper timeline. Instead of this, the lead should first analyze the executable and make sure that,whether the expectation of management is realistic. If not, then the lead should raise a voice and explain the management for the pits and falls of that. This way, it would be beneficial to both of his team and management to visualize the matter properly, resulting to the happy faces from both of the peoples.

2)Be self confident. : This is one of the essential requirement to be a good leader. You should be enough confident for the role you are performing. Sometimes, the person can be good at execution level, but not good at leading level. If this is the case for you, just explain the management about your interest and decline to be leader. This will not create a wrong impression to the management, rather it would create an impression that, you know very well, for the which skills you are best with.

Also to gain the more confidence, you should have the enough knowledge for the role and the responsibilities you are belonging to. It is always said the “half knowledge is dangerous”. If you are not sure about the matter or discussion, you should never show your confidence, for the wrong things. It always creates the negative impression. Instead, you can explain that, you don’t know it and will need to do some exercise for it, to give your better thoughts on that. This is far more good, rather than showing a wrong confidence.

Sometimes, i have seen that, in a discussion with the management, even though you are correct, you encounters circumstances, where you cant explain the same to management. Here, your real leading skills comes into the picture. Never, stop anyone in between,while he is explaining his views. Once he is done, you can raise your hand to explain your views and can convince them for the dark side the matter, over which you are confident. This way, it will allow the management, to understand your views correctly and consider those, before putting anything into an action.

Here, i remember, the way my leader was dealing with me, while i was writing some messy code. His way to explain the thing was something like this.

“Ashish, you have really done a great job..!! Awesome..!! However, i would appreciate, if you would do it via this way”.

If you read above quoted sentence carefully, then you can have an idea that, he admires me, but later asks me to take the action he wants. This way, it would help both of us to do the things happily, without hurting anyone’s sentiments passively.

3)Compete you with your self only. : In my life, i strictly follow this. I have seen since the school days, most of the peoples compare their selves with some other ones and keep running in the race. But, the thing they should clearly know is, the power which that guy has, he couldn’t have but at the same time, the power you have that the other guy can not have. They why to degrade our selves by such a meaningless comparison? Instead, you should identify your strengths, and should try to more strengthen it. This would give you the best outcome.

If i will try myself being a singer by comparing my self to some of the good singer, then definitely i am not going to earn a penny in singing, even though i am master in programming. On the other hand, if that singer would try to put his hands for programming, then he would have to loss the income he is earning from singing. So, here the thing can be understood that, both of the singer and programmer have their own strengths, and they should put their best into the direction they are good with, rather than trying something else, to get the best outcome.

Most of the times, i have found that parents are comparing their child’s result with the other ranker in the class. This way it demoralize their child. Instead, they should compare their  child’s own progress from the previous one. This would be rather a healthy competition for him. Because, in any interview i appeared, i never found that, interviewer asked me that, who was the ranker in your class?

4)Treat your team member as your family. : The outcome that emotions can do, can’t the professionalism can do. It is well told by newton that, “Action and reaction are equal and opposite”. So, if you will be over professional with your team, then the same they will be with you. You should make them feeling them, that you are one of them. Instead of continuously watching their activities, give them enough space for performing their job on their comfort. This way, they would be more happy and would be able to give their best.

“Lions in cage are not a king”. They will just follow the instructions of their master, and wont do anything else than that. Similarly, your continuous interference with the team member’s activity, can lead them to the mind state, where they will later only follow what you say,rather then applying their own thoughts.

Please note, the contents given in this article are solely my views. You can have your own views for the same too. I wish, the information given here can be useful to the interested readers.

Its fun to be your own boss

Posted: May 18, 2016 in General

The title of the blog could lead to a lot of excitement to most of the peoples, who really want to work independently and be their own boss. But this can turn realistic only if you open the door when opportunity is really knocking it. Nothing comes for free and there are pros and cons for everything in life. Same goes for being your own boss.

In my case, I started working as a junior developer and have achieved regular milestones to arise to the level of Directorate in my own software organization. Definitely depicts that, I have seen the professional life from an employee to an employer. As an employee you are never concerned about bringing new business, risk calculations on business front and many other factors to run a successful business. But along with this also comes disadvantages of job insecurity, corporate politics, traveling etc. Contrary, as an employer, you need to focus mainly on structured business flow, its expansion on timely basis, managing vendors, clients and of course the most important your own resources (employees in your organization). Briefly, Employer is somewhat more challenging, making you live life on edge everyday and can make wonders if you succeed whereas as an Employee, you have a fix chunk, don’t need to worry for anything once you leave your desk and life seems somewhat peaceful. But then it’s an individual call, what suits you the best or to be more precise, what role do you love, to which you can give your best.

Nowadays, there are lots of opportunities to turn an individual from an Employee to an Employer. One of them in my working sector is freelancing sites, giving hundreds of opportunities to everyone working in the IT sector. But on most of these freelance sites, I have observed that they welcome everyone, without a proper screening of technical backgrounds and hence may sometimes prove very disappointing for the client providing work.

During my journey to search the better service provider providing freelancing work, I came across this site – Toptal (, and on digging more into it, to understand the process of their work allotment, I figured out that they are really emphasizing on getting the best talents out of the globe rather than opening the doors for everyone. They have a very well defined screening process and based on that the candidate is allowed to be a part of their team. This guarantees to have the best person doing the right job and producing the best output.

I am yet to start analyzing their screening process and as a part of that, I have scheduled a call with these guys. In my next blog, I would try to update you all with the steps taken by them for the screening process in depth.

The thoughts given in this blog is my personal view and there might be differences with yours. Though, I hope that the information provided here, would be helpful to the readers to choose their next career path


I am back on blogs after a very long time. In this blog, i would mainly like to focus on the importance of Data Integrity for a better software product.

Recently, i have been working on a product which is really a very large product, but the main issue i have seen with that is, there is no data integrity. Most of the times developers and DBA are involved with cleaning up the bad data. Even most issues reported are the consequence of the bad data. The problem is up to an extent that, we have to develop several utilities, which runs periodically, to clean  the bad data.

So the question is, can’t we prevent creating such a bad data? And obviously my answer is yes, we can.

A most common way to ensure data integrity would be to use SQL transactions. So, now you should be thinking that even being a very large product, didn’t we opted for SQL transactions? Ya we did, but the issue was other at our hand.

Please read below brief details, to better understand the problem, i want to explain here.

We have a kind of N-tier architecture. We have named our architecture as MPRV. Where “M” stands for “Model“, “P” for “Process“, “R” for “Regulator” and “V” for “View“. In this architecture, a Handler would be an entry gate to deal with any processes. Processes will in turn deal with models. Models will communicate with the Data Access layer. And the Data Access layer would communicate with the database finally. Good Flow right?

Please refer below image to visually understand the details i have provided above.

Architecture Flow

Figure 1 : Architecture Flow

Now, if we consider a flow given in a Figure 1 above, then we can easily manage transactions using SQL transaction at data access layer and can manage data integrity. This is the most common way most guys and doing.

Please refer below image to know the problem at our level. In our case, a handler is calling a process and a process may fork its call to three different models, each model is belonging to a separate data access layer. Now what i want is, if an error occurs during saving a data in “Data Access 1″ layer, then no data should be saved at “Data Access 2″ or “Data Access 3″ layer. Those should have been roll backed.  So, in this case, if we use a SQL transaction then, it would be tough to manage data integrity.

Few stupid answers would be, move the SQL queries from all these 3 data access layers to a single data access layer and then using a single method call from process and methods perform the action. But, this is not a solution. This is a fix, and what i need is a solution for a long life of our product and a better code maintainability.



Figure 2 : Transaction Management Issue

During my tenure with previous company, we had been tackling such situations using the “TransactionScope” class available in a framework.  For this case, we can place a code inside a process method and model methods in between TransactionScope . Please refer Figure 3 below, to get a more idea about what i mean to say here.

Figure 3: Proposed Solution

Figure 3: Proposed Solution


From an above Figure 3, if we place a code of process method and model methods inside a TransactionScope, then whenever an error will occur either from any data access layer or model layers, all changes would be committed only if the “TransactionScope” for a process is committed.  So, we can say that no orphan data any more..!!

If anyone have trouble understanding this article or else if needs any further information, please give your views in a comment, so that in my next blog, if needed then i can provide you some coding examples.

Hope information included in this article would be useful to its reader.


VB.NET and C# Syntax Comparison

Posted: March 4, 2011 in Uncategorized

VB.NET Program Structure C#
Imports System

Namespace Hello
   Class HelloWorld

      Overloads Shared Sub Main(ByVal args() As

         Dim name As String = “VB.NET”

         ‘See if an argument
was passed from the command line

          If args.Length = 1 Then name
= args(0)

” & name & “!”)

      End Sub

   End Class

End Namespace

using System;

namespace Hello {
   public class HelloWorld {
      public static void Main(string[] args) {
         string name = “C#”;

         // See if an argument
was passed from the command line

         if (args.Length == 1)
            name = args[0];

         Console.WriteLine(“Hello, ” + name +

VB.NET Comments C#
‘ Single line only
REM Single line only
”’ <summary>XML comments</summary>

// Single line
/* Multiple
    line  */
/// <summary>XML comments on single line</summary>
/** <summary>XML comments on multiple lines</summary> */

VB.NET Data Types C#

Value Types
Byte, SByte
Short, UShort, Integer, UInteger, Long, ULong
Single, Double
Date   (alias of System.DateTime)

Reference Types

Dim correct As Boolean = True
Dim b As Byte = &H2A   ‘hex or &O52 for octal
Dim person As Object = Nothing
Dim name As String = “Dwight”
Dim grade As Char = “B”c
Dim today As Date = #12/31/2010 12:15:00 PM#
Dim amount As Decimal = 35.99@
Dim gpa As Single = 2.9!
Dim pi As Double = 3.14159265
Dim lTotal As Long = 123456L
Dim sTotal As Short = 123S
Dim usTotal As UShort = 123US
Dim uiTotal As UInteger = 123UI
Dim ulTotal As ULong = 123UL

Implicitly Typed Local Variables
Dim s = “Hello!”
Dim nums = New Integer() {1, 2, 3}
Dim hero = New SuperHero With {.Name = “Batman”}

Type Information
Dim x As Integer

‘ Prints System.Int32

Console.WriteLine(GetType(Integer))   ‘ Prints System.Int32

‘ Prints Integer

Dim c as New Circle
If TypeOf c Is Shape Then _
    Console.WriteLine(“c is a Shape”)

Type Conversion / Casting
Dim d As Single = 3.5

Dim i As Integer = CType(d, Integer)   ‘ set
to 4 (Banker’s rounding)

i = CInt(d)  ‘ same result as CType
i = Int(d)    ‘ set to 3 (Int function truncates
the decimal)

Dim o As Object = 2
i = DirectCast(o, Integer)   ‘ Throws InvalidCastException
if type cast fails

Dim s As New Shape
Dim c As Circle = TryCast(s, Circle)   ‘ Returns Nothing
if type cast fails

Value Types
byte, sbyte
short, ushort, int, uint, long, ulong
float, double
DateTime   (not a built-in C# type)

Reference Types

bool correct = true;
byte b = 0x2A;   // hex
object person = null;
string name = “Dwight”;
char grade = ‘B’;
DateTime today = DateTime.Parse(“12/31/2010 12:15:00 PM”);
decimal amount = 35.99m;
float gpa = 2.9f;
double pi = 3.14159265;
long lTotal = 123456L;
short sTotal = 123;
ushort usTotal = 123;
uint uiTotal = 123;
ulong ulTotal = 123;

Implicitly Typed Local Variables
var s = “Hello!”;
var nums = new int[] { 1, 2, 3 };
var hero = new SuperHero() { Name = “Batman” };

Type Information
int x;
 // Prints System.Int32
  // Prints System.Int32

Console.WriteLine(x.GetType().Name);   // prints Int32

Circle c = new Circle();
if (c is Shape)
    Console.WriteLine(“c is a Shape”);

Type Conversion / Casting

float d = 3.5f;

i = Convert.ToInt32(d);     // Set to 4 (rounds)

int i = (int)d;     // set to 3 (truncates decimal)

object o = 2;
int i = (int)o;   // Throws InvalidCastException if type
cast fails

Shape s = new Shape();
Circle c = s as Circle;   // Returns null if type
cast fails

VB.NET Constants C#
Const MAX_STUDENTS As Integer = 25

‘ Can set to a const or var; may be initialized in a constructor
ReadOnly MIN_DIAMETER As Single = 4.93

const int MAX_STUDENTS = 25;

// Can set to a const or var; may be initialized in a constructor

readonly float MIN_DIAMETER = 4.93f;

VB.NET Enumerations C#
Enum Action

  [Stop]   ‘ Stop is a reserved word


End Enum

Enum Status

  Flunk = 50

  Pass = 70

  Excel = 90

End Enum

Dim a As Action = Action.Stop

If a <> Action.Start Then _

   Console.WriteLine(a.ToString & ” is ” & a)    
‘ Prints “Stop is 1”

Console.WriteLine(Status.Pass)     ‘ Prints

Prints Pass

enum Action {Start, Stop, Rewind, Forward};
enum Status {Flunk = 50, Pass = 70, Excel = 90};

Action a = Action.Stop;
if (a != Action.Start)
  Console.WriteLine(a + ” is ” + (int) a);    //
Prints “Stop is 1”

Console.WriteLine((int) Status.Pass);    // Prints

Console.WriteLine(Status.Pass);      // Prints

VB.NET Operators C#

=  <  >  <=  >=  <>

+  –  *  /
(integer division)
(raise to a power)

=  +=  -=  *=  /=  \=  ^=  <<=  >>= 

And   Or   Xor   Not   <<   >>

AndAlso   OrElse   And   Or   Xor   Not

Note: AndAlso and OrElse perform short-circuit logical evaluations

String Concatenation

==  <  >  <=  >=  !=

+  –  *  /
(integer division if both operands are ints)
Math.Pow(x, y)

=  +=  -=  *=  /=   %=  &=  |=  ^= 
<<=  >>=  ++  —

&   |   ^   ~   <<   >>

&&   ||   &   |   ^   !

Note: && and || perform short-circuit logical evaluations

String Concatenation

VB.NET Choices C#

‘ Ternary/Conditional operator (IIf evaluates 2nd and 3rd expressions)
greeting = If(age < 20, “What’s up?”, “Hello”)

‘ One line doesn’t require “End If”
If age < 20 Then greeting = “What’s up?”

If age < 20 Then greeting = “What’s up?” Else greeting =

‘ Use : to put two commands on same line
If x <> 100 AndAlso y < 5 Then x *= 5 : y *= 2  

‘ Preferred
If x <> 100 AndAlso y < 5 Then
  x *= 5

  y *= 2
End If

‘ Use _ to break up long single line or use implicit line break
If whenYouHaveAReally < longLine And

  itNeedsToBeBrokenInto2 > Lines Then _

If x > 5 Then

  x *= y

ElseIf x = 5 OrElse y Mod 2 = 0 Then

  x += y

ElseIf x < 10 Then

  x -= y


  x /= y

End If

Select Case color   ‘ Must be a primitive data

  Case “pink”, “red”
    r += 1

  Case “blue”

    b += 1

  Case “green”

    g += 1

  Case Else

    other += 1

End Select

// Ternary/Conditional operator
greeting = age < 20 ? “What’s up?” : “Hello”;

if (age < 20)
  greeting = “What’s up?”;
  greeting = “Hello”;

// Multiple statements must be enclosed in {}
if (x != 100 && y < 5) {   
  x *= 5;
  y *= 2;

No need for _ or : since ; is used to terminate each statement.

(x > 5)

  x *= y;

else if (x == 5 || y % 2 == 0)

  x += y;

else if (x < 10)

  x -= y;


  x /= y;

// Every case must end with break or goto case

switch (color) {                         
// Must be integer or string
  case “pink”:
  case “red”:    r++;    break;

  case “blue”:   b++;   break;
  case “green”: g++;   break;
  default:    other++;   break;
      // break necessary on default

VB.NET Loops C#
Pre-test Loops:
While c < 10

  c += 1

End While

Do Until c = 10 
  c += 1


Do While c < 10

  c += 1


For c = 2 To 10 Step 2



Post-test Loops:
  c += 1

Loop While c < 10
  c += 1

Loop Until c = 10

‘  Array or collection looping
Dim names As String() = {“Fred”, “Sue”, “Barney”}

For Each s As String In names



‘ Breaking out of loops
Dim i As Integer = 0
While (True)
  If (i = 5) Then Exit While
  i += 1
End While

‘ Continue to next iteration
For i = 0 To 4
  If i < 4 Then Continue For
  Console.WriteLine(i)   ‘ Only prints 4

Pre-test Loops:  

// no “until” keyword
while (c < 10)


for (c = 2; c <= 10; c += 2)


Post-test Loop:



while (c < 10);

// Array or collection looping
string[] names = {“Fred”, “Sue”, “Barney”};
foreach (string s in names)

// Breaking out of loops
int i = 0;
while (true) {
  if (i == 5)

// Continue to next iteration
for (i = 0; i <= 4; i++) {
  if (i < 4)
  Console.WriteLine(i);   // Only prints 4

VB.NET Arrays C#

Dim nums() As Integer = {1, 2, 3} 
For i As Integer = 0 To nums.Length – 1



‘ 4 is the index of the last element, so it holds 5 elements
Dim names(4) As String

names(0) = “David”
names(5) = “Bobby”  ‘ Throws System.IndexOutOfRangeException

‘ Resize the array, keeping the existing values (Preserve is optional)
ReDim Preserve names(6)

Dim twoD(rows-1, cols-1) As Single

twoD(2, 0) = 4.5

Dim jagged()() As Integer = { _

  New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }

jagged(0)(4) = 5

int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)

// 5 is the size of the array
string[] names = new string[5];
names[0] = “David”;
names[5] = “Bobby”;   // Throws System.IndexOutOfRangeException

// C# can’t dynamically resize an array.  Just copy into
new array.

string[] names2 = new string[7];

Array.Copy(names, names2, names.Length);   // or names.CopyTo(names2,

float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f; 

int[][] jagged = new int[3][] {

  new int[5], new int[2], new int[3] };
jagged[0][4] = 5;

VB.NET Functions C#

‘ Pass by value (in, default), reference (in/out), and reference

Sub TestFunc(ByVal x As Integer, ByRef y As Integer, ByRef
z As Integer)
  x += 1
  y += 1

  z = 5

End Sub

Dim a = 1, b = 1, c As Integer   ‘ c set
to zero by default

TestFunc(a, b, c)

Console.WriteLine(“{0} {1} {2}”, a, b, c)   ‘ 1 2

‘ Accept variable number of arguments

Function Sum(ByVal ParamArray nums As Integer()) As Integer

  Sum = 0 

  For Each i As Integer In nums

    Sum += i


End Function   ‘ Or use Return statement like

Dim total As Integer = Sum(4, 3, 2, 1)   ‘ returns 10

‘ Optional parameters must be listed last and must have
a default value

Sub SayHello(ByVal name As String, Optional ByVal prefix As String
= “”)
  Console.WriteLine(“Greetings, ” & prefix & ” ” & name)

End Sub

SayHello(“Strangelove”, “Dr.”)

// Pass by value (in, default), reference (in/out), and reference

void TestFunc(int x, ref int y, out int z) {
  z = 5;

int a = 1, b = 1, c;  // c doesn’t need initializing
TestFunc(a, ref b, out c);
Console.WriteLine(“{0} {1} {2}”, a, b, c);  // 1 2 5

// Accept variable number of arguments
int Sum(params int[] nums) {
  int sum = 0;
  foreach (int i in nums)
    sum += i;
  return sum;

int total = Sum(4, 3, 2, 1);   // returns 10

/* C# 4.0 supports optional parameters. Previous versions required
function overloading. */

void SayHello(string name, string prefix = “”) {
  Console.WriteLine(“Greetings, ” + prefix + ” ” + name);

SayHello(“Strangelove”, “Dr.”);

VB.NET Strings C#

Special character constants (all also accessible from ControlChars

vbCrLf, vbCr, vbLf, vbNewLine






‘ String concatenation (use & or +)

Dim school As String = “Harding” & vbTab
school = school & “University” ‘ school is “Harding (tab)

‘ Chars
Dim letter As Char = school.Chars(0)   ‘ letter
is H

letter = “Z”c                    
‘ letter is Z

letter = Convert.ToChar(65)              
 ‘ letter is A

letter = Chr(65)                                 ‘ same thing

Dim word() As Char = school.ToCharArray() ‘ word holds

‘ No string literal operator

Dim msg As String = “File is c:\temp\x.dat”

‘ String comparison
Dim mascot As String = “Bisons”
If (mascot = “Bisons”) Then   ‘ true
If (mascot.Equals(“Bisons”)) Then   ‘ true
If (mascot.ToUpper().Equals(“BISONS”)) Then  

If (mascot.CompareTo(“Bisons”) = 0) Then   

‘ String matching with Like – Regex is more powerful
If (“John 3:16” Like “Jo[Hh]? #:*”) Then   ‘true

‘ Substring
s = mascot.Substring(2, 3)) ‘ s is “son”

‘ Replacement
s = mascot.Replace(“sons”, “nomial”)) ‘ s is “Binomial”

‘ Split
Dim names As String = “Michael,Dwight,Jim,Pam”
Dim parts() As String = names.Split(“,”.ToCharArray())  
‘ One name in each slot

‘ Date to string
Dim dt As New DateTime(1973, 10, 12)
Dim s As String = “My birthday: ” & dt.ToString(“MMM dd, yyyy”)   ‘ Oct 12, 1973

‘ Integer to String
Dim x As Integer = 2
Dim y As String = x.ToString()     ‘ y is “2”

‘ String to Integer
Dim x As Integer = Convert.ToInt32(“-5”)     ‘ x is

‘ Mutable string

Dim buffer As New System.Text.StringBuilder(“two “)
buffer.Append(“three “)
buffer.Insert(0, “one “)
buffer.Replace(“two”, “TWO”)
‘ Prints “one TWO three”

Escape sequences
\r    // carriage-return
\n    // line-feed
\t    // tab
\\    // backslash
\”    // quote

// String concatenation
string school = “Harding\t”;

school = school + “University”;   // school is “Harding
(tab) University”

// Chars
char letter = school[0];           
// letter is H

letter = ‘Z’;                    
          // letter is Z
letter = Convert.ToChar(65);     // letter is A

letter = (char)65;                   
// same thing

char[] word = school.ToCharArray();  
// word holds Harding

// String literal

string msg = @“File is c:\temp\x.dat”;

// same as

string msg = “File is c:\\temp\\x.dat”;

// String comparison
string mascot = “Bisons”;

if (mascot == “Bisons”)    // true
if (mascot.Equals(“Bisons”))   // true
if (mascot.ToUpper().Equals(“BISONS”))  
// true

if (mascot.CompareTo(“Bisons”) == 0)   
// true

// String matching – No Like equivalent, use Regex

// Substring
s = mascot.Substring(2, 3))     // s is “son”

// Replacement
s = mascot.Replace(“sons”, “nomial”))     //
s is “Binomial”

// Split
string names = “Michael,Dwight,Jim,Pam”;
string[] parts = names.Split(“,”.ToCharArray());  
// One name in each slot

// Date to string
DateTime dt = new DateTime(1973, 10, 12);
string s = dt.ToString(“MMM dd, yyyy”);     // Oct 12,

// int to string
int x = 2;
string y = x.ToString();     // y is “2”

// string to int
int x = Convert.ToInt32(“-5”);     // x is -5

// Mutable string

System.Text.StringBuilder buffer = new System.Text.StringBuilder(“two

buffer.Append(“three “);

buffer.Insert(0, “one “);

buffer.Replace(“two”, “TWO”);

Console.WriteLine(buffer);     // Prints “one
TWO three”

VB.NET Regular Expressions C#

Imports System.Text.RegularExpressions

‘ Match a string pattern
Dim r As New Regex(“j[aeiou]h?. \d:*”, RegexOptions.IgnoreCase Or _
If (r.Match(“John 3:16”).Success) Then   ‘true
End If

‘ Find and remember all matching patterns
Dim s As String = “My number is 305-1881, not 305-1818.”
Dim r As New Regex(“(\d+-\d+)”)
Dim m As Match = r.Match(s)     ‘ Matches 305-1881
and 305-1818

While m.Success
    Console.WriteLine(“Found number: ” & m.Groups(1).Value & ” at position
” _
            & m.Groups(1).Index.ToString)
    m = m.NextMatch()

End While

‘ Remeber multiple parts of matched pattern
Dim r As New Regex(“(\d\d):(\d\d) (am|pm)”)
Dim m As Match = r.Match(“We left at 03:15 pm.”)
If m.Success Then
    Console.WriteLine(“Hour: ” & m.Groups(1).ToString)      
‘ 03
    Console.WriteLine(“Min: ” & m.Groups(2).ToString)      
  ‘ 15
    Console.WriteLine(“Ending: ” & m.Groups(3).ToString)  
‘ pm

End If

‘ Replace all occurrances of a pattern
Dim r As New Regex(“h\w+?d”, RegexOptions.IgnoreCase)
Dim s As String = r.Replace(“I heard this was HARD!”, “easy”)   ‘ I easy this was easy!

‘ Replace matched patterns
Dim s As String = Regex.Replace(“123 $1”)
  ‘ 456 > 123

‘ Split a string based on a pattern
Dim names As String = “Michael, Dwight, Jim, Pam”
Dim r As New Regex(“,\s*”)
Dim parts() As String = r.Split(names)   ‘ One name
in each slot

using System.Text.RegularExpressions;

// Match a string pattern

Regex r = new Regex(@”j[aeiou]h?. \d:*”, RegexOptions.IgnoreCase |

if (r.Match(“John 3:16”).Success)   // true

// Find and remember all matching patterns
string s = “My number is 305-1881, not 305-1818.”;
Regex r = new Regex(“(\\d+-\\d+)”);
// Matches 305-1881 and 305-1818
for (Match m = r.Match(s); m.Success; m = m.NextMatch())

    Console.WriteLine(“Found number: ” + m.Groups[1] + ” at position ”


// Remeber multiple parts of matched pattern
Regex r = new Regex(“@(\d\d):(\d\d) (am|pm)”);
Match m = r.Match(“We left at 03:15 pm.”);
if (m.Success) {
    Console.WriteLine(“Hour: ” + m.Groups[1]);       // 03

    Console.WriteLine(“Min: ” + m.Groups[2]);        
// 15

    Console.WriteLine(“Ending: ” + m.Groups[3]);  
// pm


// Replace all occurrances of a pattern
Regex r = new Regex(“h\\w+?d”, RegexOptions.IgnoreCase);
string s = r.Replace(“I heard this was HARD!”, “easy”));  
// I easy this was easy!

// Replace matched patterns
string s = Regex.Replace(“123 $1”);  
// 456 > 123

// Split a string based on a pattern
string names = “Michael, Dwight, Jim, Pam”;
Regex r = new Regex(@”,\s*”);
string[] parts = r.Split(names);   // One name in
each slot

VB.NET Exception Handling C#

‘ Throw an exception
Dim ex As New Exception(“Something is really wrong.”)

Throw  ex 

‘ Catch an exception
  y = 0
  x = 10 / y
Catch ex As Exception When y = 0 ‘ Argument
and When is optional




End Try

‘ Deprecated unstructured error handling
On Error GoTo MyErrorHandler

MyErrorHandler: Console.WriteLine(Err.Description)

// Throw an exception
Exception up = new Exception(“Something is really wrong.”);

throw up;  // ha ha

// Catch an exception
  y = 0;

  x = 10 / y;


catch (Exception ex) {   // Argument is optional,
no “When” keyword


finally {



VB.NET Namespaces C#

Namespace Harding.Compsci.Graphics 
End Namespace

‘ or

Namespace Harding

  Namespace Compsci

    Namespace Graphics 
    End Namespace

  End Namespace

End Namespace

Imports Harding.Compsci.Graphics

namespace Harding.Compsci.Graphics {

// or

namespace Harding {
  namespace Compsci {
    namespace Graphics {

using Harding.Compsci.Graphics;

VB.NET Classes / Interfaces C#

Access Modifiers

Protected Friend

Class Modifiers

Method Modifiers


‘ All members are Shared

‘ Partial classes
Partial Class Competition
End Class 

‘ Inheritance
Class FootballGame
  Inherits Competition
End Class 

‘ Interface definition
Interface IAlarmClock
  Sub Ring()
  Property TriggerDateTime() As DateTime
End Interface

‘ Extending an interface
Interface IAlarmClock

  Inherits IClock
End Interface

‘ Interface implementation
Class WristWatch 
  Implements IAlarmClock, ITimer

  Public Sub Ring() Implements IAlarmClock.Ring
    Console.WriteLine(“Wake up!”)
  End Sub

  Public Property TriggerDateTime As DateTime Implements IAlarmClock.TriggerDateTime
End Class 

Access Modifiers

protected internal

Class Modifiers


Method Modifiers


No Module equivalent – just use static class

// Partial classes
partial class Competition {

// Inheritance
class FootballGame : Competition {

// Interface definition

interface IAlarmClock {
  void Ring();

  DateTime CurrentDateTime { get; set; }

// Extending an interface 
interface IAlarmClock : IClock {

// Interface implementation

class WristWatch : IAlarmClock, ITimer {

  public void Ring() {
    Console.WriteLine(“Wake up!”);

  public DateTime TriggerDateTime { get; set; }

VB.NET Constructors / Destructors C#
Class SuperHero
  Private powerLevel As Integer

  Public Sub New()

    powerLevel = 0

  End Sub

  Public Sub New(ByVal powerLevel As Integer)

    Me.powerLevel = powerLevel

  End Sub

  Shared Sub New()
    ‘ Shared constructor invoked before 1st instance
is created

  End Sub

  Protected Overrides Sub Finalize() 
   ‘ Destructor to free unmanaged resources


  End Sub
End Class

class SuperHero {
  private int powerLevel;

  public SuperHero() {
     powerLevel = 0;

  public SuperHero(int powerLevel) {
    this.powerLevel = powerLevel; 

  static SuperHero() {
    // Static constructor invoked before 1st instance
is created


  ~SuperHero() {
    // Destructor implicitly creates a Finalize


VB.NET Using Objects C#

Dim hero As SuperHero = New SuperHero
‘ or
Dim hero As New SuperHero

With hero

  .Name = “SpamMan”

  .PowerLevel = 3

End With

hero.Defend(“Laura Jones”)

hero.Rest()     ‘ Calling Shared method
‘ or

Dim hero2 As SuperHero = hero  ‘ Both reference the same

hero2.Name = “WormWoman”

Console.WriteLine(hero.Name)   ‘ Prints WormWoman

hero = Nothing    ‘ Free the object

If hero Is Nothing Then _

  hero = New SuperHero

Dim obj As Object = New SuperHero

If TypeOf obj Is SuperHero Then _
  Console.WriteLine(“Is a SuperHero object.”)

‘ Mark object for quick disposal
Using reader As StreamReader = File.OpenText(“test.txt”)
  Dim line As String = reader.ReadLine()
  While Not line Is Nothing
    line = reader.ReadLine()
  End While
End Using

SuperHero hero = new SuperHero();

// No “With” construct
hero.Name = “SpamMan”;

hero.PowerLevel = 3;

hero.Defend(“Laura Jones”);
SuperHero.Rest();   // Calling static method

SuperHero hero2 = hero;   // Both reference the same

hero2.Name = “WormWoman”;

Console.WriteLine(hero.Name);   // Prints WormWoman

hero = null ;   // Free the object

if (hero == null)
  hero = new SuperHero();

Object obj = new SuperHero(); 
if (obj is SuperHero)

  Console.WriteLine(“Is a SuperHero object.”);

// Mark object for quick disposal
using (StreamReader reader = File.OpenText(“test.txt”)) {
  string line;
  while ((line = reader.ReadLine()) != null)

VB.NET Structs C#

Structure StudentRecord

  Public name As String

  Public gpa As Single

  Public Sub New(ByVal name As String, ByVal gpa As Single) = name

    Me.gpa = gpa

  End Sub

End Structure

Dim stu As StudentRecord = New StudentRecord(“Bob”, 3.5)

Dim stu2 As StudentRecord = stu = “Sue”

Console.WriteLine(    ‘ Prints Bob

Console.WriteLine(  ‘ Prints Sue

struct StudentRecord {
  public string name;
  public float gpa;

  public StudentRecord(string name, float gpa) { = name;
    this.gpa = gpa;

StudentRecord stu = new StudentRecord(“Bob”, 3.5f);
StudentRecord stu2 = stu; = “Sue”;
Console.WriteLine(;    // Prints Bob
Console.WriteLine(;   // Prints Sue

VB.NET Properties C#

‘ Auto-implemented properties are new to VB10
Public Property Name As String
Public Property Size As Integer = -1     ‘ Default
value, Get and Set both Public

‘ Traditional property implementation
Private mName As String
Public Property Name() As String
        Return mName
    End Get
    Set(ByVal value As String)
        mName = value
    End Set
End Property

‘ Read-only property
Private mPowerLevel As Integer
Public ReadOnly Property PowerLevel() As Integer
        Return mPowerLevel
    End Get
End Property

‘ Write-only property
Private mHeight As Double
Public WriteOnly Property Height() As Double
    Set(ByVal value As Double)
        mHeight = If(value < 0, mHeight = 0, mHeight = value)
    End Set
End Property

// Auto-implemented properties
public string Name { get; set; }
public int Size { get; protected set; }    
// Set default value in constructor

// Traditional property implementation
private string name;
public string Name {
  get {
    return name;
  set {
    name = value;

// Read-only property
private int powerLevel;
public int PowerLevel {
  get {
    return powerLevel;

// Write-only property
private double height;
public double Height {
  set {
    height = value < 0 ? 0 : value;

VB.NET Delegates / Events C#

Delegate Sub MsgArrivedEventHandler(ByVal message As String)

Event MsgArrivedEvent As MsgArrivedEventHandler

‘ or to define an event which declares a delegate implicitly
Event MsgArrivedEvent(ByVal message As String)

AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback

‘ Won’t throw an exception if obj is Nothing
RaiseEvent MsgArrivedEvent(“Test message”)

RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback

Imports System.Windows.Forms

Dim WithEvents MyButton As Button   ‘ WithEvents
can’t be used on local variable

MyButton = New Button

Private Sub MyButton_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles MyButton.Click

  MessageBox.Show(Me, “Button was clicked”, “Info”, _
    MessageBoxButtons.OK, MessageBoxIcon.Information)

End Sub

delegate void MsgArrivedEventHandler(string message);

event MsgArrivedEventHandler MsgArrivedEvent;

// Delegates must be used with events in C#

MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);
MsgArrivedEvent(“Test message”);    // Throws exception
if obj is null

MsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEventCallback);

using System.Windows.Forms;

Button MyButton = new Button(); 
MyButton.Click += new System.EventHandler(MyButton_Click);

private void MyButton_Click(object sender, System.EventArgs e) {

  MessageBox.Show(this, “Button was clicked”, “Info”,

    MessageBoxButtons.OK, MessageBoxIcon.Information);


VB.NET Generics C#

‘ Enforce accepted data type at compile-time

Dim numbers As New List(Of Integer)
DisplayList(Of Integer)(numbers)

‘ Subroutine can display any type of List

Sub DisplayList(Of T)(ByVal list As List(Of T))
    For Each item As T In list
End Sub

‘ Class works on any data type

Class SillyList(Of T)
    Private list(10) As T
    Private rand As New Random

    Public Sub Add(ByVal item As T)
        list(rand.Next(10)) = item
    End Sub

    Public Function GetItem() As T
        Return list(rand.Next(10))
    End Function
End Class

‘ Limit T to only types that implement IComparable
Function Maximum(Of T As IComparable)(ByVal ParamArray items As T())
As T
    Dim max As T = items(0)
    For Each item As T In items
        If item.CompareTo(max) > 0 Then max = item
    Return max
End Function

// Enforce accepted data type at compile-time

List<int> numbers = new List<int>();

// Function can display any type of List

void DisplayList<T>(List<T> list) {
    foreach (T item in list)

// Class works on any data type

class SillyList<T> {
    private T[] list = new T[10];
    private Random rand = new Random();

    public void Add(T item) {
        list[rand.Next(10)] = item;

    public T GetItem() {
        return list[rand.Next(10)];

// Limit T to only types that implement IComparable
T Maximum<T>(params T[] items) where T : IComparable<T>
    T max = items[0];
    foreach (T item in items)
        if (item.CompareTo(max) > 0)
            max = item;
    return max;


Dim nums() As Integer = {5, 8, 2, 1, 6}

‘ Get all numbers in the array above 4
Dim results = From value In nums
                  Where value
> 4
                  Select value

Console.WriteLine(results.Count())     ‘ 3

Console.WriteLine(results.First())     ‘ 5

Console.WriteLine(results.Last())     ‘ 6

Console.WriteLine(results.Average())     ‘ 6.33333

‘ Displays 5 8 6

For Each n As Integer In results
    Console.Write(n & ” “)

results = results.Intersect({5, 6, 7})    
5 6

results = results.Concat({5, 1, 5})     ‘ 5 6
5 1 5

results = results.Distinct()     ‘ 5 6 1

Dim Students() As Student = {
    New Student With {.Name = “Bob”, .GPA = 3.5},
    New Student With {.Name = “Sue”, .GPA = 4.0},
    New Student With {.Name = “Joe”, .GPA = 1.9}

‘ Get an ordered list of all students by GPA with GPA >= 3.0
Dim goodStudents = From s In Students
            Where s.GPA >= 3.0
            Order By s.GPA Descending
            Select s

‘ Sue

int[] nums = { 5, 8, 2, 1, 6 };

// Get all numbers in the array above 4
var results = from value in nums
                where value > 4
                select value;

Console.WriteLine(results.Count());     // 3

Console.WriteLine(results.First());     // 5

Console.WriteLine(results.Last());     // 6

Console.WriteLine(results.Average());     //

// Displays 5 8 6

foreach (int n in results)
    Console.Write(n + ” “);

results = results.Intersect(new[] {5, 6, 7});    
// 5 6

results = results.Concat(new[] {5, 1, 5});    
// 5 6 5 1 5

results = results.Distinct();     // 5 6 1

Student[] Students = {
    new Student{ Name = “Bob”, GPA = 3.5 },
    new Student{ Name = “Sue”, GPA = 4.0 },
    new Student{ Name = “Joe”, GPA = 1.9 }

// Get an ordered list of all students by GPA with GPA >= 3.0
var goodStudents = from s in Students
            where s.GPA >= 3.0
            orderby s.GPA descending
            select s;

// Sue

VB.NET Console I/O C#

Console.Write(“What’s your name? “)

Dim name As String = Console.ReadLine()

Console.Write(“How old are you? “)

Dim age As Integer = Val(Console.ReadLine())

Console.WriteLine(“{0} is {1} years old.”, name, age) 

‘ or

Console.WriteLine(name & ” is ” & age & ” years old.”)

Dim c As Integer

c = Console.Read()    ‘ Read single char

Console.WriteLine(c)   ‘ Prints 65 if user enters “A”

Console.Write(“What’s your name? “);
string name = Console.ReadLine();
Console.Write(“How old are you? “);
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(“{0} is {1} years old.”, name, age);
// or
Console.WriteLine(name + ” is ” + age + ” years old.”);

int c = Console.Read();  // Read single char
Console.WriteLine(c);    // Prints 65 if user enters

VB.NET File I/O C#

Imports System.IO

‘ Write out to text file
Dim writer As StreamWriter = File.CreateText(“c:\myfile.txt”)

writer.WriteLine(“Out to file.”)


‘ Read all lines from text file
Dim reader As StreamReader = File.OpenText(“c:\myfile.txt”)

Dim line As String = reader.ReadLine()

While Not line Is Nothing


  line = reader.ReadLine()

End While


‘ Write out to binary file
Dim str As String = “Text data”

Dim num As Integer = 123

Dim binWriter As New BinaryWriter(File.OpenWrite(“c:\myfile.dat”)) 



‘ Read from binary file
Dim binReader As New BinaryReader(File.OpenRead(“c:\myfile.dat”))

str = binReader.ReadString()

num = binReader.ReadInt32()


using System.IO;

// Write out to text file
StreamWriter writer = File.CreateText(“c:\\myfile.txt”);

writer.WriteLine(“Out to file.”);


// Read all lines from text file
StreamReader reader = File.OpenText(“c:\\myfile.txt”);

string line = reader.ReadLine();

while (line != null) {

  line = reader.ReadLine();



// Write out to binary file
string str = “Text data”;

int num = 123;

BinaryWriter binWriter = new BinaryWriter(File.OpenWrite(“c:\\myfile.dat”));




// Read from binary file
BinaryReader binReader = new BinaryReader(File.OpenRead(“c:\\myfile.dat”));

str = binReader.ReadString();

num = binReader.ReadInt32();


Looping through GridView with Javascript on the client side

Posted: March 1, 2011 in Uncategorized

Every had to find a specific control inside of a gridview on the client side or grab a group of controls to manipulate them. Here is how to grab controls in the gridview with javascript:

function GetTotal() {
totalDTH = 0;
totalMCF = 0;

// Get the gridview
var grid = document.getElementById(“<%= grdVolumes.ClientID%>”);

// Get all the input controls (can be any DOM element you would like)
var inputs = grid.getElementsByTagName(“input”);

// Loop through all the DOM elements we grabbed
for (var i = 0; i < inputs.length; i++) {

// In this case we are looping through all the Dek Volume and then the Mcf volume boxes in the grid and not an individual one and totalling them
if (inputs[i].name.indexOf(“txtDekVolume”) > 1) {
if (inputs[i].value != “”) {
totalDTH = totalDTH + parseInt(inputs[i].value);

if (inputs[i].name.indexOf(“txtMcfVolume”) > 1) {
if (inputs[i].value != “”) {
totalMCF = totalMCF +  parseInt(inputs[i].value);



Installing a SSL Certificate in Plesk 9

Posted: March 1, 2011 in Uncategorized

1) We first login to Plesk and navigate to the domain you wish to install the Certificate on to.

2) Enter into the configuration of the target domain.

3) Click on SSL Certificates

4) Click on Add SSL Certificate

5) If you already have a SSL Certificate then you can skip this step and go to step 8.
Name the certificate. This can be named anything that you choose, but we will attempt to use a descriptive name including a timestamp.
In this case we are using YYYYMMDDRR format where RR is the revision number (00 in this case as there are no revisions for the same day)
Make any needed adjustments to the SSL Request. This information will be embedded in the SSL Certificate and should be similar to the domain registration information.
The email address should match one of the email addresses in the domain whois information provided by your domain registrar.
Falsified information may be rejected by your SSL Certificate Authority.

6) Now enter back into the Certificate configuration

7) You can now review the CSR and Private Key.
Save the Private Key in a safe location. Should anything occur with your server that the certificate must be re-entered you MUST have at least the Certificate and Private Key.
Take the CSR and submit it to the Certificate Authority of your choice. We, SoftLayer, do not provide SSL Certificates.

8) Once you have received the Certificate from your Certificate Authority you can paste it into the Certificate text area.
If your Certificate Authority requires, you may need to paste their own Certificate into the CA certificate text area (often called a CA Bundle)

9) If the Private Key does not match the Certificate then you will see a page similar to this. You MUST have a matching Private Key and Certificate in order to use a Certificate.

10) Once installed you will see a page similar to this. These three all match up and are ready to be used.

11) Now you will navigate back in to the Web Hosting Settings from the Domains configuration.

12) Select the corresponding Certificate and click OK at the bottom.

The new certificate is now being used for the domain. If you have updated the certificate then you may need to completely close out of your browser before the new certificate is used.