2013年12月29日 星期日

HTML Removal 類別庫(移除Html標籤)

HTML Removal 類別庫(移除Html標籤)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// HtmlRemoval 的摘要描述
/// </summary>
using System;
using System.Text.RegularExpressions;

/// <summary>
/// Methods to remove HTML from strings.
/// </summary>
public static class HtmlRemoval
{
    /// <summary>
    /// Remove HTML from string with Regex.
    /// </summary>
    public static string StripTagsRegex(string source)
    {
        return Regex.Replace(source, "<.*?>", string.Empty);
    }

    /// <summary>
    /// Compiled regular expression for performance.
    /// </summary>
    static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);

    /// <summary>
    /// Remove HTML from string with compiled Regex.
    /// </summary>
    public static string StripTagsRegexCompiled(string source)
    {
        return _htmlRegex.Replace(source, string.Empty);
    }

    /// <summary>
    /// Remove HTML tags from string using char array.
    /// </summary>
    public static string StripTagsCharArray(string source)
    {
        char[] array = new char[source.Length];
        int arrayIndex = 0;
        bool inside = false;

        for (int i = 0; i < source.Length; i++)
        {
            char let = source[i];
            if (let == '<')
            {
                inside = true;
                continue;
            }
            if (let == '>')
            {
                inside = false;
                continue;
            }
            if (!inside)
            {
                array[arrayIndex] = let;
                arrayIndex++;
            }
        }
        return new string(array, 0, arrayIndex);
    }

    /// <summary>
    /// 尋找及取代 Visual C#.NET 中的 XML 檔案中的特殊字元
    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static string StripTagsRestore(string source)
    {
        string Rsource = source;
        try
        {
            Rsource = Rsource.Replace("&amp;", "&");
            Rsource = Rsource.Replace("&lt;", "<");
            Rsource = Rsource.Replace("&gt;", ">");
            Rsource = Rsource.Replace("&quto;", "\"");
            Rsource = Rsource.Replace("&apos;", "'");
        }
        catch (System.Exception)
        {
            //throw;
        }
        return Rsource;
    }
}

參考來源:不知名網友(年代久遠已追溯不到來源)

2013年11月25日 星期一

Select Into & Insert Into

Select Into & Insert Into

下列指令會先創建newTable欄位與sourceTable一致,再將sourceTable的資料全部複製到newTable, newTable事先必須不存在
--select * into newTable from sourceTable

下列指令會將sourceTale的資料全部複製到newTable, newTable事先必須存在, 兩者欄位必須相同
--Insert into newTable select * from sourceTable

2013年11月21日 星期四

CRM2011 Outlook Track

Microsoft Dynamics CRM 2011 Outlook Track

The owner of this queue does not have sufficient privileges to work with the queue.

Please go to settings=>customizations=>customize the system=>Entities=>Email, then uncheck "Automatically move records to the owner's default queue when a record is created or assigned", publish all customizations and try again.

Open the appropriate Security Role, Find Queue in the list and apply Read permissions



Reference: http://social.microsoft.com/Forums/en-US/b35ad118-ac41-4aab-8a08-969737bbff2b/outlook-tracking-error-the-owner-of-this-queue-does-not-have-sufficient-privileges-to-work-with?forum=crm

http://msdynamicswiki.com/2011/11/01/error-message-when-attempting-to-send-tracked-email-message-to-another-user-in-microsoft-dynamics-crm-2011/

2013年11月14日 星期四

EnableEventValidation

無效的回傳或回呼引數。已在組態中使用 <pages enableEventValidation="true"/> 或在網頁中使用 <%@ Page EnableEventValidation="true" %> 啟用事件驗證。基於安全性理由,這項功能驗證回傳或回呼引數是來自原本呈現它們的伺服器控制項。如果資料為有效並且是必須的,請使用 ClientScriptManager.RegisterForEventValidation 方法註冊回傳或回呼資料,以進行驗證

解決方法:
在.aspx的@Page標籤內加入一行EnableEventValidation="false"即可

HyperLink按右鍵執行Script

HyperLink按右鍵執行Script
















----------------------------------------------------------------------------------------------------
.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="tsHyperLink.aspx.cs" Inherits="Test_tsHyperLink" EnableEventValidation="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></title>
    <script language="javascript" type="text/javascript">

        function deleteFile(arg1) {
            if (confirm("Are you sure want to delete?")) {
                alert(arg1); //出現警示視窗
                window.open("/deletefile.aspx?filename=" + arg1); //開另一個新視窗
                __doPostBack('LinkButton1', '') //執行一個onClick / onChange Event //必須在<$@Page />加入EnableEventValidation="false"
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/default.aspx" >HyperLink按右鍵執行Script</asp:HyperLink><br />
        <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click" Visible="false">LinkButton</asp:LinkButton><br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>

----------------------------------------------------------------------------------------------------
.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test_tsHyperLink : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HyperLink hpl = (HyperLink)this.form1.FindControl("HyperLink1");
        hpl.Attributes["oncontextmenu"] = "deleteFile('test.xls')";

        //關閉form1內的右鍵功能,避免干擾
        this.form1.Attributes.Add("oncontextmenu", "return false");
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        // Do to...
        Label1.Text = "test";
    }
}

Panel區塊內防止右鍵

Panel區塊內防止右鍵

.aspx

<asp:Panel ID="pan_fileslist" runat="server">
</asp:Panel>


.cs

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            //防右鍵
            this.pan_fileslist.Attributes.Add("oncontextmenu", "return false");

            //防選取
            this.pan_fileslist.Attributes.Add("onSelectStart", "return false");
            this.pan_fileslist.Attributes.Add("onDragStart", "return false");
        }
        catch (Exception)
        {

            throw;
        }
    }

2013年11月11日 星期一

取得PostBack Control

取得PostBack Control

C#

public Control GetPostBackControl(Page page)
        {
            Control control = null;
            string ctrlname = page.Request.Params.Get("__EVENTTARGET");
            if (ctrlname != null && ctrlname != string.Empty)
            {
                control = page.FindControl(ctrlname);
            }
            else
            {
                foreach (string ctl in page.Request.Form)
                {
                    Control mycontrol = page.FindControl(ctl);
                    if (mycontrol is System.Web.UI.WebControls.Button)
                    {
                        control = mycontrol;
                        // This gives you ID of which button caused postback
                        Response.Write(mycontrol.ID);
                        break;
                    }
                }
            }
            return control;
        }


protected void Page_Load(object sender, EventArgs e)
{
            Control a = GetPostBackControl(this.Page);
}
Reference: http://www.codeproject.com/Questions/123490/_EVENTTARGET-empty

CuteEditor 上傳中文檔名

CuteEditor 上傳中文檔名

File name not supported!  Please keep the file name one word with no spaces or special characters.

1. Edit security policy file.

CuteSoft_Client\CuteEditor\Configuration\Security\Default.config

<security name="filenamePattern">^[a-zA-Z0-9\._\s-\#]+$</security>

Please change it to:

<security name="filenamePattern">^[a-zA-Z0-9\._\s-\u4e00-\u9fa5]+$</security>

2. or Programmatically define the image name filter

C#: Page_Load
Editor1.Setting["security:filenamePattern"]= "^[a-zA-Z0-9\._\s-\u4e00-\u9fa5]+$";

2013年11月1日 星期五

自訂檢查日期欄位格式

自訂檢查日期欄位格式

.aspx

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="送出" />
         <asp:CustomValidator ID="CustomValidator1" runat="server"
             ControlToValidate="TextBox1" ErrorMessage="CustomValidator"
             onservervalidate="CustomValidator1_ServerValidate" ValidateEmptyText="True"></asp:CustomValidator>
    </div>
    </form>


.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test_tsValidatorDate : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
     {
         if (CustomValidator1.IsValid)
         {
             Response.Write("送出成功!");
         }
     }
     protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
     {
         DateTime dt;

         if (string.IsNullOrEmpty(args.Value))
         {
             CustomValidator1.ErrorMessage = "該欄位必填";
             args.IsValid = false;
         }

         else if (DateTime.TryParseExact(args.Value, "yyyy/MM/dd", null,System.Globalization.DateTimeStyles.AllowWhiteSpaces, out dt) == false)
         {
             CustomValidator1.ErrorMessage = "日期格式為 yyyy/MM/dd";
             args.IsValid = false;
         }
         else
         {
             args.IsValid = true;
         }
     }
}

2013年10月31日 星期四

File.WriteAllBytes

File.WriteAllBytes

將存放在SQL2008的image型態欄位的檔案,轉成實體檔案
ps:以下程式在windows form測試

private void button1_Click(object sender, EventArgs e)
{
DataTable dt = ds.Tables["resultTable"];
DataRow dr = dt.rows[0];

File.WriteAllBytes(@"C:\" + dr["filename"].ToString(), (byte[])dr["data"]);
}

2013年10月30日 星期三

簡易AD驗証

簡易AD驗証


C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;

public partial class Test_tsLDAP : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// Button1 Event
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string a;
            a = isADauth("user1", "pass1");
            Response.Write(a.ToString());
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            //throw ex;
        }
       
    }

    /// <summary>
    /// AD驗証
    /// </summary>
    /// <param name="uid">帳號</param>
    /// <param name="passwd">密碼</param>
    /// <returns></returns>
    public static string isADauth(string uid, string passwd)
    {
        string authentic = "";
        try
        {
            DirectoryEntry entry = new DirectoryEntry("LDAP://DC01", uid, passwd);
            object nativeObject = entry.NativeObject;
            authentic = "LOGIN_SUCCESSFUL";
        }
        catch (DirectoryServicesCOMException dscom_ex)
        {
            //authentic = "LOGIN_FAILED";
            throw dscom_ex;
        }
        return authentic;
    }
}

2013年10月24日 星期四

擷取元件 (CLSID 為 {00024500-0000-0000-C000-000000000046}) 的 COM Class Factory 失敗

擷取元件 (CLSID {00024500-0000-0000-C000-000000000046}) COM Class Factory 失敗,因為發生下列錯誤: 80040154 類別未登錄 (發生例外狀況於 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
描述: 在執行目前 Web 要求的過程中發生未處理的例外狀況。請檢閱堆疊追蹤以取得錯誤的詳細資訊,以及在程式碼中產生的位置。

例外狀況詳細資訊: System.Runtime.InteropServices.COMException: 擷取元件 (CLSID {00024500-0000-0000-C000-000000000046}) COM Class Factory 失敗,因為發生下列錯誤: 80040154 類別未登錄 (發生例外狀況於 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

以下嘗試的解決方式:

1. Start->run->regedit 
Find 00024500-0000-0000-C000-000000000046 ->資料夾按右鍵內容,安全性加入NETWORK SERVICE給予權限,找遍所有00024500-0000-0000-C000-000000000046相關的機碼全部設了Network service IIS_IUSRS完全控制的權限,結果失敗

2. Start -> run -> DCOMCNFG
來想照著以上說明去「元件服務」設定DCOM元件,竟然沒有Microsoft Excel Application。因為Excel32位元,64位元的作業系統看不到該元件,結果失敗

3.web.config 加入
<configuration>
<system.web>
<identity impersonate="true" userName="adminUser" password="adminUserPassword" />
帳號密碼請先使用本機administrator帳號試比較沒問題
若是 Server 2008 x64 請建立下述資料夾
C:\Windows\SysWOW64\config\systemprofile\Desktop
若是 Server 2008 x86 請建立下述資料夾
C:\Windows\System32\config\systemprofile\Desktop
以上的設定。結果成功

4. Start -> run -> mmc comexp.msc /32
元件服務 -> 電腦 ->我的電腦 ->DCOM設定 ->Microsoft Excel Application ->安全性->啟動和啟用權限&存取權限->自訂權限加入Network service與IIS_IUSRS完全控制權限, 識別身份用互動式使用者。結果成功

2013年10月23日 星期三

Could not load file or assembly 'Microsoft.ReportViewer.ProcessingObjectModel

無法載入檔案或組件 'Microsoft.ReportViewer.ProcessingObjectModel, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

Could not load file or assembly 'Microsoft.ReportViewer.ProcessingObjectModel, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

Install the following:
Microsoft Report Viewer 2010 SP1 Redistributable Package
Microsoft Report Viewer Redistributable 2010 SP1 Language Pack

http://www.microsoft.com/en-us/download/details.aspx?id=6610
http://www.microsoft.com/en-us/download/details.aspx?id=24932

無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組

無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組。
描述: 在執行目前 Web 要求的過程中發生未處理的例外狀況。請檢閱堆疊追蹤以取得錯誤的詳細資訊,以及在程式碼中產生的位置。

例外狀況詳細資訊: System.IO.FileNotFoundException: 無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組。

原始程式錯誤:
在執行目前 Web 要求期間,產生未處理的例外狀況。如需有關例外狀況來源與位置的資訊,可以使用下列的例外狀況堆疊追蹤取得。

堆疊追蹤:

[FileNotFoundException: 無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組。]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +34
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +16
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: 無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組。]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +752
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +218
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +91
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +258
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +135
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): 無法載入檔案或組件 'sapnco_utils.DLL' 或其相依性的其中之一。 找不到指定的模組。]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9874840
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254




版本資訊: Microsoft .NET Framework 版本:4.0.30319; ASP.NET 版本:4.0.30319.18055


Please try:

1.Install Microsoft Visual C++ 2010 Redistributable Package (x86)  and 
Microsoft Visual C++ 2010 Redistributable Package (x64) 

2. IIS Setting / Application Pool / Advanced Settings / Enable 32-Bit Applications = True



2013年10月17日 星期四

Exchange Service Binding

使用Exchange Service Send Mail

C#

public void SendMessage(ExchangeServiceBinding ewsServiceBinding, ItemIdType iiCreateItemid)
        {
            SendItemType siSendItem = new SendItemType();
            siSendItem.ItemIds = new BaseItemIdType[1];
            siSendItem.SavedItemFolderId = new TargetFolderIdType();
            DistinguishedFolderIdType siSentItemsFolder = new DistinguishedFolderIdType();
            siSentItemsFolder.Id = DistinguishedFolderIdNameType.sentitems;
            siSendItem.SavedItemFolderId.Item = siSentItemsFolder;
            siSendItem.SaveItemToFolder = true;


            siSendItem.ItemIds[0] = (BaseItemIdType)iiCreateItemid;
            SendItemResponseType srSendItemReponseMessage = ewsServiceBinding.SendItem(siSendItem);
            if (srSendItemReponseMessage.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Error)
            {
                Console.WriteLine("Error Occured");
                Console.WriteLine(srSendItemReponseMessage.ResponseMessages.Items[0].MessageText);
            }
            else
            {
                Console.WriteLine("Message Sent");
            }
        }

        public string SendMail_ex2007(String Sender, String reciver, String subject, String content)
        {

            ExchangeServiceBinding esb = new ExchangeServiceBinding();
            esb.Url = "https://mail.xxx.com/EWS/Exchange.asmx";
            servicea = esb;
            //System.Net.ServicePointManager.ServerCertificateValidationCallback =
            System.Net.ServicePointManager.ServerCertificateValidationCallback = (Object obj, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) => true;
            esb.Credentials = new NetworkCredential("USERNAME", "PASSWORD", "SMTP");
            MessageType emailMessage = new MessageType();
            emailMessage.From = new SingleRecipientType();
            //set up a single sender
            //寄件者
            emailMessage.From.Item = new EmailAddressType();
            emailMessage.From.Item.EmailAddress = Sender;
            //標題
            emailMessage.Subject = subject;
            emailMessage.Body = new Microsoft.ServiceModel.Channels.Mail.ExchangeWebService.Exchange2007.BodyType();
            emailMessage.Body.BodyType1 = BodyTypeType.Text;
            //本文
            emailMessage.Body.BodyType1 = BodyTypeType.HTML;
            emailMessage.Body.Value = content;
            //將email寄出
            emailMessage.Sender = new SingleRecipientType();
            emailMessage.Sender.Item = new EmailAddressType();
            emailMessage.Sender.Item.EmailAddress = Sender;
            emailMessage.ToRecipients = new EmailAddressType[1];
            emailMessage.ToRecipients[0] = new EmailAddressType();
            emailMessage.ToRecipients[0].EmailAddress = reciver;
            emailMessage.Sensitivity = SensitivityChoicesType.Normal;
            //建立附件
            ItemIdType iiCreateItemid = CreateDraftMessage(esb, emailMessage);
            //iiCreateItemid = CreateAttachment(esb, iiCreateItemid);
            SendMessage(esb, iiCreateItemid);
            return "sendok";
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
SendMail_ex2007("SenderName", "xxx@gmail.com", "smtp.xxx.com", "subject", "Content");
        }

非同步執行緒寄送郵件

非同步執行緒寄送郵件

C#

#region 非同步執行緒寄送郵件
 
    //1-1.建立非同步委派簽章
    delegate string AsyncSendMail();
    //1-2.建立了一個具有IAsyncResult參數的Callback方法
    void EndCallback(IAsyncResult ar)
    {
        AsyncSendMail asynDelegate = ar.AsyncState as AsyncSendMail;
    }
    //1-3.建立執行主體程式
    string SendMailAsync()
    {
        try
        {
            #region 寄送郵件執行緒-Start
            //宣告執行緒
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Reset();
            //開始執行緒
            sw.Start();

            //發送郵件
            System.Net.Mail.MailMessage message = new MailMessage();
            SmtpClient smtp = new SmtpClient();
            message.From = new MailAddress(strFrom);
            message.To.Add(new MailAddress(strTo));
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            message.Subject = "Test";
            message.Body = strBody;
            smtp.Host = "192.168.1.1";
            smtp.Port = "25";
            smtp.Send(message);

            //停止執行緒
            sw.Stop();

            #endregion  執行緒-End
            return "successful";
        }
        catch (Exception)
        {
            return "failed";
            //throw;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        //1-4.實體化委派
        AsyncSendMail asynDelegate = new AsyncSendMail(SendMailAsync);
        //1-5.開始非同步作業
        asynDelegate.BeginInvoke(EndCallback, asynDelegate);

    }

#endregion 非同步執行緒寄送郵件

HTTP Error 404.0 - Not Found

Create New IIS Web Site HTTP Error 404.0 - Not Found
解決方法:Application Pools / Advanced Settings / Enable 32-Bit Applications = true
-------------------------------

HTTP Error 404.0 - Not Found

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.



Please try the next...




2013年9月10日 星期二

TSQL Cursor Example 語法

TSQL Cursor Example 語法

--定義變數
DECLARE @oid varchar(50),
        @ono varchar(18),
        @s_company nvarchar(50),
        @company nvarchar(50),
        @sql varchar(max)

--設定變數初始值
SET @oid = ''
SET @ono = ''
SET @s_company= ''
SET @company = ''
SET @sql = ''

--宣告Cursor for 迴圈
DECLARE rma_cursor CURSOR FOR

--SQL指令
SELECT oid,ono,s_company,company FROM dbo.t_RMA_Request

--開始執行 cursor
OPEN rma_cursor

--將第一筆資料放入變數
FETCH NEXT FROM rma_cursor INTO @oid,@ono,@s_company,@company

--檢查是否有讀取到資料; WHILE用來處理迴圈,當為true時則進入迴圈執行
WHILE @@FETCH_STATUS=0
BEGIN --開始

--迴圈內要執行的程序
IF @s_company <> ''
BEGIN
--組合@sql字串變數
SET @sql  = @sql + ';' + 'update t_RMA_Request_Item set s_company=''' + @s_company + ''' where opid=''' + @oid + ''''
--實際執行另一段內部SQL指令
UPDATE t_RMA_Request_Item SET s_company=@s_company WHERE opid=@oid
END
ELSE
BEGIN
--組合@sql字串變數
SET @sql  = @sql + ';' + 'update t_RMA_Request_Item set s_company=''' + @company + ''' where opid=''' + @oid + ''''
--實際執行另一段內部SQL指令
UPDATE t_RMA_Request_Item SET s_company=@company WHERE opid=@oid
END

--將下一筆資料放入變數
FETCH NEXT FROM rma_cursor INTO @oid,@ono,@s_company,@company
END --結束

--關閉Cursor與參數的關聯
CLOSE rma_cursor

--將Cursor物件從記憶體移除
DEALLOCATE rma_cursor

--列印字串組合結果
PRINT @sql

2013年9月9日 星期一

C# ASP.NET form1 的 Default Button

C# ASP.NET form1 的 Default Button


Sample 1
HTML:
<body>
    <form id="form1" runat="server" defaultbutton="Button2">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Button" /><br />
        <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" /><br />
    </div>
    </form>
</body>

C#:
public partial class Test_tsDefaultButton : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this, typeof(string), "Location", "alert(\"Butonn2\");", true);
    }
}

Sample 2
HTML:
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Button" /><br />
        <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" /><br />
    </div>
    </form>
</body>

C#:
public partial class Test_tsDefaultButton : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        #region Default Button
        Button btn = (Button)this.form1.FindControl("Button2");
        this.Form.DefaultButton = btn.UniqueID;
        #endregion
        #region Default Button UserControl Sample
        //Button  btn  =  (Button)UserControl1.FindControl("Button2");
        //this.form1.DefaultButton = btn.UniqueID;
        #endregion
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this, typeof(string), "Location", "alert(\"Butonn2\");", true);
    }
}

2013年8月26日 星期一

ASP.NET 西班牙語系Convert.ToDouble

ASP.NET 西班牙語系Convert.ToDouble

Error Sample:
//假設textBox1.Text等於1.5
textBox1.Text = "1.5";

//轉換textBox1.Text成Double
double a = Convert.ToDouble(textBox1.Text);

//印出結果es錯誤, 語系=en, a=1.5;語系=es, a=15
Response.Write(a.Tostring());

Good Sample:
//假設textBox1.Text等於1.5
textBox1.Text = "1.5";

//轉換textBox1.Text成Double並加上區域文化
double b = Convert.ToDouble(textBox1.Text, System.Globalization.CultureInfo.InvariantCulture)

//印出結果es正確,語系=en, b=1.5;語系=es, b=1.5
Response.Write(b.Tostring());

2013年6月27日 星期四

ASP.NET Copy File to Network Share Folder 複製檔案到網路磁碟機

ASP.NET Copy File to Network Share Folder
複製檔案到網路磁碟機


C#:
    private void CopyFileToNetwork()
    {
        System.IO.StreamReader sErr;
        System.IO.StreamReader sOut;
        String tempErr, tempOut;
        System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
        myProcess.StartInfo.FileName = @"NET";
        myProcess.StartInfo.Arguments = "USE Y: \\\\192.168.0.136\\folder001 \"123456\" /user:\"Administrator\""; //password is 123456, username is Administrator
        myProcess.StartInfo.CreateNoWindow = true;
        myProcess.StartInfo.UseShellExecute = false;
        myProcess.StartInfo.RedirectStandardError = true;
        myProcess.StartInfo.RedirectStandardOutput = true; // 導出 StandardOutput
        try
        {
            myProcess.Start();
            myProcess.WaitForExit(10000);

            if (!myProcess.HasExited)
            {
                myProcess.Kill();
                Response.Write("執行失敗!!");
            }
            else
            {
                sErr = myProcess.StandardError;
                tempErr = sErr.ReadToEnd();
                sErr.Close();

                sOut = myProcess.StandardOutput;
                tempOut = sOut.ReadToEnd();
                sOut.Close();

                if (myProcess.ExitCode == 0) //連線磁碟機建立成功
                {
                    //Response.Write("執行成功" + "<BR>" + tempOut.ToString()); // 把執行結果也印出來
                    System.IO.File.Copy(@"D:\abc.xls", @"Y:\abc.xls",true);
                }
                else if (myProcess.ExitCode == 2) // 忽略連線磁碟機已存在
                {
                    System.IO.File.Copy(@"D:\abc.xls", @"Y:\abc.xls", true);
                }
                else
                {
                    Response.Write(tempErr);
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            myProcess.Close();
        }
        finally
        {
            myProcess.Close();
        }
    }

2013年6月17日 星期一

ASP.NET Request.UrlReferrer取得上一頁的網址

ASP.NET Request.UrlReferrer取得上一頁的網址


HTML:
<form id="form1" runat="server">
<div>
    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test_tsUrlReferrer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            ViewState["UrlReferrer"] = "";
            if (!IsPostBack)
            {
                if (Request.UrlReferrer != null)
                    ViewState["UrlReferrer"] = Request.UrlReferrer.ToString();
            }
            Label1.Text = ViewState["UrlReferrer"].ToString();
        }
        catch (Exception ex)
        {
            throw ex;
        }
     
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Redirect(ViewState["UrlReferrer"].ToString());
        }
        catch (Exception)
        {
         
            throw;
        }
     
    }
}

2013年6月12日 星期三

X-UA-Compatible設置IE兼容模式

[HTML]X-UA-Compatible設置IE兼容模式

強制瀏覽器呈現為特定的版本的標準。它不支持IE7及以下:
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7"/>

如果用分號分開,它設置為不同版本的兼容級別,IE7、IE9。它允許不同層次的向後兼容性:
<meta http-equiv="X-UA-Compatible" content="IE=7; IE-9"/>

只選擇其中一個選項:
<meta http-equiv="X-UA-Compatible" content="IE=9">
<meta http-equiv="X-UA-Compatible" content="IE=8"/>
<meta http-equiv="X-UA-Compatible" content="IE=7">
<meta http-equiv="X-UA-Compatible" content="IE=5">

允許更容易的測試和維護。雖然通常比較有用的版本,這是使用模擬:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">

什麼版本IE 就用什麼版本的標準模式:
<meta http-equiv="X-UA-Compatible" content="IE=edge">

使用以下代碼強制IE 使用Chrome Frame:
<meta http-equiv="X-UA-Compatible" content="chrome=1">

最佳的兼容模式方案,結合考慮以上兩種:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

指定文件兼容性模式,在網頁中使用meta元素放入X-UA-Compatible  http-equiv  標頭。以下是指定為Emulate IE7 mode兼容性之範例:
< html >
< head >
  <!--  Mimic Internet Explorer 7  -->
  < meta  http-equiv ="X-UA-Compatible"  content ="IE=EmulateIE7"  />
  < title > My Web Page </ title >
< / head >
< body >
</ body >
</ html >

設定網站服務器以指定預設兼容性模式:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
   <system.webServer>
      <httpProtocol>
         <customHeaders>
            <clear />
            <add name="X-UA-Compatible" value="IE=EmulateIE7" />
         </customHeaders>
      </httpProtocol>
   </system.webServer>
</configuration>

2013年6月11日 星期二

ASP.NET 使用JavaScript

ASP.NET 使用JavaScript


C#:
string strScript = "alert(\"建立完成!\");";
ScriptManager.RegisterStartupScript(this, typeof(string), "ALERT", strScript, true);

string strScript = "<script>alert(\"建立完成!\");</script>";
this.Page.Controls.Add(new LiteralControl(str_Script));

ASP.NET 新增資料後立即取得自動編號的ID(2)

ASP.NET 新增資料後立即取得自動編號的ID(2)


HTML:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:KMSConnectionString %>"
            InsertCommand="INSERT INTO category(cat001, cat002, objactive, objcreate) VALUES (@cat001,@cat002,@objactive,@objcreate);select @ID=@@Identity
" oninserted="SqlDataSource1_Inserted">
<InsertParameters>
                <asp:ControlParameter Name="cat001" ControlID="cat001" Type="String" />
                <asp:Parameter Name="cat002" DefaultValue="Folder" Type="String" />
                <asp:ControlParameter Name="objactive" ControlID="objactive" Type="String" />
                <asp:Parameter Name="objcreate" Type="String" />
                <asp:Parameter Name="ID" Direction="InputOutput" Type="Decimal" />
            </InsertParameters>
        </asp:SqlDataSource>

C#:
protected void SaveButton_Click(object sender, ImageClickEventArgs e)
    {
     
        SqlDataSource1.InsertParameters["objcreate"].DefaultValue = Context.User.Identity.Name;
        SqlDataSource1.Insert();
   }
protected void SqlDataSource1_Inserted(object sender,  SqlDataSourceStatusEventArgs e)
    {
        string strReturn = e.Command.Parameters["@ID"].Value.ToString();
     
    }

ASP.NET 新增資料後立即取得自動編號的ID(1)

ASP.NET 新增資料後立即取得自動編號的ID(1)


C#:
SqlConnection conn = new SqlConnection(ConnectionString);
conn.open();
string strSQL = "Insert Into table1(t1,t2) value(1,2);select @@IDENTITY";
SqlCommand cmd = new SqlCommand(strSQL);
cmd.Connection = conn;
int i = cmd.ExecuteScalar();   //i就是你要的
cmd.Dispose();
conn.close();
conn.Dispose()

VB:
Dim cid As String = ""
Dim conn As SqlConnection
conn = Class1.conn_sql
Dim command As New SqlCommand("INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description);SELECT SCOPE_IDENTITY() ;", conn)
command.Parameters.AddWithValue("@CategoryName", "test")
command.Parameters.AddWithValue("@Description", "abcd")
conn.Open()
cid = command.ExecuteScalar
conn.Close()

ASP.NET 取得Windows驗証Login ID

ASP.NET 取得Windows驗証Login ID


C#:
    private string GetLogonUserID()
    {
        string strLogonUser = Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.IndexOf("\\") + 1, Request.LogonUserIdentity.Name.Length - Request.LogonUserIdentity.Name.IndexOf("\\") - 1);
        return strLogonUser.ToString();
    }

SQL 列出資料庫中所有的Table

SQL 列出資料庫中所有的Table


MsSQL:
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE (TABLE_TYPE = 'BASE TABLE') AND (TABLE_SCHEMA = 'dbo')

Access:
SELECT * FROM MSYSOBJECTS

Oracle:
SELECT * FROM USER_OBJECTS

ASP.NET ListBox 互傳

ASP.NET ListBox 互傳


HTML:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
    <asp:ListItem>a</asp:ListItem>
    <asp:ListItem>b</asp:ListItem>
    <asp:ListItem>c</asp:ListItem>
</asp:ListBox>
<asp:Button ID="Button1" runat="server" Text="Add" onclick="Button1_Click" />

<asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple">
</asp:ListBox>
<asp:Button ID="Button2" runat="server" Text="Del" onclick="Button2_Click" />

C#:
    protected void Button1_Click(object sender, EventArgs e)
    {
        //單選add時用下列這行
        //ListBox2.Items.Add(ListBox1.SelectedItem);

        //多選add用迴圈
        for (int i = 0; i < ListBox1.Items.Count; i++)
        {
            if (ListBox1.Items[i].Selected)
            {
                ListBox2.Items.Add(ListBox1.Items[i]);
            }
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        //單選del
        //ListBox2.Items.RemoveAt(ListBox2.SelectedIndex);

        //多選del用迴圈
        for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
        {
            if (ListBox2.Items[i].Selected)
            {
                ListBox2.Items.RemoveAt(i);
            }
        }
    }

2013年6月6日 星期四

ASP.NET DropDownList 尋找符合項目

ASP.NET DropDownList 尋找符合項目


C#:
protected void Page_Load(object sender, EventArgs e)
{
    //由於DropDownList只能單選,為了避免錯誤,先將已選定的項目取消
    this.DropDownList1.Items[DropDownList1.SelectedIndex].Selected = false;

    //尋找符合"1"的項目
    ListItem item=this.DropDownList1.Items.FindByValue("1");

    //如果在DropDownList清單中有找到相符的,則將它改成被選取的項目
    if(item!=null)item.Selected = true;
}

2013年6月5日 星期三

C# ASCII字碼轉換應用

C# ASCII字碼轉換應用

如何將英文字母大寫”A”轉換為”65”與如何將”65”轉換為英文字母大寫的”A”。
下列範例中RetAsciiCode將大寫”A”轉換成”65”後return給呼叫RetAsciiCode的原程序變數,另外RetAsciiChar帶入一個數字(asciiCode)例如”65”,轉換成大寫”A”並將結果return給呼叫的原程序變數。

C#:
    int intAsciiCode = Int32.Parse(RetAsciiCode(“A”)); //回傳數字65
    string strAsciiChar = RetAsciiChar(65);  //回傳大寫A

    public int RetAsciiCode(string MyString)
    {
        if (MyString.Length == 0)
            return 0;
        else if (MyString.Length > 1)
            MyString = MyString[0].ToString();

        int AsciiCodeO = (int)System.Convert.ToChar(MyString);
        byte[] AsciiCodeB = System.Text.Encoding.ASCII.GetBytes(MyString);
        //int AsciiCode = System.Convert.ToInt32(AsciiCodeB);
        return AsciiCodeO;
    }

    public string RetAsciiChar(int AsciiCode)
    {
        return System.Convert.ToChar(AsciiCode).ToString();
    }

C# Get MAC Address

Get MAC Address C#

C#
    public string GetMACAddress()
    {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();
        string MACAddress = String.Empty;
        foreach (ManagementObject mo in moc)
        {
            if (MACAddress == String.Empty) // only return MAC Address from first card
            {
                if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString();
            }
            mo.Dispose();
        }
        return MACAddress;
    }

ASP.NET Encrypt Excel加密

ASP.NET Encrypt Excel加密

C#:
private void EncryptExcel(string FileName)
    {
        try
        {
            FileName = @"D:\Inetpub\PORTAL\Test\MyFilests.xlsx";

            Microsoft.Office.Interop.Excel.Application xlApp = null;
            Workbook wb = null;
            Worksheet ws = null;
            Range aRange = null;
            xlApp = new Microsoft.Office.Interop.Excel.Application();

            //打開Server上的Excel檔案
            xlApp.Workbooks.Open(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            //第一個Workbook
            wb = xlApp.Workbooks[1];
            //設密碼
            wb.Password = "123456";
            //另存新檔
            wb.SaveAs(@"D:\Inetpub\PORTAL\Test\NewPasswordx.xlsx");
            //取得worksheet
            ws = (Worksheet)wb.Worksheets[1];
            Label1.Text = ws.Name;
            //開啟檔案
            System.Diagnostics.Process.Start(@"D:\Inetpub\PORTAL\Test\NewPasswordx.xlsx");

        }
        catch (Exception)
        {

            throw;
        }
    }

ASP.NET TextBox onKeyDown網頁中按Enter鍵後指定一個Button並送出

ASP.NET TextBox onKeyDown網頁中按Enter鍵後指定一個Button並送出

在TextBox1下按Enter之後,觸發Script Event onKeyDown,執行window.open到google網頁;另一個觸發.Net ImageButton1_Click,Redirect到www.msn.com.tw。以上觸發Event會跳過Button1


JavaScript:
<script language="javascript" type='text/javascript'>

        function body_onKeyDown() {
            if (window.event.keyCode == 13) {
                alert(event.type);
                document.all.ImageButton1.focus();
                newWindow = window.open("http://www.google.com", "SelectUser", "width=500,height=500");
                newWindow.focus();
            }
        }
    </script>

HTML:
<body onkeydown="body_onKeyDown()">
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <asp:ImageButton ID="ImageButton1" runat="server"
            onclick="ImageButton1_Click" />
    </div>
    </form>
</body>

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test_tsOnKeyDown : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("http://www.yahoo.com.tw");
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("http://www.msn.com.tw");
    }
}

ASP.NET Dynamic InnerHTML

ASP.NET Dynamic InnerHTML

HTML:
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Inner" OnClick="Button1_Click" />
    </div>
    <div id="dynamic1">
    </div>
    <div id="dynamic2" runat="server">
    </div>
    </form>
</body>

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test_tsInnerHTML : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            //Script
            string strScript = "document.getElementById('dynamic1').innerHTML='<input type=\"file\" name=\"FileUpload1\" id=\"FileUpload1\" />'";
            ScriptManager.RegisterStartupScript(this, typeof(string), "Function", strScript, true);
            //Asp.net
            dynamic2.InnerHtml = Server.HtmlDecode("<Input type='file' name='fileupload2' id='fileupload2'>");
        }
        catch (Exception)
        {
            throw;
        }
    }
}

C# Excel to GridView

[C#]Excel to GridView

HTML:
<form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
        <br />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <asp:Label ID="lbl_Err" runat="server" Text="Label"></asp:Label><br />
        <div runat="server" clientidmode="Static" id="DIV1">
        </div>
    </div>
</form>

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Test_FileUpload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string FileFullPath = string.Empty;
            DataSet ds = null;
            DataTable dt = null;

            File_Upload flu = new File_Upload();
            flu.Set_AllowedExtension = "EXCEL";
            flu.UploadXLS(FileUpload1);
         
            ImportData imp = new ImportData();
            ds = imp.GetExcelData(flu.Get_SavePath + flu.Get_FileName);
         
            dt = ds.Tables[0];
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            lbl_Err.Text = ex.Message;
        }
    }
}

C# 網頁PostBack後回到原來停留的位置

[C#]網頁PostBack後回到原來停留的位置

web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<!--網頁PostBack後回到原來停留的位置-->
<pages maintainScrollPositionOnPostBack="true">
</pages>
</system.web>
</configuration>

2013年6月4日 星期二

C# ViewState存入Session

[C#]ViewState存入Session


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test_tsViewStateNon : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// ViewState存在Session
    /// </summary>
    protected override PageStatePersister PageStatePersister
    {
        get
        {
            //return base.PageStatePersister;
            return new SessionPageStatePersister(this);
        }
     }
}

C# 呼叫外部檔案

[C#]呼叫外部檔案


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test_tsRUNexe : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            System.Diagnostics.Process.Start(@"c:\GetApplicationBG.exe");

            #region Sample
            // open text file in notepad (or another default text editor)
            //System.Diagnostics.Process.Start(@"c:\textfile.txt");

            // open image in default viewer
            //System.Diagnostics.Process.Start(@"c:\image.jpg");

            // open url in default web browser
            //System.Diagnostics.Process.Start("http://www.csharp-examples.net");

            // open PDF file
            //System.Diagnostics.Process.Start(@"c:\document.pdf");

            #endregion
        }
        catch (Exception)
        {
         
            throw;
        }
    }
}

C# 日期相減

[C#]日期相減


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test_tsDateSubtract : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DateTime StartTime = DateTime.Parse("2013-05-20"); //開始日
        //DateTime EndTime = DateTime.Parse("2013-05-21"); //指定結束日
        DateTime EndTime = DateTime.Now; //當日
        TimeSpan TS = EndTime.Subtract(StartTime); //日期相減

        Response.Write(TS.Days.ToString() + "<br>");         //天(int)
        Response.Write(TS.Hours.ToString() + "<br>");        //小時(int)
        Response.Write(TS.Minutes.ToString() + "<br>");      //分(int)

        Response.Write(TS.TotalDays.ToString() + "<br>");    //天(double)
        Response.Write(TS.TotalHours.ToString() + "<br>");   //小時(double)
        Response.Write(TS.TotalSeconds.ToString() + "<br>"); //分(double)
    }
}

C# 取得Browser Language

[C#]取得Browser Language


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test_tsBrowserLanguage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            HttpRequest Request = HttpContext.Current.Request;
            string browerlang = Request.UserLanguages[0].ToString();
            Response.Write(browerlang);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

C# DataTable to XML

[C#]DataTable to XML


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Xml;
using System.Xml.Linq;
using System.Text;

public partial class Test_tsDataTabletoXML : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = "Data Source=localhost;Initial Catalog=db1;Persist Security Info=True;User ID=sa;Password=123456";

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cn;
            cmd.CommandText = "select * from Product";

            cn.Open();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;
            DataSet ds = new DataSet("ds1");
            da.Fill(ds, "Product");
            DataTable dt = ds.Tables["Product"];

            // XML Setting
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = false;
            settings.Encoding = settings.Encoding = Encoding.GetEncoding("utf-8");

            // XML Write
            XElement tElement = new XElement("DataTable", "");
            using (XmlWriter xmlWriter = XmlWriter.Create("c:\\Product.xml", settings))
            {
                // Write the data set to the writer.
                tElement = DataTableToXml(dt, "root");
                tElement.WriteTo(xmlWriter);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// DataTable to XML
    /// </summary>
    /// <param name="pAttributeTable"></param>
    /// <param name="tParentTag"></param>
    /// <returns></returns>
    private XElement DataTableToXml(DataTable pAttributeTable, string tParentTag)
    {
        if (pAttributeTable == null)
            return null;

        XElement tParent = null;
        try
        {
            tParent = new XElement(tParentTag);  // 集合Tag的名字
            //每個DataRow為屬性分類
            foreach (DataRow tRow in pAttributeTable.Rows)
            {
                XElement tChild = new XElement("DataRow");
                //每個DataRow的DataColumn為屬性分類裡的項目
                foreach (DataColumn tColumn in pAttributeTable.Columns)
                {
                    tChild.Add(new XElement(tColumn.ColumnName, tRow[tColumn]));
                }
                tParent.Add(tChild);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return tParent;
    }
}