Windows Phone 7 网络编程之留言板应用
这个简易的留言板,是通过手机客户端与web程序的交互来设计的,保存留言的时候将数据传输到web,显示留言的时候再从数据库取数通过web传输到客户端。加强对HttpWebRequest异步请求的学习。
<phone:PhoneApplicationPage
x:Class="WindowsPhoneLiuyan.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="PageTitle" Text="网络留言板" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Canvas Height="600" Margin="0,4,6,4">
<TextBlock x:Name="name1" Canvas.Top="327" Canvas.Left="8" Text="网 名:" Foreground="#FFF7F6F6"/>
<TextBox x:Name="name" Width="122" Canvas.Left="86" Canvas.Top="308" Background="#FFFBF6F6"/>
<TextBlock x:Name="message1" Canvas.Left="11" Canvas.Top="360" Text="留 言:" Foreground="#FFFBF9F9"/>
<TextBox x:Name="message" Width="321" Canvas.Left="86" Canvas.Top="360" VerticalScrollBarVisibility="Hidden" Height="124"/>
<Button Canvas.Left="30" Canvas.Top="490" Content="保存" Height="71" Name="save" Width="160" Click="save_Click" />
<Button Canvas.Left="217" Canvas.Top="490" Content="重置" Height="71" Name="reset" Width="160" Click="reset_Click" />
<TextBox Canvas.Left="-4" Canvas.Top="6" Height="296" Name="messages" Text="TextBox" Width="460" AcceptsReturn="True" />
</Canvas>
</Grid>
</Grid>
</phone:PhoneApplicationPage>
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;
using Microsoft.Phone.Controls;
using System.Text;
using System.IO;
using System.Collections.ObjectModel;
namespace WindowsPhoneLiuyan
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
getMessage();
}
private void save_Click(object sender, RoutedEventArgs e)
{
UriBuilder fullUri = new UriBuilder("http://localhost/liuyan/messege.ashx");
fullUri.Query = "type=insert&name=" + name.Text + "&description=" + message.Text;
// 创建WebRequest
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
// 创建同步的AsyncRequest
UpdateState State = new UpdateState();
State.AsyncRequest = myRequest;
// 开始异步请求
myRequest.BeginGetResponse(new AsyncCallback(HandleMyResponse), State);
}
public void getMessage()
{
UriBuilder fullUri = new UriBuilder("http://localhost/liuyan/messege.ashx");
fullUri.Query = "type=get";
// 创建WebRequest
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
// 创建同步的AsyncRequest
UpdateState State = new UpdateState();
State.AsyncRequest = myRequest;
// 开始异步请求
myRequest.BeginGetResponse(new AsyncCallback(HandleMyResponse), State);
}
private void HandleMyResponse(IAsyncResult asyncResult)
{
// 获取返回的信息
UpdateState myState = (UpdateState)asyncResult.AsyncState;
HttpWebRequest myRequest = (HttpWebRequest)myState.AsyncRequest;
//结束异步请求
myState.AsyncResponse = (HttpWebResponse)myRequest.EndGetResponse(asyncResult);
Stream streamResult = myState.AsyncResponse.GetResponseStream();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (streamResult.Length != 0)
{
StreamReader sr = new StreamReader(streamResult);
messages.Text = sr.ReadToEnd();
}
});
}
private void reset_Click(object sender, RoutedEventArgs e)
{
name.Text = "";
message.Text = "";
}
}
public class UpdateState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}
}
web依然使用.NET
Message.ashx文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.OleDb;
using System.Data;
namespace liuyan.Web
{
/// <summary>
/// Messege 的摘要说明
/// </summary>
public class Message : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string type = context.Request.QueryString["type"].ToString();
switch (type)
{
case "get":
get(context);
break;
case "insert":
insert(context);
break;
default:
break;
}
}
/// <summary>
/// 获取留言板数据
/// </summary>
/// <param name="context"></param>
public void get(HttpContext context)
{
string messages = "";
OleDbCommand cmd = new OleDbCommand();
SQLExcute("SELECT * from about order by id desc", cmd);
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
messages += dr[1] + " say:" + dr[2]+" ";
}
context.Response.Write(messages.ToString());
}
/// <summary>
/// 先往access数据库插入数据 然后再查询返回数据
/// </summary>
/// <param name="context"></param>
public void insert(HttpContext context)
{
string name = context.Request.QueryString["name"].ToString();
string description = context.Request.QueryString["description"].ToString();
string sql = "insert into about(name,description) values('" + name + "','" + description + "')";
SQLExcute(sql);
string messages = "";
OleDbCommand cmd = new OleDbCommand();
SQLExcute("SELECT * from about order by id desc", cmd);
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
messages += "("+dr[1]+")" + " say:" + dr[2];
}
context.Response.Write(messages.ToString());
}
//SQL的操作
private void SQLExcute(string SQLCmd)
{
string ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=D:\\code\\Message\\App_Data\\information.mdb";
OleDbConnection conn = new OleDbConnection(ConnectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandTimeout = 15;
cmd.CommandType = CommandType.Text;
cmd.CommandText = SQLCmd;
cmd.ExecuteNonQuery();
conn.Close();
}
//SQL的操作 是SQLExcute的重构
private void SQLExcute(string SQLCmd, OleDbCommand Cmd)
{
string ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=D:\\code\\Message\\App_Data\\information.mdb";
OleDbCommand cmd = new OleDbCommand();
OleDbConnection Conn = new OleDbConnection(ConnectionString);
Conn.Open();
Cmd.Connection = Conn;
Cmd.CommandTimeout = 15;
Cmd.CommandType = CommandType.Text;
Cmd.CommandText = SQLCmd;
Cmd.ExecuteNonQuery();
Conn.Close();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
posted on 2011-03-05 11:42 linzheng 阅读(1616) 评论(10) 编辑 收藏 举报