Sunday, June 24, 2012
Friday, October 22, 2010
ASP.Net Client Call Back
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.
-
GetCallbackResult
-
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.
Expand and Collapse Dev Express hierarchical grid
In this demo I will add a check box in the header of Dev express grid. If i check that checkbox then hierarchical grid will be expanded, and in the second hierarchical grid will be collapsed.
First of all I have to add a checkbox in the header of the grid. There might be some other ways to do this, but I have done this by using the following line of code. Place it after the line where you have bind your grid with the datasource.
1: System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "chkExpCol", "ExpandCollapse('" + GRID_NAME.ClientID + "', true);", true);
Then add the following JS function in ur page.
1: function ExpandCollapse(gridName, reload) {
2: var hDiv = $("div[id$='GRIDNAME_hdiv']");
3: if (hDiv.length > 0) {
4: var firstHeader = hDiv.children()[0].tHead.childNodes[0].childNodes[0];
5: firstHeader.innerHTML = "<input type='checkbox' id='chkExpCol' onclick='ExpandCollapse(" + gridName + ")'>";
6: }
7: }
8: function ExpandCollapse(gridName) {
9: var chkExpColl = document.getElementById('chkExpCol');
10: var grid = igtbl_getGridById('CLIENT ID OF GRID');
11: if (chkExpColl != null) {
12: if (typeof (grid) != "undefined") {
13: for (var i = 0; i < grid.Rows.length; i++) {
14: var row = grid.Rows.getRow(i);
15: if (row != null) {
16: try {
17: row.setExpanded(chkExpColl.checked);
18: }
19: catch (err) {
20: }
21: }
22: }
23: }
24: }
25: }
Thats is it
Data Table at Client Side
Data table can be created at the client side. Here is a small illustration:
1: function CreateDataTable(){
2: var dt = new Ajax.Web.DataTable();
3: dt.addColumn("C1", "System.String");
4: dt.addColumn("C2", "System.String");
5: dt.addRow({ "C1": "Value of C1", "C2": "Value of C2"});
6: }
Done.
Sunday, January 31, 2010
Read data from SharePoint List
n my previous POST i showed that how we can use SharePoint object model to insert records into a SharePoint List. In that example I made a console application which reads a comma separated file and then inserts those records into SharePoint List. Topics which I covered in that example are given below:
- SPWeb
- SPList
- SPListItemCollection
The URL of that example is given below: Click here to see that example.
So the concept which we used in that example is very useful. We can make a client application (i.e. Window/Web) which could be used to insert take input from the user and inserts those records into SharePoint List.
Now today I will show you that how can we retrieve data from a SharePoint list and can display those records in a tabular form to user.
Possible approaches are given below:
- Make a Window/Web application which Query the SharePoint list and display those records into a Datagrid/DataList or repeater.
- We can make a console application which query the SharePoint List and show the data in console screen.
- We can make a user control, which query the SharePoint list and show the result set into Datagrid/DataList or repeater. Then we can put that user control directly on any web page or can place that user control in SharePoint web page.
- Another approach is also that we wrap the user control into a web part and then place that web part on Moss web site page.
- Create Web part, which query the SharePoint list and display the result set into a tabular form.
I have used all the above mentioned to display SharePoint list. For this example I will use approach # 5.
Topics which we will learn in this example are:
- SPWeb
- SPContext
- SPList
- SPListItem
- SPListItemCollection
- Collaborative Application Markup Language (CAML)
- WebPart
My purpose is just to query the sharepoint list and display data into a tabular form, So I will not be using rich css to to decorate my web part.
Here is the summary of my Web part:
- Create a SharePoint Web part.
- I will declare and Initilize my controls in CreateChildControls event of the web part to add my controls in web part.
- In the same event (i.e. CreateChildControls) I will query my SharePoint list and will populate my controls with the SharePoint List data.
Part of my web part code is given below:
In the above snapshot I have highlighted the section which is using CAML. This will be used to fetch the record from the SharePoint List. Rest of the code is self explanatory. In the rest of the code I am pulling data from individual column of the list and inserting it into a table cell.
This is It.
Note:
- Code file of the web part is attached in this POST. (File Name is WebPart1)
- List template which I am using is also attached in this POST. (MYNews.stp)
To find the above two files plz visit following web site:
http://www.shahidriaz.com/post/2010/01/31/ReadSharePointList.aspx
You can follow this approach, but if you want to use my code, then you have to make list from the list template which is attached in this POST.
Basically this is first part of the web part. In my next web part I will make another web part which will open the detailed news, when user click on the see more link of this web part.
Regards,
Shahid Riaz Bhatti
Sunday, January 24, 2010
Insert Data in Sharepoint List using Sharepoint object model
Hi,
I am writing on my blog after a very long long time and I logged in on my web site after several unsuccessful attempt. :)
Well I have just started studying Sharepoint. So this is not for the guru. It is just for the people who just started Sharepoint like me.
In this example I will write a console application, which will read some data from a comma separated file (.csv) and will insert that data into sharepoint list.
I created a custom list in MOSS and named it myData. This list has some columns which are given below:
FirstName, LastName, age.
I also made a .csv file which have some data.
Snapshot of the sharepoint list is given below. You can see that this list is empty.
Code of my class is given below. You can also find this class in attachment of this post.
Code is self explanatory and also commented.
here is the code:
1: class Program
2: {3: static void Main(string[] args)
4: {5: try
6: {7: SPSecurity.RunWithElevatedPrivileges(delegate()
8: {9: //OPEN THE REQUIRED WEB
10: SPSite site = new SPSite("http://qaiser-6tmdbbtq:40934");
11: SPWeb web = site.OpenWeb();12: // REQUIRED LIST OF THE WEB
13: SPList lstNames = web.Lists["myData"];
14: //READ THE CSB FILE
15: StreamReader sr =
File.OpenText("C:\\Names.csv");
16: string Data = string.Empty;
17: //LOOP THROUGHT AL THE FILE
18: while (!sr.EndOfStream)
19: { 20: Data = sr.ReadLine();21: if (Data.IndexOf(',') > 0)
22: {23: //SPLIT DATA
24: string[] Columndata =
Data.Split(new char[] { ',' });
25: // DECLARE LIST ITEM FOR ADD
26: SPListItem item = lstNames.Items.Add();27: // ASSIGN APPROPRITE VALUES FROM THE
// DATA
28: item["Title"] =
Columndata[0].ToString();
29: item["LastName"] =
Columndata[1].ToString();
30: item["Age"] =
Convert.ToInt32(Columndata[2].ToString());
31: // DATA WILL NOT BE INSERTED UNLESS YOU
// CALL UPDATE METHOD OF LIST ITEM.
32: ///NOTE:
33: ///item.Update was throwing an error
//which was saying that I dont have rights to insert
34: ///data into the list. So to make sure
//that my code runs with proper security I encapsulate 35:///all of my code into a delegate which you can see in the first line
/// of try body, which is
36:///SPSecurity.RunWithElevatedPrivileges(delegate()
37: ///
38: item.Update(); 39: } 40: } 41: web.Dispose(); 42: site.Dispose(); 43: }); 44: 45: }46: catch (Exception ex)
47: { 48: Console.WriteLine(ex.ToString()); 49: } 50: } 51: }.
In next post I will do the same thing but insted of using sharepoint object model, I will use Sharepoint web services.
Sorry that I didn't explain things in detail as I am in hurry :)
Remember me in your prayers..