November 2008 - Posts
Hi developer friends, lately i found a cool blop post Here , explaining how to change the theme of you IDE into a Dark background color, I must admit i was not very exited by the idea of changing my entire IDE look and feel. Once i have tested and tried it i cant stop.so my IDE now looks like this:
All you need to do is download from the link above the vssettings file and import it using the Tools -> Import and Export Settings.Dont forget to save your previous setting.
Hi everyone, In this post i will show how to call web services as the ajax "end point".In addition i will show how to use something called PageMethods.
But as usual in this series of posts, a reminder of what has been written and said so far:
Microsoft Ajax, from the bottom up
Microsoft Ajax, from the bottom up - part 2.
Microsoft Ajax, from the bottom up - part 3
Microsoft Ajax, from the bottom up - part 4
Microsoft Ajax, from the bottom up - part 5
ASP.NET Ajax Web services
ASP.NET AJAX supports ASMX Web methods as endpoints for asynchronous AJAX callbacks, What this means is we can write even efficient ajax calls instead of using the UpdatePanel.If you recall, The UpdatePanel, although has many advantages , has also a very important disadvantage. He is not very efficient on the fire since every partial page update sends the entire page to the server,an unnecessary behavior most of the times. In addition, the entire life cycle of this page is also in action.
So if we only wish to send to the server something like an ID, or any other "small" data to the server, the way is PageMethods or web services. What do we gain:
Efficient on the wire (no SOAP or XML) and Efficient on the server (no page lifecycle). All we need to do in order to use an existing or new web service is to add to this service an Attribute that is within the System.Web.Script.Services namespace.
Here is a sample for this asmx.cs code:
namespace MyWebServices
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
public WebService()
{
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
In addition to that i can add another attribute that specifies what is the response format:
JSON or XML using the ScriptMethod attribute.This attribute can be applies to methods only.([AttributeUsage(AttributeTargets.Method)])
Now, in the aspx file that wishes to use this web service ,we need to add to the ScriptManager the following code:
<asp:ScriptManager ID="ScriptManager1" Runat="server">
<Services>
<asp:ServiceReference Path="WebService.asmx" />
</Services>
</asp:ScriptManager>All that is left is to consume this web service from JavaScript like this:
<script>
function SayHello()
{
//namespace.classname.methodname
MyWebServices.WebService.HelloWorld(onCompleted,onFail);
}
function onCompleted(result,context, methodName)
{
alert(result);
}
function onFail(error,context, methodName)
{
alert(error.get_message());
}
</script>
Notice that the calling conversion is "NamespaceName.ClassName.FunctionName".
We also need to specify a callback function that will be invoked when returning from the server,we then can use it using the "result" parameter.Another helpful we can specify when calling this web method,is the fail call back.
ASP.NET Ajax PageMethods
Now what if we want to write something like web service but we need it only to a single page, it's a bourdon to write and add a web service to our project. Besides, we dont need anyone to use this web service but out page. This is where Page methods come in handy. What this mean is we can use our page itself as a web service y setting some of its methods to be Web Methods.
In order to use Page Methods, you need to allow this behavior in your ScriptManager
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods=true/>
In order to specify that a cs function is a Page Method, add the WebMethod attribute to the function declaration. The function should be also declared as public static.
[WebMethod]
public static string Search(string sName)
{
DataTable oDataTable = DB.GetDate();
DataRow[] oResultRows = oDataTable.Select("Name = '" + sName + "'");
if (oResultRows.Length > 0)
{
return oResultRows[0]["Phone"].ToString();
}
return string.Empty;
}
Now in the aspx file you can use these Page Methods like this:
<script>
function Search()
{
var sSearchText = document.getElementById('<%= txtName.ClientID %>').value;
if(sSearchText != '')
{
PageMethods.Search(sSearchText,GetResultsCallBack);
}
}
function GetResultsCallBack(result)
{
document.getElementById('<%= txtName.ClientID %>').value = result;
}
</script>
Again , you can add the client callbacks for the fail and complete as well.
That's it , now we can move to the client half of the Microsoft ASP.Net Ajax.
Hi all ,Finally we have reached the client side of Microsoft Ajax, known by the name "Microsoft Ajax Library". But as usual in this series of posts, a reminder of what has been written and said so far:
Microsoft Ajax, from the bottom up
Microsoft Ajax, from the bottom up - part 2.
Microsoft Ajax, from the bottom up - part 3
Microsoft Ajax, from the bottom up - part 4
Microsoft Ajax, from the bottom up - part 5
Microsoft Ajax, from the bottom up - part 6
If we take a look on the Client side architecture in this figure
We can see it has many "things" in it , including the following:
1. It is a JavaScript framework, meaning it contains some js files that can be used independently from ajax , or being used internally by the Microsoft asp.net Ajax, like when using an UpdatePanel.
2. It has a JavaScript base type extensions. What Microsoft did is very simple, They used the native types prototypes and added more functionality to them. i will explain about it later, but for now, take a look at these 2 lines of code for instance:
var str1 = " This is some string with white spaces ";
alert(str1.trim());
Where did the trim functions came from?JavaScript does not have any trim function in its native string type!!! is this C# like Trim function? The answer is very simple, all that has been done is extending the native string type using its prototype attribute. I will discuss it shortly in this post.
3. It has a JavaScript new types known as Script BCL, organized in a C#/Java like namespaces. Look at these couple of lines of code:
var oStringBuilder = new Sys.StringBuilder();
oStringBuilder.append("<Books>");
oStringBuilder.append("<Book name='C# in action'>");
oStringBuilder.append("<Book name='Linq in action'>");
oStringBuilder.append("<Book name='ASP.NET 3.5 in action'>");
oStringBuilder.append("</Books>");
alert(oStringBuilder.toString());
What ta BIP BIP BIP is going on here???? StringBuilder is a C# class , isn't it? Well as it turns out JavaScript combined with "Microsoft Ajax Library" now has new types anyone can
used and build a nicer and better code.
4. It has a JavaScript classes being used as the core classes for the internal operations for the Ajax engine in the client side.This part includes among many other JavaScript classes the
Sys.Net.WebRequest Class
Type Class
Sys.WebForms.BeginRequestEventArgs Class and much much more.
4. It has Web services proxies for making the ajax calls to web services (of WCF services).
5. It has a JavaScript serializing the http request results.
6. It has a History solution for partial page updates that can be used in the server side or even in the client side. I will show some very cool sample later.
7. It has a built in objects that can be very helpful for debugging and tracing JavaScript.
By the way , a good reference to the asp.net ajax extensions can be found here:
http://asp.net/AJAX/Documentation/Live/ClientReference/Global/default.aspx
So lets begin and Show some of the new types JavaScript has to offer, In the next post i will show how they extended the existing JavaScript native types.
JavaScript "new" objects:
first of all, in order to use these "new" objects that come out of the box for you, you need to add a ScriptManager to the page. Now lets see a sample of a very useful object that i mentioned earlier, The StringBuilder objects.
The Sys.StringBuilder provides a way to concat strings. It has just like C# StringBuilder an append method, an appendLine method and a toString method that returns the concat string so far.Here is a sample code just i like i wrote a couple of lines ago:
var oStringBuilder = new Sys.StringBuilder();
oStringBuilder.append("<Books>");
oStringBuilder.append("<Book name='C# in action'>");
oStringBuilder.append("<Book name='Linq in action'>");
oStringBuilder.append("<Book name='ASP.NET 3.5 in action'>");
oStringBuilder.append("</Books>");
alert(oStringBuilder.toString());
Lets explain some of the things here, first of all the namespace,
how can there be a namespace in JavaScript.Lets say you wish to implement a namespace in JavaScript, all you need to do , is to create an empty objects using the constructor function ,
something like:
function MyNamespace() { };
MyNamespace.ClassA = function(x, y)
{
this.x = x;
this.y = y;
this.toString = function() {alert(this.x + " " + this.y); }
}
var oClassA = new MyNamespace.ClassA(5,10);
oClassA.toString();
Here i created an empty object using constructor functions (If you are not familiar with the term i suggest you read about it)and added to this object "sub object" by the name "Class1". Since every Object in JavaScript is basically a dictionary Adding properties is very simple.
If you wish to so this yourself ,"ASP.NET AJAX Extensions" has a built in mechanism that
does exactly that using Type class:Type.registerNamespace("Samples");
Type.registerNamespace("Samples");It adds this namespace to the global window object in your host environment (The browser)
So starting from today, any concatenation operations can be done using the new StringBuilder class;
In the next post i will show how to use the native types extensions and how they were implemented.
Hi all again, Today i will show the Timer server control which is one of the five server controls that are available in the Microsoft Ajax server side controls. I will also explain the use of the ScriptManager and the ScriptManagerProxy server controls in a nutshell.
For those who missed the first 4 previous post about ajax, you can read them here:
Microsoft Ajax, from the bottom up
Microsoft Ajax, from the bottom up - part 2.
Microsoft Ajax, from the bottom up - part 3
Microsoft Ajax, from the bottom up - part 4
The Timer control:
The Timer controls Performs asynchronous or synchronous post backs or partial page updates at a user defined intervals.
The accurate timer between each interval is browser dependent, since it rely on the window.setTimeout JavaScript function.
The Timer control has a main Event by the name "Tick" that you can register on and specifying a server side event handler.this event handler will be invoked once the interval has elapsed. What will happen while this interval elapsed (A post back or a partial page update) depends on the implantation.
If you use the Timer side by side with an UpdatePanel , and set a trigger to your timer,or , if you write your timer inside the UpdatePanel , a partial page update (Async) will be performed. If you don't , a real post back will occur.
If you don't specify any value for the interval, the value will be 60000 milliseconds.
Here is a simple sample that does periodic updates using the Timer control:
<div>
<asp:ScriptManager runat="server" ID="ScriptManager1"
EnablePartialRendering="true" ></asp:ScriptManager>
<asp:Timer ID="Timer1" Runat="server" Interval="2000"
OnTick="Timer1_Tick" />
<asp:UpdatePanel UpdateMode="Conditional" runat=server>
<ContentTemplate>
<asp:Label runat=server ID="lblTime"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" />
</Triggers>
</asp:UpdatePanel>
</div>
The ScriptManager control:
As you probably know, every page that uses any of the controls i mentioned so far must contain a single ScriptManager on the page, but what does it really doing?
As it turns out it does the following:
1. Downloads JavaScript files to the client. These files are browser specific. A file can be for instance the file that is responsible for partial page updates and manages all the round trips to the server and back, The file name is:
2. Enables partial page updates using UpdatePanel. Manages the round trip to the server and back to the client.
3.Manages callback timeouts and provide error handling option.
4. Enables asp.net ajax localization.
5. Provides registration methods for scripts.
6. Manages Application services such as Membership, Roles etc. you can use Membership services and Roles services in javascript just as if you are using it on the server using C#.
7. Configure if release files or debug files for the asp.net ajax client side script will be downloaded to the browser.(A good practice is to deploy the release versions since it is smaller in size. ) When the ScriptMode is set to Auto(The default value) the settings are "derived" from the server settings.
Here is a complete schema:
<asp:ScriptManager ID="ScriptManager1" Runat="server"
EnablePartialRendering="true|false“
EnableHistory="true|false"
EnablePageMethods="true|false"
AsyncPostBackTimeout="seconds"
AsyncPostBackErrorMessage="message"
AllowCustomErrorsRedirect="true|false"
OnAsyncPostBackError="handler"
EnableScriptGlobalization="true|false"
EnableScriptLocalization="true|false"
ScriptMode="Auto|Inherit|Debug|Release"
ScriptPath="path">
<Scripts>
<!-- Declare script references here -->
</Scripts>
<Services>
<!-- Declare Web service references here -->
</Services>
</asp:ScriptManager>
This peace of code does nothing then render the Microsoft ajax library files to the client.
<div>
<asp:ScriptManager runat="server" ID="ScriptManager1"
EnablePartialRendering="true" ></asp:ScriptManager>
</div>
For instance , when you wish to use PageMethods(another feature i will discuss in a later post)You need to tell the ScriptManager EnablePageMethods=true.
The ScriptManagerProxy control:
This control does exactly what the ScriptManager does , only that this control enables nested components such as Master/content pages, or user controls to add scripts and service references to pages that already contain ScriptManager control.
So you will use this control only when the hosted page already contain a ScriptManager control. for instance : to add functionality only to those pages that i want and not to the entire content pages connected to my master page.
Hi all again, I didn't had much time to continue writing my serious of post about Microsoft Ajax, but now i have some free time, so lets continue....
In this post i will discuss and show the sibling control of the UpdatePanel control, the UpdateProgress control .
For those who missed the first 3 previous post about ajax, you can read them here:
Microsoft Ajax, from the bottom up
Microsoft Ajax, from the bottom up - part 2.
Microsoft Ajax, from the bottom up - part 3
The UpdateProgress control is a very simple one, all it does is showing the user any text , image or animated image during a partial post back caused by the UpdatePanel control. It does this by setting its AssociatedUpdatePanelID property to the wanted UpdatePanel.
For example, consider the following code:
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManager1"
EnablePartialRendering="true"></asp:ScriptManager>
<div>
Some Data Table<br />
<asp:UpdateProgress runat=server ID="upUpdateProgress1"
AssociatedUpdatePanelID="upUpdatePanel1"
Visible=true DisplayAfter=10>
<ProgressTemplate>
<span style="background-color:Silver;color:Green">Sorting....</span>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat=server ID="upUpdatePanel1">
<ContentTemplate>
<asp:GridView runat=server id="gvCustomers" AutoGenerateColumns=true
AllowSorting=true onsorting="gvCustomers_Sorting"></asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Notice the AssociatedUpdatePanelID which is set to the update panel , and notice the DisplayAfter property which specifies how many milliseconds from the beginning of the partial page update should this progress show itself.
In my sample i used the ProcessTemplate section which allows me to put any html content to be seen during a partial page update. That's the place to put an animation gif for instance.
Here are some notes you should remember when using this control:
1. If not provided with a AssociatedUpdatePanelID the UpdateProgress will show itself for every partial post back of any UpdatePanel on the page.
2. If provided with a non existing UpdatePanel ID, It will never show itself.
If you ask any C# developer for the features C# 2 has to offer the answers will be Generics, Anonymous functions , partial types and so on, That would be my answer to , but lately i needed something new which i didn't know exited in the .NET world up until now.
This new feature (well not so new :)) is called a Friend Assembly.
The use in this feature is not very common since the need for it is not common as well.
The motivation is as follow: Suppose you are building a solution and this solution contains many assemblies,
And suppose one of these assemblies contains some types with access modifier as internal.
If you wish to use this type functionality from some other assembly , you simply cannot.
If you need this types functionality because there is, lets say a logical group of assemblies that can share this functionality there is a solution. The solution is friend assemblies.
The solution is as follow, Lets say assembly A has the internal type we want to share to assembly B.
We need to add the following code to the assemblyinfo.cs of assembly A:
[assembly:InternalsVisiblieTo("AssemblyB")]
where AssemblyB is the name of the friend assembly.
Some notes:
1. The relationship of these 2 or 3 assemblies is not transitive nor it is symmetric.
So if Assembly C is a friend of Assembly B and B is a friend of A that C is not a friend of A.
In addition if B is a friend of A that A is not a friend of B.
2. This attribute is defined in the System.Runtime.CompilerServices
Enjoy.