0% found this document useful (0 votes)
80 views132 pages

T 470 F 05

The document discusses ASP.NET and FTP. It explains how to use FTP functionality in ASP.NET including listing directories, downloading, uploading and deleting files. Methods for different FTP operations like LIST, RETR, STOR are also covered.

Uploaded by

hnhngtb1111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views132 pages

T 470 F 05

The document discusses ASP.NET and FTP. It explains how to use FTP functionality in ASP.NET including listing directories, downloading, uploading and deleting files. Methods for different FTP operations like LIST, RETR, STOR are also covered.

Uploaded by

hnhngtb1111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 132

PART 5

Q53 ASP.NET FTP


Q54 ASP.NET ( )
Q55 ASP.NET ?
Q56 ASP.NET
Q57 Web Service
Q58 Web Service Session
Q59 ?
Q60 Active Directory
Q61 Active Directory
Q62 Active Directory
Q63
Q64 ( ), ( )
Q65 (Code-Based Forms Authentication) ?
Q66 ASP.NET ?
Q67 ASP.NET
Q68 (Authentication Code)
Q69 URL URL
Q53 FTP
ASP.NET

V ASP.NET 2.0 V ASP.NET 3.5

FTP , ,
Web Web
,

FTP Server Web Server ,


FTP Server , Web Server, Web
, , FTP
, FTP , Web

FTP Server , FTP


Server , FTP ,
FTP , WS-FTP CuteFTP FileZilla ,
Web FTP ,
, Web FTP Server

FTP Internet , RFC 959 , ,


FTP Client Port 20/21 FTP Server ,
.NET 2.0 , FTP FtpWebRequest
FtpWebResponse , .NET FTP
WebRequestMethod.Ftp , HttpWebRequest/
HttpWebResponse , NetworkStream ( ) (
)

FtpWebRequest FTP ,
FTP Server ( WebRequestMethods.Ftp
, )

5-2
ASP.NET FTP Q53

FTP
AppendFile FTP APPE ,
FTP

DeleteFile FTP DELE , FTP

DownloadFile FTP RETR , FTP

GetDateTimestamp FTP MDTM , FTP

GetFileSize FTP SIZE , FTP

ListDirectory FTP NLIST , FTP

ListDirectoryDetails FTP LIST , FTP

MakeDirectory FTP MKD , FTP

PrintWorkingDirectory FTP PWD ,

RemoveDirectory FTP RMD

Rename FTP RENAME

UploadFile FTP FTP STOR

UploadFileWithUniqueName FTP
FTP STOU

( .NET Framework SDK , WebRequestMethods.Ftp )

.NET 1.x , System.Net.Socket


TcpClient FTP , FTP

5-3
Part5

FtpWebRequest FtpWebResponse FTP Server ,


FTP Server ,

FtpWebRequest request = FtpWebRequest.Create(this.T_FtpUrl.Text)

as FtpWebRequest;

// FTP

request.Method = WebRequestMethods.Ftp.ListDirectory;

request.KeepAlive = true;

request.Credentials = new NetworkCredential(this.T_UserName.Text,

this.T_Password.Text);

request.UsePassive = false;

request.ReadWriteTimeout = 2000000;

request.Timeout = 1200000;

//

Dictionary<string, string> accountInfo =

new Dictionary<string, string>();

accountInfo.Add("UserName", this.T_UserName.Text);

accountInfo.Add("Password", this.T_Password.Text);

ViewState["FtpAccount"] = accountInfo;

//

FtpWebResponse response = request.GetResponse() as FtpWebResponse;

StreamReader sr = new StreamReader(response.GetResponseStream(),

System.Text.Encoding.Default);

do

//

string item = sr.ReadLine();

if (item.IndexOf('.') >= 0)

5-4
ASP.NET FTP Q53

this.cboFileList.Items.Add(new ListItem(item, item));

while (!sr.EndOfStream);

response.Close();

FTP ,

FTP , ( FTP Method,

// FTP URL ( ftp://ftp.myftp.org/myfile.zip)

FtpWebRequest request = FtpWebRequest.Create(

this.T_FtpUrl.Text + "/" +

this.cboFileList.SelectedValue) as FtpWebRequest;

5-5
Part5

// ViewState ,

Dictionary<string, string> accountInfo =

ViewState["FtpAccount"] as Dictionary<string, string>;

// FTP ,

request.Method = WebRequestMethods.Ftp.DownloadFile;

request.KeepAlive = true;

request.Credentials = new NetworkCredential(

accountInfo["UserName"], accountInfo["Password"]);

request.UsePassive = false;

request.ReadWriteTimeout = 2000000;

request.Timeout = 1200000;

FtpWebResponse response = request.GetResponse() as FtpWebResponse;

//

BinaryReader reader = new BinaryReader(response.GetResponseStream());

int readCount = 0;

byte[] data = null;

MemoryStream ms = new MemoryStream();

do

// , MemoryStream

data = new byte[8192];

readCount = reader.Read(data, 0, 8192);

ms.Write(data, 0, readCount);

while (readCount > 0);

5-6
ASP.NET FTP Q53

ms.Flush();

ms.Position = 0;

reader.Close();

response.Close();

//

Response.AddHeader("Content-Disposition", string.Format(

"attachment; filename=" + this.cboFileList.SelectedValue));

Response.HeaderEncoding = System.Text.Encoding.Default;

Response.BinaryWrite(ms.ToArray());

Response.End();

ms.Close();

ms.Dispose();

5-7
Q54 (
ASP.NET
)
V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

ASP.NET , ,
( ),
,

, (
) , ,
( , ,
), ,
, , ,
,

, , ,
, , ASP.NET
(ASP.NET ),
, ASP.NET ,

5-8
ASP.NET ( ) Q54

, ASP.NET
, System.IO FileStream
, DirectoryInfo ,

// ,

FileStream fs = new FileStream(@"\\FileServer\Path\MyFile.docx",

FileMode.Open, FileAccess.Read);

byte[] data = new byte[(int)fs.Length];

fs.Read(data, 0, (int)fs.Length);

fs.Close();

5-9
Part5

Response.BinaryWriter(data);

//

DirectoryInfo di = new DirectoryInfo(@"\\FileServer\Path");

FileInfo[] list = di.GetFiles("*.docx");

( ) ,
, ,
, (Transaction)

using System.IO;

using System.Data;

using System.Data.SqlClient;

...

private void SaveFile(string FileName, byte[] FileContent)

try

// File Server

// //MyServer/FileStore ,

string fileserverPath = "//MyServer/FileStore";

FileStream fs = new FileStream(

fileserverPath + "/" + FileName, FileMode.Create,

FileAccess.Write);

fs.Write(FileContent, 0, (int)FileContent.Length);

fs.Flush();

fs.Close();

5-10
ASP.NET ( ) Q54

//

SqlConnection conn = new SqlConnection(...);

conn.Open();

SqlTransaction tran = conn.BeginTransaction();

SqlCommand cmd = new SqlCommand(

"INSERT INTO FileList VALUES (@filename, @filepath", conn);

cmd.Transaction = tran;

cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

catch (SqlException e)

// ,

tran.Rollback(); //

FileInfo fi = new FileInfo(fileserverPath + "/" + FileName);

fs.Delete(); //

fs.Close();

catch (IOException e2)

// I/O ,

, ASP.NET
, System.IO ,

5-11
Q55 ASP.NET
?
V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

, ,
, , ASP.NET

,
, , ,
, ,
, , ,
Regular Expression ( ) ,

, Winsock, HTTP Web Server


, HTTP POST HTTP GET, ,
Request, Response .NET Framework
Winsock System.Net.Sockets ,
TCP/IP

Socket Winsock , IPv4, IPv6

TcpClient Winsock TCP

UdpClient Winsock UDP

TcpListener Winsock TCP

5-12
ASP.NET ? Q55

.NET Framework HTTP


HttpWebRequest HttpWebResponse, HTTP
Web Server, , , FTP
, FtpWebRequest FtpWebResponse

( ) ,

1 HttpWebRequest

HttpWebRequest request = WebRequest.Create(

"http://tw.stock.yahoo.com/q/q?s=2330") as HttpWebRequest;

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

StreamReader sr = new StreamReader(response.GetResponseStream(),

System.Text.Encoding.Default);

strContent = sr.ReadToEnd();

sr.Close();

request = null;

response = null;

, NetworkCredential,
, HttpWebRequest.GetResponse() ,
,

, HttpWebResponse.StatusCode ,
HTTP ,

5-13
Part5

200 OK

403

404

405 HTTP

500

503

HTTP POST , POST,


Stream ( HttpWebRequest.GetRequestStream()
), GetResponse() ,

HttpWebRequest request = WebRequest.Create(strURL) as HttpWebRequest;

request.Method = "POST"; // HTTP POST

request.ContentLength = strPostData; // ,

//

request.ContentType = "application/x-www-form-urlencoded";

StreamWriter sw = new StreamWriter(request.GetRequestStream());

sw.Write(strPostData); // Request Stream

sw.Flush();

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

StreamReader sr = new StreamReader(response.GetResponseStream(),

System.Text.Encoding.Default);

strResponse = sr.ReadToEnd();

5-14
ASP.NET ? Q55

sr.Close();

sw.Close();

request = null;

response = null;

, , MSXML
(XmlDocument, HTML XML,
XHTML , HTML , XmlDocument
) Regular Expression ,

,
HttpWebRequest HttpWebResponse ,
, 91

, ,
,
, ,
, ,

, , ,

5-15
Q56 ASP.NET
V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

ASP.NET , ,
,

, , 95
, 23, 249, 262 , 95
22, 876, 527 , 1.01 ,

, (SMS) ,

, ,
(SMS Code) , ,
,

Winsock, TCP Winsock Library

HTTP HttpWebRequest

HTTP + MIoD HttpWebRequest

, , API ,
, MIoD , HTTP
, socket C

5-16
ASP.NET Q56

.NET , HTTP
, HttpWebRequest HttpWebResponse
, Winsock , TCP
, , ,
IMS ( ) HTTP ,
HttpWebRequest ,

2005 ASP.NET ,
( ),
, , ,
, , ,
, ,

1 ( )

//

private string _userID = null; // required.

private string _password = null; // required.

private string _srcaddr = null; // required.

private string _destaddr = null; // required.

private string _smbody = null; // required.

private string _encoding = null; // optional.

private string _wapurl = null; // optional.

private string _dlvtime = null; // optional.

private string _vldtime = null; // optional.

private string _responseUrl = null; // optional.

public struct Encoding

public const string ASCII = "ASCII";

public const string BIG5 = "BIG5";

public const string CP950 = "CP950";

5-17
Part5

public const string NHEAD = "NHEAD";

public const string PASCII = "PASCII";

public const string PBIG5 = "PBIG5";

public const string PUSH = "PUSH";

public const string UPUSH = "UPUSH";

public const string UCS2 = "UCS2";

public const string GB2 = "GB2";

public const string L_ASCII = "LASCI";

public const string L_BIG5 = "LBIG5";

public const string L_NHEAD = "NHEAD";

// HTTP URL

private string _templateUrl = "http://{0}:{1}/send.cgi?{2}";

private string _host = null;

private int _port = 0;

public Tcc(string Host, int Port, string UserID, string Password,

string SrcAddr, string DestAddr, string encoding, string Body)

this._host = Host;

this._port = Port;

this._userID = UserID;

this._password = Password;

this._srcaddr = SrcAddr;

this._destaddr = DestAddr;

this._encoding = encoding;

this._smbody = Body;

5-18
ASP.NET Q56

public void SetDeliveryDateTime(DateTime DeliveryDateTime)

this._dlvtime = DeliveryDateTime.ToString("yyyy/MM/dd HH:mm:ss");

public void SetValidLimitDateTime(DateTime ValidLimitDateTime)

this._vldtime = ValidLimitDateTime.ToString("yyyy/MM/dd HH:mm:ss");

public string SendMessage()

HttpWebRequest request =

(HttpWebRequest)HttpWebRequest.Create(this.BuildUrl());

HttpWebResponse response = null;

Stream stream = null;

StreamReader reader = null;

string Result = null;

request.UserAgent = "TCC_SMS_Manager";

request.Method = "GET";

response = (HttpWebResponse)request.GetResponse();

//

stream = response.GetResponseStream();

reader = new StreamReader(stream);

Result = reader.ReadToEnd();

//

5-19
Part5

reader.Close();

response.Close();

response = null;

request = null;

//

// msgid=value1\nstatusstr=value2

// parse string.

if (Result != null)

string MsgID = Result.Split('\n')[0].Split('=')[1];

string StatusStr = Result.Split('\n')[1].Split('=')[1];

if (Int32.Parse(MsgID) > 0)

// , ID

return MsgID;

else

switch (MsgID)

//

else

5-20
ASP.NET Q56

//

throw new InvalidOperationException(

" .");

private string BuildUrl()

// default RATE_PLAN is A.

string template =

"username={0}&password={1}&rateplan=A&srcaddr={2}&dstaddr={3}&smbody={4}";

string strResult =

string.Format(template, this._userID, this._password,

this._srcaddr, this._destaddr, this._smbody);

if (_encoding != null)

strResult += string.Format("&encoding={0}", this._encoding);

if (_wapurl != null)

strResult += string.Format("&wapurl={0}", this._wapurl);

if (_dlvtime != null)

strResult += string.Format("&dlvtime={0}", this._dlvtime);

if (_vldtime != null)

strResult += string.Format("&vldtime={0}", this._vldtime);

if (_responseUrl != null)

strResult += string.Format("&response={0}", this._responseUrl);

// HTTP

return string.Format(this._templateUrl, this._host, this._port,

strResult);

5-21
Part5

2 ( )

// Winsock

// HTTP , HTTP

// ,

// TcpClient TcpClient ,

private TcpClient _client = null;

private NetworkStream _ns = null;

private string _userID = null;

private string _password = null;

private string _sendPhoneNumber = null;

private string _primaryServer = null;

private string _backupServer = null;

//

public struct Constants

public const int MAX_ID_LEN = 8;

public const int MAX_PASSWD_LEN = 8;

public const int MAX_MSISDN_LEN = 12;

public const int MAX_MESSAGEID_LEN = 8;

public const int MAX_MSG_LEN = 159;

public const int ORDERTIME_LEN = 12;

public const byte SERV_CHECK = 0;

public const byte SERV_EDIT_PASSWD = 1;

public const byte SERV_SEND = 2;

public const byte SERV_QUERY = 3;

public const byte SERV_GET = 4;

public const byte SERV_SEND_WITH_UDHI = 6;

public const byte SEND_NOW = 100;

public const byte SEND_ORDER = 101;

}
5-22
ASP.NET Q56

//

public struct SendMsg

public byte type;

public byte coding;

public byte length;

public byte tran_type;

public char[] pchID;

public char[] pchPasswd;

public char[] pchMsisdn;

public char[] pchMessageID;

public byte[] pchMessage;

public char[] pchSendTime;

public byte[] ToBytes()

int length = 10 + Constants.MAX_ID_LEN +

Constants.MAX_PASSWD_LEN + Constants.MAX_MSISDN_LEN +

Constants.MAX_MESSAGEID_LEN + Constants.MAX_MSG_LEN +

Constants.ORDERTIME_LEN;

byte[] buffer = new byte[length];

int iBitLocation = 0;

// fill information.

buffer[0] = this.type;

buffer[1] = this.coding;

buffer[2] = this.length;

buffer[3] = this.tran_type;

iBitLocation = 4;

5-23
Part5

// pchID

for (int i=0; i<Constants.MAX_ID_LEN+1; i++)

if (i < this.pchID.Length)

buffer[iBitLocation] = (byte)this.pchID[i];

else

buffer[iBitLocation] = 0x0;

iBitLocation++;

// pchPasswd

for (int i=0; i<Constants.MAX_PASSWD_LEN+1; i++)

if (i < this.pchPasswd.Length)

buffer[iBitLocation] = (byte)this.pchPasswd[i];

else

buffer[iBitLocation] = 0x0;

iBitLocation++;

// pchMsisdn

for (int i=0; i<Constants.MAX_MSISDN_LEN+1; i++)

if (i < this.pchMsisdn.Length)

buffer[iBitLocation] = (byte)this.pchMsisdn[i];

else

buffer[iBitLocation] = 0x0;

iBitLocation++;

5-24
ASP.NET Q56

// pchMessageID

for (int i=0; i<Constants.MAX_MESSAGEID_LEN+1; i++)

if (i < this.pchMessageID.Length)

buffer[iBitLocation] = (byte)this.pchMessageID[i];

else

buffer[iBitLocation] = 0x0;

iBitLocation++;

for (int i=0; i<Constants.MAX_MSG_LEN+1; i++)

if (i < this.pchMessage.Length)

buffer[iBitLocation] = (byte)this.pchMessage[i];

else

buffer[iBitLocation] = 0x0;

iBitLocation++;

// pchSendTime

for (int i=0; i<Constants.ORDERTIME_LEN+1; i++)

if (i < this.pchSendTime.Length)

buffer[iBitLocation] = (byte)this.pchSendTime[i];

else

buffer[iBitLocation] = 0x0;

iBitLocation++;

return buffer;

}
5-25
Part5

// ,

public struct RecvMsg

public byte code;

public byte coding;

public byte length;

public char[] send_msisdn;

public char[] recv_msisdn;

public char[] buffer;

public CHT(string ServerAddr, int Port, string SendPhoneNumber)

this._client = new TcpClient(ServerAddr, Port); // TcpClient

this._sendPhoneNumber = SendPhoneNumber;

this._client.SendTimeout = 100;

this._client.ReceiveTimeout = 100;

public CHT(string ServerAddr, string BackupServerAddr, int Port)

this._client = new TcpClient(ServerAddr, Port);

this._client.SendTimeout = 100;

this._client.ReceiveTimeout = 100;

this._primaryServer = ServerAddr;

this._backupServer = BackupServerAddr;

5-26
ASP.NET Q56

~CHT()

if (this._ns != null)

this._ns = null;

if (this._client != null)

this._client = null;

// helper.

private IPEndPoint CreateEndPoint(string RemoteAddress, int Port)

byte[] ip_addr = new byte[4];

IPAddress ipaddr = null;

IPEndPoint ep = null;

ipaddr = IPAddress.Parse(RemoteAddress);

ep = new IPEndPoint(ipaddr, Port);

return ep;

//

public SendMsg InitSendMsg()

SendMsg msg = new SendMsg();

msg.pchID = new char[Constants.MAX_ID_LEN+1];

msg.pchPasswd = new char[Constants.MAX_PASSWD_LEN+1];

msg.pchMsisdn = new char[Constants.MAX_MSISDN_LEN+1];

5-27
Part5

msg.pchMessageID = new char[Constants.MAX_MESSAGEID_LEN+1];

msg.pchMessage = new byte[Constants.MAX_MSG_LEN+1];

msg.pchSendTime = new char[Constants.ORDERTIME_LEN+1];

return msg;

//

public RecvMsg InitRecvMsg()

RecvMsg msg = new RecvMsg();

msg.send_msisdn = new char[Constants.MAX_MSISDN_LEN+1];

msg.recv_msisdn = new char[Constants.MAX_MSISDN_LEN+1];

msg.buffer = new char[Constants.MAX_MSG_LEN+1];

return msg;

public void Open()

// connect to remote server.

// detect socket error, if connection refused,

// try connection for 2nd IP.

try

this._client.Open();

catch (SocketException se)

5-28
ASP.NET Q56

if (se.ErrorCode == 10061)

try

// try 2nd IP for connection.

this._client.Open(this._backupServer);

catch (SocketException socketEx)

throw new Exception(string.Format(

"Backup IP connection Socket Error Code: {0}",

socketEx.ErrorCode));

catch (Exception ex)

throw new Exception(

"Backup IP connection error : " + ex.Message + "\n\n" +

ex.StackTrace);

else

throw new Exception(

string.Format(

"Primary IP connection Socket Error Code: {0}",

se.ErrorCode));

catch (Exception ex)

throw new Exception("Primary IP connection error: " +

ex.Message + "\n\n" + ex.StackTrace);

}
5-29
Part5

public void Close()

// close remote connection.

this._client.Close();

public void Send(SendMsg sendMsg)

// send command.

this._client.SendStructure(sendMsg);

//

public RecvMsg Recv()

byte[] data = this._client.ReceiveRawData();

RecvMsg msg = this.InitRecvMsg();

string Message = string.Empty;

int size = 200;

char[] buf = ASCIIEncoding.ASCII.GetChars(data, 0, data.Length);

//

if (buf.Length != 0)

msg.code = data[0];

msg.coding = data[1];

msg.length = byte.Parse(data[2].ToString());

msg.send_msisdn = this.GetChars(buf, 3, msg.send_msisdn.Length);

msg.recv_msisdn = this.GetChars(buf, 3 +

msg.send_msisdn.Length, msg.recv_msisdn.Length);

5-30
ASP.NET Q56

msg.buffer = this.GetChars(buf,

3 + msg.send_msisdn.Length + msg.send_msisdn.Length,

size - (3 + msg.send_msisdn.Length+msg.recv_msisdn.Length));

if (msg.code == (byte)12) // msg.code

// build message string.

for (int i=0; i<data.Length; i++)

Message += data[i].ToString();

throw new InvalidOperationException(

string.Format("Format Error: {0}", Message));

else

throw new FormatException("Data Length: 0");

return msg;

// helper.

// parse byte[] to structure.

public char[] GetChars(char[] Source, int Start, int Length)

char[] result = new char[Length];

for (int i=Start; i<Length; i++)

result[i] = Source[i];

return result;

5-31
Part5

private void ParseNullBytesToEmptyString(ref byte[] Data)

for (int i=0; i<Data.Length; i++)

// set byte=0 to String.Empty.

// code : 0x20,

if (Data[i] == 0x00)

Data[i] = 0x20;

// public functions.

// use this to do your operation.

public void Login(string UserID, string Password)

SendMsg sendMsg = this.InitSendMsg();

RecvMsg recvMsg = this.InitRecvMsg();

string RawData = null;

this._userID = UserID;

this._password = Password;

//

sendMsg.type = Constants.SERV_CHECK;

sendMsg.pchID = UserID.ToCharArray();

sendMsg.pchPasswd = Password.ToCharArray();

this._client.Send(sendMsg.ToBytes()); //

5-32
ASP.NET Q56

recvMsg = this.Recv(); //

switch (recvMsg.code)

case 0:

// authenticated successfully.

break;

case 1:

throw new Exception(RawData);

case 2:

throw new Exception("Cannot send from this IP.");

case 3:

throw new Exception("System error, try again.");

case 4:

throw new Exception("This account is forbidden.");

//

public void SendMessage(string TargetPhoneNumber, byte coding,

string Message, out string MessageID)

SendMsg sendMsg = this.InitSendMsg();

RecvMsg recvMsg = this.InitRecvMsg();

string BufferContent = string.Empty;

char[] pchID = { (char)0x00 };

5-33
Part5

//

sendMsg.type = Constants.SERV_SEND;

sendMsg.coding = coding;

sendMsg.pchMsisdn = TargetPhoneNumber.ToCharArray();

sendMsg.pchMessage = Encoding.Default.GetBytes(Message);

sendMsg.length = (byte)sendMsg.pchMessage.Length;

sendMsg.tran_type = Constants.SEND_NOW;

//

this._client.SendBufferSize = sendMsg.ToBytes().Length;

this._client.Send(sendMsg.ToBytes());

//

this._client.recvBufferSize = 200;

recvMsg = this.Recv();

// build buffer.

for (int i=0; i<recvMsg.buffer.Length; i++)

BufferContent += new string(recvMsg.buffer[i], 1);

switch (recvMsg.code)

case 0:

MessageID = new string(recvMsg.buffer).Trim();

break;

case 1:

throw new Exception("Cannot send character.");

case 2:

throw new Exception("Message sending failure.");

5-34
ASP.NET Q56

case 3:

throw new Exception("Orderd time beyond 48 hours.");

case 4:

throw new Exception("Send binary to pager.");

case 5:

throw new Exception("Code transfer fail.");

case 6:

throw new Exception("Message sequence number error.");

case 7:

throw new Exception("Message out of sequence.");

default:

throw new Exception(string.Format(

"Unknow code: {0}, Content: {1}", recvMsg.code,

BufferContent));

//

public bool Query(string TargetPhoneNumber, string MessgaeID)

SendMsg sendMsg = this.InitSendMsg();

RecvMsg recvMsg = this.InitRecvMsg();

//

sendMsg.type = Constants.SERV_QUERY;

5-35
Part5

//

this.Send(sendMsg);

//

recvMsg = this.Recv();

switch (recvMsg.code)

case 0:

// message sent successfully.

return true;

case 1:

// message processing.

return false;

case 2:

throw new Exception("Message sending failure.");

case 3:

throw new Exception("Orderd time beyond 48 hours.");

case 4:

throw new Exception("Send binary to pager.");

case 5:

throw new Exception("Code transfer fail.");

case 6:

throw new Exception("Message sequence number error.");

5-36
ASP.NET Q56

case 7:

throw new Exception("Message out of sequence.");

default:

throw new Exception(string.Format(

"Unknow code: {0}, Content: {1}", recvMsg.code,

recvMsg.buffer));

//

public RecvMsg Receive()

SendMsg sendMsg = this.InitSendMsg();

RecvMsg recvMsg = this.InitRecvMsg();

string BufferContent = string.Empty;

//

sendMsg.type = Constants.SERV_GET;

//

this._client.Send(sendMsg.ToBytes());

//

recvMsg = this.Recv();

// build buffer.

for (int i=0; i<recvMsg.buffer.Length; i++)

BufferContent += new string(recvMsg.buffer[i], 1);

5-37
Part5

switch (recvMsg.code)

case 0:

// get message.

return recvMsg;

case 1:

//

recvMsg = this.InitRecvMsg();

recvMsg.code = 1;

return recvMsg;

case 2:

throw new Exception("Message sending failure.");

case 3:

throw new Exception("Orderd time beyond 48 hours.");

case 4:

throw new Exception("Send binary to pager.");

case 5:

throw new Exception("Code transfer fail.");

case 6:

throw new Exception("Message sequence number error.");

case 7:

throw new Exception("Message out of sequence.");

5-38
ASP.NET Q56

default:

throw new Exception(string.Format(

"Unknow code: {0}, Content: {1}", recvMsg.code,

BufferContent));

// TcpClient

public class TcpClient : System.Net.Sockets.TcpClient

private NetworkStream _ns = null;

private string _serverAddr = null;

private int _serverPort = 0;

private int _timeout = 5; // 3 sec of timeout.

public TcpClient(string ServerAddress, int Port)

this._serverAddr = ServerAddress;

this._serverPort = Port;

~TcpClient()

base.Dispose(true);

GC.Collect();

public int Timeout

get { return this._timeout; }

set { this._timeout = value; }

}
5-39
Part5

public int recvBufferSize

get { return base.ReceiveBufferSize; }

set { base.ReceiveBufferSize = value; }

public int sendBufferSize

get { return base.SendBufferSize; }

set { base.SendBufferSize = value; }

public void Open()

base.Connect(this._serverAddr, this._serverPort);

public void Open(string ServerAddr)

base.Connect(ServerAddr, this._serverPort);

public void Open(string ServerAddr, int Port)

base.Connect(ServerAddr, Port);

new public void Close()

base.Close();

5-40
ASP.NET Q56

// send string directly.

public void Send(string Data)

byte[] rawData = ASCIIEncoding.ASCII.GetBytes(Data);

if (!base.Active)

throw new Exception("Connection is not be created.");

// get network stream.

this._ns = base.GetStream();

// write data.

this._ns.Write(rawData, 0, rawData.Length);

// object convert to string and send it.

public void Send(object Data)

byte[] rawData = ASCIIEncoding.ASCII.GetBytes(Data.ToString());

if (!base.Active)

throw new Exception("Connection is not be created.");

// get network stream.

this._ns = base.GetStream();

// write data.

this._ns.Write(rawData, 0, rawData.Length);

public void Send(byte[] rawData)

5-41
Part5

if (!base.Active)

throw new Exception("Connection is not be created.");

// get network stream.

this._ns = base.GetStream();

// write data.

this._ns.Write(rawData, 0, rawData.Length);

// object convert to string and send it.

public void SendStructure(object Data)

if (!base.Active)

throw new Exception("Connection is not be created.");

//

//

IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(Data));

byte[] rawData = new byte[Marshal.SizeOf(Data)];

// (like memset() API.)

Marshal.StructureToPtr(Data, ptr, true);

//

Marshal.Copy(ptr, rawData, 0, Marshal.SizeOf(Data));

// get network stream.

this._ns = base.GetStream();

// write data.

this._ns.Write(rawData, 0, rawData.Length);

5-42
ASP.NET Q56

public string Receive()

byte[] buffer = this.ReceiveRawData();

return this.ParseBytesToString(buffer);

public byte[] ReceiveRawData()

DateTime sTimeout = DateTime.Now.AddSeconds(this._timeout);

MemoryStream ms = new MemoryStream();

byte[] buffer = new byte[base.ReceiveBufferSize];

// wait specified time for return.

while (DateTime.Now < sTimeout)

// do nothing, for loop and exit when timeout.

this._ns = base.GetStream();

// receive data.

while (this._ns.DataAvailable)

// read to buffer.

this._ns.Read(buffer, 0, base.ReceiveBufferSize);

// write to memory stream.

ms.Write(buffer, 0, buffer.Length);

ms.Flush();

ms.Position = 0;

5-43
Part5

byte[] result = new byte[ms.Length];

// read from memory stream.

ms.Read(result, 0, result.Length);

ms.Close();

return result;

public object ReceiveStructure(System.Type StructType)

//

byte[] t_buffer = this.ReceiveRawData();

IntPtr ptr = Marshal.AllocCoTaskMem(t_buffer.Length);

object Result = new object();

//

Marshal.Copy(t_buffer, 0, ptr, t_buffer.Length);

//

Result = Marshal.PtrToStructure(ptr, StructType);

return Result;

// helper.

private string ParseBytesToString(byte[] Data)

for (int i=0; i<Data.Length; i++)

5-44
ASP.NET Q56

// set byte=0 to String.Empty.

// code : 0x20,

if (Data[i] == 0x00)

Data[i] = 0x20;

// convert to string.

return

ASCIIEncoding.ASCII.GetString(Data, 0, Data.Length).Trim();

private HttpWebRequest _request = null;

private HttpWebResponse _response = null;

private string _MiodServletContext = null;

private string _serverAddr = null;

private int _port = 0;

//

private string _username = null;

private string _password = null;

// URL

private string _pattern =

"http://{0}/{1}/servlet/com.fet.miod.SendSMS?{2}";

public FETNET(string ServerAddr, int Port, string UserName,

string Password, string MiodServletContext)

5-45
Part5

this._serverAddr = ServerAddr;

this._port = Port;

this._username = UserName;

this._password = Password;

this._MiodServletContext = MiodServletContext;

// NOTE: Server.UrlEncode()

public void Send(string[] Target, string Message, string Language,

DateTime DeliverDate, int Dr_Flag)

string QueryString = null;

string Url = null;

// generate query string.

QueryString += string.Format("username={0}", this._username);

QueryString += string.Format("&password={0}", this._password);

QueryString += string.Format("&language={0}", Language);

QueryString += string.Format("&message={0}", Message);

// additional parameters.

if (!Dr_Flag.Equals(null))

QueryString += string.Format("&dr_flag={0}", Dr_Flag);

if (!DeliverDate.Equals(null))

QueryString += string.Format("&deliver_date={0}",

DeliverDate.ToString("yyyyMMddhhmmss"));

// bind target parameter.

if (Target != null)

5-46
ASP.NET Q56

for (int i=0; i<Target.Length; i++)

QueryString += string.Format("&target{0}={1}", i, Target[i]);

Url = string.Format(

this._pattern, string.Format("{0}:{1}", this._serverAddr,

this._port),

this._MiodServletContext, QueryString);

this._request = (HttpWebRequest)HttpWebRequest.Create(

string.Format("{0}:{1}", this._serverAddr, this._port));

// send message.

this._response = (HttpWebResponse)this._request.GetResponse();

if (this._response.StatusCode != HttpStatusCode.OK)

string strCode = this._response.StatusCode.ToString();

this._response.Close();

this._request = null;

this._response = null;

throw new InvalidOperationException(

string.Format("HTTP CODE: {0}", strCode));

this._response.Close();

this._request = null;

this._response = null;

5-47
Part5

, API , ,
HttpWebRequest Winsock TCP ,

, ,
, ( , ),
, ,

5-48
Q57 Web Service
V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

A , A SCM
(Supply Chain Management) , A ,
Web Service ,
Web Service

, Web Service , ,
API, SOAP ,
Web Service , , Web Service
, WSDL

Microsoft .NET 1.0 , Web Service


(Distributed Application) , COM+ ,
XML Web Service , , XML Web Service Web
Service Microsoft .NET Framework 1.0
Web Service , Visual Studio
Web ,
Web Service

5-49
Part5

URL , Web Service


, Web Service (Proxy Class)
, Web Service ( WeatherForecast) Web
Service Proxy

Visual Studio Web , Web Service WSDL


, Web Service , Visual Studio
, Web Service Proxy,
, Proxy Web Service ,
Web Service ,

Web Service ,

5-50
Web Service Q57

private void Button1_Click(object sender, EventArgs e)

// Web Service Proxy

net.webservicex.www.WeatherForecast wf =

new net.webservicex.www.WeatherForecast();

// (Seattle)

string data = wf.GetWeatherByPlaceName("Seattle");

//

...

, Web Service , Vi-


sual Studio , (
AJAX) , , WSDL
JavaScript Web Service , ,
Web Service , JavaScript
SOAP Client jQuery , JavaScript SOAP
Client Web Service JavaScript

using System.Data;

using System.Data.SqlClient;

using System.Xml;

...

[WebMethod]

public string GetProductInfo()

SqlConnection conn = new SqlConnection(

"Initial Catalog=Northwind; Integrated Security=SSPI");

SqlCommand cmd = new SqlCommand(

"SELECT ProductID, ProductName, QuantityPerUnit, UnitPrice FROM


Products", conn);
5-51
Part5

SqlDataReader reader =

cmd.ExecuteReader(CommandBehavior.CloseConnection);

XmlDocument doc = new XmlDocument();

doc.LoadXml("<ProductInfo></ProductInfo>");

// XML

while (reader.Read())

XmlNode node = doc.CreateNode(XmlNodeType.Element,

"Product", null);

for (int i=0; i<reader.Fields.Count; i++)

XmlNode attr = doc.CreateNode(XmlNodeType.Attribute,

"Product", null);

attr.Name = reader.GetName(i);

attr.Value = reader.GetValue(i).ToString();

node.Attributes.SetNamedItem(attr);

doc.DocumentElement.AppendChild(node);

reader.Close();

reader = null;

cmd.Dispose();

conn.Dispose();

return doc.InnerXml;

5-52
Web Service Q57

function GetProductInfo(Barcode)

var pl = new SOAPClientParameters();

// send request.

SOAPClient.invoke(

"http://localhost/MyWebService.asmx", // Web Service URL

"GetProductInfo", //

pl, //

true, //

GetProductWebServiceResponse); //

function GetProductWebServiceResponse(e)

alert(e); // Web Service XML

( )

<ProductInfo>

<Product ProductID="1" ProductName="Chai" QuantityPerUnit="10

boxes x 20 bags" UnitPrice="18.00" />

<Product ProductID="2" ProductName="Chang"

QuantityPerUnit="24 - 12 oz bottles" UnitPrice="19.00" />

...

</ProductInfo>

, ASP.NET AJAX AJAX Web Service


, ScriptManager Web Service,
ASP.NET AJAX

5-53
Part5

<asp:ScriptManager ID="myScriptManager" runat="server">

<Services>

<asp:ServiceReference Path="MyWebService.asmx" />

</Services>

</asp:ScriptManager>

A Web Service URL API , Web Service


Web , API , Web
Service

JavaScript SOAP Library ( JavaScript SOAP


) jQuery ,

JavaScript SOAP Library

http://www.guru4.net/articoli/javascript-soap-client/en/

jQuery

http://jquery.com/

5-54
Web Service Q57

Web Service
Web Service HTTP , , HTTP POST
GET Web Service, , Web Service HTTP POST
, Web Service SOAP , HTTP
POST ,

HttpWebRequest request = WebRequest.Create(

"http://www.webservicex.net/WeatherForecast.asmx/
GetWeatherByPlaceName")

as HttpWebRequest;

request.Method = "POST";

string postData = "PlaceName=Seattle";

ASCIIEncoding encoding = new ASCIIEncoding ();

byte[] byte1 = encoding.GetBytes (postData);

request.ContentType = "application/x-www-form-urlencoded";

request.ContentLength = byte1.Length;

Stream s = request.GetRequestStream ();

s.Write (byte1, 0, byte1.Length);

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

, WS-Security WS-Profile Web Service


, Web Service (Web Service Enhancement WSE) ,
SOAP , Visual Studio

5-55
Q58 Web Service Session
V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

Web Service, , Web Service


, Session , Web Service
Session

Web Service , Web Server


, Web Server , Web Service

Session Web ,
Session, , Web Service
( ), ,
Web Service ViewState, Session

Web Service Session , Web Service


[WebMethod(EnableSession=true)] ,

[WebMethod(EnableSession=true)]

public string myWebMethod(string arg1, string arg2)

....

Session , Web , ,
Application , , Application

5-56
Web Service Session Q58

, ,
SOAP Header , ,
Token ( ) , SOAP Header ,

SOAP Header SOAP ,


SOAP , Web Service ,
, Web Service , ,
SoapHeader

using System.Web.Service;

using System.Web.Service.Protocols;

public class UserInfo : SoapHeader {

string UserName;

string Password;

public class MyWebService : System.Web.Service.WebService {

....

SOAP Header , Web Service ,


SOAP Header , , Web Service
SOAP Header

public class MyWebService : System.Web.Service.WebService {

private UserInfo _myInfo;

public UserInfo MyUserInfo

5-57
Part5

get { return this._myInfo; }

set { this._myInfo = value; }

...

, , [SoapHeader], ,
SOAP Header , SOAP Header

[WebMethod]

[SoapHeader("MyUserInfo", Direction = SoapHeaderDirection.In)]

public int CalculateSalary(string EmployeeID)

// SOAP Header

if (!AuthenticateUser(this._myInfo.UserName, this._myInfo.Password))

return 0;

...

SOAP Header , WSDL , Web


( WSDL , WSDL) ,
SOAP Header

, , SOAP Header ,
, Web Service SOAP Header ( SOAP
Header )

protected void cmdInvoke_Click(object sender, EventArgs e)

SoapHeaderWebservice ws = new SoapHeaderWebservice();

// SOAP Header

5-58
Web Service Session Q58

UserInfo userInfo = new UserInfo();

// SOAP Header

userInfo.UserName = this.T_UserName.Text;

userInfo.Password = this.T_Password.Text;

// SOAP Header

ws.MyUserInfo = userInfo;

// Web Service

Response.Write("<script> alert('" + ws.CalculateSalary(5) +

"'); </script>");

ws = null;

SOAP Header , ( SOAP


Header ), , Web
Service , MSDN Library XML Web Service

// Web Service

using System;

using System.Data;

using System.Data.SqlClient;

using System.Web;

using System.Collections;

using System.Web.Services;

using System.Web.Services.Protocols;

// SOAP Header

public class UserInfo : SoapHeader

public string UserName;

public string Password;

5-59
Part5

public class SoapHeaderWebservice : System.Web.Services.WebService

private UserInfo _myInfo = null; // SOAP Header

// SOAP Header

public UserInfo MyUserInfo

get { return this._myInfo; }

set { this._myInfo = value; }

// ,

private bool AuthenticateUser(string UserName, string Password)

if (UserName != "root" && Password != "mypassword")

return false;

else

return true;

[WebMethod]

[SoapHeader("MyUserInfo", Direction = SoapHeaderDirection.In)]

public int CalculateSalary(int EmployeeID)

if (!AuthenticateUser(this._myInfo.UserName,

this._myInfo.Password))

return -1;

SqlConnection conn = new SqlConnection(

"Initial Catalog=Northwind; Integrated Security=SSPI");

SqlCommand cmd = new SqlCommand(@"

SELECT CAST(ISNULL(SUM(UnitPrice * Quantity * Discount), 0) *

0.5 as int)

5-60
Web Service Session Q58

FROM Orders o INNER JOIN Employees e ON

o.EmployeeID = e.EmployeeID

INNER JOIN [Order Details] od ON o.OrderID = od.OrderID

WHERE e.EmployeeID = @employeeID", conn);

cmd.Parameters.Add("@employeeID", EmployeeID);

cmd.CommandType = CommandType.Text;

conn.Open();

int salary = Convert.ToInt32(cmd.ExecuteScalar());

conn.Close();

cmd.Dispose();

conn.Dispose();

return salary;

// , SoapHeader

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

5-61
Part5

public partial class Part5_InvokeMyWebService : System.Web.UI.Page

protected void Page_Load(object sender, EventArgs e)

protected void cmdInvoke_Click(object sender, EventArgs e)

SoapHeaderWebservice ws = new SoapHeaderWebservice();

// SOAP Header

UserInfo userInfo = new UserInfo();

// SOAP Header

userInfo.UserName = this.T_UserName.Text;

userInfo.Password = this.T_Password.Text;

// SOAP Header

ws.MyUserInfo = userInfo;

// Web Service

Response.Write("<script> alert('" + ws.CalculateSalary(5) +

"'); </script>");

ws = null;

WebMethod , EnableSession=true Session ,


Session, Web

5-62
Web Service Session Q58

Session , SOAP Header,


, SOAP Header , SSL
,

, Exam 70-529: TS: Microsoft .NET Framework 2.0 Distributed


Application Development

Web Service

Web Service (Session State)

Session

SOAP Headers

SOAP Header

SoapHeader Web

Web SOAP Header

SOAP Header

5-63
Q59 ?
V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

,
, , (
), ,
, ,

Web , ,
Web Server, ,
, W3C (HTML, XHTML, CSS, Dy-
namic HTML) , , Windows
Mobile Pocket Internet Explorer, Internet

Internet Explorer 78.68%

Firefox 14.56%

Safari 4.68%

Opera 0.88%

Netscape 0.71%

Opera Mini 0.27%

Mozilla 0.11%

Market Share
http://marketshare.hitslink.com/report.aspx?qprid=0

5-64
? Q59

W3C , CSS
DOM , HTML
( IE marquee ),
, ,
,

, ,
, Session, Session Cookie
, cookie , Session , Web
cookie , cookie

Cookie

Scripting

ActiveX Plug-in

, ,
HttpRequest.Browser , HttpBrowserCapabilities ,

5-65
Part5

HttpBrowserCapabilities bc = Request.Browser;

Response.Write("<p>Browser Capabilities:</p>");

Response.Write("Type = " + bc.Type + "<br>");

Response.Write("Name = " + bc.Browser + "<br>");

Response.Write("Version = " + bc.Version + "<br>");

Response.Write("Major Version = " + bc.MajorVersion + "<br>");

Response.Write("Minor Version = " + bc.MinorVersion + "<br>");

Response.Write("Platform = " + bc.Platform + "<br>");

Response.Write("Is Beta = " + bc.Beta + "<br>");

Response.Write("Is Crawler = " + bc.Crawler + "<br>");

Response.Write("Is AOL = " + bc.AOL + "<br>");

Response.Write("Is Win16 = " + bc.Win16 + "<br>");

Response.Write("Is Win32 = " + bc.Win32 + "<br>");

Response.Write("Supports Frames = " + bc.Frames + "<br>");

Response.Write("Supports Tables = " + bc.Tables + "<br>");

Response.Write("Supports Cookies = " + bc.Cookies + "<br>");

Response.Write("Supports VB Script = " + bc.VBScript + "<br>");

Response.Write("Supports JavaScript = " + bc.JavaScript + "<br>");

Response.Write("Supports Java Applets = " + bc.JavaApplets + "<br>");

Response.Write("Supports ActiveX Controls = " +

bc.ActiveXControls + "<br>");

Response.Write("CDF = " + bc.CDF + "<br>");

HttpBrowserCapabilities ,
.NET Framework Config\Browsers , .NET
Framework 2.0 , 25 , , .NET
Browser , XML , *.browser, ASP.
NET User-Agent ,
, Internet Explorer User-Agent

5-66
? Q59

<browser id="IE" parentID="Mozilla">

<identification>

<userAgent match="^Mozilla[^(]*\

([C|c]ompatible;\s*MSIE

(?'version'(?'major'\d+)(?'minor'\.\d+)

(?'letters'\w*))(?'extra'[^)]*)" />

<userAgent nonMatch="Opera|Go\.Web|

Windows CE|EudoraWeb" />

</identification>

</browser>

, , Browser
, User-Agent

<browser id="IE6to9" parentID="IE5to9">

<identification>

<capability name="majorversion" match="[6-9]" />

</identification>

</browser>

Web
, (Mobility Device Browser)
Web , (
, DHTML JavaScript ), Web , ,
, , ASP.NET Mobile Web Controls
HTML (C-HTML WML )

, , Mobile
, , Device-Specific Rendering,
, ,
Mobile ,

5-67
Part5

, ,
, Mobile ,

<mobile:Image ID="logoImage" ImageUrl="LogoMono.gif" Runat="server">

<DeviceSpecific>

<Choice Filter="isColor" ImageUrl="LogoColor.gif" />

</DeviceSpecific>

</mobile:Image>

<DeviceSpecific> <Choice> BrowserCapabilities


( isColor) , true , <Choice> ImageUrl
ImageUrl,

Request.Browsers HttpBrowserCapabilities ,
, , DeviceFilter
DeviceSpecific

, Exam 70-528: TS: Microsoft .NET Framework 2.0 Web Client


Development

Web

Web

Web Form

ASP.NET Mobile

Device-Specific Rendering

Mobile Web

5-68
Q60 Active Directory
V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

Active Directory , ASP.


NET AD , ASP.NET
Active Directory

Active Directory Windows 2000 ,


(Directory Service) , Windows NT 4.0 NTDS (Windows NT
Directory Service) , NTDS ,
Internet , Domain Name Service (DNS) LDAP (Lightweight
Directory Access Protocol) Kerberos V5 , Active
Directory Internet , , OU
Domain Forest ,

, Active Directory
AD , ADSI (Active Directory Service Interface) ,
COM , AD , Active Direc-
tory ( OLE DB Provider for Active Directory)

Microsoft .NET Framework , ADSI ,


System.DirectoryService, ,
, DirectoryEntry, DirectorySearcher,
, DirectoryEntry ,
DirectorySearcher AD

5-69
Part5

System.DirectoryService Active Directory,

System.DirectoryService.dll , System.
DirectoryService

, (
)

, LDAP

LDAP Active Directory , AD ,


, Distinguished Names (DN) ,
DirectoryEntry LDAP DN AD, LDAP DN
,

LDAP

LDAP://[distinguished name]

LDAP://cn=[common name], ou=[Organization Unit Name], dc=[Domain


Control Name]

LDAP
DC domainComponent

CN commonName

OU organizationalUnitName

O organizationName

STREET streetAddress

L localityName

ST stateOrProvinceName

C countryName

UID userid

5-70
Active Directory Q60

, , ,
, AD , LDAP ,
,

, Acme.com DC Administrator ,
Domain, LDAP

LDAP://cn=Administrator, cn=Users, dc=acme, dc=com

Management OU Steven ,

LDAP://cn=Steven, ou=Management, dc=acme, dc=com

AD ,

Active Directory
Active Directory ,

System.DirectoryService DirectoryEntry DirectorySearcher


AD , , AD
LDAP

5-71
Q61 Active Directory

V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

Active Directory ,
, , Web
, Active Directory
, ASP.NET Active Directory

Active Directory , Microsoft .NET


Framework ADSI , LDAP
, , Active Directory

Active Directory ,

(Domain Controller) domainComponent (dc) ,


AD , ADSI

(Domain) AD ,
, , Forest

(Forest) , ,
(Trust Relationship) , AD

(Organization Unit) organizationUnitName (ou) ,


Domain AD , ,

AD (Object) , AD
AD Schema

5-72
Active Directory Q61

AD Schema , Schema,
Schema

Active Directory , Windows


Server 2003 MCSE , TechNet

ADSI , LDAP , LDAP


, ,
DirectorySearcher , DirectorySearcher
DirectoryEntry

DirectoryEntry

DirectoryEntry(LDAP_DN, UserName, Password);

LDAP_DN LDAP ,

UserName LDAP

Password LDAP

DirectoryEntry , UserName Password


, ,
, DirectoryEntry.AuthenticateType (.NET 2.0 ,
, .NET 1.x, )

, DirectoryEntry Schema , Schema


CommitChanges(), AD
, DirectoryEntry Properties , AD Schema
, DirectoryEntry , DirectoryEntry.InvokeGet() ,
DirectoryEntry.Properties[name].Value Schema

5-73
Part5

DirectoryEntry entry = null;

string strLDAP = "LDAP://cn=steven, cn=Users, dc=acme, dc=com";

string strUserName = "myAccount", strPassword = "myPassword";

try

// DirectoryEntry,

// strUserName strPassword

entry = new DirectoryEntry(strLDAP, strUserName, strPassword);

// AD Schema

string[] keys = new string[entry.Properties.Count];

entry.Properties.PropertyNames.CopyTo(keys, 0);

for (int i = 0; i < keys.Length; i++)

Response.Write(

"Schema: " + keys[i] + " Value: " +

entry.Properties[keys[i]].Value.ToString() + "<br>");

catch (DirectoryServicesCOMException dsex)

Response.Write(dsex.Message);

entry = null;

AD Schema , DirectoryEntry.InvokeSet()
AD Schema , DirectoryEntry.CommitChanges(),

5-74
Active Directory Q61

DirectoryEntry entry = null;

try

entry = new DirectoryEntry(this.T_Url.Text, this.T_UserName.Text,

this.T_Password.Text);

// Schema

entry.InvokeSet(this.cboSchema.SelectedValue, this.T_Value.Text);

// ,

entry.CommitChanges();

catch (DirectoryServicesCOMException dsex)

Response.Write(dsex.Message);

entry = null;

, DirectoryEntry (DirectoryEntry.Parent
) (DirectoryEntry.Children ) (DirectoryEntry.
MoveTo()) (DirectoryEntry.DeleteTree()) ,

( OU) , DirectorySearcher
, DirectorySearcher Schema AD ,
DirectorySearcher (DirectorySearcher.SearchRoot
, LDAP , ), (DirectorySearcher.
SearchScope , )
(DirectorySearcher.Filter, Schema ),
DirectorySearcher.FindAll() DirectorySearcher.FindOne()
AD

5-75
Part5

DirectorySearcher searcher = null;

try

// DirectoryEntry

searcher = new DirectorySearcher(new DirectoryEntry(

this.T_Url.Text, this.T_UserName.Text, this.T_Password.Text));

//

SearchResultCollection results = searcher.FindAll();

if (results.Count == 0)

Response.Write("No object found");

else

foreach (SearchResult result in results)

Response.Write(result.Path + "<br>");

catch (DirectoryServicesCOMException dsex)

Response.Write(dsex.Message);

searcher = null;

, Active Directory , AD
( , LDAP://RootDSE ,
, AD , RootDSE )
, DirectorySearcher ,

5-76
Active Directory Q61

string ldapURL = "LDAP://cn=Computers, dc=acme, dc=com";

DirectorySearcher searcher = new DirectorySearcher(

new DirectoryEntry(ldapURL, "myAccount", "myPassword"));

// AD

// (objectClass=Computer)

searcher.Filter = "(objectClass=User)";

//

SearchResultCollection results = searcher.FindAll();

ADSI , MSDN , Active Directory


Domain Service Active Directory Schema ,

Active Directory Schema


Active Directory ,
, , ,
, ,
, , AD , AD Schema, AD
Schema, , ( Exchange Server)
AD Schema , 1000 , Schema ,
AD , ,

, AD Schema ( , AD ),
AD Schema , , AD Schema , Ac-
tive Directory Domain Service , Schema,

Q60 Active Directory ?

5-77
Q62 Active Directory
V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

, ,
Active Directory, , Active Directory
, Active Directory

Q61 Active Directory ,


DirectoryEntry AD , UserName
Password , Active Directory
Forms Authentication ,

AD , DirectoryEntry AD
( ID) , AD
, AD , , DirectoryEntry
, (
Q61 DirectoryEntry )

, , DirectoryEntry
, ( uid SID ),
DirectorySearcher , , ,
, , SearchResult.GetDirectoryEntry()
AD , objectSid userPrincipalName
AD

5-78
Active Directory Q62

DirectorySearcher searcher = new DirectorySearcher(

new DirectoryEntry("LDAP://dc=jcistudio.idv.tw",

userName, password));

//

searcher.Filter =

"(&(objectClass=User)( sAMAccountName=" + userName + "))";

//

SearchResult result = searcher.FindOne();

if (result == null)

Response.Write("User is not exist.");

else

// SID

object sid =

result.GetDirectoryEntry().Properties["objectSid"].Value;

, DirectoryEntry DirectorySearcher
, , ,
DirectorySearcher ,

Q60 Active Directory ?

5-79
Q63
V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

, ,
, , ,

, ,
, ,
, ,
, ,
, ,
,

(Cracker) , , ,
, (
),
(Social Engineering) , ,
( DBA) ,
, (Encryption)

(Hashing) , (Hashing
Function) , , ,
, ,
, , ,

5-80
Q63

, (One-Way) ,
,
, ,

.NET Framework , System. ( )


Security.Cryptographics MD5 128

RIPEMD160 160
( )
SHA1 160

SHA256 256

SHA384 384

SHA512 512

, , ,
,

, , (
), ComputeHash() ,
,

using System.Text;

using System.Security;

using System.Security.Cryptography;

...

//

SHA256Managed algorithm = new SHA256Managed();

// ABCDEF

byte[] str = Encoding.ASCII.GetBytes("ABCDEF");

5-81
Part5

// ,

byte[] data = algorithm.ComputeHash(str);

//

string result = Encoding.ASCII.GetString(data);

algorithm = null;

// ABCDE

// ?9?????U?/{????NR}??V???{?#?

, ,
, , , ,
, ,

, , SHA1 ,
SHA256 , ,
, ,
,

, ,
, 1

using System.Text;

using System.Security;

using System.Security.Cryptography;

...

5-82
Q63

// , PasswordHashedString

public bool IsPasswordMatched(string Password,

string PasswordHashedString)

SHA384Managed algorithm = new SHA384Managed();

string hashedStr = Encoding.ASCII.GetString(

algorithm.ComputeHash(Encoding.ASCII.GetBytes(Password)));

bool result = (hashedStr == PasswordHashedString);

algorithm = null;

return result;

, ,
, ,

, Exam 70-536: TS: Microsoft .NET Framework 2.0 Application


Development Foundation

.NET Framework .NET Framework

System.Security.Cryptography
(System.Security.Cryptography )

(HMAC)

MD5

RIPEMD160

SHA1

SHA256

SHA384

SHA512

5-83
Q64 ( )
( ),

V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

, ,
,

, ,
,
, , ,
,

.NET Framework , Principal ,


, ,
, ASP.NET .NET Frame-
work ,

ASP.NET 2.0 Role Service (Role Manager) ,


, , Role Service, ,
, Membership Service

, XML ,
(Role Management Module) ,
,

5-84
( ), ( ) Q64

AddRole(rolename)

DeleteRole(role_id)

EditRole(role_id, rolename)

AddMemberToRole(member_id, role_id)

RemoveMember(member_id)

ChangeRole(member_id, new_role_id)

IsInRole(member_id, role_id)

GetRoles()

GetRoleByID(role_id)

//

public abstract class Role

public abstract void AddRole(string RoleName);

public abstract void DeleteRole(string RoleID);

public abstract void EditRole(string RoleID, string RoleName);

public abstract void AddMemberToRole(string MemberID,

string RoleID);

public abstract void RemoveMember(string MemberID);

public abstract void ChangeRole(string MemberID, string RoleID);

public abstract bool IsInRole(string MemberID, string RoleID);

public abstract DataTable GetRoles();

public abstract DataTable GetRoleByID(string RoleID);

, ,
, , AddMemberToRole()
RemoveMember()

5-85
Part5

-- Role

--

CREATE TABLE Role (

RoleID uniqueidentifier NOT NULL PRIMARY KEY,

RoleName nvarchar(50) NOT NULL,

CreateDate datetime NOT NULL DEFAULT GETDATE()

-- ID GUID,

CREATE TABLE RoleMembers (

MemberID uniqueidentifier NOT NULL,

RoleID uniqueidentifier NOT NULL REFERENCES Role(RoleID)

, ,
ADO.NET SQL , ,

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public abstract class Role

5-86
( ), ( ) Q64

public abstract void AddRole(string RoleName);

public abstract void DeleteRole(string RoleID);

public abstract void EditRole(string RoleID, string RoleName);

public abstract void AddMemberToRole(string MemberID,

string RoleID);

public abstract void RemoveMember(string MemberID);

public abstract void ChangeRole(string MemberID, string RoleID);

public abstract bool IsInRole(string MemberID, string RoleID);

public abstract DataTable GetRoles();

public abstract DataTable GetRoleByID(string RoleID);

public class MyRoleManager : Role

public override void AddRole(string RoleName)

SqlConnection conn = new SqlConnection(

"initial catalog=TestDB; Integrated Security=SSPI");

SqlCommand cmd = new SqlCommand(

"INSERT INTO Role VALUES (NEWID, @roleName, GETDATE())",

conn);

cmd.Parameters.Add(

"@roleName", SqlDbType.NVarChar, 50).Value = RoleName;

conn.Open();

cmd.ExecuteNonQuery();

conn.Close();

conn.Dispose();

cmd.Dispose();

}
5-87
Part5

public override void DeleteRole(string RoleID)

SqlConnection conn = new SqlConnection(

"initial catalog=TestDB; Integrated Security=SSPI");

SqlCommand cmd = new SqlCommand(

"DELETE FROM Role WHERE RoleID = @roleID",

conn);

cmd.Parameters.Add(

"@roleID", SqlDbType.UniqueIdentifier, 16).Value =

new Guid(RoleID);

conn.Open();

cmd.ExecuteNonQuery();

conn.Close();

conn.Dispose();

cmd.Dispose();

public override void EditRole(string RoleID, string RoleName)

SqlConnection conn = new SqlConnection(

"initial catalog=TestDB; Integrated Security=SSPI");

SqlCommand cmd = new SqlCommand(

"UPDATE Role SET RoleName = @roleName WHERE RoleID = @roleID",

conn);

cmd.Parameters.Add(

"@roleID", SqlDbType.UniqueIdentifier, 16).Value =

new Guid(RoleID);

5-88
( ), ( ) Q64

cmd.Parameters.Add(

"@roleName", SqlDbType.NVarChar, 50).Value = RoleName;

conn.Open();

cmd.ExecuteNonQuery();

conn.Close();

conn.Dispose();

cmd.Dispose();

public override void AddMemberToRole(string MemberID,

string RoleID)

SqlConnection conn = new SqlConnection(

"initial catalog=TestDB; Integrated Security=SSPI");

SqlCommand cmd = new SqlCommand(

"INSERT INTO RoleMembers VALUES (@memberID, @roleID)", conn);

cmd.Parameters.Add(

"@memberID", SqlDbType.UniqueIdentifier, 16).Value =

new Guid(MemberID);

cmd.Parameters.Add(

"@roleID", SqlDbType.UniqueIdentifier, 16).Value =

new Guid(RoleID);

conn.Open();

cmd.ExecuteNonQuery();

conn.Close();

5-89
Part5

conn.Dispose();

cmd.Dispose();

public override void RemoveMember(string MemberID)

SqlConnection conn = new SqlConnection(

"initial catalog=TestDB; Integrated Security=SSPI");

SqlCommand cmd = new SqlCommand(

"DELETE FROM RoleMembers WHERE MemberID = @memberID", conn);

cmd.Parameters.Add(

"@memberID", SqlDbType.UniqueIdentifier, 16).Value =

new Guid(MemberID);

conn.Open();

cmd.ExecuteNonQuery();

conn.Close();

conn.Dispose();

cmd.Dispose();

public override bool IsInRole(string MemberID, string RoleID)

SqlConnection conn = new SqlConnection(

"initial catalog=TestDB; Integrated Security=SSPI");

SqlCommand cmd = new SqlCommand(

"SELECT MemberID FROM RoleMembers WHERE RoleID = @roleID",

conn);

bool isInRole = false;

5-90
( ), ( ) Q64

cmd.Parameters.Add(

"@roleID", SqlDbType.UniqueIdentifier, 16).Value =

new Guid(RoleID);

conn.Open();

SqlDataReader reader =

cmd.ExecuteReader(CommandBehavior.CloseConnection);

while (reader.Read())

if (reader.GetValue(0).ToString().ToUpper() ==

MemberID.ToUpper())

isInRole = true;

break;

reader = null;

conn.Dispose();

cmd.Dispose();

return isInRole;

public override void ChangeRole(string MemberID, string RoleID)

SqlConnection conn = new SqlConnection(

"initial catalog=TestDB; Integrated Security=SSPI");

5-91
Part5

SqlCommand cmd = new SqlCommand(

"UPDATE Role SET RoleID = @roleID WHERE MemberID = @memberID",

conn);

cmd.Parameters.Add(

"@memberID", SqlDbType.UniqueIdentifier, 16).Value =

new Guid(MemberID);

cmd.Parameters.Add(

"@roleID", SqlDbType.UniqueIdentifier, 16).Value =

new Guid(RoleID);

conn.Open();

cmd.ExecuteNonQuery();

conn.Close();

conn.Dispose();

cmd.Dispose();

public override DataTable GetRoleByID(string RoleID)

SqlConnection conn = new SqlConnection(

"initial catalog=TestDB; Integrated Security=SSPI");

SqlCommand cmd = new SqlCommand(

"SELECT * FROM Role WHERE RoleID = @roleID", conn);

SqlDataAdapter adapter = new SqlDataAdapter(cmd);

DataTable table = null;

cmd.Parameters.Add(

"@roleID", SqlDbType.UniqueIdentifier, 16).Value =

new Guid(RoleID);

5-92
( ), ( ) Q64

adapter.Fill(table);

adapter = null;

conn.Dispose();

cmd.Dispose();

return table;

public override DataTable GetRoles()

SqlConnection conn = new SqlConnection(

"initial catalog=TestDB; Integrated Security=SSPI");

SqlCommand cmd = new SqlCommand("SELECT * FROM Role", conn);

SqlDataAdapter adapter = new SqlDataAdapter(cmd);

DataTable table = null;

adapter.Fill(table);

adapter = null;

conn.Dispose();

cmd.Dispose();

return table;

, Principal , ,
Q65

5-93
Part5

, , Web.config ,
, , URL
(URL Authorization) , <location> ,
URL

, , /members, Web.config

<configuration>

<location path="~/members">

<system.web>

<authorization>

<deny users="?"/>

<allow roles="members" />

<allow users="Administrator" />

</authorization>

</system.web>

</location>

</configuration>

<deny users="?" />

<allow roles="members" /> members

<allow users="Administrator" /> Administrator

<location> , <location>
<allow> <deny> ,
, ( <forms> loginUrl )

5-94
( ), ( ) Q64

Web.config , ,

if (Request.IsAuthenticated)

if (!HttpContext.Current.User.IsInRole("member"))

Response.Redirect("login.aspx");

else

Response.Redirect("login.aspx");

member , , login.
aspx , <location>

member , ,
Web.config , ,
,

, Exam 70-528: TS: Microsoft .NET Framework 2.0 Web-Based


Client Development

URL

5-95
Q65 Forms Authentication) ?
(Code-Based

V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

ASP.NET , ,
, ,

ASP.NET (Forms Authentication) Cookies


(User Identity) , , (
login.aspx), FormsAuthentication.RedirectFromLoginPage
() , RedirectFromLoginPage() Cookies
, ,
RedirectFromLoginPage() , ,
, , ,
RedirectFromLoginPage()

ASP.NET RedirectFromLoginPage() ,
,

Cookie

FormsIdentity

GenericPrincipal, HttpContext.Current.User

, FormsAuthentication ,
Cookie, Cookie Cookies ,
SetAuthCookie()

5-96
(Code-Based Forms Authentication) ? Q65

FormsAuthentication.SetAuthCookie(user_name, bPersistent,

CookiePath);

user_name String ,

bPersistent Boolean Cookie

CookiePah String Cookie Cookie Path

Cookie

, FormsAuthentication , FormsIdentity,
, , Request.
IsAuthenticated , true FormsIdentity
(ticket) , ,
, ,

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(

version, name, issueDate, expirationDate, isPersistent, userData);

version Integer ,

name String ,

issueDate DateTime , DateTime.Now

expirationDate DateTime ,

isPersistent Boolean Cookie

userData String ,

, FormsIdentity

FormsIdentity identity = new FormsIdentity(ticket);

5-97
Part5

, ASP.NET Cookie ,
Cookies, HttpCookie Cookie , Response.
Cookies.Add() , ,

HttpCookie cookie = new HttpCookie();

cookie.Name = "Cookie's Name";

cookie.Value = "Cookie's Value";

cookie.Expires = DateTime.Now.AddHours(8);

Response.Cookies.Add(cookie);

HttpCookie , , ASP.NET
FormsAuthentication.Encrypt() ,
HttpCookie Cookie

HttpCookie cookie = new HttpCookie(

FormsAuthentication.FormCookName,

FormsAuthentication.Encrypt(ticket));

Response.Cookies.Add(cookie);

, HttpContext.Current.User, HttpContext.
Current.User ASP.NET ,
, HttpContext.Current.User NULL (VB Nothing) ,
Request.IsAuthenticated false, , true

HttpContext.Current.User IPrincipal , WindowsPrincipal


( Windows ) PassportPrincipal ( Passport )
GenericPrincipal ( ) , ,
, GenericPrincipal

5-98
(Code-Based Forms Authentication) ? Q65

GenericPrincipal , IIdentity ,

GenericPrincipal gp = new GenericPrincipal(identity, role_list);

identity IIdentity IIdentity ,


FormsIdentity

role_list String ,

(Role List) ,
GenericPrincipal.IsInRole() ,
(Role-Based)

, FormsIdentity , GenericPrincipal ,

GenericPrincipal gp = new GenericPrincipal(identity, "".Split(', ');

HttpContext.Current.User = gp;

, ,

Response.Redirect(Request.RawUrl);

, ,

private void cmdLogin_Click(object sender, EventArgs e)

5-99
Part5

//

//

string userID = Security.Login(

this.txtUserName.Text, this.txtPassword.Text);

// Cookie

FormsAuthentication.SetAuthCookie(this.txtUserName.Text,

FormsAuthentication.FormCookiePath);

//

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(

1, this.txtUserName.Text, DateTime.Now,

Datetime.Now.AddHours(8), false, userID);

// FormsIdentity , Principal

FormsIdentity identity = new FormsIdentity(ticket);

// Cookie

HttpCookie cookie = new HttpCookie(

FormsAuthentication.FormCookieName,

FormsAnthentication.Encrypt(ticket));

Response.Cookies.Add(cookie);

// Principal, FormsIdentity

GenericPrincipal gp =

new GenericPrincipal(identity, "".Split(', '));

HttpContext.Current.User = gp;

// ,

Response.Redirect(Request.RawUrl);

5-100
(Code-Based Forms Authentication) ? Q65

ASP.NET , ,

, Active Directory (
WindowsIdentity) , ticket ( ),
( ) ,
, ( , )

ASP.NET 2.0 Membership , ,


,

, Exam 70-528: TS: Microsoft .NET Framework 2.0 Web


Application

Q62 Active Directory ?

Q63 ?

5-101
Q66 ASP.NET ?
V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

Web CRM , ,
, ,
, , Email,

,
, SMTP Server ( IIS
SMTP Virtual Server Exchange SMTP Virtual Server) ,
, SMTP Server

ASP , CDO for NT Server ,


, ( )
.NET , .NET Framework SMTP ,
.NET 1.x .NET 2.0

.NET 1.x System.Web.Mail

.NET 2.0 System.Net.Mail

System.Web.Mail CDO for NT Server ,


Web , System.Net.Mail SMTP ,
CDO for NT Server , Windows Forms ,
Web

5-102
ASP.NET ? Q66

, SmtpClient SMTP Server (


, SSL ), MailMessage
, SmtpClient

EnableSsl SSL SMTP Server

Port SMTP Server

Credentials SMTP Server ,

Host SMTP Server DNS IP

Timeout SMTP Server

MailMessage , (
) ( HTML) ,
( , ),

Gmail SmtpClient MailMessage

1 SmtpClient Gmail

SmtpClient client = new SmtpClient();

client.Host = "smtp.gmail.com";

client.Port = 587;

client.EnableSsl = true;

client.Credentials = new NetworkCredential("my_gmail_account ",

"my_gmail_password");

client.Timeout = 150;

Dictionary<string, byte[]> attachments =

new Dictionary<string, byte[]>();

5-103
Part5

if (this.T_File.HasFile)

attachments.Add(this.T_File.FileName, this.T_File.FileBytes);

MailMessage msg = ProcessMailMessage("sender_mail",

this.T_SendToList.Text.Split(', '), this.T_CCList.Text.Split(', '),

this.T_BCCList.Text.Split(', '), false, MailPriority.Low,

"TestMessage", this.T_Body.Text, attachments);

client.Send(msg);

client = null;

public MailMessage ProcessMailMessage(

string Sender, string[] To, string[] CC, string[] Bcc,

bool IsBodyHTML, MailPriority Priority, string Subject,

string Body, Dictionary<string, byte[]> Attachments)

MailMessage msg = new MailMessage();

msg.From = new MailAddress(Sender);

msg.Priority = Priority;

msg.Subject = Subject;

msg.Body = Body;

msg.IsBodyHtml = IsBodyHTML;

if (!string.IsNullOrEmpty(To[0]))

if (To.Length > 0)

for (int i = 0; i < To.Length; i++)

msg.To.Add(new MailAddress(To[i]));

5-104
ASP.NET ? Q66

if (!string.IsNullOrEmpty(CC[0]))

if (CC.Length > 0)

for (int i = 0; i < CC.Length; i++)

msg.CC.Add(new MailAddress(CC[i]));

if (!string.IsNullOrEmpty(Bcc[0]))

if (Bcc.Length > 0)

for (int i = 0; i < Bcc.Length; i++)

msg.Bcc.Add(new MailAddress(Bcc[i]));

// process attachments

if (Attachments != null && Attachments.Count > 0)

string[] keys = new string[Attachments.Count];

Attachments.Keys.CopyTo(keys, 0);

for (int i = 0; i < keys.Length; i++)

MemoryStream ms = new MemoryStream(Attachments[keys[i]]);

msg.Attachments.Add(new Attachment(ms, keys[i]));

return msg;

Email Address, MailMessage ,


SmtpClient

5-105
Part5

System.Net.Mail SmtpClient ,
, (Send Queue) , (Spam) ,
Mail Server (Mail Relay) ,
SMTP Server , ,

, IIS SMTP Server, SMTP Virtual Server IP


, SMTP Server
, , , SmtpClient ,
SMTP Server , SmtpClient , SMTP Server

, Web ,
, ASP.NET ,
Windows , Service Application ( ),
, Windows
, Windows Service

Service , Windows Service , OnStart


, , ,
OnStop , Windows ,

protected override void OnStart(string[] args)

this._Timer = new Timer();

this._Timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);

5-106
ASP.NET ? Q66

this._Timer.Interval = 6000000;

this._Timer.Start();

private void Timer_Elapsed(object sender, ElapsedEventArgs e)

// process information.

// create mail.

MailMessage msg = ProcessMailMessage(sender, SendToList, CCList,

BccList, IsBodyHTML, MailPrioritySetup, Subject, Body, null);

// send mail

this.SendMail(msg);

protected override void OnStop()

this._Timer.Stop();

this._Timer.Dispose();

, SMTP , Windows Service ,

5-107
Part5

, Exam 70-536: TS: Microsoft .NET Framework 2.0 Application


Development Foundation

.NET Framework

, (System.ServiceProcess )

ServiceBase

.NET Framework

.NET Framework SMTP Server

MailMessage

MailAddress MailAddressCollection

SmtpClient

Attachment

5-108
Q67 ASP.NET

V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

ASP.NET , ASP.NET (
), , ASP.
NET ,

ASP.NET Network Service (IIS 5.0 ASPNET) ,


, ASP.NET ,
, ASP.NET , ,
ASP.NET ,

, (
) , , (
), ASP.NET
, ASP.NET (Impersonate Account)
ASP.NET , , ASP.
NET

, ,
(Impersonation Temporary) , , ,
ASP.NET ,

WindowsIdentity Impersonate() ,
Impersonate() , Windows
ImpersonationContext , , Undo()
,

5-109
Part5

WindowsIdentity , WindowsIdentity
IntPtr,
, , LogonUser() API

LogonUser() API .NET Framework ,

[DllImport("advapi32.dll", SetLastError = true)]

public static extern bool LogonUser(

String lpszUsername, //

String lpszDomain, //

String lpszPassword, //

int dwLogonType, //

int dwLogonProvider, //

ref IntPtr phToken); //

LogonUser() API ,
, (LOGON32_LOGON_
INTERACTIVE) (LOGON32_PROVIDER_DEFAULT)

, API

[DllImport("advapi32.dll", SetLastError = true)]

public static extern bool LogonUser(String lpszUsername,

String lpszDomain, String lpszPassword, int dwLogonType,

int dwLogonProvider, ref IntPtr phToken);

5-110
ASP.NET Q67

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]

public extern static bool CloseHandle(IntPtr handle);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]

public extern static bool DuplicateToken(

IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL,

ref IntPtr DuplicateTokenHandle);

, ( )
, LogonUser() API

string userName, domainName, password;

// Domain, UserName Password

domainName = this.T_DomainName.Text;

userName = this.T_UserName.Text;

password = this.T_Password.Text;

//

const int LOGON32_PROVIDER_DEFAULT = 0;

const int LOGON32_LOGON_INTERACTIVE = 2;

// handle (Win32 API )

tokenHandle = IntPtr.Zero;

// LogonUser() API

bool returnValue = LogonUser(userName, domainName, password,

LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,

ref tokenHandle);

// true, false

if (false == returnValue)

5-111
Part5

// ,

int ret = Marshal.GetLastWin32Error();

throw new System.ComponentModel.Win32Exception(ret);

(Token ID) ,

// , WindowsIdentity

WindowsIdentity newId = new WindowsIdentity(tokenHandle);

//

WindowsImpersonationContext impersonatedUser = newId.Impersonate();

, WindowsImpersonationContext , Session ,
, , , (
)

// WindowsImpersonationContext Session

Session["ImpersonateUser"] = impersonatedUser;

, WindowsImpersonationContext Session ,
Undo() ,

// WindowsImpersonationContext

WindowsImpersonationContext impersonatedUser =

Session["ImpersonateUser"] as WindowsImpersonationContext;

//

impersonatedUser.Undo();

,
,

5-112
ASP.NET Q67

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Runtime.InteropServices;

using System.Security;

using System.Security.Principal;

using System.Security.Permissions;

public partial class Part5_ImpersonateUser : System.Web.UI.Page

[DllImport("advapi32.dll", SetLastError = true)]

public static extern bool LogonUser(

String lpszUsername, String lpszDomain, String lpszPassword,

int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]

public extern static bool CloseHandle(IntPtr handle);

[DllImport("advapi32.dll", CharSet = CharSet.Auto,

SetLastError = true)]

public extern static bool DuplicateToken(

IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL,

ref IntPtr DuplicateTokenHandle);

5-113
Part5

protected void Page_Load(object sender, EventArgs e)

if (!Page.IsPostBack)

this.labelUser.Text = WindowsIdentity.GetCurrent().Name;

protected void cmdImpersonate_Click(object sender, EventArgs e)

IntPtr tokenHandle = new IntPtr(0);

IntPtr dupeTokenHandle = new IntPtr(0);

try

string userName, domainName, password;

domainName = this.T_DomainName.Text;

userName = this.T_UserName.Text;

password = this.T_Password.Text;

const int LOGON32_PROVIDER_DEFAULT = 0;

//This parameter causes LogonUser to create a primary token.

const int LOGON32_LOGON_INTERACTIVE = 2;

tokenHandle = IntPtr.Zero;

// Call LogonUser to obtain a handle to an access token.

bool returnValue = LogonUser(userName, domainName, password,

LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,

ref tokenHandle);

Response.Write("LogonUser Called" + "<br>");

5-114
ASP.NET Q67

if (false == returnValue)

int ret = Marshal.GetLastWin32Error();

Response.Write(string.Format(

"LogonUser failed with error code : {0}", ret));

throw new System.ComponentModel.Win32Exception(ret);

Response.Write("Did LogonUser Succeed? " +

(returnValue ? "Yes" : "No") + "<br>");

Response.Write("Value of Windows NT token: " +

tokenHandle + "<br>");

// Check the identity.

Response.Write("Before impersonation: " +

WindowsIdentity.GetCurrent().Name + "<br>");

// Use the token handle returned by LogonUser.

WindowsIdentity newId = new WindowsIdentity(tokenHandle);

WindowsImpersonationContext impersonatedUser =

newId.Impersonate();

Session["ImpersonateUser"] = impersonatedUser;

// Check the identity.

this.labelUser.Text = WindowsIdentity.GetCurrent().Name;

// Free the tokens.

if (tokenHandle != IntPtr.Zero)

CloseHandle(tokenHandle);

5-115
Part5

catch (Exception ex)

Console.WriteLine("Exception occurred. " + ex.Message);

protected void cmdUndo_Click(object sender, EventArgs e)

WindowsImpersonationContext impersonatedUser =

Session["ImpersonateUser"] as WindowsImpersonationContext;

impersonatedUser.Undo();

this.labelUser.Text = WindowsIdentity.GetCurrent().Name;

.NET Framework 2.0 SDK WindowsIdentity.Im-


personate() ,

http://msdn2.microsoft.com/zh-tw/library/chf6fbt4(VS.80).aspx

Q54 ASP.NET ( ) ?

5-116
Q68 (Authentication Code)

V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

ASP.NET , ,
,
( ),

,
,
, ,
, ,
(phpBB, DotNetNuke vBulletin ) ,
,

,
, Session Cookie

( ), (
), ,

5-117
Part5

, , 4-8 ,
,

, ,

, HTTP Handler , Q25

, HTTP Handler, HTTP Handler ,


1

1 HTTP Handler

using System;

using System.Collections.Generic;

using System.IO;

using System.Drawing;

using System.Drawing.Imaging;

using System.Web;

public class DrawAuthCode : IHttpHandler {

public void ProcessRequest (HttpContext context)

// Cookie ( Session)

HttpCookie cookie = context.Request.Cookies["authCode"];

string authCode = cookie.Value;

5-118
(Authentication Code) Q68

// ,

MemoryStream ms = new MemoryStream();

Bitmap bmp = new Bitmap(100, 30);

//

Graphics g = Graphics.FromImage(bmp);

List<Font> fontList = new List<Font>();

//

Font font1 = new Font("Times New Roman", 14, FontStyle.Italic);

Font font2 = new Font("Verdana", 14, FontStyle.Bold);

Font font3 = new Font("Bookman Old Style", 14,

FontStyle.Regular);

Font font4 = new Font("Tahoma", 14, FontStyle.Underline);

// ( 4 )

while (fontList.Count < 4)

Random random = new Random();

int fontIndex = random.Next(0, 5);

switch (fontIndex)

case 1:

if (!fontList.Contains(font1))

fontList.Add(font1);

break;

case 2:

if (!fontList.Contains(font2))

fontList.Add(font2);

break;

5-119
Part5

case 3:

if (!fontList.Contains(font3))

fontList.Add(font3);

break;

case 4:

if (!fontList.Contains(font4))

fontList.Add(font4);

break;

default:

break;

//

g.FillRectangle(Brushes.White,

new Rectangle(new Point(0, 0), bmp.Size));

g.DrawRectangle(Pens.Black, new Rectangle(new Point(0, 0),

new Size(bmp.Size.Width - 1, bmp.Size.Height - 1)));

// ( )

SizeF sizeStr = g.MeasureString("1", new Font("Vendana", 14));

//

float drawY =

(Convert.ToSingle(bmp.Size.Height) - sizeStr.Height) / 2;

float drawX =

(Convert.ToSingle(bmp.Size.Width) - sizeStr.Width * 4) / 2;

g.DrawString(authCode[0].ToString(), fontList[0],

System.Drawing.Brushes.Black, new PointF(drawX, drawY));

5-120
(Authentication Code) Q68

g.DrawString(authCode[1].ToString(), fontList[1],

System.Drawing.Brushes.Black, new PointF(drawX * 2, drawY));

g.DrawString(authCode[2].ToString(), fontList[2],

System.Drawing.Brushes.Black, new PointF(drawX * 3, drawY));

g.DrawString(authCode[3].ToString(), fontList[3],

System.Drawing.Brushes.Black, new PointF(drawX * 4, drawY));

// MemoryStream

bmp.Save(ms, ImageFormat.Gif);

ms.Flush();

g.Dispose();

context.Response.ContentType = "image/gif";

context.Response.BinaryWrite(ms.ToArray());

bmp.Dispose();

ms.Close();

, , , Cookie , HTTP Handler


, , Session , 2

2 cookie

protected void Page_Load(object sender, EventArgs e)

if (!Page.IsPostBack)

5-121
Part5

HttpCookie cookie = new HttpCookie("AuthCode");

cookie.Expires = DateTime.Now.AddMinutes(5);

// ,

//

cookie.Value = (new Random()).Next(1000, 10000).ToString();

// Cookie

Response.Cookies.Add(cookie);

Cookie , , 3

protected void cmdAuth_Click(object sender, EventArgs e)

// cookie

HttpCookie cookie = Request.Cookies["AuthCode"];

//

if (cookie.Value == this.T_AuthCode.Text)

Response.Write(" ");

else

Response.Write(" ");

// ,

cookie = new HttpCookie("AuthCode");

cookie.Expires = DateTime.Now.AddMinutes(5);

cookie.Value = (new Random()).Next(1000, 10000).ToString();

Response.Cookies.Add(cookie);

5-122
(Authentication Code) Q68

CAPTCHA
SPAM Collector ,
, ,
, Luis von Ahn, Manuel Blum, Nicholas J. Hopper John Langford
CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart)
, , ,
, ( OCR )

CAPTCHA ,

http://www.cs.sfu.ca/~mori/research/gimpy/ez/

, ,
CAPTCHA ( ),
CAPTCHA ,

CAPTCHA reCAPTCHA , reCAPTCHA CAPTCHA


, , reCAPTCHA
, , reCAPTCHA Project

CAPTCHA

http://en.wikipedia.org/wiki/Captcha

reCAPTCHAProject

http://recaptcha.net/

5-123
Q69 URL URL

V ASP.NET 1.0 V ASP.NET 1.1 V ASP.NET 2.0 V ASP.NET 3.5

ASP.NET , ,
, , URL
,

Web ,
, , Query String ,
, Query String

ProductInfo.aspx?root=0&lv1=4&lv2=5&lv3=18&sp=134...

, , ,
, , SQL
Injection , , (
)

URL ,
, URL ,
ASP.NET , ID URL

http://forums.asp.net/t/1187232.aspx

5-124
URL URL Q69

Bookpool ( ) URL
ISBN

Developing Drivers with the Microsoft Windows Driver Foundation

http://www.bookpool.com/sm/0735623740

Inside Microsoft Windows Communication Foundation

http://www.bookpool.com/sm/0735623066

Blog, Blog URL,


Microsoft Learning Trika, Blog URL

Trika's Blog:

http://blogs.msdn.com/trika

2007/6/27 - People at Microsoft Learning

http://blogs.msdn.com/trika/archive/2007/06/27/people-at-microsoft-
learning.aspx

URL, Web ,
URL , URL , URL
(URL Rewriting)

URL Rewriting URL , HTTP Request


URL , ,
, URL
,

URL Rewriting URL ,


,

http://www.mybooks.com.tw/ProductInfo/Inside WCF

5-125
Part5

URL Rewriting, URL

http://www.mybooks.com.tw/ProductInfo/ProductInfo.aspx?keyword=Inside WCF

URL

http://www.mybooks.com.tw/books/Microsoft Press/Windows/Introducing Win-


dows Server 2008

URL Rewriting,

http://www.mybooks.com.tw/ProductInfo/ProductInfo.aspx?
type=books&vendor=Microsoft Press&category=Windows&caption=Introducing
Windows Server 2008

URL , URL Rewriting


, ,

URL Rewriting ASP.NET HTTP Module ( HTTP


Handler, HTTP Module ,
HTTP Module HTTP Handler IIS, ,
URL Rewriting, HTTP Handler
), Request , URL
, ,

URL Rewriting , URL (Rewriting Engine) URL


(Rewriting Rules) , , HTTP Module
, Rewriting , (Parsing)
, ,
, , ,

5-126
URL URL Q69

URL Rewriting ,
URL Rewriting , URL Rewriting
,

URL Rewriting , ,
, , ,

// ( Products.aspx )

http://localhost/Products.aspx

// (Ikura)

http://localhost/Products.aspx/ Ikura

// ( Customers.aspx )

http://localhost/Customers.aspx

// (Chop-suey Chinese)

http://localhost/Customers.aspx/Chop-suey Chinese

, App_Code (.cs) , IHttpModule,


HTTP Module,

ModuleName

Init() , HttpApplication

Dispose()

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

5-127
Part5

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

public class Rewriter : IHttpModule

public Rewriter()

// empty constructor

public String ModuleName

get { return "RewriterModule"; }

public void Init(HttpApplication application)

public void Dispose()

5-128
URL URL Q69

, Init() , HTTP Module HttpApplication


BeginRequest

public void Init(HttpApplication application)

application.BeginRequest +=

new EventHandler(this.Rewriter_BeginRequest);

, URL BeginRequest

private void Rewriter_BeginRequest(Object source, EventArgs e)

HttpApplication application = (HttpApplication)source;

HttpContext context = application.Context;

// URL,

if (context.Request.Url.ToString().IndexOf("Products") >= 0 ||

context.Request.Url.ToString().IndexOf("Products/default.aspx")

>= 0)

string[] productArgs =

context.Request.Url.ToString().Split('/');

// URL,

// HttpContext.RewritePath() URL

if (productArgs.Length > 1)

context.RewritePath("default.aspx?t=Products&name=" +

productArgs[productArgs.Length - 1]);

else

context.RewritePath("default.aspx?t=Products");

5-129
Part5

else if (

context.Request.Url.ToString().IndexOf("Customers") >= 0 ||

context.Request.Url.ToString().IndexOf("Customers/default.aspx")

>= 0)

string[] customerArgs =

context.Request.Url.ToString().Split('/');

// URL,

// HttpContext.RewritePath() URL

if (customerArgs.Length > 1)

context.RewritePath("default.aspx?t=Customers&name=" +

customerArgs[customerArgs.Length - 1]);

else

context.RewritePath("default.aspx?t=Customers");

HttpContext.RewritePath() .NET 1.x ,


Cookieless , URL

HttpContext.RewritePath() URL, default.aspx ,


, default.aspx

protected void Page_Load(object sender, EventArgs e)

if (Request.QueryString["t"] == null)

return;

SqlDataSource ds = new SqlDataSource();

ds.ConnectionString = ConfigurationManager.ConnectionStrings[

"northwindConnectionString"].ConnectionString;

5-130
URL URL Q69

if (Request.QueryString["t"] == "Products")

if (!string.IsNullOrEmpty(Request.QueryString["name"]))

ds.SelectCommand =

"SELECT * FROM Products WHERE ProductName='" +

Request.QueryString["name"] + "'";

else

ds.SelectCommand = "SELECT * FROM Products";

else if (Request.QueryString["t"] == "Customers")

if (!string.IsNullOrEmpty(Request.QueryString["name"]))

ds.SelectCommand =

"SELECT * FROM Customers WHERE CompanyName = '" +

Request.QueryString["name"] + "'";

else

ds.SelectCommand = "SELECT * FROM Customers";

this.GridView1.DataSource =

ds.Select(new DataSourceSelectArguments());

this.GridView1.DataBind();

ds.Dispose();

5-131
Part5

, HTTP Module , Web.config

<Configurations>

<system.web>

<httpModules> <!-- HTTP Module -->

<add name="Rewriter" type="Rewriter"/>

</httpModules>

</system.web>

</Configurations>

, URL Rewriting

URL Rewriting , , , URL


Rewriting Google Windows Live

URL Rewriting in ASP.NET

http://msdn2.microsoft.com/en-us/library/ms972974.aspx

15 Seconds : Rewrite.NET

http://www.15seconds.com/issue/030522.htm

URL Rewriting with ASP.NET

http://www.codeproject.com/aspnet/URLRewriter.asp

URLRewriting.NET:

http://www.urlrewriting.net/en/Default.aspx

5-132

You might also like