顯示具有 IDE 標籤的文章。 顯示所有文章
顯示具有 IDE 標籤的文章。 顯示所有文章

2015年8月13日 星期四

Visual Studio 2015 的localDB

好久沒更新部落格…近半年已無時間跟體力在文章上,但依然遇到一些問題還是有做一些未經整理的筆記,有時間再一一補上來分享….

今年依然是個技術大爆發的一年,前陣子將開發環境重新安裝成 Win 10 + Visual Studio 2015後,原本在2013 Run的專案,SQL Server是用本機的localDB,但用VS 2015開已經連不上,至於什麼是localDB呢?可以看看保哥這篇文章:

再以往使用localdb你的連線字串可能看起來會是這樣:

<add name="ConnectionString" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=DataBaseName;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework" providerName="System.Data.SqlClient" />


再VS 2015 開始有了新的命名方式,必須改用 (localdb)\MSSQLLocalDB 來取代

<add name="ConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DataBaseName;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework" providerName="System.Data.SqlClient" />


當然,如果還是要用舊的執行個體,也可以下載安裝:


https://msdn.microsoft.com/zh-tw/sqlserver2014express.aspx


--


一點小筆記...

2014年10月3日 星期五

[鐵人30天]當ASP.NET MVC 遇見 Angular.js MVC 客戶管理系統(6) - 取得WebAPI資料

* 本篇目標

建置一個RESTful風格的Web服務

* Web API 2.2

現在開發通常會考慮到多平台,如手機平板等等,但關於資料來源不可能針對每個平台都去寫一樣的Code,早期.NET解決方案有Web Service、WCF Service的應用,.NET Freamwork 4.5後推出了更輕量化的Web API服務,搭配MVC架構開發上變得非常的輕鬆,本系列文章使用Web API 2.2。

延伸閱讀  [Web API] 初探 Web API 筆記

* 建置Web API

我們再UI層新增Web專案時,其實就已經勾選安裝Web API了,如果忘記選擇了,可以透過Nuget安裝。

a8dcf173f2614837b442e02a913799a9

WebAPI開發習慣,我通常會再專案底下建一個API資料夾,接著點選右鍵,加入Web API控制器

f247eb1d2af848babad98b146db3126a

建立以後,她預設會幫我們建立CRUD function,我們就針對每個function去改寫,注意Web API也是MVC架構,命名也是為Controller結尾,但不同的是Web API是繼承ApiController。

9c6601b5d9a54583bdc1d37aab8aae37

接下來我們將Get稍作修改,向BLL層要客戶資料,HttpReponseMessage可以很方便的讓前端知道是否有發生錯誤,並回傳自己定義的Object。

7b24c666c2444fae98ab71461d75553d

接著在瀏覽器執行,輸入 host/api/Customer即可取得我們的資料

a109f7e377e44ef48a866cb63d5a45ad

* 於MVC的Controller及View列出資料

接著我們再專案裡Contoller,新增一個CustomerController

e7bede476978464188a15b911f382cc7

在Controller使用WebClinet像Web API要資料

3dded709ab774d879f9ecd1cf1d1df83

在新增一個View,套入原本樣板的主體Layout

b47227cee9764b49a4fcc1a2ebd5c62b

使用ViewModel,並用好用的Razor語法印出資料

39321e5640db412282e6ee4a0567e661

結果畫面

8dc19f6dfc0745b28cd4d067c85db1f5

* 後記

我認為Web API是個趨勢,未來我也一定會採用這種架構,一方面MVC的Contoller不會有太多跟BLL Service溝通的code,且對於多專案平台,都可向WebAPI取得資料。但實務上我並不會將跟Web API的Code寫在Controller裡,而會是在前端的View,也就是Angular.js登場的時候了!

延伸閱讀ASP.NET MVC - 第一個Web API,Hello Web API

ASP.NET WEB API 心得筆記 (4) WEB API ROUTING

MSDN – MVC Razor語法

 

本系列程式原始碼請至我的Github下載  https://github.com/kyleap

** 如內容有誤請告知,將進行修改,謝謝 **

2014年2月16日 星期日

Visual Studio 2013–C#.JavaScript outline,一個摺疊程式碼(if else or for each)的小套件

這幾天發現一個小套件對Debug還蠻實用的,可以將程式碼摺疊起來,看程式邏輯時就會比較方便

安裝方式可透過Nuget

1111

Visual Studo 2010/2012也有支援,詳細效果與版本介紹可擴充功能頁面查看

http://visualstudiogallery.msdn.microsoft.com/6c3c5dec-1534-4c42-81b1-cfd4615fd0e9

至於Javascript則可下載 JavaScript outlining

1111

2014年1月23日 星期四

Chome瀏覽器開發工具分享(不定期更新)

工欲善其事,必先利其器,自從Chome出現之後已經取代我用firefox的習慣,當做主要開發的瀏覽器,而Chome其實不只是只有案F12開啟開發人員工具那麼簡單,還能下載很多的應用程式來搭配使用,以下就分享一些我常用的應用程式,文章會不定期更新!

安裝方式很簡單,點選連結後安裝即可。(如連結失效,請到Google商店輸入關鍵字)

  • Chrome 遠端桌面 - 你是IT fire man嗎 ? 需要遠端回公司救火嗎 ? 試試TeamViewer外的救火工具吧
  • IE Tab - 讓Chome也能執行IE瀏覽器的環境,並可預設開啟的IE模式
  • Eye dropper(拾色器) - 想查看網頁的色碼,或在配色時需要尋找相似顏色,這個調色盤工具非常方便
  • One Tab - Google 尋找問題時不知不覺開啟一堆頁籤,每個頁籤分頁變得跟螞蟻一樣小時就點這個按鈕吧,會幫你整理成群組
  • PostMan - 這不用多說了開發必備,撰寫REST介面的Web Service時搭配的好工具,可模擬表單POST
  • JSON View - 除了Json online viewer網站,你有另外一個選擇能查看json字串節點
  • Window Resizer - 想測試網站在各解析度下是否正常無跑版? 不要傻傻的切換電腦解析度阿,此外掛一鍵就能變更
  • Feedly - 忙碌之餘,別忘了訂閱RSS來吸收新知阿,一個Google RSS Reader的替代方案

以上,隨著更新越來越多我會在分門別類的整理,也歡迎留言告知我。

2014年1月12日 星期日

在SQL Server 2012 or LocalDB 附加安裝北風資料庫

微軟在以往SQL 2000時代就有提供北風資料庫(Northwind)供下載測試,安裝方式就不再多說,Google一下就有很多教學,例如此篇文章,而在SQL 2012後安裝後會發現無法附加,微軟又提供另一個範例資料庫叫Adventure Works 範例資料庫,雖然這個資料庫關聯很多,資料表命名也更整齊,但通常會用到範例資料庫應該都只是撰寫些Demo,不希望有太複雜關聯的資料庫吧,故本文章主要教學如何在SQL Server 2012安裝北風資料庫,以LocalDB為例。

以傳統附加方式會發生以下錯誤:

image

 

這主要是因為一些相容性問題導致附加失敗,而我們可以用另外一種方式來建立,首先先到從此下載的北風資料庫安裝檔,而預設安裝資料夾為C:\SQL Server 2000 Sample Databases,打開後會有以下檔案,打開instnwnd檔案

 

image

將以下兩行程式碼註解並執行

exec sp_dboption 'Northwind','trunc. log on chkpt.','true'

exec sp_dboption 'Northwind','select into/bulkcopy','true'

 

image

 

這樣就會發現建立完成了 : )

 

image


參考資料

http://buli.waw.pl/sql-server-2012-northwind-database/

2013年12月27日 星期五

KendoUI & ASP.NET MVC系列文章 - 處理CRUD-繼續完成新增、修改、刪除

前言

再前一篇我們已經完成利用Ajax來讀取後端資料顯示於Grid,而此篇就會將新增、修改、刪除功能接續完成

CRUD的 Create - 新增

Controller

利用原本樣板產生的程式做一些修改,原本程式如下

image

將上面程式修改為以下,透過MVC的Model Bindder可以接收前端傳來的Customers物件,並依情況回傳是否新增成功

image

View

將dataSrc新增一個Create function,指向後端的CreateCustomer,並在完成後alert處理結果

 image

Schema部分新增model定義,讓KendoUI知道你的模組結構,並且可設定一些欄位驗證

image

接著在屬性部分新增toolbar及editable,editable模式可分為inline(直接在Gird新增一個)或者是popup(彈跳視窗)方式,此例我們希望新增時是跳出一個燈箱視窗

image

結果圖

這樣就完成,在以往我們可能自己要實做View的頁面,現在KendoUI都幫你做好好的,且表單也排得很整理 lol

image


CRUD的Update-編輯

Controller

基本上跟新增大同小異,我們在Controller新增EditCustomer的JsonResult

image 

View

新增一個Update function

image

在columns多一個command成員,並設定edit按鈕(這邊也可以自訂義Button標籤)

image

這樣就完成編輯燈箱視窗了!!

image

CRUD的Delete-刪除

Contoller (這邊就不解釋了)

image

View

image

image

後記

以上是一種實做CRUD的方式,但其實做法有很多種,譬如你也可自訂新增、編輯的View去實做,或者你也可以自訂一些查詢欄位POST到後端去,關於版面,如果要修改中文的顯示其實也可以做到,之後也會分享一些實做心得PO上來。而下一篇,預計完將後端改成用WebAPI + OData的方式實做 =V=

完成程式碼

Contoller

public class GridAjaxController : Controller
{
private NorthwindEntities db = new NorthwindEntities();

// GET: /GridAjax/
public ActionResult Index()
{
return View();
}

public JsonResult GetCustomer(KendoGridRequest request)
{
try
{
var result = db.Customers.ToList();
return Json(new KendoGrid<Customers>(request, result), JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
Dictionary<string, object> error = new Dictionary<string, object>();
error.Add("ErrorCode", -1);
error.Add("ErrorMessage", "讀取資料失敗!");
return Json(error);
}
}

// GET: /GridAjax/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customers customers = db.Customers.Find(id);
if (customers == null)
{
return HttpNotFound();
}
return View(customers);
}

// GET: /GridAjax/Create
public ActionResult Create()
{
return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult CreateCustomer(Customers customers)
{
if (ModelState.IsValid)
{
if (TryUpdateModel(customers))
{
db.Customers.Add(customers);
db.SaveChanges();
return Json("新增成功!!");
}
}
return Json("新增失敗!!");
}

public JsonResult EditCustomer(Customers customers)
{
if (ModelState.IsValid)
{
db.Entry(customers).State = EntityState.Modified;
if (TryUpdateModel(customers))
{
db.SaveChanges();
return Json("更新成功!!");
}
}
return Json("更新失敗!!");
}

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult DeleteCustomer(string CustomerID)
{
Customers customers = db.Customers.Find(CustomerID);
db.Customers.Remove(customers);
if (TryUpdateModel(customers))
{
db.SaveChanges();
return Json("刪除成功!!");
}
return Json("刪除失敗!!");
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}

View

@model IEnumerable<KendoUI.Model.Customers>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/BaseLayoutPage.cshtml";
}

@section scripts
{
<script type="text/javascript">
$(function () {

//資料來源物件改用Ajax
var dataSrc = new kendo.data.DataSource({
transport: {
read: {
type: "POST",
url: "/GridAjax/GetCustomer",
dataType: "json",
complete: function (response, status) {
if (response.responseJSON.ErrorCode == -1) {
alert(response.responseJSON.ErrorMessage);
}
}

},
update: {
url: "/GridAjax/EditCustomer",
dataType: "json",
type: "POST",
complete: function (response, status) {
alert(response.responseJSON);
}
},
create: {
url: "/GridAjax/CreateCustomer",
dataType: "json",
type: "POST",
complete: function (response, status) {
alert(response.responseJSON);
}
},
destroy: {
url: "/GridAjax/DeleteCustomer",
dataType: "json",
type: "POST",
complete: function (response, status) {
alert(response.responseJSON);
}
},
},
schema: {
data: function (d) {
return d.data;
},
total: function (d) { return d.total; },
model: {
id: "CustomerID",
fields: {
product: { editable: false, nullable: false },
CompanyName: { validation: { required: true } },
ContactName: { validation: { required: true } },
City: { validation: { required: true } }
}
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
});

$("#gridData").kendoGrid({
dataSource: dataSrc,
columns: [
{ field: "CustomerID", title: "CustomerID" },
{ field: "CompanyName", title: "CompanyName" },
{ field: "ContactName", title: "ContactName" },
{ field: "City", title: "City" },
{ command: ["edit","destroy"], title: "&nbsp;", width: "160px" }
], //columns的field對應到customer資料表的欄位
sortable: true,
pageable: true,
filterable: true,
width: 800,
toolbar: ["create"],
editable: {
mode: "popup", //使用Popup的模式編輯資料
update: true, // 若設定為True,當按下Update才server資料
}
});
});
</script>
}
<div id="gridData"></div>


延伸閱讀




2013年12月25日 星期三

KendoUI & ASP.NET MVC系列文章 - 處理CRUD-使用Ajax讀取後端Model資料

前言

前兩篇為KendoUI基本的介紹,而此篇將會使用ASP.NET MVC來實做Ajax讀取資料。以下是本範例的環境:

Visual Studio 2013

ASP.NET MVC 5

Entity Framwork 6.0.2

北風資料庫(localdb)

以上逐一解釋就太佔篇幅了,將會整理一些學習資源於延伸閱讀裡

加入MVC的M (Model)

雖然新增一個MVC專案,就會將Model、View、Contoller三個資料夾拆分好,但實務上,因為Model通常會因為有複雜的關聯表或商業邏輯,所以通常即使是小專案,我還是會將Model變成是一個獨立的專案來處理。

在方案檔點選右鍵→新增專案

image

新增一個KendoUI.Model類別庫

image

在KendoUI.Model專案點右鍵,加入新項目,選擇ADO.NET實體資料模型

image

選擇從資料庫產生(這就是所謂的database first開發方式),而至於北風資料庫如何加到localDB,這邊就不多介紹了

image

選擇建立連線,輸入(localdb)\v11.0,並選擇已建好的資料庫

image

接著加入Customers資料表,本例將已此做Demo

image

接著我們回到Web專案,點選右鍵→加入參考,選擇我們的Model專案,接著整個方案Build一下,讓Web專案看得懂Model專案的class

image

加入MVC的C (Controller )

加入Contoller部分上一篇已經介紹過,而不同的是這次我們選擇自動新增view和基本的Entity Framework model

image

依照下圖,命名為GridAjax,資料來源為北風資料庫的Customers,還有載入上一篇所建置的layout(主要載入一些JQuery和KendoUI函式庫)

image 

新增完後會發現MVC已經幫我們建置好很陽春的Grid了

image 

而我們不需要用此陽春的Gird,再來就是將KendoUI Grid套用進去,我們先回到View,將內建產生的程式碼由以下程式碼替代,KendoUI Grid 的設置方式都不再多說,要注意的是,我們資料來源不再是像前一篇載入一個.js檔,而是用Ajax跟後端要資料。

@model IEnumerable<KendoUI.Model.Customers>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/BaseLayoutPage.cshtml";
}

@section scripts
{
<script type="text/javascript">
$(function () {
//資料來源物件改用Ajax
var dataSrc = new kendo.data.DataSource({
transport: {
read: {
type: "POST",
url: "/GridAjax/GetCustomer",
dataType: "json"
}
},
pageSize: 20,
serverPaging: true,
serverSorting: true
});

$("#gridData").kendoGrid({
dataSource: dataSrc,
columns: [
{ field: "CustomerID", title: "CustomerID" },
{ field: "CompanyName", title: "CompanyName" },
{ field: "ContactName", title: "ContactName" },
{ field: "City", title: "City" },
], //columns的field對應到customer資料表的欄位
sortable: true,
pageable: true,
filterable: true,
width: '800'
});
});
</script>
}
<div id="gridData"></div>

接著回到Contoller,預設是載入Index時就將Customers資料抓回來


image


但我們希望Grid是用Ajax的方式載入,故做以下小修改,先新增一個接收Ajax的function

private NorthwindEntities db = new NorthwindEntities();

// GET: /GridAjax/
public ActionResult Index()
{
return View();
}

public JsonResult GetCustomer()
{
var customers = db.Customers.ToList();
return Json(customers, JsonRequestBehavior.AllowGet);

}

這樣就很輕鬆的完成Gird繫結資料,但會發現這樣並沒有分頁的功能,所以我們接下來要實做


image


開啟偵錯模式,我們會發現POST過來的資料已有一些分頁的參數(take、skip、page、pagesize、sort),我們可以利用這些參數去進去分頁篩選或排序


image


但是其實不用這麼麻煩…有高手幫我們把這些事情都處理掉了!


首先再方案檔點右鍵,選擇管理Nuget套件,下載安裝KendoGridBinder


image


我們再將Contoller做以下修改,KendoGridRequest和Kendo這個類別就幫我們搞定了分頁排序等等功能

private NorthwindEntities db = new NorthwindEntities();

// GET: /GridAjax/
public ActionResult Index()
{
return View();
}

public JsonResult GetCustomer(KendoGridRequest request)
{
var result = db.Customers.ToList();
return Json(new KendoGrid<Customers>(request, result), JsonRequestBehavior.AllowGet);
}
而View我們增加以下schema的code,至於為什麼要增加此段呢?原因是因為KendoGridBinder這個套件回傳的JSON格式不太相同,他將所有資料放入一個名稱叫data的陣列,和回傳total的數字欄位
    var dataSrc = new kendo.data.DataSource({
transport: {
read: {
type: "POST",
url: "/GridAjax/GetCustomer",
dataType: "json"
}
},
schema: {
data: function (d) {
return d.data;
},
total: function (d) { return d.total; }
},
pageSize: 20,
serverPaging: true,
serverSorting: true
});

image


這樣就輕鬆完成一個多功能的Grid啦!!來看看執行結果吧


1.gif


後記


本篇會有點攏長,但希望用逐步的方式讓初學者能照步驟實做出來,如果對MVC已經相當熟悉的建議可以看黑暗大-在ASP.NET MVC 4中使用Kendo UI Grid 的文章,非常的簡潔明瞭!!


再來的幾篇我們將繼續完成新增、編輯、刪除功能!


延伸閱讀


如果對上列技術不太熟的,建議可以看看這些很棒的文章

mrkt 的程式學習筆記 - ASP.NET MVC 分層架構系列文
天空的垃圾場 – ASP.NET MVC系列文
[下載] 範例資料庫(含中文Northwind資料庫)
LocalDB:微软的新生代轻量级数据库-CSDN.NET
ASP.NET MVC 4 與 jqGrid 入門實作
Kendo UI API Reference

2013年12月23日 星期一

KendoUI & ASP.NET MVC系列文章 - 基本的Grid功能

前言

在上一篇我們介紹了開發KendoUI相關的準備工作後,這篇將會介紹網頁開發上最為常見的Grid功能,而此篇的目的希望使用MVC的View,來介紹KendoUI Grid的幾個好用功能。

建立MVC的View (如已熟悉可跳過此區塊)

在ASP.NET Webform我們有Master Page的頁面,用來放一些共用的Html(如header或footer),及一些共用的.js、.css檔,而在ASP.NET MVC我們所使用的為Layout Page,找到View裡面的Shared資料夾,點選右鍵加入新項目,選擇Layout Page並修改名稱為BaseLayoutPage.cshtml

image

接下來我們在這個共用的Layout載入KendoUI,載入的檔案在上一篇已經提過,而RenderSection可以把他想成是我們"挖的洞",如我新增了一個scripts的洞,目的就是讓使用此Layout的頁面,能在這個洞坑裡面寫一些JavaScript。

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/kendo/2013.3.1119/kendo.common.min.css")
@Styles.Render("~/Content/kendo/2013.3.1119/kendo.bootstrap.min.css")
@Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
@Scripts.Render("~/Scripts/kendo/2013.3.1119/kendo.web.min.js")
@RenderSection("scripts", required: false)
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>


接著我們到Controller資料夾,點選加入控制器,新增一個空白的Controller,此例命名為BaseController


image


將ActionResult重新命名為BaseGrid,點選新增檢視


image


Layout Page記得選擇我們剛剛建的BaseLayoutPage.cshtml


image


如此我們就建立了一個View了,下個段落將開始實做KendoUI的Grid!


image


建立KendoUI Grid的資料繫結


此篇重點會在介紹Grid的基本功能及屬性,故不會使用到MVC的Model,故我會載入一個.js檔來當資料來源


而打開這個.js檔,主要就是定義一個products的物件

var products = [{
ProductID: 1,
ProductName: "Chai",
SupplierID: 1,
CategoryID: 1,
QuantityPerUnit: "10 boxes x 20 bags",
UnitPrice: 18.0000,
UnitsInStock: 39,
UnitsOnOrder: 0,
ReorderLevel: 10,
Discontinued: false,
Category: {
CategoryID: 1,
CategoryName: "Beverages",
Description: "Soft drinks, coffees, teas, beers, and ales"
}
}

接著我們在html新增一個div標籤,ID命名為gridData

<div id="gridData"></div>

接著在剛剛挖的scripts區塊加入以下程式碼,就可以完成Grid的資料繫結了,對我來講,這些程式碼的功能和屬性設置方式並不會很難懂,故上手其實蠻容易的,且對於欄位的設定,還能針對價錢做格式的轉換,不用在程式另外處理。

@section scripts
{
<script src="~/Scripts/products.js"></script>
<script type="text/javascript">
$(function () {
//建立資料來源
var dataSrc = new kendo.data.DataSource({
data: products, //指定products.js的products陣列
schema: {
model: {
fields: {
ProductName: { type: "string" },
UnitPrice: { type: "number" },
UnitsInStock: { type: "number" },
Discontinued: { type: "boolean" }
}
}
},
pageSize: 20 //每筆顯示頁數設定為20
});

$("#gridData").kendoGrid({
//Grid的屬性及功能設置都可加在以下程式區塊
dataSource: dataSrc,
height: 500,
pageable: {
input: true,
numeric: false
},//分頁導覽顯示
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
{ field: "UnitsInStock", title: "Units In Stock", width: "130px" },
{ field: "Discontinued", width: "130px" }
]
});
});
</script>
}

image


KendoUI Grid功能介紹


KendoUI Grid提供的功能非常多,以下介紹幾個我覺得不錯的功能,會發現以往要另外寫程式處理的功能,現在只要指定一個屬性就可完成了 lol


詳細可搭配此API文件的Configuration去設定http://docs.kendoui.com/api/web/grid

filterable: true (欄位篩選)
image 
sortable: true (欄位排序)
image 
selectable: true (選取某列)
image 


resizable: true (欄位寬度拖曳)

groupable: true (欄位群組分類)
image 

其他小技巧


Grid在很多頁面都會使用到時,不仿將基本的設置移至VS的工具箱,下次使用時直接拖拉即可


1


後記


這兩篇我們都沒寫到什麼程式  囧 !! 主要都在KendoUI Grid的基本功能,而再來的幾篇,我們將會實做搭配後端Model做為資料來源,漸漸的完成實務上碰到的情況。


參考資料


http://demos.kendoui.com/web/overview/index.html