Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Wednesday, 31 October 2012

IsWrapped Element of MessageContract?

Yes, based on the IsWrapped attribute value proxy will generates at client as differently.


class MessageContract
{
        public bool IsWrapped { get; set; }
}

 true if the message body has a wrapper element; otherwise, false. The default is true.


Case 1:
 iswrapped=true
 // Default is true. Based on the isWrapped element of Messagecontract –the generated client signature will change.
 for RetrieveCaseRequest and RetrieveCaseResponse custom classes
[MessageContract(IsWrapped=true)]
    public class RetrieveCaseRequest
    {
        [MessageBodyMember]
        public int invalue;

    }
   [MessageContract(IsWrapped=true)]
    public class RetrieveCaseResponse
    {
        [MessageBodyMember]
        public int outvalue;

    }
Note: default also true only.
At client method-àGetMethod signature is
   [System.ServiceModel.MessageContractAttribute(WrapperName="RetrieveCaseRequest", WrapperNamespace="http://tempuri.org/", IsWrapped=true)]
    public partial class RetrieveCaseRequest {
       
        [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tempuri.org/", Order=0)]
        public int invalue;
       
        public RetrieveCaseRequest() {
        }
       
        public RetrieveCaseRequest(int invalue) {
            this.invalue = invalue;
        }
    }
[System.ServiceModel.MessageContractAttribute(WrapperName="RetrieveCaseResponse", WrapperNamespace="http://tempuri.org/", IsWrapped=true)]
    public partial class RetrieveCaseResponse {
       
        [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tempuri.org/", Order=0)]
        public int outvalue;
       
        public RetrieveCaseResponse() {
        }
       
        public RetrieveCaseResponse(int outvalue) {
            this.outvalue = outvalue;
        }
    }
The request and response IsWrapped=ture.
So both method[GetMethod excepting integer and return integer).
   
So
Method request and response is
isWrappedtruetruedefault.ServiceReference1.RetrieveCaseResponse // response
isWrappedtruetruedefault.ServiceReference1.IService1.Getmethod
(
isWrappedtruetruedefault.ServiceReference1.RetrieveCaseRequest request   //request)
        {
            return base.Channel.Getmethod(request);
        }
       
Then below is accepting like intergers only.
public int Getmethod(int invalue)
{
isWrappedtruetruedefault.ServiceReference1.RetrieveCaseRequest inValue
= new isWrappedtruetruedefault.ServiceReference1.RetrieveCaseRequest();

            inValue.invalue = invalue;

isWrappedtruetruedefault.ServiceReference1.RetrieveCaseResponse retVal =

((isWrappedtruetruedefault.ServiceReference1.IService1)(this)).Getmethod(inValue);

 return retVal.outvalue;
}
Then request is set true
So get method
  public int Getmethod(int invalue)
{ }
CASE 2:
[MessageContract(IsWrapped=true)]
    public class RetrieveCaseRequest
    {
        [MessageBodyMember]
        public int invalue;

    }
   [MessageContract(IsWrapped=false)]
    public class RetrieveCaseResponse
    {
        [MessageBodyMember]
        public int outvalue;

    }
Then proxy
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
    public partial class RetrieveCaseRequest1
{
       
        [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tempuri.org/", Order=0)]
        public isWrappedtrueandfalse.ServiceReference2.RetrieveCaseRequest RetrieveCaseRequest;
       
        public RetrieveCaseRequest1()
        {
        }
       
        public RetrieveCaseRequest1(isWrappedtrueandfalse.ServiceReference2.RetrieveCaseRequest RetrieveCaseRequest) {
            this.RetrieveCaseRequest = RetrieveCaseRequest;
        }
    }
   
   // [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
    public partial class RetrieveCaseResponse {
       
        [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tempuri.org/", Order=0)]
        public int outvalue;
       
        public RetrieveCaseResponse() // normal
{
        }
       
        public RetrieveCaseResponse(int outvalue) {
            this.outvalue = outvalue;
        }
    }
then
isWrappedtrueandfalse.ServiceReference2.RetrieveCaseResponse isWrappedtrueandfalse.ServiceReference2.IService1.Getmethod(isWrappedtrueandfalse.ServiceReference2.RetrieveCaseRequest1 request)
        {
            return base.Channel.Getmethod(request);
        }
       
public int Getmethod(isWrappedtrueandfalse.ServiceReference2.RetrieveCaseRequest RetrieveCaseRequest)
        {
isWrappedtrueandfalse.ServiceReference2.RetrieveCaseRequest1 inValue
 = new isWrappedtrueandfalse.ServiceReference2.RetrieveCaseRequest1();
// here request is RetrieveCaseRequest1 and
                                           Response is RetrieveCaseRequest

            inValue.RetrieveCaseRequest = RetrieveCaseRequest;
            isWrappedtrueandfalse.ServiceReference2.RetrieveCaseResponse retVal = ((isWrappedtrueandfalse.ServiceReference2.IService1)(this)).Getmethod(inValue);
            return retVal.outvalue;
        }

    Then
            Service1Client proxy = new Service1Client();
            RetrieveCaseRequest obj = new RetrieveCaseRequest();
            obj.invalue = 41;
            int values=proxy.Getmethod(obj);
            Console.WriteLine(values.ToString());

            Console.ReadKey();
Here Getmethod excepting

int Getmethod(RetrieveCaseRequest retriveveCaseRequest);


as well request and response proxy codes

// [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Name="RetrieveCaseRequest", Namespace="http://tempuri.org/")]
    [System.SerializableAttribute()]
    public partial class RetrieveCaseRequest : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
       
        [System.NonSerializedAttribute()]
        private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
       
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private int invalueField;
       
        [global::System.ComponentModel.BrowsableAttribute(false)]
        public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
            get {
                return this.extensionDataField;
            }
            set {
                this.extensionDataField = value;
            }
        }
       
        [System.Runtime.Serialization.DataMemberAttribute()]
        public int invalue {
            get {
                return this.invalueField;
            }
            set {
                if ((this.invalueField.Equals(value) != true)) {
                    this.invalueField = value;
                    this.RaisePropertyChanged("invalue");
                }
            }
        }
       
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
       
        protected void RaisePropertyChanged(string propertyName) {
            System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
            if ((propertyChanged != null)) {
                propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
    }
   
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName="ServiceReference2.IService1")]
    public interface IService1
    {
       
        // CODEGEN: Generating message contract since the operation Getmethod is neither RPC nor document wrapped.
        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IService1/Getmethod", ReplyAction="http://tempuri.org/IService1/GetmethodResponse")]

isWrappedtrueandfalse.ServiceReference2.RetrieveCaseResponse Getmethod(isWrappedtrueandfalse.ServiceReference2.RetrieveCaseRequest1 request);
    }
   
   // [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
    public partial class RetrieveCaseRequest1
{
       
        [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tempuri.org/", Order=0)]
public isWrappedtrueandfalse.ServiceReference2.RetrieveCaseRequest RetrieveCaseRequest;
       
        public RetrieveCaseRequest1() {
        }
       
        public RetrieveCaseRequest1(isWrappedtrueandfalse.ServiceReference2.RetrieveCaseRequest RetrieveCaseRequest) {
            this.RetrieveCaseRequest = RetrieveCaseRequest;
        }
    }
   
   // [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
    public partial class RetrieveCaseResponse {
       
        [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://tempuri.org/", Order=0)]
        public int outvalue;
       
        public RetrieveCaseResponse() {
        }
       
        public RetrieveCaseResponse(int outvalue) {
            this.outvalue = outvalue;
        }
    }
CASE 2:
[MessageContract(IsWrapped=false)]
    public class RetrieveCaseRequest
    {
        [MessageBodyMember]
        public int invalue;

    }
   [MessageContract(IsWrapped=true)]
    public class RetrieveCaseResponse
    {
        [MessageBodyMember]
        public int outvalue;

    }
Here Response will created as like Response1
   public isWrappedfalseandtrue.ServiceReference3.RetrieveCaseResponse Getmethod(int invalue) {
isWrappedfalseandtrue.ServiceReference3.RetrieveCaseRequest inValue
 = new isWrappedfalseandtrue.ServiceReference3.RetrieveCaseRequest();

            inValue.invalue = invalue;

            isWrappedfalseandtrue.ServiceReference3.RetrieveCaseResponse1 retVal = ((isWrappedfalseandtrue.ServiceReference3.IService1)(this)).Getmethod(inValue);
            return retVal.RetrieveCaseResponse;
        }
NOTE: Both makes as false also not works like true only.

when we changes at service without updated proxy at client which gives invalid output 

outwise SerializationException



Friday, 26 October 2012

WCF supports transactions?


Yes, WCF(Windows Communication Foundation) builds WSE/web service extensions as their bindings
binding is a communication way: between client and service.
which done through transaction supported bindings.

we have many bindings

BasicHttpBinding

WSHttpBinding
NetTcpBinding

msmqnetbinding......these are classes in .net framework.

wshttpbinding,nettcpbinding,..ect so first we must know what bindings supports the transactions.

basichttpbinding not supports transactions.

better to choose wshttpbinding.(introbility with old .asmx).
nettcpbinding(best performance).

namespace WcfTransactionsDemos
{
    [ServiceContract]
    public interface IService1
    {
       [OperationContract]
       [TransactionFlow (TransactionFlowOption.Allowed)]
       void Transfer (string accountFrom,string accountTo, double amount);
    }
}
Service Implementation
[ServiceBehavior]
    public class Service1 : IService1
    {

      static  SqlConnection conn = new SqlConnection("uid=sa;pwd=zolt123$;database=wcfdb");

        [OperationBehavior(TransactionScopeRequired = true)]
        public void Transfer(string accountFrom, string accountTo, double amount)
        {           
          Transaction originalTransaction = Transaction.Current;
          CommittableTransaction transaction = new CommittableTransaction ();
          try
          {
              Transaction.Current = transaction;
              Withdraw (accountFrom, amount);
              Deposite (accountTo, amount);
              transaction.Commit ();
             
         }
          catch (Exception ex)
          {
             
              //Transaction.Current = transaction;
              transaction.Rollback();
          
         }
         finally
         {
              Transaction.Current = originalTransaction;
               transaction.Dispose ();
          }

        }
          void Deposite ( string accountId, double deptamount)
         {
             SqlCommand cmd = new SqlCommand();
             cmd.Connection = conn;
             cmd.CommandText = "P_DEPOSIT";
             cmd.CommandType = CommandType.StoredProcedure;
             SqlParameter id = new SqlParameter("@atid",accountId);
         
             cmd.Parameters.Add(id);

             SqlParameter amount = new SqlParameter("@amount",deptamount);          
             cmd.Parameters.Add(amount);
             cmd.ExecuteNonQuery();
             conn.Close();
            
            
        }
          void Withdraw(string accountid, double withamount)
          {

              SqlCommand cmd = new SqlCommand();
              cmd.Connection = conn;
              cmd.CommandType = CommandType.StoredProcedure;
              cmd.CommandText = "P_WITHDRAW";

              SqlParameter id = new SqlParameter("@atid", accountid);             
              cmd.Parameters.Add(id);

              SqlParameter amount = new SqlParameter("@amount",withamount);          
              cmd.Parameters.Add(amount);
              conn.Open();
              cmd.ExecuteNonQuery();

          }
          private static double GetBalance(string accountId)
          {
              double amount = 0;
              SqlCommand cmd = new SqlCommand();
              cmd.Connection = conn;
              cmd.CommandType = CommandType.StoredProcedure;
              cmd.CommandText = "P_GET_BALANCE_BY_ID";

              SqlParameter id = new SqlParameter("@atid",accountId);
          
              cmd.Parameters.Add(id);

              SqlDataReader dr = cmd.ExecuteReader();
              while (dr.Read()==true)
              {
                   amount=Convert.ToDouble(dr[0].ToString());
                 
              }
              return amount;

           
         
          }
    }
Stored Procedures:
P_WITHDRAW

    ALTER  Procedure [dbo].[P_WITHDRAW]
(
        @atid  VARCHAR (50),
        @amount money)
     AS
     IF  NOT  EXISTS ( SELECT * FROM [dbo].[T_ACCOUNT] WHERE accounid = @atid)
        BEGIN
            RAISERROR ( 'Account ID does not exist' , 16,1)
           RETURN
      END   
  IF  NOT  EXISTS ( SELECT * FROM [dbo]. [T_ACCOUNT] WHERE accounid = @atid AND BALANCE> @amount)
      BEGIN
          RAISERROR ( 'insufficient balance' , 16,1)
           RETURN
        END
   
 UPDATE [dbo].[T_ACCOUNT] SET Balance = Balance - @amount WHERE accounid = @atid
dbo.P_DEPOSIT
  ALTER  Procedure [dbo].[P_DEPOSIT]
      (
        @atid         VARCHAR(50),
         @amount FLOAT
    )
 AS
 IF  NOT  EXISTS ( SELECT * FROM [dbo].[T_ACCOUNT] WHERE accounid =@atid)
     BEGIN
        RAISERROR ( 'Account ID does not exist' , 16,1)
      END
 UPDATE [dbo].[T_ACCOUNT] SET Balance = Balance + @amount WHERE accounid =@atid

Table
CREATE TABLE [dbo].[T_ACCOUNT](
      [accounid] [int] IDENTITY(1,1) NOT NULL,
      [NAME] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
      [Balance] [money] NULL,
 CONSTRAINT [PK__T_ACCOUNT__47DBAE45] PRIMARY KEY CLUSTERED
(
      [accounid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Using WCF Test Cleint


Transactions in wcf:




at database


select * from dbo.T_ACCOUNT


1 anand 21000.00
2 balu 9000.00