顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

2015年6月25日 星期四

[C#][php] POST json data TO a PHP page

原本只是很簡單的,跨頁傳值從C#到php
沒想到搞了半天,php那端一直接收不到json值


string json = "{\"user\":\"test\"," +
                "\"n\":\"2\"}";
var webAddr = "http://";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.ContentLength = json.Length;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
     streamWriter.Write(json);
     streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
     var result = streamReader.ReadToEnd();
     //return result;

}


找了很久,原來是php那端看不懂,C#這邊傳過去的json格式
在php接收那端需加上

// Error handling is left as an exercise
$input = json_decode(file_get_contents('php://input'), true);

這樣就行了,然後這是php端的改法
C#端也有另一種寫法


string postData = "user=" + HttpUtility.UrlEncode("test") +
                  "&n=" + HttpUtility.UrlEncode("2");

byte[] byteArray = Encoding.ASCII.GetBytes(postData);

string postData = "json=" +
                HttpUtility.UrlEncode(serializer.Serialize(p));

php端:

$json_array = json_decode($_POST['json']);

2015年2月13日 星期五

[php]Object search value LIKE list.where

在C#中有

List.Where(x => x.value == value).ToList();

那在PHP中也有類似的

value = 5;
$Result = array_filter (
    $Object, function($x) use (value) {
        if(($x['value']) == value)
        return $x;
    }
);

回傳是一組Object


2014年10月28日 星期二

強制下載檔案

現在瀏覽器日新月異,像PDF檔之類的

按下去不像以前是下載,而是開新頁幫你打開檔案

而下面這個方面是讓檔案直接下載

先開一個新的頁面,把下載路徑導到那頁

下面為程式碼

//設定要下載的檔案路徑  
string path = 下載路徑;
strFileName = 檔名 + 副檔名;
//宣告並建立WebClient物件
WebClient wc = new WebClient();

//載入要下載的檔案
byte[] b = wc.DownloadData(Server.MapPath(path));

//清除Response內的HTML
Response.Clear();

//設定標頭檔資訊 attachment 是本文章的關鍵字
Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);

//開始輸出讀取到的檔案
Response.BinaryWrite(b);

//一定要加入這一行,否則會持續把Web內的HTML文字也輸出。
Response.End();

[Web Form] google站內搜尋FancyBox應用

有了Google後,現在站內搜尋很方便

照著Google的方法,一步一步走,然後貼上程式碼就OK了

Google自訂搜尋 ,但這不是我要說的!


然後也因為很方便,所以樣式反而都是公版

以下是用FancyBox應用,而達成自訂Google搜尋樣式

也有浮動視窗的效果。

首先你需要先去Google申請ID,上方連結有

再來再去下載 fancybox

之後你要確定你會點程式!

1.在你的專案裡開一個新的webform在body加入

    <form id="form1" runat="server">
    <div>
        <div id="cse" style="width: 100%;">Loading</div>
        <script src="http://www.google.com/jsapi" type="text/javascript"></script>
        <script type="text/javascript">
            function parseQueryFromUrl() {
                var queryParamName = "q";//接收參數的名稱
                var search = window.location.search.substr(1);
                var parts = search.split('&');
                for (var i = 0; i < parts.length; i++) {
                    var keyvaluepair = parts[i].split('=');
                    if (decodeURIComponent(keyvaluepair[0]) == queryParamName) {
                        return decodeURIComponent(keyvaluepair[1].replace(/\+/g, ' '));
                    }
                }
                return '';
            }

            google.load('search', '1', { language: 'zh-TW' });
            google.setOnLoadCallback(function () {
                var customSearchControl = new google.search.CustomSearchControl('google申請的ID');

                customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
                customSearchControl.draw('cse');
                var queryFromUrl = parseQueryFromUrl();
                if (queryFromUrl) {
                    customSearchControl.execute(queryFromUrl);
                }
            }, true);
        </script> 
        <link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />
    </div>
    </form>

2.在你有搜尋欄的那個頁面加入

<link href="Scripts/jquery.fancybox-1.3.4.css" rel="stylesheet" />
<script src="Scripts/jquery.fancybox-1.3.4.pack.js"></script>

3.設定你TEXT的ID,跟Button onclick的function

    <form>
        <input type="text" id="txtSearch" placeholder="Search" />
        <button type="button" onclick="search()">SEARCH</button>
    </form>

4.同搜尋欄那一頁,寫function

<script>
    function search() {
        var q = $("#txtSearch").val();
        if (q != "") {
            $.fancybox({
                'href': '剛剛新增的頁面.aspx?q=' + q,//傳遞的參數
                'type': 'iframe',
                'padding': 0,
                'closeBtn': false,
                'width': 690,
                'height': 500,
                'overlayOpacity': '0.6'
            });
        }
    }
</script>

設定完後,你就可以用你自己的搜尋框去站內搜尋了。

參考:冠譯

2014年10月23日 星期四

在沒有placeholder的時候,TEXT的提示字

就如題,現在HTML5,TEXT裡有placeholder可以用

以前沒有這功能時,用JavaScript實現

<input type="text" name="search" id="search" value="" onfocus="onfocusState()" onblur="onfocusState()"/>
     
function onfocusState() {
    if (document.getElementById("search").value == "請輸入關鍵字....") {
        document.getElementById("search").value = "";
    } else if (document.getElementById("search").value == "") {
        document.getElementById("search").value = "請輸入關鍵字....";
    } else { }
}

2014年10月13日 星期一

[Web Form] 下拉選單jQuery塞值,後台取不到值

因為舊站台翻新

原本下拉選單要postback回後台取值方式

都改成jQuery的方式,在前台轉換


在前台submit到後台取值存檔時

<asp:Button runat="server" Text="確定送出" OnClick="submit" /> 

下拉選單

<select name="selectid" id="selectid" runat="server"></select>

在後台

string select_id = selectid.Value;

竟然是取不到值的,其實這邊我也不知道為什麼!

如果有哪位高手大大,知道的話,麻煩留言告知小弟一下,感謝!


最後解決的方式是

先建一個hidden,在下拉選單轉換時

<input type="hidden" name="hidselectid" id="hidselectid" runat="server" />
var selectid = $('#ctl00_ContentPlaceHolder1_selectid');
selectid.change(function () {
    $('#ctl00_ContentPlaceHolder1_hidselectid').val(selectid.val());
});

把值塞到hidden裡,這樣後台就可以取到hidden裡的值來用了。

2014年10月6日 星期一

alert 中換行!

一般來說 C# 字串中換行

我們會寫成 "這是一個\n字串"

但這在alert("這是一個\n字串"); 這樣是不行的!

要把"\n"改今"\\r",這樣就OK了


該死的n,害我的一直alert不出來!!

2014年10月1日 星期三

Cookie 中文存取

中國文字博大精深,所以連Cookie存取都要先編碼((咦

HttpContext context = HttpContext.Current;
HttpCookie acookie = new HttpCookie("admin");
acookie.Values["uname"] = HttpUtility.UrlEncode("中文");//編碼
context.Response.AppendCookie(acookie);


HttpCookie aCookie = context.Request.Cookies["admin"];

HttpUtility.UrlDecode(aCookie.Values["uname"]).ToString()//解碼

2014年9月25日 星期四

OAuth 2.0 & Google+ API_LOGIN

這幾天因為公司需求
研究了一下OAuth 2.0  的 Google+ API 登入

官網的解說

很快的建立一個測試專案,迅速的 copy paste

興高采烈的執行專案


看到了"登入",看來是成功一半了!!





結果按下去卻.......


Error:invalid_client

查了一下 用戶端 ID 跟 JAVASCRIPT 起點

都正確啊!!沒理由不行啊!


花了我快三個小時,終於在  找到了同樣的問題


原來是在 developers.google.com 專案裡 API和驗證 => 同意畫面 => 專案名稱

這個專案名稱一定要"設名稱"……搞了那麼久。

2014年9月21日 星期日

.NET 3.5 maxJsonLength設定

在.net 3.5 上設定 maxJsonLength 原本以為跟 4.0 一樣在

Web.Config



<configuration> 
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="50000000"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration> 

就好,結果一直出現未定義<webServices>的錯誤。

GOOGLE了一下 ,還真的是 .net 3.5搞的鬼!

要在 web.config 裡多加一些東西

  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false"/>
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
          <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
          <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
          <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
        </sectionGroup>     
      </sectionGroup>
    </sectionGroup>
  </configSections>

這樣就解決啦!

2014年8月21日 星期四

'/' 應用程式中發生伺服器錯誤。

最近開發.net的時候,遇到了下面這種錯誤。

因為也是第一次遇到,所以就GOOGLE了一下原來是服務被關掉。

無法將工作階段狀態要求送至工作階段狀態伺服器。請確定 ASP.NET 狀態服務已經啟動且用戶端與伺服器的通訊埠都相同。如果伺服器是在遠端電腦上,請檢查 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection 的值,確定它是否接受遠端要求。如果伺服器是在本機電腦上,而且前述登錄值不存在或設定為 0,狀態伺服器連接字串就必須使用 'localhost' 或 '127.0.0.1' 做為伺服器名稱。

2014年8月19日 星期二

ASP.NET 4.5-C#-FileUpload控制項-一次上傳多個檔案

前台:
            <asp: FileUpload ID ="FileUpload1" runat="server" AllowMultiple="true" />

後台:
            foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
            {
                fileName = postedFile.FileName;
                FileNameAll = FileNameAll + fileName + ",";
                // –完成檔案上傳的動作。
                savePath = appPath + saveDir + fileName;
                postedFile.SaveAs(savePath);
            }


PostedFiles這個函數,在4.5才有喔!切記!