Thursday, December 30, 2010

Generating Random Strings of Characters in SQL

The following Transact SQL procedure can be used to generate a random string of characters. As such it can be used to for example generate a default password for a user. The specific characters that are used to generate the string can be specified, so it can be customised (e.g. to only create passwords of digits or lower cased letters). The length of the generated random string can also be specified.

It is recommended that this SQL procedure be used as a stored procedure.

Using as a Stored Procedure


The following stored procedure creates a random string of characters of a length specified by the parameter @Length:
CREATE PROCEDURE sp_GeneratePassword
(
@Length int
)
AS
DECLARE @RandomID varchar(32)
DECLARE @counter smallint
DECLARE @RandomNumber float
DECLARE @RandomNumberInt tinyint
DECLARE @CurrentCharacter varchar(1)
DECLARE @ValidCharacters varchar(255)

SET @ValidCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+&$'

DECLARE @ValidCharactersLength int
SET @ValidCharactersLength = len(@ValidCharacters)
SET @CurrentCharacter = ''
SET @RandomNumber = 0
SET @RandomNumberInt = 0
SET @RandomID = ''
SET NOCOUNT ON
SET @counter = 1

WHILE @counter < (@Length + 1)
BEGIN
SET @RandomNumber = Rand()
SET @RandomNumberInt = Convert(tinyint, ((@ValidCharactersLength - 1) * @RandomNumber + 1))
SELECT @CurrentCharacter = SUBSTRING(@ValidCharacters, @RandomNumberInt, 1)
SET @counter = @counter + 1

SET @RandomID = @RandomID + @CurrentCharacter
END

SELECT @RandomID AS 'Password'
GO

Wednesday, December 15, 2010

Extension Methods

The .NET Framework employs the concept of sealed classes. A sealed class is a class that cannot be inherited from. But, what if we want to extend these classes? Based on the meaning of sealed it's not possible. Compound the technical inability to extend sealed classes with classes that are defined as the result of a LINQ query, called projections, and there is no opportunity to extend.

Another desire that class designers have is to avoid deep inheritance trees. Generally using inheritance to add a capability or two is undesirable because it leads to deep inheritance trees that are difficult to comprehend and maintain.


To overcome some of these challenges Microsoft introduced the extension method. Extension methods are defined in separate static classes as static methods and the first argument of the method is the extended type. The extended type—the first argument—is modified with the keyword this. Although an extension method is a static method in a static class, extension methods have member method semantics. That is, extension methods are called is if they were a member of the extended class, a regular member method.


Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.



Extension method are only in scope when you explicitly import the namespace into your source code with "using" directive.


namespace ExtensionMethods
{
public static class ExtensionsClass
{
public static string Reverse(this String strReverse)
{
char[] charArray = new char[strReverse.Length];
int len = strReverse.Length - 1;
for (int i = 0; i <= len; i++)
{
charArray[i] = strReverse[len - i];
}
return new string(charArray);
}
}
}

using ExtensionMethods;
protected void Page_Load(object sender, EventArgs e)
{
string str = "Hello Extension Methods";
string strReverse = str.Reverse();
}

Thursday, November 18, 2010

Finding Geolocation information from ip address in asp.net

Ip is the internet protocol for communication between nodes.

Ip is used to identify a host and address the location. If we need to identify the user

who are all accessing our website and store the ip address in our database is very simple and very easier.

This is the way to track the users ip address. Fetch a client's ip address as soon as he access our web site in asp.net.

Some of them may use a proxy ip address. But we can get their ip address with this simple code.

Add following namespace in page
using System.Net;

string ipAddress ="";

//Get the Host Name
string hostName = Dns.GetHostName();

//Get The Ip Host Entry
IPHostEntry ipHostEntry = Dns.GetHostEntry(hostName);

//Get The Ip Address From The Ip Host Entry Address List
IPAddress[] ipAddress = ipHostEntry.AddressList;

ipAddress = ipAddress[ipAddress.Length - 1].ToString();

To get the Geolocation of IP address you can use the various
API which would gives you result in various different format(csv,xml)

http://www.ipinfodb.com/ip_location_api.php

You can get Geolocation information from

http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false

Response comes in XML format. using xml deserialize, I deserialize the response.

[XmlRootAttribute(ElementName = "Response", IsNullable = false)]

public class IPLocator
{
private string longitude;
public string Longitude
{
get { return longitude; }
set { longitude = value; }
}

private string latitude;
public string Latitude
{
get { return latitude; }
set { latitude = value; }
}
private string zip;
public string Zip
{
get { return zip; }
set { zip = value; }
}

private string ip;
public string IP
{
get { return ip; }
set { ip = value; }
}
}

After deserialization IPLocater class bind All properties of requested IP Address.

Binding Class is return IPLocater class.

Code of IPDetals Class
public IPLocator GetData(string ipAddress)
{
IPLocator ipLoc = new IPLocator();
try
{
//apiKey can be generated from below link

//http://www.ipinfodb.com/ip_location_api.php

string apiKey = "anykey";
string path = "http://api.ipinfodb.com/v2/ip_query.php?key=" + apiKey + "&ip=" + ipAddress + "&timezone=false";

WebClient client = new WebClient();
string[] eResult = client.DownloadString(path).ToString().Split(',');

if (eResult.Length > 0)
ipLoc = (IPLocator)Deserialize(eResult[0].ToString());
}
catch
{ }

return ipLoc;
}

//Desrialize XML String
private Object Deserialize(String pXmlizedString)
{
XmlSerializer xs = new XmlSerializer(typeof(IPLocator));

MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));

XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

return xs.Deserialize(memoryStream);

}

//String to UTF8ByteArray

private Byte[] StringToUTF8ByteArray(String pXmlString)
{

UTF8Encoding encoding = new UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
}

//You can get the Geolocation infoamation here

string ipAddress = HttpContext.Current.Request.UserHostAddress;

IPDetails ipDetails=new IPDetails ();
IPLocator ipLocater = ipDetails.GetData(ipAddress);
Response.Write(ipLocater.CountryName);

Tuesday, October 26, 2010

Windows Communication Foundation in Framework 4.0

Windows Communication Foundation (WCF) provides the following improvements:

  • Configuration-based activation: Removes the requirement for having an .svc file.
  • System.Web.Routing integration: Gives you more control over your service's URL by allowing the use of extensionless URLs.
  • Multiple IIS site bindings support: Allows you to have multiple base addresses with the same protocol on the same Web site.
  • Routing Service: Allows you to route messages based on content.
  • Support for WS-Discovery: Allows you to create and search for discoverable services.
  • Standard endpoints: Predefined endpoints that allow you to specify only certain properties.
  • Workflow services: Integrates WCF and WF by providing activities to send and receive messages, the ability to correlate messages based on content, and a workflow service host.
  • WCF REST features:
    • Web HTTP caching: Allows caching of Web HTTP service responses.
    • Web HTTP formats support: Allows you to dynamically determine the best format for a service operation to respond in.
    • Web HTTP services help page: Provides an automatic help page for Web HTTP services, similar to the WCF service help page.
    • Web HTTP error handling: Allows Web HTTP Services to return error information in the same format as the operation.
    • Web HTTP cross-domain JavaScript support: Allows use of JSON Padding (JSONP).
  • Simplified configuration: Reduces the amount of configuration a service requires

WCF Architecture

The following figure illustrates the major components of WCF.


 
 

Contracts

Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

Service contracts

- Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

Data contract

- It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

Message Contract

- Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Policies and Binding

- Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

Service Runtime

- It contains the behaviors that occur during runtime of service.

  • Throttling Behavior- Controls how many messages are processed.
  • Error Behavior - Specifies what occurs, when internal error occurs on the service.
  • Metadata Behavior - Tells how and whether metadata is available to outside world.
  • Instance Behavior - Specifies how many instance of the service has to be created while running.
  • Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
  • Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.

Messaging

- Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

  • Transport Channels
    Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.
  • Protocol Channels
    Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

Activation and Hosting

- Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism

  • IIS
    Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
  • Windows Activation Service
    (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
  • Self-Hosting
    WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
  • Windows Service
    WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).

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/