T 470 F 05
T 470 F 05
FTP , ,
Web Web
,
FtpWebRequest FTP ,
FTP Server ( WebRequestMethods.Ftp
, )
5-2
ASP.NET FTP Q53
FTP
AppendFile FTP APPE ,
FTP
UploadFileWithUniqueName FTP
FTP STOU
5-3
Part5
as FtpWebRequest;
// FTP
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.KeepAlive = true;
this.T_Password.Text);
request.UsePassive = false;
request.ReadWriteTimeout = 2000000;
request.Timeout = 1200000;
//
accountInfo.Add("UserName", this.T_UserName.Text);
accountInfo.Add("Password", this.T_Password.Text);
ViewState["FtpAccount"] = accountInfo;
//
System.Text.Encoding.Default);
do
//
if (item.IndexOf('.') >= 0)
5-4
ASP.NET FTP Q53
while (!sr.EndOfStream);
response.Close();
FTP ,
this.T_FtpUrl.Text + "/" +
this.cboFileList.SelectedValue) as FtpWebRequest;
5-5
Part5
// ViewState ,
// FTP ,
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.KeepAlive = true;
accountInfo["UserName"], accountInfo["Password"]);
request.UsePassive = false;
request.ReadWriteTimeout = 2000000;
request.Timeout = 1200000;
//
int readCount = 0;
do
// , MemoryStream
ms.Write(data, 0, readCount);
5-6
ASP.NET FTP Q53
ms.Flush();
ms.Position = 0;
reader.Close();
response.Close();
//
Response.AddHeader("Content-Disposition", string.Format(
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 ,
// ,
FileMode.Open, FileAccess.Read);
fs.Read(data, 0, (int)fs.Length);
fs.Close();
5-9
Part5
Response.BinaryWriter(data);
//
( ) ,
, ,
, (Transaction)
using System.IO;
using System.Data;
using System.Data.SqlClient;
...
try
// File Server
// //MyServer/FileStore ,
FileAccess.Write);
fs.Write(FileContent, 0, (int)FileContent.Length);
fs.Flush();
fs.Close();
5-10
ASP.NET ( ) Q54
//
conn.Open();
cmd.Transaction = tran;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
catch (SqlException e)
// ,
tran.Rollback(); //
fs.Delete(); //
fs.Close();
// 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 ( ) ,
5-12
ASP.NET ? Q55
( ) ,
1 HttpWebRequest
"http://tw.stock.yahoo.com/q/q?s=2330") as HttpWebRequest;
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
request.ContentLength = strPostData; // ,
//
request.ContentType = "application/x-www-form-urlencoded";
sw.Flush();
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) , ,
,
HTTP HttpWebRequest
, , API ,
, MIoD , HTTP
, socket C
5-16
ASP.NET Q56
.NET , HTTP
, HttpWebRequest HttpWebResponse
, Winsock , TCP
, , ,
IMS ( ) HTTP ,
HttpWebRequest ,
2005 ASP.NET ,
( ),
, , ,
, , ,
, ,
1 ( )
//
5-17
Part5
// HTTP URL
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
HttpWebRequest request =
(HttpWebRequest)HttpWebRequest.Create(this.BuildUrl());
request.UserAgent = "TCC_SMS_Manager";
request.Method = "GET";
response = (HttpWebResponse)request.GetResponse();
//
stream = response.GetResponseStream();
Result = reader.ReadToEnd();
//
5-19
Part5
reader.Close();
response.Close();
response = null;
request = null;
//
// msgid=value1\nstatusstr=value2
// parse string.
if (Result != null)
if (Int32.Parse(MsgID) > 0)
// , ID
return MsgID;
else
switch (MsgID)
//
else
5-20
ASP.NET Q56
//
" .");
// default RATE_PLAN is A.
string template =
"username={0}&password={1}&rateplan=A&srcaddr={2}&dstaddr={3}&smbody={4}";
string strResult =
if (_encoding != null)
if (_wapurl != null)
if (_dlvtime != null)
if (_vldtime != null)
if (_responseUrl != null)
// HTTP
strResult);
5-21
Part5
2 ( )
// Winsock
// HTTP , HTTP
// ,
// TcpClient TcpClient ,
//
}
5-22
ASP.NET Q56
//
Constants.MAX_PASSWD_LEN + Constants.MAX_MSISDN_LEN +
Constants.MAX_MESSAGEID_LEN + Constants.MAX_MSG_LEN +
Constants.ORDERTIME_LEN;
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
if (i < this.pchID.Length)
buffer[iBitLocation] = (byte)this.pchID[i];
else
buffer[iBitLocation] = 0x0;
iBitLocation++;
// pchPasswd
if (i < this.pchPasswd.Length)
buffer[iBitLocation] = (byte)this.pchPasswd[i];
else
buffer[iBitLocation] = 0x0;
iBitLocation++;
// pchMsisdn
if (i < this.pchMsisdn.Length)
buffer[iBitLocation] = (byte)this.pchMsisdn[i];
else
buffer[iBitLocation] = 0x0;
iBitLocation++;
5-24
ASP.NET Q56
// pchMessageID
if (i < this.pchMessageID.Length)
buffer[iBitLocation] = (byte)this.pchMessageID[i];
else
buffer[iBitLocation] = 0x0;
iBitLocation++;
if (i < this.pchMessage.Length)
buffer[iBitLocation] = (byte)this.pchMessage[i];
else
buffer[iBitLocation] = 0x0;
iBitLocation++;
// pchSendTime
if (i < this.pchSendTime.Length)
buffer[iBitLocation] = (byte)this.pchSendTime[i];
else
buffer[iBitLocation] = 0x0;
iBitLocation++;
return buffer;
}
5-25
Part5
// ,
this._sendPhoneNumber = SendPhoneNumber;
this._client.SendTimeout = 100;
this._client.ReceiveTimeout = 100;
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.
IPEndPoint ep = null;
ipaddr = IPAddress.Parse(RemoteAddress);
return ep;
//
5-27
Part5
return msg;
//
return msg;
try
this._client.Open();
5-28
ASP.NET Q56
if (se.ErrorCode == 10061)
try
this._client.Open(this._backupServer);
socketEx.ErrorCode));
ex.StackTrace);
else
string.Format(
se.ErrorCode));
}
5-29
Part5
this._client.Close();
// send command.
this._client.SendStructure(sendMsg);
//
//
if (buf.Length != 0)
msg.code = data[0];
msg.coding = data[1];
msg.length = byte.Parse(data[2].ToString());
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));
Message += data[i].ToString();
else
return msg;
// helper.
result[i] = Source[i];
return result;
5-31
Part5
// code : 0x20,
if (Data[i] == 0x00)
Data[i] = 0x20;
// public functions.
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:
case 2:
case 3:
case 4:
//
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.
switch (recvMsg.code)
case 0:
break;
case 1:
case 2:
5-34
ASP.NET Q56
case 3:
case 4:
case 5:
case 6:
case 7:
default:
BufferContent));
//
//
sendMsg.type = Constants.SERV_QUERY;
5-35
Part5
//
this.Send(sendMsg);
//
recvMsg = this.Recv();
switch (recvMsg.code)
case 0:
return true;
case 1:
// message processing.
return false;
case 2:
case 3:
case 4:
case 5:
case 6:
5-36
ASP.NET Q56
case 7:
default:
recvMsg.buffer));
//
//
sendMsg.type = Constants.SERV_GET;
//
this._client.Send(sendMsg.ToBytes());
//
recvMsg = this.Recv();
// build buffer.
5-37
Part5
switch (recvMsg.code)
case 0:
// get message.
return recvMsg;
case 1:
//
recvMsg = this.InitRecvMsg();
recvMsg.code = 1;
return recvMsg;
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
5-38
ASP.NET Q56
default:
BufferContent));
// TcpClient
this._serverAddr = ServerAddress;
this._serverPort = Port;
~TcpClient()
base.Dispose(true);
GC.Collect();
}
5-39
Part5
base.Connect(this._serverAddr, this._serverPort);
base.Connect(ServerAddr, this._serverPort);
base.Connect(ServerAddr, Port);
base.Close();
5-40
ASP.NET Q56
if (!base.Active)
this._ns = base.GetStream();
// write data.
this._ns.Write(rawData, 0, rawData.Length);
if (!base.Active)
this._ns = base.GetStream();
// write data.
this._ns.Write(rawData, 0, rawData.Length);
5-41
Part5
if (!base.Active)
this._ns = base.GetStream();
// write data.
this._ns.Write(rawData, 0, rawData.Length);
if (!base.Active)
//
//
//
this._ns = base.GetStream();
// write data.
this._ns.Write(rawData, 0, rawData.Length);
5-42
ASP.NET Q56
return this.ParseBytesToString(buffer);
this._ns = base.GetStream();
// receive data.
while (this._ns.DataAvailable)
// read to buffer.
this._ns.Read(buffer, 0, base.ReceiveBufferSize);
ms.Write(buffer, 0, buffer.Length);
ms.Flush();
ms.Position = 0;
5-43
Part5
ms.Read(result, 0, result.Length);
ms.Close();
return result;
//
//
//
return Result;
// helper.
5-44
ASP.NET Q56
// code : 0x20,
if (Data[i] == 0x00)
Data[i] = 0x20;
// convert to string.
return
ASCIIEncoding.ASCII.GetString(Data, 0, Data.Length).Trim();
//
// URL
"http://{0}/{1}/servlet/com.fet.miod.SendSMS?{2}";
5-45
Part5
this._serverAddr = ServerAddr;
this._port = Port;
this._username = UserName;
this._password = Password;
this._MiodServletContext = MiodServletContext;
// NOTE: Server.UrlEncode()
// additional parameters.
if (!Dr_Flag.Equals(null))
if (!DeliverDate.Equals(null))
QueryString += string.Format("&deliver_date={0}",
DeliverDate.ToString("yyyyMMddhhmmss"));
if (Target != null)
5-46
ASP.NET Q56
Url = string.Format(
this._port),
this._MiodServletContext, QueryString);
this._request = (HttpWebRequest)HttpWebRequest.Create(
// send message.
this._response = (HttpWebResponse)this._request.GetResponse();
if (this._response.StatusCode != HttpStatusCode.OK)
this._response.Close();
this._request = null;
this._response = null;
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
5-49
Part5
Web Service ,
5-50
Web Service Q57
net.webservicex.www.WeatherForecast wf =
new net.webservicex.www.WeatherForecast();
// (Seattle)
//
...
using System.Data;
using System.Data.SqlClient;
using System.Xml;
...
[WebMethod]
SqlDataReader reader =
cmd.ExecuteReader(CommandBehavior.CloseConnection);
doc.LoadXml("<ProductInfo></ProductInfo>");
// XML
while (reader.Read())
"Product", null);
"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)
// send request.
SOAPClient.invoke(
"GetProductInfo", //
pl, //
true, //
GetProductWebServiceResponse); //
function GetProductWebServiceResponse(e)
( )
<ProductInfo>
...
</ProductInfo>
5-53
Part5
<Services>
</Services>
</asp:ScriptManager>
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 ,
"http://www.webservicex.net/WeatherForecast.asmx/
GetWeatherByPlaceName")
as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byte1.Length;
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
Session Web ,
Session, , Web Service
( ), ,
Web Service ViewState, Session
[WebMethod(EnableSession=true)]
....
Session , Web , ,
Application , , Application
5-56
Web Service Session Q58
, ,
SOAP Header , ,
Token ( ) , SOAP Header ,
using System.Web.Service;
using System.Web.Service.Protocols;
string UserName;
string Password;
....
5-57
Part5
...
, , [SoapHeader], ,
SOAP Header , SOAP Header
[WebMethod]
// SOAP Header
if (!AuthenticateUser(this._myInfo.UserName, this._myInfo.Password))
return 0;
...
, , SOAP Header ,
, Web Service SOAP Header ( SOAP
Header )
// SOAP Header
5-58
Web Service Session Q58
// SOAP Header
userInfo.UserName = this.T_UserName.Text;
userInfo.Password = this.T_Password.Text;
// SOAP Header
ws.MyUserInfo = userInfo;
// Web Service
"'); </script>");
ws = null;
// 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
5-59
Part5
// SOAP Header
// ,
return false;
else
return true;
[WebMethod]
if (!AuthenticateUser(this._myInfo.UserName,
this._myInfo.Password))
return -1;
0.5 as int)
5-60
Web Service Session Q58
o.EmployeeID = e.EmployeeID
cmd.Parameters.Add("@employeeID", EmployeeID);
cmd.CommandType = CommandType.Text;
conn.Open();
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
// SOAP Header
// SOAP Header
userInfo.UserName = this.T_UserName.Text;
userInfo.Password = this.T_Password.Text;
// SOAP Header
ws.MyUserInfo = userInfo;
// Web Service
"'); </script>");
ws = null;
5-62
Web Service Session Q58
Web Service
Session
SOAP Headers
SOAP Header
SoapHeader Web
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
Firefox 14.56%
Safari 4.68%
Opera 0.88%
Netscape 0.71%
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>");
bc.ActiveXControls + "<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
<identification>
<userAgent match="^Mozilla[^(]*\
([C|c]ompatible;\s*MSIE
(?'version'(?'major'\d+)(?'minor'\.\d+)
(?'letters'\w*))(?'extra'[^)]*)" />
<userAgent nonMatch="Opera|Go\.Web|
</identification>
</browser>
, , Browser
, User-Agent
<identification>
</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 ,
<DeviceSpecific>
</DeviceSpecific>
</mobile:Image>
Request.Browsers HttpBrowserCapabilities ,
, , DeviceFilter
DeviceSpecific
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
AD , ADSI (Active Directory Service Interface) ,
COM , AD , Active Direc-
tory ( OLE DB Provider for Active Directory)
5-69
Part5
System.DirectoryService.dll , System.
DirectoryService
, (
)
, LDAP
LDAP
LDAP://[distinguished 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
Management OU Steven ,
AD ,
Active Directory
Active Directory ,
5-71
Q61 Active Directory
Active Directory ,
, , Web
, Active Directory
, ASP.NET Active Directory
Active Directory ,
(Domain) AD ,
, , Forest
(Forest) , ,
(Trust Relationship) , AD
AD (Object) , AD
AD Schema
5-72
Active Directory Q61
AD Schema , Schema,
Schema
DirectoryEntry
LDAP_DN LDAP ,
UserName LDAP
Password LDAP
5-73
Part5
try
// DirectoryEntry,
// strUserName strPassword
// AD Schema
entry.Properties.PropertyNames.CopyTo(keys, 0);
Response.Write(
entry.Properties[keys[i]].Value.ToString() + "<br>");
Response.Write(dsex.Message);
entry = null;
AD Schema , DirectoryEntry.InvokeSet()
AD Schema , DirectoryEntry.CommitChanges(),
5-74
Active Directory Q61
try
this.T_Password.Text);
// Schema
entry.InvokeSet(this.cboSchema.SelectedValue, this.T_Value.Text);
// ,
entry.CommitChanges();
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
try
// DirectoryEntry
//
if (results.Count == 0)
else
Response.Write(result.Path + "<br>");
Response.Write(dsex.Message);
searcher = null;
, Active Directory , AD
( , LDAP://RootDSE ,
, AD , RootDSE )
, DirectorySearcher ,
5-76
Active Directory Q61
// AD
// (objectClass=Computer)
searcher.Filter = "(objectClass=User)";
//
, AD Schema ( , AD ),
AD Schema , , AD Schema , Ac-
tive Directory Domain Service , Schema,
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
AD , DirectoryEntry AD
( ID) , AD
, AD , , DirectoryEntry
, (
Q61 DirectoryEntry )
, , DirectoryEntry
, ( uid SID ),
DirectorySearcher , , ,
, , SearchResult.GetDirectoryEntry()
AD , objectSid userPrincipalName
AD
5-78
Active Directory Q62
new DirectoryEntry("LDAP://dc=jcistudio.idv.tw",
userName, password));
//
searcher.Filter =
//
if (result == null)
else
// SID
object sid =
result.GetDirectoryEntry().Properties["objectSid"].Value;
, DirectoryEntry DirectorySearcher
, , ,
DirectorySearcher ,
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) ,
,
, ,
RIPEMD160 160
( )
SHA1 160
SHA256 256
SHA384 384
SHA512 512
, , ,
,
, , (
), ComputeHash() ,
,
using System.Text;
using System.Security;
using System.Security.Cryptography;
...
//
// ABCDEF
5-81
Part5
// ,
//
algorithm = null;
// ABCDE
// ?9?????U?/{????NR}??V???{?#?
, ,
, , , ,
, ,
, , SHA1 ,
SHA256 , ,
, ,
,
, ,
, 1
using System.Text;
using System.Security;
using System.Security.Cryptography;
...
5-82
Q63
// , PasswordHashedString
string PasswordHashedString)
algorithm.ComputeHash(Encoding.ASCII.GetBytes(Password)));
algorithm = null;
return result;
, ,
, ,
System.Security.Cryptography
(System.Security.Cryptography )
(HMAC)
MD5
RIPEMD160
SHA1
SHA256
SHA384
SHA512
5-83
Q64 ( )
( ),
, ,
,
, ,
,
, , ,
,
, 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)
//
string RoleID);
, ,
, , AddMemberToRole()
RemoveMember()
5-85
Part5
-- Role
--
-- ID GUID,
, ,
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;
5-86
( ), ( ) Q64
string RoleID);
conn);
cmd.Parameters.Add(
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
5-87
Part5
conn);
cmd.Parameters.Add(
new Guid(RoleID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
conn);
cmd.Parameters.Add(
new Guid(RoleID);
5-88
( ), ( ) Q64
cmd.Parameters.Add(
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
string RoleID)
cmd.Parameters.Add(
new Guid(MemberID);
cmd.Parameters.Add(
new Guid(RoleID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
5-89
Part5
conn.Dispose();
cmd.Dispose();
cmd.Parameters.Add(
new Guid(MemberID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
conn);
5-90
( ), ( ) Q64
cmd.Parameters.Add(
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;
5-91
Part5
conn);
cmd.Parameters.Add(
new Guid(MemberID);
cmd.Parameters.Add(
new Guid(RoleID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
cmd.Parameters.Add(
new Guid(RoleID);
5-92
( ), ( ) Q64
adapter.Fill(table);
adapter = null;
conn.Dispose();
cmd.Dispose();
return table;
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="?"/>
</authorization>
</system.web>
</location>
</configuration>
<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 , ,
,
URL
5-95
Q65 Forms Authentication) ?
(Code-Based
ASP.NET , ,
, ,
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 ,
Cookie
, FormsAuthentication , FormsIdentity,
, , Request.
IsAuthenticated , true FormsIdentity
(ticket) , ,
, ,
version Integer ,
name String ,
expirationDate DateTime ,
userData String ,
, FormsIdentity
5-97
Part5
, ASP.NET Cookie ,
Cookies, HttpCookie Cookie , Response.
Cookies.Add() , ,
cookie.Expires = DateTime.Now.AddHours(8);
Response.Cookies.Add(cookie);
HttpCookie , , ASP.NET
FormsAuthentication.Encrypt() ,
HttpCookie Cookie
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
5-98
(Code-Based Forms Authentication) ? Q65
GenericPrincipal , IIdentity ,
role_list String ,
(Role List) ,
GenericPrincipal.IsInRole() ,
(Role-Based)
, FormsIdentity , GenericPrincipal ,
HttpContext.Current.User = gp;
, ,
Response.Redirect(Request.RawUrl);
, ,
5-99
Part5
//
//
this.txtUserName.Text, this.txtPassword.Text);
// Cookie
FormsAuthentication.SetAuthCookie(this.txtUserName.Text,
FormsAuthentication.FormCookiePath);
//
1, this.txtUserName.Text, DateTime.Now,
// FormsIdentity , Principal
// Cookie
FormsAuthentication.FormCookieName,
FormsAnthentication.Encrypt(ticket));
Response.Cookies.Add(cookie);
// Principal, FormsIdentity
GenericPrincipal gp =
HttpContext.Current.User = gp;
// ,
Response.Redirect(Request.RawUrl);
5-100
(Code-Based Forms Authentication) ? Q65
ASP.NET , ,
, Active Directory (
WindowsIdentity) , ticket ( ),
( ) ,
, ( , )
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
5-102
ASP.NET ? Q66
MailMessage , (
) ( HTML) ,
( , ),
1 SmtpClient Gmail
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
"my_gmail_password");
client.Timeout = 150;
5-103
Part5
if (this.T_File.HasFile)
attachments.Add(this.T_File.FileName, this.T_File.FileBytes);
client.Send(msg);
client = null;
msg.Priority = Priority;
msg.Subject = Subject;
msg.Body = Body;
msg.IsBodyHtml = IsBodyHTML;
if (!string.IsNullOrEmpty(To[0]))
if (To.Length > 0)
msg.To.Add(new MailAddress(To[i]));
5-104
ASP.NET ? Q66
if (!string.IsNullOrEmpty(CC[0]))
if (CC.Length > 0)
msg.CC.Add(new MailAddress(CC[i]));
if (!string.IsNullOrEmpty(Bcc[0]))
if (Bcc.Length > 0)
msg.Bcc.Add(new MailAddress(Bcc[i]));
// process attachments
Attachments.Keys.CopyTo(keys, 0);
return msg;
5-105
Part5
System.Net.Mail SmtpClient ,
, (Send Queue) , (Spam) ,
Mail Server (Mail Relay) ,
SMTP Server , ,
, Web ,
, ASP.NET ,
Windows , Service Application ( ),
, Windows
, Windows Service
5-106
ASP.NET ? Q66
this._Timer.Interval = 6000000;
this._Timer.Start();
// process information.
// create mail.
// send mail
this.SendMail(msg);
this._Timer.Stop();
this._Timer.Dispose();
5-107
Part5
.NET Framework
, (System.ServiceProcess )
ServiceBase
.NET Framework
MailMessage
MailAddress MailAddressCollection
SmtpClient
Attachment
5-108
Q67 ASP.NET
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
String lpszUsername, //
String lpszDomain, //
String lpszPassword, //
int dwLogonType, //
int dwLogonProvider, //
LogonUser() API ,
, (LOGON32_LOGON_
INTERACTIVE) (LOGON32_PROVIDER_DEFAULT)
, API
5-110
ASP.NET Q67
, ( )
, LogonUser() API
domainName = this.T_DomainName.Text;
userName = this.T_UserName.Text;
password = this.T_Password.Text;
//
tokenHandle = IntPtr.Zero;
// LogonUser() API
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
// true, false
if (false == returnValue)
5-111
Part5
// ,
(Token ID) ,
// , WindowsIdentity
//
, 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;
SetLastError = true)]
5-113
Part5
if (!Page.IsPostBack)
this.labelUser.Text = WindowsIdentity.GetCurrent().Name;
try
domainName = this.T_DomainName.Text;
userName = this.T_UserName.Text;
password = this.T_Password.Text;
tokenHandle = IntPtr.Zero;
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
5-114
ASP.NET Q67
if (false == returnValue)
Response.Write(string.Format(
tokenHandle + "<br>");
WindowsIdentity.GetCurrent().Name + "<br>");
WindowsImpersonationContext impersonatedUser =
newId.Impersonate();
Session["ImpersonateUser"] = impersonatedUser;
this.labelUser.Text = WindowsIdentity.GetCurrent().Name;
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
5-115
Part5
WindowsImpersonationContext impersonatedUser =
Session["ImpersonateUser"] as WindowsImpersonationContext;
impersonatedUser.Undo();
this.labelUser.Text = WindowsIdentity.GetCurrent().Name;
http://msdn2.microsoft.com/zh-tw/library/chf6fbt4(VS.80).aspx
Q54 ASP.NET ( ) ?
5-116
Q68 (Authentication Code)
ASP.NET , ,
,
( ),
,
,
, ,
, ,
(phpBB, DotNetNuke vBulletin ) ,
,
,
, Session Cookie
( ), (
), ,
5-117
Part5
, , 4-8 ,
,
, ,
1 HTTP Handler
using System;
using System.Collections.Generic;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
// Cookie ( Session)
5-118
(Authentication Code) Q68
// ,
//
Graphics g = Graphics.FromImage(bmp);
//
FontStyle.Regular);
// ( 4 )
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,
// ( )
//
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],
5-120
(Authentication Code) Q68
g.DrawString(authCode[1].ToString(), fontList[1],
g.DrawString(authCode[2].ToString(), fontList[2],
g.DrawString(authCode[3].ToString(), fontList[3],
// MemoryStream
bmp.Save(ms, ImageFormat.Gif);
ms.Flush();
g.Dispose();
context.Response.ContentType = "image/gif";
context.Response.BinaryWrite(ms.ToArray());
bmp.Dispose();
ms.Close();
2 cookie
if (!Page.IsPostBack)
5-121
Part5
cookie.Expires = DateTime.Now.AddMinutes(5);
// ,
//
// Cookie
Response.Cookies.Add(cookie);
Cookie , , 3
// cookie
//
if (cookie.Value == this.T_AuthCode.Text)
Response.Write(" ");
else
Response.Write(" ");
// ,
cookie.Expires = DateTime.Now.AddMinutes(5);
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
http://en.wikipedia.org/wiki/Captcha
reCAPTCHAProject
http://recaptcha.net/
5-123
Q69 URL URL
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
http://www.bookpool.com/sm/0735623740
http://www.bookpool.com/sm/0735623066
Trika's Blog:
http://blogs.msdn.com/trika
http://blogs.msdn.com/trika/archive/2007/06/27/people-at-microsoft-
learning.aspx
URL, Web ,
URL , URL , URL
(URL Rewriting)
http://www.mybooks.com.tw/ProductInfo/Inside WCF
5-125
Part5
http://www.mybooks.com.tw/ProductInfo/ProductInfo.aspx?keyword=Inside WCF
URL
URL Rewriting,
http://www.mybooks.com.tw/ProductInfo/ProductInfo.aspx?
type=books&vendor=Microsoft Press&category=Windows&caption=Introducing
Windows Server 2008
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
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 Rewriter()
// empty constructor
5-128
URL URL Q69
application.BeginRequest +=
new EventHandler(this.Rewriter_BeginRequest);
, URL BeginRequest
// 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");
if (Request.QueryString["t"] == null)
return;
ds.ConnectionString = ConfigurationManager.ConnectionStrings[
"northwindConnectionString"].ConnectionString;
5-130
URL URL Q69
if (Request.QueryString["t"] == "Products")
if (!string.IsNullOrEmpty(Request.QueryString["name"]))
ds.SelectCommand =
Request.QueryString["name"] + "'";
else
if (!string.IsNullOrEmpty(Request.QueryString["name"]))
ds.SelectCommand =
Request.QueryString["name"] + "'";
else
this.GridView1.DataSource =
ds.Select(new DataSourceSelectArguments());
this.GridView1.DataBind();
ds.Dispose();
5-131
Part5
<Configurations>
<system.web>
</httpModules>
</system.web>
</Configurations>
, URL Rewriting
http://msdn2.microsoft.com/en-us/library/ms972974.aspx
15 Seconds : Rewrite.NET
http://www.15seconds.com/issue/030522.htm
http://www.codeproject.com/aspnet/URLRewriter.asp
URLRewriting.NET:
http://www.urlrewriting.net/en/Default.aspx
5-132