String.IsNullOrEmpty

Might be some of you already using this. But for others it could be a great utility method.

We use a method static method IsNullOrEmpty of string in most of our daily task/Projects a lot. It works fine in most of the cases, but it could work bizarre in some cases if not handled properly.

Say, you get a entry from UI, and having a check whether user has entered something or not. It would work fine as long as user enters the data or not.

But what happen if user enters just spaces. This method would return false, ironically this method is behaving as coded. But do we need this?

Obviously not, spaces could lead wrong entry in our database even can corrupt the data and leads to uncommon results/Y SODS/malfunctioning.

Although being a good developer, one always trim the input before having the check. But it also tends a lots of extra LOCs which we can save and can make our system less error prone.

As most of aware that the beauty of the extension methods that were introduced in c#3.0. So we can have a extension method over a string, which actually does the both first trimming and then checking for IsNullOrEmpty.

So we can have the extension method as

public static bool IsNullorEmpty(this String val)
 {
 if (val != null)
 {
 if (string.IsNullOrEmpty(val.Trim()))
 return true;
 else
 return false;
 }
 return true;
 }

Lets see both existing and our new method running.

My code is

static void Main(string[] args)
 {
 string name = "   ";
 Console.WriteLine(String.IsNullOrEmpty(name));
 Console.WriteLine(name.IsNullorEmpty());
 Console.ReadKey();
 }

The output is

Output

But if you are still using .NET 2.0, you can have a normal static method in your utility call, which does the job for as.

public static bool CheckNullorEmpty(string val)
 {
 if (val != null)
 {
 if (string.IsNullOrEmpty(val.Trim()))
 return true;
 else
 return false;
 }
 return true;
 }

Note: I must say, the limitation of existing IsNullorEmpty has been resolved in .NET 4.0. Means you don’t need to do all this. There is a new method String.IsNullOrWhiteSpace will do the both for you. But unlikely, most of us still working on .NET2.0/3.5

Hope you all must have liked it.

Exploring Client Callback

Download Demo

Client Callback is one of very important features, provided by ASP.NET. Earlier I was not aware on this. In my last application, I implemented this and got a very good result.

This is another way to avoid full post back on the page and can be a great alternative of the Ajax update panel.

Also I was looking for a good article but could not find one, explaining the details. So thought of sharing to you all.

There are various ways, update a part of page without a full page post back, Like update panel, callback etc. But I found callback, is a very useful approach certain times. When we used to display the data.

So here, in this Article I will be discussing the Client Callback, How to implement this, their pros n cons,and how it is handled by the ASP.NET.

What is Client Call back:

We can define the Client Call back like  this “Client Call back provides us a way to call a server side code/method asynchronously and fetch some new data without page refresh.”

So one can initiate Client callback from JavaScript and get the result that can be shown on UI after any required modification. Lets take an pictorial overview.

How to implement Client Callback: To implement call back, one need to follow the below steps.

Things required at Server Side

1 – Implement interface ICallbackEventHandler on any page or control where implemented.

2 – Need to implement two methods RaiseCallbackEvent and GetCallbackResult provided by the interface ICallbackEventHandler.

3 -  RaiseCallbackEvent event is called to perform the Callback on server

4- GetCallbackResult event returns the result of the callback

(Note: There is a property IsCallback of page returns true, if callback is in progress at server.)

Things required at Client Side:

Apart from the above steps, we also require few Client script to complete the Callback functionality. These are

1 – A function that is registered from server and called by any function that want to initiate the callback. It also takes one argument, that can be passed to server.

2- Another function, that is called after finishing the callback, which returns the callback result

3 – On more helper function that performs the actual request to the server. This function is generated automatically by ASP.NET when you generate a reference to this function by using the GetCallbackEventReference method in server code.

Lots more thing written, Not lets jump to code

Here in my example: I have a button and a textbox which is taking Sex type. And on clicking of this button, I am initiating the callback and sending the the type as an argument and accordingly

creating the result and sending it back to the client. And at client side I am displaying in a Client side Div.

So this is a demo, for How to use callback.

Server side code:

I have taken a global variable string, that is used to hold the response, sent to the client as.

string result;

And

public void RaiseCallbackEvent(String eventArgument)
 {
 if (eventArgument == "M")
 {
 result = "You are Male";
 }
 else if (eventArgument == "F")
 {
 result = "You are Female";
 }
 else
 {
 result = "Cannot say";
 }
 }
 

The above method is called at server side, which has one argument, that is passed from the Client. It takes here the textbox value and return the result accordingly.

Another Server side method that is called,

public string GetCallbackResult()
 {
 return result;
 }

It just returned the result that is generated by the method RaiseCallbackEvent.

Also, we need to register some Client side script at Page load.

Here, we need to create a Callback reference, that is the Client side method that is called, after finishing the callback. and assign that reference, in the method that initiate callback from Client.

Lets see the code,

protected void Page_Load(object sender, EventArgs e)
 {
 //Creating a reference of Client side Method, that is called after callback on server
 String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg",
 "ReceiveServerData", "");

 //Putting the reference in the method that will initiate Callback
 String callbackScript = "function CallServer(arg, context) {" +
 cbReference + "; }";

 //Registering the method
 Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
 "CallServer", callbackScript, true);
 }

We should also write one line at pageload, because no code is required to be executed when call back is in progress

if (Page.IsCallback)
 return;

Client Side ( aspx) code:

There are two javascript function. First is called to initiate the callback.And other one is called after finsihing server side callback events to update the UI.

Let’s see first one

function InitiateCallBack() {
 // gets the input from input box
 var type = document.getElementById('txtType').value;
 //Intiate the callback
 CallServer(type,'');
 }

It is called from when user clicks on button. Now let’s move other function

// Called after the server side processing is done
 function ReceiveServerData(arg, context) {
 //arg: hold the result
 //Updating the UI
 document.getElementById('divCallbacl').innerHTML = arg;
 }

And my aspx code is like this.

<div>
 <span>Enter your Sex(M/F):</span>
 <input id="txtType" type="text" />
 <input id="Button1" type="button" value="button" onclick="InitiateCallBack();"/>
 <div id="divCallbacl">
 </div>

Above are self explanatory.

ClientCallback: Digging deep

As I said, it gives faster response, it actually trim down the page life cycle. Many of events does not execute. We’ll see it. Also to distinguish, at server side, whether it is a normal postback or a Callback. One will find the property isCallback true, which shows that it is a callback request, which I have suggested to use at Pageload earlier. Also the IsPostBack property will also be true.

One more thing, viewstate  information is retireved and available at server but any changes made in it, does not persist. As we’ll see the Callback lifecycle Saveviewstate event doesn’t fire. Which also leads in better performance.

Now lets see the lifecycle comparison between normal postback and a Callback

 

 

 

 

 

 

 

 

 

 

 

As above we can see, SaveViewstate and render events does not get fired on server. So it does two things, one we get better performance and on flip side we cannot save viewstate so we should keep in mind while implementing this.

Where to use, where not to:

- Callback is light action and gives us better performance over normal Update Panels.

- One should use Client Callback, for display purpose only. Because we would not get the updated/entered data from the UI on server.

- Also viewstate does not get maintained across during Postback. So one should not rely on it.

Data linking with jQuery

Download Sample

Recently, Microsoft anounced three jQuery plugins as Official plugin.

  • jQuery Client Templating
  • Data linking
  • Globalisation.

In my last article, I discussed about the jQuery Templating. You can view that Article here .

So I think, you all must find Templating article very useful. Because, by the time
web applications development is evolving, we are moving towards Client side
development/scripting, to provide fast and very trendy/flashy look and feel.

So in this article, I am going to discuss another very cool feature, ie
Data linking.This helps us linkling the data and the UI.

What is jQuery:

jQuery is a JavaScript library that works on top of the JavaScript.
jQuery provides a very simple way for HTML document traversing,
DOM manipulation, event handling, animating, and Ajax interactions for
rapid web development. That could have been very complex while working
with normal JavaScript.

jQuery is becoming more and more popular day by day. Even it was integrated
with VS2008 and also available with VS2010.
jQuery is open source. Due to its features,
Microsoft started to support jQuery team and also working with them,
to provide better web based tools to their Clients.

Prerequisite:

  • jQuery library
  • A plugin for datalinking
  • JSON library

jQuery already comes with VS2008/2010. But if you are working VS 2005 then you can
download from the following link.

Download jQuery

To download JSON library,
click here

Data Linking:

Data kinking provides us a way, to link our data/objects to UI controls.
Means, if the controls get updated, the underlying data object would
also be updated. In the same way, if the data objects get updated,
the controls on UI will also get updated (In case of two way linking).

Means once you linked your data with the controls, you don’t need think about
the data object. The syncing between data object and your UI will be taken care
by the jQuery plug in.

So you can imagine, you dont need to get the updated data from the
controls and update the object, which is required at the time
of saving the data at server. Which requires lot more code to be
written and also error prone.

There are several options to link the data.

  • One way Linking
  • Two way Linking

One Way Linking:

One can link the UI controls to some object. Means the object will
always be in sync with UI. Whenever the Data in UI will get changed the underlying
object will also get updated. So one need not worry about the data once it is
done, one can send the object directly to the server for further processing

I have explained it with one sample.

In my example, there is form named as Add Vehicle, where user can enter the
Vehicle name and its price, then click on the Add Vehicle to add the vehicle
at server side.
One can also see the state of the underlying object at any point of time, using
Show Updated Object button.
Now lets go through the code.

Lets see aspx code first

 <table>
            <tr>
                <td colspan="2"><h2>Add Vehicle to Vehicle Store</h2></td>
            </tr>
            <tr>
                <td>Vehicle Name</td>
                <td><input id="txtVName" type="text" /></td>
            </tr>
            <tr>
                <td>Price</td>
                <td><input id="txtVPrice" type="text" /></td>
            </tr>
            <tr>
                <td><input id="btnShow" type="button" value="Show updated object"
                 onclick="ShowUpdatedData();"/> </td>
                <td><input id="btnAdd" type="button" value="Add vehicle to store"
                 onclick="AddVehicle();"/> </td>
            </tr>
        </table>

Here I have two input box to enter the name and price of the vehicle, and two
buttons, one to show the object and other one to add it.

Now lets move to Javascript code,

 var vehicle = {};
 //linking the UI controls with vehicle object
        $(document).ready(function() {
        $(vehicle)
            .linkFrom('Name', '#txtVName', 'val')
            .linkFrom('Price', '#txtVPrice', 'val')
    });

Here I have a global variable vehicle that is linked with the using
linkForm method for the plugin as shown above.

I have also written the code for adding the data at server, using
jQuery Ajax Call as

 function AddVehicle() {
        var inputs = new Object();
        inputs.vehicle = JSON.stringify(vehicle);
        $.ajax({
            type: "POST",
            url: "AddVehcle.aspx/AdVehicle",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(inputs),
            dataType: "json",
            success: ShowStatus,
            error: AjaxFailed
        });

    }
    function ShowStatus(result) {
        alert(result.d);
    }
    function AjaxFailed(result) {
        alert('Ajax failed');
    }

    //to show the state of the object
     function ShowUpdatedData() {
        alert([vehicle.Name, vehicle.Price]);
    }
    

Also lets have a look at server side code


public partial class AddVehicle : System.Web.UI.Page
{
public static List lstVehicle = null;
protected void Page_Load(object sender, EventArgs e)
{

}
//This method adds one vehicle
[WebMethod()]
public static string AdVehicle(string vehicle)
{
if (lstVehicle == null)
{
lstVehicle = new List();
}
JavaScriptSerializer ser = new JavaScriptSerializer();
Vehicle objVehicle = ser.Deserialize(vehicle);
lstVehicle.Add(objVehicle);
return "Vehicle added sucessfully";
}
}

public class Vehicle
{
public string Name { get; set; }
public decimal Price { get; set; }
}

The above code is self-explanatory.AdVehicle() is called to add a vehicle using Ajax call.

Now lets run the application,
Here I have entered data about one vehicle,

Now when I click to see the updated object, ShowUpdatedData
then get to see the vehicle object as below

Converters:

There is also a good feature provided. We may not
want to save the data as we show at UI. Like if there is some price or quantity,
we may want to format the quantity in some manner before saving. So for that
we can put some converters at the time of linking as

 $(document).ready(function() {
    $(vehicle)
        .linkFrom('Name', '#txtVName', 'val')
        .linkFrom('Price', '#txtVPrice', 'val',
        //Converter that will be called before updating the underlying object
        function(value) { return value.replace(/[^0-9.]/g, "") }
        );
     });

As you can see, I have a converter with Price, that will return only numbers and dot.
Lets see it running

What it is doing, its taking the value from the textbox converting it with the
conerter and the setting to property Price of the vehicle object.

Two way linking:

It also do all the things as above but have one more feature. You can also update the object from code also,  as soon as object will get updated that will also be reflected in the UI.

This feature can be very use full in editing/searching feature.You searched
some data and now want to update it. Now you can update UI as well as underlying
object, both UI and data will always be in sync.

I have discussed it with one sample

In my example, Lets we have a list of person at server. One can fetch the
details of an existing person.One also update the existing person or can add a
new person.

So I have created one class person as

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string SSN { get; set; }
    public string Gender { get; set; }
    public string ContactNo { get; set; }

}

My aspx page is as

<table>
            <tr>
                <td> Name </td>
                <td>
                    <input id="txtPersonName" type="text" />
                    <input id="Button1" type="button" value="GetPersonDetails"
                    onclick="PopulatePersonDetails();"/>
                </td>
            </tr>
            <tr>
                <td colspan="3"> <b>Person Details</b></td>
            </tr>
            <tr>
                <td>Name</td>
                <td><input id="txtName" type="text" /></td>
            </tr>
            <tr>
                <td>Age</td>
                <td><input id="txtAge" type="text" /></td>
            </tr>
            <tr>
                <td>SSN</td>
                <td><input id="txtSSN" type="text" /></td>
            </tr>
            <tr>
                <td>Gender</td>
                <td><input id="txtGender" type="text" /></td>
            </tr>
            <tr>
                <td>Contact Number</td>
                <td><input id="txtCNo" type="text" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input id="Button3" type="button" value="Show Updated JS Object"
                     onclick="ShowUpdatedData();"/>
                    <input id="Button2" type="button" value="Add/Update Person"
                     onclick="UpdateorAddData();"/>
                </td>
            </tr>
        </table>

As you can see, in my page I have put the input boxes for every property of
person.

At the start of the page I have also, provided a input box to enter the person name and
a button to fetch the requested person from the server.

I have provided two more buttons, One to see the updated objects in javascript alert
and another one to update the data at the server. It actually looks the list for the SSN if it found then update the existing record else add the new
person. We’ll see the code in a moment.

Now lets move the Javascript code that is written.
The code that is used to link the data

First I have declared one global object that object will be linked to the UI controls
as
var person = {};

and the code for linking the data is

//Linking the controls from the object
 $(document).ready(function()
    {
        $(person)
        .linkBoth('Name','#txtName','val')
        .linkBoth('Age','#txtAge','val')
        .linkBoth('SSN','#txtSSN','val')
        .linkBoth('Gender','#txtGender','val')
        .linkBoth('ContactNo','#txtCNo','val');

    });

As from the above you can see, that person object is used and
linked using linkBoth method, which takes three parameters
first the name of the property of the object,
second the id of the control with sign #
third val
Now, after this you don’t need to worry about the data, all things will be taken care the
plugin itself.

Rest javascript method, I have used

// To fetch the detail from the server of the entert person name
 function PopulatePersonDetails() {

        var inputs = new Object();
        inputs.name = document.getElementById('txtPersonName').value;

        $.ajax({
            type: "POST",
            url: "EditPerson.aspx/GetPerson",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(inputs),
            dataType: "json",
            success: AjaxSucceeded,
            error: AjaxFailed
        });

        // To be called when ajax call succeeded
        //If no object will be found, it'll show an error message as
        //'Person Not found' else call update the person object
         function AjaxSucceeded(result) {
            if (result.d == 'null')
                alert('Person Not found');
            else
                $(person).attr(JSON.parse(result.d));
        }

        //Will be called, if ajax call gets failed somehow.
        function AjaxFailed(result) {
            alert('Ajax failed');
        }
    }

For the functionality of the updating or adding the person
object at server we have following methods

    //This function get the global variable person object
    //which is always sync with with UI and sends it
    //to server to add/update
    function UpdateorAddData() {

        var inputs = new Object();
        inputs.person = JSON.stringify(person);
        $.ajax({
            type: "POST",
            url: "EditPerson.aspx/AddUpdatePerson",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(inputs),
            dataType: "json",
            success: ShowStatus,
            error: AjaxFailed
        });

        }

        //This function is to show the status whether a new person is added or updated
         function ShowStatus(result) {
            alert(result.d);
        }

As I have linked the object to the UI controls, so I am just picking or updating
the person object, that always gives the most updated and synced data.

Also lets have a look to server side code

public partial class EditPerson : System.Web.UI.Page
{
public static List lstPerson = null;
protected void Page_Load(object sender, EventArgs e)
{
}

//This method will return the searched person.
[WebMethod()]
public static string GetPerson(string name)
{
InitializePersons();
JavaScriptSerializer ser = new JavaScriptSerializer();
// ser.Serialize(persons);
return ser.Serialize(lstPerson.Find(p => p.Name == name));
}

//This method will add or update a person based on SSN
[WebMethod()]
public static string AddUpdatePerson(string person)
{
string status;
JavaScriptSerializer ser = new JavaScriptSerializer();
Person obj = ser.Deserialize(person);
InitializePersons();
Person per = lstPerson.Find(p => p.SSN == obj.SSN);
if (per == null)
{
lstPerson.Add(obj);
status = "New person added";
}
else
{
// Updating the person
lstPerson.Remove(per);
lstPerson.Add(obj);
status = "Person updated";
}

// ser.Serialize(persons);
return status;
}

public static void InitializePersons()
{
if (lstPerson == null)
{
lstPerson = new List()
{
new Person { Age = 27, Name= "Brij",
Gender="Male", ContactNo="123456789",
SSN="CC123456"},
new Person { Age = 18, Name = "Ravi",
Gender = "Male", ContactNo = "987654321",
SSN="AB654321"}
};
}
}
}

Lets see the runing application,

I have few person data at server.When I am entering and clicking
for getting the person details, UI gets updated. While actually I am making
an Ajax call, to get the person data and updating the underlying object
as discussed in above code.

Rest things as per the Vehicle Store example

I have also to added a button, which one can click to see the state of the person
object at any point of time, when one wants.

Please find the full sample in attachment

Conclusion:

I found this feature very useful, while using ajax and jQuery
as I discussed in above example. One should go for the one way or two way linking
based on their requirements.

Hope you all must have enjoyed my above article. Please share your valuable
feedback, that will help me a lot for better writing.

Feedback and Suggestions:

Hope you all must have enjoyed my above article. Please share your valuable
feedback, that will help me a lot for better writing.

Also lets have a look at server side code