2017-03-05

Mac OSX 安裝 scriptcs 使用 Visual Studio Code 編輯

ScriptCS 是一個將 C# 語言撰寫的程式碼檔案(*.csx)編譯與執行的工具。




安裝Homebrew套件管理工具

Homebrew 的安裝很簡單,只要在終端機(Terminal)中輸入以下指令就能進行安裝:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

安裝 ScriptCS

brew install scriptcs

確認 scriptcs 安裝成功,查看 scriptcs 版本

安裝過程有看到版本號為 0.17.1
🍺  /usr/local/Cellar/mono/4.8.0.495: 1,604 files, 242.6M
==> Installing scriptcs 
==> Downloading https://homebrew.bintray.com/bottles/scriptcs-0.17.1.sierra.bott
######################################################################## 100.0%
==> Pouring scriptcs-0.17.1.sierra.bottle.tar.gz
🍺  /usr/local/Cellar/scriptcs/0.17.1: 38 files, 12.4
使用 scriptcs -version 查看版本號時顯示的是 Version: 0.0.0,可能是bug吧,使用很正常,沒遇到什麼特別的問題
scriptcs -version
               _       _
 ___  ___ _ __(_)_ __ | |__ ___ ___
/ __|/ __| '__| | '_ \| __// __/ __|
\__ \ (__| |  | | |_) | |_| (__\__ \
|___/\___|_|  |_| .__/ \__\\___|___/
                |_| Version: 0.0.0


建立 helloworld.csx

將以下內容存成 helloworld.csx

string s="Hello World!";
Console.WriteLine(s);

開啟終端機(Terminal),在helloworld.csx 所在資料夾中執行以下命令

scriptcs helloworld.csx
如果成功在畫面上看到 "Hello World!" 的文字表示正常執行.

安裝 Vusual Studio Code

到官網Visual Studio Code下載安裝即可

安裝 Code Runner

Code Runner 可以設定多種程式語言的編譯和執行,因為我有時會寫 javascript,所以我安裝這套可以支援多種程式語言,如果只有要編譯執行 csx 的檔 案,可以安裝 scriptcsRunner.

開啟 Visual Studio Code,在Extensions (Shift + Command + X)輸入「Code Runner 0.6.12」,找到後安裝它

設定scriptcs的編譯參數

到主選單 Code/Preferences/Settings 或 command + , 開啟設定 在User Settings 加入 scriptcs $fileName。
{
    "code-runner.executorMap": {
        "csharp": "scriptcs $fileName"
    }
}
預設只有 scriptcs 的後面沒有帶檔名參數,在執行時會自動帶入「完整檔案路徑和檔名」,這樣反而執行都失敗。

測試Visual Studio Code執行csx 檔

使用 Visual studio code 開啟csx檔,然後選取要執行的程式碼,點右鍵彈出選單,選RUN Code

2017-02-24

Javascript get utc time

2016-08-30

mac install .NET Core

install git
install node.js

npm install -g gulp bower
如果遇到 permission denied

要用
$ sudo chown -R $(whoami) ~/.npm
如果有 /usr/local/lib/node_modules 的權限錯誤
$ sudo chown -R $(whoami) /usr/local/lib/node_modules
如還有 /usr/local permissions
$ sudo chown -R $(whoami) /usr/local

其他方式參考
http://stackoverflow.com/questions/16151018/npm-throws-error-without-sudo



istall donet core 需要先安裝 openssl,使用 brew 安裝 openssl
$ brew update
$ brew install openssl
$ brew link --force openssl


install .NET Core

執行 dotnet restore 遇到錯誤

$ dotnet restore
Unhandled Exception: System.TypeInitializationException: The type initializer for 'Crypto' threw an exception. ---> System.TypeInitializationException: The type initializer for 'CryptoInitializer' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'System.Security.Cryptography.Native': The specified module could not be found. (Exception from HRESULT: 0x8007007E) at Interop.CryptoInitializer.EnsureOpenSslInitialized() at Interop.CryptoInitializer..cctor() --- End of inner exception stack trace --- at Interop.Crypto..cctor() --- End of inner exception stack trace --- at Interop.Crypto.GetRandomBytes(Byte* buf, Int32 num) at System.IO.Path.GetCryptoRandomBytes(Byte* bytes, Int32 byteCount) at System.IO.Path.GetRandomFileName() at Microsoft.DotNet.InternalAbstractions.TemporaryDirectory..ctor() at Microsoft.Extensions.EnvironmentAbstractions.DirectoryWrapper.CreateTemporaryDirectory() at Microsoft.DotNet.Configurer.NuGetPackagesArchiver..ctor() at Microsoft.DotNet.Cli.Program.ConfigureDotNetForFirstTimeUse(INuGetCacheSentinel nugetCacheSentinel) at Microsoft.DotNet.Cli.Program.ProcessArgs(String[] args, ITelemetry telemetryClient) at Microsoft.DotNet.Cli.Program.Main(String[] args) Abort trap: 6

執行以下這行,然後 dotnet restore 就能正常了
$ sudo install_name_tool -add_rpath /usr/local/opt/openssl/lib /usr/local/share/dotnet/shared/Microsoft.NETCore.App/1.0.0/System.Security.Cryptography.Native.dylib&nbsp

環境資訊


$ node -v
v6.5.0
$ npm -v
3.10.3
$ dotnet --info
.NET Command Line Tools (1.0.0-preview2-003121) Product Information: Version: 1.0.0-preview2-003121 Commit SHA-1 hash: 1e9d529bc5 Runtime Environment: OS Name: Mac OS X OS Version: 10.11 OS Platform: Darwin RID: osx.10.11-x64
$ brew -v
Homebrew 0.9.9 (git revision 8e29c; last commit 2016-08-28) Homebrew/homebrew-core (git revision 1727; last commit 2016-08-29)
$ brew info openssl
openssl: stable 1.0.2h (bottled) [keg-only] SSL/TLS cryptography library https://openssl.org/ /usr/local/Cellar/openssl/1.0.2h_1 (1,691 files, 12M) Poured from bottle on 2016-08-30 at 03:15:48 From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/openssl.rb ==> Dependencies Build: makedepend ✘ ==> Options --universal Build a universal binary --without-test Skip build-time tests (not recommended) ==> Caveats A CA file has been bootstrapped using certificates from the system keychain. To add additional certificates, place .pem files in /usr/local/etc/openssl/certs and run /usr/local/opt/openssl/bin/c_rehash This formula is keg-only, which means it was not symlinked into /usr/local. Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries Generally there are no consequences of this for you. If you build your own software and it requires this formula, you'll need to add to your build variables: LDFLAGS: -L/usr/local/opt/openssl/lib CPPFLAGS: -I/usr/local/opt/openssl/include

2016-08-21

Mac OS 抓取螢幕截圖

1. 整個螢幕截圖:
    command + shift + 3 : 取得螢幕畫面,自動儲存在桌面。
    control + command + shift + 3 : 取得螢幕畫面,儲存在剪貼簿中,當你要將擷取畫面放到其它應用程式中時使用此方式。

2. 部份區域截圖:
    command + shift + 4 : 拖拉擷取螢幕畫面中的區域,自動儲存在桌面。
    control + command + shift + 4 : 拖拉擷取螢幕畫面中的區域,自動儲存在剪貼簿。

3. 視窗截圖:
    command + shift + 4 然後按「空白鍵」切換「區域截圖」或「視窗」,自動儲存在桌面。
    control + command + shift + 4 然後按「空白鍵」切換「區域截圖」或「視窗」,自動儲存在剪貼簿。



修改預設截圖檔案名稱

開啟 Terminal 輸入以下命令

defaults write com.apple.screencapture name "wei_capture(date)"

killall SystemUIServer


參考來源:

OSXDaily

2015-05-12

ASP.NET MVC4 + Kendo UI - FileUpload Sample

使用 kendoui 同時上傳 model 與 檔案

Javascript:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
[HttpPost]
public ActionResult Upload([Bind(Include = "Title")]MyDataViewModel model)
{
    if (model == null) throw new Exception("Null");
    using (var transaction = _db.Database.BeginTransaction(IsolationLevel.Serializable))
    {
        var tempFileList = new List<MyFile>();
        try
        {
            model.CreateTime = DateTime.Now;
            model.CreateUser = Auth.CurrentId;
            _db.MyDataTable.Add(model);
            _db.SaveChanges();

            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];
                var fileEntity=new MyFile(file);

                // do save file
                tempFileList.Add(fileEntity);
            }

            transaction.Commit();
            return new JsonResult()
            {
                Data = "Success",
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        catch (Exception ex)
        {
            foreach (var file in tempFileList)
            {
                // do remove file
            }
            transaction.Rollback();
            return new JsonResult()
            {
                Data = "Failure",
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
    }
}

2014-07-29

Select / Deselect All Checkboxes using jQuery

使用 jQuery 全選/取消選取 全部checkbox

2013-08-15

incrementing version number (Visual Studio)

自動增加版本號

stackoverflow 看到一篇增加版本號的討論,其中使用 TextTransform.exe 將樣板建立成有新的版本號的 assemblyinfo.cs。裡面的步驟需要的依序建立 assemblyinfo.tt,然後在專案的建置屬性設置 prebuild。

  如果每個新建專案都要加入 assemblyinfo.tt 和設定 Prebuild 又有點麻煩,所以我直接修改 Visual Studio 的 ProjectTemplates 達到每次新增專案,就已經是配置好的項目。



樣板路徑 是 Visual studio 安裝路徑
%ProgramFiles%\Microsoft Visual studio 9.0\Common7\Ide\ProjectTemplates
%ProgramFiles%\Microsoft Visual studio 9.0\Common7\Ide\ProjectTemplatesCache

在使用時會從 ProjectTemplatesCache 產生專案,所以可以只改 ProjectTemplatesCache


增加編譯時自動增加版本號的樣板,例如 Windows Application
D:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ProjectTemplates\CSharp\Windows\1028\WindowsApplication

1. 覆製 assemblyinfo.cs  -> assemblyinfo.tt

=====assemblyinfo.tt=====================================
<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#
    int incRevision = 1;
    int incBuild = 1;

    try { incRevision = Convert.ToInt32(this.Host.ResolveParameterValue("","","Debug"));} catch( Exception ) { incBuild=0; }
    try { incBuild = Convert.ToInt32(this.Host.ResolveParameterValue("","","Release")); } catch( Exception ) { incRevision=0; }
    try {
        string currentDirectory = Path.GetDirectoryName(Host.TemplateFile);
        string assemblyInfo = File.ReadAllText(Path.Combine(currentDirectory,"AssemblyInfo.cs"));
        Regex pattern = new Regex("AssemblyVersion\\(\"\\d+\\.\\d+\\.(?<revision>\\d+)\\.(?<build>\\d+)\"\\)");
        MatchCollection matches = pattern.Matches(assemblyInfo);
        revision = Convert.ToInt32(matches[0].Groups["revision"].Value) + incRevision;
        build = Convert.ToInt32(matches[0].Groups["build"].Value) + incBuild;
    }
    catch( Exception ) { }
#>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// 組件的一般資訊是由下列的屬性集控制。
// 變更這些屬性的值即可修改組件的相關
// 資訊。
[assembly: AssemblyTitle("$projectname$")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("$registeredorganization$")]
[assembly: AssemblyProduct("$projectname$")]
[assembly: AssemblyCopyright("Copyright © $registeredorganization$ $year$")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// 將 ComVisible 設定為 false 會使得這個組件中的型別
// 對 COM 元件而言為不可見。如果您需要從 COM 存取這個組件中
// 的型別,請在該型別上將 ComVisible 屬性設定為 true。
[assembly: ComVisible(false)]

// 下列 GUID 為專案公開 (Expose) 至 COM 時所要使用的 typelib ID
[assembly: Guid("$guid1$")]

// 組件的版本資訊是由下列四項值構成:
//
//      主要版本
//      次要版本
//      組建編號
//      修訂編號
//
// 您可以指定所有的值,也可以依照以下的方式,使用 '*' 將組建和修訂編號
// 指定為預設值:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.<#= this.revision #>.<#= this.build #>")]
[assembly: AssemblyFileVersion("1.0.<#= this.revision #>.<#= this.build #>")]

<#+
    int revision = 0;
    int build = 0;
#>
=====assemblyinfo.tt  End=====================================


2. csWindowsAplication.vstemplate 加入內容       <ProjectItem ReplaceParameters="true" TargetFileName="Properties\AssemblyInfo.tt">AssemblyInfo.tt</ProjectItem>

<VSTemplate Version="3.0.0" Type="Project" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateContent>
    <Project File="WindowsApplication.csproj" ReplaceParameters="true">
      <ProjectItem ReplaceParameters="true" TargetFileName="Properties\AssemblyInfo.tt">AssemblyInfo.tt</ProjectItem>
      <ProjectItem ReplaceParameters="true" TargetFileName="Properties\AssemblyInfo.cs">AssemblyInfo.cs</ProjectItem>
    </Project>
  </TemplateContent>
</VSTemplate

3. windowsapplication.csproj 修改
    3.1 找到 <Compile Include="Properties\AssemblyInfo.cs"/> 用以下內容置換

        <None Include="Properties\AssemblyInfo.tt">
          <Generator>TextTemplatingFileGenerator</Generator>
          <LastGenOutput>AssemblyInfo.cs</LastGenOutput>
        </None>
        <Compile Include="Properties\AssemblyInfo.cs">
          <AutoGen>True</AutoGen>
          <DesignTime>True</DesignTime>
          <DependentUpon>AssemblyInfo.tt</DependentUpon>
        </Compile>

   3.2 找到 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> 這行下面加入以下內容,讓msbuild 時能透過樣板重建 assemblyinfo.cs

  <PropertyGroup>
    <PreBuildEvent>"%25CommonProgramFiles(x86)%25\microsoft shared\TextTemplating\10.0\TextTransform.exe" -a !!$(ConfigurationName)!1 "$(ProjectDir)Properties\AssemblyInfo.tt"</PreBuildEvent>
  </PropertyGroup>

adsense