2018年11月9日 星期五

[MVC] WebAPI and Azure Blob Storage Upload - 簡易的將檔案上傳到Azure Blob Storage

因為工作有用到,所以在這裡留下有關於檔案上傳到Azure Blob Storage 的紀錄


1. Azure Storage
先到Azure Storage中 設定完Blob 儲存體後,取得連線字串



然後建立好Blob Container



將連線字串加入WebConfig中

    <add key="FileUploadAzureBlob" value="DefaultEndpointsProtocol=https;AccountName={blob_storage_name};AccountKey**********************;EndpointSuffix=core.windows.net" />


2. 在前端Html 中先建立 類別為file 的 Input  以及 Upload 的按鈕



<input class="col-md-12" id="inputFile" multiple="" name="files[]" type="file" />
<button class="btn btn-success" id="btnUpload" type="button"> Upload </button>

如下所示 :

3. 在JavaScript的區塊中建立 Upload 按鈕的Event




 $(document).on('click', '#btnUpload', function () {
        var files = $('#inputFile')[0].files;

        //FormData 是Html表單中的 <form > 
        //此處我們利用建立表單的方式儲存檔案
        //之後再透過Ajax的方式,將檔案傳遞到 WebApi 或Controller 
        var fileData = new FormData();
        $.each(files, function (i, o) {
            fileData.append(o.name, o);  //將檔案"們" Append 進表單
        });
        

        if (Object.keys(files).length < 1) {
            return;       //若input 中沒有檔案,就不使用Ajax
        } 

    
        $.ajax({
            url: '/AzureApi/Upload/',
            type: "POST",
            contentType: false, // 不設定任何的 Content Header
            processData: false, // 不進行資料轉換的步驟
            data: fileData,     //將檔案放進body中
            success: function (result) {
                alert('檔案上傳成功');
            }
        });
    });

4. WebApi的建立
這裡會使用到 WindowsAzure.Storage 的Nuget 套件
著手紀錄的時候最新版本為 9.3.2,未來有更新的版本還是建議使用新的版本
請參照 : NuGet Gallery







using Microsoft.WindowsAzure.Storage;            //引用
using Microsoft.WindowsAzure.Storage.Blob;       //引用

namespace TASSWeb.Controllers.Api
{

    public class AzureApiController : BaseApiController
    {

        [HttpPost]
        [Route("AzureApi/Upload/")]       
        public async Task PostUpload()
        {
            //FormData Setting 
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);   //將檔案放進provider內

            //Connection String , and Azure Blob Container 
            string sConnStr = System.Configuration.ConfigurationManager.AppSettings["FileUploadAzureBlob"].ToString();
            string sContainer = "filupload"; //需要為小寫英文字母

            //建立與Storage的連線以及認證
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(sConnStr);

            //連接到Blob Client
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

           //使用GetBlockBlobReference去取得 CloudBlockBlob 物件的參考
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(guFileID.ToString());

           //將provider內的資料轉為Stream
           Stream filestream = await provider.Files[0].ReadAsStreamAsync();

            //檢查容器是否存在,不存在則建立
            container.CreateIfNotExists();
            try
            {
                //使用UploadFromStream 將Stream的檔案上傳至Azure Blob Storage 中的Container
                //UploadFromStream  或是 UploadFromStreamAsync 這兩種方法 都會已覆蓋的方式上傳檔案
                blockBlob.UploadFromStream(filestream);
            }
            catch (Exception ex){
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
    }
}

2018年7月29日 星期日

[Azure WebApp] TimeZone

因網站發布至Azure Web Application 之後,發現凡是使用到


DateTime.Now();

通通一率是UTC時間。

經同事查證,只單純修改WebConfig 的時間是無效的,
需要在 Azure WebApp 中 設定 [ 應用程式設定 ]

實際操作如下 :


圖1.Web Application 中點選應用程式設定



圖2. 輸入應用程式設定 WEBSITE_TIME_ZONE    :    自己的時區  (eg. Taipei Standard Time )。






參考:



2018年6月18日 星期一

C# Connection String & DataAdapter Fill

  以前的紀錄不見了,只好重新紀錄一次常用的Connection String .

在Web.config 中 新增 Connectionstring
----------------------------------------------------------------------------------------------------------------------

  <connectionStrings> 
    <add name="ConnectionString1" connectionString="Data Source=DatabaseName;Initial Catalog=AdventureWorksLT2008;Persist Security Info=True;User ID=xx;Password=xxxxxxxxx" providerName="System.Data.SqlClient"/> 
  </connectionStrings> 
 
----------------------------------------------------------------------------------------------------------------------
 在aspx中新增telerik GridView
---------------------------------------------------

   <div>

        <telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging="True" Skin="MetroTouch"></telerik:RadGrid>

        <asp:Label ID="Label1" runat="server" Text="Label"/>

    </div>

----------------------------------------------------------------------------------------------------------------------
aspx.cs中 新增 DataBind 的Function ,並在頁面啟動時就呼叫
---------------------------------------------------

protected void Page_Load(object sender, EventArgs e)

    {

        //呼叫Function

        DataBind_GridView();

    }

----------------------------------------------------------------------------------------------------------------------
Function 
---------------------------------------------------

    // Function Start

    private void DataBind_GridView() {

       //Connection String

        string Connection1 = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;

        string selectDB = "SELECT * FROM SalesLT.Customer";     

    

        SqlConnection db = new SqlConnection(Connection1); //new Sql 連線

        SqlCommand cmd = new SqlCommand(selectDB, db); //Sql Command

        SqlDataAdapter da = new SqlDataAdapter(cmd);

        DataSet ds = new DataSet();

        da.Fill(ds);

        RadGrid1.DataSource = ds;

    }





----------------------------------------------------------------------------------------------------------------------

[MVC] 錨點 , 跨頁錨點

1. 普通錨點

<a href="#id1">Test 錨點</a>

or
<button type="button" onclick="location.href='#id1'">
2.跨頁錨點
<a href='@Url.Action("Action", "Controller")#id1'>
or
<button type="button" onclick="location.href='@Url.Action("Action", "Controller")#id1'">


參考自 :

kyle'sBlog - MVC使用錨點

2018年6月8日 星期五

[Debug] 重複名稱的烏龍

從Index帶進Get頁面的參數, 如果與Model的欄位命名相同,

會產生Model.Validate Error , Hiddenfor的 Value會被替換掉
Eg.

1.傳進的參數  與Model欄位的 Myear相同



2. 會造成Model綁定錯誤 , 影響到Model的驗證






解決方法 :

把傳入的參數  Myear 改成別的名子就好







問題解決!!









2017年7月24日 星期一

[Oracle DB 紀錄] OpenQuery 訊息 7302,層級 16,狀態 1,行 1 無法建立連結伺服器 "(null)" 的 OLE DB 提供者 "Microsoft.ACE.OLEDB.12.0" 的執行個體。

訊息 7302,層級 16,狀態 1,行 27
無法建立連結伺服器 "(null)" 的 OLE DB 提供者 "Microsoft.ACE.OLEDB.12.0" 的執行個體。



若出現以上錯誤訊息,則可先確認 是否安裝 64位元版本 (http://goo.gl/8NtKXO) ,
或確認 Microsoft.ACE.OLEDB.12.0 是否有在屬性中開啟權限




DataTable 的資料呈現,由直向轉橫向呈現


將DataTable 由直轉橫向

稍早,因特殊需求的關係,User 有提到希望能以橫式的方式來顯示從資料庫取得的資料。

所以實作了將DataTable 內的資料由直向轉為橫向顯示的方法,
目前已交付使用,且運作一段不短時間後仍舊正常,
所以寫下此篇文章作為紀錄  (以下將利用模擬資料進行)。



Ex :

圖、1 直向的資料


          #region 準備範例資料
            //建立DataTable
            DataTable dt = new DataTable();
            //新增2欄位
            dt.Columns.Add("Name");
            dt.Columns.Add("TEL");

            //寫入直向的10筆資料
            for (int i = 1; i < 11; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = "A" + i;
                dr[1] = "B" + i;
                dt.Rows.Add(dr);
            }
            #endregion


開始進行轉換

先準備好新的DataTable, 並產生Columns
           //建立新的DataTablle
            DataTable dtNew = new DataTable();
            for (int i = 1; i < 4; i++)
            {
                dtNew.Columns.Add("Name" + i);
                dtNew.Columns.Add("TEL" + i);
            }


圖、2 新的橫向DataTable

開始將直向的資料(舊的) 放進新的DataTable

            #region  開始準備進行轉為橫向
            //dtNew 的新DataRow
            DataRow drNew = dtNew.NewRow();
            int iLast = 1;          //用來記錄跑到第幾個舊資料列

            //用來說明寫入的是新資料列的第幾個Cell
            int iCellCount = 0;

            //開始by 每一個舊資料的Rows 寫入新的DataTable
            foreach (DataRow item in dt.Rows)
            {
                //寫入每個Rows的特定Column內
                drNew[iCellCount] = item["Name"].ToString();
                drNew[iCellCount + 1] = item["TEL"].ToString();
                iCellCount = iCellCount + 2;        //用來計算第幾個Column

                //如果裝滿了一個Row,就在dtNew中新增新的Row
                if (iCellCount &gt;= 6)
                {
                    iCellCount = 0;
                    dtNew.Rows.Add(drNew);
                    drNew = dtNew.NewRow();
                }
                //如果是最後一筆資料,直接新增進dtNew
                else if (iLast == item.Table.Rows.Count)
                {
                    dtNew.Rows.Add(drNew);
                }

                //紀錄 +1 
                iLast += 1;
            }

            #endregion


圖、3 完成後的資料


我相信一定會有更好的方法可以將DataTable 由直向轉為橫向呈現,也歡迎各位用力鞭打。

但目前還沒有知道更好的方法之前,可能先暫時以這種方式進行囉!!