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

Tuesday, April 14, 2015

JavaScriptSerializer: JSON serialize và deserialize trong C#

Ngày này JSON đang trở nên phổ biến bởi tính tiện lợi của nó so với XML. Với .Net thư viện JavaScriptSerializer đã được phát triển giúp cho việc chuyển đổi dữ liệu dang định dạng JSON trở nên rất đơn giản.

Chúng ta cùng tìm hiểu một chút về thư viện này qua ví dụ sau:
Mã nguồn
Định nghĩa lớp

[sourcecode language="csharp"]

public class Student
{
public Student()
{
}
public Student(int id, string name)
{
_id = id;
_name = name;
}

int _id;
string _name;
public int ID
{
get
{
return _id;
}

set
{
_id = value;
}
}

public string Name
{
get
{
return _name;
}

set
{
_name = value;
}
}
}
[/sourcecode]

Chuyển đối tượng sang json
[sourcecode language="csharp"]
Student s = new Student(100, "Nguyễn Văn Mít");
string str = serializer.Serialize(s);
Response.Write("Object: " + str);
[/sourcecode]

Kết quả chạy có như sau:
Object: {"ID":100,"Name":"Nguyễn Văn Mít"}

Chuyển từ chuỗi JSON sang đối tượng Student
[sourcecode language="csharp"]
Student s1 = serializer.Deserialize<Student>(str);
Response.Write("<br/>Name: " + s1.Name);
[/sourcecode]

Tương tự như vậy chúng ta cũng có thể chuyển một mảng sang JSON và ngược lại
Tạo một mảng như sau
[sourcecode language="csharp"]
List<Student> list = new List<Student>();
list.Add(new Student(1, "Trần Văn Cam"));
list.Add(new Student(2, "Trần Thanh Long"));
list.Add(new Student(3, "Lê Thị Lựu"));

string strlist = serializer.Serialize(list);
Response.Write("<br/>List: " + strlist);

// in
Response.Write("<br/>List deserialize ");
List<Student> listDe = serializer.Deserialize<List<Student>>(strlist);
foreach (Student item in listDe)
{
Response.Write("<br/>Name: " + item.Name);
}
[/sourcecode]

Chạy lại ví dụ, chúng ta có kết quả
List: [{"ID":1,"Name":"Trần Văn Cam"},{"ID":2,"Name":"Trần Thanh Long"},{"ID":3,"Name":"Lê Thị Lựu"}]

Chuyển một DataTable sang JSON và ngược lại
Kết nối và đọc dữ liệu
[sourcecode language="csharp"]
SqlConnection conn = new SqlConnection("server=.;database=northwind;uid=sa;pwd=sa;");
SqlDataAdapter adp = new SqlDataAdapter("Select employeeid, firstname, lastname, birthdate, photopath from employees", conn);
DataSet ds = new DataSet();
adp.Fill(ds, "Emp");
[/sourcecode]

Chuyển sang JSON
[sourcecode language="csharp"]
List<Dictionary<string, object>> table = new List<Dictionary<string, object>>();
foreach (DataRow r in ds.Tables[0].Rows)
{
Dictionary<string, object> column = new Dictionary<string, object>();
foreach (DataColumn c in ds.Tables[0].Columns)
{
column.Add(c.ColumnName, r[c.ColumnName]);
}
table.Add(column);
}

string dsStr = serializer.Serialize(table);
Response.Write("<br/>Data table: " + dsStr);
[/sourcecode]

Chuyển từ JSON sang DataTable
[sourcecode language="csharp"]
List<Dictionary<string, object>> t2 = serializer.Deserialize<List<Dictionary<string, object>>>(dsStr);
DataTable dt = ds.Tables[0];
dt.Clear();
DataRow deRow;
foreach (Dictionary<string, object> d in t2)
{
deRow = dt.NewRow();
foreach (DataColumn col in dt.Columns)
{
deRow[col.ColumnName] = (d[col.ColumnName] == null ? DBNull.Value : d[col.ColumnName]);
}
dt.Rows.Add(deRow);
}
GridView1.DataSource = dt;
GridView1.DataBind();
[/sourcecode]

Tới đây chạy lại ví dụ có kết quả như sau:

Data table: [{"employeeid":1,"firstname":"Mit","lastname":"Nguyen Van","birthdate":"\/Date(-664786800000)\/","photopath":"http://accweb/emmployees/davolio.bmp"},{"employeeid":2,"firstname":"Fuller","lastname":"Andrew","birthdate":"\/Date(-563871600000)\/","photopath":"http://accweb/emmployees/fuller.bmp"},{"employeeid":3,"firstname":"Janetsssss","lastname":"Leverling","birthdate":"\/Date(-200127600000)\/","photopath":"http://accweb/emmployees/leverling.bmp"},{"employeeid":4,"firstname":"Margaret","lastname":"Peacockdd","birthdate":"\/Date(-1018854000000)\/","photopath":"http://accweb/emmployees/peacock.bmp"},{"employeeid":5,"firstname":"Buchanan","lastname":"Steven","birthdate":"\/Date(-468054000000)\/","photopath":"http://accweb/emmployees/buchanan.bmp"},{"employeeid":6,"firstname":"Suyama","lastname":"Michael","birthdate":"\/Date(1278003600000)\/","photopath":"http://accweb/emmployees/davolio.bmp"},{"employeeid":7,"firstname":"Robert","lastname":"King","birthdate":"\/Date(-302770800000)\/","photopath":"http://accweb/emmployees/davolio.bmp"},{"employeeid":8,"firstname":"Lauradddd","lastname":"Callahan","birthdate":"\/Date(-378025200000)\/","photopath":"http://accweb/emmployees/davolio.bmp"},{"employeeid":9,"firstname":"Anne","lastname":"9","birthdate":"\/Date(-124009200000)\/","photopath":"http://accweb/emmployees/davolio.bmp"},{"employeeid":87,"firstname":"Mr","lastname":"Ben","birthdate":"\/Date(-664786800000)\/","photopath":null},{"employeeid":89,"firstname":"Mrdddd","lastname":"dd","birthdate":"\/Date(-664786800000)\/","photopath":null},{"employeeid":91,"firstname":"Dan","lastname":"Mss","birthdate":"\/Date(-664786800000)\/","photopath":null},{"employeeid":102,"firstname":"Mr","lastname":"Been","birthdate":"\/Date(340822800000)\/","photopath":null},{"employeeid":103,"firstname":"Mr","lastname":"Dan","birthdate":"\/Date(340822800000)\/","photopath":null},{"employeeid":105,"firstname":"Mr","lastname":"Been","birthdate":"\/Date(-664786800000)\/","photopath":null},{"employeeid":106,"firstname":"Mr","lastname":"Dan","birthdate":"\/Date(-664786800000)\/","photopath":null}]


table

Như vậy là cơ bản chúng ta có thể chuyển đổi qua lại giữa JSON và một vài kiểu của .net.


Trong PHP

Friday, October 11, 2013

Xây dựng và sử dụng WCF đơn giản (WCF basic demo for student)

Objectives

1. Create WCF service (host on web server )

2. Using WCF service from window form application

Hits: Step for create and using service
  • Create WCF service “Student” with two operations “list()” and “detail(id)”
    1. Define service interface (ServiceContract)
    2. Define class describe detail of student (DataContract)
    3. Define Service by implement from server interface
  • Using WCF service from window form application
    1. Find service description of WCF “student”
    2. Reference WCF service
    3. Call operations of student service

Student table

No. Data field Data type
1. S_ID Int
2. S_FullName Text
3. S_Birthdate DateTime
4. S_Address Text

WCF basic demo 2013 (PDF version of this post)

http://www.mediafire.com/?ji9uiz5l70d8n (Source code of this post)

BEGIN

Open visual studio 2008 (or later)

File -> Create Project

clip_image002

Select as figure

Right click on project -> Add new Item

clip_image004

Select as figure

Right click on project -> Add new Item

clip_image006

Select as figure

Modified class as

1 namespace students
2 {
3 [DataContract]
4 public class StudentDetail
5 {
6 [DataMember]
7 public int ID;
8 [DataMember]
9 public string FullName;
10 [DataMember]
11 public DateTime Birthdate;
12 [DataMember]
13 public string Address;
14 }
15 }
16
17 Modified IStudent interface as
18
19 namespace students
20 {
21 [ServiceContract]
22 public interface IStudent
23 {
24 [OperationContract]
25 DataSet List();
26 [OperationContract]
27 StudentDetail Detail(int ID);
28 }
29 }

Edit Student service as


clip_image002[4]



1 namespace students
2 {
3 public class Student : IStudent
4 {
5 public DataSet List()
6 {
7 DataSet dsS = new DataSet();
8 // insert C# code to get data from student table
9 return dsS;
10 }
11 public StudentDetail Detail(int ID)
12 {
13 StudentDetail sDetail = new StudentDetail();
14 return sDetail;
15 }
16 }
17 }
18
Now right click on service and select view in browser


clip_image005


Right click on solution -> add new project


clip_image007


Select as figure


Design form as


clip_image010


GUI of client


Add service reference as


clip_image012


Modify form load event:


1 wcf.StudentClient proxy;
2 private void Form1_Load(object sender, EventArgs e)
3 {
4 proxy = new WCF_Client.wcf.StudentClient();
5 }

Double click on button Find and insert code as


1 private void btnFind_Click(object sender, EventArgs e)
2 {
3 wcf.StudentDetail detail = proxy.Detail(Convert.ToInt32(txtID.Text));
4 MessageBox.Show("Student id: " + detail.ID + "\nStudent fullname: " + detail.FullName);
5 }
6

Double click on button List and insert code as


1 private void btnList_Click(object sender, EventArgs e)
2 {
3 dgrStudent.DataSource = proxy.List();
4 dgrStudent.DataMember = "student";
5 }

Now run client


clip_image014


Client at runtime








Xem hướng dẫn video trên


Mã nguồn:  http://www.mediafire.com/download/f4l6dpz2wla513w/WebApplication1.rar

Translate