2012年12月28日 星期五

window.location.Reload() and window.location.href=window.location.href; difference

window.location.Reload() is refresh page, it will submit the data again and has a alert message is continue.

window.location.href=window.location.href is redirect url.

2012年11月21日 星期三

Get screen width Javascript


<script type="text/javascript" language="javascript">
    if (document.getElementById("rightMenu") != null) {
        if (screen.width < 1200) {
            document.getElementById("rightMenu").style.display = "none";
        }
    }

</script>

position fixed for IE6

Add this code in the header

<!--[if IE 6]>
<style type="text/css">
.promomenu{
position:absolute; /* position fixed for IE6 */
top:expression(200+((e=document.documentElement.scrollTop)?e:document.body.scrollTop)+'px');
right:expression(0+((e=document.documentElement.scrollLeft)?e:document.body.scrollLeft)+'px');
}
</style>
<![endif]-->

2012年9月20日 星期四

日期時間倒數器


  <SCRIPT type="text/javascript" language="javascript">
      var startDate = new Date();
      var endDate = new Date(2012, 8, 20, 10, 00);
      var spantime = (endDate - startDate) / 1000;

      function getString(dt) {
          return dt.getFullYear() + "?" + (dt.getMonth() + 1) + "?" + dt.getDate() + "?" + dt.getHours() + "?" + dt.getMinutes() + "?";
      }
      function leftPad(n, len) {
          return (new Array(len - String(n).length + 1)).join("0").concat(n);
      }
      function cal() {
          spantime--;
          var d = Math.floor(spantime / (24 * 3600));
          var h = Math.floor((spantime % (24 * 3600)) / 3600);
          var m = Math.floor((spantime % 3600) / (60));
          var s = Math.floor(spantime % 60);
          str = d + "? " + h + "?" + m + "? " + s + "? ";



          document.getElementById("hours2").innerHTML = leftPad(h, 2);
          document.getElementById("min2").innerHTML = leftPad(m, 2);
          document.getElementById("sec2").innerHTML = leftPad(s, 2);
          if (document.getElementById("hours3") != null) {
              document.getElementById("hours3").innerHTML = leftPad(h, 2);
              document.getElementById("min3").innerHTML = leftPad(m, 2);
              document.getElementById("sec3").innerHTML = leftPad(s, 2);
          }

      }

      window.onload = function () {
          setInterval(cal, 1000);
      }
</SCRIPT>

2012年4月18日 星期三

DetailsView FindControl when Edit or Insert mode

Must in the PreRender or ItemCreated even.

.aspx file:

onprerender="DetailsView1_PreRender"


.cs file:

protected void DetailsView1_PreRender(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            DetailsView detailsView = (DetailsView)sender;
            if (detailsView.CurrentMode == DetailsViewMode.Edit)
            {
                DropDownList dropDownList = (DropDownList)detailsView.FindControl("DropDownList1");
                dropDownList.Items.Add(new ListItem("text", "value"));
            }
        }
    }

2012年2月21日 星期二

Create Google Calendar Event using Google Calendar API


Google api asp.net client download







public void CreateCalendarEvent(string content)
        {
            CalendarService calendarService = new CalendarService("CNBlogsMeeting");
            calendarService.setUserCredentials("Email", "Password");

            EventEntry entry = new EventEntry();

            //日曆標題與內容
            entry.Title.Text = content;
            entry.Content.Content = content;

            //開始與結束時間,17:00~18:00
            When eventTime = new When(DateTime.Now,
                DateTime.Now);
            entry.Times.Add(eventTime);

            //需要邀請的参會者
            //Who who = new Who();
            //who.Email = "cho88hk@gmail.com";
            //who.Rel = "http://www.yahoo.com.hk";
            //entry.Participants.Add(who);

            //给被邀請者發送通知
            //entry.Notifications = true;

            //被邀請者可以修改該日曆項
            //entry.ExtensionElements.Add(new GuestsCanModify("true"));

            Uri postUri = new Uri("https://www.google.com/calendar/feeds/default/private/full");
            AtomEntry insertEntry = calendarService.Insert(postUri, entry);

            //Assert.NotNull(insertEntry);
        }

2012年2月9日 星期四

Formatting the GridView Based on the Underlying Data


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // determine the value of the status field
            int status = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "status"));
            // color the background of the row
            switch (status)
            {
                case 0:
                    e.Row.BackColor = Color.LightGreen;
                    break;
                case 1:
                    e.Row.BackColor = Color.Red;
                    break;
                case 2:
                    e.Row.BackColor = Color.Blue ;
                    break;

            }
               
           
        }
}

2012年2月7日 星期二

HtmlAgilityPack 抓取HTML上的資訊 asp.net c#

HtmlAgilityPack 是可以簡單抓取html上特定位置資訊。

先在project>add reference 加上HtmlAgilityPack.dll
再配合firebug 的XPATH


//apple store iphone 4s 為例
                    string str = "http://store.apple.com/hk/browse/home/shop_iphone/family/iphone/iphone4s";


 HttpWebRequest httpWebRequest = WebRequest.Create(str) as HttpWebRequest;
                try
                {
                    
                    HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;

                    Stream stream = httpWebResponse.GetResponseStream();

                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    string s = reader.ReadToEnd();
                    reader.Close();
                    stream.Close();
                    httpWebResponse.Close();

                    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();

                    htmlDoc.LoadHtml(s);
                    //16GB 32GB 64GB 的運送時間XPATH
                    HtmlNode anchors = htmlDoc.DocumentNode.SelectSingleNode(
"/html/body/div[2]/div[3]/div/div[2]/div[2]/div[3]/ul/li/label/span/span[3]/span");
                    HtmlNode anchors32 = htmlDoc.DocumentNode.SelectSingleNode(
"/html/body/div[2]/div[3]/div/div[2]/div[2]/div[3]/ul/li[2]/label/span/span[3]/span");
                    HtmlNode anchors64 = htmlDoc.DocumentNode.SelectSingleNode(
"/html/body/div[2]/div[3]/div/div[2]/div[2]/div[3]/ul/li[3]/label/span/span[3]/span");

//output

txtStatus.Text += anchors.InnerText + " " + anchors32.InnerText + " " + anchors64.InnerText + " ";

                }
                catch (WebException web)
                {
                    
                    //error message
                }

2012年1月26日 星期四

asp.net sent GMAIL email C#


System.Net.Mail.SmtpClient MySmtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);

//設定你的帳號密碼
MySmtp.Credentials = new System.Net.NetworkCredential("YourID""YourPassword");

//Gmial 的 smtp 使用 SSL
MySmtp.EnableSsl = true;

//發送Email
MySmtp.Send("發送者<sender@gmail.com>""收件者<receiver@gmail.com>", "C# Gmail發信測試""文件內容");

2012年1月16日 星期一

GridView DataFormatString

日期格式: DataFormatString={0:yyyy-MM-dd}

decimal 小數後2位: DataFormatString={0:F2}

2012年1月6日 星期五

Multiple Files Upload asp.net Uploadify


Uploadify這個基於Flash的支持多檔上傳的Jquery外掛程式

官網:http://www.uploadify.com/
問題:
uploadifyie下可以正常上傳,在實現非同步上傳的時候,每一個檔在上傳時都會提交給伺服器一個請求。每個請求都需要安全驗證,sessioncookie的校驗。由於uploadify是借助flash來上傳的,每一次向後臺發送資料流程請求時,ie會自動把本地cookie存儲捆綁在一起發送給伺服器。但firefoxchrome不會這樣做,所以在firefox chrome會出現http error IO error.


解決方法:
在Global.asax加上:



void Application_BeginRequest(object sender, EventArgs e)
    {
        try
        {
            string session_param_name = "ASPSESSID";
            string session_cookie_name = "ASP.NET_SessionId";
            if (HttpContext.Current.Request.Form[session_param_name] != null)
            {
                UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
            }
            else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
            {
                UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
            }
        }
        catch
        {
        }


       
        try
        {
            string auth_param_name = "AUTHID";
            string auth_cookie_name = FormsAuthentication.FormsCookieName;
            if (HttpContext.Current.Request.Form[auth_param_name] != null)
            {
                UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
            }
            else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
            {
                UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
            }
        }
        catch { }
    }

    private void UpdateCookie(string cookie_name, string cookie_value)
    {
        HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
        if (null == cookie)
        {
            cookie = new HttpCookie(cookie_name);
        }
        cookie.Value = cookie_value;
        HttpContext.Current.Request.Cookies.Set(cookie);//重新設定請求中的cookie值,將伺服器端的session值賦值給它
    }


在放javascript 加上auth 和 ASPSESSID,然後在scriptData 傳送cookie。

<script type = "text/javascript">
            var auth = "<% = Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>";
            var ASPSESSID = "<%= Session.SessionID %>";
            $(window).load(
    function () {
        $("#<%=FileUpload1.ClientID%>").fileUpload({
            'uploader': '/js/uploader.swf',
            'cancelImg': '/image/cancel.png',
            'buttonText': 'Browse Files',
            'script': '/js/Upload.ashx',
            'folder': 'uploads',
            'fileDesc': 'Image Files',
            'fileExt': '*.jpg;*.jpeg;',
            'multi': true,
            'auto': false,
            'simUploadLimit' : 1,//如果沒限制有幾會上傳不完整
            'onComplete': function (event, ID, fileObj, response, data) {
                $("#msg").append(response + "<br/>");
            },
            'onError': function (event, ID, fileObj, errorObj) {
                alert(errorObj.type + ' Error: ' + errorObj.info + errorObj.status + errorObj.text);
            },
            'scriptData': { 'ASPSESSID': ASPSESSID,'AUTHID': auth }



        });
    }
);
            function cleanImg() {
                $("#msg").html("");
            }
</script>




Upload.ashx:

<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Web;
using System.IO;

public class Upload : IHttpHandler {

   
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        try
        {
            HttpPostedFile postedFile = context.Request.Files["Filedata"];
           
           // string savepath = "";
            string tempPath = "";
            tempPath = @"c:\temp\";
            //savepath = context.Server.MapPath(tempPath);
            string filename = postedFile.FileName;
            if (!Directory.Exists(tempPath))
                Directory.CreateDirectory(tempPath);

            string file2 = tempPath + filename;

            int count = 1;
            //if exist, filename "-" +1
            while (File.Exists(file2))
            {
                file2 = tempPath + filename + "-" + count + ".JPG";
                count++;
            }
           
           

            postedFile.SaveAs(file2);
            //context.Response.Write(file2.Replace("c:",""));
            context.Response.Write(context.Request["firstName"]);
            context.Response.StatusCode = 200;
        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message);
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}


他是每個file行一次Upload.ashx

Source download