Friday, October 15, 2010

Introducing $(document).ready()

This is the first thing to learn about jQuery: If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.
$(document).ready(function() {
// put all your jQuery goodness in here.
});

The $(document).ready() function has a ton of advantages over other ways of getting events to work. First of all, you don't have to put any "behavioral" markup in the HTML. You can separate all of your JavaScript/jQuery into a separate file where it's easier to maintain and where it can stay out of the way of the content. I never did like seeing all those "javascript:void()" messages in the status bar when I would hover over a link. That's what happens when you attach the event directly inside an <a href> tag.

On some pages that use traditional JavaScript, you'll see an "onload" attribute in the <body> tag. The problem with this is that it's limited to only one function. Oh yeah, and it adds "behavioral" markup to the content again. Jeremy Keith's excellent book, DOM Scripting, showed me how to create an addLoadEvent function to a separate JavaScript file that allows for multiple functions to be loaded inside it. But it requires a fair amount of code for something that should be rather straightforward. Also, it triggers those events when the window loads, which leads me to another advantage of $(document).ready().

With $(document).ready(), you can get your events to load or fire or whatever you want them to do before the window loads. Everything that you stick inside its brackets is ready to go at the earliest possible moment — as soon as the DOM is registered by the browser, which allows for some nice hiding and showing effects and other stuff immediately when the user first sees the page elements.

Tuesday, October 5, 2010

Endpoints: Address, Bindings, and Contracts

WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.

All the WCF communications are take place through end point. End point consists of three components which are known as ‘ABC’: ‘A’ for Address, ‘B’ for Binding and ‘C’ for Contracts.

Address


Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g

http://localhost/MyService/TestCalculator.svc

Binding


Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.

A binding has several characteristics, including the following:

  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.

  • Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).

  • Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability


The following table gives some list of protocols supported by WCF binding.











































BindingDescription
BasicHttpBindingBasic Web service communication. No security by default
WSHttpBindingWeb services with WS-* support. Supports transactions
WSDualHttpBindingWeb services with duplex contract and transaction support
WSFederationHttpBindingWeb services with federated security. Supports transactions
MsmqIntegrationBindingCommunication directly with MSMQ applications. Supports transactions
NetMsmqBindingCommunication between WCF applications by using queuing. Supports transactions
NetNamedPipeBindingCommunication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBindingCommunication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBindingCommunication between WCF applications across computers. Supports duplex contracts and transactions

Contract


Contracts specifies the info for how the service is implemented and what it offers. Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.

Example:


Endpoints will be mentioned in the web.config file on the created service.
<system.serviceModel>
<services>
      <service
        behaviorConfiguration="TestServiceBehavior">
       <endpoint
         address="http://localhost/MyService/TestCalculator.svc" contract="ITestService"
          binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Thursday, September 30, 2010

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service.The main feature of WCF is it's security.
WCF = Web services + .Net Remoting + MSMQ + (COM+)
















































FeaturesWeb ServiceWCF
HostingIt can be hosted in IISIt can be hosted in IIS,

windows activation service (WAS),

Self-hosting,

Managed Windows service
Programming[WebService] attribute has to be added to the class[ServiceContraact] attribute has to be added to the class
Model[WebMethod] attribute represents the method exposed to client[OperationContract] attribute represents the method exposed to client
OperationOne-way, Request- Response are the different operations supported in web serviceOne-Way, Request-Response, Duplex are different type of operations supported in WCF
XMLSystem.Xml.serialization name space is used for serializationSystem.Runtime.Serialization namespace is used for serialization
EncodingXML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, CustomXML 1.0, MTOM, Binary, Custom
TransportsIt Can be accessed only over HTTPCan be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
ProtocolsSecuritySecurity, Reliable messaging, Transactions

Thursday, September 16, 2010

Delegates

Delegates is also known as Type Safe pointer.

To understand type Safe Pointer, you need to understand call back function used in C++. Call back function is generally implemented in Business Tier in 3-tier architecture. Once business logic is implemented, it requires memory address of the function or method to use it. This memory address does not have any information of Method signature, so it can be called as it is not Type Safe.

But Delegates has the feature of callback in Safe way, as it take cares of signature information.

How to define delegate,

Public Delegate Sub MakeDelegate (ByVal EmployeeID As String)

We are declaring public delegate, so it can be accessed from anywhere in the application.

Here we are going to define a Employee class which uses the delegates and method.
Public Class Employee
    Public FirstName As String
    Public LastName As String
 
    Public Sub ValidEmployee (ByVal objDelegate As MakeDelegate, _
                                ByVal EmployeeID As String)
        If EmployeeID.StartsWith ("MKT") Then
            objDelegate.Invoke(EmployeeID)
        End If
    End Sub
End Class

The method ValidEmployee is going to accept the EmployeeID and a Delegate Object of type "MakeDelegate" as the parameters and validate whether it is a Starting with E1 and invoke the Delegate Object accordingly.

Dim objEmployee As Employee = New Employee()

        Dim objDelegate As MakeDelegate
        objDelegate = AddressOf NotifyEmployee
 
        objEmployee .FirstName = txtFirstName.Text
        objEmployee.LastName = txtLastName.Text
 

objEmployee.ValidateEmployee(objDelegate, txtEmployeeID.Text)

We assign the local procedure "NotifyEmployee", which is declared and defined inside the Windows Form Class to the Delegate Object.
Private Sub NotifyEmployee(ByVal EmployeeID As String)

MsgBox("This Employee is from Marketing Department") End Sub

Once we assign the instance of the Delegate, we must provide the address of a method implementation with a matching method signature.

Serialization in the .NET Framework

Serialization in .NET allows the programmer to take an instance of an object and convert it into a format that is easily transmittable over the network, or even stored in a database or file system. This object will actually be an instance of a custom type, including any properties or fields you may have set.

The first step in any serialization process is to take the instance of the object and convert it to a memory stream. From there we have the ability to perform any number of operations with (file IO, database IO, etc.).

There are 2 types of serialization. Binary serialization and xml serialization

Core Serialization Methods

#region Binary Serializers

public static System.IO.MemoryStream SerializeBinary(object request) {

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =

new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

System.IO.MemoryStream memStream = new System.IO.MemoryStream();

serializer.Serialize(memStream, request);

return memStream;

}



public static object DeSerializeBinary(System.IO.MemoryStream memStream) {

memStream.Position=0;

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer =

new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

object newobj = deserializer.Deserialize(memStream);

memStream.Close();

return newobj;

}

#endregion


#region XML Serializers
 
public static System.IO.MemoryStream SerializeSOAP(object request) {
  System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer =
  new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
  System.IO.MemoryStream memStream = new System.IO.MemoryStream();
  serializer.Serialize(memStream, request);
  return memStream;
}
 
public static object DeSerializeSOAP(System.IO.MemoryStream memStream) {
  object sr;
  System.Runtime.Serialization.Formatters.Soap.SoapFormatter deserializer =
  new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
  memStream.Position=0;
  sr = deserializer.Deserialize(memStream);
  memStream.Close();
  return sr;
}
#endregion

Wednesday, February 24, 2010

Making XAMPP (Apache) work with IIS

Port 80, and Apache (in my case) to run on Port 81 (and SSL running on Port 4499):

C:\xampp\apache\conf\httpd.conf:

  • Search for “Listen 80″, change to “Listen 81″

  • Search for “ServerName localhost:80″, change to “ServerName localhost:81″


C:\xampp\apache\conf\extra\httpd-ssl.conf

  • Search for “Listen 443″, change to “Listen 4499″

  • Search for “<VirtualHost _default_:443>”, change to “<VirtualHost _default_:4499>”

  • Search for “ServerName localhost:443″, change to “ServerName localhost:4499″


Then, you should be able to start Apache successfully through the XAMPP control panel.

Try using81 port.

http://localhost:81/xampp/

Friday, December 25, 2009

Making URL rewriting on IIS 7 works like IIS 6

what is URL rewriting ?

URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource. When performing URL rewriting, typically the URL being requested is checked and, based on its value, the request is redirected to a different URL.

Making URL rewriting  on IIS7?

Upgrading to IIS 7 should be rather transparent, unfortunately that is not the case when it comes to URL rewriting as we knew it from IIS 6. In IIS 6 all we had to do was to add a wildcard mapping making sure that all requests went through the ASPNET ISAPI process. After this was done, one could create a global.asax file that would either pass requests directly through or rewrite the URL based on an internal algorithm.

1) Start by opening the IIS Manager and selecting your website.

2) Now enter the "Handler Mappings" section

3) Notice the "StaticFile" handler. Currently it's set to match * and catch both File and Directory requests. If you look back at the first image, you'll notice that the error message details that the handler causing the 404 error is the StaticFile handler. As I know that all my static files will have a file extension (also I don't care for directory browsing), I'll simply change my StaticFile handler so it only matches *.* - and only files.

What needs to be done now is that we need to map any and all requests to the aspnet_isapi.dll isapi file - just like we would usually do in IIS 6.

Add a new Script Map to the list of Handler Mappings and set it up like this:

The aspnet_isapi.dll file cannot be used as a Handler for websites running in the new IIS 7 Integrated Mode, thus we will need to make our website run in classic .NET mode. Right click your website node in the IIS Manager and select Advanced Settings. Select the "Classic .NET AppPool" and close the dialog boxes:

"Failed to Execute URL", what a great descriptive error. Fortunately you won't have to spend hours ripping out hair... As I have already done that - at least I'll save a trip or two to the barber.

The problem is that the static files are being processed by the aspnet_isapi.dll file instead of simply sending the request along to the StaticFile handler. If you click the "View Ordered List..." link in the IIS Manager from the Handler Mappings view, you'll see the order in which the handlers are being executed for each request:

When you add a new Script Map it'll automatically get placed at the very top of the line taking precedence over any other handlers, including the StaticFile one.

What we have to do is to move our Wildcard handler to the very bottom, below the StaticFile handler. By letting the StaticFile handler have precedence over our Wildcard handler we ensure that any static files (matching *.*) gets processed correctly while any other URL's gets passed along to our own Wildcard handler that'll do the URL rewriting and make business work as usual: