Windows Store Apps and Oracle Database (C#) |
Windows Store Apps and Oracle Database (C#) บทความนี้จะเป็นการเขียน Windows Store Apps เพื่อติดต่อกับ Oracle Database ด้วยการอ่านข้อมูลที่อยู่บน Table (ตาราง) มาแสดงบนหน้าจอ Apps แบบง่าย ๆ ก่อนที่จะเขียนติดต่อกับ Oracle Database นั้นให้ทำความเข้าใจนิดหนึ่งก่อนว่า WinRT API นั้นจะไม่มี Class ที่เกี่ยวข้องกับ System.Data และ System.Data.OracleClient ฉะนั้นการที่จะเขียน Windows Store Apps เพื่อติดต่อกับ Oracle Database โดยตรงเหมือนกับ .NET Application ทั่ว ๆ ไป นั้นจะใช้ไมได้กับ Windows Store Apps ฉะนั้นทางเลือกที่เราจะเขียนติดต่อกันได้คือจะต้องผ่านตัวกลาง อาจจะอยู่ในรูปแบบของ API ,Restful หรือ Web Services แต่วิธที่จะแนะนำและง่ายที่สุดคือ Web Services เพราะมีรูปแบบการใช้งานที่ง่าย โดยเราสามารถเขียนและออกแบบ Method บน Web Services ต่าง ๆ จากนั้นเพียงแค่ใช้ Windows Store Apps ไป Call ตัว Method ที่อยู่บน Web Services ก็จะได้ค่าต่าง ๆ ที่ต้องการกลับมา
Windows Store Apps and Oracle Database (C#)
ซึ่งรูปแบบการใช้ Web Services กับ Oracle Database นั้นเราจะต้องมีตัวกลาง ก็คือจะต้องมี Web Services ที่ทำหน้าที่คอยบริการ Services และติดต่อกับ Oracle Database อยุ่ตลอดเวลา

โครงสร้าง Table บน Oracle Database

01. create table customer
02. (
03. CUSTOMERID varchar2(4),
04. NAME varchar2(50),
05. EMAIL varchar2(50),
06. COUNTRYCODE varchar2(3),
07. BUDGET number,
08. USED number
09. )
10. tablespace SYSTEM
11. storage
12. (
13. initial 64K
14. minextents 1
15. maxextents unlimited
16. );
17. alter table customer
18. add constraint PK_CUSTOMER primary key (CUSTOMERID);
19.
20. INSERT INTO customer VALUES ( 'C001' , 'Win Weerachai' , 'win.weerachai@thaicreate.com' , 'TH' , 1000000, 600000);
21. INSERT INTO customer VALUES ( 'C002' , 'John Smith' , 'john.smith@thaicreate.com' , 'UK' , 2000000, 800000);
22. INSERT INTO customer VALUES ( 'C003' , 'Jame Born' , 'jame.born@thaicreate.com' , 'US' , 3000000, 600000);
23. INSERT INTO customer VALUES ( 'C004' , 'Chalee Angel' , 'chalee.angel@thaicreate.com' , 'US' , 4000000, 100000);
ตัวอย่างฐานข้อมูลที่อยู่บน Oracle Database
ขั้นตอนที่ 1 การสร้าง Web Services เพื่อเรียกใช้งาน Oracle ซึ่งในบทความนี้จะใช้ ASP.Net เป็นตัวที่จะทำหน้าที่เป็น Web Services

ในการสร้าง Web Services ด้วย ASP.Net ให้เลือกสร้าง Item ชื่อว่า Web Services (ASMX) โดยไฟล์ Web Services ของ ASP.Net จะได้นามสกุลไฟล์เป็น .asmx
เรียกใช้งาน Class สำหรับติดต่อกับ Oracle และการสร้าง JSON
1. using System.Data;
2. using Newtonsoft.Json;
3. using System.Data.OracleClient;
คำสั่งการติดต่อกับ Oracle
1. strConnString = "Data Source=TCDB;User Id=myuser;Password=mypassword;" ;
2. strSQL = "SELECT * FROM customer" ;
3.
4. objConn.ConnectionString = strConnString;
5.
6. objCmd.Connection = objConn;
7. objCmd.CommandText = strSQL;
8. objCmd.CommandType = CommandType.Text;
TCDB คือ TNS Name (Oracle Create TNS Name (Net Service))
การแปลงค่าเป็น JSON
1. string json = JsonConvert.SerializeObject(dt, Formatting.Indented);
2. return json;
Code ทั้งหมด
01. using System;
02. using System.Collections.Generic;
03. using System.Linq;
04. using System.Web;
05. using System.Web.Services;
06.
07. using System.Data;
08. using Newtonsoft.Json;
09. using System.Data.OracleClient;
10.
11. namespace myAppWeb
12. {
13. /// <summary>
14. /// Summary description for myWSV
15. /// </summary>
17. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
18. [System.ComponentModel.ToolboxItem( false )]
19.
20.
21. public class myWSV : System.Web.Services.WebService
22. {
23.
24. [WebMethod]
25. public string getCustomerData()
26. {
27. OracleConnection objConn = new OracleConnection();
28. OracleCommand objCmd = new OracleCommand();
29. OracleDataAdapter dtAdapter = new OracleDataAdapter();
30.
31. DataSet ds = new DataSet();
32. DataTable dt;
33. String strConnString, strSQL;
34.
35.
36. strConnString = "Data Source=TCDB;User Id=myuser;Password=mypassword;" ;
37. strSQL = "SELECT * FROM customer" ;
38.
39. objConn.ConnectionString = strConnString;
40.
41. objCmd.Connection = objConn;
42. objCmd.CommandText = strSQL;
43. objCmd.CommandType = CommandType.Text;
44.
45. dtAdapter.SelectCommand = objCmd;
46.
47. dtAdapter.Fill(ds);
48. dt = ds.Tables[0];
49.
50. dtAdapter = null ;
51. objConn.Close();
52. objConn = null ;
53.
54. string json = JsonConvert.SerializeObject(dt, Formatting.Indented);
55. return json;
56. }
57.
58. }
59. }
เป็นไฟล์ Web Services และการติดต่อกับ Oracle Database ซึ่งเราจะส่งค่า JSON กลับมา

ทดสอบการทำงานของ Web Services

คลิก Invoke

เป็นตัวอย่างไฟล์ JSON ที่ถูกส่งมาจาก Web Services
[ { "CustomerID": "C001", "Name": "Win Weerachai", "Email": "win.weerachai@thaicreate.com", "CountryCode": "TH", "Budget": 1000000.0, "Used": 600000.0 }, { "CustomerID": "C002", "Name": "John Smith", "Email": "john.smith@thaicreate.com", "CountryCode": "UK", "Budget": 2000000.0, "Used": 800000.0 }, { "CustomerID": "C003", "Name": "Jame Born", "Email": "jame.born@thaicreate.com", "CountryCode": "US", "Budget": 3000000.0, "Used": 600000.0 }, { "CustomerID": "C004", "Name": "Chalee Angel", "Email": "chalee.angel@thaicreate.com", "CountryCode": "US", "Budget": 4000000.0, "Used": 100000.0 } ]
ขั้นตอนที่ 2 การสร้าง Windows Store Apps เพื่อเรียกใช้งาน Web Services ที่ติดต่อกับ Oracle

คลิกวาที่ Reference เลือก Add Service Reference

จากนั้นกรอก URL ของ Services และระบุชื่อ Services Name ที่ต้องการเรียกใช้งาน

ได้ Services เรียบร้อยแล้ว จากนั้นเราจะเรียกใช้งาน Web Services บน Windows Store Apps
MainPage.xaml

ออกแบบหน้าจอดังรูป
01. < Page
02. x:Class = "WindowsStoreApps.MainPage"
05. xmlns:local = "using:WindowsStoreApps"
08. mc:Ignorable = "d" >
09.
10.
11. < Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}" >
12.
13. < Button x:Name = "btnSubmit" Content = "Submit" HorizontalAlignment = "Left" Margin = "137,68,0,0" VerticalAlignment = "Top" FontSize = "20" Width = "120" Click = "btnSubmit_Click" />
14.
15. < ListView x:Name = "myListView" HorizontalAlignment = "Left" Height = "386" Margin = "140,165,0,0" VerticalAlignment = "Top" Width = "907" >
16. < ListView.ItemTemplate >
17. < DataTemplate >
18. < StackPanel Orientation = "Horizontal" Margin = "0,0,0,17" >
19. < StackPanel Width = "80" >
20. < TextBlock Text = "{Binding CustomerID}" TextWrapping = "Wrap" FontSize = "20" Foreground = "#FFBFB9B9" Margin = "5,0,0,0" FontFamily = "Global User Interface" />
21. </ StackPanel >
22. < StackPanel Width = "150" >
23. < TextBlock Text = "{Binding Name}" TextWrapping = "Wrap" FontSize = "20" Foreground = "#FFBFB9B9" Margin = "5,0,0,0" />
24. </ StackPanel >
25. < StackPanel Width = "300" >
26. < TextBlock Text = "{Binding Email}" TextWrapping = "Wrap" FontSize = "20" Foreground = "#FFBFB9B9" Margin = "5,0,0,0" />
27. </ StackPanel >
28. < StackPanel Width = "50" >
29. < TextBlock Text = "{Binding CountryCode}" TextWrapping = "Wrap" FontSize = "20" Foreground = "#FFBFB9B9" Margin = "5,0,0,0" />
30. </ StackPanel >
31. < StackPanel Width = "100" >
32. < TextBlock Text = "{Binding Budget}" TextWrapping = "Wrap" FontSize = "20" Foreground = "#FFBFB9B9" Margin = "5,0,0,0" />
33. </ StackPanel >
34. < StackPanel Width = "100" >
35. < TextBlock Text = "{Binding Used}" TextWrapping = "Wrap" FontSize = "20" Foreground = "#FFBFB9B9" Margin = "5,0,0,0" />
36. </ StackPanel >
37. </ StackPanel >
38. </ DataTemplate >
39. </ ListView.ItemTemplate >
40. </ ListView >
41.
42. </ Grid >
43.
44. </ Page >
MainPage.xaml.cs
01. using System;
02. using System.Collections.Generic;
03. using System.IO;
04. using System.Linq;
05. using Windows.Devices.Geolocation;
06. using Windows.Foundation;
07. using Windows.Foundation.Collections;
08. using Windows.UI.Core;
09. using Windows.UI.Xaml;
10. using Windows.UI.Xaml.Controls;
11. using Windows.UI.Xaml.Controls.Primitives;
12. using Windows.UI.Xaml.Data;
13. using Windows.UI.Xaml.Input;
14. using Windows.UI.Xaml.Media;
15. using Windows.UI.Xaml.Navigation;
16.
17. using WindowsStoreApps.myWebServices;
18.
19. using System.Xml.Linq;
20. using System.Runtime.Serialization;
21. using System.Runtime.Serialization.Json;
22. using System.Collections.ObjectModel;
23. using System.Text;
24.
25.
26.
27. namespace WindowsStoreApps
28. {
29. /// <summary>
30. /// An empty page that can be used on its own or navigated to within a Frame.
31. /// </summary>
32. ///
33.
34. public sealed partial class MainPage : Page
35. {
36. public MainPage()
37. {
38. this .InitializeComponent();
39. }
40.
41. public class myCustomer
42. {
43. public string CustomerID { get ; set ; }
44. public string Name { get ; set ; }
45. public string Email { get ; set ; }
46. public string CountryCode { get ; set ; }
47. public string Budget { get ; set ; }
48. public string Used { get ; set ; }
49. }
50.
51. private async void btnSubmit_Click( object sender, RoutedEventArgs e)
52. {
53.
54. var client = new myWebServices.myWSVSoapClient();
55. var result = await client.getCustomerDataAsync();
56.
57. string jsonData = result.Body.getCustomerDataResult;
58.
59. MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
60. ObservableCollection<myCustomer> list = new ObservableCollection<myCustomer>();
61. DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof (ObservableCollection<myCustomer>));
62. list = (ObservableCollection<myCustomer>)serializer.ReadObject(ms);
63.
64. this .myListView.ItemsSource = list;
65.
66. }
67.
68. }
69.
70. }
Result

ค่าที่ได้จาก Web Services ที่อ่านจาก Oracle Database
อ่านเพิ่มเติม Windows Store App and Web Services (C#)
ตัวอย่างการ Insert ข้อมูล
01. using System;
02. using System.Collections.Generic;
03. using System.Linq;
04. using System.Web;
05. using System.Web.Services;
06.
07. using System.Data;
08. using Newtonsoft.Json;
09. using System.Data.OracleClient;
10.
11. namespace myAppWeb
12. {
13. /// <summary>
14. /// Summary description for myWSV
15. /// </summary>
17. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
18. [System.ComponentModel.ToolboxItem( false )]
19.
20.
21. public class myWSV : System.Web.Services.WebService
22. {
23.
24.
25. [WebMethod]
26. public string AddData( string sCustomerID,
27. string sName,
28. string sEmail,
29. string sCountryCode,
30. string sBudget,
31. string sUsed)
32. {
33.
34. try
35. {
36. OracleConnection objConn = new OracleConnection();
37. OracleCommand objCmd = new OracleCommand();
38.
39. String strConnString, strSQL;
40.
41. strConnString = "Data Source=TCDB;User Id=myuser;Password=mypassword;" ;
42.
43. objConn.ConnectionString = strConnString;
44. objConn.Open();
45.
46. strSQL = "INSERT INTO customer (CUSTOMERID,NAME,EMAIL,COUNTRYCODE,BUDGET,USED) VALUES " +
47. " ('" + sCustomerID + "' " +
48. " ,'" + sName + "' " +
49. " ,'" + sEmail + "' " +
50. " ,'" + sCountryCode + "' " +
51. " ,'" + sBudget + "' " +
52. " ,'" + sUsed + "') " ;
53.
54. objCmd = new OracleCommand();
55. objCmd.Connection = objConn;
56. objCmd.CommandText = strSQL;
57. objCmd.CommandType = CommandType.Text;
58. objCmd.ExecuteNonQuery();
59.
60. return "1" ;
61.
62. }
63. catch (Exception ex)
64. {
65. return "0" ;
66. }
67. }
68.
69.
70. }
71. }
01. private async void btnSave_Click( object sender, RoutedEventArgs e)
02. {
03.
04. var client = new myWebServices.myWSVSoapClient();
05. var result = await client.AddDataAsync( this .txtCustomerID.Text,
06. this .txtName.Text,
07. this .txtEmail.Text,
08. this .txtCountryCode.Text,
09. this .txtBudget.Text,
10. this .txtUsed.Text);
11.
12. string jsonData = result.Body.AddDataResult;
13.
14. if (jsonData == "0" )
15. {
16. MessageDialog msgDialog = new MessageDialog( "Add Data Failed" , "Error" );
17. await msgDialog.ShowAsync();
18. }
19. else
20. {
21. MessageDialog msgDialog = new MessageDialog( "Add Data Success." , "Success" );
22. await msgDialog.ShowAsync();
23. }
24.
25. }
ตัวอย่างการ Update ข้อมูล
01. using System;
02. using System.Collections.Generic;
03. using System.Linq;
04. using System.Web;
05. using System.Web.Services;
06.
07. using System.Data;
08. using Newtonsoft.Json;
09. using System.Data.OracleClient;
10.
11. namespace myAppWeb
12. {
13. /// <summary>
14. /// Summary description for myWSV
15. /// </summary>
17. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
18. [System.ComponentModel.ToolboxItem( false )]
19.
20.
21. public class myWSV : System.Web.Services.WebService
22. {
23.
24. [WebMethod]
25. public void UpdateData( string sCustomerID,
26. string sName,
27. string sEmail,
28. string sCountryCode,
29. string sBudget,
30. string sUsed)
31. {
32.
33. OracleConnection objConn = new OracleConnection();
34. OracleCommand objCmd = new OracleCommand();
35.
36. String strConnString, strSQL;
37.
38. strConnString = "Data Source=TCDB;User Id=myuser;Password=mypassword;" ;
39.
40. objConn.ConnectionString = strConnString;
41. objConn.Open();
42.
43. strSQL = "UPDATE customer SET " +
44. " NAME = '" + sName + "' " +
45. " ,EMAIL = '" + sEmail + "' " +
46. " ,COUNTRYCODE = '" + sCountryCode + "' " +
47. " ,BUDGET = '" + sBudget + "' " +
48. " ,USED = '" + sUsed + "' " +
49. " WHERE CUSTOMERID = '" + sCustomerID + "' " ;
50.
51. objCmd = new OracleCommand();
52. objCmd.Connection = objConn;
53. objCmd.CommandText = strSQL;
54. objCmd.CommandType = CommandType.Text;
55. objCmd.ExecuteNonQuery();
56. }
57.
58. }
59. }
01. private async void btnSave_Click( object sender, RoutedEventArgs e)
02. {
03. var client = new myWebServices.myWSVSoapClient();
04. var result = await client.UpdateDataAsync( this .lblCustomerID.Text,
05. this .txtName.Text,
06. this .txtEmail.Text,
07. this .txtCountryCode.Text,
08. this .txtBudget.Text,
09. this .txtUsed.Text);
10.
11. this .Frame.Navigate( typeof (MainPage));
12. }
ตัวอย่างการ Delete ข้อมูล
01. using System;
02. using System.Collections.Generic;
03. using System.Linq;
04. using System.Web;
05. using System.Web.Services;
06.
07. using System.Data;
08. using Newtonsoft.Json;
09. using System.Data.OracleClient;
10.
11. namespace myAppWeb
12. {
13. /// <summary>
14. /// Summary description for myWSV
15. /// </summary>
17. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
18. [System.ComponentModel.ToolboxItem( false )]
19.
20.
21. public class myWSV : System.Web.Services.WebService
22. {
23.
24. [WebMethod]
25. public void DeleteData( string sCustomerID)
26. {
27.
28. OracleConnection objConn = new OracleConnection();
29. OracleCommand objCmd = new OracleCommand();
30.
31. String strConnString, strSQL;
32.
33. strConnString = "Data Source=TCDB;User Id=myuser;Password=mypassword;" ;
34. strSQL = "DELETE FROM customer WHERE CUSTOMERID ='" + sCustomerID + "'" ;
35.
36. objConn.ConnectionString = strConnString;
37. objConn.Open();
38.
39. objCmd = new OracleCommand();
40. objCmd.Connection = objConn;
41. objCmd.CommandText = strSQL;
42. objCmd.CommandType = CommandType.Text;
43. objCmd.ExecuteNonQuery();
44.
45. }
46.
47. }
48. }
1. private async void btnDelete_Click( object sender, RoutedEventArgs e)
2. {
3. string CustomerID = "C001" ;
4.
5. var client = new myWebServices.myWSVSoapClient();
6. var result = await client.DeleteDataAsync(CustomerID);
7. }
.
|