Tuesday, 24 April 2012

Binding in WCF Services ?


Windows Communication Foundation (WCF) separates how the software for an application is written from how it communicates with other software. Bindings are used to specify the transport, encoding, and protocol details required for clients and services to communicate with each other. WCF uses bindings to generate the underlying wire representation of the endpoint, so most of the binding details must be agreed upon by the parties that are communicating. The easiest way to achieve this is for clients of a service to use the same binding that the endpoint for the service uses. For more information about how to do this, see Using Bindings to Configure Windows Communication Foundation Services and Clients.

A binding is made up of a collection of binding elements. Each element describes some aspect of how the endpoint communicates with clients. A binding must include at least one transport binding element, at least one message-encoding binding element (which the transport binding element can provide by default), and any number of other protocol binding elements. The process that builds a runtime out of this description allows each binding element to contribute code to that runtime.

WCF provides bindings that contain common selections of binding elements. These can be used with their default settings or you can modify those default values according to user requirements. These system-provided bindings have properties that allow direct control over the binding elements and their settings. You can also easily work side-by-side with multiple versions of a binding by giving each version of the binding its own name. For details, see Configuring System-Provided Bindings.

If you need a collection of binding elements not provided by one of these system-provided bindings, you can create a custom binding that consists of the collection of binding elements required. These custom bindings are easy to create and do not require a new class, but they do not provide properties for controlling the binding elements or their settings. You can access the binding elements and modify their settings through the collection that contains them. For details, see Custom Bindings.


To specify in code to use the BasicHttpBinding for the service :

1. Define a service contract for the type of service.


[ServiceContract]
public interface ICalculator
{
   [OperationContract]
   double Add(double n1, double n2);
   [OperationContract]
   double Subtract(double n1, double n2);
   [OperationContract]
   double Multiply(double n1, double n2);
   [OperationContract]
   double Divide(double n1, double n2);
}


2. Implement the service contract in a service class.

public class CalculatorService : ICalculator
{
   public double Add(double n1, double n2)
   {
      return n1 + n2;
   }
   public double Subtract(double n1, double n2)
   {
      return n1 - n2;
   }
   public double Multiply(double n1, double n2)
   {
      return n1 * n2;
   }
   public double Divide(double n1, double n2)
   {
      return n1 / n2;
   }
} 


3. In the hosting application, create the base address for the service and the binding to use with the service.

// Specify a base address for the service

String baseAddress = "http://localhost/CalculatorService";
// Create the binding to be used by the service.

BasicHttpBinding binding1 = new BasicHttpBinding();

4. Create the host for the service, add the endpoint, and then open the host.
using(ServiceHost host = new ServiceHost(typeof(CalculatorService)))
{
    host.AddServiceEndpoint(typeof(ICalculator),binding1, baseAddress);



    host.Open();
}    

To modify the default values of the binding properties ;

To modify one of the default property values of the BasicHttpBinding class, set the property value on the binding to the new value before creating the host. For example, to change the default open and close timeout values of 1 minute to 2 minutes, use the following.
TimeSpan modifiedCloseTimeout = new TimeSpan(00, 02, 00);
binding1.CloseTimeout = modifiedCloseTimeout;
If you dont want to add the service endpoint using code behind, then you can usethe Configuration method of defining service binding in web.config file as below
Create a Web.config file to configure an endpoint for the CalculatorService that uses the WSHttpBinding.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name=" CalculatorService" >
        <endpoint 
        <-- Leave the address blank to be populated by default-->
        <--from the hosting environment,in this case IIS, so -->
        <-- the address will just be that of the IIS Virtual -->
        <--Directory.-->
            address="" 
        <--Specify the binding type -->
            binding="wsHttpBinding"
        <--Specify the binding configuration name for that -->
        <--binding type. This is optional but useful if you  -->
        <--want to modify the properties of the binding. -->
        <--The bindingConfiguration name Binding1 is defined  -->
        <--below in the bindings element.  -->
            bindingConfiguration="Binding1"
            contract="ICalculator" />
      </service>
    </services>
    <bindings>
      <wsHttpBinding>
        <binding name="Binding1">
          <-- Binding property values can be modified here. -->
          <--See the next procedure. -->
        </binding>
      </wsHttpBinding>
   </bindings>
  </system.serviceModel>
</configuration>
Then Create a Service.svc file that contains the following line and place it in your Internet Information Services (IIS) virtual directory.
<%@ServiceHost language=c# Service="CalculatorService" %>


To modify the default values of the binding properties

  1. To modify one of the default property values of the WSHttpBinding, create a new binding configuration name - <binding name="Binding1"> - within the<wsHttpBinding> element and set the new values for the attributes of the binding in this binding element. For example, to change the default open and close timeout values of 1 minute to 2 minutes, add the following to the configuration file.


     <wsHttpBinding>
            <binding name="Binding1"
                     closeTimeout="00:02:00"
                     openTimeout="00:02:00">
            </binding>
          </wsHttpBinding>
    
    
    
    
Thanks For Reading..!!
Default Programmer


What is Having Clause in SQL Server ?


HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.
HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause.
A HAVING clause is like a WHERE clause, but applies only to groups as a whole, whereas the WHERE clause applies to individual rows. A query can contain both a WHERE clause and a HAVING clause. The WHERE clause is applied first to the individual rows in the tables . Only the rows that meet the conditions in the WHERE clause are grouped. The HAVING clause is then applied to the rows in the result set. Only the groups that meet the HAVING conditions appear in the query output. You can apply a HAVING clause only to columns that also appear in the GROUP BY clause or in an aggregate function. (Reference :BOL)
Example of HAVING and WHERE in one query:
SELECT BloggerName,AVG(total) AS ‘Average’ FROM blogcount
WHERE Topic=‘SQL’
GROUP BY BloggerName
HAVING AVG(total)>25

Sometimes you can specify the same set of rows using either a WHERE clause or a HAVING clause. In such cases, one method is not more or less efficient than the other. The optimizer always automatically analyzes each statement you enter and selects an efficient means of executing it. It is best to use the syntax that most clearly describes the desired result. In general, that means eliminating undesired rows in earlier clauses.


Thanks For Reading..!!
Default Programmer

What is a Dirty Read ?

Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value.
While you can easily command a database to disallow dirty reads, this usually degrades the performance of your application due to the increased locking overhead. Disallowing dirty reads also leads to decreased system concurrency. 

Monday, 23 April 2012

What is Connection Pooling in SQL Server ?


Connecting to a database server typically consists of several time-consuming steps. A physical channel such as a socket or a named pipe must be established, the initial handshake with the server must occur, the connection string information must be parsed, the connection must be authenticated by the server, checks must be run for enlisting in the current transaction, and so on.


In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.


Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application callsClose on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.


Only connections with the same configuration can be pooled. ADO.NET keeps several pools at the same time, one for each configuration. Connections are separated into pools by connection string, and by Windows identity when integrated security is used. Connections are also pooled based on whether they are enlisted in a transaction.



Pooling connections can significantly enhance the performance and scalability of your application. By default, connection pooling is enabled in ADO.NET. Unless you explicitly disable it, the pooler optimizes the connections as they are opened and closed in your application. You can also supply several connection string modifiers to control connection pooling behavior. 





Thanks For Reading..!!

Default Programmer

Difference Between Delete and Truncate Command in SQL Server.


Truncate an Delete both are used to delete data from the table. These both command will only delete data of the specified table, they cannot remove the whole table data structure.Both statements delete the data from the table not the structure of the table.
  • TRUNCATE is a DDL (data definition language) command whereas DELETE is a DML (data manipulation language) command.
  • You can use WHERE clause(conditions) with DELETE but you can't use WHERE clause with TRUNCATE .
  • You cann't rollback data in TRUNCATE( unless it is used in Trasaction)  but in DELETE you can rollback data.TRUNCATE removes(delete) the record permanently.
  • A trigger doesn’t get fired in case of TRUNCATE whereas Triggers get fired in DELETE command.
  • If tables which are referenced by one or more FOREIGN KEY constraints then TRUNCATE will not work.
  • TRUNCATE resets the Identity counter if there is any identity column present in the table where delete not resets the identity counter.
  • Delete and Truncate both are logged operation.But DELETE is a logged operation on a per row basis and TRUNCATE logs the deallocation of the data pages in which the data exists.
  • TRUNCATE is faster than DELETE.





Thanks For Reading..!!
Default Programmer

What is Collation in SQL Server ?


Collation refers to  set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case sensitivity, accent marks, kana character types and character width.
You can check you database collation using below query :

SELECT DATABASEPROPERTYEX('YourDatabaseName', 'Collation') SQLCollation;

if it reutrns Latin1_General_CI_AS it means :

Arguments
SortRules

A string identifying the alphabet or language whose sorting rules are applied when dictionary sorting is specified. Examples are Latin1_General or Polish.

Pref

Specifies uppercase preference.

Codepage

Specifies a one to four digit number identifying the code page used by the collation. CP1 specifies code page 1252, for all other code pages the complete code page number is specified. For example, CP1251 specifies code page 1251 and CP850 specifies code page 850.

CaseSensitivity

CI specifies case-insensitive, CS specifies case-sensitive.

AccentSensitivity

AI specifies accent-insensitive, AS specifies accent-sensitive.

BIN

Specifies the binary sort order is to be used.

Detail can be found at :http://msdn.microsoft.com/en-us/library/aa258233(v=sql.80).aspx

Thanks For Reading..!!

Default programmer

Friday, 20 April 2012

How to send email from an asp.net web application using gmail account

Here is the code which will help you to send email from your gmail account using asp.net application. Copy and paste the below code in click event of the button if you are sending mail using button click.


string from = "demo@gmail.com"; //Replace this with your own correct Gmail Address

string to = "demo123@gmail.com"; //Replace this with the Email Address to whom you want to send the mail

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to);
 mail.From = new MailAddress(from,"demo" , System.Text.Encoding.UTF8);
mail.Subject = "This is a test mail";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true ;
mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
//Add the Creddentials- use your own email id and password

 client.Credentials = new System.Net.NetworkCredential(from, "password");

client.Port = 587; // Gmail works on this port
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
       try
        {
            client.Send(mail);
        }      
       catch (Exception ex)
        {
            Exception ex2 = ex;
            string errorMessage = string.Empty;
            while (ex2 != null)
            {
                errorMessage += ex2.ToString();
                ex2 = ex2.InnerException;
            }
 HttpContext.Current.Response.Write(errorMessage );
        } // end try


Thanks for reading..!!

Default Programmer