在ES2015裡面,幾個比較大的改變Part1

Arrow Function

人真的可以在懶惰一點,為了不要寫__function__這幾個字,就有 ()=>{} 的出現。這就是Arror Function 跟Lambda的表示法很像, 真的用法也是跟那個一樣

1
2
3
4
5
6
7
8
9
10
11
12
// Old
var old = function(n) {
return n * n;
};

// with Arror Functions express 1
let new_1 = (n) => n * n;

// with arror function express 2
let new_2 = (n) => {
return n * n;
};

另外一個要注意的是Arrow Scope的問題,

1
2
3
4
5
6
7
8
9
10
11
12
var hendrik = {
this.name = "Hendrik";

sayHello: (names) => {
names.forEach((name)=>{
console.log(`${this.name} greets ${name}`);
});
}
}
hendrik.sayHello(['frikkie']);
// output
// hendrik greets frikkie

String templates

最快樂的事情非屬這個, 文字串的組合可以用 ` (鍵盤左上角流水符號的那個鍵), 可以讓你多行編輯文字字串 在配合 ${變數} 來將變數顯示在文字裡面。 這樣子就不用一堆的 『加號』 來串文字了,超快樂的

1
2
3
4
5
6
7
8
9
10
11
// old
function sayHello(name, surname){
console.log('hello there ' + name + ' ' + surname + ', the time is now ' + new Date());
}

// new way
function sayHello_new(name, surname){
console.log(`hello there ${name} ${surname},
the time is now ${new Date()}`);
}

FYI: 新版的C#/VB.net也有將此功能加入,已經可以不用string.format + 無數的{流水號}了

Let

非常重要 要將使用var來定義變數的改用let來定義變數, 這樣子就可以避免同樣名稱的變數在不同的scope被覆蓋的情形發生

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
//=== old ===
var
name = 'Fido',
breed = 'schnauzer',
owners = ['Hendrik', 'Alice']
;

console.log(name + '(' + breed + '):');

for(var i = 0; i < owners.length; i++){
var name = owners[i];

console.log('Owner ' + name);
}

console.log(name);
//output
// Fido(schnauzer):
// Owner Hendrik
// Owner Alice
// Alice (被改變掉了)

//=== new ===
let fname = 'Fido',
breed = 'schnauzer',
owners = ['Hendrik', 'Alice']
;

console.log(`${fname} (${breed}):`);

for(let i = 0; i < owners.length; i++){
let fname = owners[i];
console.log(`Owner ${fname}`);
}

console.log(fname);
// output:
// Fido (schnauzer):
// Owner Hendrik
// Owner Alice
// Fido

const

常數,當變數一旦被指定為const時,就不可以被改變了

1
2
3
4
const pi = Math.PI;

pi = 123;
// this will cause error message

準備練習環境

  1. VSCode
  2. Gulp
  3. browersync
  4. Typescript

設定項目

  1. tsconfig.json
1
2
3
4
5
6
7
8
9
{
"compilerOptions": {
"target": "ES5",
"module": "amd",
"sourceMap": false,
"watch": true,
"outDir": "public/"
}
}
  1. tasks.json
1
2
3
4
5
6
7
8
9
10
11
12
13
{
"version": "0.1.0",
"command": "gulp",
"isShellCommand": true,
"tasks": [
{
"taskName": "watch",
"isBuildCommand": true,
"showOutput": "silent",
"problemMatcher": "$tsc"
}
]
}
  1. gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var gulp = require('gulp'),
browserSync = require('browser-sync').create(),
typescript = require('gulp-tsc');

gulp.task('browser-sync',function(){
browserSync.init({
server:{
baseDir:"./"
}
})
})

gulp.task('compile',function(){
gulp.src(['src/**/*.ts'])
.pipe(typescript())
.pipe(gulp.dest('public/'))
.pipe(browserSync.reload({stream:true}));
});

gulp.task('watch',['browser-sync'],function(){
gulp.watch(['src/**/*.ts'],['compile']);
});

gulp.task('default',['watch']);

gulpfile會做兩件事情

  1. 當ts檔案有異動的時候做Compile並輸出到public的資料夾下
  2. 透過browsersync更新瀏覽器

這樣子就可以專心來練習javascript了

###ReportViewer的遠端報表的設定方式

  1. 如果需要設定登入使用者的權限時, 需要實作IReportServerCredentials, 但是如果需要就抄下面的Code 用法:
1
ReportViewer1.ServerReport.ReportServerCredentials = New CustomReportCredentials(username, password, domain)
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
Imports System.Net
Public Class CustomReportCredentials
Implements Microsoft.Reporting.WebForms.IReportServerCredentials

' local variable for network credential
Private strUserName As String
Private strPassWord As String
Private strDomainName As String
Public Sub New(ByVal UserName As String, ByVal PassWord As String, ByVal DomainName As String)
strUserName = UserName
strPassWord = PassWord
strDomainName = DomainName
End Sub
Public ReadOnly Property ImpersonationUser() As System.Security.Principal.WindowsIdentity Implements Microsoft.Reporting.WebForms.IReportServerCredentials.ImpersonationUser
Get
' not use ImpersonationUser
Return Nothing
End Get
End Property
Public ReadOnly Property NetworkCredentials() As System.Net.ICredentials Implements Microsoft.Reporting.WebForms.IReportServerCredentials.NetworkCredentials
Get
' use NetworkCredentials
Return New NetworkCredential(strUserName, strPassWord, strDomainName)
End Get
End Property
Public Function GetFormsCredentials(ByRef authCookie As System.Net.Cookie, ByRef userName As String, ByRef password As String, ByRef authority As String) As Boolean Implements Microsoft.Reporting.WebForms.IReportServerCredentials.GetFormsCredentials
' not use FormsCredentials unless you have implements a custom autentication.
authCookie = Nothing
password = authority = Nothing
Return False
End Function
End Class
  1. ServerReportUrl要指定SSRS的Report Server URL, 而不是Report Manager URL。因為這個URL的錯誤,讓我一直遇到404的錯誤. ex: http://serverIP/ReportServer

  2. ReportPath就是根據Root的相對應位置而設定,不需要.rdlc(localReport就需要搭配附檔名)

  3. 如果有參數要設定, 使用方式如下

1
2
3
Dim objParms As New System.Collections.ObjectModel.Collection(Of ReportParameter)
objParms.Add(New ReportParameter("param1", "param1 value"))
ReportViewer1.ServerReport.SetParameters(objParms)

##需求

  • Visual Studio 2015

##Note

所有的參考都需要手動加入, 所以新功課會是了解每一個參考裡面有的功能是什麼

1. Microsoft.AspNet.Diagnostics => MiddleWare to handle request(ex: welcomepage, errorpage)
2. Microsoft.AspNet.StaticFiles => 顯示靜態網頁

Microsoft.AspNet.Diagnostics Example

1
2
3
// app.useXXXXX
app.UseWelcomePage();
app.UseErrorPage();

project.json

網站所有的設定都會在這個檔案裏面做設定, 包含dependencies, webroot, exclude, frameworks, etc.

Commands

新增MVC功能

  • project.json add 「Microsoft.AspNet.Mvc」 to dependencies
  • startup.cs
1
2
3
4
5
6
7
8
9
10
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options => { });
}

public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}

如果要設定mvc route時, 在startup.cs的configure裡(in c# 6 syntax)

1
2
3
4
5
6
app.UseMvc(routes=>
{
routes.MapRoute(
name: "Default",
template: "{controller=Home}/{action=Index}/{id?}");
});

建立Configuration

  • dependence: 「Microsoft.Framework.Configuration.UserSecrets」
  • Useage:
1
2
3
4
5
6
7
8
9
10
11
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
// 設定ConfiurationBuilder
var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath);
configurationBuilder.AddJsonFile("config.json");
configurationBuilder.AddEnvironmentVariables();
// 必須執行Build才能建立Configuration物件
var config = configurationBuilder.Build();
// Build後
var value = config.get("key");
}

使用TagHelpers

如果想要使用MVC內建的TagHelper, 幾個需要加入的dependencies

1
2
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final" <= 在vs編輯時會將tag的部分顯示成不同的顏色及其他功能

然後在_ViewImports.cshtml加入

1
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"

最近要寫一個api,其功能需要呼叫一個exe執行檔然後取得該檔回傳的dbf檔案 但是該執行檔又需要讀取網路磁碟機的檔案。這IIS就會卡住了。不管權限怎麼設定都過不去。

所以只好繞路解決了. 解法是: 建立另外一個selfhost的webapi (console mode), 在該api下執行該執行檔就可以正常運作了,因為不是透過IIS. 然後網站去呼叫那個自行運作的webapi取回結果.

雖然有點麻煩,但是至少解決問題了。(浪費我兩天的生命)

關於selft的webapi建立方式,請參考webapi selfhost

Bindingsource物件是屬於winform的,所以在web環境下的design time是沒有辦法直接設定物件到datasource的屬性裡 所以這部分需要手動加進去,作法是進入 xxx.Designer.cs的InitializeComponent()加入

1
this.bindingSource1.DataSource = typeof(Object); // replace with the object you want

這樣子回到設計模式就會出現可以設定的binding物件了

^^

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
********************
****讀取ini file****
********************
function getinit(mfilename,msection,mentry)
local lcinifile,lcvalue,lcbuffer,luentryvalue,lnnumbytes

*-- DECLARE DLL statements for reading/writing to private INI files
declare integer GetPrivateProfileString in Win32API ;
string cSection, string cKey, string cDefault, string @cBuffer, ;
integer nBufferSize, string cINIFile

local minivalue, mresult, mbuffersize
mbuffersize = 255
minivalue = spac(mbuffersize)
mresult=getprivateprofilestring(msection,mentry,"*NULL*",@minivalue,mbuffersize,mfilename)
minivalue=substr(minivalue,1,mresult)
if minivalue="*NULL*"
minivalue=.null.
endif
return minivalue
endfun

demo config ini file

1
2
[section]
entryName=return value

- connection retry policy
- works great with async
- four modes
    - DefaultExcutionStrategy
    - DefaultSqlExecutionStrategy
    - DbExecutionStrategy
    - SqlAzureExecutionStrategy
- throws RetryLimitExceededException

##Configuration

1
2
3
4
5
6
7
8
public class MyConfiguration : DbConfiguration 
{
public MyConfiguration()
{
SetExecutionStrategy("System.Data.SqlClient",
() => new SqlAzureExecutionStrategy(1, TimeSpan.FromSeconds(30)));
}
}

MSDB

參考網址