<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>
2011/08/29
Register User Controls and Custom Controls in Web.config
2011/08/22
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"));
2011/08/19
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);
2011/08/16
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 );
2011/08/14
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> <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> <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>

- Remove update panel
- Create a user control wrapping update panel
2011/08/02
Test mail sender
import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import bruce.lib.swing.SwingWrench; import bruce.lib.util.DateTime; import bruce.lib.util.PostCenter; public class PostMan extends JFrame { JTextField txtIP; JTextField txtPort; JTextField txtAccount; JPasswordField txtPassword; JTextField txtSenderMail; JTextField txtSednerName; JTextField txtReceiverMail; JCheckBox cbIsHtml; JTextField txtSubject; JTextArea txtBody; JButton btnSubmit; JTextArea txtConsole; public PostMan() { setLayout(new GridBagLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("發信測試"); JPanel control = new JPanel(new GridBagLayout()); control.setMinimumSize(new Dimension(350, 100)); control.add(new JLabel("主機ip"), new GridBagConstraints(1, 1, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); control.add(txtIP = new JTextField("ms2.ccic.com.tw", 10), new GridBagConstraints(2, 1, 1, 1, 0.3, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 3, 3, 3), 1, 1)); control.add(new JLabel("通訊埠"), new GridBagConstraints(3, 1, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); control.add(txtPort = new JTextField("25", 3), new GridBagConstraints(4, 1, 1, 1, 0.3, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 3, 3, 3), 1, 1)); control.add(new JLabel("帳號"), new GridBagConstraints(1, 2, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); control.add(txtAccount = new JTextField("gp_report", 10), new GridBagConstraints(2, 2, 1, 1, 0.3, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 3, 3, 3), 1, 1)); control.add(new JLabel("密碼"), new GridBagConstraints(3, 2, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); control.add(txtPassword = new JPasswordField("29952666", 10), new GridBagConstraints(4, 2, 1, 1, 0.3, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 3, 3, 3), 1, 1)); control.add(new JLabel("寄件人名稱"), new GridBagConstraints(1, 3, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); control.add(txtSednerName = new JTextField("MES系統訊息", 10), new GridBagConstraints(2, 3, 1, 1, 0.3, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 3, 3, 3), 1, 1)); control.add(new JLabel("寄件人mail"), new GridBagConstraints(3, 3, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); control.add(txtSenderMail = new JTextField("gp_report@ccic.com.tw", 10), new GridBagConstraints(4, 3, 1, 1, 0.3, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 3, 3, 3), 1, 1)); control.add(new JLabel("收件人"), new GridBagConstraints(1, 4, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); control.add(txtReceiverMail = new JTextField("", 10), new GridBagConstraints(2, 4, 3, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 3, 3, 3), 1, 1)); control.add(new JLabel("html格式"), new GridBagConstraints(1, 5, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); control.add(cbIsHtml = new JCheckBox(), new GridBagConstraints(2, 5, 3, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); control.add(new JLabel("主旨"), new GridBagConstraints(1, 6, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); control.add(txtSubject = new JTextField("", 10), new GridBagConstraints(2, 6, 3, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(3, 3, 3, 3), 1, 1)); control.add(new JScrollPane(txtBody = new JTextArea()), new GridBagConstraints(1, 7, 4, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(3, 3, 3, 3), 1, 1)); add(control, new GridBagConstraints(1, 1, 1, 2, 0, 1, GridBagConstraints.EAST, GridBagConstraints.VERTICAL, new Insets(3, 3, 3, 3), 1, 1)); add(new JLabel("LOG"), new GridBagConstraints(2, 1, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); add(btnSubmit = new JButton("發送"), new GridBagConstraints(3, 1, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(3, 3, 3, 3), 1, 1)); add(new JScrollPane(txtConsole = new JTextArea()), new GridBagConstraints(2, 2, 2, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(3, 3, 3, 3), 1, 1)); btnSubmit.addActionListener(btnSubmit_Click); // redirect console System.setOut(new PrintStream(new OutputStream() { StringBuffer buffer = new StringBuffer(); @Override public void write(int b) throws IOException { switch (b) { case '\n': txtConsole.append(buffer.toString() + System.getProperty("line.separator")); buffer.delete(0, buffer.length() - 1); break; default: buffer.append((char) b); break; } } })); setSize(600, 400); SwingWrench.setLocationCenter(this); } private ActionListener btnSubmit_Click = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { System.out.printf("==========Try sending mail at %s==========%n", DateTime.now().toString("yyyy-MM-dd HH:mm:ss")); PostCenter<PostCenter> pc = new PostCenter<PostCenter>(); pc.init(txtIP.getText().trim(), Integer.parseInt(txtPort.getText().trim()), true, txtAccount.getText().trim(), txtPassword.getText().trim()); pc.setDebug(true); pc.setDebugOut(System.out); pc.setEncoding("UTF-8"); if (txtSednerName.getText().trim().length() == 0) pc.setSender(txtSenderMail.getText().trim()); else pc.setSender(txtSenderMail.getText().trim(), txtSednerName.getText().trim()); String[] receivers = txtReceiverMail.getText().replaceAll("\\s", "").replaceAll(",", ";").split(";"); for (String s : receivers) { pc.addReceiver(s); } pc.send(txtSubject.getText(), txtBody.getText(), cbIsHtml.isSelected()); } catch (Exception ex) { ex.printStackTrace(System.out); } System.out.println(); System.out.println(); System.out.println(); } }; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new PostMan().setVisible(true); } }