Thursday, 4 October 2012

How to use DataContract ?


  [ServiceContract]   
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);
        [OperationContract]
        void SaveEmployeeDetails(Employee eobj);
        [OperationContract]
        [FaultContract(typeof(MyFaultException))]
        Employee GetEmployee(int eid);
        [OperationContract]
        IList<Employee> GetEmpbyDept(int did);
        [OperationContract]
        void SubmitEmployees(IEnumerable<Employee> emps);
        [OperationContract]
        Employeedetails GetEmployeeMsg();
     
   
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations
    [DataContract]   
    public class Employee
    {
        [DataMember]
        public string Ename { get; set; }
        [DataMember]
        public string Eloc { get; set; }
        [DataMember]
        public int Deptid { get; set; }
        [DataMember]
        public int Uploadstatus { get; set; }
    }


    [DataContract]
    public class MyFaultException
    {
        private string _reason;

        [DataMember]
        public string Reason
        {
            get { return _reason; }
            set { _reason = value; }
        }
    }
    [MessageContract]
    public class Employeedetails
    {
        [MessageHeader]
        public string Ename { get; set; }
        [MessageBodyMember]
        public string Eloc { get; set; }
        [MessageBodyMember]
        public int Deptid { get; set; }
        [MessageHeader]
        public int Uploadstatus { get; set; }
   
    }
Implementation
   public class Service1 : IService1
    {
        SqlConnection con = new SqlConnection("uid=sa;pwd=zolt123$;database=wcfdb");
       
        SqlDataAdapter da;
        DataSet ds;
        List<Employee> elist = new List<Employee>();
    
        public string GetData(int value)
        {
           
            return "you entred value is:" + value;
        }
        public void SaveEmployeeDetails(Employee eobj)
        {
            da = new SqlDataAdapter("insert into emp values('" + eobj.Ename + "','" + eobj.Eloc + "'," + eobj.Deptid + "," + eobj.Uploadstatus + ")", con);
            ds = new DataSet();
            da.Fill(ds);
        }
        public Employee GetEmployee(int eid)
        {
            da = new SqlDataAdapter("select * from emp where Eid=" + eid, con);
            ds = new DataSet();
            da.Fill(ds);
         
            try
            {
                Employee eobj = new Employee();
                eobj.Ename = ds.Tables[0].Rows[0][1].ToString();
                eobj.Eloc = ds.Tables[0].Rows[0][2].ToString();
                eobj.Deptid = Convert.ToInt32(ds.Tables[0].Rows[0][3].ToString());
                //   eobj.Uploadstatus = Convert.ToBoolean(ds.Tables[0].Rows[0][4].ToString());
                return eobj;

            }
            catch (Exception )
            {

                MyFaultException exs = new MyFaultException { Reason = "There is no employee exist with the emp id : " + eid };
              
                throw new FaultException<MyFaultException>(exs);
            }
        
        }
        #region IService1 Members


        public IList<Employee> GetEmpbyDept(int did)
        {
            da = new SqlDataAdapter("select * from emp where deptr=" + did, con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            try
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    Employee e = new Employee();
                    e.Ename = ds.Tables[0].Rows[i]["ename"].ToString();
                    e.Eloc = ds.Tables[0].Rows[i]["eloc"].ToString();
                    e.Deptid = Convert.ToInt32(ds.Tables[0].Rows[i]["deptr"].ToString());
                    elist.Add(e);

                }
                return elist;
            }
            catch (Exception)
            {

                List<FaultReasonText> flist = new List<FaultReasonText>();
                flist.Add(new FaultReasonText("general exceptionsss"));
                throw new FaultException(new FaultReason(flist),FaultCode.CreateReceiverFaultCode(new FaultCode("lsitall")));
            }
         
        }

        #endregion






        #region IService1 Members


        public void SubmitEmployees(IEnumerable<Employee> emps)
        {

            IEnumerator<Employee> ier = emps.GetEnumerator();
            while (ier.MoveNext() == true)
            {
                Employee e = new Employee();
                e.Ename = ier.Current.Ename;
                e.Eloc = ier.Current.Eloc;
                e.Deptid = ier.Current.Deptid;
                e.Uploadstatus=0;
                SqlCommand cmd = new SqlCommand("InsertEmp",con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlParameter sp1 = new SqlParameter("@ename", SqlDbType.VarChar);
                sp1.Value=e.Ename;
                SqlParameter sp2 = new SqlParameter("@eloc", SqlDbType.VarChar);
                sp2.Value = e.Eloc;
                SqlParameter sp3 = new SqlParameter("@dept", SqlDbType.Int);
                sp3.Value = e.Deptid;
                SqlParameter sp4 = new SqlParameter("@upload", SqlDbType.Bit);
                sp4.Value = e.Uploadstatus;
               cmd.Parameters.Add(sp1);
               cmd.Parameters.Add(sp2);
               cmd.Parameters.Add(sp3);
               cmd.Parameters.Add(sp4);             
                con.Open();
                int i=cmd.ExecuteNonQuery();
                con.Close();              
            }

        }
        #endregion






        #region IService1 Members


        public Employeedetails GetEmployeeMsg()
        {
            da = new SqlDataAdapter("select * from emp where Eid=" + 103, con);
            ds = new DataSet();
            da.Fill(ds);

            try
            {
                Employeedetails eobj = new Employeedetails();
                eobj.Ename = ds.Tables[0].Rows[0][1].ToString();
                eobj.Eloc = ds.Tables[0].Rows[0][2].ToString();
                eobj.Deptid = Convert.ToInt32(ds.Tables[0].Rows[0][3].ToString());
                //   eobj.Uploadstatus = Convert.ToBoolean(ds.Tables[0].Rows[0][4].ToString());
                return eobj;

            }
            catch (Exception)
            {

                MyFaultException exs = new MyFaultException();
                exs.Reason = "this my exception ";
                throw new FaultException<MyFaultException>(exs);
            }
        }

        #endregion
    }

At Client


Class Declaration
  SqlConnection con = new SqlConnection("uid=sa;pwd=zolt123$;database=wcfdb");
        SqlCommand cmd;
        DataSet ds;
private void button1_Click(object sender, EventArgs e)
        {
            ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client();
            List<EmployeeServices.ServiceReference1.Employee> elist = new List<EmployeeServices.ServiceReference1.Employee>();
            Employee emp = new Employee();
            try
            {
                int eid = Convert.ToInt32(txtEid.Text);
                emp = proxy.GetEmployee(eid);

            
                List<Employee> es = new List<Employee>();
                es.Add(emp);
                dataGridView1.DataSource = es.ToList<Employee>();
            }
            catch (FaultException<MyFaultException> ex)
            {
              
          

                MessageBox.Show(ex.Reason.ToString());
               
            }
          


            //dataGridView1.DataSource = GetEmpbyDept(4);

       

        }
        public List<Employes1> GetEmpbyDept(int did)
        {
            SqlDataAdapter da=new SqlDataAdapter("select * from emp where deptr=" + did, con);
            DataSet ds=new DataSet();
            da.Fill(ds);
          
                List<Employes1> elist = new List<Employes1>();
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    Employes1 e = new Employes1();
                    e.Ename = ds.Tables[0].Rows[i]["ename"].ToString();
                    e.Eloc = ds.Tables[0].Rows[i]["eloc"].ToString();
                    e.Deptid = Convert.ToInt32(ds.Tables[0].Rows[i]["deptr"].ToString());

                    elist.Add(e);

                }
                return elist;   

            }

        private void btnEnumerable_Click(object sender, EventArgs e)
        {
            Employee e1 = new Employee();
            e1.Ename = txtEname.Text;
            e1.Eloc = txtEloc.Text;
            e1.Deptid = Convert.ToInt32(txtDept.Text);
         
            List<Employee> li = new List<Employee>();
            li.Add(e1);
            Service1Client proxy = new Service1Client();
            proxy.SubmitEmployees(li.ToArray());
       
            MessageBox.Show("Saved Succefully......");
 
        }

        private void btnDept_Click(object sender, EventArgs e)
        {
            ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client();
            List<EmployeeServices.ServiceReference1.Employee> elist = new List<EmployeeServices.ServiceReference1.Employee>();       
            Employee[] emps = new Employee[2];
            try
            {
                int did = Convert.ToInt32(txtDeptId.Text);
                emps = proxy.GetEmpbyDept(did);
               
            //    List<Employee> es = new List<Employee>();
             //   es.Add(emps[0]);
             //   es.Add(emps[1]);  // errors if no employee return by the servies
                dataGridView1.DataSource = emps.ToArray<Employee>();
                //dataGridView1.DataSource = es.ToList<Employee>();
            }
            catch (FaultException<MyFaultException> ex)
            {

                MessageBox.Show(ex.Reason.ToString());

            }
          

        }

No comments:

Post a Comment