Monday, May 14, 2012

WCF-DataContract Example

Interface and Classes : IDataContService.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace DataContractDatBinding
{
    [ServiceContract]
    public interface IDataContService
    {
    
        [OperationContract]
        FundDetail getFunds();

        [OperationContract]
        Pricedetail getpricedetail(int FundID);
   
        [OperationContract]
        List<Pricedetail> GetListPricedetails(int FundID);
       
        [OperationContract]
        string[] ArayFund();

        [OperationContract]
        Pricedetail[] GetPriceDetailClassArray();
       
        [OperationContract]
        string[] getpbjectvalues();
       
    }


    [DataContract]
    [KnownType(typeof(string[]))]
    public class ClassObjectreturn
    {
       
        object _Objval = new object() ;
        [DataMember]
        public object ObjectValue
        {
            get { return _Objval; }
            set { _Objval = value; }
        }
   
    }


    [DataContract]
    [KnownType(typeof(Pricedetail))]
    [KnownType(typeof(FundClass))]
    public class FundDetail
    {
        private int _FundID;
        private string _FundName;     

        [DataMember]
        public int FundID_Master
        {
            get { return _FundID; }
            set { _FundID = value; }
        }
        [DataMember]
        public string FundName
        {
            get { return _FundName; }
            set { _FundName = value; }
        }

        List<Pricedetail> prices;

        [DataMember()]
        public List<Pricedetail> pricedetailslist
        {
            get
            {
                if (prices == null)
                    prices = new List<Pricedetail>();
                return prices;
            }
            set
            {
                prices = value;
            }
        }
        
    }

    [DataContract]
    public class Pricedetail //: FundDetail
    {
        private int _PriceID;
        private int _FundID;
        private DateTime _PriceDate;
        private DateTime? _IssuedDate;  // For Nullable value , Dont know when price issued
        private string _FundSize;
        private decimal _Bid;
        private decimal _Offer;


        [DataMember(Name = "PriceIDNo", Order = 1)]
        public int PriceID
        {
            get { return _PriceID; }
            set { _PriceID = value; }
        }

        [DataMember(Name = "PriceFundID", Order = 0)]
        public int FundID
        {
            get { return _FundID; }
            set { _FundID = value; }
        }
        [DataMember(Name = "DateOfPrice", Order = 3)]
        public DateTime PriceDate
        {
            get { return _PriceDate; }
            set { _PriceDate = value; }
        }


        [DataMember(Order = 6)]
        public Nullable<DateTime> IssuedDate
        {
            get { return _IssuedDate; }
            set { _IssuedDate = value; }
        }


        [DataMember(Name = "SizeOfFund", Order = 2)]
        public string FundSize
        {
            get { return _FundSize; }
            set { _FundSize = value; }
        }

        [DataMember(Order = 5)]
        public decimal Bid
        {
            get { return _Bid; }
            set { _Bid = value; }
        }
        [DataMember(Order = 4)]
        public decimal Offer
        {
            get { return _Offer; }
            set { _Offer = value; }
        }

    }




    [DataContract]
    public class FundClass : FundDetail
    {
        private int _FundClassID;
        private string _FundClass;
        [DataMember]
        public int FundClassID
        {
            get { return _FundClassID; }
            set { _FundClassID = value; }
        }
        [DataMember]
        public string FundClassName
        {
            get { return _FundClass; }
            set { _FundClass = value; }
        }
    }
}




Service  : DataContService.svc



using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using System.Xml;

 

namespace DataContractDatBinding
{

    public class DataContService : IDataContService
    {
         SqlConnection Conn;
         public DataContService()
        {
            Conn = new SqlConnection("Connection String");
        }


         List<Pricedetail> listOfprices = new List<Pricedetail>();

         public FundDetail getFunds()
         {

             

                 List<Pricedetail> fundPriceList = new List<Pricedetail>();
                 Pricedetail dc = new Pricedetail();
                 Conn.Open();
                 SqlCommand Cmd = new SqlCommand("Select top 5 PriceID,FundID,convert(varchar(50),FundSize) as FundSize,bid,offer,Pricedate from tblPrice where FundID=" + 7 + " order by Pricedate desc ", Conn);
                 SqlDataReader dr = Cmd.ExecuteReader();
               
                 while (dr.Read())
                 {
                     dc.PriceID = Convert.ToInt32(dr["PriceID"].ToString());
                     dc.FundID = Convert.ToInt32(dr["FundID"].ToString());
                     dc.FundSize = dr["FundSize"].ToString();
                     dc.Bid = Convert.ToDecimal(dr["bid"].ToString());
                     dc.Offer = Convert.ToDecimal(dr["offer"].ToString());
                     dc.IssuedDate = Convert.ToDateTime(dr["Pricedate"].ToString());
                     dc.PriceDate = Convert.ToDateTime(dr["Pricedate"].ToString());
                     fundPriceList.Add(dc);
                 }
                 dr.Close();
                                        
             FundDetail _objFund = new FundDetail();
             _objFund.FundID_Master = 7;
             _objFund.FundName  = "MasterFund";
             _objFund.pricedetailslist = fundPriceList;

            


             // This part is user to Serialize Funddetail Class /

             DataContractSerializer ds = new DataContractSerializer(typeof(FundDetail));
             XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
             using (XmlWriter w = XmlWriter.Create("person.xml", settings))
             ds.WriteObject(w, _objFund);
             System.Diagnostics.Process.Start("person.xml");


          
             // Deserialize the data and read it from the instance.
              FileStream fs = new FileStream("person.xml", FileMode.Open);
              XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
              DataContractSerializer ser = new DataContractSerializer(typeof(FundDetail));
              FundDetail dser = (FundDetail)ser.ReadObject(reader, true);
              reader.Close();
              fs.Close();

// Here we are returning  De Serializer object
 
              return dser;


         }

         public Pricedetail getpricedetail(int FundID)
         {

             Conn.Open();
             SqlCommand Cmd = new SqlCommand("Select top 1 PriceID,FundID,convert(varchar(50),FundSize) as FundSize,bid,offer,Pricedate from tblPrice where FundID=" + FundID + " order by Pricedate desc ", Conn);
             SqlDataReader dr = Cmd.ExecuteReader();
             Pricedetail dc = new Pricedetail();
             while (dr.Read())
             {
                 dc.PriceID = Convert.ToInt32(dr["PriceID"].ToString());
                 dc.FundID = Convert.ToInt32(dr["FundID"].ToString());
                 dc.FundSize = dr["FundSize"].ToString();
                 dc.Bid = Convert.ToDecimal(dr["bid"].ToString());
                 dc.Offer = Convert.ToDecimal(dr["offer"].ToString());
                 dc.IssuedDate = Convert.ToDateTime(dr["Pricedate"].ToString());
                 dc.PriceDate = Convert.ToDateTime(dr["Pricedate"].ToString());

             }
             dr.Close();        

             Conn.Close();
             return dc;
         }

       

         public List<Pricedetail> GetListPricedetails(int FundID)
         {
            
             Conn.Open();
             SqlCommand Cmd = new SqlCommand("Select top 5 PriceID,FundID,convert(varchar(50),FundSize) as FundSize,bid,offer,Pricedate from tblPrice where FundID=" + FundID + " order by Pricedate desc ", Conn);
             SqlDataReader dr = Cmd.ExecuteReader();
             Pricedetail dc = new Pricedetail();
             while (dr.Read())
             {
                 dc.PriceID = Convert.ToInt32(dr["PriceID"].ToString());
                 dc.FundID = Convert.ToInt32(dr["FundID"].ToString());
                 dc.FundSize = dr["FundSize"].ToString();
                 dc.Bid = Convert.ToDecimal(dr["bid"].ToString());
                 dc.Offer = Convert.ToDecimal(dr["offer"].ToString());
                 dc.IssuedDate = Convert.ToDateTime(dr["Pricedate"].ToString());
                 dc.PriceDate = Convert.ToDateTime(dr["Pricedate"].ToString());
                 listOfprices.Add(dc);
             }
            
             dr.Close();
             Conn.Close();
             return listOfprices;
         }
    
         public string[] ArayFund()
         {
             string[] result;
             Conn.Open();
             SqlCommand Cmd = new SqlCommand("Select top 10 FundName from tblfund order by FundID", Conn);
             SqlDataReader dr = Cmd.ExecuteReader();
             Pricedetail dc = new Pricedetail();
             using (DataTable dt = new DataTable())
             {
               dt.Load(dr);
               result = new string[dt.Rows.Count];          
               for (int i = 0; i < dt.Rows.Count; i++)
               {
                   result[i] = dt.Rows[i]["FundName"].ToString();
               }
             }     
            Conn.Close();
           return  result;
         }

      

         public Pricedetail[] GetPriceDetailClassArray()
         {

             Conn.Open();
             SqlCommand Cmd = new SqlCommand("Select top 5 PriceID,FundID,convert(varchar(50),FundSize) as FundSize,bid,offer,Pricedate from tblPrice where FundID=" + 7 + " order by Pricedate desc ", Conn);
             SqlDataReader dr = Cmd.ExecuteReader();
             Pricedetail dc = new Pricedetail();
             while (dr.Read())
             {
                 dc.PriceID = Convert.ToInt32(dr["PriceID"].ToString());
                 dc.FundID = Convert.ToInt32(dr["FundID"].ToString());
                 dc.FundSize = dr["FundSize"].ToString();
                 dc.Bid = Convert.ToDecimal(dr["bid"].ToString());
                 dc.Offer = Convert.ToDecimal(dr["offer"].ToString());
                 dc.IssuedDate = Convert.ToDateTime(dr["Pricedate"].ToString());
                 dc.PriceDate = Convert.ToDateTime(dr["Pricedate"].ToString());
                 listOfprices.Add(dc);
             }

             dr.Close();
             Conn.Close();

             //Pricedetail[] priceObject = listOfprices.ToArray() ;


             return listOfprices.ToArray();

         }

           
      


         string[] IDataContService.getpbjectvalues()
         {
             ClassObjectreturn _objFund = new ClassObjectreturn();
             string[] b = new string[10];
             _objFund.ObjectValue = b;
             return b;
         }
    }
}



TEST Service 

Step 1 . view service in browser and get URL


Step 2 .  Open Visual studio command prompt aand type WCFTESTCLIENT which will open window and you can paste url there as shown in image below


 step 3. After click ok button below screen will open where you can test all methods 

 

Step 4. Double Click on first method getFunds() and click on Invoke button.You can see output in screen below.

In above class Datacontract we define datamember List<Pricedetail> which retrieve Price detail for specified FundID eg: 7 .




     [DataMember()]
        public List<Pricedetail> pricedetailslist
        {
            get
            {
                if (prices == null)
                    prices = new List<Pricedetail>();
                return prices;
            }
            set
            {
                prices = value;
            }
        }
In GetFunds()  method we fill list with price details for FundID 7 and assign to member pricedetailslist.

Note : In this method We are also Serialize Funddetail Class Object and save data in XML File which is shown below after that we De Serialize  data and return DeSerialize object.

My concern here is to show how to  Serialize  and De Serialize Class objects as well. 

 



XML File
 






GetPricedetail() method return Price detail for specific FundID eg : 7
This method return FundPrice Class Object with data.
 




GetListPricedetails() Method return Generic List with Price datils 






Array Fund() Method return Array Of Fund Names


  

 GetPriceDetailClassArray() method return  price detail Class Array


No comments :

Post a Comment