2014年12月3日 星期三

Tips : 串接擴充方法–C#

 

Tool:Visual Studio 2013 Ultimate Update 4
OS:Windows 8.1

在C#中,可以定義Extension Method (擴充方法),為型別新增新功能,例如以下為String型別新增Print1與Print2方法,在Main方法中,所有字串都可以叫用Print1與Print2方法,但是要分兩行叫用:

class Program {
  static void Main( string[ ] args ) {
    string s1 = "mary";
    s1.Print1( );
    s1.Print2( );
  }
}
static class StringExtension {
  public static void Print1( this string s ) {
    Console.WriteLine( "Print 1 : " + s );
  }
  public static void Print2( this string s ) {
    Console.WriteLine( "Print 2 : " + s );
  }
}

2014年12月2日 星期二

Visual Studio 2015 新功能 1 - 除錯Lambda

 

Tool:Visual Studio 2015 Preview、Visual Studio 2013 Update 4

在Visual Studio 2013 除錯Lambda Expression時,除錯視窗總是會出現Expression cannot contain lambda expressions的錯誤訊息,不允許進一步做除錯動作。

2014年12月1日 星期一

使用OData擴充ASP.NET Web API

 

Tool:Visual Studio 2013 Ultimate Update 4、OData Client Code Generator
OS:Windows 8.1
Microsoft ASP.NET Web API 2.2 for OData v4.0

本文改自原<使用OData擴充ASP.NET Web API>一文上半段。因ASP.NET Web API與OData開發相關套件改版,以致於程式語法和步驟有些不同。更新工具與設計步驟如下:

2014年11月28日 星期五

常用NuGet指令

 

Tool:Visual Studio 2013 Ultimate Update 4
OS:Windows 8.1

以下記錄常用的NuGet指令

先開啟Package Manager Console :

image

MVC路由除錯工具

Tool:Visual Studio 2013 Ultimate Update 4
OS:Windows 8.1
ASP.NET MVC 5

若要偵測MVC路由,可以使用NuGet安裝routedebugger工具。

使用Area產生的例外錯誤

Tool:Visual Studio 2013 Ultimate Update 4
OS:Windows 8.1
ASP.NET MVC 5

在ASP.NET MVC5專案中建立Area時發生例外錯誤:

Multiple types were found that match the controller named 'Home'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.

2014年10月28日 星期二

客製化MVC Scaffolding Template

 

Tool:Visual Studio 2013 Ultimate Update 3
OS:Windows 8.1
ASP.NET MVC 5

在Visual Studio 2013建立MVC5專案時,若使用預設的Scaffolding Template產生出來的View,都會直接套用Bootstrap 樣式,這對於不使用Bootstrap的專案而言,有點困擾,你可以選擇客製化Scaffolding Template。

以下是客製化Scaffolding Template步驟:

使用ScaffolderTemplates快速套用Attribute Routing

 

Tool:Visual Studio 2013 Ultimate Update 3
OS:Windows 8.1
ASP.NET MVC 5

ASP.NET MVC5支援Attribute Routing的功能,可參考<ASP.NET MVC5 Attribute Routing簡介>一文。若要在MVC專案中快速產生支援AttributeRouting的控制器,可以利用現成的ScaffolderTemplates。

參考以下步驟:

使用jQuery載入Partial View

 

Tool:Visual Studio 2013 Ultimate Update 3
OS:Windows 8.1
ASP.NET MVC 5

以下步驟展示建立一個MVC5範本專案,並利用jQuery載入Partial View

ViewBag & ViewData

 

Tool:Visual Studio 2013 Ultimate Update 3
OS:Windows 8.1
ASP.NET MVC 5

在Controller的Action Method要傳資料到View,可以使用ViewBag或ViewData。ViewBag底層是透過ViewData來實作,提供一種比較簡易的撰寫語法。

ViewBag是dynamic的,因此有一個限制,不能夠當做擴充方法的參數。

 

2014年8月6日 星期三

切割appSettings設定到外部檔案

 

若ASP.NET WebSite網站組態檔定義appSettings,描述文件路徑:

<configuration>
  <appSettings>
    <add key="docPath" value="c:\doc"/>
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
  </system.web>

</configuration>

 

切割組態檔案

在.NET程式中,常常使用組態檔案,有些設定要在不同專案中重複使用,你可以將常常重複使用的區段儲存在個別的config檔案,以方便重複使用。

 

2014年8月4日 星期一

Q&A : 使用HttpClient呼叫ASP.NET Web API

如何使用HttpClient呼叫ASP.NET Web API?

若有一個ASP.NET Web API程式如下:

public class EmployeesController : ApiController {
  static List<string> employees = new
  List<string> { "Mary" , "Candy" , "Lilly" , "Betty" , "Jessica" };
  public IEnumerable<string> Get( ) {
    return employees;
  }
  public string Get( int id ) {
    return employees[ id ];
  }
  public void Post( [FromBody]string value ) {
    employees.Add( value );
  }
  public void Put( int id , [FromBody]string value ) {
    employees[ id ] = value;
  }
  public void Delete( int id ) {
    employees.RemoveAt( id );
  }
}


我們可以使用HttpClient來進行呼叫,以下範例在Console 程式呼叫Get:



static async void Gettest( ) {
  HttpClient client = new HttpClient( );
  client.BaseAddress = new Uri( "http://localhost:25201/" );
  HttpResponseMessage resp = client.GetAsync( "api/employees" ).Result;
  IEnumerable<string> data = null;
  if ( resp.IsSuccessStatusCode ) {
    data = resp.Content.ReadAsAsync<IEnumerable<string>>( ).Result;
    foreach ( var item in data ) {
      Console.WriteLine( item);
    }
  }
}

POST,新增一筆


static async void posttest( ) {
  var client = new HttpClient( );
  client.BaseAddress = new Uri( @"http://localhost:25201/" );
  var response = await client.PostAsJsonAsync( "api/employees" , "hahaha" );
  if ( response.IsSuccessStatusCode ) {
    Console.WriteLine( "Inserted");
  }
}



PUT,修改第一筆


static async void puttest( ) {
  var client = new HttpClient( );
  client.BaseAddress = new Uri( @"http://localhost:25201/" );     
  var response = await client.PutAsJsonAsync( "api/employees/0" , "new xxx" );
  if ( response.IsSuccessStatusCode ) {
    Console.WriteLine( "updated" );
  }
}
DELETE第一筆


static async void deletetest( ) {
  var client = new HttpClient( );
  client.BaseAddress = new Uri( @"http://localhost:25201/" );
  var response = await client.DeleteAsync( "api/employees/0" );
  if ( response.IsSuccessStatusCode ) {
    Console.WriteLine( "deleted" );
  }
}

2014年7月24日 星期四

Tips : Visual Studio 2013 Color Theme Editor

 

Tool:Visual Studio 2013 Ultimate Update 2
OS:Windows 8.1

Visual Studio 2013 Color Theme Editor可以為Visual Studio 2013開發工具編輯自己喜歡的色系。

  • Tools->Extensions and Updates,下載:

image

 

2014年7月14日 星期一

好用的Web API Test Client - 2

 

Tool:Visual Studio 2013 Ultimate Update 2
OS:Windows 8.1
IIS : IIS 8
.NET Framework : 4.5.5
Browser : Chrome

你可以將測試Web API的請求儲存在Collection,方便後續在其它電腦上測試

  • 新增Colleciton

image

  • 取名稱

image

  • 編輯Request,並加到Collection

image

  • Add To Collection

image

  • 加入POST

image

image

  • 加入PUT

image

imageimage

  • 加入DELETE

image

image

 

  • 下載Colleciton設定

image

image

  • 可以另存成一個檔案

image

  • 之後可以載新環境中匯入

image

好用的Web API Test Client

 

Tool:Visual Studio 2013 Ultimate Update 2
OS:Windows 8.1
IIS : IIS 8
.NET Framework : 4.5.5
Browser : Chrome

 

除了使用強大的Fiddler工具來除錯Web API 之外,有個Postman - REST Client,可以搭配Chome瀏覽器使用。你可以從Chrome線上應用程式商店免費下載。

  • 使用Visual Studio建立 Web API專案來測試:

image

  • 在api範本程式中的每個method設中斷點:

image

  • 按F5執行
  • 開啟Chrome,下載Postman – REST Client

image

  • 執行

image

  • 輸入API的URI,叫用Get

image

  • VS會進入中斷點,表示呼叫Get:

image

  • 按F5執行程式
  • 取得執行結果

image

  • POST測試

image

  • value有正確傳到method

image

  • PUT測試

image

  • 叫用put,且資料正確送到value

image

 

  • DELETE測試

image

  • VS收到id

image

2014年7月8日 星期二

Web Form Scaffolding

 

Tool:Visual Studio 2013 Ultimate Update 2
OS:Windows 8.1
IIS : IIS 8
.NET Framework : 4.5.5

Web Form專案支援Scaffolding的功能了

  • 目前只限Project類型專案可用,Web Site類型不支援
  • Step-by – step :

image

image

image

image

image

  • 在ASP.NET專案中,在Models資料夾加入類別檔案,定義Model如下:

public class Employee {
   public int EmployeeID { get; set; }
   public string EmployeeName { get; set; }
   public int Age { get; set; }
}

  • 加入MyDbContext 類別

public class MyDbContext : DbContext {
   public DbSet<Employee> Employees { get; set; }
}

  • Build Solution
  • Add Scaffikded Item

image

image

 

image

  • 工具會產生範本檔案,放在Employee資料夾

image

  • RUN,新增資料

image

 

image

  • 執行結果

image

2014年7月4日 星期五

Microsoft .NET Native懶人包

 

Microsoft .NET Native

  • 將C#程式碼編譯成原生機器碼 (native machine code)
  • 未來部署時,目地電腦將不需要安裝.NET Framework
  • 目前只能用在Windows Store App程式,其它類型的程式支援開發中…如Windows Phone App,未來可能會有支援其它類型的.NET程式版本
  • 有C#的程式生產力,但擁有C++程式的執行效能
  • 大幅提升Windows Store App 執行效能
  • 目前需要 Visual Studio 2013 Update 2才可以安裝
  • 目前preview release版本只支援C#語言
  • 下載 http://msdn.microsoft.com/en-US/dotnetnative
  • 安裝

 

image

  • 在Windows Store App程式,啟用

image

  • 設定native architecture ,例x64

image

  • 設屬性

image

  • Build

image

 

參考資料:


http://msdn.microsoft.com/en-US/dotnetnative

2014年7月3日 星期四

在MVC5 專案之中使用WCF Data Service

 

Tool:Visual Studio 2013 Ultimate Update 2
OS:Windows 8.1
.NET Framework : 4.5.x
Entity Framework : 6.1.x版以上
ASP.NET MVC 5

 

step-by-step : 在MVC5 專案之中使用WCF Data Service

  • New Project

image

  • Empty MVC

image

  • 安裝Microsoft.OData.EntityFrameworkProvider (Entity Framework Provider for OData)

image

  • 加入ADO.NET Entity Data Model (Database First方式)

image

image

image

  • 使用Pubs資料庫

image

image

  • 按Finish
  • 加入WCF Data Service

 

image

 

image

  • 修改程式,改繼承 EntityFrameworkDataService<T>
public class WcfDataService1 : EntityFrameworkDataService<PubsEntities>
    public static void InitializeService( DataServiceConfiguration config ) {
      config.SetEntitySetAccessRule( "*" , EntitySetRights.All );
      config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
    }
  }
  • 開放路由

public class RouteConfig {
    public static void RegisterRoutes( RouteCollection routes ) {
      routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" );

     routes.IgnoreRoute( "WcfDataService1.svc/{*pathInfo}" );

      routes.MapRoute(
          name: "Default" ,
          url: "{controller}/{action}/{id}" ,
          defaults: new { controller = "Home" , action = "Index" , id = UrlParameter.Optional }
      );
    }
  }

 

  • 測試

image

  • 看到Aton feed:

image

  • 查詢第一筆資料,ID為6380

image

  • 後續便可以使用OData URI Convention進一步查詢,如找尋 Jobs資料表,job_id大於5的資料

總網頁瀏覽量