RSS

Monthly Archives: February 2011

Developing Web Services Using PHP

A web service consists of a server to serve requests to the web service and a client to invoke methods on the web service. The PHP class library provides the SOAP extension to develop SOAP servers and clients and the XML-RPC extension to create XML-RPC servers and clients. Before I delve further into developing web services with PHP, I shall briefly discuss web services.

Introduction to Web Services

A web service is a software system designed for interoperable interaction over a network. A web service is defined with a WSDL (Web Services Description Language) document, and other systems interact with the web service using SOAP messages, transferred using HTTP with an XML serialization. A web service is an abstract resource that provides a set of functions and is implemented by an agent, which sends and receives messages. A provider entity provides the functionality of a web service with a provider agent and a requester entity uses the web service functionality with a requester agent. Web services implement various technologies, some of which are XML, SOAP, and WSDL. XML is a standard format for data exchange. Web service requests and responses are sent as XML messages. The elements and attributes that may be specified in an XML document are specified in an XML Schema. SOAP provides a standard framework for packaging and exchanging XML messages. WSDL is an XML document in the http://schemas.xmlsoap.org/wsdl/ namespace for describing a web service as a set of endpoints operating on messages. A WSDL document specifies the operations (methods) provided by a web service and the format of the XML messages.

Installing the PHP Web Services Extensions

The SOAP and XML-RPC extensions are packaged with the PHP 5 installation. The SOAP extension and the XML-RPC extension are not enabled by default in a PHP installation. To enable the SOAP and XML-RPC extensions add the following extension directives in the php.ini configuration file.

extension=php_xmlrpc.dll
extension=php_soap.dll

Restart the Apache 2 server to activate the SOAP and XML-RPC extensions. The SOAP extension supports subsets of the SOAP 1.1, SOAP 1.2, and WSDL 1.1 specifications.

Creating a SOAP Web Service

After activating the SOAP extension in the PHP configuration file, a SOAP server and a SOAP client may be created using the SOAP PHP class library. A SOAP server serves web service requests and a SOAP client invokes methods on the SOAP web service. The SOAP library provides various functions for creating a SOAP server and a SOAP client. Some of the commonly used SOAP functions are discussed in Table 1.

Table 1. SOAP functions

Method Description
SoapServer->__construct( mixed wsdl [, array options] ) Creates a SoapServer object. The wsdl parameter specifies the URI of the WSDL. SoapServer options such as SOAP version may be specified in the options array.
SoapServer->addFunction( mixed functions ) Adds one or more PHP functions that will handle SOAP requests. A single function may be added as a string. More than one function may be added as an array.
SoapServer->fault() SoapServer fault indicating an error.
SoapServer->getFunctions() Returns a list of functions.
SoapServer->handle() Processes a SOAP request, invokes required functions and sends back a response.
SoapServer->setClass(string class_name [, mixed args [, mixed ...]] ) Sets the class that will handle SOAP requests. Exports all methods from the specified class. The args are used by the default class constructor.
SoapHeader->__construct() Creates a SOAP header.
SoapClient->__soapCall( string function_name, array arguments [, array options [, mixed input_headers [, array &output_headers]]] ) Invokes a SOAP function.
SoapClient->__doRequest() Performs a SOAP request.
SoapClient->__getFunctions() Returns a list of SOAP functions.
SoapClient->__getTypes() Returns a list of SOAP types.

Creating a SOAP Server

Before we create a SOAP server we need to create a WSDL document defining the web service. The WSDL document defines the operations that the web service provides. I will create an example web service that provides an operation getCatalogEntry, which returns a catalog entry for a catalog ID. A WSDL is an XML document in the http://schemas.xmlsoap.org/wsdl/ namespace. Some of the elements of a WSDL document are discussed in Table 2.

Table 2. WSDL elements

Element Description
definitions Root element of a WSDL document.
types Specifies data type definitions for the messages exchanged by the web service. XML Schema is the recommended type system.
message Defines the data being transmitted. A message consists of one or more parts. A part is associated with a type.
portType Defines a set of operations and the input-output messages for each operation.
operation An action (method) supported by the service. Each operation consists of input and output messages.
input Specifies a message format for the request.
output Specifies a message format for the response.
binding Defines message format and protocol details for operations and messages for a particular portType.
service Specifies a group of ports.
port Defines an endpoint by associating an address with a binding.

Next, create a WSDL document for the example web service. The example WSDL document, catalog.wsdl, defines message elements getCatalogRequest and getCatalogResponse for the request and response messages. In the WSDL document define a portType, CatalogPortType, for the getCatalogEntry operation that returns a catalog entry as a HTML string for a string catalogId. Define a binding, CatalogBinding, for the getCatalogEntry operation and the input output messages. The soap:binding element specifies that the binding is bound to the SOAP protocol format. The soap:operation element specifies information for the operation. The soap:body element specifies how the message parts appear inside the SOAP Body element. Define a service CatalogService that consists of a port, CatalogPort, which is associated with the CatalogBinding binding. The soap:address element specifies the URI of an address. The catalog.wsdl WSDL document is listed below.

<?xml version ='1.0' encoding ='UTF-8' ?> 
<definitions name='Catalog' 
  targetNamespace='http://example.org/catalog' 
  xmlns:tns=' http://example.org/catalog ' 
  xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/' 
  xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
  xmlns:soapenc='http://schemas.xmlsoap.org/soap/
  encoding/' 
  xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/' 
  xmlns='http://schemas.xmlsoap.org/wsdl/'> 

<message name='getCatalogRequest'> 
  <part name='catalogId' type='xsd:string'/> 
</message> 
<message name='getCatalogResponse'> 
  <part name='Result' type='xsd:string'/> 
</message> 

<portType name='CatalogPortType'> 
  <operation name='getCatalogEntry'> 
    <input message='tns:getCatalogRequest'/> 
    <output message='tns:getCatalogResponse'/> 
  </operation> 
</portType> 

<binding name='CatalogBinding' type=
'tns:CatalogPortType'> 
  <soap:binding style='rpc' 
    transport='http://schemas.xmlsoap.org/soap/http'
  /> 
  <operation name='getCatalogEntry'> 
    <soap:operation soapAction='urn:localhost-catalog#
    getCatalogEntry'/> 
    <input> 
      <soap:body use='encoded' namespace=
      'urn:localhost-catalog' 
        encodingStyle='http://schemas.xmlsoap.org/soap
       /encoding/'/> 
    </input> 
    <output> 
      <soap:body use='encoded' namespace=
   'urn:localhost-catalog' 
        encodingStyle='http://schemas.xmlsoap.org/soap/
    encoding/'/> 
    </output> 
  </operation> 
</binding> 

<service name='CatalogService'> 
  <port name='CatalogPort' binding=
  'CatalogBinding'> 
    <soap:address location='http://localhost/
    soap-server.php'/> 
  </port> 
</service>
</definitions>

Copy the catalog.wsdl document to the C:\Apache2\htdocs directory, the directory in which PHP scripts are run. Create a PHP script, soap-server.php, to define the operations provided by the CatalogService web service. In the soap-server.php script define a function getCatalogEntry() that takes a catalogId as an argument and returns a string consisting of an HTML document. The HTML document string returned comprises of the catalog entry for the specified catalogId.

 

 

function getCatalogEntry($catalogId) { 
  if($catalogId=='catalog1')
          return "<HTML> … </HTML>";
elseif ($catalogId='catalog2')
return "<HTML>…</HTML>";

}

The WSDL cache is enabled by default. Disable the WSDL cache by setting the soap.wsdl_cache_enabled configuration option to 0.

ini_set("soap.wsdl_cache_enabled", "0");

Create a SoapServer object using the catalog.wsdl WSDL.

$server = new SoapServer("catalog.wsdl");

Add the getCatalogEntry function to the SoapServer object using the addFunction() method. The SOAP web service provides the getCatalogEntry operation.

$server->addFunction("getCatalogEntry");

Handle a SOAP request.

$server->handle();

The soap-server.php script is listed below.

<?php 
function getCatalogEntry($catalogId) { 
  if($catalogId=='catalog1')

return "<HTML>
 <HEAD>
  <TITLE>Catalog</TITLE>
 </HEAD
 <BODY>
<p> </p>
 <table border>
<tr><th>CatalogId</th>
<th>Journal</th><th>Section
</th><th>Edition</th><th>
Title</th><th>Author</th>
</tr><tr><td>catalog1</td>
<td>IBM developerWorks</td><td>
XML</td><td>October 2005</td>
<td>JAXP validation</td>
<td>Brett McLaughlin</td></tr>
</table>
</BODY>
</HTML>";

elseif ($catalogId='catalog2')

return "<HTML>
 <HEAD>
  <TITLE>Catalog</TITLE>
 </HEAD
 <BODY>
<p> </p>
 <table border>

<tr><th>CatalogId</th><th>
Journal</th><th>Section</th>
<th>Edition</th><th>Title
</th><th>Author
</th></tr><tr><td>catalog1
</td><td>IBM developerWorks</td>
<td>XML</td><td>July 2006</td>
<td>The Java XPath API
</td><td>Elliotte Harold</td>
</tr>
</table>
</BODY>
</HTML>";
} 

ini_set("soap.wsdl_cache_enabled", "0"); 
$server = new SoapServer("catalog.wsdl"); 
$server->addFunction("getCatalogEntry"); 
$server->handle(); 

?>

In the next section, I will create a SOAP client to send a request to the SOAP server.

Creating a SOAP Client

Create a PHP script, soap-client.php, in the C:\Apache2\htdocs directory. In the PHP script, create a SOAP client using the SoapClient class. The WSDL document, catalog.wsdl, is specified as an argument to the SoapClient constructor. The WSDL document specifies the operations that are available to the SOAP client.

$client = new SoapClient("catalog.wsdl");

Specify the catalogId for which a catalog entry is to be retrieved. Invoke the getCatalogEntry method of the SOAP web service.

$catalogId='catalog1';
$response = $client->getCatalogEntry($catalogId);

Output the response to the browser.

echo $response;

The soap-client.php script is listed below.

<?php  
  $client = new SoapClient("catalog.wsdl");
  $catalogId='catalog1';
  $response = $client->getCatalogEntry($catalogId);
  echo $response;
?>

Invoke the soap-client.php PHP script with the URL http://localhost/soap-client.php.The catalog entry for the catalog1 catalogId gets output as shown in Figure 1.

Invoking the SOAP client
Figure 1. Invoking the SOAP client

 

 

Creating an XML-RPC Web Service

XML-RPC is a specification and a set of implementations designed for applications to make remote procedure calls over the network. The remote procedure calls are made using HTTP as the transport and XML as the encoding.

Structure of an XML-RPC Request and Response

An XML-RPC message is an HTTP-POST request. The request body is in XML format. The request is sent to an XML-RPC server, which runs some business logic and returns a response in the form of XML. An example XML-RPC request is listed below.

POST /php/xmlrpc-server.php HTTP/1.0
User-Agent: Example Client
Host: localhost
Content-Type: text/xml
Content-length: 190

<?xml version="1.0"?>
<methodCall>
   <methodName>getCatalog</methodName>
   <params>
      <param>
         <value><string>catalog1
         </string></value>
         </param>
      </params>
   </methodCall>

The URI in the header, /php/xmlrpc-server.php specifies the server URI to which the request is sent. The HTTP version is also specified. The User-Agent and Host are required to be specified. The Content-Type is text/xml and the Content-Length specifies the content length.

The request body is in XML with root element as methodCall. The methodCall element is required to contain a sub-element methodName which specifies the name of the method to be invoked as a string. If the XML-RPC request has parameters, the methodCall element contains sub-element params. The params element contains one or more param elements. Each of the param elements contains a value element. The param value may be specified as a string, a Boolean, a four-byte signed integer, double-precision signed, floating point number, date/time, or base-64 encoded binary. The sub-element of value in which a param value is specified is different for different value types. If a type is not specified the default type is string. The sub-elements for the value types are listed in Table 3.

Table 3. Value elements

Value Type Element
ASCII String <string>
Four-byte signed integer <i4> or <int>
Boolean <boolean>
Double-precision signed or floating point number. <double>
Date/time <dateTime.iso8601>
Base-64 encoded binary. <base64>

A param value may also be of type <struct>. A <struct> element consists of <member> elements. Each <member> element contains a <name> element and a <value> element. An example of struct value is listed below.

<struct>
   <member>
      <name>catalogId</name>
      <value><string>catalog1
      </string></value>
      </member>
   <member>
      <name>journal</name>
      <value><string>IBM developerWorks
      </string></value>
      </member>
   </struct>

A value element in a member element may be of any of the param data types including struct. A param type may also be of type <array>. An <array> element consists of of a <data> element, which consists of one or more <value> elements. An example of an <array> param value is listed below.

<array>
   <data>
      <value><i4>1</i4></value>
      <value><string>IBM developerWorks
      </string></value>
      <value>XML</value>
      <value><string>Introduction to dom4j
      </string></value>
      <value><string>Deepak Vohra</string
      ></value>
      </data>
   </array>

A <value> element in a <data> element may consist of any of the data types including struct and array. The server response to an XML-RPC request is in the format of XML. An example response is listed below.

HTTP/1.1 200 OK
Connection: close
Content-Length: 190
Content-Type: text/xml
Date: 
Server: Example Server

<?xml version="1.0"?>
<methodResponse>
   <params>
      <param>
         <value><string>Introduction 
         to SQLXML</string></value>
         </param>
      </params>
   </methodResponse>

If an error has not occurred, the server response returns “200 OK.” The Connection header specifies the state of the connection after the response is completed. For non-persistent connection the Connection header value is “close.” The Content-Type is text/xml. The response body is in XML format with root element as methodResponse. The methodResponse element consists of a single <params> element, which consists of a single <param> element. The <param> element contains a single <value> element.

Instead of a <params> element a methodResponse element may also consists of a single <fault> element. The <fault> element contains a <value> element, which contains a <struct> element with two <member> elements faultCode of type integer and faultString of type string. An example of a XML-RPC server response with a <<fault> element is listed below.

HTTP/1.1 200 OK
Connection: close
Content-Length: 190
Content-Type: text/xml
Date: 
Server: Example Server

<?xml version="1.0"?>
<methodResponse>
   <fault>
      <value>
         <struct>
            <member>
               <name>faultCode</name>
               <value><int>4</int
               ></value>
               </member>
            <member>
               <name>faultString</name>
               <value><string>No such Method.
               </string></value>
               </member>
            </struct>
         </value>
      </fault>
   </methodResponse>

Creating an XML-RPC Server

The PHP XML-RPC extension is a PHP implementation of the XML-RPC specification. The XML-RPC PHP class library provides functions to create a XML-RPC server and invoke methods on the server. Some of the commonly used XML-RPC functions are discussed in Table 4.

Table 4. XML-RPC PHP functions

Function
Description
xmlrpc_server_create ()
Creates an XML-RPC server
xmlrpc_encode_request ( string method, mixed params [, array output_options] )
Generates XML for a method request or response. Returns a string or FALSE on error.
xmlrpc_encode ( mixed value )
Generates XML for a PHP variable.
xmlrpc_decode_request ( string xml, string &method [, string encoding] )
Decodes XML into PHP. Returns an array.
xmlrpc_get_type ( mixed value )
Returns XML-RPC data types, for example “struct”, “int”, “string”, “base64” for a PHP value.
xmlrpc_set_type ( string &value, string type )
Sets xmlrpc type, base64, or datetime for a PHP string value. Returns True or False on error.
xmlrpc_server_register_method ( resource server, string method_name, string function )
Registers PHP function to a web service method. The method_name value is the same as the value of the methodName element in the XML-RPC request.
xmlrpc_server_call_method ( resource server, string xml, mixed user_data [, array output_options] )
Parses XML request and invokes method. Returns result of method call. The user_data parameter specifies any application data for the method handler function. The output_options parameter specifies a hashed array of options for generating response XML. The following options may be specified. output_type: Specifies output data type; “php” or “xml”. Default data type is “xml”. If output type is “php” other values are ignored. verbosity: Specifies compactness of generated message.escaping: Specifies if and how to escape some characters.version: Specifies version of XML to use. Value may be “xmlrpc”, “soap 1.1” and “simple”. Version may also be set to “auto”, which specifies to use the version the request came in. encoding: Specifies the encoding of the data. Default is “iso-8859-1”.Example value of the output_options parameter is as follows.$output_options = array( “output_type” => “xml”, “verbosity” => “no_white_space”, “escaping” => array(“markup”, “non-ascii”, “non-print”), “version” => “xmlrpc”, “encoding” => “utf-8” );
xmlrpc_is_fault ( array arg )
Determines if an array value represents XML-RPC fault.
xmlrpc_server_destroy ( resource server )
Destroys a server resource.
 

 

Create a PHP script, xmlrpc-webservice.php, in the C:/Apache2/htdocs directory. In the PHP script, define a function, hello_func. Any function that is invoked by a client is required to take three parameters: the first parameter is the name of the XML-RPC method invoked. The second parameter is an array containing the parameters sent by the client. The third parameter is the application data sent in the user_data parameter of the xmlrpc_server_call_method() function. In the hello_func function, retrieve the first parameter, which is a name sent by the client, and output a Hello message.

function hello_func($method_name, $params, $app_data)
{
$name = $params[0];
return "Hello $name.";
}

Create an XML-RPC server using the xmlrpc_server_create() method.

$xmlrpc_server=xmlrpc_server_create();

If a server does not get created the xmlrpc_server_create method returns FALSE. Register the hello_func function with the server using the xmlrpc_server_register_method method. The first argument to the xmlrpc_server_register_method method is the XML-RPC server resource. The second argument is name of the method that is provided by the web service, which is the <methodName> element value in a XML-RPC request. The third argument is the PHP function to be registered with the server.

$registered=xmlrpc_server_register_method 
($xmlrpc_server, "hello", "hello_func" );

If the PHP function gets registered, the xmlrpc_server_register_method returns TRUE.

Creating an XML-RPC Client

Next, I shall create a XML-RPC client to send a request to the XML-RPC server. First, specify the XML string to be sent in the request.

$request_xml = <<< END
<?xml version="1.0"?>
<methodCall>
    <methodName>hello</methodName>
      <params>
        <param>
          <value>
            <string>Deepak</string>
          </value>
        </param>
      </params>
<methodCall>
END;

To escape XML in PHP, <<<END ….END; is used. An XML document demarker other END may also be used. The methodCall element specifies the web service method that is to be invoked. Invoke the web service method using the xmlrpc_server_call_method function. The first argument to the xmlrpc_server_call_method function is the server resource. The second argument is the string containing the XML-RPC request. The third argument is the application data that is sent to the third parameter of the method handler function.

$response=xmlrpc_server_call_method( $xmlrpc_server, 
$request_xml, '', array(output_type => "xml"));

Output the XML-RPC response from the server.

print $response;

The PHP script, xmlrpc-webservice.php, is listed below.

<?php
function hello_func($method_name, $params, $app_data)
{
$name = $params[0];
return "Hello $name.";
}

$xmlrpc_server=xmlrpc_server_create();
$registered=xmlrpc_server_register_method 
($xmlrpc_server, "hello", "hello_func" );

$request_xml = <<< END
<?xml version="1.0"?>
<methodCall>
    <methodName>hello</methodName>
      <params>
        <param>
          <value>
            <string>Deepak</string>
          </value>
        </param>
      </params>
</methodCall>
END;
$response=xmlrpc_server_call_method( $xmlrpc_server, 
$request_xml, '', array(output_type => "xml"));
print $response;
?>

Copy the xmlrpc-webservice.php script to the C:/Apache2/htdocs directory. Invoke the PHP script with the URL http://localhost/xmlrpc-webservice.php. The response from the server gets output to the browser as shown in Figure 2.

Response From XML-RPC Web Service
Figure 2. Response from XML-RPC web service

To demonstrate an error in the request, returned as a <fault> element in the response XML, make the request XML not valid XML. For example replace </methodCall> with <methodCall> in the $request_xml. Invoke the xmlrpc-webservice.php. The response from the server is returned as a <fault> element that consists of a struct element value, which consists of faultCode and faultString members, as shown in Figure 3.

Response As fault Element
Figure 3. Response as fault element

References

For more information, see W3C’s WSDL page and SOAP Primer.

Deepak Vohra is a NuBean consultant and a web developer.

http://onlamp.com/pub/a/php/2007/07/26/php-web-services.html

Advertisements
 
1 Comment

Posted by on February 26, 2011 in PHP

 

Implementation Generic Singleton in C#

The last singleton implementation I am going to go over is a generic singleton. This implementation is very similar to the last except that it now uses generics syntax to create a singleton of any class. This does not however prevent the class T from being created by itself. So this implementation has the benefit of being used as is but has the downfall of not being able to force strict control over the singleton.
class GenericSingleton<T> where T : class, new()
{
private static T instance; 

public static T GetInstance()
{
lock (typeof(T))
{
if (instance == null)
{
instance = new T();
}
return instance;
}
}
}

To use this you simply would use a piece of code like below, assuming you have the class AutoFactory defined. AutoFactory’s constructor would also not be able to take parameters in this implementation.

AutoFactory autoF = GenericSingleton<AutoFactory>.GetInstance();

This should give a decent understanding of the singleton pattern and how to implement it using C#. Please post any questions in the comments.

 
Leave a comment

Posted by on February 26, 2011 in Design Pattern

 

Implementing the Singleton Pattern in C#

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don’t allow any parameters to be specified when creating the instance – as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily – i.e. that the instance isn’t created until it is first needed.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should be used.

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing – if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn’t known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

Note that all of these implementations also use a public static property Instance as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.

First version – not thread-safe

// Bad code! Do not use!
public sealed class Singleton
{
    static Singleton instance=null;

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn’t guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version – simple thread-safety

public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance==null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time – by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine – wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version – attempted thread-safety using double-check locking

// Bad code! Do not use!
public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                lock (padlock)
                {
                    if (instance==null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

  • It doesn’t work in Java. This may seem an odd thing to comment on, but it’s worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn’t ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
  • Without any memory barriers, it’s broken in the ECMA CLI specification too. It’s possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it’s safe, but I’d rather not rely on those stronger semantics, especially if there’s any doubt as to the safety. Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can’t agree exactly which barriers are required. I tend to try to avoid situations where experts don’t agree what’s right and what’s wrong!
  • It’s easy to get wrong. The pattern needs to be pretty much exactly as above – any significant changes are likely to impact either performance or correctness.
  • It still doesn’t perform as well as the later implementations.

Fourth version – not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

As you can see, this is really is extremely simple – but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

  • It’s not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers – they’re unlikely to bite you, but it’s worth being aware of the consequences of static constructors which refer to each other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn’t marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don’t have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit. I now have a discussion page with more details about this issue. Also note that it affects performance, as discussed near the bottom of this article.

One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)

Fifth version – fully lazy instantiation

public sealed class Singleton
{
    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class’s private members, the reverse is not true, hence the need for instance to be internal here. That doesn’t raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Performance vs laziness

In many cases, you won’t actually require full laziness – unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it’s probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a (relatively) significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. (See below for more on performance, however.)

Exceptions

Sometimes, you need to do work in a singleton constructor which may throw an exception, but might not be fatal to the whole application. Potentially, your application may be able to fix the problem and want to try again. Using type initializers to construct the singleton becomes problematic at this stage. Different runtimes handle this case differently, but I don’t know of any which do the desired thing (running the type initializer again), and even if one did, your code would be broken on other runtimes. To avoid these problems, I’d suggest using the second pattern listed on the page – just use a simple lock, and go through the check each time, building the instance in the method/property if it hasn’t already been successfully built.

Thanks to Andriy Tereshchenko for raising this issue.

A word on performance

A lot of the reason for this page stemmed from people trying to be clever, and thus coming up with the double-checked locking algorithm. There is an attitude of locking being expensive which is common and misguided. I’ve written a very quick benchmark which just acquires singleton instances in a loop a billion ways, trying different variants. It’s not terribly scientific, because in real life you may want to know how fast it is if each iteration actually involved a call into a method fetching the singleton, etc. However, it does show an important point. On my laptop, the slowest solution (by a factor of about 5) is the locking one (solution 2). Is that important? Probably not, when you bear in mind that it still managed to acquire the singleton a billion times in under 40 seconds. That means that if you’re “only” acquiring the singleton four hundred thousand times per second, the cost of the acquisition is going to be 1% of the performance – so improving it isn’t going to do a lot. Now, if you are acquiring the singleton that often – isn’t it likely you’re using it within a loop? If you care that much about improving the performance a little bit, why not declare a local variable outside the loop, acquire the singleton once and then loop. Bingo, even the slowest implementation becomes easily adequate.

I would be very interested to see a real world application where the difference between using simple locking and using one of the faster solutions actually made a significant performance difference.

Conclusion (modified slightly on January 7th 2006)

There are various different ways of implementing the singleton pattern in C#. A reader has written to me detailing a way he has encapsulated the synchronization aspect, which while I acknowledge may be useful in a few very particular situations (specifically where you want very high performance, and the ability to determine whether or not the singleton has been created, and full laziness regardless of other static members being called). I don’t personally see that situation coming up often enough to merit going further with on this page, but please mail me if you’re in that situation.

My personal preference is for solution 4: the only time I would normally go away from it is if I needed to be able to call other static methods without triggering initialization, or if I needed to know whether or not the singleton has already been instantiated. I don’t remember the last time I was in that situation, assuming I even have. In that case, I’d probably go for solution 2, which is still nice and easy to get right.

Solution 5 is elegant, but trickier than 2 or 4, and as I said above, the benefits it provides seem to only be rarely useful.

(I wouldn’t use solution 1 because it’s broken, and I wouldn’t use solution 3 because it has no benefits over 5.)

 

Referenced by: http://www.yoda.arachsys.com/csharp/singleton.html

 
Leave a comment

Posted by on February 26, 2011 in Design Pattern

 

Khmer MessageBox

This is a new library that I have developed for Khmer Developer who have some problem for developing Khmer Application with MessageBox, so It’s can help Khmer Developer as 70% because it’s look the same as Message box in Visual Studio about 60% too.

 

Quick Tour:

using cMessageDialog;

for showing message only:

cMessageBox.Show(“[Message Text]”, “[Caption]”, cButtons.OK, cIcon.Warnning);

for showing confirm message:

if(cMessageBox.Show(“[Message Text]”, “[Caption]”, cButtons.YesNo, cIcon.Warnning) == cDialogResult.Yes)

{

// Your code here;

}

Download Sourcecode and dll :

http://sourceforge.net/projects/cmessage-dialog/

 
Leave a comment

Posted by on February 25, 2011 in C#, Window Application

 

Embedded Image Resources

If you use images in a .NET application, chances are you will find it more convenient to embed those images as resources in your project, rather than leaving them as separate files and trying to locate and load the images from disk when the application runs.

 

Add Image Resource

To add an image to your project as an embedded resource:

  1. In Visual Studio, click the Project menu, and select Add Existing Item. Find and select the image you want to add to your project.
  2. In the Solution Explorer window, right-click the image file you just added to your project, and select Properties from the popup menu. The Properties tool window appears.
  3. In the Properties window (see picture below), change the Build Action property to Embedded Resource.
  4. Build the project. The image will be compiled into your project’s assembly.

Load Image Resource

Be sure to include the following namespaces in your project:

using System.IO;
using System.Reflection;

To load the image resource programmatically, use the following code:

Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream myStream = myAssembly.GetManifestResourceStream( "MyNamespace.SubFolder.MyImage.bmp" );
Bitmap bmp = new Bitmap( myStream );

Resource Path

The trickiest part of loading an embedded resource is getting the correct path. A resource path takes this form:

<namespace>.<subfolders>.<image name>.<extension>

where:

  • namespace is the namespace for the project
  • subfolders is the folder path within the project, with each folder separated by a period instead of a slash
  • image name is the name of the image file
  • extension is the image file extension (for example, “bmp” or “jpg”)

Important: Unlike Windows file paths, embedded resource paths are case sensitive.

For example, the About24.png image file is stored in the Art\A subfolder under the main .NET development project. In this case, the path would be “MyNamespace.Art.A.About24.png”.

Show All Embedded Resources

If you’re having trouble determining the correct path, you can always add the following code to show the paths of all embedded resources:

Assembly myAssembly = Assembly.GetExecutingAssembly();
string[] names = myAssembly.GetManifestResourceNames();
foreach (string name in names)
{
    Console.WriteLine( name );
}

Referrenced by: http://www.csharp411.com/embedded-image-resources/

 

 
Leave a comment

Posted by on February 24, 2011 in C#, Window Application

 

Crystal report with Dynamic Column

The objective of this article is to provide a process which can be followed to develop a crystal report with dynamic columns using parameterized column fields and formula fields. Before going for this the developer has to decide the maximum number of columns he/she has to display and as per the no. of columns the size of the paper. The developer can define the size of the paper by selecting Printer Setup in File menu.

There are two ways to display the columns in Crystal Report dynamically. The default is using the infamous Cross Tab component and the other is using parameterized columns. But there are certain limitations to this . Where the cross tab does not provide complete control to each individual cells value, for using dynamic columns, the developer has to decide the maximum no columns in design time and all the field values should be of same data type.

Lets take an example of an yearly report where the developer has to create  such a report , when executed will display only those month values as columns , which are selected with “Total” immediately next . So the view may look like :

If the sales of products selected from Mar 2006 to May 2006.

 

Product Name Mar Apr May Total
Pro 1 12 89 90 191
Pro 2 20 99 70 199
Grand Total 32 188 160 390

Same way if the end results for different scenario :

  1. If date is between Jan 2006 – Aug 2006
    Product Name  Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Total
  2. If date is between Jun 2006 – Nov 2006
    Product Name  Jun  Jul  Aug  Sep  Oct  Nov  Total

Note : These instructions only work if all the attribute fields are of the same data type as they will be dynamically interchanged using a logic statement.

It seems most of the attribute fields will be of a String data type. We can create formulas in our report that will convert numbers to text using the ToText function. Then, simply use the formula instead of the database field. Or, if our organization uses Views or Queries as data source, convert the data type on that end.

Steps to create a report with dynamic columns…

1) Determine the maximum number of columns the report page can handle. Or determine the reasonable number of attributes an end user would want to see. (Consider a report with 50 columns of attributes. It would be unreadable.)

2) Create a string parameter for every attribute column on the report. Do not set the default values at this time (see next step).

3) Open Note Pad (on your desktop under accessories). Type all possible attributes starting in top right corner with one below the other (see below).

None
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
Total

Keep in mind, these will be listed in the pick list and displayed on the report as column headings. The value “None” is important. It will be used in a logic statement, later in these instructions. Save the file (as a text file, .txt) in a shared location all users of the report can access (or on the CE server if using Enterprise).

Name the file similar to the .rpt file name combined with the word “attributes” or “parameter” so it is easy to locate.

4) Edit each parameter created in step 2 and do the following:

Click on “Set default values”.

Click on “Import pick list”.

Browse to locate the text file you just created in step 3.

Click OK. The list is automatically populated with the values in the text file.

5) Create empty formulas for the detail fields. The Design will look something like this…

Row Num Product name {?Month1} {?Month2} {?Month3}{?Month4}……………………{?Total}
{rownum} {db.ProdName}
{@mon.1-Detail} {@Mon.2-Detail} {@Mon.3-Detail}………….{@Total-Detail}

Just use the Insert Fields box and create the formulas up front. Leave them empty. Place them on the Design Tab. Then use the Insert Fields box to edit them later.

6) Edit the Mon.1-Detail field. Enter the following logic…

(assuming the Stored Proc or View returning column names as ProdName Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)

if {?Month1}= “JAN” then {DB.JAN}
else if {?Month1}= “FEB” then {DB.FEB}
else if {?Month1}= “MAR” then {DB.MAR}
else if {?Month1}= “APR” then {DB.APR}
else if {?Month1}= “MAY” then {DB.MAY}
else if {?Month1}= “JUN” then {DB.JUN}
else if {?Month1}= “JUL” then {DB.JUL}
else if {?Month1}= “AUG” then {DB.AUG}
else if {?Month1}= “SEP” then {DB.SEP}
else if {?Month1}= “OCT” then {DB.OCT}
else if {?Month1}= “NOV” then {DB.NOV}
else if {?Month1}= “DEC” then {DB.DEC}
—— add the total field value if applicable
else 0;

Save the formula changes, but don’t exit the formula editor. Copy the entire logic statement, then exit.

7) Edit {@Mon.2-Detail}. Paste the logic statement from step 6 into the Formula editor. Use Find/Replace in the formula Editor to find “?Month1” and replace with “?Month2”.

Then save the change. Repeat this process for the remaining column detail formulas.

Note: Incase of Total field it will start from the second field onwards. So to display the Total value add the line below (incase if second column will be counted as the total column)

else if {?Month2}= “Total” then {@Month_Det1}

Same way for all other columns also add …..

else if {?Month3}= “Total” then {@Month_Det1} + {@Month_Det2} If 3rd will be the Total column

else if {?Month4}= “Total” then {@Month_Det1} + {@Month_Det2} + {@Month_Det3} if 4th col will be the Total and so on..

8) You may also want to add conditional formatting to supress the columns that are not used. To do this you need to edit each field in the column (header and detail).

Start with Column 1’s heading…

Right click on the parameter field, {?Column 1}.
Select Format field.
On the Common tab find Supress at the top.

Go to the right and click on the “X+2” button. Enter the following logic in the Format formula editor:

if {?Month1}=”None” then true else false;

Save, but don’t close. Copy the statement. Close the Format formula editor.

Repeat on the {@Month.1-Detail} field using the pasted statement.

Repeat on the remaining columns, but remember to change the column number in the logic.

9) To add a running total for each column select a new running total field as display below

Select the parameterized field to sum up and and in the type of summary field select Sum from the dropdown.

Repeat the same process for all the columns as displayed above and also suppress them as per the condition (Refer Sec 8 to make a conditional suppress).

How it works :

1) The column heading will display the parameter value selected by the user. It will display just as you typed it into the default value list when creating the parameter.

Example :

In the example below I am displaying the records of references  during the month of Aug and Sep 2006 including the total and grand total value.

Select Aug for the month1 parameter field

Repeat it to select Sep for month2 parameter field and Total for month3 field . And select From Date and To date as 1st Aug 2006  – 30th Sep 2006.

2) The detail section will display the corresponding attributes for each item record based on the parameter values provided at run time.

On execution of this report it will display like the below

Contribution by: Kishore Gandra , Sarika Pahurkar , Edmond Joseph

Referenced by:

 
1 Comment

Posted by on February 23, 2011 in Crystal Report

 

Puting Form in Panel in C#

I am trying to add a Form into a Panel in .NET 2003:

Form2 ff2 = new Form2();
panel2.Controls.Add(ff2);

But it failed in runtime which said I could not add a top control into another control.
Can I have any way to add a Form into a Panel? Need I modify any property of the Form to make it not a “top control”?

 

Set the toplevel property to false.

 

Referenced by: http://bytes.com/topic/c-sharp/answers/267797-can-i-add-form-into-panel

 
Leave a comment

Posted by on February 21, 2011 in C#, Window Application