We all know that data manipulation using tables have been made very easy by LINQ to SQL right! For an example a sample data retrieval and update query using LINQ will look something like this.

I'll just note down the steps involved so rookies will have an idea of what I'm talking about

  1. Add a new LINQ to SQL class file (.dbml) to your project
  2. Then drag and drop a table you want to query using the server explorer of VS (lets name the new file as Demo.dbml)
Here is some sample code to get you started with

var context = new DemoDataContext(); //get the data context you want to query
//retreive data from the table
var records = from tableTest in dc.DemoTable
              where tableTest.condition == -1
              select tableTest;


Now let's play with them a bit

foreach (var record in records){
  try

   {
    var rowInfo = context.DemoTable.Single(ob => ob.Id == rec.Id);
    var someValue=GetValue();
    rowInfo.condition = someValue > 0 ? 1 : 0; //Change a value of a property
    context.SubmitChanges();//Save the changed data to the table
   }
  catch (Exception ex)

  {
    Console.WriteLine(ex.Message);
    continue;

  }
}

That's really straight forward right! We can use the same set of steps to manipulate data using SQL Views. But there seems to be some sort of a bug in VS2010 when using LINQ to SQL class files. When we drag and drop a table to a dbml file the primary key of the table is identified and is set correctly. But if we use a VIEW that incorporates a set of tables using UNIONS this does not happen. Making it impossible to save or update data in the underlying table because of the missing primary key. You will run the same code for a view but no data will get saved.
 To avoid such a bizarre situation you need to manually set the primary key of the view using properties. To do that select the view that you needs to work on and in its attributes set click on its primary key column and go to its properties. And set the Primary Key property to true.

Now you will be able to work with your views without any problems.

I came across a very useful plug-in few days back for drawing Gantt charts using JQuery. You can find all the information plus the files you need to download from here (https://github.com/thegrubbsian/jquery.ganttView).

As I described previously from a blog when we drew JQuery charts, we can use the power of JSON to get serialized data from the server side to populate the needed data model. In this case the the data model looked something like this.

var ganttData =
[
    {
        id: 1, name: "Feature 1"
        series: 
        [
            { name: "Planned", start: new Date(2010,00,01), end: new Date(2010,00,03) },
            { name: "Actual", start: new Date(2010,00,02), end: new Date(2010,00,05) }
        ]
    },
    {
        id: 2, name: "Feature 2" 

        series: 
        [
            { name: "Planned", start: new Date(2010,00,05), end: new Date(2010,00,20) },
            { name: "Actual", start: new Date(2010,00,06), end: new Date(2010,00,17) },
            { name: "Projected", start: new Date(2010,00,06), end: new Date(2010,00,17) }
        ]
    }
]

 
In order to tackle this, my server side data model should look something like this.

public class ContainerModel

{
   public String id { get; set; }
   public String name { get; set; }
   public List<DataModel> series { get; set; }

}
public class DataModel
{
   public string name { get; set; }
   public DateTime start { get; set; }
   public DateTime end { get; set; }

}
 

Let's write a sample method to populate the data model with some dummy data.

public static List<ContainerModel> PopulateData(){
  var startDate = new DateTime(2010, 5, 12);
  var endDate = new DateTime(2010, 12, 5);


  var planned = new DataModel { name = "Planned", start = startDate, end = endDate };
  var actual = new DataModel { name = "Actual", start = startDate, end = endDate };
  var projected = new DataModel { name = "Projected", start = startDate, end = endDate };


  var dataSet = new List<ContainerModel>();
  for (int k = 0; k < 10; k++)
{
    var container = new ContainerModel
{
                          id = k.ToString(),
                          name = string.Format("Feature {0}", k),
                          series = new List<DataModel> { planned, actual, projected }
                        };
    dataSet.Add(container); 

  }
  return dataSet;

}

And these methods were used to serialize the data model to JSON so we can use it from the JavaScript side.

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(List<ContainerModel> dataModel)
{
  return dataModel.ToJson();

}


Let's write a web method so we can use a JQuery AJAX call back to retrieve the prepared data.
I have embedded the above mentioned PopulateData, ToJson, GetJason methods in to a Helper class for more code clarity

[WebMethod]
public static string GetData()
{
  var modelData = Helper.PopulateData();
  var jsonData = Helper.GetJason(modelData);
  return jsonData;

}

Now all our server side codes are completed, but then come the fun part. As you can see in the above mentioned data model the dates are represented as JavaScript Date objects
{ name: "Planned", start: new Date(2010,00,05), end: new Date(2010,00,20) },
But date returned by Json is a string that looks something like this "/Date(1273602600000+0530)/" .
In order to convert that JSON serialized millisecond date string to a JavaScript Date object, we can use JavaScript substring function with eval
startDate = eval("new " + start.substring(1, start.length - 7) + ")");
Resulting in returning a JavaScript Date object with a value like
"Wed May 12 2010 00:00:00 GMT+0530 (Sri Lanka Standard Time)"

So let's replace the DateUtils Class in the jQuery.ganttView.js with this one

var DateUtils = {
  daysBetweenBothString: function (start, end){
    var startDate, endDate;

    startDate = eval("new " + start.substring(1, start.length - 7) + ")");
    endDate = eval("new " + end.substring(1, end.length - 7) + ")");
    var count = 0, date = startDate.clone();
    while (date.compareTo(endDate) == -1) { count = count + 1; date.addDays(1); }
    return count;

  },
  daysBetweenEndString: function (start, end){
   endDate = eval("new " + end.substring(1, end.length - 7) + ")");
    var count = 0, date = start.clone();
    while (date.compareTo(endDate) == -1) { count = count + 1; date.addDays(1); }
    return count;

  },
  daysBetween: function (start, end){
    var count = 0, date = start.clone();
    while (date.compareTo(end) == -1) { count = count + 1; date.addDays(1); }
    return count;

  },
  isWeekend: function (date){
    return date.getDay() % 6 == 0;

  }
};

And the addBlocks method with this

addBlocks: function (div, data, cellWidth, start){
  var rows = jQuery("div.ganttview-blocks div.ganttview-block-container", div);
  var rowIdx = 0;
  for (var i = 0; i < data.length; i++) {
   for (var j = 0; j < data[i].series.length; j++) {
   var size = DateUtils.daysBetweenBothString(data[i].series[j].start, data[i].series[j].end);
   var offset = DateUtils.daysBetweenEndString(start, data[i].series[j].start);
   var blockDiv = jQuery("<div>", {
     "class": "ganttview-block",
     "title": data[i].series[j].name + ", " + size + " days",
     "css": {
     "width": ((size * cellWidth) - 9) + "px",
     "margin-left": ((offset * cellWidth) + 3) + "px"

    }});
  if (data[i].series[j].color){

   blockDiv.css("background-color", data[i].series[j].color);
  }
  blockDiv.append($("<div>", { "class": "ganttview-block-text" }).text(size));
  jQuery(rows[rowIdx]).append(blockDiv);
  rowIdx = rowIdx + 1;
  }
  }
}

Now you can use this modified version of the JS file to support your JSON serialized data object.
In the aspx page (in this case Default.aspx ) where we need to draw the chart insert the following script

<script type="text/javascript">
$(document).ready(function (){
var ganttData = [];

$("#btnGetData").live("click", function (e){
  var button = $(this);

  function onDataReceived(series){

    ganttData = series.d;
    $("#ganttChart").ganttView({
    data: $.parseJSON(ganttData),
    start: new Date(2010, 05, 01),
    end: new Date(2010, 12, 31),
    slideWidth: 900
   });
  }
  var dataUrl = "Default.aspx/GetData";

  $.ajax({
   type: "POST",
   url: dataUrl,
   data: "{}",
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: onDataReceived
  });
  });
});
</script>

And add the following div tag to the page so the JS file can inject the rendered Chart inside it
<div id="ganttChart"></div>
Accompanied with the button to trigger the AJAX call back
<div><input id="btnGetData" type="button" value="Get Data" /></div>

Now you are all set for your first JQuery Gantt Chart.




 

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!!!