2012年11月14日 星期三

透過jQuery 呼叫webservice 取得datatable內容

專案參考Newtonsoft.Json.dll

server
====
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string GetScheduledActivity(string id)
{
DataTable dt = new DataTable();
...
return JsonConvert.SerializeObject(dt, Formatting.Indented);
}

client
====
 $.ajax({
                type: "POST",
                url: "webservice1.asmx/GetScheduledActivity",
                contentType: "application/json; charset=utf-8",
                data: "{'id':'" + id + "'}",
                dataType: "json",
                success: function (jsonObj) {
                    var objdata = $.parseJSON(jsonObj.d);
                    // 只有一筆資料的用法
                    // objdata[0].欄位名稱
                    // 多筆資料的用法
                    $.each(objdata, function (i, val) {
                    // val.欄位名稱
                    });
                }
            });  

解決事件函數搭配資料繫結時單引號及雙引號混合所引發的問題

外圍用單引號,裡面的雙引號字元加上反斜線,如
onclick='<%#Eval("id","設定排定活動相關選項(\"{0}\");return false;")%>'

2012年11月8日 星期四

server 事件未觸發?

使用AjaxControlToolkit CascadingDropDown之類或其他非postback方式動態改變control 內容,需加入 EnableEventValidation="false" 於 <%@ Page ,以避免 server 誤認資料被竄改而拒絕執行事件函數

2012年10月23日 星期二

ASP.NET 提示使用者下載檔案

Response.Clear()
Response.Buffer = True
Response.HeaderEncoding = System.Text.Encoding.GetEncoding("big5")
Response.AppendHeader("Content-Disposition", "attachment;filename=" + "交通住宿名單.xml")
Response.ContentType = "application/vnd.ms-excel"
Response.Write(filestream)
Response.End()

SQL SERVER 2005 如何於查詢結果加上序號欄位

select rank() OVER (ORDER BY a.au_lname, a.au_fname) as rank, a.au_lname, a.au_fname from authors a order by rank

透過 jQuery 呼叫 code-behind webmethod


於網頁中加入以下函數
====
function CallPageMethod(methodName, onSuccess) {
            var args = '';
            var l = arguments.length;
            if (l > 2) {
                for (var i = 2; i < l - 1; i += 2) {
                    if (args.length != 0) args += ',';
                    args += '"' + arguments[i] + '":"' + arguments[i + 1] + '"';
                }
            }
            var loc = window.location.href;
            loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "default.aspx" : loc;
            $.ajax({
                type: "POST",
                url: loc + "/" + methodName,
                data: "{" + args + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: onSuccess
            });
        }

呼叫方式
====
CallPageMethod([webmethod name], [成功時呼叫的函數名稱], [參數名稱1], [參數值1],[參數名稱2], [參數值2],...);

function [成功時呼叫的函數名稱](response) {
            //do something, response.d=webmethod return value
        }

去除文字方塊前後空白


$("input[type=text]").focusout(function () { $(this).val($.trim($(this).val())); });

2012年10月6日 星期六

使用EPPlus 時如何設定頁首頁尾

設定頁首中間文字並指定為標楷體、粗體、大小為16
====
ws.HeaderFooter.EvenHeader.CenteredText = ws.HeaderFooter.OddHeader.CenteredText = "&\"標楷體,Bold\"&16這是頁首中間文字"; 

設定頁尾右邊加入日期、時間、目前頁數、總頁數
====
ws.HeaderFooter.EvenFooter.RightAlignedText = ws.HeaderFooter.OddFooter.RightAlignedText = "{0}  {1}  {2}/{3}".FormatString(ExcelHeaderFooter.CurrentDate,ExcelHeaderFooter.CurrentTime,ExcelHeaderFooter.PageNumber,ExcelHeaderFooter.NumberOfPages);

2012年9月11日 星期二

使用updatepanel 時確保每次postback 都會呼叫函數的寫法


$(document).ready(function () {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            prm.add_pageLoaded(function () {
               ......
            });
            prm.add_initializeRequest(...);
            prm.add_endRequest(...);
        });


頁面第一次進入時,會首先激發add_pageLoaded事件
異步提交時,事件的激發順序如下:
add_initializeRequest
add_beginRequest
add_pageLoading
add_pageLoaded
add_endRequest
add_pageLoaded

2012年8月27日 星期一

Lambda Expressions 範例

事件函數用法
(aComboBox as ComboBox).SelectionChanged += new SelectionChangedEventHandler((sender, e) => { ... });

2012年8月24日 星期五

LINQ查詢語法

select left join 回傳某個物件並依據關聯物件來設定某些屬性值
====
(from a in newlist
join b in db基本.產品資料檢視 on a.產品序號 equals b.產品編號 into b1
from b in b1.DefaultIfEmpty()
select new { a, b }).Select(a =>
                          {
                              a.a.產品名稱 = a.b == null ? a.a.產品名稱 : a.b.產品名稱;
                              return a.a;
                          })
※因為是left join,要使用關聯物件的屬性前需要先判斷物件是否為null 避免nullexception

equals 多個屬性
====
寫法有兩種,第一種寫法若有錯誤則必須改用第二種(原因不明)
 1. new { 本次盤點.產品編號, 本次盤點.盤點單.倉庫 } equals new { 期初盤點.產品編號, 期初盤點.盤點單.倉庫 }
 2. new { a=本次盤點.產品編號, b=本次盤點.盤點單.倉庫 } equals new { a=期初盤點.產品編號, b=期初盤點.盤點單.倉庫 }

group by  多個屬性
====
.GroupBy(a => new { a.銷貨資料.客戶編號, a.產品編號 })

order by 多個屬性
====
.OrderBy(a =>a.客戶編號).ThenBy(a=>a.產品編碼).ThenBy(a=>a.產品序號)

List
====
.Exists(p => ...) // 判斷是否存在特定物件
.Find(p => ...) // 尋找第一個特定物件

IEnumerable<T>
====
.Where(row => ...) // 尋找符合某些條件的row
(from a in 採購單明細Model.取得採購單明細列表(門市代號,採購單號) select a.交貨日期).Distinct() // 找出某個屬性不重複的資料並取出屬性值
.GroupBy(a => a.姓名).Select(a => a.First()) // 找出某個屬性不重複的資料並取出相同群組中第一個物件

從 IEnumerable 轉為 IEnumerable<T> 以便使用 .Where()
====
.Cast(<T>).Where(...)

2012年8月23日 星期四

2012年7月11日 星期三

網站地圖結合角色動態顯示選單


1. 登入頁認證通過時建立票證並加入cookie
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddHours(8), false, [角色名稱(多個則以逗號隔開)]);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie([cookie名稱], encryptedTicket);
Response.Cookies.Add(authCookie);

2. Global.asax 認證通過後取得cookie 中的票證並建立GenericPrincipal存入Context.User
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
        if (Context.User == null) return;
        if (!Context.User.Identity.IsAuthenticated) return;
     
        string cookieName = [cookie名稱];
        if (!Context.Request.Cookies.AllKeys.Contains(cookieName)) return;
        HttpCookie authCookie = Context.Request.Cookies[cookieName];
        FormsAuthenticationTicket authTicket = null;
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        string[] roles = authTicket.UserData.Split(new char[] { ',' });//如果有多個角色以逗號隔開則拆開
        FormsIdentity id = new FormsIdentity(authTicket);
        var principal = new System.Security.Principal.GenericPrincipal(id, roles);
        Context.User = principal;//存到HttpContext.User中
}

3. 網站地圖(web.sitemap)設定各節點可存取角色
<sitemap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
<sitemapnode roles="*" title="..."> <= 設定可以看到節點的角色,星號表示全部,若不設定則不會顯示
<sitemapnode description="..." title="..." url="..."> <= 包含網址的節點無法指定角色,會沒有作用
<sitemapnode description="..." title="..." url="...">
</sitemapnode>
</sitemapnode></sitemapnode></sitemap>

4. web.config 設定SiteMapProvider 及特定網頁可存取角色
  <sitemap defaultprovider="XmlSiteMapProvider" enabled="true">
      <providers>
        <add description="SiteMap provider which reads in .sitemap XML files." name="XmlSiteMapProvider" securitytrimmingenabled="true" sitemapfile="Web.sitemap" type="System.Web.XmlSiteMapProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
      </add></providers>
    </sitemap>

說明 : SiteMapProvider 加入 securityTrimmingEnabled="true" 的選項以啟用角色控制節點機制

  <location path="[網址]">
    <system.web>
      <authorization>
        <allow roles="[允許的角色]" />
        <deny users="*" />
      </authorization>
    </system.web>
  </location>

說明 : 針對網址節點若要控制某些角色才能存取則使用 location 來指派角色


5. 於主頁面加入選單控制項並結合SiteMapProvider,在此以 treeview 為例
<asp:TreeView ID="TreeView1" runat="server" DataSourceID="SiteMapDataSource1" ShowLines="True">
< /asp:TreeView>
< asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" SiteMapProvider="XmlSiteMapProvider" />


2012年6月7日 星期四

如何避免呼叫 Response.End、Response.Redirect 或 Server.Transfer 時遇到ThreadAbortException

•For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.

•For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:
  Response.Redirect ("nextpage.aspx", false);
If you use this workaround, the code that follows Response.Redirect is executed.

•For Server.Transfer, use the Server.Execute method instead.

來源

2012年5月29日 星期二

clickonce 應用程式無法正常安裝或執行

rundll32 %windir%\system32\dfshim.dll CleanOnlineAppCache
刪除此資料夾底下所有資料 %LocalAppData%\Apps\2.0

2012年4月26日 星期四

解決 textbox autopostback=true 造成 focus 跑掉的問題

答案在此

簡單 hardcode 版本 : Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {$('#" + box.ClientID + "').focus();});

2012年1月3日 星期二

固定ListView頂端列

1.移除 aspx 一列
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

2.用 div 包住 listview
<div style="overflow: auto; height:400px">

3.LayoutTemplate 第一個 tr 設定 style
<tr style="position:relative;top: expression(offsetParent.scrollTop); " >

Entity Framework 建立新物件並儲存後馬上取得關聯資料

使用 CreateProxy 建立物件,不要直接 new var newmodel = _contextXXX.CreateProxy<yyy>(); ... _contextXXX.yyy.Add(newmodel); await _contextXXX.SaveC...