- TypeName:為主版頁面指定類型名稱。
VirtualPath:指定產生強型別之檔案的路徑。
Reference:
Capture Master Page Events in Content Pages - ASP.NET 2.0
@ MasterType 指示詞
<!--
sitemap角色權限讀取 securityTrimmingEnabled="true"
-->
<siteMap defaultProvider="XmlSiteMapProvider" enabled="true">
<providers>
<add name="XmlSiteMapProvider" description="未登入與登入"
type="System.Web.XmlSiteMapProvider,System.Web,Version=2.0.3600.0, Culture= neutral,PublicKeyToken=b03f5f7f11d50a3a"
siteMapFile="common-map.sitemap" securityTrimmingEnabled="false" />
<add name="XmlSiteMapProviderForAdmin" description="登入管理員"
type="System.Web.XmlSiteMapProvider,System.Web,Version=2.0.3600.0, Culture= neutral,PublicKeyToken=b03f5f7f11d50a3a"
siteMapFile="admin-map.sitemap" securityTrimmingEnabled="false" />
</providers>
</siteMap>
///
/// BaseMaster 的摘要描述
///
public class BaseMaster : System.Web.UI.MasterPage
{
public BaseMaster()
{
//
// TODO: 在此加入建構函式的程式碼
//
}
///
/// 切換不同的sitemap
///
///
///
public string SitemapHelper(string username)
{
string provider = "XmlSiteMapProvider";
string[] roleTmp = System.Web.Security.Roles.GetRolesForUser(username);
for (int i = 0; i < roleTmp.Length; i++)
{
if (roleTmp[i] == "Admin")
{
provider = "XmlSiteMapProviderForAdmin";
break;
}
}
return provider;
}
}
public partial class guest_mp : BaseMaster
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.Page.User.Identity.IsAuthenticated)
{
if (!IsPostBack)
{
this.SiteMapDataSource1.SiteMapProvider = this.SitemapHelper(this.Page.User.Identity.Name);
}
}
}
}
System.Net.WebClient wc = new System.Net.WebClient(); string url = "http://www.thsrc.com.tw/tc/ticket/tic_time_result.asp"; string postData = "rom=1&to=5&sDate=2009%2F11%2F23&TimeTable=21%3A00&FromOrDest=From&x=33&y=10"; wc.Encoding = Encoding.UTF8; byte[] sendData = Encoding.GetEncoding("utf-8").GetBytes(postData.ToString()); wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-TW; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5"); wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); wc.Headers.Add("Referer", "http://www.thsrc.com.tw/tc/index.asp"); byte[] recData = wc.UploadData(url, "POST", sendData); string tmp = Encoding.UTF8.GetString(recData);
/// <summary> /// 保持連線 /// </summary> /// <param name="connectionName">連線的裝置名稱</param> void KeepConnection(string connectionName) { Shell32.ShellClass shell = new ShellClass(); //列出namespace代碼 //for (int i = 0; i < 100; i++) //{ // if (shell.NameSpace(i) != null) // this.listBox1.Items.Add("[" + i.ToString() + "]" + shell.NameSpace(i).Title); //} Folder applicationObj = shell.NameSpace(3); //取得控制台清單 foreach (FolderItem fItem in applicationObj.Items()) { //this.listBox1.Items.Add(fItem.Name); if (fItem.Name == "網路連線") { if (fItem.IsFolder) { //這裡的轉換要注意一下 Folder network = (Folder)fItem.GetFolder; //取得網路連線清單 foreach (FolderItem fItem2 in network.Items()) { //this.listBox1.Items.Add(fItem2.Name); if (fItem2.Name == connectionName) { //列出該項目右鍵選單 foreach (FolderItemVerb fivb in fItem2.Verbs()) { //this.listBox1.Items.Add(fivb.Name); if (fivb.Name.IndexOf("連線") > -1 && fivb.Name.IndexOf("預設") == -1 && fivb.Name.IndexOf("中斷") == -1) fivb.DoIt(); } } } } } } }
在web.config或app.config裡的<configSections>區塊加入下列設定: <section name="cacheProvider" type="MemcachedProviders.Cache.CacheProviderSection, MemcachedProviders" allowDefinition="MachineToApplication" restartOnExternalChanges="true"/> <sectionGroup name="enyim.com"> <section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching"/> </sectionGroup> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
<!--Memcatch 詳細設定--> <cacheProvider defaultProvider="MemcachedCacheProvider"> <providers> <add name="MemcachedCacheProvider" type="MemcachedProviders.Cache.MemcachedCacheProvider, MemcachedProviders" keySuffix="_MySuffix_" defaultExpireTime="2000"/> </providers> </cacheProvider> <enyim.com> <memcached> <servers> <!--Memcatch default port 11211--> <add address="127.0.0.1" port="8888" /> </servers> <socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00" /> </memcached> </enyim.com> <log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}]- %message%newline" /> </layout> </appender> <root> <priority value="WARN"/> <appender-ref ref="ConsoleAppender"> <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="WARN"/> <levelMax value="FATAL"/> </filter> </appender-ref> </root> </log4net>
DataTable dt = (DataTable)MemcachedProviders.Cache.DistCache.Get("SearchKey3"); if (dt == null) { Response.Write("without cache"); Module_Command.GetMenuList obj = new Module_Command.GetMenuList(3); dt = (System.Data.DataTable)obj.Execute(); MemcachedProviders.Cache.DistCache.Add("SearchKey3", dt, TimeSpan.FromSeconds(5)); } this.GridView1.DataSource = dt; this.GridView1.DataBind();
$(chirdObj).parent().attr("tagName") == "UL"
#listDiv
{
width:100%;
background:#fff;
padding:10px;
}
#listDiv:after
{
content: ".";
display: block;
clear: both;
height: 0;
overflow: hidden;
visibility: hidden;
}
#listDiv ol li
{
display: inline;
float: left;
text-align: center;
margin-right: 15px;
margin-bottom: 10px;
overflow: hidden;
background-color:#FFFFFF;
}
#listDiv ol li a
{
}
#listDiv ol li a:hover
{
}
/*album title desc*/
#listDiv ol li a span.albumTitle
{
font-size : 12px;
display: block;
text-align: left;
padding-left: 3px;
padding-top: 3px;
padding-bottom: 3px;
}
/*album cover*/
#listDiv ol li div.albumCover
{
display: table-cell;
border:1px solid #CCCCCC;
width:110px;
height:110px;
vertical-align:middle;
text-align:center;
}
#listDiv ol li div.albumCover:hover
{
background-color:#B0C4DE;
}
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h2>相簿標題:<asp:Label ID="lblAlbumTitle" runat="server"></asp:Label></h2>
<div id="photoList">
<asp:ListView ID="ListView1" runat="server"
DataSourceID="SqlDataSourcePhotoList" >
<EmptyDataTemplate>
<div class="icon-yellow">Sorry 目前相簿無照片</div>
</EmptyDataTemplate>
<ItemTemplate>
<li>
<a href="activity-photo-show.aspx?aid=<%#Eval("ActivityPhotoAID")%>&pid=<%#Eval("ActivityPhotoID")%>">
<div class="albumCover">
<img src="<%#AlbumCover(Eval("ActivityAlbumDirectory").ToString(),Eval("ActivityPhotoFile").ToString())%>" alt="<%#Eval("ActivityAlbumTitle")%>"/>
<%-- <img src="photo/default.gif" />--%>
</div>
</a>
</li>
</ItemTemplate>
<AlternatingItemTemplate>
<li>
<a href="activity-photo-show.aspx?aid=<%#Eval("ActivityPhotoAID")%>&pid=<%#Eval("ActivityPhotoID")%>">
<div class="albumCover">
<img src="<%#AlbumCover(Eval("ActivityAlbumDirectory").ToString(),Eval("ActivityPhotoFile").ToString())%>" alt="<%#Eval("ActivityAlbumTitle")%>"/>
<%--<img src="photo/default.gif" />--%>
</div>
</a>
</li>
</AlternatingItemTemplate>
<LayoutTemplate>
<div id="listDiv">
<ol>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ol>
</div>
<div class="Pagination">
<asp:DataPager ID="_moviesGridDataPager" runat="server" PageSize="20">
<Fields>
<asp:NumericPagerField CurrentPageLabelCssClass="pagerlabel" NextPageText="..."
NextPreviousButtonCssClass="pagerlink" NumericButtonCssClass="pagerlink"
PreviousPageText="..."/>
</Fields>
</asp:DataPager>
</div>
</LayoutTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSourcePhotoList" runat="server"
ConnectionString="<%$ ConnectionStrings:CSIEFriendsConnectionString %>"
SelectCommand="SELECT ActivityAlbumTitle,ActivityPhotoID, ActivityPhotoAID, ActivityPhotoFile,ActivityAlbumDirectory FROM vw_ActivityPhotoList
Where ActivityPhotoAID=@aid">
<SelectParameters>
<asp:QueryStringParameter Name="aid" QueryStringField="aid" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSourceGetAlbumTitle" runat="server"
ConnectionString="<%$ ConnectionStrings:CSIEFriendsConnectionString %>"
SelectCommand="SELECT [ActivityAlbumTitle] FROM [ActivityAlbum] WHERE ([ActivityAlbumID] = @ActivityAlbumID)">
<SelectParameters>
<asp:QueryStringParameter Name="ActivityAlbumID" QueryStringField="aid"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</asp:Content>
<!--uploader-->
<script type="text/javascript" src="../js/swfobject.js"></script>
<script type="text/javascript" src="../js/jquery.uploadify.v2.1.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="../css/uploadify.css"/>
//限制上傳的檔案格式一定要指定fileDesc
<script type="text/javascript">
$(document).ready(function() {
$("#uploadify").uploadify({
"uploader": "../js/uploadify.swf",
"script": "../uploadHandler.ashx",
"cancelImg": "../images/cancel.png",
"sizeLimit": 1024000,
"queueID": "fileQueue",
"auto": false,
"fileDesc":"選取上傳的照片",
"fileExt": "*jpeg;*.jpg;*.gif;*.png",
"multi": true,
"onComplete": function(event, queueID, fileObj, response, data) {
if (response == "0")
alert("上傳發生錯誤");
else {
$("#uploadSet").append("<div id=\"fileitem\" >file:" + fileObj.name + " size:" + fileObj.size + "</div>");
}
}
});
});
function Upload() {
$("#uploadSet").html("");
$("#uploadify").uploadifySettings("scriptData", { "aid": $("#ctl00_ContentPlaceHolder1_hiddenAlbum").val() });
$("#uploadify").uploadifyUpload();
}
function CancelUpload() {
$("#uploadify").uploadifyClearQueue();
}
</script>
需注意的是:.net預設的上傳大小為上限值 4096 (4 MB)
因此會產生超出最大要求長度的exception,
要再webconfig加入以下設定
例如, Web.config 設定會允許最大 10 MB 的檔案上傳(設跟uploadifyg sizeLimit一樣大):
<System.Web>
<httpRuntime maxRequestLength="10240" />
</System.Web>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h2>照片上傳</h2>
<p class="help">請上傳小於 1MB 的圖片,僅支援.jpg、.gif、.png等圖片格式</p>
<p>支援多檔上傳</p>
<div id="fileQueue"></div>
<input type="file" name="uploadify" id="uploadify" />
<a href="javascript:Upload()" runat="server">上傳圖片</a>
<a href="javascript:CancelUpload()" >取消選取圖片</a>
<input id="hiddenAlbum" type="hidden" runat="server" />
<div id="uploadSet"></div>
</asp:Content>
<%@ WebHandler Language="C#" Class="uploadHandler" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using BigdControls;
using System.Drawing;
using System.Drawing.Drawing2D;
public class uploadHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
if (context.Request["aid"] == null)
{
context.Response.Write("0");
return;
}
//uploadifySettings post 的 album id
string aid = context.Request["aid"].ToString();
//album directory
string aDirectory = this.GetAlbumDirectory(aid);
if (String.IsNullOrEmpty(aDirectory))
return;//無相簿目錄
string fullFileName = context.Server.MapPath("Album/" + aDirectory + "/");
string fullFileNameThumb = context.Server.MapPath("Album/" + aDirectory + "/thumb/");
for (int i = 0; i < context.Request.Files.Count; i++)
{
HttpPostedFile postedFile = context.Request.Files[i];
string fileFormat = Path.GetExtension(postedFile.FileName);
if (ModuleSecurity.ModuleSecurity.FileChecker(fileFormat,new string[] { ".jpg", ".gif", ".png" }))
{
string orgFileName = Path.GetFileNameWithoutExtension(postedFile.FileName);
//string fileName = orgFileName + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + fileFormat;
Random rn = new Random((int)DateTime.Now.Ticks);
string fileName = rn.Next().ToString() + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + fileFormat;
fullFileName = fullFileName + fileName;
fullFileNameThumb = fullFileNameThumb + fileName;
//save photo
postedFile.SaveAs(fullFileName);
//縮圖
postedFile.SaveAs(fullFileNameThumb);
ImageProcessing.Save(fullFileNameThumb,
ImageProcessing.ImagePreviewThumb(fullFileNameThumb, 100, 100, Color.White, InterpolationMode.High, SmoothingMode.HighQuality));
//add photo
this.AddAlbumPhoto(aid, fileName);
}
}
context.Response.Write("1");
}
public bool IsReusable {
get {
return false;
}
}
/// <summary>
/// 取得相簿目錄
/// </summary>
/// <param name="aid">相簿id</param>
/// <returns></returns>
public string GetAlbumDirectory(string aid)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CSIEFriendsConnectionString"].ConnectionString);
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand("select ActivityAlbumDirectory from ActivityAlbum where ActivityAlbumID=@aid",sqlConn);
sqlCmd.Parameters.Add("aid", SqlDbType.Int).Value = aid;
string direcdtory = sqlCmd.ExecuteScalar().ToString();
sqlConn.Close();
return direcdtory;
}
/// <summary>
/// 新增相片
/// </summary>
/// <param name="aid">相簿id</param>
/// <param name="photo">相本檔名</param>
public void AddAlbumPhoto(string aid, string photo)
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CSIEFriendsConnectionString"].ConnectionString);
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand("insert into ActivityPhoto(ActivityPhotoAID,ActivityPhotoFile)values(@aid,@photo) ", sqlConn);
sqlCmd.Parameters.Add("aid", SqlDbType.Int).Value = aid;
sqlCmd.Parameters.Add("photo", SqlDbType.NVarChar).Value = photo;
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
jQuery.validator.addMethod("projSN", function(value, element) { var length = value.length; return this.optional(element) || (length == 5 && /^[A-Z]{5}$/.test(value)); }, "專案代碼僅限英文大寫五碼"); jQuery.validator.addMethod("number", function(value, element) { var length = value.length; return this.optional(element) || (/^[1-9]{1}[0-9]*$/.test(value)); }, "欄位只能為數字,且第一位數不能為 0"); //
<input id="btnProdcut" type="button" value="送出" runat="server" onclick="MySubmit()"/>
<script type="text/javascript">
$(document).ready(function() {
$("#aspnetForm").validate({
event:"keyup",
rules: {
<%=tbDesignName.UniqueID %>: {
minlength: 2,
maxlength:10,
required: true
},
<%=tbDesignNameEnglish.UniqueID %>: {
minlength: 2,
maxlength:10,
required: true,
},
<%=tbDesignDesc.UniqueID %>: {
minlength: 2,
maxlength:10,
required: true,
},
<%=tbDesignDescEnglish.UniqueID %>: {
minlength: 2,
maxlength:50,
required: true,
}
},
messages: {
<%=tbDesignName.UniqueID %>: {
required: "設計名稱尚未填寫",
minlength: "設計名稱最小長度為 2",
maxlength: "設計名稱最大長度為 10"
},
<%=tbDesignDesc.UniqueID %>: {
required: "設計描述尚未填寫",
minlength: "設計描述最小長度為 2",
maxlength: "設計描述最大長度為 10"
}
}
});
});
</script>
function MySubmit() {
CancelSumbit();
if (FormValidate()) {
if (FileValidate()) {
//驗證成功
else {
//驗證失敗
}
});
}
else
alert("驗證失敗");
}
function FormValidate() {
var displayChecker = false;
//找出class=error的錯誤訊息元素
$("td .error").each(function(i, obj) {
//alert($(this).css("display"));
if ($(this).css("display") == "none")
displayChecker = true;//表示欄位都通過驗證
else
displayChecker = false;
});
if (displayChecker == true)
return true;
else
return false;
}
function CancelSumbit() {
$("input:[type=submit]").submit();
return false;
}
int allControl = this.ListView1.Items[e.ItemIndex].Controls.Count;
for (int i = 0; i < allControl; i++)
{
this.Response.Write(this.ListView1.Items[e.ItemIndex].Controls[i].ClientID + "<br/>");
}
this.SqlDataSourceActivityAlbumList.UpdateParameters["ActivityAlbumID"].DefaultValue = ((ImageButton)this.ListView1.Items[e.ItemIndex].Controls[1]).CommandArgument;
this.SqlDataSourceActivityAlbumList.UpdateParameters["ActivityAlbumTitle"].DefaultValue = ((TextBox)this.ListView1.Items[e.ItemIndex].FindControl("tbAlbumTitle")).Text;
this.SqlDataSourceActivityAlbumList.UpdateParameters["ActivityAlbumDesc"].DefaultValue = ((TextBox)this.ListView1.Items[e.ItemIndex].FindControl("tbAlbumDesc")).Text;
// Create stars $("#rat").stars({ // starWidth: 28, // only needed in "split" mode cancelShow: false, callback: function(ui, type, value) { // Hide Stars while AJAX connection is active $("#rat").hide(); $("#loader").show(); // Send request to the server using POST method /* NOTE: The same PHP script is used for the FORM submission when Javascript is not available. The only difference in script execution is the returned value. For AJAX call we expect an JSON object to be returned. The JSON object contains additional data we can use to update other elements on the page. To distinguish the AJAX request in PHP script, check if the $_SERVER['HTTP_X_REQUESTED_WITH'] header variable is set. (see: demo6.php) */ $.post("demo6.php", {rate: value}, function(db) { // Select stars to match "Average" value ui.select(Math.round(db.avg)); // Update other text controls... $("#avg").text(db.avg); $("#votes").text(db.votes); // Show Stars $("#loader").hide(); $("#rat").show(); }, "json"); } });