live wid knowledge :)

January 2008 - Posts

Callback & Controls Rendering (Manually Partial Page Rendering)

Callback & Controls Rendering (Manually Partial Page Rendering) 

In my previous article, I wrote about Callback and JSON based Javascript serialization which you can find here. 1. Why

Should I read this article       As Callback doesn’t cause postback and page rendering neither full nor even partial. We can communicate with server (IIS) and our server side code runs there successfully and could rebind our controls like Dropdownlist, Gridview, Listview, Datalist, Repeater or any server side control to which you assign data but problem is when page wont render, its controls wont render and if controls wont render then changes wont reflect and when changes wont reflect there wont be anything at front end to show on webpage. Article is mainly about Callback and Rendering Controls but through this tutorial you can also learn many other things like brief introduction of Postback, Rendering, Create server side controls dynamically, Create Datatable dynamically in memory to bind with create server side controls means binding, get server side control at client side and set their properties and registering client side event of server side control from/through server side code. First of all, I would like to brief some terms which I believe every web developer should aware of.  

2.Postback          Postback is a mechanism of communication between client-side (browser) and server-side (IIS). Through postback all contents of page/form(s) sent to the server from client for processing and after following page life cycle all server side contents get render into client side code and client (browser) display that contents. Callback is another way of communication between server and client. Callback doesn’t follow the page life cycle which followed by in standard postback and doesn’t even cause Rendering. 

3. Rendering       Rendering is process of converting server side code/contents into client side code/content so client (browser) can understand that code and could display the output. Browser can understand or you may say decode code of client side languages and scripts like HTML, DHTML, XHTML, Javascript, Vbscript and a long list. If rendering wont happen then changes won’t reflect which happens on server at client side. Ajax leverages partial postback automatically whereas callback doesn’t cause, so programmer needs to perform that task manually. ASP.NET team has created RenderControl method with its each control so by using that control we can render our control very easily. If you have read my previous article you may skip following section from 4 and 5.  

4. CALLBACK        CALLBACK is lightweight process, It uses well known xmlhttp object internally to call server side method, it doesn’t cause page postback so doesn’t cause page rendering so we to show output at client side we need to make output html ourselves and render controls manually. 

5. ICALLBACKEVENTHANDLER         ICALLBACK implemented in asp.net by using ICALLBACKEVENTHANDLER interface has two methods, one of them used to be call from javascript (client side code) and other one return result asynchronously back to javascript function. We just need to perform some action through server side code at server side and needs to return results but results could are in instance or object of any class which could be not easy for javascript code to handle easily so here we prefer JSON which stands for Javascript Object Notation. 

7. Real Time Scenario with implementation     Suppose we have categories, subcategories, products data and needs to populate categories and subcategories which depend upon categories data would be populate in two different dropdownlists. For products data which is multicolumn and we need to show that data in tabular format so I would prefer Gridview control.  So the situation would be load/populate categories on Page_Load and load/populate subcategories on the basis of selected category using callback and finally load products into Gridview on the basis of selected subcategory.  Before starting coding, I would like to write Pseudo code for better understanding.  

8. Pseudo Code

  1. Create Server side controls e.g. Dropdownlists and Gridview
  2. Load Categories on Page load
  3. Implement ICallbackEventHandler interface
  4. Create subcategories data in server memory to bind to Subcategory dropdownlist.
  5. Render control (subcategory dropdownlist) and show output.
  6. Create products data in server memory to bind to Products gridview.
  7. Render Control (products gridview) and return rendered contents to client side to show
  8. Set innerHTML of each control by rendered contents

source code with comments has attached.

 12. Conclusion: Callback is lightweight technique used to call server side methods asynchronously from javascript without any postback and reloading/rendering of unnecessary parts of page and unnecessary code  So we can use that when we need to perform any operation at backend means at server like update records in database or like that. You don’t need to send all your contents of page in request and make that object heavyweight which could cause slow performance.  

 

Callback and JSON-Based JavaScript Serialization

FYI: sample code is attached @ the end

When working in ASP.NET, sometimes you need to call server-side methods asynchronously without having either full-page or partial-page postback. Thanks go to the ASP.NET team to provide an easy implementation of ICALLBACK.

ICALLBACK

ICALLBACK is a lightweight process. It uses a well-known XMLHTTP object internally to a call server-side method. It doesn't cause page postback, so it doesn't cause page rendering. You show output at the client side, so you need to make the output in HTML yourself and render controls manually.

ICALLBACKEVENTHANDLER

ICALLBACK is implemented in ASP.NET by using the ICALLBACKEVENTHANDLER interface. This interface has two methods; one of them is used to call from JavaScript (client-side code) and other one returns the result asynchronously back to JavaScript function.

You just need to perform some action through server-side code at the server side; it needs to return results, but the results could be an instance or object of any class that would be not easy for JavaScript code to handle easily. So here, JSON, which stands for JavaScript Object Notation, is a better choice.

JSON

JSON is lightweight data-interchange format. ASP.NET gives good support for JSON as well. It's rapidly adopting JSON because it's lightweight and easy to read, both by humans and machines.

Callback Server-Side Code

First, implement ICALLBACKEVENTHANDLER to call a server-side method asynchronously, step by step.

Implement Server Side (C#) Page/Control class by System.Web.UI.ICallbackEventHandler

Following are definitions of two methods that must be implemented. The RaiseCallbackEvent method invokes by using a JavaScript function:

public void RaiseCallbackEvent(string eventArgument)
{
//to do code here
}

The GetCallbackResult method invokes itself when it has completed processing the RaiseCallbackEvent method.

public string GetCallbackResult()
{
return "";
}

In Page_Load or Page_Init event

The following statements are used to register client-side methods. CallServer(arg, context), as the name implies, would use the call/raise server-side method that was the RaiseCallbackEvent string's eventArgument. ReceiveServerData(arg, context) would get its result through the arg parameter by GetCallbackResult().

protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager scriptMgr = Page.ClientScript;
String cbReference = scriptMgr.GetCallbackEventReference(this,
"arg", "ReceiveServerData", "");
String callbackScript = "function CallServer(arg, context)
{" + cbReference + "; }";
cm.RegisterClientScriptBlock(this.GetType(),"CallServer",
callbackScript, true);
}

Call Client-Side Code

<script language=javascript type=text/javascript>
function ReceiveServerData(arg, context)
{
alert(arg);
}
function CallSrv()
{
CallServer('get customer', '');
}
</script>


<input type="button" value="get customer" onclick="CallSrv()" />

That's it. These are the steps you need to use to call and get results from server-side code using ICALLBACK. Now, you will go ahead to some very easy steps for JSON-based JavaScript serialization to return results in JavaScript's easily parseable format.

Suppose you have the following class whose object needs to return a JavaScript function through JavaScript serialization.

Sample Class

public class Customer
{
public string Name;
public int Age;
}

JSON Code

declare string jsonResult;

At the class level, this would be used to contain the final result and return. After some sample code in both methods, the code will look like the following:

public void RaiseCallbackEvent(string eventArgument)
{
//populate Customer object to return
Customer customer = new Customer();
customer.Name = "Muhammad Adnan";
customer.Age = 24;

//JavaScript serialization of Customer object
System.Web.Script.Serialization.JavaScriptSerializer jss;
jss =
new System.Web.Script.Serialization.JavaScriptSerializer();

//stringbuilder to contain serialized customer object
System.Text.StringBuilder sbCustomer =
new System.Text.StringBuilder();
jss.Serialize(customer, sbCustomer);


jsonResult = sbCustomer.ToString();
}

public string GetCallbackResult()
{
return jsonResult;
}

Asynchronous output would occur within a millisecond and without postback.

Conclusion

Callback is lightweight technique used to call server-side methods asynchronously from JavaScript without any postback and reloading/rendering of unnecessary parts the of page and unnecessary code. JSON is a lightweight data interchange format to make server-side class' objects easily parsable by client-side code to show output on the browser.

FYI: sample code is attached @ the end

client server hell

It is always been a tension for web developers to write/read/run/access code between client side and server side. like write script at server

side and use that @ client side or vice versa. today i would like to share some of my knowledge about this. HTH :)

write javascript script @ server side and invoking from server side.

private void Page_Load(object sender, System.EventArgs e)
{
string jsCode= “<script>function myFunc(){ alert(’hello adnan’); }</script>”;
Page.RegisterStartupScript(”adnan”,myfunc);
Button1.Attributes.Add(”onclick”,”return myfunc()”)
}

You can also utilize this method @ client side means write javascript(js) code at serverside and use that by html/javascript (client side)

<html><body>
<a href=”#” onclick=”myFunc()”>hehehe</a>
</body></html>

Writing js script in html/javascript and calling it from server side

<html>
<script>
function myFunc()
{
alert(’hello adnan’);
}
</script>
<body></body></html>

private void Page_Load(object sender, System.EventArgs e)
{
Button1.Attributes.Add(”onclick”,”return myFunc()”);
}
in above case you would need to call it on event (button click) but what if you wanna execute whilst executing server side code
then use RegisterClientScriptBlock

private void Page_Load(object sender, System.EventArgs e)
{
Page.RegisterClientScriptBlock(”adnan”,”myFunc”);
}

to call/access methods of server side you would need to use ajax (xmlhttprequest obj) or callback methodology for async communication and read my blog about ajax and callback here. but u can run statement/instructions of server side code or access objects of server side from client side easily by using :

if u have to run statement e.g, create/assign session in javascript

<% Session.Add(”key”, “value”); %>

or if you wanna use server side obj e.g session object again

alert(’<%= Session[”key”] %>’);

to discuss more scenarios, kindly post comment.

 

function with n number of arguments

rarely we could need of such function but i m sure whilst programming, programmers have used such functions of their framework functions/base library functions e.g, in case of c language you must have used printf() function (if u didn’t use it i can say u r n’t c programmer :D) it takes n number of arguments, hmm still confuse ok let me tell u how ………..

printf(”sum of %d and %d is %d”,1,2,1+2) ; i hope now you got my point.

but what if you have to make function with n number of arguments using .net (c#.net) then don’t worry main hoon na :D simply u would need to know/utilize PARAMS keyword of c# let me give u any example

private object Sum(params object[] numbers)
    {
        int sum = 0;
        foreach (object o in numbers)
            if (o.GetType() == typeof(int))
                sum += (int)o;
        return (object)sum;
    }

i used object to make it more flexible for you.

One really cool app (orca) to edit .msi installer

Some days back i got a work to make such installer which could display text of such languages which are not supported by visual studio 2005 by default like danish/arabic,…. :) so i start my one of fav work R&D and got one wonderful One Really Cool App (Orca.exe) which is a tool to edit .msi files ……. isn’;t that awesome:P ;)

anyhow ORCA.EXE is such tool which can edit tables of .MSI file now you can change text which shown on screen of installer even can change buttons their font, styles, size, even Prequisites whose example i gave in my previous blog post which was (INSTALL VS 2005 WITHOUT XP SP2)

you may download orca.exe by cliking here 

 

Dynamically controls creation asp.net/ event fire twice / event bubbling

 

few days back i spent alot of my time in googling about bindable controls creation on runtime but whatever tutorial/article i follow fail me to achieve my purpose mostly at 99% which makes me crazy coz this doesn’t happen with me only 1 or 2 times :( so i decided then when i will achieve this functionality i will must write blog about it and solution as well ;)

finally today i ‘d like to talk about dynamically controls creation in asp.net which i found quite easy but for newbie it become quite hectic because to create control at runtime is not an issue but to persist them after post back is an issue even u keep their EnableViewState property true :),  solution is quite simple but that depends upon scenario/need. if you need to create such controls e.g, gridview, datalist, repeater,.. which need to bind then simply follow following steps:

  1. create controls in Page_Init event
  2. bind controls in Page_Load event

thats it :)  its a matter of two steps but drive you nuts if you don’t know coz those controls which created on Page_Init doesn’t persist after postback if you just create them in Page_Load and in Not Postback condition coz it will be created once when first time page loads afterwards it wont be created so u wont be able to see it again but if u don’t put Not Postback condition then everytime it willl be create suppose if you create edittable grid (or any control) and u edit something and press update button next time but on page_load event it will create all controls again and somehow bind as well if u r binding then ur modifications wont remain anymore so …………… :s that was just a 1 scenario so if you bind again and again your modification wont persist and if you don’t create control again and again on each postback ur controls wont persist :D

so the solution is to create controls in Page_Init event without putting condition of Not postback and bind your controls in Page_Load event under condition of Not Postback …

few solutions i would like to write which are somehow out of the scope of this article but you might get whilst working on asp.net binding controls  …..

sometime when we want to bubble event means we use datalist and in datalist we put button and button will fire event of datalist which can be capture in Item_Command event of that datalist, WONT BE FIRE if you write databinding code of datalist in Page_Load event without or out of condition of Not Postback  so keep your databinding code under Page not postback condition.

you can’t rebind your code from bubble event means if you have any button/linkbutton/image button or any such control which cause postback and fire event of datalist don’t try to rebind your datalist in it .. coz it wont happen from there :)

may be some time you found problem of getting some events fired twice :D it happens when your AutoEventWireUp = true so keep it false (good practice)

i will post couple of sample code very soon or you may post comment with your email id to get sample codes via email :)

Asp.net email sending (priority, reply to, read notification)

 

Usually web developers need to write code for sending email (me 2 :P) but normally we just setup To,From, Subject, Body and login credentials and simply call Send() method ;), what if our boss ask for such features like he want our Emails Should be at HIGH priority (no matter either they deserve or not :D) and he wants set up Reply-To email id should be of Him (boss) and should also get Read Notification (in case of email is being sending to employee so he wont lie that he dind’t get/read email :D)  anyhow jokes apart… lets code

in asp.net we create instance MailMessage instance …

dim mailMsg as new MailMessage(fromEmailID, ToEmailID)

mailMsg.Subject = “testing…”

mailMsg.Body =  “always do charity :D”

mailMsg.Priority = MailPriority.High

mailMsg.ReplyTo = New MailAddress(”Enter your desired Reply To Email ID”)

mailMsg.Headers.Add(”Disposition-Notification-to”, “Send Read Receipt Email ID“)

is it complex :D

create HTTP Endpoing (Web Service) in Sql Server 2005/2k5

you must be wondering about HTTP endpoint, i did too, anyhow HTTP Endpoint means way to create service interface using either HTTP or SOAP or TCP means web service :). Scalar values, errors, messages can be return in searlized XML format. you don’t need of IIS to deploy HTTP Endpoint or you may say sql server 2005 web service. in win 2k3 u may use HTTP.sys module of kernel for that purpose rather than IIS

Lets come to the implementation:

// Create Stored procedure, which we shall use in our web service

use adventureworks // database name
go

create procedure dbo.GetEmployees //stored proc name
As
select * from employee; //simplest query
go

// code for http endpoint/web service

use adventureworks
go

CREATE ENDPOINT GetEmployees
STATE = STARTED
AS HTTP
(
PATH = ‘/Employee’,
AUTHENTICATION = (INTEGRATED),
PORTS = (CLEAR),
SITE = ‘localhost’
)
FOR SOAP
(
WEBMETHOD ‘EmployeeList’
(NAME=’AdventureWorks.dbo.GetEmployees’),
BATCHES = DISABLED,
WSDL = DEFAULT,
DATABASE = ‘AdventureWorks’,
NAMESPACE = ‘http://AdventureWorks/Employee’
)
go

There we go. We now have a web service! You access and use this endpoint the same way you would any other web service. You can create multiple WEBMETHODs in a single endpoint, just seperate them with commas in the FOR SOAP statement.

Here are the values you can use for the “STATE” argument:

  • STARTED—listening and responding
  • DISABLED—neither listening nor responding
  • STOPPED—listening, but returns errors to client requests

Here are the “AS HTTP” arguments you can use:

  • Path – The virtual URL path on the server where the Web service will reside
  • Authentication
    • INTEGRATED – most secure. It will try to use Kerberos-based authentication if possible (otherwise, NTLM).
    • DIGEST is not as secure as INTEGRATED. You should use it only if INTEGRATED authentication is not possible.
    • BASIC authentication is the least secure. You should use it only if you can’t implement either INTEGRATED or DIGEST authentication methods. BASIC requires SSL as the Port value.
  • Ports – CLEAR (HTTP - port 80 by default) SSL (HTTPS - port 443 by default)
  • Site – The name of the server on which the Web service is running

So, now lets put our endpoint to work. First, create a new windows application project, and add a web reference to it. When you browse for the web service, it won’t be discovered automatically. You have to type in the url and click “go”. The url in this case is http://localhost/Employee?wsdl. You’ll see the EmployeeList method come up in the list, just like using any other web service. Go ahead and add the service and rename it to whatever. I called mine “adventureWorksService”.

Now we just add code like using any other webservice. I’ve added a button to click to populate the listbox on my form. So here it is:

Public Class Form1

 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        ‘ Create a new instance of the web service

        Dim employeesProxy As adventureWorksService.GetEmployees = New adventureWorksService.GetEmployees

        ‘ You have to pass in credentials to authenticate yourself to use the service.  We are just going to use

          the same credentials we have logged into our computer as.

        employeesProxy.Credentials = System.Net.CredentialCache.DefaultCredentials

       ‘ The result of a SELECT statement via an endpoint can be converted to a DataSet

        Dim ds As System.Data.DataSet = DirectCast(employeesProxy.EmployeeList, DataSet)

 

        ListBox1.DataSource = ds.Tables(0)

        ListBox1.DisplayMember = “FullName”

        ListBox1.ValueMember = “EmployeeId”

     End Sub

End Class

 

Dotnetnuke Inter Module Communication

Simple as i could make that seamlessly tough concept about dotnetnuke.

i simply made two dotnetnuke modules 1 to send message to other module (receiver). simply implement two dotnetnuke

ready made interfaces and sender raise event and send data in object through eventarguments and receiver get that data through

that raised event.

i think enough talks lets code sorry for stupid formatting :P

Sender Steps with example code:

implement class by IModuleCommunicator like below{

Implements Entities.Modules.Communications.IModuleCommunicator}

Create controls and Add like below{

Me.txtMsg1.Text = “Message 2 Send”
Me.btnSend1.Text = “Send”
Me.Controls.Add(txtMsg1)
Me.Controls.Add(btnSend1)}

Declare Event and make created controls eventable{

Public Event ModuleCommunication(ByVal sender As Object, ByVal e As DotNetNuke.Entities.Modules.Communications.ModuleCommunicationEventArgs)

Implements DotNetNuke.Entities.Modules.Communications.IModuleCommunicator.ModuleCommunication
Protected WithEvents txtMsg1 As New System.Web.UI.WebControls.TextBox
Protected WithEvents btnSend1 As New System.Web.UI.WebControls.Button

}

Declare event arguments and raise event like below in btnSend click event{

Dim objEventArgs As New DotNetNuke.Entities.Modules.Communications.

ModuleCommunicationEventArgs(”IMCSender”, Me.txtMsg1.Text,

GetType(ViewIMCSender).Name, “ViewIMCSReceiver”) RaiseEvent ModuleCommunication(Me, objEventArgs)}

Receiver Steps with example code:

Implement class by IModuleListener like below{

Implements DotNetNuke.Entities.Modules.Communications.IModuleListener}

Implement OnModuleCommunication like below{

Select Case e.Type
Case “IMCSender”
If e.Sender = “ViewIMCSender” And e.Target = GetType(YourCompany.Modules.IMCSReceiver.ViewIMCSReceiver).Name Then
lblReceive.Text = e.Value.ToString()
End If End Select }

 

Conditional Breakpoint

You know how to put conditional breakpoint or do u know what conditional breakpoints are .. no? anyhow conditional breakpoints are such breakpoints which stop debugging execution conditionally i.e, either condition “is true” or “has changed” if criteria met then breakpoint will get active if no then execution wont stop on breakpoint ..isn’t that coooooool …. look on following code and then steps to put breakpoint on it ;)

static void Main(string[] args)
{
int result = add(11, 3);
Console.Write(result);
Console.Read();
}

public static int add(int a, int b)
{
int c;
c = a + b;
return c;
}

steps:

  •  press control+alt+A+B to get/activate breakpoint window
  • In the Breakpoints window, click New to create a new breakpoint.
  • On the Function tab, type add for Function. Type 1 for Line, type 1 for Character, and then set Language to C# then press OK
  • now right click on that breakpoint and select condition, and make sure that the Condition check box is selected. Type a > 0 for Condition, make sure that the is true option is selected, and then click OK.
  • In the New Breakpoint dialog box, click OK.
  • On the Debug menu, click Start.
  • The program stops at the IF statement in the Main method. To continue program execution, click Continue on the Debug menu.
  • The program stops again at the addfunction. Continue to run the program.


More Posts Next page »