AJAX based CRUD tables using ASP.NET MVC 3 and jTable jQuery plug-in


jTable overview
A full-featured jTable instance. Try a live demo here.

Contents

  • Introduction to the problem
  • What is jTable?
  • Live demo
  • A sample page with ASP.NET MVC 3 and jTable
    • Using the page
    • Model
    • Controller
      • Getting the list
      • Creating
      • Updating
      • Deleting
      • Getting options
    • View
  • Paging
  • Sorting
  • Selecting
  • Master/child tables
  • ASP.NET Web Forms support
  • Details
    • Methods
    • Actions
    • Field options
    • Other options
    • Events
    • Localization
    • Styling
  • Combining with validation
  • Future works
  • More
  • History
  • References

Introduction to the problem

When we are developing a ‘data manipulation page‘, we almost always do the same thing: A ‘table/grid’ that is used to ‘show records‘ of a table in a database, a ‘create new record‘ page/dialog to add a new record to the database, an ‘edit record‘ page/dialog to edit a record, and finally a way of ‘deleting a record‘ in the database.

Also, using AJAX, we can create more fast and interactive pages. Especially, jQuery and jQueryUI are invaluable libraries to perform manipulation in an HTML page and perform AJAX requests to the server.

Users no longer need to leave the ‘list of records’ page to create/edit or delete a record. Also, the page never refreshes itself to reflect a change in records. When the user deletes a record in the table, we can delete the corresponding row from the table without refreshing the whole page. When the user edits a record and saves it, we can change the corresponding values in the table, and so on… Also, we can do some animations while deleting, creating, or updating records.

All of the subjects I mentioned above are known techniques and we have all implemented them. But the problem is that, we are developing/coding almost the same page for every type of record. Surely, we can copy/paste/modify it! But is it a solution or another mess? All we know is, copy/paste is not desirable for all kinds of programming, it is an evil!

What is jTable

jTable [1] is a jQuery plug-in that addresses the problem mentioned above. It takes a list and properties of fields of a record and does all the job! It has several features:

  • Automatically creates an HTML table and loads records from the server using AJAX.
  • Automatically creates a ‘create new record‘ jQueryUI dialog form. When the user creates a record, it sends data to the server using AJAX and adds the same record to the table in the page.
  • Automatically creates an ‘edit record‘ jQueryUI dialog form. When the user edits a record, it updates the server using AJAX and updates all the cells on the table in the page.
  • Allow the user to ‘delete a record‘ by jQueryUI dialog based confirmation. When the user deletes a record, it deletes the record from the server using AJAX and deletes the record from the table in the page.
  • Supports server side AJAX based paging and sorting.
  • Allows user to select rows from table.
  • Supports unlimited level of master/child tables.
  • Shows animations for create/delete/edit operations on the table.
  • Exposes some events to enable validation with forms.
  • It can be localized easily.
  • Table, forms and other elements are styled in a well defined and commented CSS file.
  • It comes with four pre-defined color themes: blue, red, green and purple, for now.
  • It is browser/platform independent and works on all common browsers.
  • It is not dependent on any server-side technology such as ASP.NET MVC, and can be used with others.
  • It has direct support for ASP.NET Web Forms Page Methods.

Live demo

You can try out a demonstration here: http://www.jtable.org.

A sample page with ASP.NET MVC 3 and jTable

Here I will show how to develop a data manipulation page with ASP.NET MVC 3 and jTable. This sample project is included in the download file.

Assume that we are manipulating a Person list that has a lot of information: name, city, email, password, gender, birth date, an ‘about’ text, and education.

Using the page

First, I will show the capabilities of jTable. Here is the list of people:

The Person List

This table is automatically created by jTable. (Don’t worry about the style of the table. The HTML code of the table is not styled and is a clean HTML table. You can edit the CSS files easily.) Also, it shows only the desired fields. Edit/Delete images (buttons) are completely optional, and they are also automatically added to each row. Title is also optional and the add new record link is changeable by the user with another element in the page. While the records are being loaded, a ‘loading…’ animation is shown.

When the user clicks the add new record link, a jQueryUI dialog based form is opened:

Creating new record

This form is also completely automatically created based on the fields of the record! When you fill the form and save, jTable serializes the form and performs an AJAX call to the server. If the server responds ‘OK‘, it adds the record to the table with an animation:

Added new record animation

In the animation above, the row is highlighted with green. It turns back to normal color after a few seconds. This animation is just a CSS class transition and can be changed in the CSS file easily. So you can change the animation to whatever you want. If the server returns error while adding the record, jTable automatically shows an error dialog message and does not add the record to the table.

If you click the edit image (button) in a row, jTable automatically creates an editing jQuery dialog form:

Editing a record

jTable automatically creates and fills the form with the selected record’s values. When the user saves the form, just like creating a new record, the record is saved to the server. If the AJAX call is a success, the record values are updated in the table and an ‘edited’ animation is shown:

Editing Record Animation

As I mentioned above when creating the record, same animation mechanism does exist while updating an edited record in the table. An edited row turns to normal style in a few seconds.

When the user clicks the delete image (button), jTable shows a confirmation dialog:

Delete confirmation dialog

If the user clicks the delete button, the record is deleted from the server using an AJAX call. If the operation succeeds, it is also removed from the table automatically with a deleting animation:

Deleting animation

The deleting row is highlighted for a second and removed from the table.

Now we will see how to implement the page above in ASP.NET MVC 3.

Model

We have two classes here: Person (represents a record in the People database table) and City (represents a record in the Cities database table). A person lives in a city. So the Person class has a CityId that is the ID of a city row in the Cities table.

The Person class is shown below:

Collapse | Copy Code
public class Person
{
    public int PersonId { get; set; }

    // Id of a City in Cities
    [Required]
    public int CityId { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string EmailAddress { get; set; }

    [Required]
    public string Password { get; set; }

    // "M" for mail, "F" for female.
    [Required]
    public string Gender { get; set; }

    [Required]
    public DateTime BirthDate { get; set; }

    public string About { get; set; }

    // 0: Unselected, 1: Primary school,
    // 2: High school 3: University
    [Required]
    public int Education { get; set; }

    //true: Active, false: Passive
    [Required]
    public bool IsActive { get; set; }

    [Required]
    public DateTime RecordDate { get; set; }

    public Person()
    {
        RecordDate = DateTime.Now;
        Password = "123";
        About = "";
    }
}

The [Required] attributes are not related to jTable as you probably know. They are used by ASP.NET MVC and Entity framework for validation.

City is a simple class. It is designed to show the combobox feature of jTable (as you’ve seen above).

Collapse | Copy Code
public class City
{
    public int CityId { get; set; }

    [Required]
    public string CityName { get; set; }
}

Controller

jTable always uses the POST method while making AJAX calls to the server and expects a JSON object. URLs (Controller/Action names in ASP.NET MVC) can be arbitrary and they are set while creating a jTable instance (we will see this soon).

Getting the list

You must supply an action to jTable to get a list of records:

Collapse | Copy Code
[HttpPost]
public JsonResult PersonList()
{
    try
    {
        List<Person> persons = _personRepository.GetAllPersons();
        return Json(new { Result = "OK", Records = persons });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

All methods must return a JSON object. Result property must be “OK” if operation is successful. If an error occurs, Message property will contain an error message to show to the user. If Result is “OK“, the Records property will contain an array of records to show in the table.

You could pass some parameters to the action that can be used to get records based on some filters. Also, you can paginate or sort the table. We will see this later.

Creating

Creating a record is optional (we will see soon). If you allow user to create a record, you must supply an action to jTable to create a new record:

Collapse | Copy Code
[HttpPost]
public JsonResult CreatePerson(Person person)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return Json(new { Result = "ERROR", 
              Message = "Form is not valid! " + 
              "Please correct it and try again." });
        }

        var addedPerson = _personRepository.AddPerson(person);
        return Json(new { Result = "OK", Record = addedPerson });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

CreatePerson method must return the newly created object as the Record property. This is needed since newly inserted record will has a key (PersonId in this sample) and automatically generated values (such as RecordDate here).

Updating

Editing a record is optional (we will see soon). If you allow user to edit a record, you must supply an action to jTable to update a record:

Collapse | Copy Code
[HttpPost]
public JsonResult UpdatePerson(Person person)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return Json(new { Result = "ERROR", 
              Message = "Form is not valid! " + 
                "Please correct it and try again." });
        }

        _personRepository.UpdatePerson(person);
        return Json(new { Result = "OK" });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

Deleting

Deleting a record is optional (we will see soon). If you allow user to delete a record, You must supply an action to jTable to delete a record:

Collapse | Copy Code
[HttpPost]
public JsonResult DeletePerson(int personId)
{
    try
    {
        _personRepository.DeletePerson(personId);
        return Json(new { Result = "OK" });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

Getting options

jTable can automatically download and fill comboboxes from a URL. For instance, the City combobox in the Person create/edit form above uses this feature. In such cases, you must supply an action to get the option list:

Collapse | Copy Code
[HttpPost]
public JsonResult GetCityOptions()
{
    try
    {
        var cities = _personRepository.GetCities().Select(
            c => new { DisplayText = c.CityName, Value = c.CityId });
        return Json(new { Result = "OK", Options = cities });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

The returning JSON object must have the Options property. It is an array of objects and every object has two properties: DisplayText and Value.

View

C# codes above was not directly related to jTable and specific to the ASP.NET MVC implementation. View side is completely about jTable. When you download jTable, you will have a folder structure as shown below:

jTable folder structure

jquery.jtable.js file is the main and only JavaScript file which you must include in your project. Other files (CSS and images files) are used for styling the table and forms. We will come back to styling later.

First, we add the jtable_blue.css file (my favourite style ūüôā to the HEAD section of the HTML document (Razor view in ASP.NET MVC3):

Collapse | Copy Code
<link href="http://www.codeproject.com/Scripts/jtable/themes/standard/blue/jtable_blue.css" 
      rel="stylesheet" type="text/css" />

You can add red or purple style files instead of blue, or you can write your own style file. Then we must add the jquery.jtable.js script file to the page:

Collapse | Copy Code
<script type="text/javascript" src="http://www.codeproject.com/Scripts/jtable/jquery.jtable.js">
</script>

Note that jTable is dependent on jQuery and jQueryUI (included UI effects). So, you must add those scripts to your page before jTable. If you don’t have these libraries, go to http://jqueryui.com/download to download jQueryUI (it includes jQuery).

Finally, we can create the jTable instance like this:

Collapse | Copy Code
<div id="PersonTable" style="width: 580px; margin: auto;"></div>

<script type="text/javascript">

    $(document).ready(function () {

        //Prepare jtable plugin
        $('#PersonTable').jtable({
            title: 'The Person List',
            actions: {
                listAction: '/Home/PersonList',
                deleteAction: '/Home/DeletePerson',
                updateAction: '/Home/UpdatePerson',
                createAction: '/Home/CreatePerson'
            },
            fields: {
                PersonId: {
                    key: true,
                    create: false,
                    edit: false,
                    list: false
                },
                Name: {
                    title: 'Name',
                    width: '15%'
                },
                EmailAddress: {
                    title: 'Emal address',
                    list: false
                },
                Password: {
                    title: 'User Password',
                    type: 'password',
                    list: false
                },
                Gender: {
                    title: 'Gender',
                    width: '12%',
                    options: { 'M': 'Male', 'F': 'Female' }
                },
                CityId: {
                    title: 'Living city',
                    width: '15%',
                    options: '/Home/GetCityOptions'
                },
                BirthDate: {
                    title: 'Birth date',
                    width: '18%',
                    type: 'date',
                    displayFormat: 'yy-mm-dd'
                },
                Education: {
                    title: 'Education',
                    list: false,
                    type: 'radiobutton',
                    options: { '1': 'Primary school', 
                       '2': 'High school', '3': 'University' }
                },
                About: {
                    title: 'About this person',
                    type: 'textarea',
                    list: false
                },
                IsActive: {
                    title: 'Status',
                    width: '10%',
                    type: 'checkbox',
                    values: { 'false': 'Passive', 'true': 'Active' },
                    defaultValue: 'true'
                },
                RecordDate: {
                    title: 'Record date',
                    width: '18%',
                    type: 'date',
                    displayFormat: 'dd.mm.yy',
                    create: false,
                    edit: false
                }
            }
        });

        //Load person list from server
        $('#PersonTable').jtable('load');
    });

</script>

Yes, it’s a long definition but that’s all! jTable does not need anything else to create tables, forms, and animations. I’ll explain all options in the Details section but I want to explain some basics now.

As you can see, jTable just needs a div container as the only HTML tag. It gets options:

  • title: Title of the table.
  • actions: URLs of actions that are used to create/delete/update/list records.
  • fields: All fields of the record. A field entry has properties that define the field.

Finally, the load method of jTable is used to get records from the server (we will see this in detail). You can always call this method to load/refresh table data from the server.

Paging

jTable allows you server side paging with AJAX. See a demo here. It looks like the sample below:

Paging with jTable

To enable paging, paging option must set to true. You can also set pageSize option (default value is 10).

Collapse | Copy Code
$('#PersonTable').jtable({
    //...
    paging: true, //Set paging enabled
    actions: {
        //...
    },
    fields: {
        //...
    }
});

If paging is enabled, jTable sends two query string parameters to the server on listAction AJAX call:

  • jtStartIndex: Start index of records for current page.
  • jtPageSize: Count of maximum expected records.

Also, one additional information is expected from server:

  • TotalRecordCount: Total count of records (not only this page).

An ASP.NET MVC action that is used for paging is shown below:

Collapse | Copy Code
[HttpPost]
public JsonResult PersonList(int jtStartIndex, int jtPageSize)
{
    try
    {
        int personCount = _personRepository.GetPersonCount();
        List<Person> persons = _personRepository.GetPersons(jtStartIndex, jtPageSize);
        return Json(new { Result = "OK", Records = persons, TotalRecordCount = personCount });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

Sorting

jTable allows you server side sorting with AJAX. See a demo here. It looks like the sample below:

jTable sorting

To enable sorting, sorting option must set to true. You can also set defaultSorting option. It can be a field name of a column of the table. For instance, if you want table sorted by Name by default, defaultSorting can be ‘Name ASC‘ or ‘Name DESC‘.

Collapse | Copy Code
$('#PersonTable').jtable({
    //...
 sorting: true, //Enable sorting
 defaultSorting: 'Name ASC', //Sort by Name by default
    actions: {
        //...
    },
    fields: {
        //...
    }
});

If sorting is enabled, jTable sends a query string parameter to the server on listAction AJAX call:

  • jtSorting: A string represents requested sorting. It is built from sorting field name plus sorting direction. For instance, It can be ‘Name ASC‘, ‘BirtDate DESC‘, ‘Age ASC‘… etc.

An ASP.NET MVC action that is used for sorting is shown below:

Collapse | Copy Code
[HttpPost]
public JsonResult PersonList(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
{
    try
    {
        int personCount = _personRepository.GetPersonCount();
        List<person> persons = _personRepository.GetPersons(jtStartIndex, jtPageSize, jtSorting);
        return Json(new { Result = "OK", Records = persons, TotalRecordCount = personCount });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

Note that while sorting can be used with paging (as in this sample), it is completely independed from paging.

Selecting

jTable allows you client side selecting rows. See a demo here. It looks like the sample below:

jTable selecting

To enable selecting, selecting option must set to true. You can set multiselect option to true to allow user to select multiple rows at once. You can set selectingCheckboxes option to true to show checkboxes as the sample above. Finally, you can set selectOnRowClick to false to prevent row selecting on clicking anywhere on the row (it’s true as default).

To get list of selected rows, you can call selectedRows method of jTable anytime (see sample usage). Also, you can get notified when selection changed by selectionChanged event.

Collapse | Copy Code
//Prepare jtable plugin
$('#PersonTable').jtable({
    //...
 selecting: true, //Enable selecting
 multiselect: true, //Allow multiple selecting
 selectingCheckboxes: true, //Show checkboxes on first column
 //selectOnRowClick: false, //Enable this to only select using checkboxes
    actions: {
        //...
    },
    fields: {
        //...
    },
    //Register to selectionChanged event
    selectionChanged: function () {
        //Get all selected rows
        var $selectedRows = $('#PersonTable').jtable('selectedRows');

        $('#SelectedRowList').empty();
        if ($selectedRows.length > 0) {
            //Show selected rows
            $selectedRows.each(function () {
                var record = $(this).data('record');
                $('#SelectedRowList').append(
                    'PersonId: ' + record.PersonId +
                    'Name:' + record.Name
                    );
            });
        } else {
            //No rows selected
            $('#SelectedRowList').append('No row selected! Select rows to see here...');
        }
    }
});

In the sample above, we are registering to selectionChanged event. In the event handler, we are getting selected rows by selectedRows method. It returns a jQuery selection, so we can call any jQuery method on it. We can get the record by record data property. Then we can get fields of record as record.Name, record.PersonId… etc.

Master/Child tables

jTable supports unlimited level of child tables for a table. Child tables can also have their children and so on… A child table is releated in a row in master table. Look at the screen below:

Master Child table on jTable

Click here to see a live demo. When you click phone icon at left of a row, a new table slides down below the clicked row and you can manipulate phones of the selected person. You can do everything just as a regular jTable. When you click close button, child table slides up and closed.

To implement a child table, first we must understand custom (computed) column support of jTable. Green phone icon on the figure above is created in a custom column. To create a custom column, we use display option of jtable field definition as like below:

Collapse | Copy Code
//...
Phones: {
    title: '',
    width: '3%',
    sorting: false,
    edit: false,
    create: false,
    display: function (personData) {
        var $img = $('<img src="http://www.codeproject.com/Content/images/Misc/phone.png" title="Edit phone numbers" />');
        return $img;
    }
}
//...

Phones is a field definition as Name or Gender columns. But Person record has not a field named Phones. So, we define a function that will create value of this field to show on the table. display function is used for that. It is called by jTable for each row. It must return a text, HTML code or jQuery object. In the sample above, I created an image (green phone icon) as a jQuery object and returned it. Then jTable showed this image in the row. personData argument (you can change name of the argument of course) has record property that can be used to get record values for current row. So, if you want to use Name of the person, you can get it using personData.record.Name.

So far so good. But, how to open child table when user clicks this image. jTable defines two methods: openChildTable and closeChildTable to control child tables. So, web can open a child table when user clicks the phone icon (in the display method above):

Collapse | Copy Code
$img.click(function() {
    $('#PersonTable').jtable('openChildTable',
        $img.closest('tr'),
        {
            title: personData.record.Name + ' - Phone numbers',
            actions: {
                listAction: '/PagingPerson/PhoneList?PersonId=' +
                            personData.record.PersonId,
                deleteAction: '/PagingPerson/DeletePhone',
                updateAction: '/PagingPerson/UpdatePhone',
                createAction: '/PagingPerson/CreatePhone'
            },
            fields: {
                StudentId: {
                    type: 'hidden',
                    defaultValue: studentData.record.StudentId
                },
                PhoneId: {
                    key: true,
                    create: false,
                    edit: false,
                    list: false
                },
                PhoneType: {
                    title: 'Phone type',
                    width: '30%',
                    options: { '1': 'Home phone', 
                               '2': 'Office phone', 
                               '3': 'Cell phone'}
                },
                Number: {
                    title: 'Phone Number',
                    width: '30%'
                },
                RecordDate: {
                    title: 'Record date',
                    width: '20%',
                    type: 'date',
                    displayFormat: 'dd.mm.yy',
                    create: false,
                    edit: false
                }
            }
        }, function(data) { //opened handler
            data.childTable.jtable('load');
        });
});

openChildTable has three parameters. First one is used to indicate the row which is used as master row of child table. Here, I got container tr element of the image, so it gives the current row. Second parameter is a regular jTable initialization options. You can pass any option that can be passed to any jTable instance. So, you can define a custom column and open a second level child. Third and the last parameter is a callback method that is called by jTable after child table successfully created and opened. Here, I loaded records after child table is opened.

Look at the listAction. It’s something like that: ‘/PagingPerson/PhoneList?PersonId=’ + personData.record.PersonId. Thus, we are getting phone numbers those are related to current person (personData comes from display method, see codes above). Also, we need PersonId in the server side while creating a new phone number for a person. It’s done with a hidden field (See StudentId definition). Given default value is used for new records.

When you create a child table, jTable automatically closes it when user clicks close icon of the table. You can change/override these functionalities. See details to learn in deep.

ASP.NET Web Forms support

jTable has direct support for ASP.NET Web Forms Page Methods since jTable v1.4.1. While jTable is already platform independed, I have built an extension to jTable to support Page Methods in most proper way. For instance, see the code below. This page method is used to get student list as paged and sorted. It’s pretty much similar to it’s MVC version.

Collapse | Copy Code
[WebMethod(EnableSession = true)]
public static object StudentList(int jtStartIndex, int jtPageSize, string jtSorting)
{
    try
    {
        //Get data from database
        int studentCount = Repository.StudentRepository.GetStudentCount();
        List<student> students = Repository.StudentRepository.GetStudents(jtStartIndex, jtPageSize, jtSorting);
 
        //Return result to jTable
        return new { Result = "OK", Records = students, TotalRecordCount = studentCount };
    }
    catch (Exception ex)
    {
        return new { Result = "ERROR", Message = ex.Message };
    }
}

For more information on ASP.NET Web Forms support, see the tutorial in jTable.org. Also, the download file in this article includes samples in ASP.NET Web Forms.

Details

Now I will explain detailed usage of jTable.

Methods

jTable defines fallowing methods:

load(postData, completeCallback)

Loads records from the server. All parameters are optional. If you want to pass some parameters to the server, you can pass them in the postData argument while calling the load method, like this:

Collapse | Copy Code
$('#PersonTable').jtable('load', { CityId: 2, Name: 'Halil' });

You can get people who are living in city 2 and whose name is Halil like shown above. Surely, you must handle these parameters in the server side. Also, you can pass a callback method as completeCallback, that is called when loading of data is successfully completed.

reload(completeCallback)

Re-loads records from server with last postData. This method can be used to refresh table data from server since it does not change current page, sorting and uses last postData (passed on last load call). Also, you can pass a callback method as completeCallback, that is called when loading of data is successfully completed.

selectedRows()

Gets all selected rows as jQuery selection. See the sample above.

deleteRows(rows)

Deletes given rows from server and table. rows parameter must be a jQuery selection. This method can be combined with selectedRows method. Thus, you can get selected rows and pass to deleteRows method to delete them.

openChildTable(row, tableOptions, opened)

This method is used to create and open a child table for a data row (See Master/Child section above). rowargument is a data row on the table, tableOptions are standard jTable options that is used to initialize child table. opened is a callback that is called by jTable when the child table is shown (After opening animation is finished).

closeChildTable(row, closed)

This method is used to close an open child table for a table row. row is a jQuery row object (tr element) on the table. closed is a callback function that is called when child table is closed.

openChildRow(row)

This method is used to open child row for a table row. Child rows generally used to show child tables. If you want to show child tables, you don’t need to use this method, use openChildTable method instead. If you want to open a custom child row, use this method. It returns the opened child row. Thus, you can fill it with a custom content. A child row is related to a specific data row in the table (which is passed as row agrument). If the data row is removed from table, it’s child is also automatically removed.

closeChildRow(row)

This method is used to close an open child row for a table row. See openChildRow method. (This method is internally used by jTable to close child tables.)

getChildRow(row)

This method is used to get child row (tr element) for a table row. Thus, you can add content to the child row. See openChildRow method.

isChildRowOpen(row)

This method returns true if child row is open for specified row. See openChildRow method.

addRecord(options), removeRecord(options), updateRecord(options)

These methods are used to manipulate table data programmatically. Since they have a bit detailed usage, please see reference documentation for these methods.

Actions

There are four main actions that are used by jTable to perform AJAX requests to the server:

  • listAction: A URL address to get the list of records.
  • createAction: A URL address to submit a create new record form.
  • updateAction: A URL address to submit an edit record form.
  • deleteAction: A URL address to delete a record.

If you don’t want to use an action, just don’t define it. For instance, if you don’t want to allow user to delete a row, don’t supply a deleteAction URL. Thus, jTable will not put a delete button for the records.

Field options

Fields are the core of jTable. They define the shape and behavior of your page. A field can have these properties:

    • title: A string as header in the table and forms for this field.
    • width: Width of the column for this field in the table. Can be any CSS unit (15%, 120px.., so on).
    • key: A boolean value that indicates whether this field is the key field of the record. Every record must has one and only one key field that is used as key on update and delete operations.
    • list: A boolean value that indicates whether this field is shown in the table.
    • create: A boolean value that indicates whether this field is shown in the create record form.
    • edit: A boolean value that indicates whether this field is shown in the edit record form.
    • options: If this field’s value will be selected in an option list (combobox as default, can be radio button list), you must supply a source. An option source can be one of these values:
      • URL string: A URL to download the option list for this field (as we’ve seen above).
      • object: Property names are values, property values are display texts (see sample jTable instance in the View section above).
      • array: An array of values. If values of options are same as display texts, you can use this type.
    • type: Type of the field. If field is a string or number, no need to set the type. Other types are:
      • password: Show a password textbox for this field on edit/create forms.
      • textarea: Shows a textarea for this field on edit/create forms.
      • date: A date (not including time). You can also set the displayFormat option.
      • radiobutton: If field is a value from option, it can be a combobox (default) or radio button list. If it is a radio button list, set type as radiobutton. You must supply options as mentioned above.
      • checkbox: To show a checkbox while editing this field. You must supply values option for checked/unchecked states (see the sample page in the View section). By default, a checkbox’s text changes when user changes the state of the checkbox. If you want to fix the text, you can set the formText option for this field. By default, when the user clicks the checkbox’s text, the state of the checkbox changes. If you do not want that, you can set setOnTextClick to false.
      • hidden: A hidden field can be used hidden fields in edit and create forms. It is not shown on the table. You may want to use defaultValue option with hidden types, thus given default value is automatically set to the hidden field on creating form. See master/child demo for sample usage.
    • displayFormat: If the type is date, you can set its format. See jQueryUI datepicker formats [2].
    • defaultValue: You can set a default value for a field. It must be a valid value. For instance, if the field is an option list, it must be one of these options.
    • listClass: A string value that can be set as the class of a cell (td tag) of this field in the table. This way you can style the fields in the table.
    • inputClass: A string value that can be set as the class of an input item for this field in create/edit forms. So you can style input elements in the forms for this field. This can be useful when working with validation plug-ins (we will see soon).
    • sorting: Indicates that whether this column will be used to sort the table (If table is sortable).
    • display: This option is a function that allows you to define a fully custom column for table. jTable directly shows return value of this function on the table. See the sample below:
      Collapse | Copy Code
      TestColumn: {
          title: 'Test',
          display: function (data) {
              return 'test';
          }
      }

      This sample Test column returns a bold ‘test’ string for all rows. You can return any text, html code or jQuery object that will be shown on the table. This method is called for each row. You can get record of the row using data.record. So, if your record has Name property, you can use data.record.Name property to get the Name.
      display function can be used for many purposes such as creating calculated columns, opening child tables for a row… etc. See demos for detailed usage.

    • input: This option is a function that allows you to define a fully custom input element for create and edit forms. jTable directly shows return value of this function on the form.
      Collapse | Copy Code
      Name: {
          title: 'Name',
          width: '20%',
          input: function (data) {
              if (data.record) {
                  return '<input type="text" style="width:200px" value="' + data.record.Name + '" />';
              } else {
                  return '<input type="text" style="width:200px" value="enter your name here" />';
              }
          }
      }
    • Here, we return a simple text input for Name field of the record. If this input is being created for edit form, you can get editing record using data.record property. If this input is being created for create form, it is undefined. You can also use data.value to get current value of the field. This is default value (if defined) of field for create form, current value of field for edit form.

 

    While jTable automatically created appropriate input element for each field, you can use input option to create custom input elements.

Other options

jTable defines some other options that determine the general shape and behavior of the table and forms:

  • title: A string that is shown on top of the table. This is optional, if you don’t supply the title option, no title is displayed.
  • addRecordButton: A jQuery object that can be used instead of the ‘add new record’ link. Thus you can set any element on the page to open the ‘add new record’ dialog. If you set this option, the bottom panel of jTable is not shown (since it will be empty).
  • deleteConfirmation: This option can be a boolean value or a function. If it is a boolean value, that indicates whether a confirmation dialog is shown when user clicks delete button/icon for a record (default value is true). If this option is a function, It can fully control the delete confirmation process. It must be a function like that: deleteConfirmation: function(data) { … }
    data argument has some properties to control confirmation process:

    • row: A jQuery selection for deleting row element.
    • record: Actual deleting record. For example, you can get Name property of record asdata.record.Name.
    • cancel: You can set data.cancel to true to cancel delete process (default value is false).
    • cancelMessage: If you cancelled delete process, you can show a message to user that explains cancellation reason. If you don’t want to show any message, just don’t set it.
    • deleteConfirm: A boolean value indicates whether to show a delete confirmation message or not (default value is true).
    • deleteConfirmMessage: If confirmation enabled, you can set a custom confirmation message.

    For example, if you want to show some additional information to user on delete confirmation, you can write a function like that:

    Collapse | Copy Code
    deleteConfirmation: function(data) {
        data.deleteConfirmMessage = 'Are you sure to delete person ' + data.record.Name + '?';
    }
  • defaultDateFormat: Default format of a date field. See jQueryUI datepicker formats [2]. Default: ‘yy-mm-dd’.
  • dialogShowEffect: jQueryUI effect to be used while opening a jQueryUI dialog. Some options are ‘blind’, ‘bounce’, ‘clip’, ‘drop’, ‘explode’, ‘fold’, ‘highlight’, ‘puff’, ‘pulsate’, ‘scale’, ‘shake’, ‘size’, ‘slide’… etc. See jQueryUI documentation for all options. Default value is ‘fade’.
  • dialogHideEffect: jQueryUI effect to be used while opening a jQueryUI dialog. Some options are ‘blind’, ‘bounce’, ‘clip’, ‘drop’, ‘explode’, ‘fold’, ‘highlight’, ‘puff’, ‘pulsate’, ‘scale’, ‘shake’, ‘size’, ‘slide’… etc. See jQueryUI documentation for all options. Default value is ‘fade’.
  • messages: All messages that are shown by jTable. You can localize these messages (see the Localization section).
  • paging: Indicates that whether jTable uses paging or not.
  • pageSize: If paging enabled, this value indicates number of rows in a page.
  • sorting: Indicates that whether jTable will sort the table or not.
  • defaultSorting: Default sorting of table. It can be a field name of a column of the table. For instance, if you want table sorted by Name by default, defaultSorting can be ‘Name ASC‘ or ‘Name DESC‘.
  • selecting: Indicates that whether jTable allows user to select rows on the table.
  • multiselect: Indicates that whether jTable allows user to select multiple rows at once.
  • selectingCheckboxes: Indicates that whether jTable shows checkbox column for selecting.
  • selectOnRowClick: Indicates that whether jTable allows user to select a row by clicking anywhere on the row. This can be set as false to allow user selecting a row only by clicking to the checkbox (see selectingCheckboxes option).
  • showCloseButton: Indicates that whether jTable will show a close button/icon for the table. When user clicks the close button, closeRequested event is raised. This option is used internally by jTable to close child tables. Default value is false.
  • openChildAsAccordion: If this options is set to true, jTable automatically closes other open child tables when a child table is opened (accordion style). Default value is false.
  • animationsEnabled: Indicates that whether jTable shows animations when user creates, updates or deletes a row.

Events

jTable defines some events when certain conditions occur.

  • formCreated(event, data): This event is raised when an edit or create form is created for a record. You can reach the form using the data.form argument. You can get the type of the form using the data.formType argument. It can be ‘edit’ or ‘create’. If formType is edit, you can reach the editing record using the data.record argument (for example, you can get the name of the editing person as data.record.Name).
  • formSubmitting(event, data): This event is raised when save/submit button is clicked for a form. You can reach the form using the data.form argument. You can get the type of the form using the data.formType argument. It can be ‘edit’ or ‘create’. You can validate the form on this event. If you return false from this event callback, the submit operation is cancelled.
  • formClosed(event, data): This event is raised when an edit/create form dialog is closed. You can reach the form using the data.form argument. You can get the type of the form using the data.formType argument. It can be ‘edit’ or ‘create’.
  • loadingRecords(event, data): This event is raised just before AJAX request to load records from server. It has no arguments.
  • recordAdded(event, data): This event is raised when user successfully creates and saves a new record. You can get the added record using data.record arguement. You can get the response JSON object returned from server as data.serverResponse. If jTable is not running on paging mode, you can also get the added table row by data.row argument.
  • recordDeleted(event, data): This event is raised when user successfully deletes a record. You can get the deleted record using data.record argument. You can get the deleted table row by data.row argument. You can get the response JSON object returned from server as data.serverResponse.
  • recordsLoaded(event, data): This event is raised when jTable loads records from server and refreshes the table (If paging enabled, this event is also raised when user changes the current page). You can get all records loaded from server by data.records argument. You can get the response JSON object returned from server as data.serverResponse.
  • recordUpdated(event, data): This event is raised when user successfully updates a record. You can get the updated record using data.record arguement. You can get the updated table row by data.row argument. You can get the response JSON object returned from server as data.serverResponse.
  • rowsRemoved(event, data): This event is raised when either user deletes row/rows (actual record deletion from server) or during re-loading records from server (all rows cleared but not deleted from server). You can get all removed rows by data.rows as jQuery selection. You can get remove reason by data.reason (can be ‘deleted’ or ‘reloading’).
  • selectionChanged(event, data): This event is raised when selected rows on the table changes in anyway. It may change when user selects/deselects a row, a selected row is deleted, page changed while some rows are selected… etc. You can get selected rows by selectedRows method.
  • closeRequested(event, data): This event is raised when user clicks close button/icon of the table. Close button is shown if showCloseButton is set to true. This event has no argument.
  • rowInserted(event, data): This event is raised when a row is inserted to the shown table. A new row can be inserted either when user added a new record or records loaded from server. When records loaded from server, rowInserted event is called for each row. So, you can modify row or do whatever you need. You can get the row using data.row, you can get related record with data.record. Finally, if this is a new record (that’s added by user) data.isNewRow is set to true by jTable.
  • rowUpdated(event, data): This event is raised when a row updated. A row is updated when user updates a record. You can get the updated row using data.row, you can get related record with data.record. This event is raised after recordUpdated.

NOTE: formCreated, formSubmitting, and formClosed events are suitable to inject validation logic. See the ‘Combining with validation’ section in this article.

Localization

jTable can be easily localized. You can use the messages option to localize a jTable instance on initialization.

Default value of the messages option is shown below:

Collapse | Copy Code
messages: {
    serverCommunicationError: 'An error occured while communicating to the server.',
    loadingMessage: 'Loading records...',
    noDataAvailable: 'No data available!',
    addNewRecord: '+ Add new record',
    editRecord: 'Edit Record',
    areYouSure: 'Are you sure?',
    deleteConfirmation: 'This record will be deleted. Are you sure?',
    save: 'Save',
    saving: 'Saving',
    cancel: 'Cancel',
    deleteText: 'Delete',
    deleting: 'Deleting',
    error: 'Error',
    close: 'Close',
    cannotLoadOptionsFor: 'Can not load options for field {0}',
    pagingInfo: 'Showing {0} to {1} of {2} records',
    canNotDeletedRecords: 'Can not deleted {0} of {1} records!',
    deleteProggress: 'Deleted {0} of {1} records, processing...'
}

Here, a sample localization for Turkish language:

Collapse | Copy Code
<div id="PersonTable" style="width: 580px; margin: auto;">
</div>
<script type="text/javascript">

    $(document).ready(function () {

        //Localization messages for Turkish
        var turkishMessages = {
            serverCommunicationError: 
              'Sunucu ile iletiŇüim kurulurken bir hata oluŇütu.',
            loadingMessage: 'KayńĪtlar y√ľkleniyor...',
            noDataAvailable: 'Hi√ß kayńĪt bulunmamaktadńĪr!',
            addNewRecord: '+ Yeni kayńĪt ekle',
            editRecord: 'KayńĪt d√ľzenle',
            areYouSure: 'Emin misiniz?',
            deleteConfirmation: 'Bu kayńĪt silinecektir. Emin misiniz?',
            save: 'Kaydet',
            saving: 'Kaydediyor',
            cancel: 'ńįptal',
            deleteText: 'Sil',
            deleting: 'Siliyor',
            error: 'Hata',
            close: 'Kapat',
            cannotLoadOptionsFor: '{0} alanńĪ i√ßin se√ßenekler y√ľklenemedi!',
            pagingInfo: '{2} KayńĪttan {0} ile {1} arasńĪ g√∂steriliyor',
            canNotDeletedRecords: '{1} kayńĪttan {0} adedi silinemedi!',
            deleteProggress: '{1} kayńĪttan {0} adedi silindi, devam ediliyor...'
        };

        //Prepare jtable plugin
        $('#PersonTable').jtable({
            messages: turkishMessages, //Set messages as Turkish
            title: '...',
            actions: {
                ...
            },
            fields: {
                ...
            }
        });

        //Load person list from server
        $('#PersonTable').jtable('load');
    });

</script>

Result of the localization:

Turkish Localization

Styling

All styles of jTable are defined in the related CSS files. There are three pre-defined styles other than blue:

jTable Styles

You can set any style by including its CSS file in your HTML document:

Collapse | Copy Code
<!-- BLUE style -->
<link href="http://www.codeproject.com/Scripts/jtable/themes/standard/blue/jtable_blue.css" 
           rel="stylesheet" type="text/css" />

<!-- RED style -->
<link href="http://www.codeproject.com/Scripts/jtable/themes/standard/red/jtable_red.css" 
           rel="stylesheet" type="text/css" />

<!-- GREEN style -->
<link href="http://www.codeproject.com/Scripts/jtable/themes/standard/green/jtable_green.css" 
           rel="stylesheet" type="text/css" />

<!-- PURPLE style -->
<link href="http://www.codeproject.com/Scripts/jtable/themes/standard/purple/jtable_purple.css" 
           rel="stylesheet" type="text/css" />

If you want to use your own styles, you can start with the jtable_empty.css file. It defines all CSS selectors for jTable as empty. You can fill in the CSS selectors.

If you did like the jTable standard theme (defined in jtable_standard_base.css) but not happy with the colors, you can copy jtable_blue.css and change the colors.

Combining with validation

Validation is a common task while working with forms. jTable exposes some events (described above, in the Events section) to inject validation logic to jTable auto-created forms. You can use your own validation logic or a jQuery validation plug-in.

Validation engine [3] is a powerful validation plug-in for jQuery. I definitely recommend it. Here I will show how to inject validation engine to a jTable instance. First, see the validation engine in action:

Validatin Engine Integration

As you can see, when I try to save the form, the validation engine shows some error messages and prevent the submission of the form.

To be able to use the validation engine, first we must add style and JavaScript files to our HTML page:

Collapse | Copy Code
<!-- Validation engine style file -->
<link href="@Url.Content("~/Scripts/validationEngine/validationEngine.jquery.css")" 
      rel="stylesheet" type="text/css" />

<!-- Validation engine script file and english localization -->
<script type="text/javascript" 
  src="@Url.Content("~/Scripts/validationEngine/jquery.validationEngine.js")">
</script>
<script type="text/javascript" 
  src="@Url.Content("~/Scripts/validationEngine/jquery.validationEngine-en.js")">
</script>

Then we register to the events of jTable to inject validation engine to jTable forms:

Collapse | Copy Code
<script type="text/javascript">

    $(document).ready(function () {

        //Prepare jtable plugin
        $('#PersonTable').jtable({
            title: '...',
            actions: {
                ...
            },
            fields: {
                ...
            },
            formCreated: function (event, data) {
 data.form.find('input[name="Name"]').addClass(
 'validate[required]');
 data.form.find('input[name="EmailAddress"]').addClass(
 'validate[required,custom[email]]');
 data.form.find('input[name="Password"]').addClass(
 'validate[required]');
 data.form.find('input[name="BirthDate"]').addClass(
 'validate[required,custom[date]]');
 data.form.find('input[name="Education"]').addClass(
 'validate[required]');
 data.form.validationEngine();
            },
            formSubmitting: function (event, data) {
 return data.form.validationEngine('validate');
            },
            formClosed: function (event, data) {
 data.form.validationEngine('hide');
 data.form.validationEngine('detach');
            }
        });

        //Load person list from server
        $('#PersonTable').jtable('load');
    });

</script>

The validation engine works with CSS classes for validation. validate[required] indicates that this input element can not be empty. Take a look at the validation engine’s web site [3] for details.

In the formCreated event, I add the required classes to input elements and call the validationEngine() plug-in method on the form. In the formSubmitting event, I call the Validate method of the validation engine. It returns false if the form is not valid. So I use the same value as the return value of the formSubmitting event. jTable does not submit the form if this event returns false. Finally, in the formClosed event, I detach the validation engine from the form.

This was the first method for validation. Since jTable allows you to inject classes to your input fields using the inputClass property in field definitions, we could define a field with the validate[required] class as default:

Collapse | Copy Code
//...
Name: {
    title: 'Name',
    width: '15%',
 inputClass: 'validate[required]'
},
//...

Thus, jTable automatically adds the validate[required] class to the input element of this field. So we don’t need to add classes to inputs in the formCreated event.

See the “Using with ‘validation engine’ plugin – 2” demo page in the download file or the demo web site

Introduction to Object Oriented Programming Concepts (OOP) and More


  • 1. Introduction
  • 2. Background
  • 3. Prerequisites
  • 4. The Main Content
    • 4.1. What is Software Architecture?
    • 4.2. Why Architecture is important?
    • 4.3. What is OOP?
    • 4.4. What is an Object?
    • 4.5. What is a Class?
    • 4.6. How to identify and design a Class?
    • 4.7. What is Encapsulation (or information hiding)?
    • 4.8. What is Association?
    • 4.9. What is the difference between Association, Aggregation and Composition?
    • 4.10. What is Abstraction and Generalization?
    • 4.11. What is an Abstract class?
    • 4.12. What is an Interface?
    • 4.13. What is the difference between a Class and an Interface?
    • 4.14. What is the difference between an Interface and an Abstract class?
    • 4.15. What is Implicit and Explicit Interface Implementations?
    • 4.16. What is Inheritance?
    • 4.17. What is Polymorphism?
    • 4.18. What is Method Overloading?
    • 4.19. What is Operator overloading?
    • 4.20. What is Method Overriding?
    • 4.21. What is a Use case?
    • 4.22. What is a Class Diagram?
    • 4.23. What is a Package Diagram?
    • 4.24. What is a Sequence Diagram?
    • 4.25. What is two-tier architecture?
    • 4.26. What is three-tier architecture?
    • 4.27. What is MVC architecture?
    • 4.28. What is SOA?
    • 4.29. What is the Data Access Layer?
    • 4.30. What is the Business Logic Layer?
    • 4.31. What is Gang of Four (GoF) Design Patterns?
    • 4.32. What is the difference between Abstract Factory and Builder design patterns?
  • 5. What is the Conclusion?
  • 6. What I Referred?
  • 7. History

1. Introduction

I have noticed an increase in the number of articles published in the Architect category in code-project during the last few months. The number of readers for most of these articles is also high, though the ratings for the articles are not. This indicates that readers are interested in reading articles on Architecture, but the quality does not match their expectations. This article is a constructive attempt to group/ define/ explain all introductory concepts of software architecture for well seasoned developers who are looking to take their next step as system architects.

One day I read an article that said that the richest 2 percent own half the world’s wealth. It also said that the richest 1 percent of adults owned 40 percent of global assets in the year 2000. And further, that the richest 10 percent of adults accounted for 85 percent of the world’s total wealth. So there is an unbalanced distribution of wealth in the physical world. Have you ever thought of an unbalanced distribution of knowledge in the software world? According to my view point, the massive expansion of the software industry is forcing developers to use already implemented libraries, services and frameworks to develop software within ever shorter periods of time. The new developers are trained to use (I would say more often) already developed software components, to complete the development quicker. They just plug in an existing library and some how manage to achieve the requirements. But the sad part of the story is, that they never get a training to define, design the architecture for, and implement such components. As the number of years pass by, these developers become leads and also software architects. Their titles change, but the old legacy of not understanding, of not having any architectural experience continues, creating a vacuum of good architects. The bottom line is that only a small percentage of developers know how to design a truly object oriented system. The solution to this problem is getting harder every day as the aggressive nature of the software industry does not support an easy adjustment to existing processes, and also the related online teaching materials are either complex or less practical or sometimes even wrong. The most of them use impractical, irrelevant examples of shapes, animals and many other physical world entities to teach concepts of software architecture. There are only very few good business-oriented design references. Unfortunately, I myself am no exception and am a result of this very same system. I got the same education that all of you did, and also referred to the same resource set you all read.

Coming back to the initial point, I noticed that there is a knowledge gap, increasing every day, between the architects who know how to architect a system properly and the others who do not know. The ones, who know, know it right. But the ones, who do not know, know nothing. Just like the world’s wealth distribution, it is an unbalanced distribution of knowledge.

2. Background

This article began after reading and hearing the questions new developers have, on basics of software architecture. There are some good articles out there, but still developers struggle to understand the basic concepts, and more importantly, the way to apply them correctly.

As I see it, newcomers will always struggle to understand a precise definition of a new concept, because it is always a new and hence unfamiliar idea. The one, who has experience, understands the meaning, but the one who doesn’t, struggles to understand the very same definition. It is like that. Employers want experienced employees. So they say, you need to have experience to get a job. But how the hell is one supposed to have that experience if no one is willing to give him a job? As in the general case, the start with software architecture is no exception. It will be difficult. When you start to design your very first system, you will try to apply everything you know or learned from everywhere. You will feel that an interface needs to be defined for every class, like I did once. You will find it harder to understand when and when not to do something. Just prepare to go through a painful process. Others will criticize you, may laugh at you and say that the way you have designed it is wrong. Listen to them, and learn continuously. In this process you will also have to read and think a lot. I hope that this article will give you the right start for that long journey.

‚ÄúThe knowledge of the actions of great men, acquired by long experience in contemporary affairs, and a continual study of antiquity‚ÄĚ ‚Äď I read this phrase when I was reading the book named ‚ÄúThe Art of War‚ÄĚ, seems applicable here, isn‚Äôt it?

3. Prerequisites

This article is an effort to provide an accurate information pool for new developers on the basics of software architecture, focusing on Object Oriented Programming (OOP). If you are a developer, who has a minimum of three or more years of continuous development experience and has that hunger to learn more, to step-in to the next level to become a software architect, this article is for you.

4. The Main Content

4.1. What is Software Architecture?

Software Architecture is defined to be the rules, heuristics and patterns governing:

  • Partitioning the problem and the system to be built into discrete pieces
  • Techniques used to create interfaces between these pieces
  • Techniques used to manage overall structure and flow
  • Techniques used to interface the system to its environment
  • Appropriate use of development and delivery approaches, techniques and tools.

4.2. Why Architecture is important?

OOP.jpg

The primary goal of software architecture is to define the non-functional requirements of a system and define the environment. The detailed design is followed by a definition of how to deliver the functional behavior within the architectural rules. Architecture is important because it:

  • Controls complexity
  • Enforces best practices
  • Gives consistency and uniformity
  • Increases predictability
  • Enables re-use.

4.3. What is OOP?

OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable “objects“. Hence, you gain re-usability by means of four main object-oriented programming concepts.

In order to clearly understand the object orientation, let‚Äôs take your ‚Äúhand‚ÄĚ as an example. The ‚Äúhand‚ÄĚ is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it.

4.4. What is an Object?

An object can be considered a “thing” that can perform a set of related activities. The set of activities that the object performs defines the object’s behavior. For example, the hand can grip something or a Student (object) can give the name or address.

In pure OOP terms an object is an instance of a class.

4.5. What is a Class?

class.gif

A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.

Collapse | Copy Code
public class Student
{
}

According to the sample given below we can say that the student object, named objectStudent, has created out of the Student class.

Collapse | Copy Code
Student objectStudent = new Student();

In real world, you’ll often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles.

In the software world, though you may not have realized it, you have already used classes. For example, the TextBox control, you always used, is made out of the TextBox class, which defines its appearance and capabilities. Each time you drag a TextBox control, you are actually creating a new instance of the TextBox class.

4.6. How to identify and design a Class?

This is an art; each designer uses different techniques to identify classes. However according to Object Oriented Design Principles, there are five principles that you must follow when design a class,

  • SRP – The Single Responsibility Principle –
    A class should have one, and only one, reason to change.
  • OCP – The Open Closed Principle –
    You should be able to extend a classes behavior, without modifying it.
  • LSP – The Liskov Substitution Principle-
    Derived classes must be substitutable for their base classes.
  • DIP – The Dependency Inversion Principle-
    Depend on abstractions, not on concretions.
  • ISP – The Interface Segregation Principle-
    Make fine grained interfaces that are client specific.

For more information on design principles, please refer to Object Mentor.

Additionally to identify a class correctly, you need to identify the full list of leaf level functions/ operations of the system (granular level use cases of the system). Then you can proceed to group each function to form classes (classes will group same types of functions/ operations). However a well defined class must be a meaningful grouping of a set of functions and should support the re-usability while increasing expandability/ maintainability of the overall system.

In software world the concept of dividing and conquering is always recommended, if you start analyzing a full system at the start, you will find it harder to manage. So the better approach is to identify the module of the system first and then dig deep in to each module separately to seek out classes.

A software system may consist of many classes. But in any case, when you have many, it needs to be managed. Think of a big organization, with its work force exceeding several thousand employees (let’s take one employee as a one class). In order to manage such a work force, you need to have proper management policies in place. Same technique can be applies to manage classes of your software system as well. In order to manage the classes of a software system, and to reduce the complexity, the system designers use several techniques, which can be grouped under four main concepts named Encapsulation, Abstraction, Inheritance, and Polymorphism. These concepts are the four main gods of OOP world and in software term, they are called four main Object Oriented Programming (OOP) Concepts.

4.7. What is Encapsulation (or information hiding)?

The encapsulation is the inclusion within a program object of all the resources need for the object to function – basically, the methods and the data. In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes. In that sense, encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system. That idea of encapsulation is to hide how a class does it but to allow requesting what to do.

class.gif

In order to modularize/ define the functionality of a one class, that class can uses functions/ properties exposed by another class in many different ways. According to Object Oriented Programming there are several techniques, classes can use to link with each other and they are named association, aggregation, and composition.

There are several other ways that an encapsulation can be used, as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class.

Collapse | Copy Code
IStudent myStudent = new LocalStudent();
IStudent myStudent = new ForeignStudent();

According to the sample above (let’s assume that LocalStudent and ForeignStudent are implemented by the IStudent interface) we can see how LocalStudent and ForeignStudent are hiding their, localize implementing information through the IStudent interface.

4.8. What is Association?

Association is a (*a*) relationship between two classes. It allows one object instance to cause another to perform an action on its behalf. Association is the more general term that define the relationship between two classes, where as the aggregation and composition are relatively special.

Collapse | Copy Code
public class StudentRegistrar
{
    public StudentRegistrar ();
    {
        new RecordManager().Initialize();
    }
}

In this case we can say that there is an association between StudentRegistrar and RecordManager or there is a directional association from StudentRegistrar to RecordManager or StudentRegistrar use a (*Use*) RecordManager. Since a direction is explicitly specified, in this case the controller class is the StudentRegistrar.

Association.gif

To some beginners, association is a confusing concept. The troubles created not only by the association alone, but with two other OOP concepts, that is association, aggregation and composition. Every one understands association, before aggregation and composition are described. The aggregation or composition cannot be separately understood. If you understand the aggregation alone it will crack the definition given for association, and if you try to understand the composition alone it will always threaten the definition given for aggregation, all three concepts are closely related, hence must study together, by comparing one definition to another. Let’s explore all three and see whether we can understand the differences between these useful concepts.

4.9. What is the difference between Association, Aggregation and Composition?

Association is a (*a*) relationship between two classes, where one class use another. But aggregation describes a special type of an association. Aggregation is the (*the*) relationship between two classes. When object of one class has an (*has*) object of another, if second is a part of first (containment relationship) then we called that there is an aggregation between two classes. Unlike association, aggregation always insists a direction.

Collapse | Copy Code
public class University
{
    private Chancellor  universityChancellor = new Chancellor();
}

aggregation.gif

In this case I can say that University aggregate Chancellor or University has an (*has-a*) Chancellor. But even without a Chancellor a University can exists. But the Faculties cannot exist without the University, the life time of a Faculty (or Faculties) attached with the life time of the University . If University is disposed the Faculties will not exist. In that case we called that University is composed of Faculties. So that composition can be recognized as a special type of an aggregation.

Composite.gif

Same way, as another example, you can say that, there is a composite relationship in-between a KeyValuePairCollection and a KeyValuePair. The two mutually depend on each other.

.Net and Java uses the Composite relation to define their Collections. I have seen Composition is being used in many other ways too. However the more important factor, that most people forget is the life time factor. The life time of the two classes that has bond with a composite relation mutually depend on each other. If you take the .net Collection to understand this, there you have the Collection Element define inside (it is an inner part, hence called it is composed of) the Collection, farcing the Element to get disposed with the Collection. If not, as an example, if you define the Collection and it’s Element to be independent, then the relationship would be more of a type Aggregation, than a Composition. So the point is, if you want to bind two classes with Composite relation, more accurate way is to have a one define inside the other class (making it a protected or private class). This way you are allowing the outer class to fulfill its purpose, while tying the lifetime of the inner class with the outer class.

So in summary, we can say that aggregation is a special kind of an association and composition is a special kind of an aggregation. (Association->Aggregation->Composition)

association_aggre_com.gif

4.10. What is Abstraction and Generalization?

Abstraction is an emphasis on the idea, qualities and properties rather than the particulars (a suppression of detail). The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs.

While abstraction reduces complexity by hiding irrelevant detail, generalization reduces complexity by replacing multiple entities which perform similar functions with a single construct. Generalization is the broadening of application to encompass a larger domain of objects of the same or different type. Programming languages provide generalization through variables, parameterization, generics and polymorphism. It places the emphasis on the similarities between objects. Thus, it helps to manage complexity by collecting individuals into groups and providing a representative which can be used to specify any individual of the group.

Abstraction and generalization are often used together. Abstracts are generalized through parameterization to provide greater utility. In parameterization, one or more parts of an entity are replaced with a name which is new to the entity. The name is used as a parameter. When the parameterized abstract is invoked, it is invoked with a binding of the parameter to an argument.

4.11. What is an Abstract class?

Abstract classes, which declared with the abstract keyword, cannot be instantiated. It can only be used as a super-class for other classes that extend the abstract class. Abstract class is the concept and implementation gets completed when it is being realized by a subclass. In addition to this a class can inherit only from one abstract class (but a class may implement many interfaces) and must override all its abstract methods/ properties and may override virtual methods/ properties.

Abstract classes are ideal when implementing frameworks. As an example, let’s study the abstract class named LoggerBase below. Please carefully read the comments as it will help you to understand the reasoning behind this code.

Collapse | Copy Code
public abstract class LoggerBase
{
    /// <summary>
    /// field is private, so it intend to use inside the class only
    /// </summary>
    private log4net.ILog logger = null; 

    /// <summary>
    /// protected, so it only visible for inherited class
    /// </summary>
    protected LoggerBase()
    {
        // The private object is created inside the constructor
        logger = log4net.LogManager.GetLogger(this.LogPrefix);
        // The additional initialization is done immediately after
        log4net.Config.DOMConfigurator.Configure();
    }

    /// <summary>
    /// When you define the property as abstract,
    /// it forces the inherited class to override the LogPrefix
    /// So, with the help of this technique the log can be made,
    /// inside the abstract class itself, irrespective of it origin.
    /// If you study carefully you will find a reason for not to have ‚Äúset‚ÄĚ method here.
    /// </summary>
    protected abstract System.Type LogPrefix
    {
        get;
    }

    /// <summary>
    /// Simple log method,
    /// which is only visible for inherited classes
    /// </summary>
    /// <param name="message"></param>
    protected void LogError(string message)
    {
        if (this.logger.IsErrorEnabled)
        {
            this.logger.Error(message);
        }
    }

    /// <summary>
    /// Public properties which exposes to inherited class
    /// and all other classes that have access to inherited class
    /// </summary>
    public bool IsThisLogError
    {
        get
        {
            return this.logger.IsErrorEnabled;
        }
    }
}

The idea of having this class as an abstract is to define a framework for exception logging. This class will allow all subclass to gain access to a common exception logging module and will facilitate to easily replace the logging library. By the time you define the LoggerBase, you wouldn’t have an idea about other modules of the system. But you do have a concept in mind and that is, if a class is going to log an exception, they have to inherit the LoggerBase. In other word the LoggerBase provide a framework for exception logging.

Let’s try to understand each line of the above code.

Like any other class, an abstract class can contain fields, hence I used a private field named logger declare the ILog interface of the famous log4net library. This will allow the Loggerbase class to control, what to use, for logging, hence, will allow changing the source logger library easily.

The access modifier of the constructor of the LoggerBase is protected. The public constructor has no use when the class is of type abstract. The abstract classes are not allowed to instantiate the class. So I went for the protected constructor.

The abstract property named LogPrefix is an important one. It enforces and guarantees to have a value for LogPrefix (LogPrefix uses to obtain the detail of the source class, which the exception has occurred) for every subclass, before they invoke a method to log an error.

The method named LogError is protected, hence exposed to all subclasses. You are not allowed or rather you cannot make it public, as any class, without inheriting the LoggerBase cannot use it meaningfully.

Let’s find out why the property named IsThisLogError is public. It may be important/ useful for other associated classes of an inherited class to know whether the associated member logs its errors or not.

Apart from these you can also have virtual methods defined in an abstract class. The virtual method may have its default implementation, where a subclass can override it when required.

All and all, the important factor here is that all OOP concepts should be used carefully with reasons, you should be able to logically explain, why you make a property a public or a field a private or a class an abstract. Additionally, when architecting frameworks, the OOP concepts can be used to forcefully guide the system to be developed in the way framework architect’s wanted it to be architected initially.

4.12. What is an Interface?

In summary the Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be interchangeable. Apart from that an interface is very useful when the implementation changes frequently. Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme.

Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can contain properties (which are also implicitly public and abstract). Interface definition begins with the keyword interface. An interface like that of an abstract class cannot be instantiated.

If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. In addition to this an interfaces can inherit other interfaces.

The sample below will provide an interface for our LoggerBase abstract class.

Collapse | Copy Code
public interface ILogger
{
    bool IsThisLogError { get; }
}

4.13. What is the difference between a Class and an Interface?

In .Net/ C# a class can be defined to implement an interface and also it supports multiple implementations. When a class implements an interface, an object of such class can be encapsulated inside an interface.

If MyLogger is a class, which implements ILogger, there we can write

Collapse | Copy Code
ILogger log = new MyLogger();

A class and an interface are two different types (conceptually). Theoretically a class emphasis the idea of encapsulation, while an interface emphasis the idea of abstraction (by suppressing the details of the implementation). The two poses a clear separation from one to another. Therefore it is very difficult or rather impossible to have an effective meaningful comparison between the two, but it is very useful and also meaningful to have a comparison between an interface and an abstract class.

4.14. What is the difference between an Interface and an Abstract class?

There are quite a big difference between an interface and an abstract class, even though both look similar.

    • Interface definition begins with a keyword interface so it is of type interface
    • Abstract classes are declared with the abstract keyword so it is of type class
    • Interface has no implementation, but they have to be implemented.
    • Abstract class‚Äôs methods can have implementations and they have to be extended.
    • Interfaces can only have method declaration (implicitly public and abstract) and fields (implicitly public static)
    • Abstract class‚Äôs methods can‚Äôt have implementation only when declared abstract.
    • Interface can inherit more than one interfaces
    • Abstract class can implement more than one interfaces, but can inherit only one class
    • Abstract class must override all abstract method and may override virtual methods
    • Interface can be used when the implementation is changing
    • Abstract class can be used to provide some default behavior for a base class.
    • Interface makes implementation interchangeable
    • Interface increase security by hiding the implementation
    • Abstract class can be used when implementing framework
    • Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies.

Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class can be used to provide the default implementation of the services and all mandatory modules such as event logging and message handling etc. This approach allows the developers to develop the application within the guided help provided by the framework.

However, in practice when you come across with some application-specific functionality that only your application can perform, such as startup and shutdown tasks etc. The abstract base class can declare virtual shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn’t know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, it can execute the method defined by the child class.

4.15. What is Implicit and Explicit Interface Implementations?

As mentioned before .Net support multiple implementations, the concept of implicit and explicit implementation provide safe way to implement methods of multiple interfaces by hiding, exposing or preserving identities of each of interface methods, even when the method signatures are the same.

Let’s consider the interfaces defined below.

Collapse | Copy Code
interface IDisposable
{
    void Dispose();
}

Here you can see that the class Student has implicitly and explicitly implemented the method named Dispose() via Dispose and IDisposable.Dispose.

Collapse | Copy Code
class Student : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("Student.Dispose");
    }

    void IDisposable.Dispose()
    {
        Console.WriteLine("IDisposable.Dispose");
    }
}

4.16. What is Inheritance?

Ability of a new class to be created, from an existing class by extending it, is called inheritance.

Inheritance.gif

Collapse | Copy Code
public class Exception
{
}

public class IOException : Exception
{
}

According to the above example the new class (IOException), which is called the derived class or subclass, inherits the members of an existing class (Exception), which is called the base class or super-class. The class IOException can extend the functionality of the class Exception by adding new types and methods and by overriding existing ones.

Just like abstraction is closely related with generalization, the inheritance is closely related with specialization. It is important to discuss those two concepts together with generalization to better understand and to reduce the complexity.

One of the most important relationships among objects in the real world is specialization, which can be described as the ‚Äúis-a‚ÄĚ relationship. When we say that a dog is a mammal, we mean that the dog is a specialized kind of mammal. It has all the characteristics of any mammal (it bears live young, nurses with milk, has hair), but it specializes these characteristics to the familiar characteristics of canis domesticus. A cat is also a mammal. As such, we expect it to share certain characteristics with the dog that are generalized in Mammal, but to differ in those characteristics that are specialized in cats.

The specialization and generalization relationships are both reciprocal and hierarchical. Specialization is just the other side of the generalization coin: Mammal generalizes what is common between dogs and cats, and dogs and cats specialize mammals to their own specific subtypes.

Similarly, as an example you can say that both IOException and SecurityException are of type Exception. They have all characteristics and behaviors of an Exception, That mean the IOException is a specialized kind of Exception. A SecurityException is also an Exception. As such, we expect it to share certain characteristic with IOException that are generalized in Exception, but to differ in those characteristics that are specialized in SecurityExceptions. In other words, Exception generalizes the shared characteristics of both IOException and SecurityException, while IOException and SecurityException specialize with their characteristics and behaviors.

In OOP, the specialization relationship is implemented using the principle called inheritance. This is the most common and most natural and widely accepted way of implement this relationship.

4.17. What is Polymorphisms?

Polymorphisms is a generic term that means ‘many shapes’. More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.

At times, I used to think that understanding Object Oriented Programming concepts have made it difficult since they have grouped under four main concepts, while each concept is closely related with one another. Hence one has to be extremely careful to correctly understand each concept separately, while understanding the way each related with other concepts.

In OOP the polymorphisms is achieved by using many different techniques named method overloading, operator overloading and method overriding,

4.18. What is Method Overloading?

The method overloading is the ability to define several methods all with the same name.

Collapse | Copy Code
public class MyLogger
{
    public void LogError(Exception e)
    {
        // Implementation goes here
    }

    public bool LogError(Exception e, string message)
    {
        // Implementation goes here
    }
}

4.19. What is Operator Overloading?

The operator overloading (less commonly known as ad-hoc polymorphisms) is a specific case of polymorphisms in which some or all of operators like +, – or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments.

Collapse | Copy Code
public class Complex
{
    private int real;
    public int Real
    { get { return real; } }

    private int imaginary;
    public int Imaginary
    { get { return imaginary; } }

    public Complex(int real, int imaginary)
    {
        this.real = real;
        this.imaginary = imaginary;
    }

    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
    }
}

I above example I have overloaded the plus operator for adding two complex numbers. There the two properties named Real and Imaginary has been declared exposing only the required ‚Äúget‚ÄĚ method, while the object‚Äôs constructor is demanding for mandatory real and imaginary values with the user defined constructor of the class.

4.20. What is Method Overriding?

Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.

A subclass can give its own definition of methods but need to have the same signature as the method in its super-class. This means that when overriding a method the subclass’s method has to have the same name and parameter list as the super-class’s overridden method.

Collapse | Copy Code
using System;
public class Complex
{
    private int real;
    public int Real
    { get { return real; } }

    private int imaginary;
    public int Imaginary
    { get { return imaginary; } }

    public Complex(int real, int imaginary)
    {
        this.real = real;
        this.imaginary = imaginary;
    }

    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
    }

    public override string ToString()
    {
        return (String.Format("{0} + {1}i", real, imaginary));
    }
}

In above example I have extended the implementation of the sample Complex class given under operator overloading section. This class has one overridden method named ‚ÄúToString‚ÄĚ, which override the default implementation of the standard ‚ÄúToString‚ÄĚ method to support the correct string conversion of a complex number.

Collapse | Copy Code
Complex num1 = new Complex(5, 7);
Complex num2 = new Complex(3, 8);

// Add two Complex numbers using the
// overloaded plus operator
Complex sum = num1 + num2;

// Print the numbers and the sum
// using the overriden ToString method
Console.WriteLine("({0}) + ({1}) = {2}", num1, num2, sum);
Console.ReadLine();

4.21. What is a Use case?

A use case is a thing an actor perceives from the system. A use case maps actors with functions. Importantly, the actors need not be people. As an example a system can perform the role of an actor, when it communicate with another system.

usercase1.gif

In another angle a use case encodes a typical user interaction with the system. In particular, it:

  • Captures some user-visible function.
  • Achieves some concrete goal for the user.

A complete set of use cases largely defines the requirements for your system: everything the user can see, and would like to do. The below diagram contains a set of use cases that describes a simple login module of a gaming website.

usecaseLogin.gif

4.22. What is a Class Diagram?

A class diagrams are widely used to describe the types of objects in a system and their relationships. Class diagrams model class structure and contents using design elements such as classes, packages and objects. Class diagrams describe three different perspectives when designing a system, conceptual, specification, and implementation. These perspectives become evident as the diagram is created and help solidify the design.

The Class diagrams, physical data models, along with the system overview diagram are in my opinion the most important diagrams that suite the current day rapid application development requirements.

UML Notations:

notation.jpg

4.23. What is a Package Diagram?

Package diagrams are used to reflect the organization of packages and their elements. When used to represent class elements, package diagrams provide a visualization of the name-spaces. In my designs, I use the package diagrams to organize classes in to different modules of the system.

4.24. What is a Sequence Diagram?

A sequence diagrams model the flow of logic within a system in a visual manner, it enable both to document and validate your logic, and are used for both analysis and design purposes. Sequence diagrams are the most popular UML artifact for dynamic modeling, which focuses on identifying the behavior within your system.

4.25. What is two-tier architecture?

The two-tier architecture is refers to client/ server architectures as well, the term client/ server was first used in the 1980s in reference to personal computers (PCs) on a network. The actual client/ server model started gaining acceptance in the late 1980s, and later it was adapted to World Wide Web programming.

According to the modern days use of two-tier architecture the user interfaces (or with ASP.NET, all web pages) runs on the client and the database is stored on the server. The actual application logic can run on either the client or the server. So in this case the user interfaces are directly access the database. Those can also be non-interface processing engines, which provide solutions to other remote/ local systems. In either case, today the two-tier model is not as reputed as the three-tier model. The advantage of the two-tier design is its simplicity, but the simplicity comes with the cost of scalability. The newer three-tier architecture, which is more famous, introduces a middle tier for the application logic.

2-Tier.jpg

4.26. What is three-tier architecture?

The three tier software architecture (also known as three layer architectures) emerged in the 1990s to overcome the limitations of the two tier architecture. This architecture has aggressively customized and adopted by modern day system designer to web systems.

Three-tier is a client-server architecture in which the user interface, functional process logic, data storage and data access are developed and maintained as independent modules, some time on separate platforms. The term “three-tier” or “three-layer“, as well as the concept of multi-tier architectures (often refers to as three-tier architecture), seems to have originated within Rational Software.

3-Tier.jpg

The 3-Tier architecture has the following three tiers.

  1. Presentation Tier or Web Server: User Interface, displaying/ accepting data/ input to/ from the user
  2. Application Logic/ Business Logic/ Transaction Tier or Application Server: Data validation, acceptability check before being added to the database and all other business/ application specific operations
  3. Data Tier or Database server: Simple reading and writing method to database or any other storage, connection, command, stored procedures etc

4.27. What is MVC architecture?

The Model-View-Controller (MVC) architecture separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes.

Unfortunately, the popularity of this pattern has resulted in a number of faulty usages; each technology (Java, ASP.NET etc) has defined it in their own way making it difficult to understand. In particular, the term “controller” has been used to mean different things in different contexts. The definitions given bellow are the closes possible ones I found for ASP.NET version of MVC.

mvc.jpg

  1. Model: DataSet and typed DataSet (some times business object, object collection, XML etc) are the most common use of the model.
  2. View: The ASPX and ASCX files generally handle the responsibilities of the view.
  3. Controllers: The handling of events or the controlling is usually done in the code-behind class.

In a complex n-tier distributed system the MVC architecture place the vital role of organizing the presentation tier of the system.

4.28. What is SOA?

A service-oriented architecture is essentially a collection of services. These services communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating some activity. Some means of connecting services to each other is needed.

The .Net technology introduces the SOA by mean of web services.

SOA.gif

The SOA can be used as the concept to connect multiple systems to provide services. It has it’s great share in the future of the IT world.

According to the imaginary diagram above, we can see how the Service Oriented Architecture is being used to provide a set of centralized services to the citizens of a country. The citizens are given a unique identifying card, where that card carries all personal information of each citizen. Each service centers such as shopping complex, hospital, station, and factory are equipped with a computer system where that system is connected to a central server, which is responsible of providing service to a city. As an example when a customer enter the shopping complex the regional computer system report it to the central server and obtain information about the customer before providing access to the premises. The system welcomes the customer. The customer finished the shopping and then by the time he leaves the shopping complex, he will be asked to go through a billing process, where the regional computer system will manage the process. The payment will be automatically handled with the input details obtain from the customer identifying card.

The regional system will report to the city (computer system of the city) while the city will report to the country (computer system of the country).

4.29. What is the Data Access Layer?

The data access layer (DAL), which is a key part of every n-tier system, is mainly consist of a simple set of code that does basic interactions with the database or any other storage device. These functionalities are often referred to as CRUD (Create, Retrieve, Update, and Delete).

The data access layer need to be generic, simple, quick and efficient as much as possible. It should not include complex application/ business logics.

I have seen systems with lengthy, complex store procedures (SP), which run through several cases before doing a simple retrieval. They contain not only most part of the business logic, but application logic and user interface logic as well. If SP is getting longer and complicated, then it is a good indication that you are burring your business logic inside the data access layer.

4.30. What is the Business Logic Layer?

I know for a fact that this is a question for most, but from the other hand by reading many articles I have become aware that not everyone agrees to what business logic actually is, and in many cases it’s just the bridge in between the presentation layer and the data access layer with having nothing much, except taking from one and passing to the other. In some other cases, it is not even been well thought out, they just take the leftovers from the presentation layer and the data access layer then put them in another layer which automatically is called the business logic layer. However there are no god said things that cannot be changed in software world. You can change as and when you feel comfortable that the method you apply is flexible enough to support the growth of your system. There are many great ways, but be careful when selecting them, they can over complicating the simple system. It is a balance one needs to find with their experience.

As a general advice when you define business entities, you must decide how to map the data in your tables to correctly defined business entities. The business entities should meaningfully define considering various types of requirements and functioning of your system. It is recommended to identify the business entities to encapsulate the functional/ UI (User Interface) requirements of your application, rather than define a separate business entity for each table of your database. For example, if you want to combine data from couple of table to build a UI (User Interface) control (Web Control), implement that function in the Business Logic Layer with a business object that uses couple of data object to support with your complex business requirement.

4.31. What is Gang of Four (GoF) Design Patterns?

The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. Here you will find information on these important patterns.

Creational Patterns

      • Abstract Factory Creates an instance of several families of classes
      • Builder Separates object construction from its representation
      • Factory Method Creates an instance of several derived classes
      • Prototype A fully initialized instance to be copied or cloned
      • Singleton A class of which only a single instance can exist

Structural Patterns

      • Adapter Match interfaces of different classes
      • Bridge Separates an object‚Äôs interface from its implementation
      • Composite A tree structure of simple and composite objects
      • Decorator Add responsibilities to objects dynamically
      • Facade A single class that represents an entire subsystem
      • Flyweight A fine-grained instance used for efficient sharing
      • Proxy An object representing another object

Behavioral Patterns

    • Chain of Resp. A way of passing a request between a chain of objects
    • Command Encapsulate a command request as an object
    • Interpreter A way to include language elements in a program
    • Iterator Sequentially access the elements of a collection
    • Mediator Defines simplified communication between classes
    • Memento Capture and restore an object’s internal state
    • Observer A way of notifying change to a number of classes
    • State Alter an object’s behavior when its state changes
    • Strategy Encapsulates an algorithm inside a class
    • Template Method Defer the exact steps of an algorithm to a subclass
    • Visitor Defines a new operation to a class without change

4.32. What is the difference between Abstract Factory and Builder design patterns?

The two design patterns are fundamentally different. However, when you learn them for the first time, you will see a confusing similarity. So that it will make harder for you to understand them. But if you continue to study eventually, you will get afraid of design patterns too. It is like infant phobia, once you get afraid at your early age, it stays with you forever. So the result would be that you never look back at design patterns again. Let me see whether I can solve this brain teaser for you.

In the image below, you have both design pattern listed in. I am trying to compare the two one on one to identify the similarities. If you observe the figure carefully, you will see an easily understandable color pattern (same color is used to mark the classes that are of similar kind).

Factory and Builder

Please follow up with the numbers in the image when reading the listing below.

Mark #1: Both patterns have used a generic class as the entry-class. The only difference is the name of the class. One pattern has named it as ‚ÄúClient‚ÄĚ, while the other named it as ‚ÄúDirector‚ÄĚ.
Mark #2: Here again the difference is the class name. It is ‚ÄúAbstractFactory‚ÄĚ for one and ‚ÄúBuilder‚ÄĚ for the other. Additionally both classes are of type abstract.
Mark #3: Once again both patterns have defined two generic (WindowsFactory & ConcreteBuilder) classes. They both have created by inheriting their respective abstract class.
Mark #4: Finally, both seem to produce some kind of a generic output.

Now, where are we? Aren’t they looking almost identical? So then why are we having two different patterns here?

Let’s compare the two again side by side for one last time, but this time, focusing on the differences.

  • Abstract Factory: Emphasizes a family of product objects (either simple or complex)
  • Builder: Focuses on constructing a complex object step by step
  • Abstract Factory: Focus on *what* is made
  • Builder: Focus on *how* it is made
  • Abstract Factory: Focus on defining many different types of *factories* to build many *products*, and it is not a one builder for just one product
  • Builder: Focus on building a one complex but one single *product*
  • Abstract Factory: Defers the choice of what concrete type of object to make until run time
  • Builder: Hide the logic/ operation of how to compile that complex object
  • Abstract Factory: *Every* method call creates and returns different objects
  • Builder: Only the *last* method call returns the object, while other calls partially build the object

Sometimes creational patterns are complementary: So you can join one or many patterns when you design your system. As an example builder can use one of the other patterns to implement which components get built or in another case Abstract Factory, Builder, and Prototype can use Singleton in their implementations. So the conclusion would be that the two design patterns exist to resolve two type of business problems, so even though they look similar, they are not.

I hope that this shed some light to resolve the puzzle. If you still don’t understand it, then this time it is not you, it has to be me and it is since that I don’t know how to explain it.

5. What is the Conclusion?

I don’t think, that it is realistic trying to make a programming language be everything to everybody. The language becomes bloated, hard to learn, and hard to read if everything plus the kitchen sink is thrown in. In another word every language has their limitations. As system architect and designer we should be able to fully and more importantly correctly (this also mean that you shouldn‚Äôt use a ballistic missile to kill a fly or hire FBI to catch the fly) utilize the available tools and features to build usable, sustainable, maintainable and also very importantly expandable software systems, that fully utilize the feature of the language to bring a competitively advance system to their customers. In order to do it, the foundation of a system places a vital role. The design or the architecture of a software system is the foundation. It hold the system together, hence designing a system properly (this never mean an *over* desinging) is the key to the success. When you talk about designing a software system, the correct handling of OOP concept is very important. I have made the above article richer with idea but still kept it short so that one can learn/ remind all of important concept at a glance. Hope you all will enjoy reading it.

Finally, after reading all these, one may argue with me saying that anybody can write all these concept definitions but do I know how/ when to apply them in real world systems. So for them to see these concepts being applied in real world systems, please check the source code of the latest of my open-source project name Rocket Framework.

Note: For newbies¬†Rocket Framework¬†is going to be little too advance but check it, use it and review it if you have any questions/ criticisms around my design¬†don’t hesitate to shoot them here or there..

6. What I Referred?

3 tips if you want to use crystal report. Net 2010:


1. Crystal Reports .NET is no longer included with Visual Studio .NET 2010. it is a separate download. Use this link to download it to your application and install it after you have installed Visual Studio .NET 2010.

http://downloads.businessobjects.com/akdlm/cr4vs2010/CRforVS_13_0_1.exe

2. You will find that the Crystal Reports viewer is strangely missing from the Visual Studio toolbox. To fix this go to Project > Properties > Compile > Advanced Compiler Settings > Target framework(all configurations) > .NET

Framework 4. Set the Target Framework to be .NET Framework 4. After doing so, you application will close and re-open and the viewer will now be in the toolbox.

3. The Crystal Reports DLLs were written with .NET Framework 2 and they are compatible with Framework 4 as wel. But your application needs to have mixed-mode compatibility turned on for it to use the Crystal assemblies. To fix

this go to Solution Explorer > app.config.  You should add this property to the Startup tag in the app.config file.

useLegacyV2RuntimeActivationPolicy=”true”

Detail as follows:
….

<startup useLegacyV2RuntimeActivationPolicy=”true”><supportedRuntime version=”v4.0″ sku=”.NETFramework,Version=v4.0″/></startup></configuration>

ASP.NET interview questions and answers


  1. Describe the difference between a Thread and a Process?
  2. What is a Windows Service and how does its lifecycle differ from a √ɬĘ√Ę‚Äö¬¨√Ö‚Äústandard√ɬĘ√Ę‚Äö¬¨√ā¬Ě EXE?
  3. What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?
  4. What is the difference between an EXE and a DLL?
  5. What is strong-typing versus weak-typing? Which is preferred? Why?
  6.  

  7. What√ɬĘ√Ę‚Äö¬¨√Ę‚Äě¬Ęs wrong with a line like this? DateTime.Parse(myString
  8. What are PDBs? Where must they be located for debugging to work?
  9. What is cyclomatic complexity and why is it important?
  10. Write a standard lock() plus double check to create a critical section around a variable access.
  11. What is FullTrust? Do GAC’ed assemblies have FullTrust?
  12. What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?
  13. What does this do? gacutil /l | find /i ‚Äúabout‚ÄĚ
  14. What does this do? sn -t foo.dll
  15. What ports must be open for DCOM over a firewall? What is the purpose of Port 135?
  16. Contrast OOP and SOA. What are tenets of each
  17. How does the XmlSerializer work? What ACL permissions does a process using it require?
  18. Why is catch(Exception) almost always a bad idea?
  19. What is the difference between Debug.Write and Trace.Write? When should each be used?
  20. What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?
  21. Does JITting occur per-assembly or per-method? How does this affect the working set?
  22. Contrast the use of an abstract base class against an interface?
  23. What is the difference between a.Equals(b) and a == b?
  24. In the context of a comparison, what is object identity versus object equivalence?
  25. How would one do a deep copy in .NET?
  26. Explain current thinking around IClonable.
  27. What is boxing?
  28. Is string a value type or a reference type?

 

How To Play Flash Video Files In ASP.NET using C#.net or VB.net


Videos are becoming common part of web sites today. Before just a few years, web designers avoided even larger picture on site, because Internet connection of many visitors was slow, and movies usually have much more bytes than pictures. Visitors did not like to wait more than a few seconds to see page loaded. Rare videos was very short, had low resolution and bad quality. But now, circumstances are changed. Now almost everyone have fast connection and time of dial-up connection is past. Now you can display video whenever you want to better describe your product or service.

 

There is a few different ways to show video on web page. Most popular are Windows Media Player, Quick Time, Adobe Flash or Silverlight. If you want to find out how to show video with Windows Media Player you can read How to build ASP.NET Media Player Control tutorial. This tutorial will focus on using of Flash to show flash video files on ASP.NET web site.

Flash becomes widely used and today it is most used technology for showing movies on Internet. Flash is used by most popular video sharing web sites like YouTube or Google Video. It is compatible with almost every operating system and web browser and very prevalent on Internet users computers. To see Flash movies, users need to have Flash player installed. On my experiences, at least 95% visitors have Flash player installed which is more than other available technologies. Flash is client side technology, although it can be used with static HTML page, but it is usually manipulated by server side web application.

You can’t show flash video files directly. Flash is just a programming framework, which uses Action Script programming language. You need a program made in Flash (video player) to show .flv video on page. You can of course learn Action Script and develop your own player, but that is out of scope of this tutorial. I will leave that task to Flash developers. Fortunately, there are already some free and very good Flash video players available. Using of them will short your development cycle and provide you a quality solution. I selected¬†JW FLV Player as the best solution.

Using of JW FLV Player on web page

There are a two basic steps when placing Flash application to web page:

– First, declare and initiate a Flash object

– Second, set properties of object according to your needs.

You can do this on two different ways, with static HTML tags <OBJECT > and , or by using a JavaScript. With static HTML your code could look something like this:

<object¬†width=”640″¬†height=”480″>
<param¬†name=”movie”¬†value=”player.swf”¬†/>

</object>

 

We need both <object > and tags to get browser compatibility. Internet Explorer uses <object> tag, but Firefox and Netscape can’t see it and recognize just . We set parameters by using <param > tags, and inside tag. Code example above have added parameter name “movie” and value “player.swf”. You can add any other parameter on the same way. Complete list of supported parameters for JW FLV Player you can see at their¬†Flash vars page.

http://cdn5.tribalfusion.com/media/2481846/template_300x250_v8.swf

There is a problem with static HTML if visitors access with Internet Explorer. Flash application would not start until visitor clicks on it. If you just place a cursor over a movie you’ll see an ugly border. Common way to avoid need to click every time when page load is to initiate Flash player with JavaScript. JavaScript code for starting Flash movie could look like this:

<p¬†id=’preview’>The player will show in this paragraph</p>

<script¬†type=’text/javascript’¬†src=’swfobject.js’></script>
<script¬†type=’text/javascript’>
var¬†s1 =¬†new¬†SWFObject(‘player.swf’,’player’,’400′,’300′,’9′);
s1.addParam(‘allowfullscreen’,’true’);
s1.addParam(‘allowscriptaccess’,’always’);
s1.addParam(‘flashvars’,’file=video.flv’);
s1.write(‘preview’);
</script>

 

As you can see, nothing complicated here. Code creates SWFObject dynamically and then set its parameters. In this case visitor is not required to click to start a movie. Of course, JavaScript must be enabled in visitor’s web browser.

Manipulating Flash Player with ASP.NET

Basically, playing video files with JW FLV Player is simple, you just create an object and set needed parameters as in two code examples above. But, if you work with large number of video files or you need to enable to your users to add their movies you need to automate things. Writing static HTML code for every video certainly not sounds professional. Fortunately, with a little ASP.NET code we can make this task much easier :).

Creating a custom ASP.NET Flash Player Control

Basic idea is this: Custom ASP.NET control will have properties related to JW FLV Player parameters. In run time, control will render appropriate content on client side so JW FLV player will show video correctly, and you can manipulate flash videos with ASP.NET web application. Now, we can create admin ASP.NET pages, load videos from database, enable database search etc., without hard coding.

I created ASP.NET JW FLV Flash Video Player Control that do this task. Control is free and you can use it to show Flash video files on your web site. Source code of control is also available in C# andVB.NET. Example web project is included in download to see how it works.


Image 1: ASP.NET Flash player control at run time

You can download this control compiled for ASP.NET 1.1, ASP.NET 2.0 and ASP.NET 3.5. Every download contains example web application with sample video files, so you can immediately see how it works.

Flash Player Control Code Analysis

As you can see from C# and VB.NET code listings, control code consists from three parts:

1. Declaring of properties default values on the beginning. For server control, I used same default values like JW FLV Flash player already uses. I added two additional properties to describe location of JW FLV .swf and .js file, like in code bellow.

[ C# ]

#region Properties defaults
const¬†string¬†DefaultSwfobject_jsLocation = “”;¬†// in the same directory
const¬†string¬†DefaultFlashPlayerLocation = “”;¬†// in the same directory
const bool DefaultAllowFullScreen = true;
const¬†string¬†DefaultFile = “”;
const bool DefaultAutoStart = false;
const int DefaultBufferLength = 1;

#endregion

[ VB.NET ]

#Region¬†“Properties defaults”
Const¬†DefaultSwfobject_jsLocation¬†As¬†String¬†= “”¬†‘ in the same directory
Const¬†DefaultFlashPlayerLocation¬†As¬†String¬†= “”¬†‘ in the same directory
Const DefaultAllowFullScreen As Boolean = True
Const¬†DefaultFile¬†As¬†String¬†= “”
Const DefaultAutoStart As Boolean = False
Const DefaultBufferLength As Integer = 1

#End Region

 

2. Value of every property is saved to ViewState if value is different from default value. For example, code for AllowFullScreen property looks like this:

[ C# ]

[Bindable(true), Category(“Settings”)]
bool AllowFullScreen
{
get
{
if(ViewState[“AllowFullScreen”] ==¬†null)
return DefaultAllowFullScreen;
else
return¬†(bool)ViewState[“AllowFullScreen”];
}
set
{
if(value != DefaultAllowFullScreen)
ViewState[“AllowFullScreen”] =¬†value;
else
ViewState[“AllowFullScreen”] =¬†null;
}
}

[ VB.NET ]

<Bindable(True), Category(“Settings”)> _
Property AllowFullScreen() As Boolean
Get
If¬†ViewState(“AllowFullScreen”)¬†Is¬†Nothing¬†Then
Return DefaultAllowFullScreen
Else
Return¬†ViewState(“AllowFullScreen”)
End If
End Get
Set(ByVal value As Boolean)
If value <> DefaultAllowFullScreen Then
ViewState(“AllowFullScreen”) = value
Else
ViewState(“AllowFullScreen”) =¬†Nothing
End If
End Set
End Property

 

3. RenderContents function produces output to, depended of values of every property, correctly initialize Flash player on client side by using a JavaScript, like mentioned before.

Conclusion

With custom ASP.NET Flash Player control that manipulate client side flash player you can save a lot of time. I tested control in Firefox and Internet Explorer and worked fine. Please let me know if you find some bug or you have a suggestion for improvement.

Going professional with ASPNetFlashVideo

Control introduced in this tutorial is useful in some simpler scenarios, but keep in mind that JW FLV Player is free only for noncommercial projects. Fortunately, there is pure ASP.NET control namedASPNetFlashVideo that allows you to effortlessly incorporate beautiful Adobe Flash Video (FLV) media into ASP.NET website. For $49 you can use it on single site or just $99 for use on unlimited number of web sites. Except common interface commands for playing flash video files, ASPNetFlashVideosupports skins, custom user interface, play lists, integration with Visual Studio, search engine optimization and more. Things like no ongoing subscription costs, free future updates or 30 days money back guarantee justify decision to give it a try.

 

Simple Gallery ‚Äď An Easy Image Gallery for ASP.NET


This article addresses the construction of a simple image gallery type of web application. This is not the be all, end all solution for web image galleries, but if you want to share a few photos or put together a site to display a small catalog of images, it is a very simple way to get there. In fact, it is so simple; the whole shooting match is entirely managed within the page load event of a single web form.

Figure 1: Image Gallery Web Application in Use

Getting Started

Unzip the solution included with this download, and store it in your file system. After saving the solution, create a virtual directory pointing to that solution using the IIS management console. Next, open the solution up in Visual Studio 2005. In the Solution Explorer, you will note the following:

Figure 2: Solution Explorer showing the Image Gallery Project

As you can see, there is not a whole lot to it. There is a single web form called Default.aspx and an added folder (Images) which contains a set of seven JPG image files. All of the action associated with this project occurs in the single code-behind file associated with the Default.aspx page.

Incidentally, all of the photographs are of the USS Isherwood (DD-520) which was the ship my father served on during World War II. The photograph entitled ÔŅĹDD520_1.jpgÔŅĹ was taken on April 16, 1945 during the Okinawa invasion; six days later, the Isherwood was attacked by a Kamikaze in a raid that killed or wounded 80 of the sailors onboard (including my father).

Default.aspx Form Layout

The form layout for this example is pretty simple, the web form uses absolute positioning and it contains two objects. One is a¬†Panel control (pnlThumbs) that is set to scroll vertically and which has a fixed width and height (500 x 170px). The other control is an¬†Image control (imgMain) with its height and width properties left unset. With the imageÔŅĹs height and width properties unset, whenever a new image is loaded into the control, the width and height will be set to display the image without any distortion.

The Code: Default.aspx

As advertised, there is only one bit of code to look at in this project, and that is the page load event handler. There are a few imports made at the start of the class, those imports include:

Collapse
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Bitmap
Imports System.Drawing.Drawing2D

These imports are necessary, and are used to work with the image files. Now, take a look at the page load event handler; that bit of code is as follows:

Collapse
Protected Sub Page_Load(ByVal sender As Object, _
          ByVal e As System.EventArgs) Handles Me.Load

    Me.Title = "USS Isherwood DD-520"

    'retrieve selected files of a folder

    Dim files() As String
    Dim i As Integer
    files = Directory.GetFiles(Server.MapPath("~\Images"), "*.jpg")

    If Page.IsPostBack Then
        Me.imgMain.ImageUrl = Request.QueryString("Img")
    End If

    Dim arrIbs(files.Length) As ImageButton
    For i = 0 To files.Length - 1
        Dim image As New Bitmap(files(i).ToString)
        arrIbs(i) = New ImageButton()
        arrIbs(i).ImageUrl = files(i).ToString()
        arrIbs(i).Width = 160
        arrIbs(i).Height = 100
        arrIbs(i).BorderStyle = BorderStyle.Inset
        arrIbs(i).BorderWidth = 2
        arrIbs(i).AlternateText = _
            System.IO.Path.GetFileName(files(i).ToString())
        arrIbs(i).PostBackUrl = "default.aspx?Img=" & _
                                files(i).ToString()
        Me.pnlThumbs.Controls.Add(arrIbs(i))
        Dim lbl As New Label
        lbl.Text = "<br/>"
        pnlThumbs.Controls.Add(lbl)
    Next

End Sub

The first line of the handler merely sets the title of the page.

Collapse
Me.Title = "USS Isherwood DD-520"

Following that, the next bit of code declares a String array (files) used to contain the paths to the image files contained in the Images folder. The files collected are limited to JPG files; naturally, this could include other file types.

Collapse
'retrieve selected files of a folder

Dim files() As String
Dim i As Integer
files = Directory.GetFiles(Server.MapPath("~\Images"), "*.jpg")

After the files are identified, the event handler will check for a post back and, if the page is a post back, use the query string value entitled ÔŅĹImgÔŅĹ to get the path to the last selected file and set the formÔŅĹs main image to display that image by setting the¬†ImageUrl property of the control to point to the path of the last selected image file.

Collapse
If Page.IsPostBack Then
    Me.imgMain.ImageUrl = Request.QueryString("Img")
End If

The event handler will wrap up by creating the image gallery:

Collapse
Dim arrIbs(files.Length) As ImageButton
For i = 0 To files.Length - 1
    arrIbs(i) = New ImageButton()
    arrIbs(i).ImageUrl = files(i).ToString()
    arrIbs(i).Width = 160
    arrIbs(i).Height = 100
    arrIbs(i).BorderStyle = BorderStyle.Inset
    arrIbs(i).BorderWidth = 2
    arrIbs(i).AlternateText = System.IO.Path.GetFileName(files(i).ToString())
    arrIbs(i).PostBackUrl = "default.aspx?Img=" & files(i).ToString()
    Me.pnlThumbs.Controls.Add(arrIbs(i))
    Dim lbl As New Label
    lbl.Text = "<br/>"
    pnlThumbs.Controls.Add(lbl)
Next

To create the gallery, the handler creates an array of ImageButton controls, with the size of the array set to equal the number of files in the filesarray. Next, the code will loop through the array of files and declare and capture an image from the current file, and in each pass, instance the image control from the array of image buttons, and set the ImageUrl property to point to the current image file. The height and width of the image control are set to make all of the images the same size (and depending upon the images you are dealing with, you may want to set the height and width to some other values). In this instance, I merely set the size of the image to be on half of the size of a 320 x 200 pixel image.

After the image URL is set, the image is given an inset border with a width of 2px. The AlternateText property of the current image button is set to display the name of the file without the full path information included. Next, the PostBackUrl property is set to recall the current page and pass the query string containing the path to the last selected image file. This control is then added to the control collection of the panel.

The Label control is added as a spacer between the small version of the image, and it is added as well to the Panel after it has been declared and populated.

That is all there is to it; when the page is displayed, whenever the user selects an image button from the gallery, the page does a post back and the query string value is used to load the selected image into the main image.

 

Building A Web Service In ASP.NET 3.5


The steps to build a web service in ASP.NET 3.5 haven’t changed much from previous versions but there are few new things to keep in mind. The biggest new feature in ASP.NET 3.5 are the “AJAX-enabled” web services. You can now set up your web service to return in either the standard SOAP/XML format or “AJAX-enable” your service with a single setting that will allow you to call your Web Service methods directly in javascript in your ASPX pages.

Building a Simple Web Service

To create a web service, first add a new .ASMX file to your web project by right-clicking your web project and selectingAdd New Item.

Choose¬†Web Service from the horribly unsorted list (Why can’t we get this alphabetized!!!). Then choose a name for your service. I recommend selecting “Place code in separate file”. This setting will create a “ExampleWebService.asmx” file at the project root or where ever you are currently adding this service and will put the actualy C# code for the services in your App_Code directory as a file called “ExampleWebService.asmx.cs”. Then click Add.

visual studio add new item - web service

Your new service should look something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for ExampleWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 

// [System.Web.Script.Services.ScriptService]
public class ExampleWebService : System.Web.Services.WebService
{
    public ExampleWebService()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
}

Setting up the Web Service code

The first thing you need to do is change your URI namespace. By default, it is set to¬†http://tempuri.org/. But you want this to a completely unique URI string to you and/or your organization. It does not have to be a valid URL to an actual page (although that’s a good idea if you want to publish a user guide or usage policy there). I normally just use the URL to where this web service will reside in production. For instance, I might put:http://www.devtoolshed.com/webservices/examplewebservice/. NOTE: It’s always good to add the final “/” to end of your URL if it is to a directory path to make it a well-formed URL.

The next thing to notice here is the section just below that says “To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.” If you uncomment this line, it will “AJAX-enable” your service so that you can call it using the ASP.NET AJAX framework and javascript. Very useful. But if you aren’t using this feature, just leave it commented out.

It’s kind of lame but Microsoft puts a sample “HelloWorld” web method already in there so you can see the format (I guess it’s tradition because this has been in there since ASP.NET 1.0). For a simple service that just returns a base data type such as int or string, this HelloWorld method is a good example.

Notice in the HelloWorld method, the way that you enable this method to be called remotely is by using the “[WebMethod]” attribute above the method signature. When WebMethod is placed above a public function in this web service class, ASP.NET does ALL the work for you. This really is the best part. It will automatically add your method to the WSDL definition of the service. It will wrap your return values as well as parameters in SOAP for you. You literally just code this like a normal method and all the SOAP and security layer work is done automatically for you.

NOTE: You can add as many [WebMethod]’s as you like to your web service class and they will all be available as remotely executable functions for your clients invokers.

[WebMethod] Description parameter

There is an extra parameter that is available for the [WebMethod] attribute that I like to add called Description. This allows you to describe the web method. Just for fun, I’ve added a parameter to the HelloWorld service as well to pass a message to the string.

Here’s an example using the Description parameter for the HelloWorld method:

[WebMethod(Description = "Says hello to the world!")]
public string HelloWorld(string sMessage)
{
    return "Hello World" + sMessage;
}

Running the Web Service

Now you can run this web service by right-clicking the ExampleWebService.asmx file and choosing “Set as start page” and hitting F5. ASP.NET automatically generates a run-time wrapper for your services so you can test, step into code, and make sure you have them all coded correctly before going live. You should see a page something like this:

web service list of operations

If you click on the HelloWorld method link, you can actually run the service. ASP.NET will even create a simple web form that you can enter the parameter values for your method to invoke it. Type a message and then click “Invoke”.

invoke a web service method

You should have an XML return value that looks something like this:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.devtoolshed.com/webservices/examplewebservice/">Hello World you look wonderful!</string>

NOTE: The SOAP wrapper is not shown here to keep things simple when developing but it will be added automatically when this service is invoked via a SOAP enabled client.

Web Services that return Complex Types

For simple web services (not very common), this works great. But what if you want to actually pass a complex type such as an object your created as the return value or even accept one as a parameter to your method? Luckily, this is also supported out of the box.

Here are a few things to keep in mind when doing this:

  • If you pass a complex type as a parameter, then ASP.NET will not be able to generate the run-time web page wrapper we just used. It won’t know how to translate your custom object to a base data type. So to test your methods, you will need to use a simple client application to call your web services so you can step into code, etc.
  • I¬†HIGHLY RECOMMEND that when you return complex types as return values, you do NOT use your direct data access layer objects. There are a couple of reasons for this. 1) Web services, once in production and being used, become one of your most brittle interfaces. If you decide to change your database object down the road, then as soon as you do, it will ripple effect through your services and break every interface. 2) Once your service is being called by client applications, they would all need to be updated each time you made a change to your data access layer objects.
  • NEVER return Strongly Typed DataSets as return values! There is a known limitation in ASP.NET which limits you to 1 method per web service class that can return a DataSet. This has to do with the fact that DataSets are actually stored as XML and the service itself is XML so there are conflicts. I ran into this issue a while back and it took a long time to figure out. The only work around we could ever find was to create a separate web service class for each method that returned a strongly typed DataSet. We had 10’s of web service objects and it was a nightmare to manage.

What I’ve found that works great is to isolate your interfaces for your web services into a namespace. I usually call this namespace something like “WebServiceTypes”. I recommend putting every object type that is returned as a value and is passed as a parameter to your web services here. Here’s an example of how to do this:

Complex Type Example

First, create a new directory in your App_Code directory called “WebServiceTypes”. Let’s change HelloWorld to return a complex type.

Add new Class to the WebServiceTypes directory called “ExampleComplexType”. Here’s some code to make it a complex type:

namespace WebServiceTypes
{
    /// <summary>
    /// An example of a complex type to be used as a return value in a web service.
    /// </summary>
    public class ExampleComplexType
    {
        public ExampleComplexType()
        {
            // constructor
        }

        // unique id of the message
        public int MessageId { get; set; }
        // message to say hello
        public string HelloMessage { get; set; }
        // message to say world
        public string WorldMessage { get; set; }
    }
}

Modified HelloWorld Method

Here is the HelloWorld method changed to return ExampleComplexType as the return value:

[WebMethod(Description = "Says hello to the world!")]
public WebServiceTypes.ExampleComplexType HelloWorld(string sMessage)
{
    // create new complex type object to be returned
    WebServiceTypes.ExampleComplexType complexType = new WebServiceTypes.ExampleComplexType

();

    // fill object with values to return.
    // NOTE: here you could do a database query or file system read
    // to get the values to build up you complex type properties.
    complexType.MessageId = 1234;
    complexType.HelloMessage = "Hello";
    complexType.WorldMessage = "World " + sMessage;

    // return the complex type
    return complexType;
}

Now run the web service again and the XML returned should look like this:

<?xml version="1.0" encoding="utf-8"?>
<ExampleComplexType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.devtoolshed.com/webservices/examplewebservice/">
  <MessageId>1234</MessageId>
  <HelloMessage>Hello</HelloMessage>
  <WorldMessage>World is so wonderful!</WorldMessage>
</ExampleComplexType>

The nice thing about doing a WebServiceTypes namespace is that you are translating your objects for the web service calls so even if your data access classes or any other objects change, your web services will still work and you won’t break your client callers.

 

Creating Shortened URLs


Introduction

URL shortening services have been around since at least 2002, which was when TinyURL, the first notable shortening service, was launched. URL shortening services work by taking a long URL as input and generating a shorter URL that, when visited, redirects to the original, longer URL. URL shortening services are useful for sharing long URLs in limited space, such as in a tweet or PowerPoint presentation.

There are a variety of free, publicly available URL shortening services, including TinyURL,¬†Bit.ly, and¬†Goo.gl (Google’s URL shortener service), among others. All of these services provide a website where you can create and manage shortened URLs from your browser; some also offer an API from which you can programmatically create shortened URLs.

This article shows how to use¬†Google’s URL Shortener API to create shortened URLs.

Step 1: An Overview of Google’s URL Shortener API

The Google URL Shortener API offers programmatic access to¬†goo.gl, which is Google’s URL shortener service. Interfacing with the Google URL Shortener API involves making an HTTP request to¬†https://www.googleapis.com/urlshortener/v1/url and sending along appropriate parameters. For example, to shorten the URLhttp://www.dotnetslackers.com, make a¬†POST request of the following format:

2.Content-Type: application/json

The Google URL Shortener API will then respond with the following:

1.{
2.kind: "urlshortener#url"
5.}

Here, id reports the shortened URL, while longUrl indicates the URL a user will be redirected to when the shortened URL is visited. Note that both the data transmitted to and received from the Google URL shortener service is represented as JSON, which is a lightweight data-exchange format commonly used in Ajaxscenarios.

NOTEAt the time of writing, the Google URL Shortener API is still in Google Labs, meaning it is not a finalized product. Be aware that its functionality or interface may change or may have changed since this article was authored.

Step 2: Register an API Key

You can use the Google URL Shortener API anonymously, as in the example above. However, Google recommends that you authenticate when using the API. This is a simple process:

Using an API key grants you a higher number of queries to the URL Shortening API per day – currently, 1,000,000 requests per day. Moreover, by making authenticated requests you can track your API usage from your Google account.

Calling the Google URL Shortener API from ASP.NET

To generate a short URL from a long one we need to send a properly formatted HTTP request to the Google URL Shortener API. The¬†HttpWebRequest andHttpWebResponse class’s in the .NET Framework’s¬†System.Net namespace contain all of the functionality we need for issuing the request and reading the response.

The following code starts by creating an¬†HttpWebRequest object and specifying that the request should be a¬†POST and use a¬†Content-Type header of¬†application/json. Next, the JSON payload sent in the¬†POST is crafted and then converted into a¬†byte array so that it can be written to the HttpWebRequest’s request stream:

01.var req = HttpWebRequest.Create(GetUrl());
02.req.Method = "POST";
03.req.ContentType = "application/json";
04.var postBody = string.Format(@"{{""longUrl"": ""{0}""}}", longUrl);
05.var postData = Encoding.ASCII.GetBytes(postBody);
06.req.ContentLength = postData.Length;
07.var reqStream = req.GetRequestStream();
08.reqStream.Write(postData, 0, postData.Length);
09.reqStream.Close();

We are now ready to transmit the HTTP request and work with the response. The following code does just that. First, we call the¬†HttpWebRequest object’sGetResponse method, which sends the request and creates a¬†HttpWebResponse object from which we can examine the response. The response is read into a string and then¬†ASP.NET’s¬†JavaScriptSerializer class is used to deserialize the JSON payload into a¬†ShortenLongUrlResponse object. (ShortenLongUrlResponse is a class I created that models the data returned by the JSON payload; it has three string properties:¬†kind,¬†id, and¬†longUrl.)

01.var resp
02.
03.= req.GetResponse();
04.using (var respReader = new StreamReader(resp.GetResponseStream()))
05.{
06.var responseBody = respReader.ReadToEnd();
07.var deserializer = new JavaScriptSerializer();
08.var results = deserializer.Deserialize<ShortenLongUrlResponse>(responseBody);
09.}

At this point you can get the shortened URL via the¬†results object’s¬†id property.

The¬†download for this article includes a class named¬†UrlShortener that has a method named¬†Shorten.¬†Shorten accepts a¬†string as input ‚Äď the long URL ‚Äď and returns a¬†ShortenLongUrlResponse object whose¬†id property specifies the shortened URL. You could use this class to shorten a URL like so:

1.var shortenedResponse = UrlShortener.Shorten
2.
4.string shortenedUrl = shortenedResponse.id;

Calling the Google URL Shortener API from JavaScript

As we have seen, generating a shortened URL is as simple as sending a properly-formatted HTTP¬†POST request to¬†https://www.googleapis.com/urlshortener/v1/url, and in ASP.NET this can be accomplished using the¬†HttpWebRequest class. But what if we want to generate a shortened URL from client-side script? Unfortunately, browsers prohibit cross-domain POST requests from script for security reasons, meaning we cannot directly call the Google URL Shortener API from¬†JavaScript. Instead, we’ll need to use a¬†proxy. Rather than calling the Google URL Shortener API directly, our script will have to make a request to a web page on our site, which can then make the call to Google and return the shortened URL.

The demo available for download includes such a proxy. I created a generic HTTP Handler in the Services folder named Url.ashx. This handler:

  1. Reads in the querystring parameter longUrl,
  2. Sends this value to the Google URL Shortener API, and
  3. Returns the shortened URL as its output.

For example, visiting www.example.com/Services/Url.ashx?longUrl=http://www.json.org/ returns the response http://goo.gl/O2WH.

This proxy can then be invoked from JavaScript. The following script shows how to use jQuery’s¬†$.get function to make a request to the proxy and display the returned shortened URL:

1.var longUrl = "http://www.json.org/";
2.$.get("Services/Url.ashx?longUrl=" + longUrl, function (shortenedUrl) {
3.alert("The new, short URL: " + shortenedUrl);
4.});

 

 

Crystal Report


This is the first article in a series focusing on programming with Crystal Reports with ASP.NET 2.0. In this article, we will focus on adding a Crystal Report to an ASP.NET 2.0 web site and displaying the same using the CrystalReportViewer control in a number of different ways.

The entire solution (source code) for this article is available as a free download (in the form of a zip). The source code in this article has been developed using Microsoft Visual Studio 2005 Professional Edition on Microsoft Windows Vista Ultimate Edition with Microsoft SQL Server 2005 Express Edition. I used the same version of Crystal Reports which comes with Visual Studio 2005 Professional Edition. I didn’t really test any of the code in any other tools/IDEs/servers/editions/versions. If you have any problems, please feel free to post in the discussion area.

I contributed two articles¬†focusing on the capabilities of ASP.NET 2.0’s built-in reporting. If you are new to the built-in reporting (also called local reporting), you can find the¬†articles¬†here:

http://www.aspfree.com/c/a/ASP.NET/Designing-and-Developing-Reports-in-
ASPNET-20/

http://www.aspfree.com/c/a/ASP.NET/Binding-Data-to-the-ReportViewer-Control-
Dynamically-in-ASPNET-20/

Starting an ASP.NET 2.0 Web Site Project

The following are the steps necessary to create a new ASP.NET 2.0 web site:

  • Open Microsoft Visual Studio 2005 Professional Edition
  • Open File || New || Web Site

 

  • Select “ASP.NET Web Site” in templates, select “File System” as the location, provide the website name¬†“SampleWebSite01”¬† and finally click on OK.

 

  • Right click on “SampleWebSite01” available in Solution Explorer and select “Add New Item.”

 

The next section walks you through adding a Crystal report to the project.

Programming Crystal Reports with ASP.NET 2.0 – Adding a Crystal Report to the Project
(Page 2 of 6 )

In the previous section, a new ASP.NET web site was created. In this section, we shall walk through the creation of a Crystal report. The following are the steps you need to take; they pick up from where we left off in the previous section:

In the “Add New Item” dialog box, select “Crystal Report” as the template, provide the name¬†“SampleRpt01.rpt” and click on the “Add” button.

 

You should see “SampleRpt01.rpt” added to the “Solution Explorer” and the “Crystal Reports Gallery” dialog will be shown (Fig 05). Select “Standard” in “Choose an Expert” and click OK (Fig 05).

 

Next, you will be taken to provide details for the Data Source. In the “Available Data Sources,” open “Create New Connection” and open “OLE DB (ADO).” It brings up another dialog box to let you select the OLEDB Provider. Select “Microsoft OLEDB Provider for SQL Server” in the list of Providers and click on “Next” as shown below.

 

Provide the db connection information to connect to the Northwind database and click on “Finish.”

A new connection gets added to the “OLEDB (ADO)” group. Open the added connection and further drill down to Northwind || dbo || Tables, add the “Orders” table to the “Selected Tables” list (by selecting it and clicking on the greater than arrow), and click on “Next” as shown below.

 

In the next screen of the wizard, you will be provided with all the fields (or columns) to include in the report. Add OrderID, CustomerID, EmployeeID and OrderDate to the “Fields to Display” section by double clicking each of those fields in the “Available Fields” list and click on “Finish” as shown below.

 

 

Programming Crystal Reports with ASP.NET 2.0 – Crystal Report Components
(Page 3 of 6 )

In the previous section, we added a new Crystal Report to the web site. Once the report gets added, you should be able to see the Visual Studio layout with “Field Explorer,” the¬†new “Crystal Reports” menu and an “Embedded Crystal Report Designer” with two modes (“Main Report” and “Main Report Preview” at the bottom) as shown below.

 

The “Field Explorer” can be used to drag and drop the columns onto the report, add new, add new tables to the report, add new formula oriented columns, running totals, and so on.

The report designer is initially divided into five sections (Report Header, Report Footer, Page Header, Page Footer and Details). Report Header gets displayed only on the first page. Report Footer gets displayed only on the last page. Page Header gets displayed on top of every page. Page Footer gets displayed at the bottom of every page. The Detail section is the body of the report where all of the rows get displayed.

Using the formatting toolbar, properties windows and tools in toolbox, we can format the report in the required manner. Try playing with formatting the report (and preview it simultaneously without executing the project).

Displaying Crystal Report on the ASP.NET 2.0 web page

To display the report on the web page, we need to work with Crystal Report Viewer control. The following are the steps required to attach the Crystal Report to the ASP.NET 2.0 web page:

Using the ToolBox, drag and drop the CrystalReportViewer control.

Using the Smart tag of the CrystalReportViewer control, select “New Report Source.”

This leads you to a new dialog box, “Crystal Report Source.” Every CrystalReportViewer gets associated with the CrystalReportSource control. You can directly drag and drop the CrystalReportSource control from the toolbox as well and assign the same in a smart tag. Provide the details and click OK.

The moment you hit¬†OK, you should be¬†previewing the report. Just hit F5 to execute your web site. Once the web page gets displayed, provide logon information for the report and click on “Logon.”

Programming Crystal Reports with ASP.NET 2.0 – Providing Login information for the CrystalReportViewer control dynamically
(Page 4 of 6 )

The CrystalReportViewer control needs to be provided with database logon information to execute and show the report. At the same time, it is a bit awkward to have the database login page displayed for every Crystal Report. No end user likes it (and of course, it is dangerous too!).

To solve this problem, we can provide database logon information to the CrystalReportViewer control dynamically at runtime. The following is the code to achieve the same:

Imports CrystalDecisions.Shared

 

Partial Class _Default

Inherits System.Web.UI.Page

 

Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load

Dim ConnInfo As New ConnectionInfo

With ConnInfo

.ServerName = “.sqlexpress”

.DatabaseName = “Northwind”

.UserID = “sa”

.Password = “eXpress2005”

End With

 

For Each cnInfo As TableLogOnInfo In Me.CrystalReportViewer1.LogOnInfo

cnInfo.ConnectionInfo = ConnInfo

Next

End Sub

 

End Class

You must observe that the CrystalDecisions.Shared namespace is added to the top. In the above code, the database connection information is stored in ConnInfo and is defined as follows:

Dim ConnInfo As New ConnectionInfo

With ConnInfo

.ServerName = “.sqlexpress”

.DatabaseName = “Northwind”

.UserID = “sa”

.Password = “eXpress2005”

End With

The above connection information is assigned to CrystalReportViewer control using the following code:

For Each cnInfo As TableLogOnInfo In Me.CrystalReportViewer1.LogOnInfo

cnInfo.ConnectionInfo = ConnInfo

Next

Programming Crystal Reports with ASP.NET 2.0 – Hiding the toolbar and adding First, Last, Next and Previous page buttons to the report
(Page 5 of 6 )

By default, CrystalReportViewer automatically displays toolbar at the top. Not every end user uses all features. At the same time, some end users may not like the toolbar.

To hide the toolbar, modify the CrystalReportViewer code (in Source mode) as follows:

<CR:CrystalReportViewer¬†ID=”CrystalReportViewer1″¬†runat=”server”AutoDataBind=”True”¬†ReuseParameterValuesOnRefresh=”True”DisplayToolbar=”False”¬†EnableDatabaseLogonPrompt=”False”EnableParameterPrompt=”False”¬†DisplayGroupTree=”False”

Height=”1064px”¬†ReportSourceID=”CrystalReportSource1″Width=”928px” />

Add First, Last, Next and Previous page buttons to the web page and modify the code behind with new events as follows:

Protected Sub btnFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFirst.Click

Me.CrystalReportViewer1.ShowFirstPage()

End Sub

 

Protected Sub btnLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLast.Click

Me.CrystalReportViewer1.ShowLastPage()

End Sub

 

Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click

Me.CrystalReportViewer1.ShowNextPage()

End Sub

 

Protected Sub btnPrevious_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrevious.Click

Me.CrystalReportViewer1.ShowPreviousPage()

End Sub

Programming Crystal Reports with ASP.NET 2.0 – Enhancing the report with run-time binding along with session handling
(Page 6 of 6 )

In all of the above sections, the CrystalReportViewer worked with CrystalReportSource. Now, let us dynamically add a report source to the CrystalReportViewer and bind it at runtime. This gives us the flexibility to use the same viewer for different reports (showing one at a time).

Add a new web page to the project, add the four buttons (First, Previous, Next and Last) and a CrystalReportViewer control. Modify the CrystalReportViewer control, so that it looks like the following:

<CR:CrystalReportViewer¬†ID=”CrystalReportViewer1″¬†runat=”server”AutoDataBind=”True”¬†ReuseParameterValuesOnRefresh=”True”DisplayToolbar=”False”¬†EnableDatabaseLogonPrompt=”False”EnableParameterPrompt=”False”¬†DisplayGroupTree=”False”

Height=”1064px”¬†Width=”928px” />

In the code-behind, add the following at the top:

Imports CrystalDecisions.Shared

Imports CrystalDecisions.CrystalReports.Engine

Add a new method as follows:

Private Sub BindReport()

 

If Session(“Rep”) Is Nothing Then

Dim ConnInfo As New ConnectionInfo

With ConnInfo

.ServerName =¬†“.sqlexpress”

.DatabaseName =¬†“Northwind”

.UserID =¬†“sa”

.Password =¬†“eXpress2005”

End With

 

Dim rep As New ReportDocument

rep.Load(Server.MapPath(“SampleRpt01.rpt”))

Me.CrystalReportViewer1.ReportSource = rep

Dim RepTbls As Tables = rep.Database.Tables

For Each RepTbl As Table In RepTbls

Dim RepTblLogonInfo As TableLogOnInfo = RepTbl.LogOnInfo

RepTblLogonInfo.ConnectionInfo = ConnInfo

RepTbl.ApplyLogOnInfo(RepTblLogonInfo)

Next

Session(“Rep”) = rep

End If

 

Me.CrystalReportViewer1.ReportSource = Session(“Rep”)

Me.CrystalReportViewer1.DataBind()

End Sub

Add the following code to bind the report for every button click and also during the page load event:

Protected Sub btnFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFirst.Click

BindReport()

Me.CrystalReportViewer1.ShowFirstPage()

End Sub

 

Protected Sub btnLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLast.Click

BindReport()

Me.CrystalReportViewer1.ShowLastPage()

End Sub

 

Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNext.Click

BindReport()

Me.CrystalReportViewer1.ShowNextPage()

End Sub

 

Protected Sub btnPrev_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrev.Click

BindReport()

Me.CrystalReportViewer1.ShowPreviousPage()

End Sub

 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not IsPostBack Then

BindReport()

End If

End Sub