ทดสอบ C# ด้วย .NET Core บน OSX

สำหรับคนที่เขียน C# บน Windows ก็คงต้องอยากที่จะให้มันเขียนได้บน Mac หรือ Linux ใช่มั้ยครับ จริงๆแล้วก็มี Mono Framework ที่ตอบโจทย์อยู่แล้ว แต่ถ้าเราต้องการ Native Experience ล่ะ?

.NET Core อาจจะเป็นคำตอบ (มั้ง)

เนื่องจากผมอยากลองดูว่า .NET Core ที่เป็น Open Source ของ .NET Framework ที่ทาง Microsoft ประกาศไว้ช่วงต้นๆปีที่แล้วจะเป็นยังไง ผมก็เลยลอง Setup ดูบน Mac เพื่อทดสอบ

เริ่มต้นจากทำตาม link นี้ http://dotnet.github.io/getting-started/ ซึ่งทางเวปจะ detect ให้ว่าตอนนี้เรากำลังใช้ OS อะไรอยู่

สำหรับ Mac – OSX จะต้องโหลดไฟล์ .pkg เพื่อทำการลง dotnet compiler ลงบนเครื่อง

หลังจากลงเสร็จก็มาเริ่มต้นจากใช้ Termial

Screen Shot 2559-01-10 at 11.48.19 PM

ลองสร้าง new default project ผ่าน commandline “dotnet new”

Screen Shot 2559-01-10 at 11.49.50 PM

ลอง “ls” ดูไฟล์ที่สร้างขึ้นมาจะได้แบบนี้ ซึ่งประกอบด้วย

  1. NuGet.Config
  2. Program.cs
  3. project.json

Screen Shot 2559-01-10 at 11.51.06 PM.png

ลองรัน command ตามที่ Getting Started บอกถัดไป “dotnet restore” เพื่อทำการ restore หรือ download พวก assemblies/dlls/modules ที่ได้กำหนดใน project.json มาเพื่อใช้ในการ Compile ตัวโปรเจคของเรา

Screen Shot 2559-01-10 at 11.54.08 PM

หลังจาก restore พวก dependencies ของโปรเจคเราแล้วลองสั่ง  compile และ run กันด้วย “dotnet run”

!!!! Error…

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly ‘System.Console, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’ or one of its dependencies. The system cannot find the file specified.

Screen Shot 2559-01-10 at 11.56.20 PM

ปัญหานี้ก็คือมาดูที่ไฟล์ Program.cs

Code โปรแกรมเรามีการเรียกใช้ Console.WritLine หมายความว่ามันมี Dependency กับ System.Console ทำให้ Compile ไม่ผ่าน

using System;

namespace ConsoleApplication
{
 public class Program
 {
 public static void Main(string[] args)
 {
 Console.WriteLine("Hello World!");
 }
 }
}

ทีนี้มาดูไฟล์ project.json

{
 "version": "1.0.0-*",
 "compilationOptions": {
 "emitEntryPoint": true
 },
"dependencies": {
 "NETStandard.Library": "1.0.0-rc2-23616"
 },
"frameworks": {
 "dnxcore50": { }
 }
}

เราต้องทำการเพิ่ม dependencies เพื่อให้โปรเจคนี้รู้จัก dlls อื่นมากขึ้นเช่น System.Console ดังนั้นแก้ไฟล์ประมาณนี้

{
 "version": "1.0.0-*",
 "compilationOptions": {
 "emitEntryPoint": true
 },
"frameworks": {
 "dnxcore50": { 
"dependencies": { 
 "System.Console": "4.0.0-beta-*", 
 "System.IO": "4.0.11-beta-*", 
 "System.Runtime": "4.0.21-beta-*" 
 }
 }
 }
}

ลองรัน “dotnet restore” อีกรอบเพื่อโหลด dlls มาใหม่ก็จะยัง Error!!! ถ้าใช้ OSX 10.11.2+

ที่นี้ลองมาใช้ command นี้แทนในการ restore

“dotnet restore –runtime osx.10.10-x64”

จากนั้นก็ลอง “dotnet run” ในที่สุด Hello World! ก็ออกมาแล้ว

Screen Shot 2559-01-11 at 12.29.49 AM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s