Popular Posts
Translating 1.3 <html> <head>     <title>Translating 1.1</title>     <meta http-equiv="content-type" content="text... vi hot key guide 第一部份:一般模式可用的按鈕說明,游標移動、複製貼上、搜尋取代等 移動游標的方法 h 或 向左方向鍵(←) 游標向左移動一個字元 j 或 向下方向鍵(↓) 游標向下移動一個字元 k 或 向上方向鍵(↑) 游標向上移動一個字元 l 或 向右方向鍵(→) 游標... SwiXml SwiX ml , is a small GUI generating engine for Java applications and applets. Graphical User Interfaces are described in XML documents that ...
Stats
Register User Controls and Custom Controls in Web.config
<system.web>
    <pages>
        <controls>
            <add tagPrefix="scottgu" src="~/Controls/Header.ascx" tagName="header"/>
            <add tagPrefix="scottgu" src="~/Controls/Footer.ascx" tagName="footer"/>
            <add tagPrefix="ControlVendor" assembly="ControlVendorAssembly"/>
        </controls>
    </pages>
</system.web>
Parse query string
Uri url = new Uri("http://www.google.com.tw/search?sourceid=chrome&ie=UTF-8&q=uri");

System.Collections.Specialized.NameValueCollection queryString
    = System.Web.HttpUtility.ParseQueryString(url.Query);

Console.WriteLine(queryString.Get("sourceid"));
Console.WriteLine(queryString.Get("ie"));
script path in master page
use script manager (script will appear in body section)
<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/jquery.js" />
    </Scripts>
</asp:ScriptManager>
use ResolveClientUrl method
<script type="text/javascript" src="<%= Page.ResolveClientUrl("~/jquery.js") %>"></script>
asp.net form validate
// 確認更新
function confirmUpdate(
    confirmMessage, /* 確認訊息 */
    validateGroup, /* validate group*/
    fn /* 自訂欄位檢查function */
) {
    if ('undefined' != typeof (tinyMCE)) tinyMCE.triggerSave(); // 觸發tinyMCE儲存值
    if ('undefined' != typeof (validateGroup)) validateGroup = null;
    if ('function' != typeof (fn)) fn = function () { return true; }  // 自訂驗證的function, 若無則回傳true
    if ('function' != typeof (Page_ClientValidate)) var Page_ClientValidate = function (group) { return true; } // validate control驗證
    if ($(document.forms[0]).valid2() && Page_ClientValidate(validateGroup)) {
        return fn() && confirm(confirmMessage);
    } else {
        return false;
    }
}
Retire value from tinyMCE when jQuery validate valid() invoked
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="superspace.usercontrols.WebForm2" ValidateRequest="false" %>

<!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 runat="server">
    <title>tinyMCE + jQuery validate</title>
    <!-- jQuery -->
    <script src="<%=VirtualPathUtility.ToAbsolute("~/")%>js/jquery-1.6.2.min.js" type="text/javascript"></script>
    <!-- jQuery validate + metadata -->
    <script src="<%=VirtualPathUtility.ToAbsolute("~/")%>js/jquery.validate/jquery.metadata.min.js" type="text/javascript"></script>
    <script src="<%=VirtualPathUtility.ToAbsolute("~/")%>js/jquery.validate/jquery.validate.min.js" type="text/javascript"></script>
    <script src="<%=VirtualPathUtility.ToAbsolute("~/")%>js/jquery.validate/jquery.validate.ext.min.js" type="text/javascript"></script>
    <!-- tinyMCE Editor -->
    <script src="<%=VirtualPathUtility.ToAbsolute("~/")%>js/tiny_mce/tiny_mce.js" type="text/javascript"></script>
    <script src="<%=VirtualPathUtility.ToAbsolute("~/")%>js/tiny_mce/jquery.tinymce.js" type="text/javascript"></script>
    <style type="text/css">
        body
        {
            font-size: smaller;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            $('.txtContent').tinymce({
                theme: "advanced",
                language: "zh",
                theme_advanced_toolbar_location: "top",
                theme_advanced_toolbar_align: "left",
                theme_advanced_statusbar_location: "bottom",
                theme_advanced_resizing: true
            });
            $(document.forms).validate();
        });
        function confirmUpdate() {
            if (typeof (tinyMCE) != 'undefined') tinyMCE.triggerSave();
            if (!$(document.forms).valid()) return false;
            return true;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <h3>
        Force tinyMCE editor to save content to control, avoid validate error when valid() has been invoked;</h3>
    <table border="0">
        <tr>
            <td>
                <b style="color: Red;">*</b>標題
            </td>
            <td>
                <asp:TextBox ID="txtTitle" runat="server" CssClass="{required:true,messages:{required:'請填寫標題!'}}" />
            </td>
        </tr>
        <tr>
            <td valign="top">
                <b style="color: Red;">*</b>內容
            </td>
            <td>
                <asp:TextBox ID="txtContent" runat="server" TextMode="MultiLine" Width="100%" Rows="15" CssClass="txtContent {required:true,messages:{required:'請填寫內容!'}}" />
            </td>
        </tr>
        <tr>
            <td align="center" colspan="2">
                <asp:Button ID="btnSubmit" runat="server" Text="儲存" OnClientClick="return confirmUpdate();" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
jQuery validator: focus invalid field when calling valid()
/*
 * 在validate呼叫valid()驗證方法式, 加上focusInValid的動件
 */
(function($) {
    $.extend($.fn, {
        valid2 : function() {
            var valid = true;
            var validator;
            if ($(this[0]).is('form')) {
                validator = this.validate();
                valid = this.validate().form();
            } else {
                validator = $(this[0].form).validate();
                this.each(function() {
                    valid &= validator.element(this);
                });
            }
            if (!valid)
                validator.focusInvalid();
            return valid;
        }
    });

    // 新增一個 regex 的驗證方式
    $.validator.methods.regex = function(value, element, param) {
        return this.optional(element) || ((typeof(param) == 'function' && typeof(param.test) == 'function') ? param.test(value) : new RegExp(param).test(value));
    };
    $.validator.messages.regex = 'Please enter a valid value.';
})(jQuery);
Add a event to Outlook calendar dymatically
protected void btnAddEventToOutlook_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.ics", HttpUtility.UrlEncode(EventName, Response.HeaderEncoding)));

    Response.Write(string.Format(@"BEGIN:VCALENDAR
METHOD:PUBLISH
PRODID:-//{0}//NONSGML iCalcreator 2.6//ZH_TW
VERSION:2.0
X-WR-CALNAME;LANGUAGE=zh_tw:有 {1} 筆相關活動
BEGIN:VEVENT
UID:{2}
DTSTAMP:{3:yyyyMMddTHHmmss}Z
DESCRIPTION;LANGUAGE=zh_tw:{4}
DTSTART;TZID=TAIWAN:{5:yyyyMMddTHHmmss}
DTEND;TZID=TAIWAN:{6:yyyyMMddTHHmmss}
LOCATION;LANGUAGE=zh_tw:{7}
SUMMARY;LANGUAGE=zh_tw:{8}
URL;VALUE=URI:{9}
END:VEVENT
END:VCALENDAR",
        Request.Url.Host,
        PlaceCount,
        Request.QueryString["oid"],
        DateTime.Now,
        Description,
        Convert.ToDateTime(FromDate),
        Convert.ToDateTime(ToDate),
        Location,
        EventName,
        Request.Url));
    Response.End();
}
about ics file
Add a event to Google Calendar dynamically
hlGoogle.NavigateUrl = string.Format(
    "https://www.google.com/calendar/render?action=TEMPLATE&text={0}&dates={1:yyyyMMddTHHmmss}/{2:yyyyMMddTHHmmss}&sprop=website:{3}&location={4}&details={5}",
    EventName,
    Convert.ToDateTime(FromDate),
    Convert.ToDateTime(ToDate),
    Request.Url.Host,
    Location,
    Details
);
ObjectDataSource
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ObjectDataSourceSample.aspx.cs"
    Inherits="superspace.control.info.ObjectDataSourceSample" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:HiddenField ID="hdnContentId" runat="server" />
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
            DeleteMethod="Delete"
            InsertMethod="Insert"
            SelectMethod="Select"
            UpdateMethod="Update"
            OldValuesParameterFormatString="{0}"
            TypeName="SuperspaceLib.VoteOption">
            <DeleteParameters>
                <asp:Parameter Name="ContentId" Type="String" />
                <asp:Parameter Name="OptionID" Type="String" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="ContentId" Type="String" />
                <asp:Parameter Name="OptionID" Type="String" />
                <asp:Parameter Name="OptionName" Type="String" />
            </InsertParameters>
            <SelectParameters>
                <asp:ControlParameter ControlID="hdnContentId" Name="ContentId" PropertyName="Value"
                    Type="String" />
            </SelectParameters>
            <UpdateParameters>
                <asp:Parameter Name="ContentId" Type="String" />
                <asp:Parameter Name="OptionID" Type="String" />
                <asp:Parameter Name="OptionName" Type="String" />
            </UpdateParameters>
        </asp:ObjectDataSource>
        <asp:TextBox ID="txtVoteOption" runat="server" MaxLength="50" Style="width: 100%;" />
        <asp:Button ID="btnAddOption" runat="server" Text="新增" OnClick="btnAddOption_Click" />
        <asp:GridView ID="gvOptions" runat="server" AutoGenerateColumns="False" GridLines="None"
            ShowHeader="False" DataKeyNames="ContentId,OptionID" EnableModelValidation="True"
            DataSourceID="ObjectDataSource1">
            <Columns>
                <asp:BoundField DataField="OptionName" HeaderText="OptionName" SortExpression="OptionName" />
                <asp:TemplateField ShowHeader="False">
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
                            Text="編輯"></asp:LinkButton>
                        &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete"
                            Text="刪除"></asp:LinkButton>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
                            Text="更新"></asp:LinkButton>
                        &nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
                            Text="取消"></asp:LinkButton>
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Web;

namespace SuperspaceLib
{
    [DataObject(true)]
    public class VoteOption
    {
        [DataObjectMethod(DataObjectMethodType.Select)]
        public DataTable Select(string ContentId)
        {
            DataTable dtOption = null;
            if (HttpContext.Current.Session[ContentId] == null)
            {
                dtOption = new DataTable("VoteOption");
                dtOption.Columns.Add("ContentId");
                dtOption.Columns.Add("OptionID");
                dtOption.Columns.Add("OptionName");
            }
            else
            {
                dtOption = HttpContext.Current.Session[ContentId] as DataTable;
            }
            return dtOption;
        }

        [DataObjectMethod(DataObjectMethodType.Update)]
        public int Update(string ContentId, string OptionID, string OptionName)
        {
            DataTable dtOption = null;
            if (HttpContext.Current.Session[ContentId] == null)
            {
                dtOption = new DataTable("VoteOption");
                dtOption.Columns.Add("ContentId");
                dtOption.Columns.Add("OptionID");
                dtOption.Columns.Add("OptionName");
            }
            else
            {
                dtOption = HttpContext.Current.Session[ContentId] as DataTable;
            }

            int afftected = 0;
            foreach (DataRow row in dtOption.Rows)
            {
                if (row["ContentId"].Equals(ContentId) && row["OptionID"].Equals(OptionID))
                {
                    row["OptionName"] = OptionName;
                    afftected++;
                }
            }
            HttpContext.Current.Session[ContentId] = dtOption;

            return afftected;
        }

        [DataObjectMethod(DataObjectMethodType.Insert)]
        public int Insert(string ContentId, string OptionID, string OptionName)
        {
            DataTable dtOption = null;
            if (HttpContext.Current.Session[ContentId] == null)
            {
                dtOption = new DataTable("VoteOption");
                dtOption.Columns.Add("ContentId");
                dtOption.Columns.Add("OptionID");
                dtOption.Columns.Add("OptionName");
            }
            else
            {
                dtOption = HttpContext.Current.Session[ContentId] as DataTable;
            }

            DataRow row = dtOption.Rows.Add(ContentId, OptionID, OptionName);
            HttpContext.Current.Session[ContentId] = dtOption;

            return 1;
        }

        [DataObjectMethod(DataObjectMethodType.Delete)]
        public int Delete(string ContentId, string OptionID)
        {
            DataTable dtOption = null;
            if (HttpContext.Current.Session[ContentId] == null)
            {
                dtOption = new DataTable("VoteOption");
                dtOption.Columns.Add("ContentId");
                dtOption.Columns.Add("OptionID");
                dtOption.Columns.Add("OptionName");
            }
            else
            {
                dtOption = HttpContext.Current.Session[ContentId] as DataTable;
            }

            int afftected = 0;
            for (int i = dtOption.Rows.Count - 1; i >= 0; i--)
            {
                DataRow row = dtOption.Rows[i];
                if (row["ContentId"].Equals(ContentId) && row["OptionID"].Equals(OptionID))
                {
                    dtOption.Rows.Remove(row);
                    afftected++;
                }
            }
            HttpContext.Current.Session[ContentId] = dtOption;

            return afftected;
        }
    }
}
HINT:
  • OldValuesParameterFormatString="{0}" means parameter will take value of old value by this name format
  • Parameter name must compeletly match the param of method
UpdatePanel in Formview occurs duplicate component id error
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="InnerUpdatePanel.aspx.cs"
    Inherits="superspace.control.info.InnerUpdatePanel" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FormView ID="fvVote" runat="server" DefaultMode="Insert">
            <InsertItemTemplate>
                <asp:TextBox ID="txtVoteName" runat="server" />
                <asp:UpdatePanel ID="upOption" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>
                        <table border="0" width="100%">
                            <tr>
                                <td>
                                    <asp:TextBox ID="txtOption" runat="server" />
                                </td>
                                <td>
                                    <asp:Button ID="btnAddOption" runat="server" Text="新增選項" />
                                </td>
                            </tr>
                        </table>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </InsertItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="txtVoteName" runat="server" />
                <asp:UpdatePanel ID="upOption" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>
                        <table border="0" width="100%">
                            <tr>
                                <td>
                                    <asp:TextBox ID="txtOption" runat="server" />
                                </td>
                                <td>
                                    <asp:Button ID="btnAddOption" runat="server" Text="新增選項" />
                                </td>
                            </tr>
                        </table>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </EditItemTemplate>
        </asp:FormView>
    </div>
    </form>
</body>
</html>
Solutions:
  1. Remove update panel
  2. Create a user control wrapping update panel