Monday, 23 July 2012

WCF With Aspx and Silverlight


WCF With Aspx and Silverlight


First Type


In Web.Config to set basicHttpBinding for call by silverlight xaml side otherwise wsHttpBinding

1->WCF Service –File IService.cs

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

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService
{

    [OperationContract]
  
    int save(object id1, object name1, object salary1);
   
}





2-> WCF Service Call By Asps Page Service.cs

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

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class Service : IService
{
    SqlConnection con;
    public Service()
    {
         con= new SqlConnection("initial catalog=nkp;data source=nkp-pc;integrated security=yes");
    }
    public int save(object id1, object name1, object salary1)   //prototype
    {
       
        SqlCommand cmd = new SqlCommand("add_chk", con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        cmd.CommandType = CommandType.StoredProcedure;
         
        cmd.Parameters.AddWithValue("@id", (int)id1);
        SqlDataReader rd = cmd.ExecuteReader();
        bool b = rd.Read();
        if (b == true)
          {
            return 0;
          }
        else
          {

              SqlCommand cmd1 = new SqlCommand("add_data2", con);
              if (con.State == ConnectionState.Open)
              {
                  con.Close();
              }
              if (con.State == ConnectionState.Closed)
              {
                  con.Open();
              }
         
          
            cmd1.CommandType = CommandType.StoredProcedure;
            cmd1.Parameters.AddWithValue("@id", (int)id1);
            cmd1.Parameters.AddWithValue("@name", (string)name1);
            cmd1.Parameters.AddWithValue("@salary",(int)salary1);
            int temp = cmd1.ExecuteNonQuery();
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
          
          
            return 1;
          }
       }
    }
 



3-> On  Asps Page Take WCF Service Reference file Aspx.cs
..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        ServiceReference1.ServiceClient s = new ServiceReference1.ServiceClient();
        int t = s.save(106, "ram", 43000);
        Response.Write(t.ToString());  //return 0 (true) or
                                       // 1 (false)
     }
}
                                            Or :
//Aspx.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(TextBox1.Text);
        string name = TextBox2.Text;
        int salary = Convert.ToInt32(TextBox3.Text);

        ServiceReference1.ServiceClient s = new ServiceReference1.ServiceClient();
        int t = s.save(id, name,salary);
        if (t == 1)
        {
            Label1.Text = "Record is saved...";
            //Response.Write(t.ToString());
        }
        else
        {
           Label1.Text = "Record is exist...";
            //Response.Write(t.ToString());
        }
     }
}








Second Type
1->Class1.cs Add in WCF Service Side

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


public class Class1
{
    private int id;
    private string name;
    private decimal salary;

    public int stuid
    {
        get { return id; }
        set { id = value; }
    }
    public string stuname
    {
        get { return name; }
        set { name = value; }
    }
    public decimal stusalary
    {
        get { return salary; }
        set { salary = value; }
    }

}







2->WCF Service –File IService.cs

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

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService
{

    [OperationContract]
   // int save(object id1, object name1, object salary1);
    int save(Class1 c);
}



3->WCF Service –File Service.cs




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

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class Service : IService
{
    SqlConnection con;
    public Service()
    {
         con= new SqlConnection("initial catalog=nkp;data source=nkp-pc;integrated security=yes");
    }

public  int save(Class1 c)
          {
              SqlCommand cmd = new SqlCommand("add_chk", con);
              if (con.State == ConnectionState.Closed)
              {
                  con.Open();
              }
              cmd.CommandType = CommandType.StoredProcedure;

              cmd.Parameters.AddWithValue("@id", c.stuid);
              SqlDataReader rd = cmd.ExecuteReader();
              bool b = rd.Read();
              if (b == true)
              {
                  return 0;
              }
              else
              {

                  SqlCommand cmd1 = new SqlCommand("add_data2", con);
                  if (con.State == ConnectionState.Open)
                  {
                      con.Close();
                  }
                  if (con.State == ConnectionState.Closed)
                  {
                      con.Open();
                  }


                  cmd1.CommandType = CommandType.StoredProcedure;
                  cmd1.Parameters.AddWithValue("@id",c.stuid);
                  cmd1.Parameters.AddWithValue("@name",c.stuname);
                  cmd1.Parameters.AddWithValue("@salary",c.stusalary);
                  int temp = cmd1.ExecuteNonQuery();
                  if (con.State == ConnectionState.Open)
                  {
                      con.Close();
                  }
                  return 1;
              }
          }




4->Aspx.cs file here take WCF service Reference


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

protected void Button1_Click(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(TextBox1.Text);
        string name = TextBox2.Text;
        int salary = Convert.ToInt32(TextBox3.Text);

        ServiceReference1.ServiceClient s = new ServiceReference1.ServiceClient();
        ServiceReference1.Class1 c2 = new ServiceReference1.Class1();
        c2.stuid = id;
        c2.stuname = name;
        c2.stusalary = salary;
        int t = s.save(c2);
        if (t == 1)
        {
            Label1.Text = "Record is saved...";
            //Response.Write(t.ToString());
        }
        else
        {
            Label1.Text = "Record is exist...";
            //Response.Write(t.ToString());
        }
       
 }





Third Type

1->Before use WCF Service to take Here……..Use for WCF Service  but use this service on Silverlight xaml side then change   basicHttpBinding…..

2->Use the WCF Service in Silverlight  MainPage.xaml.cs take reference on xaml side…..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication130712
{
    public partial class MainPage : UserControl
    {
        ServiceReference1.ServiceClient s;
        ServiceReference1.Class1 c2;
       
        public MainPage()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            int id = Convert.ToInt32(textBox1.Text);
            string name = textBox2.Text;
            int salary = Convert.ToInt32(textBox3.Text);

           s= new ServiceReference1.ServiceClient();
           c2 = new ServiceReference1.Class1();
           c2.stuid = id;
           c2.stuname = name;
           c2.stusalary = salary;

           //c2.stuid = 104;
           //c2.stuname = "Rahul";
           //c2.stusalary = 32000;

           s.saveAsync(c2);
           s.saveCompleted += new EventHandler<ServiceReference1.saveCompletedEventArgs>(s_saveCompleted);
            

        }

        void s_saveCompleted(object sender, ServiceReference1.saveCompletedEventArgs e)
        {
           
            //MessageBox.Show(e.Result.ToString());
           int t= e.Result;
           if (t == 1)
           {
               label4.Content = "Record is Saved...";
           }
           else
           {
               label4.Content = "Record is exist...";
           }
          
        }
    }
}


Q: What is the difference between an Interface and an Abstract class?


Q: What is the difference between an Interface and an Abstract class?



A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Sunday, 22 July 2012

OOP Design Concepts - Interfaces

What is an interface in OOP?
During the process of designing an application using OOP Paradigm, the application will be designed as a set of classes indicating how objects will be created each with specific status and behavior, as well as defining the ways of interaction between those objects. By this way, almost every class indicates a type(an abstracted data type in a more specific manner).
For example, a class named car indicates an object of type car that has a set of status variables and a set of methods that indicates how other objects can interact with it. Consider that we have a car that have the normal four wheels and another type that uses one wheel in the middle of the car to move!!.
The common behavior between the two types of cars is that they can move, either on 4 wheels or 1 wheel it does not make a difference, all what we care about is that they can move, so, simply we can consider the two cars as "Movable". The word movable indicates the ability of the two objects to move which is an indication of the behavior of them without concerning other details like; the model of the car or even the way they can move. These are interfaces.
Interfaces indicate how certain types of objects have to behave. If we want to indicate clearly how a movable object must behave, we will create an interface with a method named " move" and make every movable object provide how this method will be implemented.
In our example; we will create something like what follows:

public interface iMovable
{
public void move();
}

public class normalCar implements iMovable
{
//actual implementation of the move method declared in iMovable
public void move()
{
//the code required to make a normal car move
}
}

public class weirdCar implements iMovable
{
public void move()
{
//the weird code to make a weird car move
}
}


So, why do we need interfaces?
OOP tries to resemble how objects are defined in the real life, and interfaces are a very logical way of grouping objects in terms of behavior. Suppose that we are making a game that has the normal and the weird car,however, a creative team member came with the idea that we need to make the extra super weird car with no wheels and with the ability to turn to a frog to hide from enemies and many many extra features. If we are not using interfaces, the game logic will need to handle the motion of each car as if they are of different type in spite that logically they share the core common behavior.
Interfaces also enhance abstraction which is a core principal of OOP, design patterns like the factory pattern make a perfect use of interfaces through abstracting objects to know which implementation of a certain object type is provided. Interfaces make it very flexible to change implementations of services specially in multilayer applications, for example; in an application, we have a data base layer that have an object named UserDb which is responsible to get the data of the user from the database, and we have another one named UserTxtFile which retrieves the information from a plain text file.
Each of the user objects can be used by a higher layer to retrieve the user data without any modification to the code, inspect the following code:

public interface iUserInfo
{
string getUserName(int userId);
string getUserAge(string username);
}

public class UserDb implements iUserInfo
{
string getUserName(int userId)
{
//code to retrieve user info from the database
}
}

public class UserTxtFile implements iUserInfo
{
string getUserName(int userId)
{
//code to retrieve user info from the plain text file
}
}

public class UserManager()
{
private iUserInfo userInfo;

public string retrieveUserData(string userName)
{
return userInfo.getUserAge(userName);
}
}


Take a close look at the manager class and you will find that it has a reference variable of type iUserInfo, so, if this reference is provided by a factory method or by any other means, the code of the manager class will be the same regardless what implementation is provided. This approach maximizes flexibilty if some implementations need to be altered during the process of software development, as higher level layers will not be affected at all.
Another benefit of interfaces shows up during the development of large projects by large teams, at which the interface acts as a specification for developers with the set of methods they need to implement in classes of a certain type.

What interfaces are NOT?
- Unless the interface specifies a common behavior, do not create one. A common mistake is to use interfaces just to make some constants visible to objects in different layers.

- Interfaces are not a work around to multiple inhertience.

OOP Design Concepts - Abstract Classes


OOP Design Concepts - Abstract Classes

hey all, and specially soli who asked about abstract classes.
In this post we discuss abstract classes, however, it would be better if you read the post titled OOP Design Concepts - Interfaces first.

- What is an abstract class?

Abstract classes are partial classes, in other words, they are classes that needs to be inherited by other classes to be used. The word abstract means that methods inside such class are not completely implemented, an abstract class can mark some methods as abstract, so, the child class needs to implement them according to its behavior. An abstract class works as a generalized type that needs specialization for each subtype.



Well, i hate those complex descriptions, so lets get to the example mentioned previously in OOP Design Concepts - Interfaces. The case was that we had different types of cars and we specified their behavior by an interface named "iMovable", now, lets consider an extension to that design. Suppose that all cars starts using the same way using the same method of ignition, so, it is not relevant for every car to implement the method named "Start" with the same implementation. In this case we will introduce the abstract class named "Car", this class implements the "iMovable" interface and introduces a new method named "Start" and implements it. Now, any new car will extend the abstract car instead of directly implementing "iMovable".

- A closer look.
So, we did not forget that the abstract car implements iMovable, but we did not mention any thing about implementing iMovable's methods?. yes, the methods are still treated the same way, as the classes extending the abstract car are still responsible for providing the actual implemenation of such methods, in our case, it is the single move method. Methods in interfaces are abstract by default, and marking a class as abstract indicates that this class is not yet complete, so it has the option to implement what it wants from the interface, and in our case, we need nothing from the interface to be implemented in the abstract car.
Now, any car extending the abstract car can use the start method directly but it still have to implement how the move method will be implemented.
An abstract class may implement methods declared in an interface, thus, making it an option for subclasses to override those methods or not.

-Why?
The previous modification makes classification perfect, as we said before, it is all about logical thinking, reconsidering the first design that rely only on interfaces, you will find it not logic that every movable object is a car!!, so, abstract classes provides an extra level of specialization, as we can introduce an extra specification level to more subtypes. In our case, we defined a common behavior for cars, if we have planes, we will introduce the plane type the same way we did with cars.

-Coding
lets see an java code segment declaring our example class.

public abstract class Car implements iMovable{

public void start()
{
//code for starting engine
}

//Another method marked abstract for implementation by child classes
public abstract void koko(); 
}


public class NormalCar extends Car{

//The method declared by the iMovable interface.
public void move()
{
//code for moving...
}

public void koko()
{
//Code for the koko method which does anything.....
}

}


Marking a method as abstract, makes it a must for child classes to implement such a method or the code will not compile, thus forcing the same kind of behavioral description provided by interfaces in the older design.