Windows Phone 7 网络编程之留言板应用

 这个简易的留言板,是通过手机客户端与web程序的交互来设计的,保存留言的时候将数据传输到web,显示留言的时候再从数据库取数通过web传输到客户端。加强对HttpWebRequest异步请求的学习。

 

Windows Phone 7 网络编程之留言板应用 

 


  1. <phone:PhoneApplicationPage   
  2.     x:Class="WindowsPhoneLiuyan.MainPage" 
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  5.     xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
  6.     xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
  7.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  8.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  9.     xmlns:Data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" 
  10.     mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768" 
  11.     FontFamily="{StaticResource PhoneFontFamilyNormal}" 
  12.     FontSize="{StaticResource PhoneFontSizeNormal}" 
  13.     Foreground="{StaticResource PhoneForegroundBrush}" 
  14.     SupportedOrientations="Portrait" Orientation="Portrait" 
  15.     shell:SystemTray.IsVisible="True"> 
  16.  
  17.     <!--LayoutRoot is the root grid where all page content is placed--> 
  18.     <Grid x:Name="LayoutRoot" Background="Transparent"> 
  19.         <Grid.RowDefinitions> 
  20.             <RowDefinition Height="Auto"/> 
  21.             <RowDefinition Height="*"/> 
  22.         </Grid.RowDefinitions> 
  23.  
  24.         <!--TitlePanel contains the name of the application and page title--> 
  25.         <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> 
  26.             <TextBlock x:Name="PageTitle" Text="网络留言板" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> 
  27.         </StackPanel> 
  28.  
  29.         <!--ContentPanel - place additional content here--> 
  30.         <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> 
  31.             <Canvas  Height="600" Margin="0,4,6,4"> 
  32.                 <TextBlock x:Name="name1" Canvas.Top="327" Canvas.Left="8" Text="网   名:" Foreground="#FFF7F6F6"/> 
  33.                 <TextBox x:Name="name" Width="122" Canvas.Left="86" Canvas.Top="308" Background="#FFFBF6F6"/> 
  34.                 <TextBlock x:Name="message1" Canvas.Left="11" Canvas.Top="360" Text="留 言:" Foreground="#FFFBF9F9"/> 
  35.                 <TextBox x:Name="message" Width="321" Canvas.Left="86" Canvas.Top="360" VerticalScrollBarVisibility="Hidden" Height="124"/> 
  36.                 <Button Canvas.Left="30" Canvas.Top="490" Content="保存" Height="71" Name="save" Width="160" Click="save_Click" /> 
  37.                 <Button Canvas.Left="217" Canvas.Top="490" Content="重置" Height="71" Name="reset" Width="160" Click="reset_Click" /> 
  38.                 <TextBox Canvas.Left="-4" Canvas.Top="6" Height="296" Name="messages" Text="TextBox" Width="460" AcceptsReturn="True" /> 
  39.             </Canvas> 
  40.         </Grid> 
  41.     </Grid> 
  42. </phone:PhoneApplicationPage> 

 


  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Windows;  
  6. using System.Windows.Controls;  
  7. using System.Windows.Documents;  
  8. using System.Windows.Input;  
  9. using System.Windows.Media;  
  10. using System.Windows.Media.Animation;  
  11. using System.Windows.Shapes;  
  12. using Microsoft.Phone.Controls;  
  13. using System.Text;  
  14. using System.IO;  
  15. using System.Collections.ObjectModel;  
  16.  
  17. namespace WindowsPhoneLiuyan  
  18. {  
  19.     public partial class MainPage : PhoneApplicationPage  
  20.     {  
  21.         public MainPage()  
  22.         {  
  23.             InitializeComponent();  
  24.             getMessage();  
  25.         }  
  26.  
  27.         private void save_Click(object sender, RoutedEventArgs e)  
  28.         {  
  29.             UriBuilder fullUri = new UriBuilder("http://localhost/liuyan/messege.ashx");  
  30.             fullUri.Query = "type=insert&name=" + name.Text + "&description=" + message.Text;  
  31.             // 创建WebRequest  
  32.             HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);  
  33.             // 创建同步的AsyncRequest  
  34.             UpdateState State = new UpdateState();  
  35.             State.AsyncRequest = myRequest;  
  36.             // 开始异步请求  
  37.             myRequest.BeginGetResponse(new AsyncCallback(HandleMyResponse), State);  
  38.         }  
  39.  
  40.         public void getMessage()  
  41.         {  
  42.             UriBuilder fullUri = new UriBuilder("http://localhost/liuyan/messege.ashx");  
  43.             fullUri.Query = "type=get";  
  44.             // 创建WebRequest  
  45.             HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);  
  46.             // 创建同步的AsyncRequest  
  47.             UpdateState State = new UpdateState();  
  48.             State.AsyncRequest = myRequest;  
  49.             // 开始异步请求  
  50.             myRequest.BeginGetResponse(new AsyncCallback(HandleMyResponse), State);  
  51.         }  
  52.  
  53.         private void HandleMyResponse(IAsyncResult asyncResult)  
  54.         {  
  55.             // 获取返回的信息  
  56.             UpdateState myState = (UpdateState)asyncResult.AsyncState;  
  57.             HttpWebRequest myRequest = (HttpWebRequest)myState.AsyncRequest;  
  58.             //结束异步请求  
  59.             myState.AsyncResponse = (HttpWebResponse)myRequest.EndGetResponse(asyncResult);  
  60.             Stream streamResult = myState.AsyncResponse.GetResponseStream();  
  61.  
  62.             Deployment.Current.Dispatcher.BeginInvoke(() => 
  63.             {  
  64.                 if (streamResult.Length != 0)  
  65.                 {  
  66.                     StreamReader sr = new StreamReader(streamResult);  
  67.                     messages.Text = sr.ReadToEnd();  
  68.                 }  
  69.             });  
  70.         }  
  71.  
  72.         private void reset_Click(object sender, RoutedEventArgs e)  
  73.         {  
  74.             name.Text = "";  
  75.             message.Text = "";  
  76.         }  
  77.  
  78.     }  
  79.  
  80.     public class UpdateState  
  81.     {  
  82.         public HttpWebRequest AsyncRequest { get; set; }  
  83.         public HttpWebResponse AsyncResponse { get; set; }  
  84.     }  

web依然使用.NET

Message.ashx文件

 


  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data.OleDb;  
  6. using System.Data;  
  7.  
  8. namespace liuyan.Web  
  9. {  
  10.     /// <summary> 
  11.     /// Messege 的摘要说明  
  12.     /// </summary> 
  13.     public class Message : IHttpHandler  
  14.     {  
  15.  
  16.         public void ProcessRequest(HttpContext context)  
  17.         {  
  18.             context.Response.ContentType = "text/plain";  
  19.             string type = context.Request.QueryString["type"].ToString();  
  20.             switch (type)  
  21.             {  
  22.                 case "get":  
  23.                     get(context);  
  24.                     break;  
  25.                 case "insert":  
  26.                     insert(context);  
  27.                     break;  
  28.                 default:  
  29.                     break;  
  30.             }  
  31.         }  
  32.         /// <summary> 
  33.         /// 获取留言板数据  
  34.         /// </summary> 
  35.         /// <param name="context"></param> 
  36.         public void get(HttpContext context)  
  37.         {  
  38.             string messages = "";  
  39.             OleDbCommand cmd = new OleDbCommand();  
  40.             SQLExcute("SELECT * from about order by id desc", cmd);  
  41.             OleDbDataAdapter da = new OleDbDataAdapter();  
  42.             da.SelectCommand = cmd;  
  43.             DataSet ds = new DataSet();  
  44.             da.Fill(ds);  
  45.  
  46.             foreach (DataRow dr in ds.Tables[0].Rows)  
  47.             {  
  48.                 messages += dr[1] + " say:" + dr[2]+" ";  
  49.             }  
  50.  
  51.             context.Response.Write(messages.ToString());  
  52.         }  
  53.         /// <summary> 
  54.         /// 先往access数据库插入数据  然后再查询返回数据  
  55.         /// </summary> 
  56.         /// <param name="context"></param> 
  57.         public void insert(HttpContext context)  
  58.         {  
  59.             string name = context.Request.QueryString["name"].ToString();  
  60.             string description = context.Request.QueryString["description"].ToString();  
  61.             string sql = "insert into about(name,description) values('" + name + "','" + description + "')";  
  62.             SQLExcute(sql);  
  63.             string messages = "";  
  64.             OleDbCommand cmd = new OleDbCommand();  
  65.             SQLExcute("SELECT * from about order by id desc", cmd);  
  66.             OleDbDataAdapter da = new OleDbDataAdapter();  
  67.             da.SelectCommand = cmd;  
  68.             DataSet ds = new DataSet();  
  69.             da.Fill(ds);  
  70.  
  71.             foreach (DataRow dr in ds.Tables[0].Rows)  
  72.             {  
  73.                 messages += "("+dr[1]+")" + " say:" + dr[2];  
  74.             }  
  75.  
  76.             context.Response.Write(messages.ToString());  
  77.         }  
  78.         //SQL的操作     
  79.         private void SQLExcute(string SQLCmd)  
  80.         {  
  81.             string ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=D:\\code\\Message\\App_Data\\information.mdb";  
  82.             OleDbConnection conn = new OleDbConnection(ConnectionString);  
  83.             conn.Open();  
  84.             OleDbCommand cmd = new OleDbCommand();  
  85.             cmd.Connection = conn;  
  86.             cmd.CommandTimeout = 15;  
  87.             cmd.CommandType = CommandType.Text;  
  88.             cmd.CommandText = SQLCmd;  
  89.             cmd.ExecuteNonQuery();  
  90.             conn.Close();  
  91.         }  
  92.         //SQL的操作 是SQLExcute的重构  
  93.         private void SQLExcute(string SQLCmd, OleDbCommand Cmd)  
  94.         {  
  95.             string ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=D:\\code\\Message\\App_Data\\information.mdb";  
  96.             OleDbCommand cmd = new OleDbCommand();  
  97.             OleDbConnection Conn = new OleDbConnection(ConnectionString);  
  98.             Conn.Open();  
  99.             Cmd.Connection = Conn;  
  100.             Cmd.CommandTimeout = 15;  
  101.             Cmd.CommandType = CommandType.Text;  
  102.             Cmd.CommandText = SQLCmd;  
  103.             Cmd.ExecuteNonQuery();  
  104.             Conn.Close();  
  105.         }  
  106.         public bool IsReusable  
  107.         {  
  108.             get  
  109.             {  
  110.                 return false;  
  111.             }  
  112.         }  
  113.     }  

 



本文转自linzheng 51CTO博客,原文链接:http://blog.51cto.com/linzheng/1078692

上一篇:解读 Knative Eventing v0.12.0 新特性


下一篇:EncryptPad—Linux中好用的加密文本编辑器