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

following code demonstrates how we can write a collection to an XML file using C#

we can do it in two ways first lets do it without using serilization.



public static void writetoXML(string fileName)
{
DataSet ds = new DataSet("ds01"); //root node
DataTable t = new DataTable("table01"); //
DataColumn qNo = new DataColumn("questionNo"); //
DataColumn ans = new DataColumn("answer"); //

t.Columns.Add(qNo); //add columns to the table
t.Columns.Add(ans);
ds.Tables.Add(t); //add table to the dataset

DataRow r;
int qLimit = 10;
for (int i = 0; i <>
{
r = t.NewRow(); //create a new row of type table
r["questionNo"] = i;
r["answer"] = "answer for question" + i;
t.Rows.Add(r); //add the newly populated row to the table
}

//write the added data to the console
Console.WriteLine("Data added to the table\n");
Console.WriteLine("QuestionNo\t\tAnswer");
Console.WriteLine("--------------------------------------------");
for (int i = 0; i <>
{
Console.WriteLine(t.Rows[i][0].ToString()+"\t\t|\t"+t.Rows[i][1].ToString());
}
ds.WriteXml(fileName);
}

lets rewrite it again using serilization there is a big advantage in this i'll show it right away
when using serialization we write the data using a XMLSerializer object which will be created using the method typeof(). this allows us to write any type of collection to a XML file with little altering of code as possible
lets see how the above method will look like when written using serilization

public static void serializeDatSet(string fileName)
{
//create a new XMLSerializer object of type DataSet
XmlSerializer ser = new XmlSerializer(typeof(DataSet));

DataSet ds = new DataSet("ds01");
DataTable t = new DataTable("table01");
DataColumn qNo = new DataColumn("questionNo");
DataColumn ans = new DataColumn("answer");

t.Columns.Add(qNo);
t.Columns.Add(ans);
ds.Tables.Add(t);

DataRow r;
int qLimit = 10;
for (int i = 0; i <>
{
r = t.NewRow();
r["questionNo"] = i;
r["answer"] = "answer for question" + i;
t.Rows.Add(r);
}

Console.WriteLine("Data added to the table\n");
Console.WriteLine("QuestionNo\t\tAnswer");
Console.WriteLine("--------------------------------------------");
for (int i = 0; i <>
{
Console.WriteLine(t.Rows[i][0].ToString()+"\t\t|\t"+t.Rows[i][1].ToString());
}
TextWriter writer=new StreamWriter(fileName);

//write the data set to the writer stream using the serialization object
ser.Serialize(writer,ds);

writer.Close();

}

so lets say you want to write an ArrayList to a XML file
well see the code below

public static void writeToXML(string fileName)
{
ArrayList arr = new ArrayList();
for (int i = 0; i <>
{
arr.Add("answer for question" + i);
}
XmlSerializer ser = new XmlSerializer(typeof(ArrayList));
TextWriter writer = new StreamWriter(fileName);
ser.Serialize(writer, arr);
writer.Close();
}