2021年3月22日月曜日

asp.net core3.1に合わせること

 blazor入門は3.1なのですべてのツールとかライブラリを3.1でせねばならない



dotnet tool uninstall <PACKAGE_NAME> -g|--globalで一応消す

dotnet tool install <package_name> -g --version ??? でバージョンを合わす

dotnet tool update dotnet-ef --gloval --version ???で

dotnet ef dbcontext scaffold "Server=localhost\SQLEXPRESS;Database=blazordb;Trusted_connection=True" Microsoft.EntityFrameworkCore.SqlServer -o Models

2021年2月6日土曜日

io books chat sample / io books p118 ok and tuyano flutter p301 (p295 can not run)

 import 'package:flutter/material.dart';

import 'package:cloud_firestore/clooud_firestore.dart';

import 'package:firebase_auth/firebase_auth.dart';


final _db = FirebaseFirestore.instance;

final _auth =FirebaseAuth.instance;

user _ user;


class ChatPage extends StatefulWidget {

 statci const String id = 'chat_screen';



--------------------------------------------------------------------------------------

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.

// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
FirebaseFirestore _db = FirebaseFirestore.instance;
int _counter = 0;

void _incrementCounter() async {
DocumentSnapshot doc = await _db.collection('counter').doc('test').get();
Map<String, dynamic> fields = doc.data() ?? {'count': 0};
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build me
// thod would not be
// called again, and so nothing would appear to happen.
_counter = fields['count'] +1;;
});

await _db.collection('counter').doc('test').set({
'count': _counter,
});
}

@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
------------------------------- 
name: mychatsample
description: A new Flutter application.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
sdk: ">=2.7.0 <3.0.0"

dependencies:
flutter:
sdk: flutter


# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.1
firebase_core: ^0.7.0
firebase_analytics: ^7.0.1
cloud_firestore: ^0.16.0


dev_dependencies:
flutter_test:
sdk: flutter
integration_test:
sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true

# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg

# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.

# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages

# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
---------------------------------------------------------
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'com.google.gms.google-services'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
compileSdkVersion 30

sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}

defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.mychatsample"
minSdkVersion 21
targetSdkVersion 28
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}

buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}

flutter {
source '../..'
}

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation platform('com.google.firebase:firebase-bom:26.4.0')
implementation 'com.google.firebase:firebase-analytics'
}
-------------------------------------------------------
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
}

dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.5'
}
}

allprojects {
repositories {
google()
jcenter()
}
}

rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
delete rootProject.buildDir
}
---------------------------------------------------
{
"project_info": {
"project_number": "728645101027",
"project_id": "chatsample-98624",
"storage_bucket": "chatsample-98624.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:728645101027:android:39dff6035eb4456bc1acd6",
"android_client_info": {
"package_name": "com.example.mychatsample" ここが最重要!
}
},
"oauth_client": [
{
"client_id": "728645101027-cmcqllh91fsl40apbpokl0m2u2s8g9gl.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyAF0z7CDTrMZI24Y0AC-keLeQ982f3AjTU"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "728645101027-cmcqllh91fsl40apbpokl0m2u2s8g9gl.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
}
],
"configuration_version": "1"
}
-------------------------------------------------------------

import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter/rendering.dart';
import 'dart:typed_data';
import 'dart:async';
import 'dart:ui' as ui;
import 'dart:math';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey _homeStateKey = GlobalKey();
  Offset _pos;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 255, 255, 255),
      appBar: AppBar(
        title: Text(
          'App Name',
          style: TextStyle(fontSize: 30.0),
        ),
      ),
      body: Center(
        child: Listener(
          onPointerDown: _pointerDown,
          onPointerMove: _pointerMove,
          child: CustomPaint(
            key: _homeStateKey,
            painter: MyPainter(_pos),
            child: ConstrainedBox(
              constraints: BoxConstraints.expand(),
            ),
          ),
        ),
      ),
    );
  }

  void _pointerDown(PointerDownEvent event) {
    RenderBox referenceBox = _homeStateKey.currentContext.findRenderObject();
    setState(() {
      _pos = referenceBox.globalToLocal(event.position);
    });
  }

  void _pointerMove(PointerMoveEvent event) {
    RenderBox referenceBox = _homeStateKey.currentContext.findRenderObject();
    setState(() {
      _pos = referenceBox.globalToLocal(event.position);
    });
  }
}

class MyPainter extends CustomPainter {
  Offset _pos;

  MyPainter(this._pos);

  @override
  void paint(Canvas canvas, Size size) {
    Paint p = Paint();
    p.style = PaintingStyle.fill;
    p.color = Color.fromARGB(25, 255, 0, 0);
    if (_pos != null) {
      for (var i = 0; i < 10; i++) {
        canvas.drawCircle(_pos, 10.0 * i, p);
      }
      canvas.drawCircle(_pos, 50.0, p);
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}
ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
310ペイジ
import 'package:flutter/material.dart';

void main() {
runApp(new MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: new FirstScreen(),
);
}
}

class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Center(
child: Container(
child: Text('Home Screen', style: TextStyle(fontSize: 32.0)),
),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: 1,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
title: Text('Home'),
icon: Icon(Icons.home),
),
BottomNavigationBarItem(
title: Text('next'),
icon: Icon(Icons.navigate_next),
),
],
onTap: (int value) {
if (value == 1)
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
},
),
);
}
}

class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Next"),
),
body: Center(
child: Text('Next Screen', style: TextStyle(fontSize: 32.0)),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: 0,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
title: Text('prev'),
icon: Icon(Icons.navigate_before),
),
BottomNavigationBarItem(
title: Text('?'),
icon: Icon(Icons.android),
),
],
onTap: (int value) {
if (value == 0) Navigator.pop(context);
},
),
);
}
}


2021年1月22日金曜日

flutter with firebase

https://qiita.com/kimuradesu/items/b74c4908efb282d16a46 ::blazor with firebase

-------------------------------------------------------------------------------------------- 

://www.flutter-study.dev/ フラッターではじめるアプリ開発(ベータ版でWebもOK)

https://airhole.ymegane.org/flutter-for-web/  いまさらでもないが

ちなみに工学社の本は参考程度 上記のサイトのほうがまし

ツヤノの本は、firebase記事はないが、それ以外は充実 (とくにカメラ利用)

-------------------------------------------------------------------------------------------------------

いろいろあたってなんとか動いた記録

まず最新のflutter_core,cloud_firestoreをpub.get 

----------------------------------------------------------------      pubspec.yaml

name: my_flutter_app
description: A new Flutter application.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
sdk: ">=2.7.0 <3.0.0"

dependencies:
flutter:
sdk: flutter


# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.0
firebase_core: "^0.7.0"
cloud_firestore: "^0.16.0"

dev_dependencies:
flutter_test:
sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true

# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg

# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.

# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages

# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
------------------------------------------------------
android-package-name for firebase is com.example.my_flutter_app
(my_flutter_appというflutter project nameから導出される) 
できたjsonをmy_flutter_app/android/appに転送
firestoreにbooksというコレクションを作りauthor,titleの項目をつくり入れ込んでおく
----------------------------------------------------- main.dart
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyHomePage());
}

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
var count = 1;

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Firestore Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Firestore Demo'),
),
body: createListView(),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Firestore 上にデータを追加
//
FirebaseFirestore.instance.collection('books').add({
'title': 'タイトル$count',
'author': '著者$count',
});
count += 1;
},
child: Icon(Icons.add),
),
),
);
}

createListView() {
FirebaseFirestore.instance.collection('books').snapshots().listen((data) {
print(data);
});

return StreamBuilder(
stream: FirebaseFirestore.instance.collection('books').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
// エラーの場合
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}

// 通信中の場合
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading ...');
default:
return ListView(
children: snapshot.data.docs.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document['title']),
subtitle: new Text(document['author']),
);
}).toList(),
);
}
},
);
}
}
----------------------------------------------------------navigation ex
import 'package:flutter/material.dart';

void main() =>
runApp(MaterialApp(
initialRoute: '/first',
routes: <String, WidgetBuilder> {
'/first':(BuildContext context) => FirstRoute(),
'/second': (BuildContext context) => SecondRoute(),
}
));

class FirstRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Route'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(
builder: (context) => SecondRoute()
));
},
child: Text('push here',
style: TextStyle(fontSize: 20),
)),
],),),);
}
}

class SecondRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Route'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('push here',
style: TextStyle(fontSize: 20),
)),
],),),);
}
}

2021年1月8日金曜日

progressive-web-app and react-redux

https://eh-career.com/engineerhub/entry/2019/10/24/103000

PWAの作り方をサクッと学ぶ - 「ホーム画面に追加」「キャッシュ操作」「プッシュ通知」の実装

but -universal-project angular-pwa   not required

https://dev.classmethod.jp/articles/angular8-pwa/ :: ok

----------------------------------------------------------------------------------------------------------

index.js and app.js at tuyano textbook

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore} from 'redux';
import { Provider } from 'react-redux';
import './index.css';
import App from './App';


// ステートの値
let state_value = {
counter:0,
message:"COUNTER"
}


// レデューサー
function counter(state = state_value, action) {
switch (action.type) {
case 'INCREMENT':
return {
counter:state.counter + 1,
message:"INCREMENT"
};
case 'DECREMENT':
return {
counter:state.counter - 1,
message:"DECREMENT"
};
default:
return state;
}
}


// ストアを作成
let store = createStore(counter);


// 表示をレンダリング
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);



import React, { Component } from 'react';
import { connect } from 'react-redux';
import './App.css';

// ステートのマッピング
//function mappingState(state) {
// return state;
//}
// Appコンポーネント
class App extends Component { // 3 lines belo are unnncessary
//constructor(props){
// super(props);
// }
render() {
return (
<div>
<h1>R edux example with 2 component :: Message and Button </h1>
<Message />
<Button />
</div>
);
}
}
// ストアのコネクト
//App = connect()(App); // unnecessary

// メッセージ表示のコンポーネント
class Message extends Component {
style = {
fontSize:"20pt",
padding:"20px 5px"
}
// this.props is store provided by Provider Tag in index.js
render(){
return (
<p style={this.style}>
{this.props.message}: {this.props.counter}
</p>
);
}
}
// ストアのコネクト
//Message = connect(mappingState)(Message);
Message = connect( (state) => state )(Message);

//
class Button extends Component {
style = {
fontSize:"16pt",
padding:"5px 10px"
}

constructor(){
super();
this.doAction = this.doAction.bind(this);
}

// ボタンクリックでディスパッチを実行
doAction(e){
if (e.shiftKey){
this.props.dispatch({ type:'DECREMENT' }); // passed to reducer named counter in index.js
} else {
this.props.dispatch({ type:'INCREMENT' });
}
}


render(){
return (
<button style={this.style}
onClick={this.doAction}>
click
</button>
);
}
}
// ストアのコネクト
Button = connect()(Button);

export default App;










2020年12月13日日曜日

mssql, asp.net core // c# and sqlite

dotnet ef dbcontext scaffold "Server=localhost\SQLEXPRESS;Database=blazordb;Trusted_connection=True" Microsoft.EntityFrameworkCore.SqlServer -o Models

文字列はsqlサーバインスト時以外に確認むつかしい

--------------------------------------------------------------------------------------

tuyano shoda の asp.net core 3.0入門の第四章から最新のasp.net core 5.0 に

置き換えてスキャホールディングに成功(core,design,sqlserver....sqlite not ye)

--------------------------------------------------------------https://3ryupg.hatenablog.com/entry/2018/03/12/2000002018-03-12 

原文を数か所変更したら成功した

(.Net,SQLite)データベースにSQLiteを使ってみた

.Net開発 ADO.Net SQLite C#

.Netアプリでスタンドアロンデータベースを使うときはいつもMDBを使ってたんですが、

今回はじめてSQLiteを使ってみました。

.Netアプリケーションから SQLite にアクセスする方法はいくつかあるらしいですが、

今回はVB.NETから組み込みデータベースのSQLiteを操作する方法 

| ラシカル開発記 を参考にさせてもらい System.Data.SQLite を使ってみました。


環境設定

System.Data.SQLite は http://sourceforge.net/projects/sqlite-dotnet2/files/から

ダウンロードできます。

setup版と、バイナリ版がありますが、バイナリ版をダウンロードし、System.Data.SQLite.DLL と System.Data.SQLite.XML を 

VisualStudioのプロジェクトフォルダに置けばOKです。(System.Data.SQLite.Linq.dllも]あるので、これを使えばLINQでアクセスできるのかもしれません)


VS側では、System.Data.SQLite.DLL を参照設定してやります。


ローカルのSQLiteの中身をWindowsPC上で編集したりデータ覗いたりするのはPupSQLite、もしくはTkSQLiteが便利です。

(WEBだと、SQLiteManagerが定番らしいですが。。)


なお、Windows用のコマンドは、http://www.sqlite.org/download.htmlからダウンロードできます。

接続

System.Data.SQLite はよくできており他のデータプロバイダとほぼ同じ感覚で使うことができます。接続は以下のような感じで出来ます。

using System.Data.SQLite;

//コネクションオブジェクト生成

SQLiteConnection sqlite_con = new SQLiteConnection();

//SQLite接続文字列定義

sqlite_con.ConnectionString = "Version=3;Data Source=test.sqlite;Compress=True;";

//DB接続

sqlite_con.Open();


//クエリ実行


//DBクローズ

sqlite_con.Close();

接続文字列についてです。


"Data Source=":SQLiteのデータベーファイルへのパスを指定。

"New=":Trueを入れると、新規データベーファイルを作成。(既にファイルが存在するとエラーになります) Falseなら既に存在するデータベーファイルを開くことになる。

"Version=":3固定。

"Password=":データベースのパスワードを指定。

"Synchronous=": 同期の設定。Normalだとディスク書き込み中にクラッシュした場合確率は低いがデータベースが壊れる可能性有り。 

Fullだと最も安全だが低速。Offだと高速だけどクラッシュすると壊れる可能性高い。

"Max Pool Size=":接続プールの最大接続数。この値を超えた接続要求があると、接続が空くまで待ち状態。

"Read Only=": Trueだと読み取り専用で開く。

詳しくは、System.Data.SQLiteの接続文字列で使用できる引数の説明 | ラシカル開発記で詳しく説明されています。


データベースファイル、テーブル作成::データベースファイルを新規に作成し、テーブルを作るサンプルはこんな感じです。


using System.Data.SQLite;

using System.Data; // DbTypeが定義されている

//コネクションオブジェクト生成

SQLiteConnection sqlite_con = new SQLiteConnection();

//SQLite接続文字列定義

sqlite_con.ConnectionString = "Version=3;Data Source=test.sqlite;New=True;Compress=True;";

//DB接続

sqlite_con.Open();

//コマンドオブジェクト生成

SQLiteCommand sqlite_cmd = sqlite_con.CreateCommand();


//テーブル作成クエリ

sqlite_cmd.CommandText  = "CREATE TABLE hoge (  id INTEGER , name TEXT , value  REAL)";

//クエリ実行

sqlite_cmd.ExecuteNonQuery();


//データ挿入

sqlite_cmd.CommandText = "INSERT INTO hoge ( id , name , value ) VALUES ( @id , @name , @value  )"

//クエリのパラメータ設定

sqlite_cmd.Parameters.Add("id", DbType.Int32);

sqlite_cmd.Parameters["id"].Value = 1;

sqlite_cmd.Parameters.Add("name", DbType.String);

sqlite_cmd.Parameters["name"].Value = "test";

sqlite_cmd.Parameters.Add("value", DbType.Double);

sqlite_cmd.Parameters["value"].Value = 0.002;


//挿入処理実行。戻り値は影響を受けた行数

int ret = sqlite_cmd.ExecuteNonQuery();


//DBクローズ

sqlite_con.Close(); 

----------------------------------------------------------------ここまで成功

データ参照クエリ

selectする場合はこんな感じ。


SQLiteConnection sqlite_con = new SQLiteConnection();

//SQLite接続文字列定義

sqlite_con.ConnectionString = "Version=3;Data Source=test.sqlite;Compress=True;";

//DB接続

sqlite_con.Open();

SQLiteCommand sqlite_cmd = sqlite_con.CreateCommand();

sqlite_cmd.CommandText = "SELECT id , name , value FROM hoge WHERE name LIKE @nameparam ";

//クエリのパラメータ設定

sqlite_cmd.Parameters.Add("nameparam", DbType.String);

sqlite_cmd.Parameters["nameparam"].Value = "test%";

//クエリ実行 結果はDataReaderで取得

SQLiteDataReader reader = sqlite_cmd.ExecuteReader();


 DataReaderでループして読み込む場合は以下のようにする。

while (reader.Read())

{

    Console.WriteLine(reader["id"] + "," + reader["name"] + "," + reader["value"] );

}


//接続終了

sqlite_con.Close();

------------------------------------------------------------------ これも成功

使ってみた感想としては十分MDBの代わりになるんじゃないかと思います。ただ、今回DLLを直接参照しただけなので、

VisualStudioのデータセットデザイナのウィザードからデータベースを参照することは出来ませんでした。インストール版であればいけるのかもしれません。

------------------------------------------------------------------- 以下は参考程度

https://codezine.jp/article/detail/2823 :: mono and sqlite 1

https://codezine.jp/article/detail/2851 :: mono and sqlite 2

2020年11月15日日曜日

c# mono sqlite3

https://kledgeb.blogspot.com/2019/12/net-core-88-deb-net-core-310.html 

:: .net  core 3.1 deb install 

------------------------------------------------

https://codezine.jp/article/detail/2823?p=2 

データベースへのパスを自分用にすればOKだった

gmcs new2.cs -r:System.Data.dll とあったがだめでmcsでOK!
https://codezine.jp/article/detail/2851 が別だてであった

2020年11月13日金曜日

mono でvb.net,csharpのGUIなどをやる

 http://simplesandsamples.com/ :: 実に詳しい

mcs below-program.cs -r:System.Windows.Forms -r:System.Drawing

using System;

using System.Windows.Forms;

using System.Drawing;

 

namespace MyFrmApp

{

    public class MyForm : Form

    {

        public MyForm()

        {

            Label label = new Label();

            label.Text = "Welcome to C#!";

            label.Font = new Font("Geneva",18,FontStyle.Regular);

            label.Height = 30;

            label.Width = 300;

            this.Controls.Add(label);

            this.Width = 300;

            this.Height = 200;

        }

    }

}


namespace MyFrmApp

{

    class Program

    {

        [STAThread]

        private static void Main(string[] args)

        {

            Application.Run(new MyForm());

        }

         

    }

}

以上は、libro tuyanoのソースコード monodevelop統合環境での開発記事だが

もうないので、最上のサイトを参考に、コマンドラインでコンパイルする