Monday, August 30, 2010

Bubble Event

When a child control pass its event to the parent. It is called even Bubbling. It happens with DataGrid, DataList, and Repeater.

Problem
If an element and one of its ancestors have an event handler for the same event, which one should fire first? Element1 is outer element and element2 is inner. Means elemnt1 is parent of element2.

-----------------------------------
| element1 |
| ------------------------- |
| |element2 | |
| ------------------------- |
| |
-----------------------------------

Ans : This depends on the browser.

Suppose you have an element inside an element and both have an onClick event handler. If the user clicks on element2 he causes a click event in both element1 and element2. But which event fires first?

Back in the bad old days Netscape and Microsoft came to different conclusions.

* Netscape said that the event on element1 takes place first. This is called event capturing.
* Microsoft maintained that the event on element2 takes precedence. This is called event bubbling.

Internet Explorer only supports event bubbling. Mozilla, Opera 7 and Konqueror support both.

W3C has very sensibly decided to take a middle position in this struggle. Any event taking place in the W3C event model is first captured until it reaches the target element and then bubbles up again.

| | / \
-----------------| |--| |-----------------
| element1 | | | | |
| -------------| |--| |----------- |
| |element2 \ / | | | |
| -------------------------------- |
| W3C event model |
------------------------------------------

You, the web developer, can choose whether to register an event handler in the capturing or in the bubbling phase. This is done through the addEventListener() method explained on the Advanced models page. If its last argument is true the event handler is set for the capturing phase, if it is false the event handler is set for the bubbling phase.

Turning it off
You can turn off buuble event on window level or control level.

In the Microsoft model you must set the event’s cancelBubble property to true.

window.event.cancelBubble = true

In the W3C model you must call the event’s stopPropagation() method.

e.stopPropagation()

This stops all propagation of the event in the bubbling phase. Stopping event propagation in the capturing phase is impossible. One wonders why.

For a complete cross-browser experience do

function doSomething(e)
{
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}

Setting the cancel Bubble property in browsers that don’t support it doesn’t hurt. The browser shrugs and creates the property. Of course it doesn’t actually cancel the bubbling, but the assignment itself is safe.

Example :- The best example of event Bubbling we see in Grid with check boxes. Just like in gmail. If click on check box it select the row if click anywhere else in the row it fires the click event of grid. While you have clicked on check box two event should be fired one is check change and other one is selectedindexchange for grid but only one fired why? since they have made event bubling false for this column or check box.

Sunday, August 29, 2010

From Authentication

Forms Authentication is a mechanism to allow only authenticated user with valid credential to view a particular page or group of pages/folders and stop unauthenticated or anonymous user outside the secure boundary.

Forms authentication uses an authentication ticket that is created when a user logs on to a site, and then it tracks the user throughout the site. The forms authentication ticket is usually contained inside a cookie.

However, ASP.NET version 2.0 supports cookieless forms authentication, which results in the ticket being passed in a query string.

Forms authentication processing is handled by the FormsAuthenticationModule class, which is an HTTP module that participates in the regular ASP.NET page-processing cycle. This document explains how forms authentication works in ASP.NET 2.0.

There are two very important features of a Security System that we should formally define, one of which I've already mentioned a number of times in the article:

# Authentication answers the question "Who is the caller?"
# Authorization answers the question, "Does the caller have the right to access this Web method?"

Authentication - Authentication is the means by which you obtain the Identity of the User by validating their credentials against a known Authority, ie: Active Directory, Database Store, Microsoft Passport Account etc. If the credentials can't be validated then the Authentication process fails and the User will assume the Identity of IUSR_Anonymous. Remember that the Web is anonymous by nature, so the only way to determine who a particular visitor is to authenticate them by having them provide user credentials (a username/password, usually).

Authorization - Authorization occurs after Authentication and involves using information obtained during the Authentication process to determine whether to grant or deny access to a given resource based on that Users role in the Application. That is, if you are trying to access a Web page that only a particular user can access, the first step performed is to authenticate you - who is this guy making the request? - and then, based on that authentication, you must be authorized to view the particular data you are requesting.

ASP.NET 2.0 defines a set of HTTP modules in the machine-level Web.config file. These include a number of authentication modules as shown here:

<httpmodules>
...
<add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule">
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule">
<add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule">
...
</add>

Only one authentication module is used for each request.The authentication module that is used depends on which authentication mode has been specified by the authentication element, usually in the Web.config file in the application's virtual directory.

The FormsAuthenticationModule class is activated when the following element is in the Web.config file.

<authentication mode="Forms">

Set the Web Config file for Form Authentication. You can define multiple config file in different directories for a single applcation.

By default it is set for window change it to Form.

</authentication></add></add></httpmodules>
<system.web>
<authentication mode="Forms">
<forms cookieless="UseDeviceProfile" defaulturl="default.aspx" enablecrossappredirects="false" loginurl="Login.aspx" name=".ASPXAUTH" path="/" protection="All" requiressl="false" slidingexpiration="true" timeout="30">
</forms>
</authentication>

</system.web>

The default attribute values are described below:

* loginUrl is the name of the page where user will be redirected when they will try to enter into secure page/folders of the website.

* protection is set to All to specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.

Possible values are :- All,Encription,None,Validation

*timeout* is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.

* name and path are set to the values defined in the application's configuration file.By default its value is .ASPXFORMSAUTH.

* requireSSL is set to false. This configuration means that authentication cookies can be transmitted over channels that are not SSL-encrypted. If you are concerned about session hijacking, you should consider setting requireSSL to true.

* slidingExpiration is set to true to enforce a sliding session lifetime. This means that the session timeout is periodically reset as long as a user stays active on the site.
* defaultUrl is the name of the page where user will be redirected by default after they are logging in from home page or not secured page.
* cookieless is set to UseDeviceProfile to specify that the application use cookies for all browsers that support cookies. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL.

Possible values for Cookieless

* UseCookies. This value forces the FormsAuthenticationModule class to use cookies for transmitting the authentication ticket.
* UseUri. This value directs the FormsAuthenticationModule class to rewrite the URL for transmitting the authentication ticket.
* UseDeviceProfile. This value directs the FormsAuthenticationModule class to look at the browser capabilities. If the browser supports cookies, then cookies are used; otherwise, the URL is rewritten.
* AutoDetect. This value directs the FormsAuthenticationModule class to detect whether the browser supports cookies through a dynamic detection mechanism. If the detection logic indicates that cookies are not supported, then the URL is rewritten.


* enableCrossAppRedirects is set to false to indicate that forms authentication does not support automatic processing of tickets that are passed between applications on the query string or as part of a form POST.


Credentials

passwordFormat : Format the password will be stored in. Valid values include Clear, SHA1, and MD5. SHA1 and MD5 are both hashing algorithms that make storing passwords in the Web.config more secure.

User : This is the area to store the username and password. You can secure the passwords by running the HashPasswordForStoringInConfigFile function to get the hashed password. I will demonstrate this later.

Authorization

Deny | Allow : This section allows us to deny or allow users to the site. ? = anonymous/unauthenticated users and * means all users. This section also allows us to specify certain users, and allow or deny permissions.

Create a Ticket
DataRow [] rows = dSet.Tables[0].Select( " UserName = '" + userName+ "' AND Password = '" + password + "'" );

// record validated

if (rows.Length > 0)

{

// get the role now

string roles = rows[0][ "Roles" ].ToString();

// Create forms authentication ticket

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (

1, // Ticket version

userName, // Username to be associated with this ticket

DateTime .Now, // Date/time ticket was issued

DateTime .Now.AddMinutes(50), // Date and time the cookie will expire

rememberUserName, // if user has chcked rememebr me then create persistent cookie

roles, // store the user data, in this case roles of the user

FormsAuthentication .FormsCookiePath); // Cookie path specified in the web.config file in tag if any.

// To give more security it is suggested to hash it

string hashCookies = FormsAuthentication .Encrypt(ticket);

HttpCookie cookie = new HttpCookie ( FormsAuthentication .FormsCookieName, hashCookies); // Hashed ticket

// Add the cookie to the response, user browser

Response.Cookies.Add(cookie);

// Get the requested page from the url

string returnUrl = Request.QueryString[ "ReturnUrl" ];

// check if it exists, if not then redirect to default page

if (returnUrl == null ) returnUrl = "~/Default.aspx" ;

Response.Redirect(returnUrl);
}

Friday, August 27, 2010

String, StringBuilder and StringBuffer

StringBuilder object is mutable while String object is Immutable.

Mutable - Value can be change.
Immutable - Value can not be change.

It means when we store any thing in string we can not change its value. But It works fine when we do it. Actually a new String object is created internally to do the changes.

But this is not the case with StringBuilder, that's why String Builder is fast than String in case of append.

String sName= "Khaleek";
sName = sName + "Ahmad";


StringBuilder sbName= new StringBuilder();
sbName.Append("Ahmad");

Result would be same but second block of code will be fast.

StringBuffer and StringBuilder

StringBuffer is synchronized(Means it is thread safe) and StringBuilder is asynchronyzed(It is not thread safe.)

So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.

Thursday, August 19, 2010

Magic Tables

While using triggers Inserted & Deleted tables
(called as magic tables) will be created automatically.

We can not see these tables in the data base. But we can access these
tables from the "TRIGGER" only.

update () and columns_updated() functions can
be used to determine the changes being caused by the DML
statements.

Note that the Magic Table does not contain the information
about the columns of the data-type text, ntext, or image.
Attempting to access these columns will cause an error.

When we insert any record then that record will be added
into this Inserted table initially, similarly while
updating a record a new entry will be inserted into
Inserted table & old value will be inserted into Deleted
table.

In the case of deletion of a record then it will insert
that record in the Deleted table

Example ( How use Magic Tables in Trigger)

CREATE TRIGGER LogMessage
ON EMP
FOR INSERT
AS
DECLARE @EMPNAME varchar(50)
SELECT @EMPNAME= (SELECT EMPNAME FROM INSERTED)
INSERT INTO LOGTABLE(UserId,Message) values (@EMPNAME,'Record Added')
GO

Tuesday, August 17, 2010

Talk to God

Once Moosa (AS) asked Allah Ta'ala: O Allah! You have granted me the honor and privilege of talking to you directly, Have you given this privilege to any other person? Allah Ta'ala replied, O!! Moosa during the last period I am going to send an ummat, who will be the Ummat of Mohammed (SAW) with dry lips, parched tongues, emaciated body with eyes sunken deep into their sockets, with livers dry and stomachs suffering the pangs of hunger- will call out to me (in dua) they will be much closer to me than you O Moosa! while you speak to me there are 70000 veils between you and me but at the time of iftaar there will not be a single veil between me and the fasting Ummati of Mohammed (SAW) O!! Moosa I have taken upon myself the responsibility that at the time of iftaar I will never refuse the dua of a fasting person!

Monday, August 9, 2010

Ues of Would

Would

Would is an auxiliary verb, a modal auxiliary verb. We use would mainly to:

* talk about the past
* talk about the future in the past
* express the conditional mood

We also use would for other functions, such as:
* expressing desire, polite requests and questions, opinion or hope, wish and regret...

We cannot say:
I would to like coffee.

Correct
I would like coffee.

Be careful! Would and had have the same short form 'd:
He'd finished. (He had finished.)
He'd like coffee. (He would like coffee.)

would: Talking about the past

We often use would as a kind of past tense of will or going to:

* Even as a boy, he knew that he would succeed in life.
* I thought it would rain so I brought my umbrella.
* She said that she would come. (NOT She said that she would to come.)

Using would as as a kind of past tense of will or going to is common in reported speech:

* She said that she would buy some eggs. ("I will buy some eggs.")
* The candidate said that he wouldn't increase taxes. ("I won't increase taxes.")
* Why didn't you bring your umbrella? I told you it would rain! ("It's going to rain.")

Questions and negatives are made without do.

* Would you like to come with me? (NOT Do you would like to come with me?)
* He wouldn’t come. (NOT He don’t would come.)

We often use would not to talk about past refusals:

* He wanted a divorce but his wife would not agree.
* Yesterday morning, the car wouldn't start.

We sometimes use would (rather like used to) when talking about habitual past behaviour:

* Every weekday my father would come home from work at 6pm and watch TV.
* Every summer we'd go to the seaside.
* Sometimes she'd phone me in the middle of the night.
* We would always argue. We could never agree.
* The old man would sit in a corner and talk to himself for hours.
* She would always bring us nice little gifts.

He used to be a chain smoker. (NOT He would be a chain smoker.)

The above sentence means that he is not a chain smoker at the moment, but he used to smoke a lot at some point in the past.

would: Future in past

When talking about the past we can use would to express something that has not happened at the time we are talking about:

* In London she met the man that she would one day marry.
* He left 5 minutes late, unaware that the delay would save his life.

would: Conditionals

We often use would to express the so-called second and third conditionals:

* If he lost his job he would have no money.
* If I had won the lottery I would have bought a car.

Using the same conditional structure, we often use would when giving advice:

* I wouldn't eat that if I were you.
* If I were in your place I'd refuse.
* If you asked me I would say you should go.

Sometimes the condition is "understood" and there does not have to be an "if" clause:

* Someone who liked John would probably love John's father. (If someone liked John they would probably love John's father.)
* You'd never know it. (for example: If you met him you would never know that he was rich.)
* Why don't you invite Mary? I'm sure she'd come.

would: Desire or inclination

* I'd love to live here.
* Would you like some coffee?
* What I'd really like is some tea.

would: Polite requests and questions

* Would you open the door, please? (more polite than: Open the door, please.)
* Would you go with me? (more polite than: Will you go with me?)
* Would you know the answer? (more polite than: Do you know the answer?)
* What would the capital of Nigeria be? (more polite than: What is the capital of Nigeria?)

would: Opinion or hope

* I would imagine that they'll buy a new one.
* I suppose some people would call it torture.
* I would have to agree.
* I would expect him to come.
* Since you ask me I'd say the blue one is best.

would: Wish

* I wish you would stay. (I really want you to stay. I hope you will stay.)
* They don't like me. I'm sure they wish I'd resign.

would: Presumption or expectation

* That would be Jo calling. I'll answer it.
* We saw a police helicopter overhead yesterday morning. | Really? They would have been looking for those bank robbers.

would: Uncertainty

* He would seem to be getting better. (less certain than: He seems to be getting better.)
* It would appear that I was wrong. (less certain than: It appears that I was wrong.)

would: Derogatory

* They would say that, wouldn't they?
* John said he didn't steal the money. | Well, he would, wouldn't he?
would that: Regret (poetic/rare) - with clause

This rare, poetic or literary use of would does not have the normal structure:

* Would that it were true! (If only it were true! We wish that it were true!)
* Would that his mother had lived to see him become president.

Some More

I would like some advice. (NOT I would to like some advice.)
She said that she would come. (NOT She said that she would to come.)
Would you like to come with me? (NOT Do you would like to come with me?)
He wouldn’t come. (NOT He don’t would come.)
Direct speech: She said, ‘I will come.’
Indirect speech: She said that she would come.
Would you move a bit? (More polite than ‘Will you move a bit?’)
Would you mind opening the window? (More polite than ‘Will you mind opening the window?)

Saturday, August 7, 2010

Remoting

.Net Remoting is a technology for communication between different application domain. Application domain can happen inside the same process, between processes on a single system , or processes on different systems.

Different technologies can be used for communication with a client and a server application.

1) Web Services
2) Remoting

Remote Objects

A Remote object is an object that is running on the server.Basically any object outside the application domain of the caller application should be considered remote, where the object will be reconstructed. Local objects that cannot be serialized cannot be passed to a different application domain, and are therefore non remotable.

Any object can be changed into a remote object by deriving it from MarshalByRefObject, or by making it serializable either by adding the [Serializable] tag or by implementing the ISerializable interface.

Types of .NET Remotable Objects
There are three types of objects that can be configured to serve as .NET remote objects. You can choose the type of object depending on the requirement of your application.

1) Single Call

Single Call objects service one and only one request coming in. Single Call objects are useful in scenarios where the objects are required to do a finite amount of work. Single Call objects are usually not required to store state information, and they cannot hold state information between method calls.

Singleton Objects

Singleton objects are those objects that service multiple clients, and hence share data by storing state information between client invocations. They are useful in cases in which data needs to be shared explicitly between clients, and also in which the overhead of creating and maintaining objects is substantial.

Client-Activated Objects (CAO)

Client-activated objects (CAO) are server-side objects that are activated upon request from the client. When the client submits a request for a server object using a "new" operator, an activation request message is sent to the remote application. The server then creates an instance of the requested class, and returns an ObjRef back to the client application that invoked it. A proxy is then created on the client side using the ObjRef. The client's method calls will be executed on the proxy. Client-activated objects can store state information between method calls for its specific client, and not across different client objects. Each invocation of "new" returns a proxy to an independent instance of the server type.

Domains

In .NET, when an application is loaded in memory, a process is created, and within this process, an application domain is created. The application is actually loaded in the application domain. If this application communicates with another application, it has to use Remoting because the other application will have its own domain, and across domains, object cannot communicate directly. Different application domains may exist in same process, or they may exist in different processes.

Contexts

The .NET runtime further divides the application domain into contexts. A context guarantees that a common set of constraints and usage semantics govern all access to the objects within it. All applications have a default context in which objects are constructed, unless otherwise instructed. A context, like an application domain, forms a .NET Remoting boundary. Access requests must be marshaled across contexts.

Proxies

When a call is made between objects in the same Application Domain, only a normal local call is required; however, a call across Application Domains requires a remote call. In order to facilitate a remote call, a proxy is introduced by the .NET framework at the client side. This proxy is an instance of the TransparentProxy class, directly available to the client to communicate with the remote object. Generally, a proxy object is an object that acts in place of some other object. The proxy object ensures that all calls made on the proxy are forwarded to the correct remote object instance. In .NET Remoting, the proxy manages the marshaling process and the other tasks required to make cross-boundary calls. The .NET Remoting infrastructure automatically handles the creation and management of proxies.

Marshaling

Marshalling (similar to serialization) is the process of transforming the memory representation of an object to a data format suitable for storage or transmission. It is typically used when data must be moved between different parts of a computer program or from one program to another.

• Marshal-by-value (MBV):- In this, the object is serialized into the channel, and a
copy of the object is created on the other side of the network. The object to marshal is stored into a stream, and the stream is used to build a copy of the object on the other side with the unmarshalling sequence.

• Marshaling-by-reference (MBR):- Here it creates a proxy on the client that is used to communicate with the remote object. The marshaling sequence of a remote object creates an ObjRef instance that itself can be serialized across the network.
Objects that are derived from “MarshalByRefObject” are always marshaled by reference. All our previous samples have classes inherited from “MarshalByRefObject”

To marshal a remote object the static method RemotingServices.Marshal() is

used.RemotingServices.Marshal () has following overloaded versions:-

Public static ObjRef Marshal (MarshalByRefObject obi)
Public static ObjRef Marshal (MarshalByRefObject obi, string objUri)
Public static ObjRef Marshal (MarshalByRefObject obi, string objUri,
Type requested Type)

Channels

The .NET Remoting infrastructure provides a mechanism by which a stream of bytes is sent from one point to the other (client to server etc.). This is achieved via a channel. Strictly speaking, it is a class that implements the IChannel interface. There are two pre-defined .NET Remoting channels existing in System.Runtime.Remoting.Channels, the TcpChannel and the HttpChannel. To use the TcpChannel, the server must instantiate and register the TcpServerChannel class, and the client, the TcpClientChannel class.

Channel selection is subject to the following rules:

* At least one channel must be registered with the remoting framework before a remote object can be called. Channels must be registered before objects are registered.
* Channels are registered per application domain. There can be multiple application domains in a single process. When a process dies, all channels that it registers are automatically destroyed.
* It is illegal to register the same channel that listens on the same port more than once. Even though channels are registered per application domain, different application domains on the same machine cannot register the same channel listening on the same port. You can register the same channel listening on two different ports for an application domain.
* Clients can communicate with a remote object using any registered channel. The remoting framework ensures that the remote object is connected to the right channel when a client attempts to connect to it. The client is responsible for calling the RegisterChannel on the ChannelService class before attempting to communicate with a remote object.

Serialization Formatters

.NET Remoting uses serialization to copy marshal-by-value objects, and to send reference of objects which are marshal-by-reference, between application domains. The .NET Framework supports two kinds of serialization: binary serialization and XML serialization.

Formatters are used for encoding and decoding the messages before they are transported by the channel. There are two native formatters in the .NET runtime, namely binary (System.Runtime.Serialization.Formatters.Binary) and SOAP (System.Runtime.Serialization.Formatters.Soap). Applications can use binary encoding where performance is critical, or XML encoding where interoperability with other remoting frameworks is essential.

A key point to remember is that .NET Remoting always uses binary serialization, but you have your choice of output formats. The type of serialization (binary or XML) determines what object data is output. The formatter determines the format in which that data is stored.

The data in binary format has smaller size then in XML format. The smaller size makes binary formatting the obvious choice for intranet applications or whenever network performance is critical. However, not all firewalls look kindly on binary formatted data, so if you're distributing an application that needs to use Remoting over the Internet, you might find yourself forced to use SOAP formatting. Another benefit of SOAP formatting is that it's human readable, which gives you the opportunity to examine message traffic for debugging. Fortunately, Remoting works exactly the same regardless of which formatter you use, so you can use SOAP formatting during initial development and debugging, and then convert to binary format for production release.

Followers

Link