TOP

[ASP.NET, jQuery] ASP.Net使用jQuery日歷選擇器

<head>
  <script>
      $(function() {          
        $("input[id*=tbStartTime]").datepicker({ showOn: "both", buttonImage: "../images/gesplus/calendar.gif", buttonImageOnly: true, dateFormat: "yy/mm/dd" });
      });
  </script>

  <style>
//調整圖片位置
    .ui-datepicker-trigger { margin-left:5px; margin-top: 5px; margin-bottom: -6px; }
  </style>
</head>


<asp:TextBox ID="tbStartTime" runat="server" Columns="10"></asp:TextBox>

參考資料:
http://blog.xuite.net/tolarku/blog/213867131-%5BAsp.net%5D+%E9%81%B8%E6%93%87%E6%97%A5%E6%9C%9F+Calendar+%E4%BD%BF%E7%94%A8+jQueryUI+%E7%9A%84+DatePicker

http://www.fbloggs.com/2009/04/16/how-to-style-the-button-image-in-jquery-datehandler-ui/

http://jqueryui.com/datepicker/#localization

http://blog.wu-boy.com/2008/04/jquery%E7%AD%86%E8%A8%98-%E5%A5%BD%E7%94%A8%E7%9A%84%E6%97%A5%E6%9C%9F%E5%87%BD%E5%BC%8F/


script取得ID的方式
一、 
$(".date-picker").datepicker()

二、

$("#<%= txtEventDate.ClientID %>").datepicker()

三、
$("input[id*=txtEventDate]").datepicker()

參考資料:
http://stackoverflow.com/questions/5115067/jquery-datepicker-not-working-in-asp-net-page

TOP

[ASP.NET]Repeater使用CheckBox的OnCheckedChanged

使用者需求:在Repeater內使用CheckBox並且勾選時立即變更資料庫狀態。
<table>
     <asp:repeater id="ContentRepeater" runat="server">
           <ItemTemplate>
                   <tr>
                        <td>
                               <asp:Literal ID="ltContentId" runat="server"
                               Text='<%# DataBinder.Eval(Container, "DataItem.ContentId") %>'>
                               </asp:Literal>
                        </td>
                       <TD>
                              <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true"                                                  OnCheckedChanged='cbCoaching_OnCheckedChanged'/>
                       </td>
                   </tr>
           </ItemTemplate>
      </asp:repeater>
</table>


    Protected Sub cbCoaching_OnCheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
         '取得在repeater內的那一欄資料。
        Dim chk As CheckBox = DirectCast(sender, CheckBox)
        Dim item As RepeaterItem = DirectCast(chk.NamingContainer, RepeaterItem)
        Dim ltContentId As Literal = DirectCast(item.FindControl("ltContentId"), Literal)
         response.write ("ltContentId =" &ltContentId  & "<BR>")
    End Sub

參考資料:
http://stackoverflow.com/questions/6997948/handling-the-checkedchanged-event-of-inner-repeater-checkbox-control-in-asp-net
http://stackoverflow.com/questions/25308247/how-to-get-the-repeater-item-in-a-checkbox-checkedchanged-event
TOP

[ASP.NET] 文字字串遇到http或https時改為超連結

Dim regx As New Regex("http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&amp;\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?", RegexOptions.IgnoreCase)

            Dim mactches As MatchCollection = regx.Matches(MyString)

            For Each match As Match In mactches
                MyString= MyString.ToString.Replace(match.Value, "<a href='" & match.Value & "' target='_blank' >" & match.Value & "</a>")
            Next

參考文章:
http://weblogs.asp.net/farazshahkhan/regex-to-find-url-within-text-and-make-them-as-link

http://www.dotblogs.com.tw/jameswu/archive/2008/04/22/3009.aspx

http://www.allenkuo.com/EBook5/view.aspx?TreeNodeID=67&id=209

http://blog.xuite.net/xiaolian/blog/59321149-%E3%80%90C%23%E3%80%91%E5%AD%97%E4%B8%B2%E6%9C%89%E6%95%88%E8%BD%89%E6%88%90%E8%B6%85%E9%80%A3%E7%B5%90

http://smallpoint-program.blogspot.tw/2012/08/phpemail.html
TOP

[ASP.NET]網頁網址及頁籤加上Icon圖片顯示

1.製作16x16的ICON圖

2.將以下的程式碼放位<head></head>之間
方式1:
<link rel="icon" href="/favicon1.ico" type="image/x-icon" />

方式2:
<link rel="shortcut icon" href="/favicon1.ico" type="image/x-icon" />

參考資料:http://www.tshopping.com.tw/thread-164857-1-1.html
TOP

[C#] Cancel CreateUserWizard from CreatedUser Event

1.利用CreateUserWizard 建立使用者帳號,同時將其他資料儲存在自已建立的table內,不使用aspnetdb的Profiles時
2.需要在CreatedUser後儲存資料但又必需要確認是否有正確儲存的方式。
3.如果未儲存成功,刪除已註冊的使用者帳號,並且顯示錯誤訊息。

幾個重點如下:
        protected void RegisterUser_CreatedUser(object sender,  EventArgs e)
        {        
         Result = AddUserProfile(userProfile);   
         if (Result == true)
         {
           return true;
         }
         else
         {
            Membership.DeleteUser(RegisterUser.UserName);
            HttpContext.Current.Items.Add("ErrorMessage""註冊失敗,請聯繫系統管理員!!");
            Server.Transfer(Request.Url.PathAndQuery, true);
         }
        }

       protected void RegisterUser_CreatingUser(object sender, LoginCancelEventArgs e)
        {
            if (HttpContext.Current.Items["ErrorMessage"] != null)
            {
                CustomValidator custValidator = (CustomValidator)RegisterUserWizardStep.ContentTemplateContainer.FindControl("CustomValidator1");
                custValidator.ErrorMessage = HttpContext.Current.Items["ErrorMessage"].ToString();
                custValidator.IsValid = false;
                e.Cancel = true;
            }
 
        }


<asp:CreateUserWizardStep runat="server" ID="RegisterUserWizardStep">
   <ContentTemplate>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" ValidationGroup="RegisterUserWizardStep" />
   </ContentTemplate>
</asp:CreateUserWizardStep>

參考資料:http://stackoverflow.com/questions/10277812/cancel-createuserwizard-from-createduser-event
TOP

[ASP.NET] 檔案下載時檔案名稱亂碼

原本使用的下載方式會造成 檔案下載時檔案名稱亂碼。
因此變更檔案下載的方式,並且將檔案名稱做UrlEncode。
Dim filePath As String = "c:/123檔案.txt"
Dim wc As WebClient = New WebClient()
Dim byteFile() As Byte = Nothing
byteFile = wc.DownloadData(filePath)
Response.AppendHeader("content-disposition", "attachment;filename=" + "123檔案名稱")
HttpContext.Current.Server.UrlEncode(docPhysicalName)
Response.ContentType = "application/octet-stream"
Response.BinaryWrite(byteFile)
Response.End()

參考資料:
http://bob.logdown.com/posts/94996-aspnet-file-download

Response.WriteFile 檔案下載方式一
using System.IO;

string filePath = "C:/porn.jpg";
FileInfo file = new FileInfo(filePath);
Response.Clear()
Response.Buffer = false; 
Response.ContentType = "application/octet-stream"; // 指定檔案類型
Response.AddHeader("Content-Disposition","attachment;filename="+"porn.jpg"); // 設定檔名
// System.Web.HttpUtility.UrlEncode(newFileName, System.Text.Encoding.UTF8) 解決中文檔名亂碼
Response.AppendHeader("Content-Length", file.Length.ToString()); // 表頭加入檔案大小
Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
## System.Net.WebClient.DownloadData 檔案下載方式二

using System.Net;

WebClient wc = new WebClient();
byte[] byteFile = null;
string path = "C:/porn.jpg"; // 設定路徑
byteFile = wc.DownloadData(path);
string fileName = System.IO.Path.GetFileName(path); // 取得檔案名稱
Response.AppendHeader("content-disposition", "attachment;filename=" + "porn.jpg"); //設定檔名
// HttpContext.Current.Server.UrlEncode(fileName) 解決中文檔名亂碼
Response.ContentType = "application/octet-stream";  // 指定檔案類型   
Response.BinaryWrite(byteFile); // 內容轉出作檔案下載
Response.End();

亂碼處理的參考資料:
TOP

[CSS] Div CSS 浮水印(WaterMark)


<div style="overflow:hidden;height:96px;width:140px;margin: 0px auto;" >
   <asp:ImageButton ID="btnImage" runat="server" ImageUrl='<%# Eval("Image") %>' />                             <asp:ImageButton ID="btnWaterMark" style="position:relative; top: -70px;" runat="server"                              ImageUrl="~/images/gesplus/watermark-play.png"/>                                      
</div>

TOP

[Asp.Net] Download File from Remote Location to User Through Server

讀取遠端主機的錄影檔案,並且可以成功播放。

利用方法一的方式發生一種狀況是檔案有成功下載,但無法播放檔案。
利用方法二只能在檔案為本機的檔案時使用,因為是使用了 FileStream

為了可以取得遠端主機的錄影檔案,但又要可以成功播放檔案,
最後參考方法二的Context.Response.OutputStream方式才解決此問題。

差異點如下:

Context.Response.BinaryWrite(myStream.ToArray())
我現在是改為使用
Context.Response.OutputStream.Write(ByteBuffer, 0, count)


方法一:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Net;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//base.OnLoad(e);
string url = string.Empty;// Request.QueryString["DownloadUrl"];
if (url == null || url.Length == 0)
{
url = "http://img444.imageshack.us/img444/6228/initialgridsq7.jpg";
}

//Initialize the input stream
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
int bufferSize = 1;

//Initialize the output stream
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=download.jpg");
Response.AppendHeader("Content-Length", resp.ContentLength.ToString());
Response.ContentType = "application/download";

//Populate the output stream
byte[] ByteBuffer = new byte[bufferSize + 1];
MemoryStream ms = new MemoryStream(ByteBuffer, true);
Stream rs = req.GetResponse().GetResponseStream();
byte[] bytes = new byte[bufferSize + 1];
while (rs.Read(ByteBuffer, 0, ByteBuffer.Length) > 0)
{
Response.BinaryWrite(ms.ToArray());
Response.Flush();
}

//Cleanup
Response.End();
ms.Close();
ms.Dispose();
rs.Dispose();
ByteBuffer = null;
}
}


參考資料:http://www.dotnetwatch.com/Programmatically-Download-File-from-Remote-Locatio451_AR.aspx

方法二:

    private string _vsk_path_root = "";
    private string _vsk_path_files = "/contents/test/"; // directory path where mp4 videos reside
    //private bool _vsk_conf_limit_bandwidth = true;
    private bool _vsk_conf_allow_file_cache = false;
    // bandwidth settings
    //private int _vsk_bw_packet_size = 90; //set how many kilobytes will be sent per time interval
    //private float _vsk_bw_packet_internal = 0.3F; //set the time interval in which data packets will be sent in seconds.
    //private bool _vsk_conf_allow_dynamic_bandwith = true; //set to TRUE to control bandwidth externally via http.
    // incomming get variables
    //private string _vsk_get_bandwidth="bw";
    // domain restriction
    private bool _islimitdomain = false; // set to TRUE to limit access to the player
    private static string[] _allowed_domains = new string[] { "www.remix-video.com", "www.mediasoftpro.com" };
    private bool _isrestrictdomain = false; // set to TRUE to restrict access to the player.
    private static string[] _restricted_domains = new string[] { "www.sampledomain.com", "www.sampledomain2.com", "www.sampledomain3.com" };

    // points to server root
    public string VSK_PATH_ROOT
    {
        set { _vsk_path_root = value; }
        get { return _vsk_path_root; }
    }

    public string VSK_PATH_FILES
    {
        set { _vsk_path_files = value; }
        get { return _vsk_path_files; }
    }

    ////set to TRUE to use bandwidth limiting.
    //public bool VSK_CONF_LIMIT_BANDWIDTH
    //{
    //    set { _vsk_conf_limit_bandwidth = value;}
    //    get { return _vsk_conf_limit_bandwidth;}
    //}

    //set to FALSE to prohibit caching of video files.
    public bool VSK_CONF_ALLOW_FILE_CACHE
    {
        set { _vsk_conf_allow_file_cache = value; }
        get { return _vsk_conf_allow_file_cache; }
    }

    ////set how many kilobytes will be sent per time interval
    //public int VSK_BW_PACKET_SIZE
    //{
    //    set { _vsk_bw_packet_size = value;}
    //    get { return _vsk_bw_packet_size;}
    //}

    //// set the time interval in which data packets will be sent in seconds.
    //public float VSK_BW_PACKET_INTERVAL
    //{
    //    set { _vsk_bw_packet_internal = value;}
    //    get { return _vsk_bw_packet_internal;}
    //}

    ////set to TRUE to control bandwidth externally via http.
    //public bool VSK_CONF_ALLOW_DYNAMIC_BANDWIDTH
    //{
    //    set { _vsk_conf_allow_dynamic_bandwith = value;}
    //    get { return _vsk_conf_allow_dynamic_bandwith;}
    //}

    //public string VSK_GET_BANDWIDTH
    //{
    //    set { _vsk_get_bandwidth =value;}
    //    get { return _vsk_get_bandwidth;}
    //}

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            int i = 0;
            bool flag = false;
            // limit access of player to certain domains
            if (_islimitdomain)
            {
                if (context.Request.UrlReferrer == null)
                {
                    context.Response.Write("<b>ERROR:</b> Unknown Referrer.");
                    return;
                }
                StringCollection _list = new StringCollection();
                _list.AddRange(_allowed_domains);
                for (i = 0; i <= _list.Count - 1; i++)
                {
                    if (_list[i].Contains(context.Request.UrlReferrer.Host))
                        flag = true; // referrer host matched with list of allowed domains
                }
                if (!flag) // referrer host not matched
                {
                    context.Response.Write("<b>ERROR:</b> Access Denied.");

                    return;
                }
            }

            // restrict access of some domains to player
            if (_isrestrictdomain)
            {
                if (context.Request.UrlReferrer == null)
                {
                    context.Response.Write("<b>ERROR:</b> Unknown Referrer.");
                    return;
                }
                flag = false;
                StringCollection _list = new StringCollection();
                _list.AddRange(_restricted_domains);
                for (i = 0; i <= _list.Count - 1; i++)
                {
                    if (_list[i].Contains(context.Request.UrlReferrer.Host))
                        flag = true; // referrer host matched with list of restricted domains
                }
                if (flag) // referrer host matched with restricted domains
                {
                    context.Response.Write("<b>ERROR:</b> Access Restricted.");
                    return;
                }
            }

            // Security Check
            if (context.Request.Params["token"] == null)
            {
                //if (context.Request.Params["token"] != "kxdffxki")
                //{
                context.Response.Write("<b>ERROR:</b> Access Denied.");
                return;
                //}
            }


            int position;
            int length;
            // Check start parameter if present
            //string filename = Path.GetFileName(context.Request.FilePath);
            string filename = context.Request.Params["file"];
            string seekpos = context.Request.Params["start"];
            string user = context.Request.Params["token"]; // point token with author of video
            // assemble file path
            string rootpath = context.Server.MapPath(context.Request.ApplicationPath);
            // string file = rootpath + "" + this.VSK_PATH_FILES + "" + user + "/FLV/" + filename;
            string file = rootpath + "" + this.VSK_PATH_FILES + "" + filename;

            if (!File.Exists(file))
            {
                context.Response.Write("<b>ERROR:</b> vsk-mp4 could not find (" + filename + ") please check your settings.");
                return;
            }

            if (File.Exists(file) && filename.EndsWith(".mp4") && filename.Length > 2)
            {
                FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
                if (string.IsNullOrEmpty(seekpos))
                {
                    position = 0;
                    length = Convert.ToInt32(fs.Length);
                }
                else
                {
                    position = Convert.ToInt32(seekpos);
                    //length = Convert.ToInt32(fs.Length - position) + _header.Length;
                    length = Convert.ToInt32(fs.Length - position);
                }

                // Add HTTP header stuff: cache, content type and length      

                if (!this.VSK_CONF_ALLOW_FILE_CACHE)
                {
                    // session_cache_limiter("nocache");
                    // header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
                    // header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
                    // header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
                    //  header("Pragma: no-cache");
                }
                else
                {
                    //context.Response.Cache.SetCacheability(HttpCacheability.Public);
                    //context.Response.Cache.SetLastModified(DateTime.Now);
                }
                //context.Response.AppendHeader("Content-Type", "video/x-flv");
                context.Response.AppendHeader("Content-Type", "video/mp4");
                context.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + "");
                context.Response.AppendHeader("Content-Length", length.ToString());

                // Read buffer and write stream to the response stream
                const int buffersize = 16384;
                byte[] buffer = new byte[buffersize];

                int count = fs.Read(buffer, 0, buffersize);
                while (count > 0)
                {
                    if (context.Response.IsClientConnected)
                    {
                        context.Response.OutputStream.Write(buffer, 0, count);
                        context.Response.Flush();
                        count = fs.Read(buffer, 0, buffersize);
                    }
                    else
                    {
                        count = -1;
                    }
                }
                fs.Close();


            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.ToString());
        }

    }

參考資料:http://www.mediasoftpro.com/articles/asp.net-progressive-mp4-streaming.html


TOP

[ASP.Net] stream video content in asp.net

stream video content in asp.net 

方法一:
byte[] buffer = new byte[4096];

while(true) {
    int bytesRead = myStream.Read(buffer, 0, buffer.Length);
    if (bytesRead == 0) break;
    Response.OutputStream.Write(buffer, 0, bytesRead);
}

參考資料:
http://stackoverflow.com/questions/2687677/how-to-stream-video-content-in-asp-net

方法二:
VB.Net:

Using req As WebRequest = HttpWebRequest.Create("url here"), _
      stream As Stream = req.GetResponse().GetResponseStream()

End Using

C#:

WebRequest req = HttpWebRequest.Create("url here");
using (Stream stream = req.GetResponse().GetResponseStream() )
{

}

參考資料:
http://stackoverflow.com/questions/1223311/is-it-possible-to-read-from-a-url-into-a-system-io-stream-object


TOP

[ASP.NET] 防止按鈕重覆點擊

防止按鈕重覆點擊

<asp:Button ID="btSubmit" runat="server"  UseSubmitBehavior="false"  />

C#
btSubmit.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btSubmit, null) + ";"); 

VB.Net
btSubmit.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btSubmit, Nothing) + ";")  

參考資料:
http://www.dotblogs.com.tw/joysdw12/archive/2011/11/22/58961.aspx
http://www.dotnetvishal.com/2013/01/disable-button-double-click-in-aspnet.html
http://www.dotblogs.com.tw/puma/archive/2008/03/16/1663.aspx
http://www.dotblogs.com.tw/sam19820611/archive/2010/04/14/14589.aspx
http://www.dotblogs.com.tw/joysdw12/archive/2011/11/22/58961.aspx
TOP

[ASP.NET] TextBox改為 MultiLine時MaxLength 無效問題

一般如果使用Textbox可以利用MaxLength 限制輸入的長度,但如果改為MultiLine時會發生MaxLength 無效問題。
<script type="text/javascript">
//檢查<TEXTAREA>的maxlength
function ismaxlength(obj){

  var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""

  if (obj.getAttribute && obj.value.length>mlength)

    obj.value=obj.value.substring(0,mlength)

}

</script


ASPX:

<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"></asp:TextBox>
 TextBox1.Attributes.Add("maxlength", "200");

TextBox1.Attributes.Add("onkeyup", "return ismaxlength(this)");



CodeBehind:
TextBox1.Attributes.Add("maxlength", "200");

TextBox1.Attributes.Add("onkeyup", "return ismaxlength(this)");



參考資料:
http://yanchi-huang.blogspot.tw/2011/12/aspnet-textbox-multiline-maxlength-is.html

http://pramaire.pixnet.net/blog/post/22512127-textbox%E5%9C%A8textmode%3Dmultiline%E7%8B%80%E6%85%8B%E4%B8%8Bmaxlength%E7%9A%84%E5%AD%97%E6%95%B8%E9%99%90
TOP

[ASP.NET] FaceBook,Google+,Twitter及微博使用Share button時指定縮圖、名稱及簡介內容

FaceBook,Google+,Twitter使用Share button時指定縮圖、名稱及簡介內容

方法1.
<link rel="image_src" href="name.jpg" />

 方法2.
<HEAD runat="server">
<meta property="og:title" content="名稱,Facebook" />
<meta property="og:type" content="web-design" />
<meta property="og:url" content="www.yahoo.com.tw" />
<meta property="og:image" content="http://www.abcdef.com.tw/images/logo.jpg" />
</HEAD>

參考資料:
http://compilerok.blogspot.tw/2013/08/facebook.html
http://cloud.zoes.tw/index.php/web-design/33-fb
http://www.freegroup.org/2012/10/how-to-avoid-no-thumbnail-issue-on-facebook/
http://jimmyyen.blogspot.tw/2010/10/blogger-facebook-facebook-like-button.html
https://developers.google.com/+/web/snippet/
http://fundesigner.net/facebook-cache/

Google+ 在share butoon 已移除Descriptions

參考資料:
http://www.seoskeptic.com/google-quietly-removes-descriptions-from-snippets/

微博參考資料:
http://open.weibo.com/sharebutton
http://www.moke.tw/wordpress/note/307
http://open.weibo.com/wiki/Weibo_meta_tag

TOP

[ASP.NET] UpdatePanel無效或失靈,造成整頁Postback。

問題:UpdatePanel使用的元件及方式跟另外一台電腦都相同,但其中一台電腦一直發生UpdatePanel無效或失靈,造成整頁Postback,無法局佈Postback的狀況。


處理方式:
web.config裡面移除
<configuration>
    <system.web>
        <xhtmlConformance mode="Legacy" />
    </system.web>
</configuration>

web.config設置
將 <system.web> 下 <xhtmlConformance mode="Legacy"/> 移除,此段為web標準的設置,但宣告此語法會讓 ajax 加載相關 js 時只加載一部份,以至於 UpdatePanel 失效,故拿掉此段語法。

使用ASP.NET AJAX UpdatePanel 控件时,做整页 postback,而不仅是局部更新。
当你打开你的web.config文件,你会看到其中的 <xhtmlConformance/> 元素,象这样:
<configuration>
    <system.web>
        <xhtmlConformance mode="Legacy" />    </system.web>
</configuration>

參考資料:
http://www.cnblogs.com/wf225/archive/2007/07/11/813580.html

http://fishsses.pixnet.net/blog/post/52406822-%E4%BD%BF%E7%94%A8-updatepanel-%E5%AF%A6%E7%8F%BE-dropdownlist-%E4%B8%8D%E5%88%B7%E6%96%B0%E9%80%A3%E5%8B%95%EF%BC%8C%E5%8C%85

http://www.cnblogs.com/calmzeal/archive/2007/04/04/699983.html

http://www.haogongju.net/art/214636

http://www.debugease.com/aspdotnet/682418.html
TOP

[ASP.NET] Google+,FaceBook,Twitter Share Button


利用Onclick控制視窗開啟大小
<script type="text/javascript">
            function OpenWindow(Url, width, height) {
                retVal = window.open(Url, "", "width=" + width + ",height=" + height +",menubar=no,location=no,status=no,resizable=no,scrollbars=yes");
            }                                
</script>

asp.net HyperLink加圖片方式顯示,因為使用Onclick所以加上 style="cursor:pointer;" 當滑鼠移到圖片上時顯示「手指」圖式。

<asp:HyperLink ID="hplGoogleShare" runat="server" ImageUrl="~/images/share.png" Target="_blank" style="cursor:pointer;"></asp:HyperLink>
<asp:HyperLink ID="hplFbShare" runat="server" ImageUrl="~/images/share.png" Target="_blank" style="cursor:pointer;"></asp:HyperLink>
                        <asp:HyperLink ID="hplTwitterShare" runat="server" ImageUrl="~/images/share.png" Target="_blank" style="cursor:pointer;"></asp:HyperLink>

加上Attributes的onclick

 FBShareUrl = "https://www.facebook.com/sharer/sharer.php?u=http://www.abc.com"
 GoogleShareUrl = "https://plus.google.com/share?url=http://www.abc.com"

 hplFbShare.Attributes.Add("onclick", "javascript:OpenWindow('" & FBShareUrl & "','500','300');void(0);")

hplGoogleShare.Attributes.Add("onclick", "javascript:OpenWindow('" & GoogleShareUrl & "','620','400');void(0);")

hplTwitterShare.Attributes.Add("onclick", "javascript:OpenWindow('https://twitter.com/share','500','400');void(0);")


參考資料:
Twitter
https://dev.twitter.com/docs/tweet-button
https://about.twitter.com/resources/buttons#tweet

FaceBook
https://developers.facebook.com/docs/plugins/share-button

Google+
https://developers.google.com/+/web/share/?hl=zh-TW
http://stackoverflow.com/questions/6585722/use-custom-image-for-google1-button
http://www.google.com/intl/en/webmasters/+1/button/index.html?utm_source=b2cp1&utm_medium=link&utm_campaign=p1#customize-snippet
TOP

[C#] CreateUserWizard + DropDownList 使用AutoPostBack及OnSelectedIndexChanged 無反應

 CreateUserWizard + DropDownList 使用AutoPostBack及OnSelectedIndexChanged 無反應

這個問題真的很怪,正常的狀況下AutoPostBack之後一定會去執行OnSelectedIndexChanged ,但掛在預設的CreateUserWizard 內使用時卻無反應。

解決的方式是把CreateUserWizard 內的 ViewStateMode="Disabled" 移除,就正常執行了。
TOP

[C#] ListView 利用 GridView 達成分頁功能

因為在asp.net 3.5 的狀況下 ListView沒有提供分頁的功能。
一般的做法都是用以下兩種方式:
(1)ListView + DataPager + LinqDataSource
(2)ListView + DataPager + SQLDataSource

但因為資料來源不是從LinqDataSource或SQLDataSource取得,所以使用DataPager 造成很多不必要的麻煩,改用ListView +GridView 的方式,雖然會浪費資源及效能但同樣可以執成同樣的效果。

一、ASPX新增及建立

1.GridView 的相關設定,並且在Columns新增一個項目,利用CSS做隱藏

<pre class='codeblock'>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" GridLines ="None" onpageindexchanging="GridView1_PageIndexChanging" onrowdatabound="GridView1_RowDataBound" >
         <PagerSettings FirstPageText="_FirstPage" LastPageText="_LastPage" Mode="NumericFirstLast" NextPageText="_NextPage" PreviousPageText="_PreviousPage" PageButtonCount="2" />
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name"
             ReadOnly="True" ItemStyle-cssclass="hiddencol" HeaderStyle-CssClass="hiddencol">
              <HeaderStyle CssClass="hiddencol"></HeaderStyle>
               <ItemStyle CssClass="hiddencol"></ItemStyle>
           </Columns>
            <FooterStyle HorizontalAlign ="Left" />
            <PagerStyle HorizontalAlign="Center" Font-Size="10" BackColor="#ffffff"                                                      ForeColor="#0072BC" Wrap="False" CssClass="PagerCss"></PagerStyle>
        </asp:GridView>
</pre>

2.增加CSS
<pre class='codeblock'>
<style type="text/css">
    .hiddencol
    {
        display:none;
    }
    .viscol
    {
        display:block;
    }
 
   .PagerCss TD A:hover { width: 20px; color: blue; }
    .PagerCss TD A:active { width: 20px; color: black; }
    .PagerCss TD A:link {width: 20px; color: Green;}
    .PagerCss TD A:visited { width: 20px; color:black ; }
    .PagerCss TD SPAN { font-weight: bold; font-size: 25px; width: 20px; color: red;  background-color:Silver ; }  
</style>
</pre>

3.ListView相關設定
<pre class='codeblock'>
    <asp:ListView ID="ListView1" runat="server" onitemdatabound="ListView1_ItemDataBound">
        <LayoutTemplate>
                <span ID="itemPlaceholder" runat="server"></span>
        </LayoutTemplate>
        <ItemTemplate>
             <asp:Label ID="Name" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
        </ItemTemplate>
    </asp:ListView>
</pre>

二、Code Behind新增及建立
1.建立全域變數的DataTable 及DataView
<pre class='codeblock'>
    public partial class Page : System.Web.UI.UserControl
    {
        public DataTable dt= new DataTable();
        public DataView dv = new DataView();
    }
</pre>

2.建立DataTable 的結構,並取得資料來源。
<pre class='codeblock'>
    protected void Page_Load(object sender, EventArgs e)
    {
        dt.Columns.Add("Name");
        dv = dt.DefaultView;
        DataView dvSource = GetSource();
        GridView1.DataSource = dvSource ;
        GridView1.DataBind();
        ListView1.DataSource = dv;
        ListView1.DataBind();
    }
</pre>
3.
<pre class='codeblock'>
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRow dr = dv.Table.NewRow();
            dr["Name"] = DataBinder.Eval(e.Row.DataItem, "Name") as string;
            dv.Table.Rows.Add(dr);
        }
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.EditIndex = -1;
        GridView1.PageIndex = e.NewPageIndex;
        dt.Columns.Add("Name");
        dv = dt.DefaultView;
        DataView dvSource = GetSource();
        GridView1.DataSource = dvSource ;
        GridView1.DataBind();
        ListView1.DataSource = dv;
        ListView1.DataBind();
    }

    protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
         Label Name = (e.Item.FindControl("Name") as Label);
         string Name = DataBinder.Eval(dataItem.DataItem, "Name ").ToString();
     }
</pre>

參考資料 :
http://charlesbc.blogspot.tw/2010/05/iqueryable-gridview-rowdatabound.html
http://www.dotblogs.com.tw/dennismao/archive/2009/08/10/9977.aspx?fid=16726
http://kennyfan88.pixnet.net/blog/post/84881604-%E4%BD%BF%E7%94%A8datatable%E5%8A%A0%E5%85%A5%E6%AC%84%E4%BD%8D%E3%80%81%E6%96%B0%E5%A2%9E%E6%AC%84%E4%BD%8D%E5%90%84%E8%B3%87%E6%96%99%E5%88%97
TOP

[C#] 在TextBox按下鍵盤上Enter後自動執行某一個button click

在TextBox按下鍵盤上Enter後自動執行某一個button click

會發生這個狀況是因為程式會自動執行Postback,並且當頁面內有button物件時,就會執行button click。

參考資料:
http://www.cnblogs.com/jiajiayuan/archive/2011/08/26/2154596.html
http://wellylin.blogspot.tw/2012/02/aspnet-form-submit-keypress-by-enter.html

解決的方式,可以利用panel預設default button或是利用javascript阻擋。
(1)利用panel預設default button
     <asp:Panel ID="asp:Panel1" runat="server" DefaultButton="btDefaultButton">
            <asp:Button ID="btDefaultButton" runat="server" Text="_DefaultButton" style="display:none" />
        </asp:Panel>

參考資料:
http://eos45.pixnet.net/blog/post/48273310-asp.net-%E8%AE%93-enter-%E7%84%A1%E6%95%88

(2)利用javascript阻擋
txtTitle.Attributes.Add("onkeypress", "if( event.keyCode == 13 ) { return false; }");

參考資料:
http://demo.tc/Post/233

(3)利用javascript指定執行的button click
Me.txt_pass.Attributes.Add("onkeypress", "if( event.keyCode == 13 ) {"& Me.ClientScript.GetPostBackEventReference(Me.btn_pass, "")& "}")
參考資料:
http://blog.xuite.net/tolarku/blog/39441722-TextBox+%E8%BC%B8%E5%85%A5%E5%AE%8C%E6%8C%89%E4%B8%8B+Enter+%E8%A7%B8%E7%99%BC%E6%8C%89%E9%88%95%E4%BA%8B%E4%BB%B6


http://nelsonkai.blogspot.tw/2008/12/text-boxentersend.html

(4)利用javascript在 Enter 鍵被按下時,改成 Tab 鍵
參考資料:
http://charlesbc.blogspot.tw/2009/06/aspnet-enter-tab.html

(5)利用 form defaultbutton
<asp:Button ID="btDefaultButton" runat="server" Text="_DefaultButton" style="display:none" />

    this.Form.DefaultButton = btDefaultButton.UniqueID;
    btDefaultButton.Style.Add("display", "none");


TOP

[SQL Server] 將會員登入機制ASPNETDB.MDF轉到SQL Server

預設的會員登入機制是在App_Data資料夾內建立ASPNETDB.MDF,因為是需要上線的會員登入機制,希望能將資料轉存至SQL Server內。

1.轉移的方式,主要是使用ASP.NET 附加資料庫轉移工具:Aspnet_reqsql.exe

路徑:C:\Windows\Microsoft.NET\Framework\v2.0.50727
參考:http://msdn.microsoft.com/en-us/library/ms229862.ASPX

2.移轉的安裝步驟可以參考以下資料:
http://www.dotblogs.com.tw/keigen/archive/2012/02/01/67152.aspx
(1)大部份都是執行「下一步」
(2)選擇「設定應用程式服務的SQL Server」
(2)輸入「伺服器名稱」
(3)選擇「Windows驗證」或是「SQL Server驗證(輸入使用者名稱及密碼)」
(4)選擇資料庫
(5)之後就都是「下一步」
(6)最後就是「完成」

參考資料:http://www.studiocoast.com.au/knowledgebase/6/aspnet/using-sql-server-instead-of-aspnetdbmdf.aspx

3.檢查SQL Server資料表,應該會有11個aspnet_XXXXXX名稱的資料表

4.因為資料庫的位置從App_Data下的ASPNETDB.MDF,移轉到SQL Server所以要重新設定Web.config的資料庫連接字串。

  <connectionStrings>
    <add name="UserAspNetConnectionString" connectionString="Data Source=xxxx\SQLEXPRESS;Initial Catalog=aspnetdb;User ID=xxxxxx;Password=xxxxxx;Min Pool Size=10;Max Pool Size=1000;Pooling=false;Connect Timeout=45;" providerName="System.Data.SqlClient" />  
  </connectionStrings>

5.設定Provider的連接字串(藍字的UserAspNetConnectionString)。

   <profile defaultProvider="DefaultProfileProvider" enabled="true">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="UserAspNetConnectionString" applicationName="/" />    
      </providers>
      <properties>
        <add name="FirstName" type="System.String"/>
        <add name="LastName" type="System.String"/>
      </properties>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="UserAspNetConnectionString" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider" enabled="true">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="UserAspNetConnectionString" applicationName="/" />
      </providers>
    </roleManager>

參考資料:
http://www.dotblogs.com.tw/dislin/archive/2010/07/28/16868.aspx

http://dnowba.blogspot.tw/2011/10/blog-post_3144.html

http://www.dotblogs.com.tw/topcat/archive/2008/06/02/4201.aspx

http://dnowba.blogspot.tw/2011/10/blog-post_3144.html

TOP

[C#] DataView.RowFilter 查詢 null 值

在SQL Sever 如果要查詢某個欄位時會使用 「 欄位 is NULL」
測試在RowFilter 同樣使用此方式
DataView.RowFilter = "LastName Is Null"; 
卻無法達到查詢 NULL值

可以轉成以下的方式達成目的
DataView.RowFilter = "IsNull(LastName, '') = ''";