LoginSignup
2

More than 5 years have passed since last update.

ちょっとした技術メモ

Last updated at Posted at 2018-03-03

EntityFramework

dotnet core

パッケージ バージョン
dotnetCore <=2.1.301

ASP.NET Core 2.1

カスタムテンプレート

カスタムテンプレートをインストールして使用するには次の2通りの方法がある。

  • nugetパッケージ
    • テンプレートはnugetのパッケージとして管理される。
    • テンプレートのインストール/アンインストールは、nugetパッケージIDで行う
  • ファイルシステム
    • テンプレートは管理されない。
    • インストールでは、template.jsonの存在するファイルパスが管理される
    • アンインストールでは、template.jsonの存在するファイルパスを指定する

ファイルシステム方式の場合、テンプレートの格納されているパスがインストール時の場所から移動した場合、そのテンプレートを使用したdotnet newコマンドは実行に失敗します。

作り方

上記サイトを参考にカスタムテンプレートを作ってみる。
カスタムテンプレートとは、dotnet newコマンドを使って新たなプロジェクトを作成する際のスケルトンを作成するためのテンプレート。

template.json

template.json

{
  "$schema": "http://json.schemastore.org/template",
  "author": "Atachimiko",
  "classifications": [ "Web", "MVC", "SPA" ],
  "name": "Atachi's Custom Template",
  "identity": "AtachiCustomTemplate",
  "shortName": "atachi",
  "tags": {
      "language": "C#"
  },
  "sourceName": "AtachiCustomTemplate",
  "preferNameDirectory" : "true"
}
  • $schema
  • author
    • テンプレートの製作者名
  • classifications
    • テンプレートの種類を示すタグ名。複数指定可能。
  • identity
    • テンプレートの定義名。システムにインストールするテンプレートには、一意のidentityを割り振らなければなりません。
  • name
    • テンプレートの名称
  • shortName
    • テンプレートの省略名。dotnet new <shortName>コマンドで使用します。
  • tags
    • テンプレートのタグ。classificationsとの違いは不明ですが、言語名の指定に使われることが多いようです。

ファイルシステム指定方式でのテンプレートのアンインストール

テンプレートの名前やshortNameでは削除できない仕様のため、まずはdotnet new -uコマンドでインストール済みのテンプレート一覧を表示し、表示された項目をパラメータに指定することで対象のテンプレートをアンインストールできる。

$ dotnet new -u
.NET Core CLI 用テンプレート インスタンス化コマンド

Currently installed items:
 Microsoft.DotNet.Common.ItemTemplates
 Microsoft.DotNet.Common.ProjectTemplates.2.0
 Microsoft.DotNet.Test.ProjectTemplates.2.0
 Microsoft.DotNet.Web.ItemTemplates
 Microsoft.DotNet.Web.ProjectTemplates.2.0
 Microsoft.DotNet.Web.Spa.ProjectTemplates
$ dotnet new -u Microsoft.DotNet.Web.Spa.ProjectTemplates

Angular

パッケージ バージョン
Angular <=6.0.0
Material <=6.0.0
CLI <=6.0.0

トラシュー

Error: Local workspace file ('angular.json') could not be found

ルーティング

テスティングフレームワーク

アサーションライブラリ chai

Angularが採用するの標準アサーションライブラリ

assert()系のメソッドを提供するライブラリです。

// user.attrが{}であることを確認する
chai.assert.isObject(user.attr);

// user.attr.idの値が-1であることを確認する
chai.assert.propertyVal(user.attr, 'id', -1);

テストランナー karuma

Materialなど外部ライブラリを使用していると定義されていないモジュールのディレクティブによりHTMLのパースに失敗してしまい、テストコードが実行できないケースが度々発生する。
1つずつ定義を追加していくか、そもそも外部ライブラリはテストしない方式が考えられる。

パースエラーで試験を停止させずに処理を続行する場合は、SPECファイルに次の記述を行う。

import { NO_ERRORS_SCHEMA } from '@angular/core';

// describe内で、NO_ERRORS_SCHEMA を記述する
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
      ],
      schemas: [
        NO_ERRORS_SCHEMA // <-- this line is also important
      ]
    }).compileComponents();
  }));

ユニットテストコード jasmine

karmaが実行する単体試験用のテストコードはjasmineを使って記述します。

appSpec.js
describe('add関数のテスト', function() {
    it('1 + 2 は 3', function() {
        expect(add(1, 2)).toBe(3);
    });
});

hammer.js

Hammer.js

<div id="myElement" style="background: silver;height: 300px;" (press)="onHammerPress($event)"
     (swipe)="onHammerSwipe($event)">SW</div>
export class HomeComponent {
    onHammerPress() {
        console.info("Execute onHammerPress");
    }

    onHammerSwipe() {
        console.info("Execute onHammerSwipe");
    }
}

Angular Material

Angular向けのUI基盤。

$ npm install --save @angular/material @angular/cdk
$ npm install --save @angular/animations

スターターコンポーネント

  • ダッシュボードコンポーネント
  • データテーブルコンポーネント
  • レスポンシブサイドメニューコンポーネント

MDB Angular

asp.net(with VisualStudio)

  1. 任意のフォルダで、dotnet new angular -o my-new-appコマンドを実行する
    • 新しいフォルダ「my-new-app」が作成される
  2. cd my-new-appコマンドを実行する
  3. my-new-app.csprojファイルを実行する(VisualStudioが起動する)

この方法で作成したAngular2基盤のソースコードは、ClientAppフォルダ内に格納される。
VisualStudioでは、自動的にこのフォルダトランスパイルしアプリケーションの起動を行う。

これらはAngular2のCLIアプリであるngコマンドで実行することも可能。

ngコマンドは、AngularCLI(@angular/cliパッケージ)に入っているコマンドでnpmでインストールできる。
グローバル空間、またはプロジェクトローカル空間にインストールする。

インストール方法は、上記で作成したプロジェクトフォルダ内で、npm install --save-dev @angular/cliコマンドを実行する。

もしAngularCLIをグローバル空間でインストール済みで、バージョンが低い場合は最新バージョンへアップデートを行います。

$ npm update -g @angular/cli

この方法でインストールされたAngularのバージョンはAngular4系とかなり古いので、ng updateコマンドを使用してアップグレードを行う。

$ ng update @angular/core

ASP.NET Core 2.1

このバージョン以降では、dotnetコマンドが生成するasp.netのテンプレートに変更が入り、次のようにSPA構成に特化したAPIが呼び出されるようになっている。

Startup.cs
if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller}/{action=Index}/{id?}");
});

app.UseSpa(spa =>
{
    // To learn more about options for serving an Angular SPA from ASP.NET Core,
    // see https://go.microsoft.com/fwlink/?linkid=864501

    spa.Options.SourcePath = "ClientApp";

    if (env.IsDevelopment())
    {
        spa.UseAngularCliServer(npmScript: "start");
    }
});

Swagger

SPA使うならインターフェースの定義にはやっぱりSwaggerだよねーということで、
Swaggerの使い方はこちらのサイトを参照。

Swashbuckle

ASP.NET CoreでSwaggerで定義したREST APIを使うために便利なライブラリSwashbuckleを使っていく。

Swagger UIを出力する

AddSwaggerGenメソッドを使用する。
コンフィグでは、生成するSwaggerUIに諸情報を与えることができる。

Startup.cs
public class Startup
{
    /// <summary>
    /// Configures app the services.
    /// </summary>
    /// <param name="services">The services.</param>
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddSwaggerGen(c =>
      {
        c.SwaggerDoc("v1", new Info
        {
          Version = "v1",
          Title = "pixstock.service.web API",
          Description = "A simple example ASP.NET Core Web API",
          Contact = new Contact { Name = "Juan García Carmona", Email = "d.jgc.it@gmail.com", Url = "https://wisegeckos.com" },
        });
        // Set the comments path for the Swagger JSON and UI.
        var basePath = AppContext.BaseDirectory;
        var xmlPath = Path.Combine(basePath, "pixstock.service.web.xml");
        c.IncludeXmlComments(xmlPath);
      });
    }
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2