SlideShare a Scribd company logo
ASP.NET 開發的奇幻漂流
ASP.NET開發要注意的是?
1
亂馬客
rainmaker_ho@gss.com.tw
25867890 # 515
Outline
• ASP.NET開發要注意的是?(ASP.NET 2.0以上)
• 基本篇
• 設定TextBox Focus、Default Button、驗証
• GridView篇
• GridView分頁、資料分頁、取得選取列的Key值…
• 狀態篇
• ViewState
• 特殊篇
• 動態加入控制項、先回Server檢查、HttpHandler
• 上線篇
• 客製化、設定Release模式、維護
• IIS篇
• 查看目前的要求、設定IIS Log的欄位、讀取IIS Log的資訊… 2
基本篇
• 設定TextBox Focus
• 設定預設Button
• 必填欄位驗證
• 檢查行動裝置
3
Page上預設Focus的TextBox在那裡呢?
• 可透過以下方式來設定Focus
DefaultFocusTextBox.Focus();
Page.SetFocus(DefaultFocusTextBox);
Page.SetFocus(DefaultFocusTextBox.ClientID);
form1.DefaultFocus = DefaultFocusTextBox.ClientID;
4
如何設定預設的Button?
• 設定form or panel的DefaultButton屬性
form1.DefaultButton = Button1.UniqueID;
panel1.DefaultButton = Button1.UniqueID;
5
顯示完必輸欄位後,為何沒有Focus呢?
• 設定 RequiredFieldValidator 的 SetFocusOnError = “True”
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server"
ErrorMessage="TextBox3一定要輸入哦"
ControlToValidate="TextBox3"
SetFocusOnError=“True" />
6
動態設定必填欄位需要Postback嗎?
AutoPostBack="True" OnCheckedChanged=“event“
vldWay_1.Enabled = chkWay_1.Checked;
7
動態設定必填欄位需要Postback嗎?(cont..)
• $(document).read, checkBox變動時
• 設定必填欄位啟用與否
ValidatorEnable(ValidatorControl, true/false);
ValidatorEnable(txtWay_2_Validator,
chkWay_2.checked);
8
檢查是否為行動裝置
• Request.Browser.IsMobileDevice
9
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Browser.IsMobileDevice)
{
Response.Redirec("~/default_mobile.aspx");
}
}
Lookup: C:WindowsMicrosoft.NETFrameworkv2.0.50727CONFIGBrowsers
Other Info:ASP.NET Mobile Device Detection
GridView篇
• GridView分頁
• 資料分頁
• 取得選取列的Key值
• ClientIdMode
• …
10
請做有分頁的GridView
• GridView
• AllowPaging="True“
• OnPageIndexChanging="GridView1_PageIndexChanging“
• GridView1.PageIndex = e.NewPageIndex;
<asp:GridView ID="GridView1" AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChan
ging“ ….
GridView1.DataSource = mydataSource;
GridView1.DataBind(); 11
如果資料量很大,要如何處理呢?
• GridView
• AllowPaging="True“
• DataSourceID="odsGridView"
• ObjectDataSource
• EnablePaging="True“
• OnSelecting="odsGridView_Selecting“
• MaximumRowsParameterName="pageSize"
• StartRowIndexParameterName="startIndex"
• TypeName="MyProduct.BO.Person“
• SelectMethod="GetPersonsPaging"
• SelectCountMethod="GetSelectedCount"
12
如果資料量很大,要如何處理呢? (cont..)
• Nbase20 搭配SQL usp_paging(Store Procedure)來做資料分頁
EXEC(
'DECLARE @StartRow int, @EndRow int
SET @StartRow = ' + @strStartRow + '
SET @EndRow = ' + @strEndRow + '
SELECT PG2.* FROM ( SELECT ROW_NUMBER() OVER( ' +
@strORDER + ') AS RowNum, PG.* FROM (' + @strSQL + ') PG )
PG2' + '
WHERE PG2.RowNum > @StartRow AND PG2.RowNum <=
@EndRow ' + @strORDER)
13
如何取得GridView選取列的資訊?
• 在GridView上的Button 在RowCommand Event中
• CommandArgument屬性
• 取得 RowIndex ,透過 RowIndex 來取得DataKeys
string key = e.CommandArgument.ToString();
14
int index =
((GridViewRow)((Button)e.CommandSource).NamingConta
iner).RowIndex;
string dataKey =
GridView1.DataKeys[index].Value.ToString();
如何取得GridView選取列的資訊? (cont..)
• 透過 GridViewRow ,利用FindControl來取得
Control lblKey =
((GridViewRow)((Button)e.CommandSource).NamingContainer)
.FindControlRecurive("labelName");
if (!lblKey.IsNull())
{
string dataKey2 = (lblKey as Label).Text;
}
15
Postback後可以不要每次都要Scroll嗎?
• MaintainScrollPositionOnPostback = “true”
<%@ Page
MaintainScrollPositionOnPostback="true“ …
<pages maintainScrollPositionOnPostBack="true“ …
16
ClientIDMode
ASP.NET 4.0
值 說明
Inherit 繼承父控制項的ID產生機制
AutoID 與之前版本相同的用戶端ID產生方式
Predictable 透過一個確定的機制來產生用戶端的ID
通常與父控制項ClientIDRowSuffix配合
Static 與伺服端指定的ID相同
17
18
可以暫時停止Ajax?
• 使用 Ajax (ScriptManager + UpdatePanel)
• 有錯誤時如果不好查,可設定ScriptManager
EnablePartialRendering=“False"
<asp:ScriptManager ID="ScriptManager1"
runat="server" EnablePartialRendering=“False" ... 19
狀態篇
• ViewState
20
ViewState Size太肥問題
• 用內建的 SessionPageStatePersister 取代預設的
HiddenFieldPageStatePersister
• 用3Party元件
• Flesk.ViewStateOptimizer (壓縮後再存)
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
21
ViewState 放到了Session
Hidden欄位為何還有資料呢?
• 因為有些資料是放在 ControlState 之中
<system.web>
<browserCaps>
<case>RequiresControlStateInSession=true</case>
</browserCaps>
</system.web>
22
特殊篇
• 動態加入控制項
• 按Button時可以先回Server檢查後,再問User要不要做
• HttpHandler
23
動態加入控制項的時機
24
動態加入控制項的時機 (cont..)
• Page_Init 、 Page_Load Event
• 每次都要加入
• !IsPostBack 設定初始值
• 用AddAt,要在Page_init
TextBox tb = new TextBox();
tb.ID = "DynamicAddTextBox";
holderTextBox.Controls.Add(tb);
if (!IsPostBack)
{
tb.Text = "Init Value";
tb.BackColor = Color.Red;
} 25
按Button時可以先回Server檢查後,
再問User要不要做嗎?
26
• 在Button的Click中判斷,然後再Render JS 問User後,再Postback一
次
按Button時可以先回Server檢查後,
再問User要不要做嗎? Postback 2 次
...btnPostbackTwice_OnClick(object s, EventArgs e)
{
...RegisterStartupScript( .... "if(confirm('警告!是否要
submit?')){window.setTimeout('__doPostBack("",
"ProcbtnRun");', 500, 'Javascript')};"
}
27
• Page_Load時判斷是不是真的要處理
按Button時可以先回Server檢查後,
再問User要不要做嗎? Postback 2 次
if (Page.IsPostBack)
{
//判斷是不是按下確認回來的
if (Request.Form["__EVENTARGUMENT"] == "ProcbtnRun")
ProcessConfirm();
}
28
• Page要實作 ICallbackEventHandler
• Button的OnClientClick = ClientScript.GetCallbackEventReference 等等
一堆JS去串起來
• 在ICallbackEventHandler.RaiseCallbackEvent 中處理Logic
• 在ICallbackEventHandler.GetCallbackResult() 回傳判斷結果
• Button的OnClick 寫實際要執行的事
• Client端還要覆寫原生的 WebForm_DoCallback Method (有Bug)
按Button時可以先回Server檢查後,
再問User要不要做嗎? Callback
29
<input type="submit"
onclick="WebForm_DoCallback(&#39;__Page&#39;,&#39;RunCallback&#3
9;,btnCallBack_CallbackHandler,&quot;&quot;,null,false); return false;" ..
• 做一個Web Service 、 Page Method or Web API …
• ClientClick 使用XMLHttpSyncExecutor(可從網路上download)
• Button的OnClick 寫實際要執行的事
按Button時可以先回Server檢查後,
再問User要不要做嗎? 同步Call WS
<asp:Button ID="btnCallWS" …..
OnClientClick="return callWSCheckConfirm();"
OnClick="btnCallWS_OnClick" />
30
• 做一個Web Service 、 Page Method or Web API …
• ClientClick Call WS,並加一個flag判斷,何時要Call WS,何時要
postback
• Button的OnClick 寫實際要執行的事
按Button時可以先回Server檢查後,
再問User要不要做嗎?非同步Call WS
<asp:Button ID="btnCallAsyncWS" ...
OnClientClick="return callWSAsyncCheckConfirm();"
OnClick="btnCallWS_OnClick" />
31
按Button時可以先回Server檢查後,
再問User要不要做嗎?
• Postback 2次、Callback都是在同一個頁面處理
• 其他方式需要將資料傳遞過去處理
• 請依實際需求狀況選擇適合的方式
32
透過HttpHandler來防護文件檔
• 如檢查Session[“uid”]不為空才能download
• public class CsvHandler : IHttpHandler, IReadOnlySessionState
• public void ProcessRequest(HttpContext context)
• …..
33
<system.webServer>
<handlers>
<add name="MyCsvHandler" verb="GET" path="*.csv"
type="MyProduct.CsvHandler" />
</handlers>
</system.webServer>
Ooops!
• Q.為何Button都是淡藍色呢?
34
上線篇
• 設定 ASP.NET 檔案上傳的大小
• 客製化
• 設定Release模式
• 維護
35
如何設定 ASP.NET 檔案上傳的大小?
<system.web>
<!– 單位是 KB, 預設是4096, 80 !>
<httpRuntime
maxRequestLength=“10240”
requestLengthDiskThreshold=“256“ />
</system.web>
36
有放客製化的地方嗎?
37
有放客製化的地方嗎? (cont..)
• 在Application_BeginRequest Event中處理
• 寫在Global.asax之中
• 寫個HttpModule
<configuration>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="MyModule" type="MyModule.MyMu, MyMu"
preCondition="managedHandler" />
</modules>
</system.webServer>
</configuration>
38
需要每個Web.config設定debug = false嗎?
• <compilation debug=“true” />
• Compilation 比較久
• Memory會用的比較多
• WebResource.axd不會被cached
• 在Machine.config中設定以下的值,可強迫每個Web AP使用
Release模式!
<system.web>
<deployment retail="true" />
</system.web> 39
如何設定系統停機維修狀態
• 在網站下加入 app_offline.htm
40
IIS篇
• 查看目前的要求
• 設定IIS Log的欄位
• 讀取IIS Log的資訊
• Log Parser
• Log Parser Lizard
• 失敗要求的追蹤
41
查看目前的要求
42
設定IIS Log的欄位
43
讀取IIS Log的資訊
• Log Parser
• logparser "SELECT top 10 cs-uri-stem, time-taken , sc-status, LogFilename
FROM E:GSSTechInfoDemoiislog*.log ORDER BY time-taken DESC" -i:W3C
• Log Parser Lizard
• 選取IIS Log
SELECT top 10 cs-uri-stem, time-taken , sc-status, LogFilename
FROM E:GSSTechInfoDemoiislog*.log
ORDER BY time-taken DESC
• 匯到DB之中分析
• logparser "select * into LogTable from
'E:GSSTechInfoDemoiislogex130222.log' " -o:SQL -createTable:ON -
server:. -database:tempdb -username:sa -password:yourpwd
44
讀取IIS Log的資訊
Log Parser
45
讀取IIS Log的資訊
Log Parser Lizard
46
匯到DB之中分析
47
SELECT TOP 10 csUriStem, timeTaken / 1000.0 AS
[timeTaken(秒)]
FROM dbo.LogTable
ORDER BY timeTaken DESC
失敗要求的追蹤
48
ASP.NET相關資源
• ASP.NET Tutorial
• Building Web Apps with ASP.NET Jump Start - 8 Hours of FREE Training
Videos
• Introduction to ASP.NET
49
Q & A
50
亂馬客
rainmaker_ho@gss.com.tw
25867890 # 515

More Related Content

Viewers also liked (7)

PPTX
軟體弱點掃描
Rainmaker Ho
 
PPTX
Angular2 DI
Rainmaker Ho
 
PPTX
SQL Count(*) VS Count(1)
Rainmaker Ho
 
PPTX
Sql效能調校分享-資料瘦身
Rainmaker Ho
 
PPTX
從Developer來看 效能調校
Rainmaker Ho
 
PPTX
Angular2 Form
Rainmaker Ho
 
PPTX
Internet of Things
Rainmaker Ho
 
軟體弱點掃描
Rainmaker Ho
 
Angular2 DI
Rainmaker Ho
 
SQL Count(*) VS Count(1)
Rainmaker Ho
 
Sql效能調校分享-資料瘦身
Rainmaker Ho
 
從Developer來看 效能調校
Rainmaker Ho
 
Angular2 Form
Rainmaker Ho
 
Internet of Things
Rainmaker Ho
 

Similar to Asp.net開發要注意的是? (6)

PPT
網站設計100步
evercislide
 
PPTX
ASP.NET AJAX
HO-HSUN LIN
 
PPS
Flash UI - &#21830;&#26989;&#25033;&#29992;&#26696;&#20363;&#25506;&#35342;
jehuen
 
PDF
twMVC#03 | ASP.NET MVC內建驗證活用與擴充
twMVC
 
PDF
ASP.NET MVC 內建驗證擴充與活用技巧 -twMVC#3
twMVC
 
PPT
Ken20150320
LearningTech
 
網站設計100步
evercislide
 
ASP.NET AJAX
HO-HSUN LIN
 
Flash UI - &#21830;&#26989;&#25033;&#29992;&#26696;&#20363;&#25506;&#35342;
jehuen
 
twMVC#03 | ASP.NET MVC內建驗證活用與擴充
twMVC
 
ASP.NET MVC 內建驗證擴充與活用技巧 -twMVC#3
twMVC
 
Ken20150320
LearningTech
 
Ad

Asp.net開發要注意的是?

Editor's Notes

  • #6: 要先focus在畫面上!
  • #8: 2RequiredValidationDemo
  • #9: RequiredValidationDemo.aspx
  • #10: http://www.codeproject.com/Articles/213825/ASP-net-Mobile-device-detection
  • #12: GridViewPagingInMemory
  • #13: GridViewPagingInDatabase.aspx
  • #14: USE AdventureWorks2012 go declare @p3 int set @p3=15470 exec usp_paging @recordCount=@p3 output ,@strSQL='SELECT BusinessEntityID, FirstName, MiddleName, LastName FROM Person.Person' ,@strORDER='ORDER BY FirstName ASC' ,@startIndex=5 ,@pageSize=5 select @p3 as [Total Count]
  • #15: GridViewPagingInMemory.aspx
  • #18: 4_1ClientIdModeDemo.aspx
  • #20: UpdatePanel.aspx => SelectedIndexChanged
  • #22: 5UpdatePanel.aspx
  • #23: Web.config UpdatePanel.aspx
  • #26: 1.先直接Postback,所以DynamicAddTextBox2的backColor不見了 2.加入一個TextBox,再Postback,結果DynamicAddTextBox1的backColor不見了 3.使用Add取代AddAt 4.使用Addat,移到Page_Init之中
  • #28: ServerCheckConfirm.aspx
  • #29: ServerCheckConfirm.aspx
  • #30: ServerCheckConfirm.aspx
  • #31: ServerCheckConfirm.aspx
  • #32: ServerCheckConfirm.aspx
  • #37: 全都上傳到memory,requestLengthDiskThreshold多大之後會存到disk
  • #39: 1.如果在Global.asax.cs中處理,需將 runAllManageModuleForAllRequests=“true” 2.如果在HttpModule處理,就不需要設定preCondition=“manageHandler”
  • #40: C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG 找<system.web> 在最上面加入 <deployment retail="true" />
  • #44: http://technet.microsoft.com/zh-tw/library/cc754702(v=ws.10).aspx
  • #45: http://mlichtenberg.wordpress.com/2011/02/03/log-parser-rocks-more-than-50-examples/
  • #46: logparser "SELECT top 10 cs-uri-stem, time-taken , sc-status, LogFilename FROM E:\GSS\TechInfo\Demo\iislog\ex130222.log ORDER BY time-taken DESC" -i:W3C
  • #47: SELECT top 10 cs-uri-stem, time-taken , sc-status, LogFilename FROM E:\GSS\TechInfo\Demo\iislog\ex130222.log ORDER BY time-taken DESC
  • #48: logparser "select * into LogTable from 'E:\GSS\TechInfo\Demo\iislog\ex130222.log' " -o:SQL -createTable:ON -server:. -database:tempdb -username:sa -password:0935