網站開發,善用 Cached DataTable 可以使網站效能倍增,不必一直去資料庫抓資料。
但是使用 Cached DataTable 有一個地方要注意
就是他是 Shared 物件,表示同時有好幾個頁面都可以存取他
例如A網頁將資料抓出,然後變更裡面的DataRow資料,
另一個B網頁也會跟著變更
由於 Cached DataTable 在 Set DataRow Value 時
可能 Critical Section 沒有處理好,若真的同時多個thread 操作
會出現 Exception
(System.ArgumentOutOfRangeException: 索引超出範圍。必須為非負數且小於集合的大小。)
建議:
'這是 UNT FixPage 物件抓取單一資料的範例
Shared Function GetSpecialPage2FromCachedDT(ByVal Key As Int32) As DB.SpecialPage2
Dim DT As DataTable = GetAllDataFromBaseTableWithCache()
Dim Row As DataRow = DT.Rows.Find(Key)
If Row IsNot Nothing Then
'避免每個thread都共用table 寫入資料會出現問題
Dim newDT As DataTable = DT.Clone()
newDT.ImportRow(Row)
Return New SpecialPage2(newDT.Rows(0))
Else
Return Nothing
End If
End Function
Dim intCount As Integer = If(Convert.IsDBNull(row("count")), 0, Convert.ToInt32(row("count")))
// C#
int intCount = Convert.IsDBNull(row("count")) ? 0 : Convert.ToInt32(row("count"));
<system.web>
<httpRuntime requestValidationMode="2.0" />
<pages validateRequest="false" />
</system.web>
後者比較算是正解 基本上處理掉 <script 我想 XSS 就解決一大半
Sub SendMail_gmail(ByVal Subject As String, ByVal Body As String, ByVal FromMail As String, ByVal ToMail As String)
Dim msg As New System.Net.Mail.MailMessage
Dim client As New System.Net.Mail.SmtpClient
Try
msg.Subject = Subject
msg.Body = Body
msg.From = New System.Net.Mail.MailAddress(FromMail)
msg.To.Add(ToMail)
msg.IsBodyHtml = True
client.Host = "smtp.gmail.com"
Dim basicauthenticationinfo As System.Net.NetworkCredential = New System.Net.NetworkCredential("username@gmail.com", "password")
client.Port = Int32.Parse("587")
client.EnableSsl = True
client.UseDefaultCredentials = False
client.Credentials = basicauthenticationinfo
client.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.Network
client.Send(msg)
Catch ex As Exception
UW.WU.DebugWriteLine(ex.ToString, True, True)
End Try
End Sub
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="5000" />
</appSettings>
void Application_BeginRequest(object sender, EventArgs e)
{
UW.WU.BlockHacker();
}
HttpApplication Events:
Application_AcquireRequestState
Occurs when ASP.NET acquires the current state (for example, session state) that is associated with the current request.
Application_AuthenticateRequest
Occurs when a security module has established the identity of the user.
Application_AuthorizeRequest
Occurs when a security module has verified user authorization.
Application_BeginRequest
Occurs as the first event in the HTTP pipeline chain of execution when ASP.NET responds to a request.
Application_Disposed
Adds an event handler to listen to the Disposed event on the application.
Application_EndRequest
Occurs as the last event in the HTTP pipeline chain of execution when ASP.NET responds to a request.
Application_Error
Occurs when an unhandled exception is thrown.
Application_PostAcquireRequestState
Occurs when the request state (for example, session state) that is associated with the current request has been obtained.
Application_PostAuthenticateRequest
Occurs when a security module has established the identity of the user.
Application_PostAuthorizeRequest
Occurs when the user for the current request has been authorized.
Application_PostMapRequestHandler
Occurs when ASP.NET has mapped the current request to the appropriate event handler.
Application_PostReleaseRequestState
Occurs when ASP.NET has completed executing all request event handlers and the request state data has been stored.
Application_PostRequestHandlerExecute
Occurs when the ASP.NET event handler (for example, a page or an XML Web service) finishes execution.
Application_PostResolveRequestCache
Occurs when ASP.NET bypasses execution of the current event handler and allows a caching module to serve a request from the cache.
Application_PostUpdateRequestCache
Occurs when ASP.NET completes updating caching modules and storing responses that are used to serve subsequent requests from the cache.
Application_PreRequestHandlerExecute
Occurs just before ASP.NET begins executing an event handler (for example, a page or an XML Web service).
Application_PreSendRequestContent
Occurs just before ASP.NET sends content to the client.
Application_PreSendRequestHeaders
Occurs just before ASP.NET sends HTTP headers to the client.
Application_ReleaseRequestState
Occurs after ASP.NET finishes executing all request event handlers. This event causes state modules to save the current state data.
Application_ResolveRequestCache
Occurs when ASP.NET completes an authorization event to let the caching modules serve requests from the cache, bypassing execution of the event handler (for example, a page or an XML Web service).
Application_UpdateRequestCache
Occurs when ASP.NET finishes executing an event handler in order to let caching modules store responses that will be used to serve subsequent requests from the cache.
Application_Init
This method occurs after _start and is used for initializing code.
Application_Start
As with traditional ASP, used to set up an application environment and only called when the application first starts.
Application_End
Again, like classic ASP, used to clean up variables and memory when an application ends.
Session Events:
Session_Start
As with classic ASP, this event is triggered when any new user accesses the web site.
Session_End
As with classic ASP, this event is triggered when a user's session times out or ends. Note this can be 20 mins (the default session timeout value) after the user actually leaves the site.
Profile Events:
Profile_MigrateAnonymous
Occurs when the anonymous user for a profile logs in.
Passport Events:
PassportAuthentication_OnAuthenticate
Raised during authentication. This is a Global.asax event that must be named PassportAuthentication_OnAuthenticate.
Possibly more events defined in other HttpModules like:
System.Web.Caching.OutputCacheModule
System.Web.SessionState.SessionStateModule
System.Web.Security.WindowsAuthentication
System.Web.Security.FormsAuthenticationModule
System.Web.Security.PassportAuthenticationModule
System.Web.Security.UrlAuthorizationModule
System.Web.Security.FileAuthorizationModule
System.Web.Profile.ProfileModule
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(window).bind("paste", function () {
if (event.clipboardData) {
var clipboardData, found;
found = false;
clipboardData = event.clipboardData;
Array.prototype.forEach.call(clipboardData.items, function (item, i) {
if (item.type.indexOf("image") !== -1) {
var blob = clipboardData.items[i].getAsFile();
var URL = window.URL || window.webkitURL;
var source = URL.createObjectURL(blob);
pastedImage = new Image();
pastedImage.src = source;
pastedImage.onload = function () {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = pastedImage.width;
canvas.height = pastedImage.height;
ctx.drawImage(pastedImage, 0, 0);
var base64 = canvas.toDataURL();
base64 = base64.substring(base64.indexOf("iVBOR"));
$.ajax({
url: "/API/AddTaskImages.aspx",
async: false,
type: "POST",
data: ({
Image: base64
}),
dataType: "html",
success: function (msg) {
var oRes;
try {
oRes = eval(msg);
}
catch (err) {
alert("無法解析傳回資料 !");
alert(msg);
alert(err);
}
if (oRes.success) {
alert("Upload Success..");
//alert(oRes.msg);
$("#MyImageDataLoadDemo").attr("src", oRes.msg);
} else {
alert(oRes.msg);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
})
};
return false;
}
});
}
});
});
</script>
</head>
<body>
<div id="hold">
<div id="imgHold"><img src="" id="MyImageDataLoadDemo"></div>
<div>Click on the area above and ctrl+p an image to paste</div>
</div>
</body>
</html>
Partial Class API_AddTaskImages
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
'DB.sysconfig.Path.TaskAttachment
Dim Base64 As String = Me.Request("Image")
'UW.JSON.WriteErrorMessage(Base64)
'Return
Dim imageBytes As Byte() = Convert.FromBase64String(Me.Request("Image"))
Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream(imageBytes, 0, imageBytes.Length)
ms.Write(imageBytes, 0, imageBytes.Length)
Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(ms, True)
Dim map As Bitmap
Dim Filename As String = Now.ToString("yyyyMMddHHmmssfff") & ".png"
Try
System.IO.Directory.CreateDirectory(DB.sysconfig.Path.TaskAttachment & "UploadImages")
image.Save(DB.sysconfig.Path.TaskAttachment & "UploadImages\" & Filename, System.Drawing.Imaging.ImageFormat.Png)
UW.JSON.WriteSuccessMessage(DB.sysconfig.URL.TaskAttachment & "UploadImages/" & Filename)
Catch ex As Exception
UW.JSON.WriteErrorMessage(ex.ToString)
End Try
End Sub
End Class
Public Shared Funciont AA() as string
return xxxxx
End Function
public static string aa()
{
return xxxx
}
Public Shared Sub AA()
......
End Sub
public static void AA()
{
.....
}
Try
xxxxxx
Catch ex As Exception
UW.WU.WriteErrorToLog(ex)
End Try
try
{
xxxxxx
}
catch (Exception ex)
{
tran.Rollback();
}
char[] delimiterChars = { ',' };
foreach (string tags in cbTags.Split(delimiterChars))
{
}
select case AA
case "AA"
xxx
case "BB"
bbb
case else
aaaa
end select
switch (AA) {
case "AA":
xxx();
break;
case "BB":
bbb();
break;
default:
aaaa();
break;
}