BloggerAds

2011年11月9日 星期三

[C#]在有驗證控制項的狀態下幫Button加上confirm (OnClientClick +Validator)


如果要對一個asp:Button控制項做再次詢問的動作(ex. 確認是否刪除? ),一般來說是可以直接這樣用:


<asp:Button ID="btnSubmit" runat="server" Text="OK" onclick="btnSubmit_Click"
    CausesValidation="true" OnClientClick="return confirm('are you sure?');"/>


而在有驗證控制項的狀況下,若還是用上面的return confirm方法,可是會讓驗證控制項失效的,所以要改成下列這種用法:

<asp:Button ID="btnSubmit" runat="server" Text="OK" onclick="btnSubmit_Click"
    CausesValidation="true" OnClientClick="if (Page_ClientValidate('[驗證群組]')) { return confirm('are you sure?');}"/>

其中 [驗證群組] 要記得改成你所設定的 ValidationGroup 

2011年11月1日 星期二

Google Analytics API called by C#

這是可以透過Google Analytics API 去抓出你網站的拜訪資料的功能,主要是送一個Request,再接收XML檔案,下面分兩段說明,首先是抓回XML的部份,:
(以下內容是參考 http://www.dotblogs.com.tw/lastsecret/archive/2010/10/06/18157.aspx )
private void GetXml() {  
        //送出request的網址
        var request = (HttpWebRequest)HttpWebRequest.Create(
            //在這是取國家的訪客數,參數可參考http://code.google.com/intl/zh-TW/apis/analytics/docs/gdata/gdataReferenceDataFeed.html#maxResults
            string.Format("https://www.google.com/analytics/feeds/data?"+                        
                            "ids=ga%3A{0}&dimensions=ga%3Acountry" +
                            "&metrics=ga%3Avisits&" +
                            "start-date={1}&end-date={2}&sort=-ga%3Avisits&max-results=10",
                            "12345678",  //Google Analytics 網站的ID
                            "2011-09-24",
                            DateTime.Now.ToString("yyyy-MM-dd")));

        //在header必須帶入token,token的取得請看下方的方法
        request.Headers.Add("Authorization", "GoogleLogin auth=" + GetAuthToken());

        try {
            var response = request.GetResponse();

            var responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd();

            //抓到XML, 存到暫存資料夾
            StreamWriter rd = File.CreateText(Server.MapPath("~/TempFile") + @"\Analytics_Country.xml");
            rd.Write(responseContent);
            rd.Flush();
        } catch (Exception ex) {
            Javascript.Alert(this.Page, "Error:" + ex.ToString());
        }
}

private static string GetAuthToken() {
        var postContent = string.Format(@"accountType=GOOGLE&Email={0}&Passwd={1}&service=analytics&source={2}",
                                         "Account", //Google 同號
                                         "PWD", //Google 密碼
                                         "1234"//隨便
                                        );

        byte[] bPostData = Encoding.ASCII.GetBytes(postContent);

        //參數與用法
        //參考http://code.google.com/intl/zh-TW/apis/accounts/docs/AuthForInstalledApps.html
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://www.google.com/accounts/ClientLogin");
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = bPostData.Length;

        var reqStream = new StreamWriter(req.GetRequestStream());

        reqStream.Write(postContent);
        reqStream.Flush();

        HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
        StreamReader repStream = new StreamReader(rep.GetResponseStream(), Encoding.UTF8);
        string ctx = repStream.ReadToEnd();

        //送出的response抓取token的值
        return Regex.Split(ctx, "Auth=", RegexOptions.IgnoreCase)[1];
     
    }  
再來是抓XML中的資料:
(以下內容是參考http://www.reimers.dk/jacob-reimers-blog/added-google-analytics-reader-for-net)
protected void GetData(object sender, EventArgs e) {
        //讀XML檔案
        XDocument xmlDoc = XDocument.Load(Server.MapPath("~/TempFile") + "/Analytics_Country.xml");
        XNamespace defaultSpace = xmlDoc.Root.GetDefaultNamespace();
        XNamespace dxpSpace = xmlDoc.Root.GetNamespaceOfPrefix("dxp");
     
        //LINQ  XML    
        var datas = from entry in xmlDoc.Root.Descendants(defaultSpace + "entry")
                    select new {
                        Country = entry.Element(dxpSpace + "dimension").Attribute("value").Value,
                        Value = entry.Element(dxpSpace + "metric").Attribute("value").Value
                    };
     
        foreach (var entry in datas) {          
            Response.Write("Country:" + entry.Country);
            Response.Write("Visits: " + entry.Value + "<br />");
        }
        //datas.ToDictionary<string, int>(m => m.Country, m => m.Value);
    }