2017年2月8日 星期三

web api 跨網站 post model

:System.Web.HttpApplication
繼承下加入 下列function


protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            //HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

標籤: ,

2016年7月25日 星期一

regex 取得特殊字串中間的內容

string body = "<a href=\"http://google.com\">Google</a>";

MatchCollection matches = Regex.Matches(body
, "href=\"(?<item>[^\"]+)\""
, RegexOptions.IgnoreCase);
   
foreach (Match match in matches)
{
     string a = match.Groups["item"].Value;
     //oupt: http://google.com
}

標籤:

2015年9月7日 星期一

MemoryStream 轉為實體檔案


var filePath = "C:/file.xls";
var ms = new MemoryStream();
FileStream fileStream = new FileStream(filePath , FileMode.Create, FileAccess.Write);
ms.WriteTo(fileStream);

標籤:

2015年2月3日 星期二

C# xml XDocument

            string result = string.Empty;
            XElement root1 = new XElement("root");

            for (int i = 0; i < 2; i++)
            {
                XElement item1 = new XElement("item",
                    new XElement("key", "test"),
                    new XElement("name", "aaa")
                );

                root1.Add(item1);
            }

            result = root1.ToString();


output:
<root>
  <item>
    <key>test</key>
    <name>aaa</name>
  </item>
  <item>
    <key>test</key>
    <name>aaa</name>
  </item>
</root>

標籤:

2014年12月31日 星期三

C# ashx 繼承

大家都知道,在ashx里面使用Session需要实现IRequiresSessionState接口。有时候我们需要判断此页面处理的请求是否是合法请求,比如说是登陆后的用户才可以请求,通常情况下都是通过Session来判断。但是每个界面写一个Session判断未免有显得太过于麻烦,所以我们可以通过实现一个基类,像我们平时写的BasePage一样,我们实现一个BaseHandler。代码如下:

/// <summary>
/// 如需要Session,ashx请继承此类并实现OnLoad方法
/// </summary>
public class BaseHandler : IHttpHandler, IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.Session == null)
        {
            context.Response.StatusCode = 405;
            context.Response.End();
        }
        if (context.Session["name"] == null)
        {
            context.Response.StatusCode = 405;
            context.Response.End();
        }
        OnLoad(context);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 代码实现
    /// </summary>
    /// <param name="context"></param>
    public virtual void OnLoad(HttpContext context)
    { 
    }
}

然后我们再回到ashx页面,现在我们来继承BaseHandler,不覆盖ProcessRequest,IsReusable方法,只需要实现OnLoad方法即可。如下:
public class test : BaseHandler
    {
        public override void OnLoad(HttpContext context)
        {
            string action = context.Request.QueryString["action"];
            if (string.IsNullOrEmpty(action))
                return;
           //DOSomething
        }
    }

參考資料:http://coderman.cn/archives/152

標籤:

2014年10月8日 星期三

html table 轉 excele


//result : html table 字串
private void OutPutExcel(string result) {
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "Big5";
        Response.AppendHeader("Content-Disposition", "attachment;filename=report.xls");

        // 如果設置为 GetEncoding("GB2312");導出的文件將會出現亂碼!!!
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.ContentType = "application/ms-excel";//設置輸出文件類型为excel文件。

        Response.Write(@"<html><head><meta http-equiv=Content-Type content=""text/html; charset=utf-8""></head><body>");
        Response.Write(result);
        Response.Write("</body></html>");
        Response.Flush();
        Response.End();
    }

標籤:

2014年8月9日 星期六

C# + Jquery 的Ajax換頁

.aspx

 <script src="js/jquery.pagebar_min.js" type="text/javascript"></script>

    <script type="text/javascript">

        //換頁      
        $(function () {
            changPage(1);
        });

         var total = 100;

        function page(idx) {
            var pagebar_arg = {
                firstPageText: "<span class=\"gr12\"> 第一頁</span>", //"第一頁",
                previousPageText: "<span class=\"gr12\"> 上一頁</span>", //"上一頁",
                nextPageText: "<span class=\"gr12\"> 下一頁› </span>", //"下一頁",
                lastPageText: "<span class=\"gr12\"> 最末頁››</span>" //"最末頁"
            };

            $("#pager").fadeIn().showPageBarPlus(total, <%= pageShowNum %>, idx, changPage, pagebar_arg);
        }


        function changPage(idx) {
           
                data = {
                    pageShowNum: <%= pageShowNum %>,
                    nodeId: <%= nodeId %>,
                    index: idx
                };

                $.ajax({
                    async: false,
                    type: 'post',
                    url: 'PageList.ashx',
                    data: data,
                    dataType: 'text',
                    success: function (s1) {    
                        //alert(s1);
                        if(s1.split("<%= sign %>").length >= 2){

                            $("#list").fadeIn().html(s1.split("<%= sign %>")[0]);
                            total = s1.split("<%= sign %>")[1];

                            //$("#totalNum").text(total);
                        }
                 
                    }


                });

                page(idx);
            }



    </script>

<body>
    <div id='list'></div>
    <div id='pager'></div>
</body>




PageList.ashx

    public void ProcessRequest (HttpContext context) {

        int pageShowNum = Int32.Parse(context.Request.Form["pageShowNum"]);
        int index = Int32.Parse(context.Request.Form["index"]);
        //int selectNodeTreeId = Int32.Parse(context.Request.Form["nodeTreeId"]);
        int nodeId = Int32.Parse(context.Request.Form["nodeId"]);

        StringBuilder sb = new StringBuilder();

        DBManger DBManger = new DBManger();
        DataSet ds = DBManger.GetPage(index, pageShowNum, "user");   //取得db資料

        DataTable dt = ds.Tables[1]; //搜出的資料
        int totalPage = (int)ds.Tables[0].Rows[0]["total"];

        sb.Append("<table>");
       
        //加入colume 名稱
        sb.Append("<tr class='White_box'>");
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            sb.Append("<th width=\"6%\">" + dt.Columns[i].ToString() + " </th>");
        }
        sb.Append("</tr>");

        //加入內容
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            sb.Append("<tr class=\"White_box\">");

            for (int j = 0; j < dt.Columns.Count; j++)
            {
                sb.Append("<td>" + dt.Rows[i][j].ToString() + "</td>");
            }
           
            sb.Append("</tr>");
        }
        sb.Append("</table>");


        string htmlStr = "";

        htmlStr = sb.ToString() + sign + totalPage;

        context.Response.ContentType = "text/plain";
        context.Response.Write(htmlStr);
    }

標籤: ,

2014年7月16日 星期三

C# 遞回 - 組ul

protected void Page_Load(object sender, EventArgs e)
    {

        string nodeStart = "15309";

        GetTree(nodeStart);
       
       
    }

    private void GetTree(string parentId)
    {
        List<NodeBase> nodeList = SelectNode(parentId);  //資料來源

        if (nodeList.Count != 0)
        {
            this.treeStr += "<ul>";

            foreach (NodeBase nb in nodeList)
            {
                this.treeStr += "<li id='" + nb.name + "'>" + "<a>" + nb.name + "</a>";
                GetTree(nb.id);
                this.treeStr += "</li>";
            }

            this.treeStr += "</ul>";
        }
    }

標籤:

2014年6月24日 星期二

C# 剖析 地址 regex

string zipCode = "", city = "", district = "", town = "", lin = "", road = "", sec = "", len = "", non = "", no = "", floor = "", at = "";

            var pattern = @"(?<zipcode>(^\d{5}|^\d{3})?)(?<city>\D{2}[縣市])?(?<district>\D+[鄉鎮市區])?(?<town>\D+[村里])?(?<lin>.+[鄰])?(?<road>\D+[路街大道])?(?<sec>.+[段])?(?<len>.+[巷])?(?<non>.+[弄])?(?<no>.+[號])?(?<floor>.+[樓Ff])?(?<at>[之-].+)?";

            Match match = Regex.Match(addr, pattern);

            zipCode = match.Groups["zipcode"].ToString();
            city = match.Groups["city"].ToString();
            district = match.Groups["district"].ToString();
            town = match.Groups["town"].ToString();
            lin = match.Groups["lin"].ToString();
            road = match.Groups["road"].ToString();
            sec = match.Groups["sec"].ToString();
            len = match.Groups["len"].ToString();
            non = match.Groups["non"].ToString();
            no = match.Groups["no"].ToString();
            floor = match.Groups["floor"].ToString();
            at = match.Groups["at"].ToString();

標籤: ,

2014年6月23日 星期一

C# call SQL stored procedure

using System.Data.SqlClient;
using System.Data;

string connStr = "Data Source=(local);Initial Catalog=SinoPacDocDB;Persist Security Info=True;User ID=sa;Password=sa";
        SqlConnection conn = new SqlConnection(connStr);


        SqlCommand cmd = new SqlCommand("Sp_Doc_MyDoc", conn);

        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Sel_PageSize", 10);
        cmd.Parameters.AddWithValue("@Sel_PageIndex", 0);
        cmd.Parameters.AddWithValue("@UserCode", "103190");

        conn.Open();

        SqlDataAdapter ad = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        ad.Fill(ds);
       

        conn.Close();

標籤:

2014年3月30日 星期日

C# Youtube 影片資訊 JSON (回傳影片瀏覽次數)



/// <summary>
/// 取得 Youtube 影片觀看次數
/// </summary>
/// <param name="youtubecode">Youtube 影片碼</param>
/// <returns></returns>
public static string GetYoutubeViewcount(string youtubecode)
{
    string url = string.Format("http://gdata.youtube.com/feeds/api/videos/{0}?alt=json", youtubecode);
    System.Net.HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    try
    {
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string retVal = reader.ReadToEnd();
            JObject googleSearch = JObject.Parse(retVal);
            return googleSearch["entry"]["yt$statistics"]["viewCount"].ToString();
        }
    }
    catch
    {
        return "0";
    }
}

參考網站:http://patw.idv.tw/blog/archives/521/asp-net-c-access-to-youtube-videos-watched/

標籤: