Tuesday, December 28, 2010

Ajax Library – Event Handling

System.ComponentModel.EventHandlerList - to add custom events to an object


To add custom events to an object, you add an instance of Sys.EventHandlerList into another object and expose public methods off that object that manipulate the instance. (Table 2.5 details the methods we use to manipulate the Sys.EventHandlerList type.)

How to add a custom event.

For instance I have an array notes[]. When I add a note I want to add an event, that shows an alert. To do this
1. Create an instance of Sys.Event.HandlerList. This instance holds list of handlers with their associated events.

_events=new Sys.EventHandlerList();

_events.addHandler("noteadded", functionName);


addHandler method adds the event name and function name to be executed on raise of that event.


How to raise this custom event


For this whenever a note is added following code needs to be written


var handler= _events.getHandler("notedded");

If(handler!=null)

handler(this,Sys.EventArgs.Empty)


2. To pass arguments of your own you need to create a class and inherit from Sys.EventArgs
Example
NotebookNamespace.NoOfNotesEventArgs=function(numOfNotes)
{

This._noOfNotes=numOfNotes;
}
NotebookNamespace.NoOfNotesEventArgs.prototype= {

Get_noOfNotes : function()

{

return this.noOfNotes;

}
}
NotebookNamespace.NoOfNotesEventArgs.registerClass("NotebookNamespace.NoOfNotesEventArgs", Sys.EventArgs)

Another this worth mentioning here is Sys.UI.DomEvent.
The Sys.UI.DomEvent class provides cross-browser access to DOM element event properties and methods to work with DOM element events
Some familiar methods of this class are $addHandlers, clearHandlers, preventDefault etc

Example

Var btn=$get("button1");

$addHandler(btn,{"click":button1_clickHandler});

However this has a problem of maintaining scope. The example below will tell you what I mean.

<html>
<body>
<form id="form1" runat="server">
<input type="button" value="btnTest" id="test" />
<asp:ScriptManager ID="scrptMgr" runat="server" />
</form>
<script type="text/javascript">
MyObject = function() {
this._name = "Deepa";
};
MyObject.prototype = {
clickEventHandler: function(e) {
alert (this._name);
}
};
var myObject = new MyObject();
$addHandler($get("btnTest"), "click", myObject.clickEventHandler);
</script>
</body>
</html>

The code looks like it will alert "Deepa". But it alerts "undefined"

That is because when event handler clickEventHandler executes, this points to the testButton and not the class MyObject.
To correct this we use Delegate provided by Microsoft Ajax Library

To create the delegate, we use the Function.createDelegate method, as
follows:
var del = Function.createDelegate(<instance>, <methodName>);

In the evenHandler i.e. <methodName> here, this will refer to <instance>

Hence with below code, "Deepa" will be alerted when clickEventHandler is executed

var myObject = new MyObject();
var dele =Function.createDelegate(myObject, myObject.clickEventHandler);
$addHandler($get("btnTest"), "click", dele);

Tuesday, November 30, 2010

.Net Framework 4.0 – What’s new

What are the major improvements provided by the common language runtime and the base class libraries?

Brief about the Improvements -

Diagnostics and Performance - Starting with the .NET Framework 4, you can get processor usage and memory usage estimates per application domain. 

Garbage Collection - This feature replaces concurrent garbage collection in previous versions and provides better performance.

Code Contracts - Code contracts let you specify contractual information that is not represented by a method's or type's signature alone. The new System.Diagnostics.Contracts namespace contains classes that provide a language-neutral way to express coding assumptions in the form of preconditions, postconditions, and object invariants.

Design-Time-Only Interop Assemblies - You no longer have to ship primary interop assemblies (PIAs) to deploy applications that interoperate with COM objects. In the .NET Framework 4, compilers can embed type information from interop assemblies, selecting only the types that an application (for example, an add-in) actually uses.

Dynamic Language Runtime - The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework. 

Covariance and Contravariance - Several generic interfaces and delegates now support covariance and contravariance.

BigInteger and Complex Numbers - The new System.Numerics.BigInteger structure is an integer data type that can store fairly large number as it has no upper and lower bound values.Complex types represents a complex number of form a + bi. IT supports arithmetic and trigonometric operations with complex numbers.

Tuples - The .NET Framework 4 provides the System..::.Tuple class for creating tuple objects that contain structured data.

File System Enumeration Improvements - You can now enumerate directories and files by using methods that return an enumerable collection of strings of their names.ou can also use methods that return an enumerable collection of DirectoryInfo, FileInfo, or FileSystemInfo objects. 

Memory-Mapped Files - A memory-mapped file contains the contents of a file in virtual memory and is an application’s logical address space. So You can use memory-mapped files to edit very large files and to create shared memory for interprocess communication.

64-Bit Operating Systems and Processes - You can identify 64-bit operating systems and processes with the Environment.Is64BitOperatingSystem and Environment.Is64BitProcess properties.

Pasted from <http://www.dotnetcodes.com/dotnetcodes/code/Articles-55-Net-framework-40-major-improvements.aspx>

Monday, November 15, 2010

My 2 hour weekend experience after the weekend

My weekend is generally busier than the whole week. My lovely endearing little princess keeps me on my toes through out Saturday and Sunday. Actually she literally wants to be on my lap all the time.

I have already given up doing tasks that I consider NECESSARY, however to finish out "THE ABSOLUTELY NECESSARY" tasks of the day like brushing my teeth, taking bath etc I get up early on the weekend so that I am done by the time she is awake.

By being so demanding of me, she actually makes me feel so very special. All she wants is her MOMMMYYYY and I feel so loved so much wanted for and so nice :). And so Sunday night I am totally exhausted, my left forearm, the region near Ulna gets swollen and my feet are on fire.

No doubt the Monday blues get worse for me. And I really need lot of will to start for office. Today was no different "Monday" and my hubby down with fever adding to the "BLUES". On my way to office an inner voice told me hey Super Women (I consider all working mothers super women) you need a break too!!!! You deserve a VACATION. And I was like OKK!!!... but is there something that can give me a VACATION experience in 2 hrs (an affordable time I could be out of office)??.....Inner voice answers - A SUPERB SPA ......My heart jumped and my car took a left turn for the parlor.... A WOW Experience :).....

A message to all superb women ... Listen to your inner voice, find time for yourself and get a WOW experience :)

Thursday, September 23, 2010

Strategy Pattern

Recently I gave a session on Strategy pattern. There were variety of feedback saying creative, good for begginers, intersting, too short etc. So I though I should upload it and document it on my blog for people access :) ..

So here are the links

Presentation

Code

MVP Design pattern demo links

MVP demo code

Happy Learning

Wednesday, September 15, 2010

DbProviderFactories

DBProvider Factories
Using DBProviderFactories we can actually create a connection without knowing what is the underlying database.


Example DbProviderFactory provider = DbProviderFactories.GetFactory(providerName);The provider name can be placed in config file can have following



I can have a method
public IDbConnection ConnectionProvider(string providerName, string connectionString)
{
DbProviderFactory provider= DbProviderFactories.GetFactory(providerName);
IDbConnection connection=provider.CreateConnection();
connection.ConnectionString=connectionString;return connection
}

this method can be called as follows

IDbConnection connection1=ConnectionProvider(ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings[DATABASE_CONNECTION_CONFIG_KEY]].providerName, ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings[DATABASE_CONNECTION_CONFIG_KEY]].ConnectionString)

DATABASE_CONNECTION_CONFIG_KEY can be "SQLDatabaseConnection" for sql.
Similarly we can have different connection string and different key for Oracle or Access or any other database.

Have also posted the same on msdn community at
http://msdn.microsoft.com/en-us/library/system.data.common.dbproviderfactories.aspx

Friday, May 14, 2010

Url encoding. Problems while opening url with quotes in a different window.

Lately I faced an issue where I was passing a string through query string and the string had quotes and some other special characters. I had to open another modal window where i was supposed to load the new page. Due to quotes it gave me a javascript Error "Expected )".
At once I tried using Uri.EscapeDataString, Uri.EscapeUriString, and HttpUtility.UrlEncode and other similar functions available in c#.
My findings were as follows
original string is: Hello 'Deepa/Hari'
Then,Uri.EscapeDataString("Hello 'Deepa/Hari'") gives: Hello%20'Deepa2FHari'
Uri.EscapeUriString("Hello 'Deepa/Hari'") gives Hello%20'Deepa/Hari'
System.Web.HttpUtility.UrlEncode("Hello 'Deepa/Hari'") gives Hello+'Deepa2FHari'
System.Web.HttpUtility.UrlPathEncode("Hello 'Deepa/Hari'") gives Hello%20'Deepa/Hari'

However JScript.Net's function gives a full proof solution.
Microsoft.JScript.GlobalObject.escape("Hello 'Deepa/Hari'") gives Hello%20%27Deepa/Hari%27
Similarly to unescape, use Microsoft.JScript.GlobalObject.unescape() function.

Monday, May 3, 2010

Stopping a postback on client side with Ajax

Requirement was - on click of a button I wanted to get an alert and then based on logic i either wanted to do a postback or stop it.
Initial code
btn.onClientClick="return validate();"
Javascript code looked like this
function validate()
{
alert('some message');
if(some condition)
return true;
else
return false;
}
I had ajax post back on my button click which i wanted to stop when false is returned from validate function. But with above code it never posted back not even if the function returned true.
Ok! What went wrong
The code btn.OnClientClick = "return validate();" would get rendered as
input type="submit" onclick="return validate(); __doPostback(..)"
So what is happening is whether the javascript function returns true or false it doesnt matter, __doPostBack will never get called.
Lets now change it to make it work
btn.OnClientClick="if(!return validate()) return false;"
This renders
input type="submit" onclick=if(!validate()) return false; __doPostBack(..)"
So only when the validate() function returns false will it execute the first statement and will return from there else it will go to __doPostBack and cause a post back to happen.
Took me some time to figure this out and it just goes to prove that common sense is actually not so common ;-)

Thursday, March 11, 2010

Calling server side code from javascript

Found a good article on how to do this ... Posting some intercepts here
You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.
One option while using Microsoft ASP.NET AJAX is to call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more ‘integrated’ with our solution.

The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.

Example
C#
[System.Web.Services.WebMethod]
public static string GetContactName(string custid)
{
}
Javascript function calling server method
function CallMe(src,dest)
{
var ctrl = document.getElementById(src);
// call server side method
PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
}
//

And here's the source http://sappidireddy.wordpress.com/2008/03/31/how-to-call-server-side-function-from-client-side-code-using-pagemethods-in-aspnet-ajax/

Coffee time

Sometimes coffee time talks though very brief have lot of depth.... It generally starts with gossip but the climax rather take way is so wise that the gossip that started it even starts looking worth :D .... Not to miss on today's climax....When you have to choose between being smart or genuine, I would say genuine. Counting on no of people I met were smart, there were many but those who were genuine i could count on fingers... and that's when i occured that the latter is rare....And yea genuinely smart is rarer :) ..
With that note Shubraatri