I came across a pretty interesting series of articles when I was reading through Eric Lippert's MSDN blog today. Here are some of the things i grasped from him.

What is the first thing that comes to your mind when someone asks from you "What is the difference between value types and reference types?" Well I bet you will reply saying that value types are allocated in the stack and reference types are allocated in heap, right! Well you are correct that's what the C# documentation tells us. Then why don't we just call them stack types and heap types instead of value and reference. Well that's because that is not true most of the time.

Let's take the following class as an example.

public class Demo
{
   private int ValueOne = 10;

   public int GetValue()

   {
    return ValueOne;

   }
}


Here the variable "ValueOne" is defined inside the "Demo" class. Here although "ValueOne" is a value type integer variable it is an integral part of the "Demo" s instance memory. So it is allocated inside the heap.

Let's have a look at how this happens.

Before we dwell in to it, let's see what does the terms "short lived" and "long lived" stands for in context of variables

When a method is called an activation period is defined for that method, which can be defined as the time between the start of the method execution and its successful return or a throwing of an exception. Code in the method may require allocation of storage in memory for its variables. Let's look at a simple example

public int GetSum()
{
   int x = 10;
   int y = 20;


   int sum = Add(x, y);


   return sum;

}

public int Add(int i, int j)

{
   return i + j;

}



Here when the method GetSum calls method Add, the use of the storage locations for the parameters passed to Add and the value returned by Add is required by GetSum. This means that the required life time of the storage location is actually longer than the activation period of the method, thus making it a long lived variable or storage.

So what does long/short lived stands for "If the required life time of a variable/storage is longer than its current method execution's activation period that variable is classified as a long lived variable otherwise a short lived one"

So how can value type variables get allocated inside the heap? Let's get to it one step at a time

  • There are three types of values in C#. Instances of value types, Instances of reference types and References.
  • There are storage locations in memory that can store values they are stack, heap and registers.
  • Every value that is managed by some kind of a program stores their values in these storage locations, as well as every reference other than a null reference.
  • Every storage location in memory which has some content in them has a life time.(short/long lived)
  • Long lived storage locations are always heap locations and short lived storage locations are always in stack or registers.
  • If the compiler cannot come to a clear decision if the variable is short lived or long lived that variable is considered as a long lived variable and is always stored in heap.
What happens is that during the compile time analysis if a local or a temporary variable is found to be un-used after the methods activation time it is stored on stack or register otherwise on heap. Depending on this model we can see that references and instances of value types are the same as far as their storage is concerned, but they can go on to either of those above mentioned storage locations depending on their life time.

So that leaves us with an explanation that actually does not explain any concrete thing.

Then what is the main, clearly distinctive difference between them. The best explanation is that "Value types are always copied by value and Reference types are always copied by reference" and we can also go on to say that "Value types semantically represents a value and Reference types are a semantic reference to something".

Yesterday I came across an interesting situation. There are some times when you need to break a string in to two parts depending on their character type.
Lets say you have a string like "Welfare Fund - 1000.00" and you need to break the string part and the number part in to two different strings. Well the first thing that comes to mind is iterate the string till you get a number and break it to apart upon hitting on a number type character, right!!
Well then what about a string like "Welfare Fund : 2009 - 3000.00"
Here as you can see, there are numbers in the string part as well.

The solution is simple, all you have to do is iterate through the string by starting from its end, till you reach a blank space. Here is the a method to accomplish that task

public static List<string> BreakString(string stringToBreak)
        {
            var charArr = stringToBreak.ToCharArray();
            var stringAppender = new StringBuilder();
            var intAppender = new StringBuilder();
            var isSeparated = false;
            for (int i = charArr.Length - 1; i > -1; i--)
            {
                if (isSeparated)
                    stringAppender.Append(charArr[i]);
                else
                {
                    isSeparated = charArr[i] == ' ';
                    if (!isSeparated)
                        intAppender.Append(charArr[i]);
                }
            }
            var returnValues = new List<string> { ReverseString(stringAppender.ToString()), ReverseString(intAppender.ToString()) };
            return returnValues;
        }

public static string ReverseString(string s)
        {
            var arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }

You can call it as follows

var input = "Welfare Fund - 1000.00";
var result = BreakString(input);

There are some pretty good Mock object frameworks available out there for .net like NMock, EasyMock, TypeMock, etc... But I think every one will ultimately wind up using Rhino Mock at the end because of its easy to grasp rich feature set. So lets see how we can use Rhino to to mock a layered architecture for unit testing purposes.

I will try to mock the repository and the service layer in the following code in an easy to understand manner

Here are my sample repository and service interfaces (I have used NHibernate and Windsor Castle in this project as the ORM solutionl)

Repository Interface

 public interface IInventoryRepository : IRepository
    {
        List<RecordItem> Get(List<int> ids);
        List<RecordItem> Get(List<int> ids, string orderByColumn, string orderType);
    }


Service Interface

public interface IInventoryService  
    {
        List<ServiceItem> Get(List<int> ids, int truncLength);
        List<ServiceItem> Get(List<int> ids, string orderByColumn, string orderType, int truncLength);
    }

As I have described in my previous post lest use Nbuilder to mock the test objects that needs to be returned when the methods in the repository are called

Mock return for List<RecordItem> Get(List<int> ids)
private static List<RecordItem> CreateRecordItems()
        {
            var items = Builder<RecordItem>.CreateListOfSize(10).WhereAll().Have(x => x.Title = "sample title").WhereAll().Have(x => x.AuthorName = "Dhanushka").Build().ToList();
            for (int i = 1; i < items.Count + 1; i++)
            {
                EntityIdSetter.SetIdOf(items[i - 1], i);
            }
            return items;
        }

Mock return for List<RecordItem> Get(List<int> ids, string orderByColumn, string orderType)
 private static List<RecordItem> CreateRecordItemsDesc()
        {
            var items = Builder<RecordItem>.CreateListOfSize(10).WhereAll().Have(x => x.Title = "sample title").WhereAll().Have(x => x.AuthorName = "Dhanushka").Build().ToList();
            var j = items.Count;
            for (int i = 1; i < items.Count + 1; i++)
            {
                EntityIdSetter.SetIdOf(items[i - 1], j);
                j--;
            }
            return items;
        }

Now lets use Rhino Mock to mock the Method Calls to the repository

public static IInventoryRepository CreateMockInventoryRepository()
        {
            var mocks = new MockRepository();
//specify the repository to mock
            var mockedRepository = mocks.StrictMock<IInventoryRepository>();


//specify what to return when a specific method is called in the mocked repository
            Expect.Call(mockedRepository.Stub(x => x.Get(Arg<List<int>>.Is.Anything)).Return(CreateRecordItems()));
            Expect.Call(mockedRepository.Stub(x => x.Get(Arg<List<int>>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Equal("asc"))).Return(CreateRecordItems()));
            Expect.Call(mockedRepository.Stub(x =>x.Get(Arg<List<int>>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Equal("desc"))).Return(CreateRecordItemsDesc()));

//mock the current data base context
            var mockedDbContext = mocks.StrictMock<IDbContext>();
            Expect.Call(mockedDbContext.CommitChanges);
            SetupResult.For(mockedRepository.DbContext).Return(mockedDbContext);

            mocks.Replay(mockedRepository);

            return mockedRepository;
        }

As you can see this method mocks the repository with specification for method calls return values and reveal the mocked repository to the outer world.

Now lets used this mocked repository to mock the service layer


public static IInventoryService   CreateMockClipboardService()
        {
            var serviceMock =new InventoryService(InventoryRepositoryMock.CreateMockInventoryRepository());
            return serviceMock;
        }

Here the dependency injection is used with Windsor Castle to inject the service with the mocked repository layer.

Now to write a sample test using NUnit all you have to do is
[TestFixture]
    public class ServiceTest
    {
        private IInventoryService  _service;

        [SetUp]
        public void SetUp()
        {
            _service = new InventoryService(InventoryRepositoryMock.CreateMockInventoryRepository());
        }

        [Test]
        public void GetWithoutSortTest()
        {
            var idList = new List<int> {1, 2, 3, 4};
            const int truncLength = 100;
            var itemsReturned = _service.Get(idList, truncLength);

            var expectedItemType = typeof (ServiceItem);
            const string expectedAuthor = "Dhanushka";
            const string expectedTitle = "sample title";

            Assert.That(itemsReturned.Count, Is.GreaterThan(0),"no items returned");
            Assert.That(itemsReturned[0], Is.TypeOf(expectedItemType),"incorrect return type");
            Assert.That(itemsReturned[0].Author,Is.EqualTo(expectedAuthor),"unexpected author returned");
            Assert.That(itemsReturned[0].Title,Is.EqualTo(expectedTitle),"unexpected title returned");

        }
   }

Now we have a simple unit test in our hand that uses a mocked service and repository layer

Most of us use some sort of a mocking library when doing unit tests in order to mock our service and repository layers right!
Well I am a big fan of Rhino Mock and I have used it in almost all of my testing projects.
But one thing that remains to be a pain in the ass is creating test objects to be returned when the mocked repository is called. Well not any more!!!

Using NBulder we can avoid hard coding test objects for mocking purposes.

Here are some sample codes to get you started with

Let's say you want to mock a a repository call that returns an item, just write
var item = Builder<RepositoyType>.CreateNew().Build();
//set the id property of each items (Nhibernate is used with Windsor Castle in this occasion)
EntityIdSetter.SetIdOf(item, 1);

To mock a method call that returns a list of record objects.
var items = Builder<RepositoyType>.CreateListOfSize(10).WhereAll().Have(x => x.Title = "sample title").WhereAll().Have(x => x.AuthorName = "Dhanushka").Build().ToList();
 for (int i = 1; i < items.Count + 1; i++)
{
    EntityIdSetter.SetIdOf(items[i - 1], i);
}

As you can see from the above example we can even set specific values for the attributes for returned objects as well.

And there are many more helper functions you can use to accomplish almost all the test object creation needs you hope for.

Happy Coding!!

I came across an interesting issue today. I used the ResetPassword method provided by C# membership class to reset the password of a user and found out that although it allows us to define the password strength using a regular expression in the web.config file, it does not guarantee that the generated password adheres to the rules defined by the expression. Microsoft says and I quote
"The random password created by the ResetPassword method is not guaranteed to pass the regular expression in the PasswordStrengthRegularExpression property. However, the random password will meet the criteria established by the MinRequiredPasswordLength and MinRequiredNonAlphanumericCharacters properties."

So to tackle the issue, I used the Regex class. The revised code is shown below

var isNotMatch = true;
                    while(isNotMatch)
                    {
                        resetpwd = manager.ResetPassword();
                        var matcher=new Regex(Membership.PasswordStrengthRegularExpression);
                        isNotMatch = !(matcher.IsMatch(resetpwd));
                    }
This code snippet will force the ResetPassword to fire until a password adhering to the rules defined by the regular expression is generated.

I came across an interesting problem when using java script "setSttribute" method with IE. Apparently it does not work with IE versions 5.5 to 7 when we try to use it to set a style to an element.

For all the browsers including IE8 and above this code will work fine when we a want to set a a style attribute to an element using java script.

var elemntToTest=document.createElement('a');
elemntToTest.setAttribute('href', '#');
elemntToTest.setAttribute('style', 'padding:3px');

but in IE 5.5-7 you will need to set the style like this.

elemntToTest.style.cssText = "padding:3px;";

Now it will work fine in all the browsers.

Hope this work around helps!!!

As we all know there are some pretty amazing and powerful charting tools available for web developers to use, some are commercial and some are free. But a main disadvantage i saw in many of them is that, almost all of them use flash to draw graphics and manipulate settings.

But there is some pretty sleek free JQuery chart plug-ins available out there. To name a few Flot, Google Charts, jQuery Chart, jQchart, TufteGraph etc...

After a brief R&D Flot attracted me most because of its rich options set and clean, easy to use and maintainable code.

Now I will explain how to draw a simple line chart using Flot in an ASP.net web site.

I will use AJAX calls to fetch data from the server to populate chart data sets in the following example. But rather than using page methods or update panels, I will use simple JQuery AJAX post backs ($.ajax) to accomplish data retrieving tasks.

So here we go...

Let’s take a look at how Flot accepts data to draw its chart. Here is a simple JSON object which will be used to draw the chart line.

{

label: 'Europe (EU27)',

data: [[1999, 3.0], [2000, 3.9]]

}

So let’s create a class similar to this JSON object so we can serialize an object of that class to something similar.

public class Model

{

public string label;

public List<List<int>> data;

}

And let’s write a Helper class containing simple methods that can be used to serialize the Model object to a JSON object.

public static class Helper

{

private static string ToJson(this object obj)

{

var serializer = new DataContractJsonSerializer(obj.GetType());

var ms = new MemoryStream();

serializer.WriteObject(ms, obj);

var json = Encoding.Default.GetString(ms.ToArray());

return json;

}

public static string GetJason(Model dataModel)

{

return dataModel.ToJson();

}

}

* DataContractJsonSerializer is inside the System.Runtime.Serialization.Json namespace

Now we will write a simple web method (web service method) that can be called from the client side JavaScript.

[WebMethod]

public static string GetData()

{

var dataModel = new Model {label = "Sample Chart"};

var dataList = new List<List<int>>();

for (int i = 1; i <>

{

var data = new List {i, (i*i) + 8};

dataList.Add(data);

}

dataModel.data = dataList;

return Helper.GetJason(dataModel);

}

This function will return a serialized data object like this.

{

"data":[[1,9],[2,12],[3,17],[4,24],[5,33],[6,44],[7,57],[8,72],[9,89]],

"label":"Sample Chart"

}

Now that's all from the server side. Let’s look at the client side javascript functions

In the aspx page add references to jquery.js and jquery.flot.js (download them from http://code.google.com/p/flot/downloads/list)

And inside the body add a div with the id "placeholder" to hold the chart.

add a button with the id “btnGetData” so we can fetch data upon user request

Here is the sample code to draw the chart using our predefined methods in the server side.

$(document).ready(function() {

//options that can be enabled in the chart, more options are available

var options = {

lines: { show: true },

points: { show: true },

xaxis: { tickDecimals: 0, tickSize: 1 }

};

var data = []; //data used to draw the chart

var placeholder = $("#placeholder"); //chart wrapper

$.plot(placeholder, data, options); //draw the chart

var alreadyFetched = {};

$("#btnGetData").live("click", function(e) {

var button = $(this); //get the clicked button

//execute this function after data is successfully retrieved from the ajax call

function onDataReceived(series) {

series = $.parseJSON(series.d); //get the json object (use the latest jquery script)

var firstcoordinate = '(' + series.data[0][0] + ', ' + series.data[0][1] + ')';

button.siblings('span').text('Fetched ' + series.dabel + ', first point: ' + firstcoordinate);

if (!alreadyFetched[series.label]) {

alreadyFetched[series.label] = true;

data.push(series); //populate data

}

$.plot(placeholder, data, options); //draw the chart

}

var dataUrl = "Default.aspx/GetData"; //server method to get data

$.ajax({

type: "POST",

url: dataUrl,

data: "{}",

contentType: "application/json; charset=utf-8",

dataType: "json",

success: onDataReceived

});

});

});

This will draw a simple line chart on your screen.

Happy charting!!!

All of us are familiar with OOP concepts, right!!
But how many of you have tried to use them in JavaScript.
Here is a simple code example to get you up and running.

First I will create a simple JavaScript class. When uing C# or Java etc... , We use the keyword "class".
To denote a class in JavaScript we use "function".

Here we go...

function Helper() {

$.fn.getCurrentIds = function (name) {
var selectedIds = new Array();
$('input:checkbox[name=' + name + ']:checked').each(function () {
selectedIds.push($(this).val());
});
var idString = "";
for (var i = 0; i < selectedIds.length; i++) {
if (i == selectedIds.length - 1)
idString += selectedIds[i];
else
idString += selectedIds[i] + ',';
}
return idString;
};

this.setAllSelectedIds = function (checkBoxName, hdnId) {
var hdnControlString = '#' + hdnId + '';
if ($(hdnControlString)) {
if ((!($(hdnControlString).val())) || $(hdnControlString).val() == "")
$(hdnControlString).val($.fn.getCurrentIds(checkBoxName));
else
if ($.fn.getCurrentIds(checkBoxName) != "")
$(hdnControlString).val($(hdnControlString).val() + ',' + $.fn.getCurrentIds(checkBoxName));
}
};

this.setCheckboxStatus = function (hdnId) {
var hdnControlString = '#' + hdnId + '';
if ($(hdnControlString) && $(hdnControlString).val()) {
if ($(hdnControlString).val() != "") {
var idArray = $(hdnControlString).val().split(',');
$.each(idArray, function (index, value) {
if ("input:checkbox[value=" + value + "]")
$("input:checkbox[value=" + value + "]").attr("checked", true);
});
}
}
};

this.getAllSelectedIds = function (hdnId) {
var hdnControlString = '#' + hdnId + '';
var idString = "";
if ($(hdnControlString))
idString = $(hdnControlString).val();
if (!idString)
idString = "";
return idString;
};

}

Here I have defined some useful common utility functions which will be used in and out side of the class.
if you look closely, you will see that the function "getCurrentIds" is called from another method or a function within the class that is "setAllSelectedIds" we have used JQuery pointers to do so - "$.fn.getCurrentIds(checkBoxName)"

what about out side of the class.

Its the same as any OOP based language.
-Create an object of the class
-Call object methods

here is an example

var helperObj = new Helper();
helperObj.setAllSelectedIds(itemCheckBoxName, hdnAllChkIds);//returns void
var allItemsSelected = helperObj.getAllSelectedIds(hdnAllChkIds);//returns a string containing all the selected check box ids.

you can elaborate further on this concept and can use it to write more complex but clean and maintainable code

Hope it helped!!!

You can use the following method to store a string value in cookie using C#.net 4.0

public static void StoreCookie(string name, string valueToStore)
{
var cookie = new HttpCookie(name) {Value = valueToStore, Expires = DateTime.Now.AddYears(1)};
HttpContext.Current.Response.Cookies.Add(cookie);
}

Here classes like "HttpCookie" and "HttpContext" needs to be used in order to access cookies from a class library.

This kind of truncation is always needed if you are displaying a truncated version of a meaningful string in the UI. Rather than simply truncating the list to a specific maximum length it is always handy to chop it to the last meaningful word.
The following lines of code accomplish that task

public static string TruncateToLastWord(string value, int maxLength)
{
string stringToTruncate = value.Substring(0, maxLength);
int indexOfLastSpace = stringToTruncate.LastIndexOf(' ');
string truncatedString = stringToTruncate.Substring(0, indexOfLastSpace);
return string.Format("{0}...", truncatedString);
}

Lets say you have two lists that contains a set of Ids, and some ids are repeated in both the lists.
Here is a simple piece of code to get a concatenated list without the duplicate ids

public static List RemoveExistingValues(List oldSet, List newSet)
{
foreach (var item in newSet)
oldSet.RemoveAll(x=>x==item);
return oldSet;
}

The requirement I am gonna illustrate now comes up in almost all development efforts where a grid or a tabular view is displayed. there is a single check box in the table header where upon click you need to change the checked status of all the check boxes in the grid
Here is a simple bit of code you can use to achieve that task

function(){
$('#' + allCheckBoxName + '').live("change", function (e) {
$("INPUT[type='checkbox']").attr('checked', $('#' + allCheckBoxName + '').is(':checked'));
});
}

Here "allCheckBoxName" is the master check box which is at the top of the grid.

But an issue arise when using this script with a drop down in the same page in IE browsers. that is in IE you need to bind check boxes events first before any other event bindings in order to work them properly. and strangely this is true with drop downs as well. so you face a strange dillema. "How can I bind events for two different kinds of controls at once?"

To overcome this just add the following code segment to the code

if ($.browser.msie) {
$('#' + allCheckBoxName + '').unbind("click");
$('#' + allCheckBoxName + '').live("click", function (e) {
$(this).trigger("change");
});

what it does is it rebinds the check box events after the drop down bind and trigger the change event.
so the completed function will look some thing like this

function () {
if ($.browser.msie) {
$('#' + allCheckBoxName + '').unbind("click");
$('#' + allCheckBoxName + '').live("click", function (e) {
$(this).trigger("change");
});
if (allCheckBoxVisibility) {
$('#' + allCheckBoxName + '').live("change", function (e) {
$("INPUT[type='checkbox']").attr('checked', $('#' + allCheckBoxName + '').is(':checked'));
});
}
}
$('#' + allCheckBoxName + '').live("click", function (e) {
$("INPUT[type='checkbox']").attr('checked', $('#' + allCheckBoxName + '').is(':checked'));
});
}

Hope it helps!!!

lots of guys have asked from me how to do this using java script. here is a small code snippet to help them out

function (name) {
var selectedIds = new Array();
$('input:checkbox[name=' + name + ']:checked').each(function () {
selectedIds.push($(this).val());
});
var idString = "";
for (var i = 0; i < selectedIds.length; i++) {
if (i == selectedIds.length - 1)
idString += selectedIds[i];
else {
idString += selectedIds[i] + ',';
}
}
return idString;
}

Cheers!!!

With C# 4.0 you can assign a default value to a parameter when you are declaring a method

e.g.
public static void updateMyCV(string name=”Dhanushka”){ do some task }

you can call the method in following ways
updateMyCV(); //this will assign the default value to the parameter name
updateMyCV(“Athukorala”); //passed in value is assigned to the parameter

As you can see when you are calling these method, parameters in the method becomes optional. We can use this feature coupled with named parameters to define methods with an optional set of parameters.

e.g.
public static void
updateMyCV
(int employeeID, string firstName=”Dhanushka”, string lastName=”Athukorala”)
{ do some task }

When you are declaring a method with optional parameters, required parameters need to come first before any optional parameter declaration, here parameters with default values are considered as optional parameters while others are considered as required. There are several ways to call this method legally.

e.g.


updateMyCV(155,”Tekla”,”Dilrukshi”);
updateMyCV(155,”Tekla”);
updateMyCV(155,lastName: “Dilrukshi”);
updateMyCV(155);


But you cannot call the method in following ways although it makes sense to do so

updateMyCV(); //required parameters need to be passed
updateMyCV(155, ,”Dilrukshi”); //cannot leave gaps between arguments
updateMyCV(“Dilrukshi”,155);
//order has to be maintained if you are not using named arguments in the method call

Let’s say that you wrote a method like this

public static int getVolumeOfCylinder(int radius, int height)
{
return 22/7*radius*radius*height;
}

Now we all know until now we have to know the order of the parameters to call this method correctly, right!
Well not any more with C# 4.0 you can consider the parameter names as labels and call them without considering their declaration order in the following way

getVolumeOfCylinder(height: 10, radius: 5);
getVolumeOfCylinder(radius: 5, height: 10);

And as you have imagined already, named arguments can follow a positional argument but a named argument can never be followed by a positional argument

e.g
getVolumeOfCylinder(5, height: 10); //this will compile
getVolumeOfCylinder(height:10, 5); // this wont

In programming languages such as c# and java we use data structures like arrays and lists to store a set of data in the memory so we can iterate through them and do some processing.
when it comes to sql the alternative solution is the T-SQL CURSOR

The basic steps of using a cursor are as follows
1)Declare a cursor and associate it with a SELECT statement, the basic characteristics of the cursor needs to be defined here as well
2)Open and populate the cursor
3)Fetch a row from the cursor
4)Process the fetched row inside the loop after checking the fetch status
5)close and de-allocate the cursor

lets write a simple cursor and demonstrate the above mentioned steps

--Declare the variables needed, to do the necessary processing
DECLARE @NAME VARCHAR(MAX)

---(1)---
DECLARE myCursor CURSOR FOR
SELECT employee_name FROM EMPLOYEES

* alternatively you can declare a local variable of type CURSOR and set its structure as well
DECLARE @myCursor CURSOR
SET @myCursor= CURSOR FOR SELECT employee_name FROM EMPLOYEES
* you can also set the cursor for read only mode to gain more performance or to update mode to update the rows as you iterate through them
DECLARE myCursor CURSOR READ_ONLY
FOR SELECT employee_name FROM EMPLOYEES
OR
DECLARE myCursor CURSOR
FOR SELECT employee_name FROM EMPLOYEES
FOR UPDATE OF designation

---(2)---
OPEN myCursor
--(3)---
FETCH NEXT FROM myCursor INTO @NAME
---(4)---
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @NAME
FETCH NEXT FROM myCursor INTO @NAME
END
* here FETCH_STATUS is used to determine the boundary status of the iterator, following are values it returns depending on the situation
0 - fetch statement was executed successfully
-1 - row that needs to be fetched is beyond the result set
-2 - row that needs to be fetched is missing
* FETCH_STATUS is defined globally for all the cursors on a connection, so when we are using it we need to be careful to check the status immediately after the fetch before another fetch occur.
* you can get the number of rows in the cursors result set using the @@CURSOR_ROWS variable

---(5)---
CLOSE myCursor
DEALLOCATE myCursor
* after using the cursor we must close and de-allocate it so there wont be any references for the cursor in the memory