註:多數瀏覽器都有一種以離線模式執行網頁的設定,將離線模式打開,你依舊能在離線模式下運行
Silverlight
程式,在適當的設計下,其實也能做出
[
偶爾連線
]
模式。
|
DBProvider.ashx.cs
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Data;
using
System.Data.SqlClient;
using
System.Configuration;
using
System.Xml.Linq;
namespace
DBDemo1.Web
{
///<summary>
/// Summary description for $codebehindclassname$
///</summary>
public class DBProvider : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/xml";
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True;User Instance=True"))
{
XDocument doc = new XDocument(new XElement("Root"));
using (SqlCommand cmd = new SqlCommand("SELECT * FROM CUSTOMERS", conn))
{
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(
CommandBehavior.CloseConnection))
{
while (reader.Read())
{
XElement elem = new XElement("Customer");
elem.Add(new XAttribute("CUSTOMER_ID",
reader.GetString(reader.GetOrdinal("CUSTOMER_ID"))));
elem.Add(new XAttribute("CUSTOMER_NAME",
reader.GetString(reader.GetOrdinal("CUSTOMER_NAME"))));
doc.Root.Add(elem);
}
}
context.Response.Write(doc.ToString());
context.Response.Flush();
context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
|
Page.xaml
|
<
UserControl
x
:
Class
="DBDemo1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
Width="400" Height="300" Loaded="UserControl_Loaded">
<
Grid
x
:
Name
="LayoutRoot"
Background
="White"
Height
="300"
Width
="400">
<
data
:
DataGrid
x
:
Name
="grid"
AutoGenerateColumns
="True">
</
data
:
DataGrid
>
</
Grid
>
</
UserControl
>
|
Page.xaml.cs
|
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
System.IO;
using
System.Xml;
using
System.Xml.Linq;
namespace
DBDemo1
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri("http://localhost:40419/DBProvider.ashx", UriKind.Absolute));
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(ReadCallback),request);
}
private void ReadCallback(IAsyncResult state)
{
HttpWebRequest request = (HttpWebRequest)state.AsyncState;
Stream postStream = request.EndGetRequestStream(state);
//byte[] buff = System.Text.Encoding.Unicode.GetBytes("TEST");
//postStream.Write(buff, 0, buff.Length);
postStream.Close(); // the request stream must closed before
request.BeginGetResponse(new AsyncCallback(GetResponse), request);
}
private void GetResponse(IAsyncResult state)
{
HttpWebRequest request = (HttpWebRequest)state.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(state);
using (Stream stream = response.GetResponseStream())
{
XDocument doc = XDocument.Load(stream);
Dispatcher.BeginInvoke(
new System.Threading.ParameterizedThreadStart(UpdateUI), doc);
}
}
private void UpdateUI(object state)
{
XDocument doc = (XDocument)state;
grid.ItemsSource = (from s1 in doc.Elements("Root").Descendants("Customer")
select new Customer()
{
ID = s1.Attribute("CUSTOMER_ID").Value,
Name = s1.Attribute("CUSTOMER_NAME").Value
}).ToList();
}
}
public class Customer
{
public string ID { get; set; }
public string Name { get; set; }
}
}
|
DBService.svc.cs
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Runtime.Serialization;
using
System.ServiceModel;
using
System.Text;
namespace
DBDemo1.Web
{
[ServiceContract]
public interface IDBService
{
[OperationContract]
CUSTOMERS[] GetData();
}
public class DBService : IDBService
{
public CUSTOMERS[] GetData()
{
using (MyDBDataContext context = new MyDBDataContext())
{
return (from s1 in context.CUSTOMERS select s1).ToArray();
}
}
}
}
|
web.config
|
............
<
services
>
<
service
behaviorConfiguration
=
"DBDemo1.Web.DBServiceBehavior"
name
=
"DBDemo1.Web.DBService">
<
endpoint
address
=
""binding="basicHttpBinding"contract="DBDemo1.Web.IDBService">
<
identity
>
<
dns
value
=
"localhost" />
</
identity
>
</
endpoint
>
<
endpoint
address
=
"mex"binding="mexHttpBinding"contract="IMetadataExchange" />
</
service
>
</
services
>
............
|
Page2.xaml
|
<
UserControl
x
:
Class
="DBDemo1.Page2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
Width="400" Height="300" Loaded="UserControl_Loaded">
<
Grid
x
:
Name
="LayoutRoot"
Background
="White"
Height
="300"
Width
="400">
<
data
:
DataGrid
x
:
Name
="grid"
AutoGenerateColumns
="True">
</
data
:
DataGrid
>
</
Grid
>
</
UserControl
>
|
Page2.xaml.cs
|
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
DBDemo1
{
public partial class Page2 : UserControl
{
public Page2()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
ServiceReference1.DBServiceClient client =
new DBDemo1.ServiceReference1.DBServiceClient();
client.GetDataCompleted +=
new
EventHandler<DBDemo1.ServiceReference1.GetDataCompletedEventArgs>(
client_GetDataCompleted);
client.GetDataAsync();
}
void client_GetDataCompleted(object sender,
DBDemo1.ServiceReference1.GetDataCompletedEventArgs e)
{
grid.ItemsSource = e.Result;
}
}
}
|
WebDataService1.svc.cs
|
using
System;
using
System.Collections.Generic;
using
System.Data.Services;
using
System.Linq;
using
System.ServiceModel.Web;
using
System.Web;
namespace
DBDemo1.Web
{
public class WebDataService1 : DataService< EntityData.MyDatabaseEntities>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
}
}
}
|
Page3.xaml
|
<
UserControl
x
:
Class
="DBDemo1.Page3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
Width="400" Height="300" Loaded="UserControl_Loaded">
<
Grid
x
:
Name
="LayoutRoot"
Background
="White"
Height
="300"
Width
="400">
<
data
:
DataGrid
x
:
Name
="grid"
AutoGenerateColumns
="True">
</
data
:
DataGrid
>
</
Grid
>
</
UserControl
>
|
Page3.xaml.cs
|
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
System.Data.Services.Client;
namespace
DBDemo1
{
public partial class Page3 : UserControl
{
public Page3()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
ServiceReference2.MyDatabaseEntities3 entities =
new
DBDemo1.ServiceReference2.MyDatabaseEntities3(
new
Uri("WebDataService1.svc",UriKind.Relative));
var result = from s1 in entities.CUSTOMERS select s1;
((DataServiceQuery<ServiceReference2.CUSTOMERS>)result).BeginExecute(
new AsyncCallback(ReadCallback), result);
}
private void ReadCallback(IAsyncResult state)
{
DataServiceQuery<ServiceReference2.CUSTOMERS> svcCtx =
(DataServiceQuery<ServiceReference2.CUSTOMERS>)state.AsyncState;
//remember, you must call tolist,toarray before set to itemsource.
grid.ItemsSource = svcCtx.EndExecute(state).ToList();
}
}
}
|
Page4.xaml
|
<
UserControl
x
:
Class
="DBDemo1.Page4"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
Width="400" Height="300" Loaded="UserControl_Loaded">
<
Grid
x
:
Name
="LayoutRoot"
Background
="White"
Height
="300"
Width
="400">
<
data
:
DataGrid
x
:
Name
="grid"
AutoGenerateColumns
="True">
</
data
:
DataGrid
>
</
Grid
>
</
UserControl
>
|
Page4.xaml.cs
|
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
System.IO;
using
System.IO.IsolatedStorage;
using
System.Xml.Linq;
namespace
DBDemo1
{
public partial class Page4 : UserControl
{
public Page4()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri("http://localhost:40419/DBProvider.ashx", UriKind.Absolute));
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);
}
private void ReadCallback(IAsyncResult state)
{
HttpWebRequest request = (HttpWebRequest)state.AsyncState;
Stream postStream = request.EndGetRequestStream(state);
//byte[] buff = System.Text.Encoding.Unicode.GetBytes("TEST");
//postStream.Write(buff, 0, buff.Length);
postStream.Close(); // the request stream must closed before
request.BeginGetResponse(new AsyncCallback(GetResponse), request);
}
private void GetResponse(IAsyncResult state)
{
try
{
HttpWebRequest request = (HttpWebRequest)state.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(state);
using (Stream stream = response.GetResponseStream())
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
store.CreateDirectory("Data");
IsolatedStorageFileStream subDirFile =
store.CreateFile(System.IO.Path.Combine("Data", "dbdata.txt"));
using (StreamWriter sw = new StreamWriter(subDirFile))
{
using(StreamReader sr = new StreamReader(stream))
{
sw.Write(sr.ReadToEnd());
}
}
}
XDocument doc = XDocument.Load(stream);
Dispatcher.BeginInvoke(
new System.Threading.ParameterizedThreadStart(UpdateUI), doc);
}
}
catch (Exception ex)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream subDirFile =
store.OpenFile(System.IO.Path.Combine("Data", "dbdata.txt"),FileMode.Open);
XDocument doc = XDocument.Load(subDirFile);
subDirFile.Close();
Dispatcher.BeginInvoke(
new System.Threading.ParameterizedThreadStart(UpdateUI), doc);
}
}
}
private void UpdateUI(object state)
{
XDocument doc = (XDocument)state;
grid.ItemsSource = (from s1 in doc.Elements("Root").Descendants("Customer")
select new Customer()
{
ID = s1.Attribute("CUSTOMER_ID").Value,
Name = s1.Attribute("CUSTOMER_NAME").Value
}).ToList();
}
}
}
|
Lad.li