Shahid Riaz Bhatti

if(my.work == “Interesting” || my.availableTime > my.workHours) { this.blog.Post();}

ASP.Net Client Call Back

July 04
by Shahid Riaz Bhatti 4. July 2010 12:07

 

In a client callback, a client-script function sends a request to an ASP.NET Web page. The Web page runs a modified version of its normal life cycle. The page is initiated and its controls and other members are created, and then a specially marked method is invoked. The method performs the processing that you have coded and then returns a value to the browser that can be read by another client script function. Throughout this process, the page is live in the browser.

I’ve copied above line from MSDN :)

To implement ClientCallback we need to implement ICallbackEventHandler interface. This interface has following two signature which we need to implement.

  1. GetCallbackResult
  2. RaiseCallbackEvent

 

GetCallbackResult method is responsible to send the call back result to the client. And RaiseCallbackEvent is responsible to perform the Postback on the server.

This can be achieved by using Ajax toolkit’s update panel. But here I will make a web page which will receive current date from the server and will display it on the web page using ASP.Net client call back approach and without using Ajax toolkit.

 

First of all we need that our aspx page must implement the ICallbackEventHandler interface. Then we need to implement the two methods of this interface. I am pasting code from my Default.aspx.cs.

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Web;
   5: using System.Web.UI;
   6: using System.Web.UI.WebControls;
   7: using System.Xml;
   8: using AjaxControlToolkit;
   9: using System.IO;
  10: /// <summary>
  11: /// Impliment the ICallbackEventHandler interface
  12: /// </summary>
  13: public partial class _Default : System.Web.UI.Page,ICallbackEventHandler 
  14: {
  15:     // variable to hold the Get Callback Event reference
  16:     public string _function = string.Empty;
  17:     /// <summary>
  18:     /// 
  19:     /// </summary>
  20:     /// <param name="sender"></param>
  21:     /// <param name="e"></param>
  22:     protected void Page_Load(object sender, EventArgs e)
  23:     {
  24:         // Get Client Script Manager
  25:         ClientScriptManager cm = Page.ClientScript;
  26:         // Client Side Function which will receive Data from the Server
  27:  
  28:         //Function "DatafromServer" will be on the Client Side
  29:         _function = cm.GetCallbackEventReference(this, "arguments", "DatafromServer", "");
  30:     }
  31:     #region ICallbackEventHandler Members
  32:     string _Date  = string.Empty;
  33:     /// <summary>
  34:     /// //This method will return the callback result to the client
  35:     /// </summary>
  36:     /// <returns></returns>
  37:     public string GetCallbackResult()
  38:     {
  39:         // Return the _Date to the Client. _Date i set to Current Date in the RaiseCallbackEvent
  40:         return _Date;
  41:     }
  42:     /// <summary>
  43:     /// //This method will be invoked to perform the callback on the server (Copied from MSDN) 
  44:     /// </summary>
  45:     /// <param name="eventArgument"></param>
  46:     public void RaiseCallbackEvent(string eventArgument)
  47:     {
  48:         // Set the Current Time in the _Date variable
  49:         _Date = System.DateTime.Now.ToLongTimeString();
  50:     }
  51:  
  52:     #endregion
  53: }

 

Look at Line 46. In this function i.e. RaiseCallBackEvent I am setting Current Time in a Global Variable which is _Date and this is a string Variable.

And on Line 37 i.e. in GetCallbackResult I am returning _Date variable which holds the current server’s time. This function is responsible to give the result back to client.

Now another important part is the code which is in the Load event. In the page load, first I got the ClientScriptManager’s object for the Page. Then using this object I have called the GetCallbackEventReference by passing some parameters, you can see the info. of these param on MSDN. Anyhow in these parameter you can see “DatafromServer”. This is a function which will be on Client Side and it will display the result which is received from the Server.

Now I am pasting my HTML file.

   1: <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
   2:  
   3: <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
   4:  
   5: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   6:  
   7: <html xmlns="http://www.w3.org/1999/xhtml">
   8: <head runat="server">
   9:     <title></title>
  10:     <script language="javascript" type="text/javascript">
   1:  
   2:         function InvokeServer() { 
   3:             // In this case we dont need to pass any thing in argument, as we
   4:             // are getting only the server time without any condition/Crteria..
   5:             // We can Pass string argument if we want to get some data from DB/anything
   6:             // based on some criteria entered by user. That crteria can be set in argument and then
   7:             // on the server side we can change the "RaiseCallbackEvent" to get our desired result
   8:             arguments = "";
   9:             // Variable which is holding the CallBackEvent reference (i.e. the method which will reseive
  10:             // the data from the Server side on Client Side
  11:             <%=_function %>;
  12:         }
  13:         /// This following Function is receiving the data from the Server and 
  14:         /// Displaying it in a span.
  15:         function DatafromServer(arguments,context)
  16:         {
  17:             // arguments contains the data which is sent from the server to the client
  18:             spresult.innerHTML = arguments;
  19:         }
  20:     
</script>
  11: </head>
  12: <body>
  13:     <form id="form1" runat="server">
  14:     <div>
  15:         <%
   1: --Following is a simple HTML button, which will call a JS function to get the data from the server--
%>
  16:         <input type="button" value="Get Server Time" onclick="javascript:InvokeServer();" />
  17:         <%
   1: --span to hold the result from the Server--
%>
  18:        <span id="spresult"></span>
  19:     </div>
  20:     </form>
  21: </body>
  22: </html>

You can see that I have placed a simple HTML button and on its Click event I have called a JS function called InvokeServer.

And in the DatafromServer function is showing the result which is received from the Server. You can see that there is no runat=”server” anywhere in the code. Now if you run the application you will see the current time of the server without post back.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Javascript Numeric Text Box

June 28
by Shahid Riaz Bhatti 28. June 2010 09:10

Sometime we need to have a text box in our website which only accepts numeric values which may include decimal. To achive this, here is a Javascript function:

 

function NumericTextbox(This, AllowDot) {

var code = event.keyCode;

switch (code) {

case 8: // backspace

case 9: // tab

case 37: // left arrow

case 39: // right arrow

case 46: // delete

event.returnValue = true;

return;

}

if (AllowDot && code == 190) {

if (This.value.indexOf(".") >= 0) {

// don't allow more than one dot

event.returnValue = false;

return;

}

event.returnValue = true;

return;

}

// allow character of between 0 and 9

if (code >= 48 && code <= 57) {

event.returnValue = true;

return;

}

// allow numbers on keypad

if (!event.shiftKey && code >= 96 && code <= 105) {

event.returnValue = true;

// run timeout function to check text on char

var s = "NumericTextbox(document.getElementById('" + This.id + "'))";

setTimeout(s, 250);

return;

}

event.returnValue = false;

}

 

You can copy the above code in your javascript file or in the page itself.

Then you can call this JS function on the keydown event of your text box. Here is the sample.

<input type="text" onkeydown="javascript:NumericTextBox(this,true)" id="txtDecimal" />

 

The Second parameter in the JS function is for decimal. If its true then it will allow decimal , if false then it wont allow decimal..

 

 

Set IFrame Src using JQuery

May 20
by Shahid Riaz Bhatti 20. May 2010 08:54

The following line will set the source of Iframe dynamically  using Jquery.

 var Iframe = $("IframeId");

Iframe.src = "www.google.com";

Thanks for reading.....

C ya

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

ASP.Net | General | Tips and Tricks

Sharepont Event Handler

April 17
by Shahid Riaz Bhatti 17. April 2010 12:07

Sometime its necessary to check some business logic when adding/editing/deleting data from a sharepoint list. In this article I’ll show how to implement the custom logic while adding/editing and deleting data in sharepoint list. For this purpose I have created a Custome List in sharepoint and named it MyNews. This list has following column.

Headline

NewsImage

NewsDetail

ExpiryDate

I will write an event handler for this list which will not allow user to set the expiry date of the MyNews list to be smaller than the Current Date. This will be a very simple event handler but this approach can be used to handle the complex scenarios.

Sharepoint 2007 provide event handlers for two types which are given below:

Asynchronous

Synchronous

ASynchronous events ends with ‘ed’ like ItemAdded, while Synchronous ends with “ing” like ItemAdding. So in case of synchronous events we can cancel a user’s action before it take place. For example we will not allow user to add data in MyNews list, if its expiry date is less than the current date by cancelling the user’s add action. So here we go.

Open Visual studio and create a New class library Project. Add reference of Microsoft.Sharepoint dll in the project. Inherit your class from SPItemEventReceiver

Like this: public class MyEvents : SPItemEventReceiver

Now override the following function: ItemAdding

Like this: public override void ItemAdding(SPItemEventProperties properties)

{

}

Now inside this function I’ll write code which will restricts the user to not add the Items if the Expiry date of the NewsList is < Current date. So here is my code:

DateTime NewsExpiryDate = Convert.ToDateTime(properties.AfterProperties["ExpiryDate"]);

if (NewsExpiryDate != null)

{

if (NewsExpiryDate.CompareTo(DateTime.Now) < 0)

{

properties.ErrorMessage = "Expiry date can not be a Past date";

properties.Cancel = true;

}

}

We have to use properties.AfterProperties[“COLUMN NAME”] to get the value which user has entered, because in case of synchronous events “properties.listItem” will always be null. So you have to check properties.Afterproperties to see that what user has entered.

Then I checked that if the entered expiry date is not a past date. If its past date then I have set appropriate message and set the properties.Cancel = true, which means that this item will not be added in to the List. Now our code is complete. Now you need to give a strong name to your class library project and after that put the dll into the GAC. I have also attached a code of a console application which will be used to register this dll with share point list. You can also use this console application to register your event handler to Sharepoint list. All you have to do is change the assembly and class name.

After doing all this I entered a past date into the list as shown in the following fig:

 

After entering the past date in expiry date I clicked on Ok button and got the following error:

 

Download the following MyEvents.cs class for my code:

MyEvents.cs (724.00 bytes)

Download following class for the console application which is used to register the event.

 

Program.cs (797.00 bytes)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

MOSS | WSS

.Net Properties Question asked and my Answer

February 05
by Shahid Riaz Bhatti 5. February 2010 05:24
Hi,

Can any body guide me whats the exact use or *Properties* (get and set) in
C#.

I know how to declare but not sure how to use it. Please guide.

Thanks,

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C# | My Inbox

RecentComments

Comment RSS

Most comments

supplynflshop supplynflshop
51 comments
tiffany-bracelets tiffany-bracelets
39 comments
AVI to iPad AVI to iPad
36 comments