Upload
ck47ht
View
62
Download
1
Embed Size (px)
DESCRIPTION
NộidungKỹthuậtlậptrìnhtrên.NET CFLậptrìnhmạngvới.NET CFEmail, Outlook, SMS
Citation preview
Lập trình .NET Compact
Framework
GV: ThS. Phan Nguyệt Minh
http://sites.google.com/site/laptrinhnhungcanban
Nội dung
Kỹ thuật lập trình trên .NET CF
Lập trình mạng với .NET CF
Email, Outlook, SMS
2Lập trình nhúng căn bản
3
Xác định đường dẫn của Ứng dụng
Xác định tự động đường dẫn của ứng dụng
(runtime)m_startuppath =
System.Reflection.Assembly.GetExecutingAssembly().
GetModules()[0].FullyQualifiedName;
m_startuppath = m_startuppath.Replace(
System.Reflection.Assembly.GetExecutingAssembly().
GetModules()[0].Name, "" );
m_BmBanCo =new Bitmap
(m_startuppath+"BanCoPocketPC.jpg");
m_BmQuanCo=new Bitmap
(m_startuppath+"QuanCoPocKetPC.bmp");
m_BmChonCo=new Bitmap
(m_startuppath+"ChonQuanPocketPC.bmp");
Lấy danh
sách các
Assembly
Xóa tên file,
chỉ giữ lại
đường dẫn
Trọn vẹn tên và
đường dẫn của
module
Tên của module
4
Xác định đường dẫn của Ứng dụng
Sử dụng đường dẫn tuyệt đối (hard-code)!!!
Phải biết trước đường dẫn (tuyệt đối) sẽ
chứa chương trình thực thipublic class Constant
{
public static int LEFT = 24;
public static int TOP = 24;
public static string AppPath
= @"\Program Files\MummyMaze\";
public static string ImagesPath
= @"\Program Files\MummyMaze\";
}
5
Load ảnh từ file
Có thể load các ảnh từ file vào đối tượng
kiểu Bitmap
Các định dạng ảnh thông dụng mà WinCE
hỗ trợ (BMP, JPG, PNG…)
Bitmap RedMummyBmp =
new Bitmap(Constant.ImagesPath+"redmummy.bmp");
Bitmap HelloBmp =
new Bitmap(Constant.ImagesPath+"hello.jpg");
6
Sử dụng Timer (1)
Khai báo biến thuộc kiểu System.Windows.Forms.Timer
Khởi tạo biến Timer
private System.Windows.Forms.Timer MyTimer;
private void InitializeComponent()
{
this.MyTimer = new System.Windows.Forms.Timer();
this.MyTimer.Interval = 300; // 300 ms
this.MyTimer.Tick +=
new System.EventHandler(this.MyTimer_Func);
}
Tên hàm
xử lý
Timer
7
Sử dụng Timer (2)
Hàm xử lý mỗi khi xảy ra biến cố timer
private void MyTimer_Func
(object sender, System.EventArgs e)
{
flag = 1 - flag;
pictureBox1.Image = CompleteBmp[flag];
pictureBox1.Refresh();
}
8
Sử dụng Timer (3)
Kích hoạt timer
Tạm dừng timer
Hủy bỏ timer
MyTimer.Enabled = true;
MyTimer.Enabled = false;
MyTimer.Dispose();
9
Sử dụng Graphics
public void Draw(Graphics g)
{
ImageAttributes imgatt = new ImageAttributes();
imgatt.SetColorKey
(Constant.BkColor, Constant.BkColor);
g.DrawImage(
HumanBmp,
new Rectangle(left, top, width, height),
Bmp_x*Constant.WidthSquare_pixel,
Bmp_y*Constant.WidthSquare_pixel,
Constant.WidthSquare_pixel,
Constant.WidthSquare_pixel,
GraphicsUnit.Pixel, imgatt);
}
10
Sử dụng Thread
Khai báo biến kiểu Thread
Tạo thread và khởi động thread
Hàm xử lý chính của Thread
private void PlaySound()
{ SoundThread =
new Thread(new ThreadStart(PlaySoundFunc));
SoundThread.Priority = ThreadPriority.Highest;
SoundThread.Start(); // Bắt đầu thread
}
private Thread SoundThread;
private void PlaySoundFunc()
{ Sound.PlayMusic(Constant.AppPath + "music.wav");
}
Tên hàm
xử lý chính
của Thread
11
Xử lý Âm thanh (1)
public class Sound
{
[DllImport("WinMM.dll",
EntryPoint="PlaySound",CharSet=CharSet.Auto)]
private static extern int PlaySoundWin32
(string pszSound, int hmod, int fdwSound) ;
[DllImport("CoreDll.dll",
EntryPoint="PlaySound",CharSet=CharSet.Auto)]
private static extern int PlaySoundWinCE
(string pszSound, int hmod, int fdwSound) ;
.........
12
Xử lý Âm thanh (2)
private enum SND
{
SND_SYNC = 0x0000,
/* play synchronously (default) */
SND_ASYNC = 0x0001,
/* play asynchronously */
SND_NODEFAULT = 0x0002,
/* silence (!default) if sound not found */
SND_MEMORY = 0x0004,
/* pszSound points to a memory file */
SND_LOOP = 0x0008,
/* loop the sound until next sndPlaySound */
13
Xử lý Âm thanh (3)
private enum SND
{
......
SND_NOSTOP = 0x0010,
/* don't stop any currently playing sound */
SND_NOWAIT = 0x00002000,
/* don't wait if the driver is busy */
SND_ALIAS = 0x00010000,
/* name is a registry alias */
SND_ALIAS_ID = 0x00110000,
/* alias is a predefined ID */
......
}
14
Xử lý Âm thanh (4)
private enum SND
{
......
SND_FILENAME = 0x00020000,
/* name is file name */
SND_RESOURCE = 0x00040004,
/* name is resource name or atom */
SND_PURGE = 0x0040,
/* purge non-static events for task */
SND_APPLICATION = 0x0080
/* look for application specific association */
};
15
Xử lý Âm thanh (5)
private const int Win32 = 0 ;
private const int WinCE = 1 ;
private static int Windows = -1 ;
public static void PlayMusic(string pszMusic)
{
int flags =
(int)(SND.SND_ASYNC|SND.SND_FILENAME|
SND.SND_NOWAIT|SND.SND_LOOP) ;
sndPlaySound(pszMusic, flags) ;
}
16
Xử lý Âm thanh (6)
private static void sndPlaySound
(string pszSound, int flags)
{
switch ( Windows )
{
case Win32 :
PlaySoundWin32(pszSound, 0, flags) ;
break ;
case WinCE :
PlaySoundWinCE(pszSound, 0, flags) ;
break ;
......
17
Xử lý Âm thanh (7)
default :
try // Play if in Win32 platform
{ PlaySoundWin32(pszSound, 0, flags) ;
Windows = Win32 ; }
catch ( Exception )
{ try // Play if in WinCE platform
{ PlaySoundWinCE(pszSound, 0, flags) ;
Windows = WinCE ; }
catch ( Exception )
{
}
}
break ;
} // switch
Lập trình mạng với .NET CF
Sử dụng Socket
Sử dụng kết nối UDP
Sử dụng HttpWebRequest
Sử dụng kết nối hồng ngoại
Lập trình nhúng căn bản 18
Một số nhận xét
Các port có giá trị dưới 1024 thường được
HĐH dành riêng cho các dịch vụ chuẩn
Nên chọn port có giá trị từ 2000 đến 60000
Chọn lựa giữa TCP/IP và UDP
◦ TCP: đảm bảo “error-free delivery”, chậm hơn
UDP
◦ UDP: không đảm bảo “error-free delivery”,
nhanh hơn TCP
Lập trình nhúng căn bản 19
Tạo kết nối tại Client
Sử dụng địa chỉ IPEndPoint l_EndPoint = new IPEndPoint
(IPAddress.Parse( "172.68.25.34“), Convert.ToInt16(9981));
Sử dụng tên của server (dùng DNS)IPHostEntry l_IPHostEntry =Dns.Resolve("www.mycomputer.net");
EndPoint l_EndPoint = new
IPEndpoint(l_IPHostEntry.AddressList[0], 9981);
Lập trình nhúng căn bản 20
Tạo kết nối tại Client
try
{
Socket l_Socket = new
Socket(Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
l_Socket.Connect(l_EndPoint);
if (l_Socket.Connected)
{
// l_Socket is now ready to send and receive data
}
}
catch (SocketException e)
{ /* do something about it */ }
Lập trình nhúng căn bản 21
Nhận yêu cầu kết nối tại Host
m_listenSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
m_listenSocket.Bind(new IPEndPoint(IPAddress.Any, 8758));
m_listenSocket.Listen((int)SocketOptionName.MaxConnections);
m_connectedSocket = m_listenSocket.Accept();
if (m_connectedSocket != null)
{
if (m_connectedSocket.Connected)
{
// Someone has connected to us.
}
}
Lập trình nhúng căn bản 22
Truyền tin bằng Socket
Truyền dữ liệu: Socket.Send◦ Send (Byte[] buffer)
◦ Send (Byte[] buffer, SocketFlags socketFlags)
◦ Send (Byte[] buffer, Int32 size, SocketFlags socketFlags)
◦ Send (Byte[] buffer, Int32 offset, Int32 size, SocketFlags
socketFlags)
Ví dụ:◦ l_Socket.Send (l_buffer, 16, SocketFlags.None);
Truyền tối đa 16 byte dữ liệu trong l_buffer
◦ l_Socket.Send (l_buffer, 2, 6, SocketFlags.None);
Truyền tối đa 6 byte dữ liệu trong l_buffer từ byte thứ 3
Lập trình nhúng căn bản 23
Truyền tin bằng Socket
l_Socket.Send(Encoding.ASCII.GetBytes("Send me") );
l_Socket.Send(Encoding.Unicode.GetBytes("Send me") );
l_Socket.Send(Encoding.ASCII.GetBytes(Convert.ToString(2003)) );
l_Socket.Send(Encoding.ASCII.GetBytes(Convert.ToString(2.71)) );
Lập trình nhúng căn bản 24
Nhận tin bằng Socket
Nhận dữ liệu: Socket.Receive◦ Receive (Byte[] buffer)
◦ Receive (Byte[] buffer, SocketFlags socketFlags)
◦ Receive (Byte[] buffer, Int32 size, SocketFlags socketFlags)
◦ Receive (Byte[] buffer, Int32 offset, Int32 size, SocketFlags
socketFlags)
Ví dụ:◦ l_Socket.Receive (l_buffer, 16, SocketFlags.None);
Nhận tối đa 16 byte dữ liệu vào l_buffer
◦ l_Socket.Receive (l_buffer, 2, 6, SocketFlags.None);
Nhận tối đa 6 byte dữ liệu ghi vào l_buffer từ byte thứ 3
Lập trình nhúng căn bản 25
Nhận tin bằng Socket
string l_ASCII = Encoding.ASCII.GetString(l_Buffer);
string l_ASCII = Encoding.ASCII.GetString(l_Buffer);
int l_Integer =
Convert.ToInt32(Encoding.ASCII.GetString(l_Buffer));
Double l_Double =
Convert.ToDouble(Encoding.ASCII.GetString(l_Double));
Lập trình nhúng căn bản 26
Sử dụng kết nối UDP
Sử dụng class UdpClient
◦ void Connect(String hostname, Int32 port);
◦ void Send(Byte[] dgram, Int32 bytes);
◦ void Receive(ref IPEndPoint remoteEP);
Ví dụ:l_UdpClient.Connect(IPAddress.Parse("172.68.25.34"), 9981);
Send(aBuffer, aBuffer.Length, "www.mycomputer.net", 9981);
Lập trình nhúng căn bản 27
Sử dụng UdpClient
IPEndPoint senderIP = new
IPEndPoint(IPAddress.Parse("192.168.0.200"),
Convert.ToInt32(8758));
UdpClient l_UdpClient = new UdpClient();
l_UdpClient.Connect(senderIP);
for (int i = 0; i < 20; i++)
{
l_UdpClient.Send(Encoding.ASCII.GetBytes("Hello_UDP_1"),
Encoding.ASCII.GetBytes("Hello_UDP_1").Length);
System.Threading.Thread.Sleep(1000);
}
l_UdpClient.Close();
Lập trình nhúng căn bản 28
Sử dụng UdpClient
IPEndPoint listenerIP = new IPEndPoint(IPAddress.Any, 8758);
UdpClient listener = new UdpClient(listenerIP);
for (int i = 0; i < Convert.ToInt16(this.txtMaxPackets.Text); i++)
{
// Now receive the three datagrams from the listener
IPEndPoint receivedIPInfo = new IPEndPoint(IPAddress.Any, 0);
byte[] data = listener.Receive(ref receivedIPInfo);
this.textBox1.Text += ("GOT: "
+ Encoding.ASCII.GetString(data, 0, data.Length)
+ " FROM: " + receivedIPInfo.ToString());
}
Lập trình nhúng căn bản 29
Sử dụng UdpClient
UdpClient udpClient = new UdpClient(5000,
AddressFamily.InterNetwork);
udpClient.BeginReceive(new AsyncCallback(ReceiveCallback),udpClient);
Lập trình nhúng căn bản 30
Sử dụng UdpClient
public static void ReceiveCallback(IAsyncResult ar)
{
UdpClient u = (UdpClient)ar.AsyncState;
IPEndPoint e = new IPEndPoint(IPAddress.Broadcast, 0);
Byte[] receiveBytes = u.EndReceive(u, ref e);
string receiveString =
Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("Received: {0}", receiveString);
u.BeginReceive(new AsyncCallback(ReceiveCallback), u);
}
Lập trình nhúng căn bản 31
Sử dụng UdpClient
IPAddress GroupAddress = IPAddress.Broadcast;
int GroupPort = 5000;
UdpClient sender = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);
byte[] bytes = Encoding.ASCII.GetBytes("Broadcast Message");
sender.Send(bytes, bytes.Length, groupEP);
sender.Close();
Lập trình nhúng căn bản 32
Sử dụng HttpWebRequest
Uri l_Uri = new Uri("http://www.myserver.com");
HttpWebRequest l_WebReq =
(HttpWebRequest)WebRequest.Create(l_Uri);
HttpWebResponse l_WebResponse =
(HttpWebResponse)l_WebReq.GetResponse();
Stream l_responseStream = l_WebResponse.GetResponseStream();
StreamReader l_SReader = new StreamReader(l_responseStream);
// Do something with l_SReader. For example, if you downloaded a
// Web page, you could
// extract the HTML code that came in the response and paint it on
// the screen.
Lập trình nhúng căn bản 33
Kết nối bằng IrDA tại Client
m_IrDAClient = new IrDAClient();
bool l_foundAnyDevice = false;
int MAX_DEVICES = 5;
// Find out who's out there to connect with...
IrDADeviceInfo[] l_DevsAvailable =
m_IrDAClient.DiscoverDevices(MAX_DEVICES);
// Show a MessageBox telling user every device we see out there
foreach (IrDADeviceInfo l_devInfo in l_DevsAvailable)
{
l_foundAnyDevice = true;
MessageBox.Show(l_devInfo.DeviceName,
"Discovered IrDA device");
// Now try to connect to the devices, hoping it offers a service
// named "IRDA_CHAT_SERVER"Lập trình nhúng căn bản 34
Kết nối bằng IrDA tại Client
try
{
// Assume that first device is offering a service that we want
IrDAEndPoint chatEndPoint = new IrDAEndPoint(
l_DevsAvailable[0].DeviceID, "IRDA_CHAT_SERVER");
m_IrDAClient.Connect(chatEndPoint);
MessageBox.Show("Connected to chat server!", "Ready to chat");
m_Connected = true;
break;
}
catch (SocketException exc) { }
}
// m_IrdaClient can now be read from or written to.
Lập trình nhúng căn bản 35
Tạo kết nối IrDa tại Server
IrDAListener l_IrDAListener = new
IrDAListener("IRDA_CHAT_SERVER");
// Listen for anyone who wants to connect
l_IrDAListener.Start();
// And now pull the first queued connection request out as an
// IrDAClient
m_IrDAClient = l_IrDAListener.AcceptIrDAClient();
MessageBox.Show("Accepted a connection", "Ready to chat");
Lập trình nhúng căn bản 36
Đọc dữ liệu từ IrDAClient
l_StreamReader = new
StreamReader(this.m_IrDAClient.GetStream(),
System.Text.Encoding.ASCII);
// Read a line of text and paint it into a GUI
this.lbInText.Items.Add(l_StreamReader.ReadLine());
l_StreamReader.Close();
Lập trình nhúng căn bản 37
Ghi dữ liệu với IrDAClient
// Grab a reference to the stream in the m_IrDAClient and send the
// text to it.
StreamWriter l_StreamWriter = new
StreamWriter (this.m_IrDAClient.GetStream(),
System.Text.Encoding.ASCII);
l_StreamWriter.WriteLine(this.txtSendText.Text);
l_StreamWriter.Close();
Lập trình nhúng căn bản 38
Pocket Outlook Object Model
(POOM) Pocket Outlook Object Model (POOM):
tập hợp các class cung cấp các API để
thao tác với Microsoft Outlook trên thiết
bị sử dụng các hệ điều hành nhóm
Windows CE.
POOM là tập con của class trong mô hình
đối tượng của Outlook trên desktop
Xử lý email, SMS, thông tin PIM
(personal information manager)
Lập trình nhúng căn bản 39
SDK và namespace
Cài đặt thêm
◦ Windows Mobile 5.0 for Smartphone SDK
(~77MB)
Namespace:
◦ Microsoft.WindowsMobile.PocketOutlook
Lập trình nhúng căn bản 40
Microsoft.WindowsMobile.PocketOutlook
Lập trình nhúng căn bản 41
Các bước sử dụngMicrosoft.WindowsMobile.PocketOutlook
Tạo session Outlook mới:
OutlookSession aSession = new OutlookSession();
Truy cập các đối tượng PIM: Các property cho phép gửi e-
mail, SMS message, thao tác trên dữ liệu PIM:
◦ Appointments
◦ Contacts
◦ Tasks
◦ EmailAccounts
◦ SmsAccount
Chấm dứt session Outlook (bắt buộc vì không thể được
gabage collector tự động xử lý)
aSession.Dispose();
Lập trình nhúng căn bản 42
Ví dụ
TaskCollection taskItems = aSession.Tasks.Items;
foreach (Task t in taskItems)
{
Messagebox.Show(t.subject);
}
Lập trình nhúng căn bản 43
Tạo email
Tạo session mới
OutlookSession aSession = new OutlookSession();
Chọn sử dụng 1 account email đã có
EmailAccount anEmailAcct = aSession.EmailAccounts[1];
hoặcEmailAccount anEmailAcct = aSession.EmailAccounts["IMAP4"];
Lập trình nhúng căn bản 44
Tạo email
Xác định người nhậnRecipient recv = new Recipient("FirtName LastName",
Tạo email mớiEmailMessage mesg = new EmailMessage();
mesg.To.Add(recv);
mesg.Subject = "Hello";
mesg.BodyText = "Dear readers, we hope you enjoy learning
Smartphone programming";
anEmailAcct.Send(mesg);
Lập trình nhúng căn bản 45
Tạo email có attachment
// Create a new Select Picture dialog box
SelectPictureDialog picDlg = new SelectPictureDialog();
picDlg.InitialDirectory = @"\Images";
// Do not forward
// a Digital Rights Management protected file
picDlg.ShowForwardLockedContent = false;
// Get the dialog result
DialogResult result = picDlg.ShowDialog();
Lập trình nhúng căn bản 46
Tạo email có attachment
//Create a new email message
EmailMessage mesg = new EmailMessage();
mesg.Subject = "Email with Picture Attachment";
mesg.BodyText = "Open the attachment. No virus";
//Create and add a new recipient
Recipient resv = new Recipient("John Doe","[email protected]");
mesg.To.Add(resv);
Lập trình nhúng căn bản 47
Tạo email có attachment
//Add the picture to the attachment
Attachment picture = new Attachment (picDlg.FileName);
mesg.Attachments.Add(picture);
//Use the default email account
EmailAccount myEmail = aSession.EmailAccounts[0];
//Display the email compose form
MessagingApplication.DisplayComposeForm(myEmail,mesg);
Lập trình nhúng căn bản 48
Thao tác với thông tin PIM
OutlookSession CalSess = new OutlookSession();
Cách truy cập thông tin Appointment:AppointmentCollection CalCol = CalSess.Appointments.Items;
Cách truy cập thông tin Task:TaskCollection TCol = CalSess.Tasks.Items;
Cách truy cập thông tin Contact:ContactCollection TCol = CalSess.Contacts.Items;
Lập trình nhúng căn bản 49
Ví dụ
//Establish a new Outlook session
OutlookSession CalSess = new OutlookSession();
//Get the collection of appointments by calling
outlookSession.Appointments.Items
AppointmentCollection CalCol = CalSess.Appointments.Items;
Lập trình nhúng căn bản 50
Ví dụ//Add each appointment to the ListView
foreach (Appointment apt in CalCol)
{
//Create one new ListView object for each appointment
ListViewItem aLVItem = new ListViewItem();
//Make the appointment date the text property of this ListView
aLVItem.Text = apt.Start.Date.ToString();
//Make other appointment property as the subitem
aLVItem.SubItems.Add(apt.Subject);
//You can also add a field for the appointment location
aLVItem.SubItems.Add(apt.Location);
//Add ListViewItem to the ListView
CalView.Items.Add(aLVItem);
}Lập trình nhúng căn bản 51
Chọn lọc thông tin
string query = "[Categories] == wrox";
AppointmentCollection wroxAppt =
aOutlookSession.Appointments.Items.restrict(query);
Lưu ý: phép so sánh <>
string query = "[Location] <> Ball State University";
Những appointment item không có thông tin
Location cũng bị loại bỏ!!!
Lập trình nhúng căn bản 52
Gửi SMS
OutlookSession aSession = new OutlookSession();
SmsMessage sendMsg = new SmsMessage("18664365702",
"Vote to Idol #2");
aSession.SmsAccount.Send(sendMsg);
aSession.Dispose();
Lập trình nhúng căn bản 53
Gửi SMS
SmsMessage sendMsg = new SmsMessage();
Recipient recv = new Recipient("18664365702");
sendMsg.Body = "Vote to Idol #2";
sendMsg.To.Add (recv);
MessagingApplication.DisplayComposeForm(sendMsg)
Lập trình nhúng căn bản 54
Nhận SMS
using Microsoft.WindowsMobile.PocketOutlook.MessageInterception;
msginterceptor = new MessageInterceptor();
msginterceptor.InterceptionAction =
InterceptionAction.NotifyAndDelete; // Notify
msginterceptor.MessageReceived += new
MessageInterceptorEventHandler(msginterceptor_MessageReceived);
Lập trình nhúng căn bản 55
Nhận SMS
//Handling received message
void msginterceptor_MessageReceived(object sender,
MessageInterceptorEventArgs e)
{
SmsMessage smsMsg = (SmsMessage)e.Message;
string fullText = "Message From: “+smsMsg.From.Name;
fullText += (" at "+ smsMsg.Received.TimeOfDay.ToString());
fullText += (" and the message is: "+smsMsg.Body);
MessageBox.Show(fullText, "New Text Message !");
}
Lập trình nhúng căn bản 56
Tài liệu tham khảo
Andy Wigley, Stephen Wheelwright, Microsoft .NET
Compact Framework, Microsoft Press, 2003
Dan Fox, Jon Box, Building Solutions with the Microsoft
.NET Compact Framework: Architecture and Best
Practices for Mobile Development, Addison Wesley,
2003
Erik Rubin, Ronnie Yates, Microsoft .NET Compact
Framework Kick Start, Sams Publishing, 2003
Dan Fergus, Larry Roof, The Definitive Guide to the
.NET Compact Framework, Apress, 2003
http://www.msdnaa.net/
Lập trình nhúng căn bản 57
Q/A
Lập trình nhúng căn bản 58