for Push.

This commit is contained in:
nobobo
2026-06-01 13:23:34 +09:00
parent 9e093ea99f
commit a6550e9928
93 changed files with 10393 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
+363
View File
@@ -0,0 +1,363 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
+30
View File
@@ -0,0 +1,30 @@
using KssSmaPlaLib.Alert.Gamen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Alert
{
public static class FullScreenAlertUxer
{
public static void ShowFullScreenAlert(
Form orner,
string message,
DateTime dateTime,
bool kyoretsu = true,
int autoCloseSec = 0)
{
using (var alert = new AlertForm(
message,
dateTime,
kyoretsu, //true,
autoCloseSec))
{
alert.ShowDialog(orner); // モーダルで前面確実化
}
}
}
}
+347
View File
@@ -0,0 +1,347 @@
using KssSmaPlaLib.Ini;
using KssSmaPlaLib.Input.Gamen;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Alert.Gamen
{
public class AlertForm : Form
{
private const string INI_KEY_BORDER = "Border";
private const string INI_KEY_TITLE = "Title";
private const string INI_KEY_ATTRIBUTE = "Attribute";
private readonly Timer _autoClose = new Timer();
private readonly Label _title = new Label();
private readonly Label _detail = new Label();
private readonly Timer _pulse = new Timer();
private ContextMenuStrip PopupMenu;
private IContainer components;
private ToolStripMenuItem BorderMenu;
private ToolStripMenuItem TitleMenu;
private ToolStripMenuItem ShozokuMenu;
private ToolStripMenuItem KyoretsuModeMenu;
private int _pulseStep = 0;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="errorLine">ログのエラー行</param>
/// <param name="dateTime">日時</param>
/// <param name="kyouretsu">強烈画面</param>
/// <param name="autoCloseSec">自動で閉じる秒数</param>
public AlertForm(
string errorLine,
DateTime dateTime,
bool kyouretsu = true,
int autoCloseSec = 0)
{
InitializeComponent();
if (kyouretsu || IniHelper.ReadValue(null, this.Name, "KyoretsuMode") == "1")
{
// ****** ここ本番強烈処理 ******
IniHelper.WriteValue(null, this.Name, INI_KEY_BORDER, "1");
if (string.IsNullOrEmpty(IniHelper.ReadValue(null, this.Name, INI_KEY_BORDER)))
{
FormBorderStyle = FormBorderStyle.None;
}
else
{
FormBorderStyle = FormBorderStyle.Sizable;
}
TopMost = true;
//WindowState = FormWindowState.Normal;
WindowState = FormWindowState.Maximized;
//Bounds = GetAllScreensBounds(); // 全画面(マルチモニタ)
// ****** ここ本番強烈処理 ******
}
BackColor = Color.FromArgb(220, 0, 0); // 深紅
Cursor = Cursors.Hand;
MouseDown += All_MouseDown;
// タイトル
_title.Text = IniHelper.ReadValue(null, this.Name, INI_KEY_TITLE, "(タイトル未設定)");
var attribute = IniHelper.ReadValue(null, this.Name, INI_KEY_ATTRIBUTE, "のぼぼ工房");
if(!string.IsNullOrEmpty(attribute))
{
_title.Text += " - " + attribute;
}
_title.Font = new Font("Yu Gothic UI", 72, FontStyle.Bold);
_title.ForeColor = Color.White;
_title.AutoSize = true; //false;
_title.MaximumSize = new Size(Screen.PrimaryScreen.Bounds.Width, 0); // 左記Widthを超えると自動改行
_title.TextAlign = ContentAlignment.MiddleCenter;
_title.Dock = DockStyle.Top;
// 高さはFormLoadにて変更する(フォームのHeightがまだデザイン時のものだから)
//_title.Height = Height / 3;
_title.MouseDown += All_MouseDown;
// 詳細
_detail.Text = $"[{dateTime:yyyy/MM/dd HH:mm:ss.fff}]\r\n{errorLine}";
_detail.Font = new Font("Consolas", 28, FontStyle.Regular);
_detail.ForeColor = Color.White;
_detail.AutoSize = false;
_detail.TextAlign = ContentAlignment.MiddleCenter;
_detail.Dock = DockStyle.Fill;
_detail.MouseDown += All_MouseDown;
Controls.Add(_detail);
Controls.Add(_title);
// フェードイン風(パルスで脈動)
_pulse.Interval = 60;
_pulse.Tick += (_, __) =>
{
_pulseStep++;
//int alpha = 200 + (int)(55 * Math.Sin(_pulseStep / 3.0));
//BackColor = Color.FromArgb(Math.Clamp(alpha, 180, 255), 120, 0, 0); // ほんのり血の脈動(控えめ)
// 180〜255にクランプ
//int a = Math.Min(255, Math.Max(180, alpha));
//BackColor = Color.FromArgb(a, 120, 0, 0); // ほんのり血の脈動(控えめ)
int r = Math.Min(255, Math.Max(120, 120 + (int)(60 * Math.Sin(_pulseStep / 3.0))));
BackColor = Color.FromArgb(255, r, 0, 0);
//_title.ForeColor = (alpha % 2 == 0) ? Color.White : Color.GhostWhite;
_title.ForeColor = (r % 2 == 0) ? Color.White : Color.GhostWhite;
Invalidate();
};
_pulse.Start();
// 自動クローズ(10秒)
if (autoCloseSec != 0)
{
_autoClose.Interval = autoCloseSec * 1000;
_autoClose.Tick += (_, __) => Close();
_autoClose.Start();
}
KeyPreview = true;
MouseDown += All_MouseDown;
Shown += AlertForm_Shown;
// 前面に確実に
Activate();
BringToFront();
Focus();
}
private void AlertForm_Shown(object sender, EventArgs e)
{
// タスクバー点滅(アクティブになったらすぐ消えるが、ならなければずっと点滅)
WindowFlasherUxer.Flash(this.Handle);
}
/// <summary>
/// フォームロード時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AlertForm_Load(object sender, EventArgs e)
{
// 高さはFormLoadにて変更する(コンストラクタではフォームのHeightがまだデザイン時のものだから)
_title.Height = Height / 3;
}
// マルチスクリーンの時全てを足したサイズになる!
private Rectangle GetAllScreensBounds()
{
int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
foreach (var s in Screen.AllScreens)
{
var b = s.Bounds;
minX = Math.Min(minX, b.Left);
minY = Math.Min(minY, b.Top);
maxX = Math.Max(maxX, b.Right);
maxY = Math.Max(maxY, b.Bottom);
}
return new Rectangle(minX, minY, maxX - minX, maxY - minY);
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.PopupMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.BorderMenu = new System.Windows.Forms.ToolStripMenuItem();
this.TitleMenu = new System.Windows.Forms.ToolStripMenuItem();
this.ShozokuMenu = new System.Windows.Forms.ToolStripMenuItem();
this.KyoretsuModeMenu = new System.Windows.Forms.ToolStripMenuItem();
this.PopupMenu.SuspendLayout();
this.SuspendLayout();
//
// PopupMenu
//
this.PopupMenu.Font = new System.Drawing.Font("メイリオ", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.PopupMenu.ImageScalingSize = new System.Drawing.Size(24, 24);
this.PopupMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.BorderMenu,
this.TitleMenu,
this.ShozokuMenu,
this.KyoretsuModeMenu});
this.PopupMenu.Name = "PopupMenu";
this.PopupMenu.Size = new System.Drawing.Size(241, 197);
this.PopupMenu.Opening += new System.ComponentModel.CancelEventHandler(this.PopupMenu_Opening);
//
// BorderMenu
//
this.BorderMenu.Name = "BorderMenu";
this.BorderMenu.Size = new System.Drawing.Size(240, 40);
this.BorderMenu.Text = "ボーダー...";
this.BorderMenu.Click += new System.EventHandler(this.BorderMenu_Click);
//
// TitleMenu
//
this.TitleMenu.Name = "TitleMenu";
this.TitleMenu.Size = new System.Drawing.Size(240, 40);
this.TitleMenu.Text = "タイトル...";
this.TitleMenu.Click += new System.EventHandler(this.TitleMenu_Click);
//
// ShozokuMenu
//
this.ShozokuMenu.Name = "ShozokuMenu";
this.ShozokuMenu.Size = new System.Drawing.Size(240, 40);
this.ShozokuMenu.Text = "所属...";
this.ShozokuMenu.Click += new System.EventHandler(this.ShozokuMenu_Click);
//
// KyoretsuModeMenu
//
this.KyoretsuModeMenu.Name = "KyoretsuModeMenu";
this.KyoretsuModeMenu.Size = new System.Drawing.Size(240, 40);
this.KyoretsuModeMenu.Text = "強烈モード?";
this.KyoretsuModeMenu.Click += new System.EventHandler(this.KyoretsuModeMenu_Click);
//
// AlertForm
//
this.ClientSize = new System.Drawing.Size(278, 244);
this.ContextMenuStrip = this.PopupMenu;
this.Name = "AlertForm";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.AlertForm_FormClosing);
this.Load += new System.EventHandler(this.AlertForm_Load);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.AlertForm_KeyDown);
this.PopupMenu.ResumeLayout(false);
this.ResumeLayout(false);
}
/// <summary>
/// ボーダーメニュークリック時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BorderMenu_Click(object sender, EventArgs e)
{
using (var frm = new TextInputForm(
IniHelper.ReadValue(null, this.Name, INI_KEY_BORDER)))
{
if (frm.ShowDialog(this) == DialogResult.Cancel) return;
IniHelper.WriteValue(null, this.Name, INI_KEY_BORDER, frm.EditedText);
}
}
private void All_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return;
this.Close();
}
private void AlertForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
Close();
}
}
/// <summary>
/// タイトルメニュークリック時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TitleMenu_Click(object sender, EventArgs e)
{
using (var frm = new TextInputForm(
IniHelper.ReadValue(null, this.Name, INI_KEY_TITLE)))
{
if (frm.ShowDialog(this) == DialogResult.Cancel) return;
IniHelper.WriteValue(null, this.Name, INI_KEY_TITLE, frm.EditedText);
}
_title.Text = IniHelper.ReadValue(null, this.Name, INI_KEY_TITLE, "重大エラー検知");
}
/// <summary>
/// フォーム閉じるとき
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AlertForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (
MessageBox.Show(
this, "アラート画面を閉じますか?",
"確認",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.No)
{
// Noのとき閉じない
e.Cancel = true;
return;
}
}
/// <summary>
/// 所属メニュークリック時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ShozokuMenu_Click(object sender, EventArgs e)
{
using (var frm = new TextInputForm(
IniHelper.ReadValue(null, this.Name, INI_KEY_ATTRIBUTE)))
{
if (frm.ShowDialog(this) == DialogResult.Cancel) return;
IniHelper.WriteValue(null, this.Name, INI_KEY_ATTRIBUTE, frm.EditedText);
}
}
/// <summary>
/// 強烈モードメニュークリック時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void KyoretsuModeMenu_Click(object sender, EventArgs e)
{
IniHelper.WriteValue(null, this.Name, "KyoretsuMode", KyoretsuModeMenu.Checked ? "0" : "1");
}
/// <summary>
/// ポップアップメニュー開くとき
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PopupMenu_Opening(object sender, CancelEventArgs e)
{
KyoretsuModeMenu.Checked = IniHelper.ReadValue(null, this.Name, "KyoretsuMode") == "1";
}
//protected override CreateParams CreateParams
//{
// get
// {
// var cp = base.CreateParams;
// cp.ExStyle |= 0x00000080; // WS_EX_TOPMOSTを強調(常に最前面)
// return cp;
// }
//}
}
}
+123
View File
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="PopupMenu.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>
+34
View File
@@ -0,0 +1,34 @@
using Microsoft.Toolkit.Uwp.Notifications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Alert
{
public static class ToastUxer
{
public static void ShowAlertToast(
string title,
DateTime dateTime,
string message,
string attributionText = "")
{
// トースト通知の組み立て
new ToastContentBuilder()
// 見出し(太字)
.AddText(title)
// 本文
.AddText($"[{dateTime:yyyy/MM/dd HH:mm:ss.fff}]\r\n{message}")
// 令和風の装飾(任意:画像などを付けることも可能)
.AddAttributionText(attributionText /*"異常検知システムより"*/)
// 通知の優先度を「緊急」に設定(通知センターに残る)
.SetToastScenario(ToastScenario.IncomingCall)
// 画面に表示!
.Show();
}
}
}
+38
View File
@@ -0,0 +1,38 @@
using System.Runtime.InteropServices; // これが必要!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Alert
{
// --- ここからコピー ---
[StructLayout(LayoutKind.Sequential)]
public struct FLASHWINFO
{
public uint cbSize; public IntPtr hwnd; public uint dwFlags;
public uint uCount; public uint dwTimeout;
}
public static class WindowFlasherUxer
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FlashWindowEx(ref FLASHWINFO pwfi);
public const uint FLASHW_ALL = 3; // タスクバーとウィンドウ両方
public const uint FLASHW_TIMERNOFG = 12; // 最前面に来るまで点滅し続ける
public static void Flash(IntPtr hWnd)
{
FLASHWINFO fInfo = new FLASHWINFO();
fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
fInfo.hwnd = hWnd;
fInfo.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG;
fInfo.uCount = uint.MaxValue; // 無限に点滅
fInfo.dwTimeout = 0;
FlashWindowEx(ref fInfo);
}
}
}
@@ -0,0 +1,22 @@
using KssSmaPlaLib.AutoTest.Command.Definition;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Command.Alias
{
public class CommandAliasUxer
{
private static Dictionary<string, CommandEnumUxer.Command> _reverseMap = new Dictionary<string, CommandEnumUxer.Command>();
public static void SetAleiasDic(Dictionary<string, CommandEnumUxer.Command> dic)
{
_reverseMap = dic;
}
public static bool TryTranslate(string userCommand, out CommandEnumUxer.Command command)
=> _reverseMap.TryGetValue(userCommand, out command);
}
}
@@ -0,0 +1,63 @@
using KssSmaPlaLib.AutoTest.Command.Definition;
using KssSmaPlaLib.AutoTest.Command.Translator;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Command.Alias.Ini
{
public static class IniReaderUxer
{
public static bool Try(string iniFilePath, out Dictionary<string, CommandEnumUxer.Command> dic, out string resultMessage)
{
dic = new Dictionary<string, CommandEnumUxer.Command>();
resultMessage = string.Empty;
try
{
if (!File.Exists(iniFilePath))
{
resultMessage = "エイリアスファイルが存在しません。";
return false;
}
var lines = File.ReadAllLines(iniFilePath, System.Text.Encoding.GetEncoding("shift_jis"));
// ここでDTOにパース(例:セクションごとに分ける、キーと値を読み込むなど)
// ↓仮の処理(実際はINIパーサーCLがあると別府)
foreach (var line in lines)
{
if (line.StartsWith("#") ||
line.StartsWith(";") ||
string.IsNullOrWhiteSpace(line))
continue;
var parts = line.Split('=');
if (parts.Length == 2)
{
var command = parts[0].Trim();
var alias = parts[1].Trim();
if (!CommandTranslatorUxer.TryTranslate(command, out var commandEnum))
{
resultMessage = $"エイリアスファイルでコマンド名が不正です。[コマンド名:{command}]";
return false;
}
// エイリアス辞書登録
dic[alias] = commandEnum;
}
}
return true;
}
catch (Exception ex)
{
resultMessage = $"エイリアスロードに失敗しました。[エラー内容:{ex.Message}]";
return false;
}
}
}
}
@@ -0,0 +1,27 @@
using KssSmaPlaLib.AutoTest.Command.Alias.Ini;
using KssSmaPlaLib.AutoTest.Command.Definition;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Command.Alias.Loader
{
public static class CommandAliasLoaderUxer
{
public const string COMMAND_ALIAS_FILE_PATH = ".\\command_alias.ini";
public static bool Try(out Dictionary<string,CommandEnumUxer.Command>dic, out string resultMessage)
{
resultMessage = string.Empty;
if (!IniReaderUxer.Try(COMMAND_ALIAS_FILE_PATH, out dic, out var messageForMe))
{
resultMessage = messageForMe;
return false;
}
return true;
}
}
}
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Command.Definition
{
public class CommandEnumUxer
{
/// <summary>
/// UIステップテストコマンド
/// </summary>
public enum Command
{
None,
Sleep,
SetText,
PushButton,
TryDbMoshimoshi
}
}
}
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Command.Definition
{
public static class CommandParserUxer
{
private static readonly Dictionary<string, CommandEnumUxer.Command> _map = new Dictionary<string, CommandEnumUxer.Command>()
{
{ "Sleep", CommandEnumUxer.Command.Sleep },
{ "SetText", CommandEnumUxer.Command.SetText },
{ "PushButton", CommandEnumUxer.Command.PushButton },
{ "TryDbMoshimoshi", CommandEnumUxer.Command.TryDbMoshimoshi }
};
public static bool TryParse(string commandStr, out CommandEnumUxer.Command command)
=> _map.TryGetValue(commandStr, out command);
}
}
@@ -0,0 +1,23 @@
using KssSmaPlaLib.AutoTest.Command.Definition;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Command.Translator
{
public static class CommandTranslatorUxer
{
private static readonly Dictionary<string, CommandEnumUxer.Command> _reverseMap = new Dictionary<string, CommandEnumUxer.Command>()
{
{ "寝る", CommandEnumUxer.Command.Sleep },
{ "あああをセット", CommandEnumUxer.Command.SetText },
{ "ボタン押す", CommandEnumUxer.Command.PushButton },
{ "もしもしDB", CommandEnumUxer.Command.TryDbMoshimoshi }
};
public static bool TryTranslate(string userCommand, out CommandEnumUxer.Command command)
=> _reverseMap.TryGetValue(userCommand, out command);
}
}
+31
View File
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Core
{
/// <summary>
/// 全体統括・ステップ順実行・ログ出力
/// </summary>
public static class StepTestRunnerUxer
{
/// <summary>
/// 起動パラメータのUIテスト指定
/// </summary>
private const string KIDOU_PARA_UITEST = "--uitest";
/// <summary>
/// メインPJのエントリーポイント用:
/// 起動パラよりUIテストモード判定
/// </summary>
/// <param name="args">起動パラメータ</param>
/// <returns>UIテストモード?</returns>
public static bool IsModeByArgs(string[] args)
{
// 起動パラ判定
return args.Any(m => m.ToLower() == KIDOU_PARA_UITEST);
}
}
}
+64
View File
@@ -0,0 +1,64 @@
using DocumentFormat.OpenXml.Wordprocessing;
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.AutoTest.Script;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KssSmaPlaLib.Batch.Log;
using KssSmaPlaLib.AutoTest.Command.Alias.Loader;
using KssSmaPlaLib.AutoTest.Command.Alias;
using KssSmaPlaLib.AutoTest.Script.Load;
using KssSmaPlaLib.AutoTest.Script.Storage;
using KssSmaPlaLib.AutoTest.Script.Parse;
namespace KssSmaPlaLib.AutoTest.Core
{
public static class TestModeInitializerUxer
{
public static bool TryInitialize(string[] args, out string resultMessage)
{
resultMessage = string.Empty;
// UIステップテストモード判定
var isMode = StepTestRunnerUxer.IsModeByArgs(args);
TestModeUxer.SetTestMode(isMode);
if (!isMode) return true;
// モードのとき、ロード(エイリアス)
if (!CommandAliasLoaderUxer.Try(out var aliasDic, out var messageForMe))
{
resultMessage = messageForMe;
return false;
}
// 保存
CommandAliasUxer.SetAleiasDic(aliasDic);
// ロード(テストスクリプト)
if (!LoadTryUxer.TryLoad(out var stepInfoDTO, out messageForMe))
{
resultMessage = messageForMe;
return false;
}
// 保存
TestScriptStorageUxer.SetStepInfo(stepInfoDTO);
// ステップ内容パース
foreach (var step in stepInfoDTO.StepList)
{
if (!ParseTryUxer.TryParse(step.Raw, out var parsed, out messageForMe))
{
resultMessage = $"ステップ内容が不正です。[ステップNo:{step.StepNo},ステップテキスト:{step.Raw.StepText},エラー内容:{messageForMe}]";
return false;
}
}
// ステップ情報ログ出力
// ↓ToDo自動テスト用ログ出力を作る!
//StepLogUxer.StepInfoLog(stepInfoDTO);
return true;
}
}
}
+18
View File
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Core
{
public static class TestModeUxer
{
public static bool IsTestMode { get; private set; }
public static void SetTestMode(bool value)
{
IsTestMode = value;
}
}
}
+91
View File
@@ -0,0 +1,91 @@
using KssSmaPlaLib.AutoTest.Script.Models;
using KssSmaPlaLib.AutoTest.Script.Parse;
using System;
using System.IO;
using System.Linq;
namespace KssSmaPlaLib.AutoTest.Script.Load
{
/// <summary>
/// UIテストスクリプトローダー
/// </summary>
public static class LoadTryUxer
{
/// <summary>
/// スクリプトファイルパス
/// </summary>
private const string UITEST_SCRIPT_FILE_PATH = "./test_script.ini";
/// <summary>
/// スクリプトロード
/// </summary>
/// <param name="scriptDto">[出力]テストスクリプトデータ</param>
/// <param name="resultMessage">[出力]メッセージ</param>
/// <returns>成否</returns>
public static bool TryLoad(out StepInfoDTO stepInfo, out string resultMessage)
{
stepInfo = new StepInfoDTO();
resultMessage = string.Empty;
try
{
if (!File.Exists(UITEST_SCRIPT_FILE_PATH))
{
resultMessage = "スクリプトファイルが存在しません。";
return false;
}
var lines = File.ReadAllLines(UITEST_SCRIPT_FILE_PATH, System.Text.Encoding.GetEncoding("shift_jis"));
stepInfo.Description = "なんか詳細...(笑)";
stepInfo.InitialStepName = "なんか初期ステップ名...(笑)";
// ここでDTOにパース(例:セクションごとに分ける、キーと値を読み込むなど)
// ↓仮の処理(実際はINIパーサーCLがあると別府)
foreach (var line in lines)
{
if (line.StartsWith("#") ||
line.StartsWith(";") ||
string.IsNullOrWhiteSpace(line))
continue;
// 左辺と右辺分離
var parts = line.Split(new[] { '=' }, 2);
// 要素数違いは飛ばす
if (parts.Length != 2) continue;
// 要素取得
var no = parts[0].Trim();
var text = parts[1].Trim();
// No重複チェック
if (stepInfo.StepList.Any(m => m.StepNo == no))
{
resultMessage = $"ステップNoが重複しています。[ステップNo:{no}]";
return false;
}
// RawDTO
var raw = new StepDTO(no, text);
// バリデーションと変換
if (!ParseTryUxer.TryParse(raw, out var parsed, out string messageForMe))
{
resultMessage = $"ステップエラーです。[行:{line},エラー内容:{messageForMe}";
return false;
}
// 正常:リストに追加
stepInfo.StepList.Add(parsed);
}
return true;
}
catch (Exception ex)
{
resultMessage = $"スクリプトロードに失敗しました。[エラー内容:{ex.Message}]";
return false;
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
using KssSmaPlaLib.AutoTest.Command.Definition;
using KssSmaPlaLib.AutoTest.Script.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Script.Models
{
/// <summary>
/// パース済みのステップDTO(1ステップの情報)
/// </summary>
public class ParsedStepDTO
{
public string StepNo => Raw.StepNo;
public CommandEnumUxer.Command Command { get; set; }
public List<string> Parameters { get; set; }
public StepDTO Raw { get; }
public ParsedStepDTO(StepDTO raw)
{
Raw = raw;
}
}
}
+27
View File
@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Script.Models
{
/// <summary>
/// ステップDTO(1ステップの情報)
/// </summary>
public class StepDTO
{
/// <summary>
/// ステップ番号
/// </summary>
public string StepNo { get; set; }
/// <summary>
/// ステップテキスト
/// </summary>
public string StepText { get; set; }
public StepDTO(string stepNo, string stepText)
{ this.StepNo = stepNo; this.StepText = stepText; }
}
}
+19
View File
@@ -0,0 +1,19 @@
using KssSmaPlaLib.AutoTest.Script;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Script.Models
{
/// <summary>
/// UIテストステップ全体情報
/// </summary>
public class StepInfoDTO
{
public List<ParsedStepDTO> StepList { get; set; } = new List<ParsedStepDTO>();
public string InitialStepName { get; set; } // 最初に実行するステップ名
public string Description { get; set; } // ステップ群の説明(任意)
}
}
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace KssSmaPlaLib.AutoTest.Script.Parse.Function
{
public class FunctionTryUxer
{
public static bool TryFunction(string input, out string functionName, out List<string> funcArgList,out string resultMessage)
{
functionName = "";
funcArgList = new List<string>();
resultMessage = string.Empty;
var match = Regex.Match(input, @"^(\w+)\((.*?)\)$");
if (match.Success)
{
functionName = match.Groups[1].Value;
var args = match.Groups[2].Value;
if (!string.IsNullOrWhiteSpace(args))
{
funcArgList.AddRange(args.Split(','));
}
return true;
}
resultMessage = $"シグネチャ形式が不正です。[シグネチャ:{input}]";
return false;
}
}
}
+47
View File
@@ -0,0 +1,47 @@
using DocumentFormat.OpenXml.Math;
using KssSmaPlaLib.AutoTest.Command.Alias;
using KssSmaPlaLib.AutoTest.Script.Models;
using KssSmaPlaLib.AutoTest.Script.Parse.Function;
using System.Linq;
using System.Reflection;
namespace KssSmaPlaLib.AutoTest.Script.Parse
{
public static class ParseTryUxer
{
public static bool TryParse(StepDTO raw, out ParsedStepDTO parsed, out string resultMessage)
{
resultMessage = string.Empty;
parsed = new ParsedStepDTO(raw); // Raw注入
// ステップNo
if (string.IsNullOrEmpty(raw.StepNo))
{
resultMessage = $"UIテストステップ:ステップ番号が指定されていません。";
return false;
}
// ステップ情報:シグネチャのバリデーション
if (!FunctionTryUxer.TryFunction(raw.StepText, out var functionName, out var argList, out var messageForMe))
{
resultMessage = $"UIテストステップ:ステップ情報のシグネチャの変換に失敗しました。[エラー内容:{messageForMe}]";
return false;
}
// 関数(機能)名
if (!CommandAliasUxer.TryTranslate(functionName, out var commandEnum))
{
resultMessage = $"UIテストステップ:ステップ情報の関数(機能)名が未登録です。[関数(機能)名:{functionName}]";
return false;
}
// コマンド(enum値)
parsed.Command = commandEnum;
// パラメータ
parsed.Parameters = argList;
return true;
}
}
}
@@ -0,0 +1,16 @@
using KssSmaPlaLib.AutoTest.Script.Models;
namespace KssSmaPlaLib.AutoTest.Script.Storage
{
public static class TestScriptStorageUxer
{
private static StepInfoDTO _stepInfo = null;
public static StepInfoDTO StepInfo { get { return _stepInfo; } }
public static void SetStepInfo(StepInfoDTO stepInfo)
{
_stepInfo = stepInfo;
}
}
}
+51
View File
@@ -0,0 +1,51 @@
using KssSmaPlaLib.Batch.Interface;
using KssSmaPlaLib.Cleanup;
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.Ini;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static KssSmaPlaLib.Batch.Sftp.SftpStepHandlerUxer;
namespace KssSmaPlaLib.Batch.Cleanup
{
public class CleanupStepHandlerUxer
{
public FuncCleanupByIniResultDto TryFuncCleanupByIni(
string iniFilePath,
string secsionName)
{
const string KEY_FOLDER_PATH = "FolderPath";
var result = new FuncCleanupByIniResultDto();
var cuDic = IniReferenceResolveUxer.ReadSectionWithReference(iniFilePath, secsionName);
var folderPath = DictionaryUxer.GetValueOrDefault(cuDic, KEY_FOLDER_PATH, string.Empty);
if (string.IsNullOrEmpty(folderPath))
{
LoggerUxer.Info($"フォルダパスが未指定のため、クリーンアップ機能をスキップしました。[キー:{KEY_FOLDER_PATH}]");
result.Succeeded = true;
return result;
}
if (!FileCleanupUxer.TryFileCleanupByDic(cuDic, out var messageForMe))
{
result.ResultMessage = $"ファイルのクリーンナップに失敗しました。[エラー内容:{messageForMe}]";
result.ExitCode = (int)RetCodeUxer.RetCode.CleanupError;
result.Succeeded = false;
return result;
}
result.Succeeded = true;
return result;
}
public class FuncCleanupByIniResultDto : IFuncResultDto
{
public bool Succeeded { get; set; } = false;
public int ExitCode { get; set; } = 0;
public string ResultMessage { get; set; } = string.Empty;
}
}
}
+96
View File
@@ -0,0 +1,96 @@
using KssSmaPlaLib.Commons;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Batch.Commons
{
public static class CommonUxer
{
public const string DIC_KEY_TITLE = "Title";
public const string DIC_KEY_DAYS_TO_START_OFFSET = "DaysToStartOffset";
public const string DIC_KEY_DAYS_TO_END_OFFSET = "DaysToEndOffset";
public static bool TryGetStartDate(Dictionary<string, string> iniDic, out DateTime startDate, out string resultMessage)
{
startDate = DateTime.Today;
resultMessage = string.Empty;
// 開始日
DateTime? fromDate = null;
if (VariableUxer.Args.Count >= 2)
{
if (DateTime.TryParseExact(
VariableUxer.Args[1].Substring(1),
"yyyy/MM/dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out var d) == false)
{
resultMessage = $"起動時パラメータの開始日(第2引数)が不正です。[起動時パラメータ:{string.Join(",", VariableUxer.Args)}]";
return false;
}
fromDate = d;
}
// 起動時パラメータで開始日指定あり
if (fromDate != null)
{
startDate = (DateTime)fromDate;
return true;
}
// 起動時パラメータで開始日指定なし
// オフセット日数取得
var daysToStartOffset = DictionaryUxer.GetValueOrDefault(iniDic, DIC_KEY_DAYS_TO_START_OFFSET, "0");
if (int.TryParse(daysToStartOffset, out var days) == false)
{
// 加算日数エラー
resultMessage = $"設定ファイルの開始日オフセット(加算日数)の設定値が不正です。[{daysToStartOffset}]";
return false;
}
// システム日付(本日日)に加算日数を加算して開始日とする
startDate = DateTime.Today.AddDays(days);
return true;
}
/// <summary>
/// 終了日のオフセット指定があるときだけ、終了日を取得する
/// </summary>
/// <param name="iniDic"></param>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <param name="resultMessage"></param>
/// <returns></returns>
public static bool TryGetEndDate(Dictionary<string, string> iniDic, DateTime startDate, out DateTime? endDate, out string resultMessage)
{
endDate = null;
resultMessage = string.Empty;
// オフセット日数取得
var daysToEndOffset = DictionaryUxer.GetValueOrDefault(iniDic, DIC_KEY_DAYS_TO_END_OFFSET, string.Empty);
if (string.IsNullOrEmpty(daysToEndOffset))
{
// オフセット日数なしのとき、終了日なし
return true;
}
if (int.TryParse(daysToEndOffset, out var days) == false)
{
// 加算日数エラー
resultMessage = $"設定ファイルの終了日オフセット(加算日数)の設定値が不正です。[{daysToEndOffset}]";
return false;
}
// 開始日に加算日数を加算して終了日とする
endDate = startDate.AddDays(days);
return true;
}
}
}
+14
View File
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Batch.DTO
{
public class StepDto
{
public string StepNo { get; set; } = string.Empty;
public string StepSignature { get; set; } = string.Empty;
}
}
+14
View File
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Batch.DTO
{
public class StepInfoDto
{
public string Title { get; set; } = string.Empty;
public List<StepDto> StepList { get; set; } = new List<StepDto>();
}
}
+56
View File
@@ -0,0 +1,56 @@
using KssSmaPlaLib.AutoTest.Script;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KssSmaPlaLib.Batch.Cleanup;
using KssSmaPlaLib.Batch.Sftp;
using KssSmaPlaLib.Batch.Interface;
using KssSmaPlaLib.Batch.Backup;
using KssSmaPlaLib.Batch.Exchange;
using KssSmaPlaLib.Batch.IO;
namespace KssSmaPlaLib.Batch.Dispatch
{
public class StepDispatcherUxer
{
// 利用可能ステップハンドラー
private readonly Dictionary<string, Func<string, string, IFuncResultDto>> _handlers;
public StepDispatcherUxer()
{
_handlers = new Dictionary<string, Func<string, string, IFuncResultDto>>()
{
{ "Cleanup", (iniPath, section) => new CleanupStepHandlerUxer().TryFuncCleanupByIni(iniPath,section) },
{ "SFTPUpload", (iniPath, section) => new SftpStepHandlerUxer().TryFuncSftpUploadByIni(iniPath,section) },
{ "SFTPDownload", (iniPath, section) => new SftpStepHandlerUxer().TryFuncSftpDownloadByIni(iniPath,section) },
{ "SFTPDelete", (iniPath, section) => new SftpStepHandlerUxer().TryFuncSftpDeleteByIni(iniPath,section) },
{ "Backup", (iniPath, section) => new BackupStepHandlerUxer().TryFuncBackupByIni(iniPath,section) },
{ "CsvToDb", (iniPath, section) => new CsvToDbStepHandlerUxer().TryFuncCsvToDbByIni(iniPath,section) },
{ "Delete", (iniPath, section) => new FileStepHandlerUxer().TryFuncFileDeleteByIni(iniPath,section) },
};
}
public bool TryDispatch(string stepName, string iniPath, string sectionName, out string resultMessage, out IFuncResultDto funcResultDto)
{
resultMessage = string.Empty;
funcResultDto = null;
if (_handlers.TryGetValue(stepName, out var func))
{
funcResultDto = func(iniPath,sectionName);
resultMessage = funcResultDto.ResultMessage;
return funcResultDto.Succeeded;
}
resultMessage = $"機能名が登録されていません。[機能名:{stepName}]";
return false;
}
}
public class TryDispatchResultDto : IFuncResultDto
{
public string ResultMessage { get; set; } = string.Empty;
public int ExitCode { get; set; } = 0;
public bool Succeeded { get; set; } = false;
}
}
+357
View File
@@ -0,0 +1,357 @@
using KssSmaPlaLib.Batch.Commons;
using KssSmaPlaLib.Batch.Interface;
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.Exchange;
using KssSmaPlaLib.Ini;
using KssSmaPlaLib.IO.Database;
using KssSmaPlaLib.IO.File;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Batch.Exchange
{
public class CsvToDbStepHandlerUxer
{
public FuncCsvToDbByIniResultDto TryFuncCsvToDbByIni(
string iniFilePath,
string sectionName)
{
const string KEY_SQL_FOLDER_PATH = "SqlFolderPath";
const string KEY_CSV_FILE_NAME_PATTERNS = "CsvFileNamePatterns";
const string KEY_INSERT_SQL_FILES = "InsertSqlFiles";
const string KEY_DUP_CHECK_SQL_FILES = "DupCheckSqlFiles";
const string KEY_DELETE_BEFORE_INSERT_SQL_FILES = "DeleteBeforeInsertSqlFiles";
const string KEY_CSV_ENCODING = "CsvEncoding";
const string KEY_DB_PROVIDER_NAME = "DbProviderName";
const string KEY_DB_CONNECTION_STRING = "DbConnectionString";
const string KEY_CSV_FOLDER_PATH = "CsvFolderPath";
var result = new FuncCsvToDbByIniResultDto();
var iniDic = IniReferenceResolveUxer.ReadSectionWithReference(iniFilePath, sectionName);
// 開始日
if (!CommonUxer.TryGetStartDate(iniDic, out var startDate, out var messageForMe))
{
var msg = $"開始日の取得に失敗しました。[エラー内容:{messageForMe}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.StartDateError;
result.ResultMessage = msg;
return result;
}
// DB接続確認
if (DbUxer.TestConnectByDic(iniDic, out messageForMe) == false)
{
var msg = $"DB接続確認で失敗しました。[エラー内容:{messageForMe}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.DbConnectError;
result.ResultMessage = msg;
return result;
}
LoggerUxer.Info($"DB接続確認が成功しました。[プロバイダ名:{DictionaryUxer.GetValueOrDefault(iniDic, KEY_DB_PROVIDER_NAME, string.Empty)},接続文字列:{DictionaryUxer.GetValueOrDefault(iniDic, KEY_DB_CONNECTION_STRING, string.Empty)}]");
if (!string.IsNullOrEmpty(messageForMe))
{
// Infoメッセージがあれば出力
LoggerUxer.Info(messageForMe);
}
// SQLフォルダパス
var sqlFolderPath = DictionaryUxer.GetValueOrDefault(iniDic, KEY_SQL_FOLDER_PATH, string.Empty);
if (string.IsNullOrEmpty(sqlFolderPath))
{
var msg = $"設定ファイルにSQLフォルダパスが設定されていません。[キー:{KEY_SQL_FOLDER_PATH}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.SqlFolderPathNoSetting;
result.ResultMessage = msg;
return result;
}
// SQLのロード
if (!DbUxer.TryLoadSqlFromText(sqlFolderPath, out messageForMe))
{
var msg = $"SQLのロードに失敗しました。[フォルダパス:SQL,エラー内容:{messageForMe}";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.SqlFileLoadError;
result.ResultMessage = msg;
return result;
}
LoggerUxer.Info(messageForMe); // 正常メッセージ
// CSVファイル名パターン群
var csvPatterns = DictionaryUxer.GetValueOrDefault(iniDic, KEY_CSV_FILE_NAME_PATTERNS, string.Empty);
if (string.IsNullOrEmpty(csvPatterns))
{
var msg = $"設定ファイルのCSVファイル名パターンが設定されていません。[キー:{KEY_CSV_FILE_NAME_PATTERNS}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.CsvFileNamePatternsNotSetting;
result.ResultMessage = msg;
return result;
}
var csvPatternArray = csvPatterns.Split(',');
// INSERT文SQLファイル群
var insertSqlFiles = DictionaryUxer.GetValueOrDefault(iniDic, KEY_INSERT_SQL_FILES, string.Empty);
var insertSqlFilesArray = insertSqlFiles.Split(',');
// 重複チェックSELECT文SQLファイル群
var dupCheckSqlFiles = DictionaryUxer.GetValueOrDefault(iniDic, KEY_DUP_CHECK_SQL_FILES, string.Empty);
var dupCheckSqlFilesArray = dupCheckSqlFiles.Split(',');
// 挿入前の削除SQLファイル群
var deleteBeforeInsertSqlFiles = DictionaryUxer.GetValueOrDefault(iniDic, KEY_DELETE_BEFORE_INSERT_SQL_FILES, string.Empty);
var deleteBeforeInsertSqlFilesArray = deleteBeforeInsertSqlFiles.Split(',');
// 要素数チェック
if (csvPatternArray.Length != insertSqlFilesArray.Length ||
csvPatternArray.Length != dupCheckSqlFilesArray.Length ||
csvPatternArray.Length != deleteBeforeInsertSqlFilesArray.Length)
{
var msg = $"設定ファイルの要素数が異なります。[{KEY_CSV_FILE_NAME_PATTERNS},{KEY_INSERT_SQL_FILES},{KEY_DUP_CHECK_SQL_FILES},{KEY_DELETE_BEFORE_INSERT_SQL_FILES}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.IniFileItemCountError;
result.ResultMessage = msg;
return result;
}
LoggerUxer.Info($"設定ファイルの要素数が一致しています。[要素数:{csvPatternArray.Length},キー:{KEY_CSV_FILE_NAME_PATTERNS},{KEY_INSERT_SQL_FILES},{KEY_DUP_CHECK_SQL_FILES},{KEY_DELETE_BEFORE_INSERT_SQL_FILES}]");
var encodingTypeName = DictionaryUxer.GetValueOrDefault(iniDic, KEY_CSV_ENCODING, "utf8");
var encodingType = EncodingUxer.GetEncodingType(encodingTypeName);
if (encodingType == null)
{
encodingType = EncodingUxer.EncodingType.Utf8WithoutBom;
LoggerUxer.Warn($"CSVエンコーディングタイプ名が不正です。UFT-8で処理します。[キー:{KEY_CSV_ENCODING},値:{encodingTypeName}]");
}
try
{
// DB接続
if (!DbUxer.TryCreateByDic(iniDic, out DbUxer con, out messageForMe, false/* ★★★ トランザクション有無:true */))
{
LoggerUxer.Error(messageForMe);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.DbConnectError;
result.ResultMessage = messageForMe;
return result;
}
LoggerUxer.Info($"DBに接続しました。[プロバイダ名:{DictionaryUxer.GetValueOrDefault(iniDic, KEY_DB_PROVIDER_NAME, string.Empty)},接続文字列:{DictionaryUxer.GetValueOrDefault(iniDic, KEY_DB_CONNECTION_STRING, string.Empty)}]");
var csvFolderPath = DictionaryUxer.GetValueOrDefault(iniDic, KEY_CSV_FOLDER_PATH, ".");
LoggerUxer.Info($"[CSVフォルダパス:{csvFolderPath}]");
using (con)
{
// CSVパターン毎
for (var cnt = 0; cnt < csvPatternArray.Length; cnt++)
{
LoggerUxer.Info($"[CSVパターン{cnt + 1}:{csvPatternArray[cnt]}]");
var insertSqlFile = insertSqlFilesArray[cnt];
var csvFileNamePattern = csvPatternArray[cnt];
var dupCheckSqlFile = dupCheckSqlFilesArray[cnt];
var deleteBeforeInsertSqlFile = deleteBeforeInsertSqlFilesArray[cnt];
LoggerUxer.Info($"[該当ファイル数:{Directory.GetFiles(csvFolderPath, csvFileNamePattern).Length}]");
// ファイル毎
foreach (var path in Directory.GetFiles(csvFolderPath, csvFileNamePattern))
{
if (deleteBeforeInsertSqlFile == "DeleteBeforeInsertWeOrder")
{
// 溶接専用!🔥🌊
// 最小日の取得(溶接専用ロジック)
var minDic = new Dictionary<int, DateTime>();
// CSV読み込み+最小値取得
if (!GetMinValueByKeyFromCsvFiles<int, DateTime>(path, "line_id", "work_date", ref minDic, out var messageForMe0))
{
LoggerUxer.Error(messageForMe0);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.InsertDbFromCsvFilesError;
result.ResultMessage = messageForMe;
return result;
}
LoggerUxer.Info($"ライン毎の最小日の取得を完了");
if (!string.IsNullOrEmpty(deleteBeforeInsertSqlFile))
{
// 挿入前の削除SQLを実行
LoggerUxer.Info($"挿入前の削除SQLを実行[SQLファイル:{deleteBeforeInsertSqlFile}]");
var totalResultCount = 0;
foreach (var kv in minDic)
{
var resultCount = 0;
if (!con.ExecuteNonQuery(
deleteBeforeInsertSqlFile,
new Dictionary<string, object>()
{
{ "LINE_ID", kv.Key },
{ "START_DATE", kv.Value }
},
out resultCount,
out messageForMe))
{
var msg = $"挿入前の削除が失敗しました。[エラー内容:{messageForMe}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.DeleteBeforeInsertException;
result.ResultMessage = msg;
return result;
}
totalResultCount += resultCount;
LoggerUxer.Info($"挿入前の削除成功[ラインID:{kv.Key},開始日:{kv.Value},削除件数:{resultCount}]");
}
LoggerUxer.Info($"挿入前の削除SQLを完了[更新件数:{totalResultCount}]");
}
else
{
LoggerUxer.Info($"挿入前の削除処理はSQLが未指定のためスキップしました。[キー:{KEY_DELETE_BEFORE_INSERT_SQL_FILES}]");
}
}
else
{
if (!string.IsNullOrEmpty(deleteBeforeInsertSqlFile))
{
// 挿入前の削除SQLを実行
LoggerUxer.Info($"挿入前の削除SQLを実行[SQLファイル:{deleteBeforeInsertSqlFile}]");
var totalResultCount = 0;
if (!con.ExecuteNonQuery(
deleteBeforeInsertSqlFile,
new Dictionary<string, object>()
{
{ "START_DATE", startDate }
},
out var resultCount,
out messageForMe))
{
var msg = $"挿入前の削除が失敗しました。[エラー内容:{messageForMe}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.DeleteBeforeInsertException;
result.ResultMessage = msg;
return result;
}
totalResultCount += resultCount;
LoggerUxer.Info($"挿入前の削除SQLを完了[更新件数:{totalResultCount}]");
}
else
{
LoggerUxer.Info($"挿入前の削除処理はSQLが未指定のためスキップしました。[キー:{KEY_DELETE_BEFORE_INSERT_SQL_FILES}]");
}
}
// CSV読み込み+DB挿入
LoggerUxer.Info($"CSV読み込み+DB挿入を実行[ファイルパス:{path}]");
if (!CsvDbSyncUxer.InsertDbFromCsvFiles(iniDic, con, path, dupCheckSqlFile, insertSqlFile, out messageForMe, (EncodingUxer.EncodingType)encodingType))
{
LoggerUxer.Error(messageForMe);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.InsertDbFromCsvFilesError;
result.ResultMessage= messageForMe;
return result;
}
LoggerUxer.Info($"CSV読み込み+DB挿入を完了");
}
}
// コミット
con.Commit();
}
LoggerUxer.Info($"DB処理が完了し、DB接続を終了しました。");
}
catch (Exception ex)
{
var msg = $"DB処理にてエラーが発生しました。[エラー内容:{ex.Message}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.CsvToDbException;
result.ResultMessage = msg;
return result;
}
result.Succeeded = true;
return result;
}
/// <summary>
/// CSVよりキー毎に最小値を取得し辞書で返す
/// </summary>
/// <typeparam name="TKeyType"></typeparam>
/// <typeparam name="TValueType"></typeparam>
/// <param name="csvFilePath"></param>
/// <param name="keyColName"></param>
/// <param name="valueColName"></param>
/// <param name="minDic"></param>
/// <param name="resultMessage"></param>
/// <param name="encodingType"></param>
/// <returns></returns>
public static bool GetMinValueByKeyFromCsvFiles<TKeyType, TValueType>(
string csvFilePath,
string keyColName,
string valueColName,
ref Dictionary<TKeyType, TValueType> minDic,
out string resultMessage,
EncodingUxer.EncodingType encodingType = EncodingUxer.EncodingType.Utf8WithoutBom)
where TKeyType : IComparable<TKeyType>
where TValueType : IComparable<TValueType>
{
// 👇参照型(追記とする)ゆえやめた
//minDic = new Dictionary<TKeyType, TValueType>();
resultMessage = string.Empty;
try
{
// CSV読み込み
if (!CsvUxer.ImportFromCsv(csvFilePath, out var rs, out var messageForMe, encodingType))
{
resultMessage = messageForMe;
return false;
}
//LoggerUxer.Info($"[CSV件数:{rs.Count}]");
foreach (var rec in rs)
{
TKeyType key;
TValueType val;
try { key = (TKeyType)Convert.ChangeType(rec[keyColName], typeof(TKeyType)); }
catch (Exception) { continue; };
try { val = (TValueType)Convert.ChangeType(rec[valueColName], typeof(TValueType)); }
catch (Exception) { continue; }
if (minDic.ContainsKey(key))
{
minDic[key] = Comparer<TValueType>.Default.Compare(val, minDic[key]) < 0 ? val : minDic[key];
}
else
{
minDic[key] = val;
}
}
return true;
}
catch (Exception ex)
{
resultMessage = $"最小日時取得時にエラーが発生しました。[エラー内容:{ex.Message}]";
return false;
}
}
}
public class FuncCsvToDbByIniResultDto : IFuncResultDto
{
public bool Succeeded { get; set; } = false;
public int ExitCode { get; set; } = 0;
public string ResultMessage { get; set; } = string.Empty;
}
}
+87
View File
@@ -0,0 +1,87 @@
using KssSmaPlaLib.Batch.Interface;
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.Ini;
using KssSmaPlaLib.IO.File;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.WebRequestMethods;
namespace KssSmaPlaLib.Batch.IO
{
public class FileStepHandlerUxer
{
public FuncFileDeleteByIniResultDto TryFuncFileDeleteByIni(
string iniFilePath,
string sectionName)
{
const string KEY_FOLDER_PATH = "FolderPath";
const string KEY_FILE_NAME_PATTERNS = "FileNamePatterns";
FuncFileDeleteByIniResultDto result = new FuncFileDeleteByIniResultDto();
var iniDic = IniReferenceResolveUxer.ReadSectionWithReference(iniFilePath, sectionName);
var folderPath = DictionaryUxer.GetValueOrDefault(iniDic, KEY_FOLDER_PATH, string.Empty);
if (string.IsNullOrEmpty(folderPath))
{
var msg = $"設定ファイルのフォルダパスが指定されていません。[キー:{KEY_FOLDER_PATH}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.FileDeleteFolderPathNotSetting;
result.ResultMessage = msg;
return result;
}
if (!Directory.Exists(folderPath))
{
var msg = $"設定ファイルのフォルダパスが存在しません。[キー:{KEY_FOLDER_PATH},値:{folderPath}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.FileDeleteFolderPathNotExist;
result.ResultMessage = msg;
return result;
}
var fileNamePatterns = DictionaryUxer.GetValueOrDefault(iniDic, KEY_FILE_NAME_PATTERNS, string.Empty);
if (string.IsNullOrEmpty(fileNamePatterns))
{
var msg = $"設定ファイルのファイル名パターンが指定されていません。[キー:{KEY_FILE_NAME_PATTERNS}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.FileDeleteFileNamePatternNotSetting;
result.ResultMessage = msg;
return result;
}
var fileNamePatternsArray = fileNamePatterns.Split(',');
// ローカルのCSVファイルの削除
LoggerUxer.Info($"ファイルの削除を実行");
for (var cnt = 0; cnt < fileNamePatternsArray.Length; cnt++)
{
var fileNamePattern = fileNamePatternsArray[cnt];
LoggerUxer.Info($"[ファイル名パターン:{fileNamePattern}]");
if (!FileUxer.TryDeletePatternFiles(folderPath, fileNamePattern, out var fileCount, out var messageForMe))
{
LoggerUxer.Error(messageForMe);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.FileDeletePatternFilesError;
result.ResultMessage = messageForMe;
return result;
}
LoggerUxer.Info($"[削除件数:{fileCount}]");
}
LoggerUxer.Info($"ローカルのCSVファイルの削除を完了");
result.Succeeded = true;
return result;
}
}
public class FuncFileDeleteByIniResultDto : IFuncResultDto
{
public bool Succeeded { get; set; } = false;
public int ExitCode { get; set; } = 0;
public string ResultMessage { get; set; } = string.Empty;
}
}
+15
View File
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Batch.Interface
{
public interface IFuncResultDto
{
bool Succeeded { get; set; }
int ExitCode { get; set; }
string ResultMessage { get; set; }
}
}
+246
View File
@@ -0,0 +1,246 @@
using KssSmaPlaLib.Batch.Interface;
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.Communications;
using KssSmaPlaLib.Ini;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
using static System.Net.WebRequestMethods;
namespace KssSmaPlaLib.Batch.Sftp
{
public class SftpStepHandlerUxer
{
public FuncSftpByIniResultDto TryFuncSftpUploadByIni(
string iniFilePath,
string sessionName)
{
const string KEY_HOST = "Host";
const string KEY_REMOTE_PATH = "RemotePath";
const string KEY_FILE_NAME_PATTERNS = "FileNamePatterns";
const string KEY_IN_FOLDER_PATH = "InFolderPath";
var result = new FuncSftpByIniResultDto();
var iniSftpDic = IniReferenceResolveUxer.ReadSectionWithReference(iniFilePath, sessionName);
var host = DictionaryUxer.GetValueOrDefault(iniSftpDic, KEY_HOST, string.Empty);
if (string.IsNullOrEmpty(host))
{
LoggerUxer.Info("ホストが未指定のためSFTPアップロード機能をスキップしました。");
result.Succeeded = true;
return result;
}
// オブジェクト生成
if (!SftpUxer.TryCreateByDic(iniSftpDic, out SftpUxer sftp, out var messageForMe))
{
result.ResultMessage = $"SFTPアップロード機能でオブジェクト生成に失敗しました。[エラー内容:{messageForMe}]";
result.ExitCode = (int)RetCodeUxer.RetCode.SftpObjectCreateError;
result.Succeeded = false;
return result;
}
// テスト接続
if (!sftp.TestConnect(out messageForMe))
{
result.ResultMessage = $"SFTPアップロード機能でテスト接続に失敗しました。[エラー内容:{messageForMe}]";
result.ExitCode = (int)RetCodeUxer.RetCode.SftpTestConnectError;
result.Succeeded = false;
return result;
}
LoggerUxer.Info($"SFTPテスト接続成功");
// リモートパス
var remotePath = DictionaryUxer.GetValueOrDefault(iniSftpDic, KEY_REMOTE_PATH, string.Empty);
// 入力フォルダパス
var inFolderPath = DictionaryUxer.GetValueOrDefault(iniSftpDic, KEY_IN_FOLDER_PATH, ".");
if (!Directory.Exists(inFolderPath))
{
result.ResultMessage = $"SFTPアップロード機能で入力フォルダパスが存在しません。[{KEY_IN_FOLDER_PATH}:{inFolderPath}]";
result.ExitCode = (int)RetCodeUxer.RetCode.SftpInFolderPathNotExist;
result.Succeeded = false;
return result;
}
// ファイル名パターン
var fileNamePatterns = DictionaryUxer.GetValueOrDefault(iniSftpDic, KEY_FILE_NAME_PATTERNS, "*");
var fileNamePatternList = fileNamePatterns.Split(',').ToList();
// ファイルパスリストの作成
var filePathList = new List<string>();
foreach(var pattern in fileNamePatternList)
{
foreach(var filePath in Directory.GetFiles(inFolderPath, pattern))
{
filePathList.Add(filePath);
}
}
LoggerUxer.Info($"[対象ファイル数:{filePathList.Count},対象ファイルパス:{string.Join(",", filePathList)}]");
if (filePathList.Count == 0)
{
var msg = $"SFTPアップロード機能で対象ファイルが無かったためSTFPアップロードは実行されませんでした。";
LoggerUxer.Info(msg);
result.ResultMessage = msg;
result.Succeeded = true;
return result;
}
// 対象のアップロード
if (!sftp.Upload(filePathList, remotePath, out messageForMe))
{
result.ResultMessage = $"SFTPアップロード機能のアップロードに失敗しました。[エラー内容:{messageForMe}]";
result.ExitCode = (int)RetCodeUxer.RetCode.SftpUploadError;
result.Succeeded = false;
return result;
}
LoggerUxer.Info($"SFTPアップロード機能完了[対象ファイル数:{filePathList.Count},対象ファイル:{string.Join(",", filePathList)},リモートパス:{remotePath},ファイル名パターン:{string.Join(",", fileNamePatternList)}]");
result.Succeeded = true;
return result;
}
public FuncSftpByIniResultDto TryFuncSftpDownloadByIni(
string iniFilePath,
string sectionName)
{
const string KEY_HOST = "Host";
const string KEY_REMOTE_PATH = "RemotePath";
const string KEY_OUT_FOLDER_PATH = "OutFolderPath";
const string KEY_FILE_NAME_PATTERNS = "FileNamePatterns";
var result = new FuncSftpByIniResultDto();
var iniDic = IniReferenceResolveUxer.ReadSectionWithReference(iniFilePath, sectionName);
var host = DictionaryUxer.GetValueOrDefault(iniDic, KEY_HOST, string.Empty);
if (!string.IsNullOrEmpty(host))
{
LoggerUxer.Info($"SFTPダウンロード処理を開始します。");
try
{
// SFTPから対象ファイルをダウンロード
// オブジェクト生成
if (!SftpUxer.TryCreateByDic(iniDic, out SftpUxer sftp, out string messageForMe))
{
LoggerUxer.Error(messageForMe);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.SftpObjectCreateError;
result.ResultMessage = messageForMe;
return result;
}
// テスト接続
if (!sftp.TestConnect(out messageForMe))
{
LoggerUxer.Error(messageForMe);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.SftpTestConnectError;
result.ResultMessage = messageForMe;
return result;
}
LoggerUxer.Info($"SFTPテスト接続成功");
// パターンにマッチするファイルのダウンロード
var fileNamePatterns = DictionaryUxer.GetValueOrDefault(iniDic, KEY_FILE_NAME_PATTERNS, string.Empty);
if (string.IsNullOrEmpty(fileNamePatterns))
{
var msg = $"SFTPのファイル名パターンが設定されていません。[キー:{KEY_FILE_NAME_PATTERNS}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.SftpCsvFileNamePatternsNotSetting;
result.ResultMessage = msg;
return result;
}
var remotePath = DictionaryUxer.GetValueOrDefault(iniDic, KEY_REMOTE_PATH, string.Empty);
var outFolderPath = DictionaryUxer.GetValueOrDefault(iniDic, KEY_OUT_FOLDER_PATH, string.Empty);
LoggerUxer.Info($"[リモートパス:{remotePath},CSV一時フォルダ:{outFolderPath}]");
foreach (var pattern in fileNamePatterns.Split(','))
{
LoggerUxer.Info($"[ファイルパターン:{pattern}]");
if (!sftp.DownloadMatchingFiles(remotePath, outFolderPath, out var downloadedFileCount, out messageForMe, pattern))
{
var msg = $"STFPでのダウンロードに失敗しました。[エラー内容:{messageForMe}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.SftpMatchFilesDownloadError;
result.ResultMessage = msg;
return result;
}
LoggerUxer.Info($"[ダウンロードしたファイル数:{downloadedFileCount}]");
}
result.Succeeded = true;
return result;
}
catch (Exception ex)
{
var msg = $"SFTPダウンロードでエラーが発生しました。[エラー内容:{ex.Message}]";
LoggerUxer.Error(msg);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.SftpDownloadException;
result.ResultMessage = msg;
return result;
}
}
else
{
LoggerUxer.Info($"SFTP処理の設定がないため、スキップします。");
result.Succeeded = true;
return result;
}
}
public FuncSftpByIniResultDto TryFuncSftpDeleteByIni(
string iniFilePath,
string sectionName)
{
const string KEY_REMOTE_PATH = "RemotePath";
const string KEY_FILE_NAME_PATTERNS = "FileNamePatterns";
FuncSftpByIniResultDto result = new FuncSftpByIniResultDto();
var iniDic = IniReferenceResolveUxer.ReadSectionWithReference(iniFilePath, sectionName);
// オブジェクト生成
if (!SftpUxer.TryCreateByDic(iniDic, out SftpUxer sftp, out string messageForMe))
{
LoggerUxer.Error(messageForMe);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.SftpObjectCreateError;
result.ResultMessage = messageForMe;
return result;
}
foreach (var pattern in iniDic[KEY_FILE_NAME_PATTERNS].Split(','))
{
if (!sftp.DeleteMatchingFiles(iniDic[KEY_REMOTE_PATH], out var deletedFileCount, out messageForMe, pattern))
{
LoggerUxer.Error(messageForMe);
result.Succeeded = false;
result.ExitCode = (int)RetCodeUxer.RetCode.SftpDeleteMatchingFilesError;
result.ResultMessage = messageForMe;
return result;
}
LoggerUxer.Info($"SFTPのファイルを削除しました。[ファイル名パターン:{pattern},削除ファイル数:{deletedFileCount}]");
}
result.Succeeded = true;
return result;
}
public class FuncSftpByIniResultDto: IFuncResultDto
{
public bool Succeeded { get; set; } = false;
public int ExitCode { get; set; } = 0;
public string ResultMessage { get; set; } = string.Empty;
}
}
}
+54
View File
@@ -0,0 +1,54 @@
using KssSmaPlaLib.Batch.DTO;
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.AutoTest.Script;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KssSmaPlaLib.Batch.Commons;
namespace KssSmaPlaLib.Batch.StepInfo
{
public static class StepInfoUxer
{
public static bool TryCreateStepInfoFromIniDic(
Dictionary<string, string> iniDic,
out StepInfoDto stepInfo,
out string resultMessage)
{
stepInfo = new StepInfoDto
{
StepList = new List<StepDto>()
};
resultMessage = string.Empty;
foreach (var key in iniDic.Keys.OrderBy(m => m))
{
// コメント行は除く
if (key.Trim().StartsWith(";")) continue;
// タイトル
if (key.Trim() == CommonUxer.DIC_KEY_TITLE)
{
stepInfo.Title = iniDic[key];
continue;
}
stepInfo.StepList.Add(new StepDto()
{
StepNo = key.Trim(),
StepSignature = iniDic[key].Trim(),
});
}
if (stepInfo.StepList.Count == 0)
{
resultMessage = $"設定ファイルに処理区分のステップ情報が登録されていません。[タイトル:{stepInfo.Title}]";
return false;
}
return true;
}
}
}
+29
View File
@@ -0,0 +1,29 @@
# CL設計ガイドライン:別府条項(試作版)
このドキュメントは、CL資産化における設計思想「別府条項」をまとめたものです。
今後、気づきや発見があるたびに追記していく「Smapla DPDesign Pattern)」の母体となります。
---
## 🧠 条項一覧
### 1. クラス名はCL内で一意であるべき
- **理由**:インテリセンス選択ミスによる論理エラーの潜在化を防ぐため。
- **背景**:同一名クラスが存在すると、シグネチャ一致による誤参照が発生しやすく、静的解析でも検出困難。
- **別府度**Smapla別府(高度PGX別府)
### 2. メソッド名のCL内重複は歓迎(意味合いが確定している場合)
- **理由**:同名メソッドが意味合いで区別される設計はPGX的に直感的でわかりやすい。
- **例**`System.IO.File.Exists``System.IO.Directory.Exists`
- **別府度**:まそさん別府(PGX別府)
---
## 🔥 今後の運用
- 本ファイルはプロジェクトルートに配置し、随時追記可能とする。
- 新たな思想・発見があれば、条項として追加し「Smapla DP」として昇華。
---
## 📝 編集履歴
- 2025-10-16: 初版作成 by 小佐井 昇 & 昼コパ
+80
View File
@@ -0,0 +1,80 @@
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.IO.File;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Cleanup
{
public static class FileCleanupUxer
{
public static bool TryFileCleanupByDic(
Dictionary<string, string> iniDic,
out string resultMessage)
{
const string KEY_FOLDER_PATH = "FolderPath";
const string KEY_MAX_DAYS = "MaxDays";
const string KEY_MAX_FILE_COUNT = "MaxFileCount";
var folderPath = DictionaryUxer.GetValueOrDefault(iniDic, KEY_FOLDER_PATH, string.Empty);
if (string.IsNullOrEmpty(folderPath))
{
resultMessage = $"クリーンナップ処理用フォルダパスが設定されていません。[キー:{KEY_FOLDER_PATH}]";
return false;
}
if (!Directory.Exists(folderPath))
{
resultMessage = $"クリーンナップ処理用フォルダパスが存在しません。[キー:{KEY_FOLDER_PATH},値:{folderPath}]";
return false;
}
var str = DictionaryUxer.GetValueOrDefault(iniDic, KEY_MAX_DAYS, "99999");
if (!int.TryParse(str, out var maxDays) || maxDays < 0)
{
resultMessage = $"クリーンナップ処理用最大保持日数が不正です。[キー:{KEY_MAX_DAYS},値:{str}]";
return false;
}
LoggerUxer.Info($"[クリーンナップ対象フォルダパス:{folderPath}]");
LoggerUxer.Info($"[クリーンナップ最大保持日数:{maxDays}]");
var now = DateTime.Now;
var thresholdDate = now.AddDays(-(maxDays - 1)).Date;
LoggerUxer.Info($"[クリーンナップ保持再過去日:{thresholdDate:yyyy/MM/dd}]");
str = DictionaryUxer.GetValueOrDefault(iniDic, KEY_MAX_FILE_COUNT, "99999");
if (!int.TryParse(str, out var maxFileCount) || maxFileCount < 0)
{
resultMessage = $"クリーンナップ処理用最大保持ファイル数が不正です。[キー:{KEY_MAX_FILE_COUNT},値:{str}]";
return false;
}
LoggerUxer.Info($"[クリーンナップ最大保持ファイル数:{maxFileCount}]");
var ret = TryFileCleanup(folderPath, thresholdDate, maxFileCount, out resultMessage);
LoggerUxer.Info($"クリーンナップ処理が終了しました。");
return ret;
}
public static bool TryFileCleanup(string folderPath, DateTime thresholdDate, int maxFileCount, out string resultMessage)
{
resultMessage = string.Empty;
// フォルダの最大日数より過去のファイルを削除
if (!FileUxer.TryApplyActionToFiles<DateTime>(folderPath, f => f.LastWriteTime < thresholdDate, f => f.Delete(), out var deleteFileCount, out var messageForMe, "日数超過削除"))
{
resultMessage = $"バックアップフォルダ過去ファイル削除(期間制限):{messageForMe}";
return false;
}
// バックアップフォルダの最大ファイル数超過時に古いファイルから削除
if (!FileUxer.TryApplyActionToFiles<DateTime>(folderPath, f => true, f => f.Delete(), out deleteFileCount, out messageForMe, "ファイル数超過削除", true, null, maxFileCount))
{
resultMessage = $"バックアップフォルダ過去ファイル削除(ファイル数制限):{messageForMe}";
return false;
}
return true;
}
}
}
+54
View File
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Commons.Conversion
{
public static class KanaConvertUxer
{
/// <summary>
/// 半角カタカナを全角カタカナに変換します。
/// 空文字やnullはそのまま返却します。
/// </summary>
public static bool TryConvertHankakuToZenkaku(string input, out string result, out string resultMessage)
{
result = input;
resultMessage = string.Empty;
if (string.IsNullOrEmpty(input))
return true;
// 半角カタカナが含まれているかチェック
if (!Regex.IsMatch(input, @"[\uFF61-\uFF9F]"))
return true;
// 変換処理
result = Microsoft.VisualBasic.Strings.StrConv(input, Microsoft.VisualBasic.VbStrConv.Katakana | Microsoft.VisualBasic.VbStrConv.Wide, 0);
return true;
}
/// <summary>
/// 全角カタカナを半角カタカナに変換します。
/// 空文字やnullはそのまま返却します。
/// </summary>
public static bool TryConvertZenkakuToHankaku(string input, out string result, out string resultMessage)
{
result = input;
resultMessage = string.Empty;
if (string.IsNullOrEmpty(input))
return true;
// 全角カタカナが含まれているかチェック(ざっくり)
if (!Regex.IsMatch(input, @"[\u30A0-\u30FF]"))
return true;
// 変換処理
result = Microsoft.VisualBasic.Strings.StrConv(input, Microsoft.VisualBasic.VbStrConv.Katakana | Microsoft.VisualBasic.VbStrConv.Narrow, 0);
return true;
}
}
}
+35
View File
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Commons
{
public static class DateHelperUxer
{
/// <summary>
/// 指定した年と月の末日を返します。
/// </summary>
/// <param name="year">年(例: 2025</param>
/// <param name="month">月(112</param>
/// <returns>末日(2831</returns>
public static bool TryGetLastDayOfMonth(int year, int month, out int matsubi,out string resultMessage)
{
matsubi = -1;
resultMessage = string.Empty;
if (month < 1 || month > 12)
{
resultMessage = "月が1~12の範囲ではありません。";
return false;
}
// DateTime構造体を使って末日を取得
matsubi = DateTime.DaysInMonth(year, month);
return true;
}
}
}
+55
View File
@@ -0,0 +1,55 @@
using KssSmaPlaLib.IO.File;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Commons
{
public static class DictionaryUxer
{
/// <summary>
/// 指定されたキーに対応する値(string)を取得します。キーが存在しない場合は 指定されたデフォルト値(未指定時はnull) を返します。
/// </summary>
public static TValue GetValueOrDefault<TKey, TValue>(
Dictionary<TKey, TValue> dict,
TKey key,
TValue defaultValue = default)
{
return dict.TryGetValue(key, out TValue value) ? value : defaultValue;
}
public static bool CreateNameToIdDic(string pcsv, out Dictionary<string,int> dic, out string resultMessage)
{
resultMessage = string.Empty;
dic = new Dictionary<string,int>();
if (string.IsNullOrEmpty(pcsv)) return true;
var csvArray = pcsv.Split('|');
foreach (var csv in csvArray)
{
var items = csv.Split(',');
if (items.Length != 2)
{
resultMessage = $"要素数が{items.Length}個のCSVあり[CSV:{csv}]";
return false;
}
// IDの数値チェック
if (!int.TryParse(items[1], out int id))
{
resultMessage = $"IDが数値でないCSVあり[CSV:{csv}]";
return false;
}
// Nameのカンマ記号復元
items[0] = items[0].Replace("@@@COMMA@@@", ",");
dic[items[0]] = id;
}
return true;
}
}
}
+54
View File
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Commons
{
public class EncodingUxer
{
#region
public enum EncodingType
{
Utf8WithBom,
Utf8WithoutBom,
ShiftJIS
}
#endregion
public static Encoding GetEncoding(EncodingType type)
{
switch (type)
{
case EncodingType.Utf8WithBom:
return new UTF8Encoding(encoderShouldEmitUTF8Identifier: true); // BOMあり
case EncodingType.Utf8WithoutBom:
return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); // BOMなし
case EncodingType.ShiftJIS:
return Encoding.GetEncoding("shift_jis"); // ANSIWindows-932
default:
throw new ArgumentOutOfRangeException(nameof(type), "未対応のエンコーディングです");
}
}
public static EncodingType? GetEncodingType(string typeString)
{
typeString = typeString.ToLower();
if (StringUxer.WildcardMatch(typeString, "*utf*8*without*bom*"))
return EncodingType.Utf8WithoutBom;
if (StringUxer.WildcardMatch(typeString, "*utf*8*with*bom*"))
return EncodingType.Utf8WithBom;
if (StringUxer.WildcardMatch(typeString, "*utf*8*"))
return EncodingType.Utf8WithoutBom;
if (StringUxer.WildcardMatch(typeString, "*s*jis*"))
return EncodingType.ShiftJIS;
if (StringUxer.WildcardMatch(typeString, "*シ*jis*"))
return EncodingType.ShiftJIS;
return null;
}
}
}
+23
View File
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Commons
{
public static class IntUxer
{
public static int StrToInt(string str, int defaultValue)
{
if (int.TryParse(str, out int intValue))
{
return intValue;
}
else
{
return defaultValue;
}
}
}
}
+81
View File
@@ -0,0 +1,81 @@
using KssSmaPlaLib.Ini;
using Serilog;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace KssSmaPlaLib.Commons
{
/// <summary>
/// ロガー
/// </summary>
public static class LoggerUxer
{
/// <summary>
/// 初期化
/// </summary>
/// <param name="iniPath">ログINIファイルパス</param>
public static void Initialize(string iniPath)
{
EnsureIniExists(iniPath);
var config = IniReferenceResolveUxer.ReadSectionWithReference(iniPath, "Logging");
var level = Enum.TryParse(config["LogLevel"], out LogEventLevel parsedLevel)
? parsedLevel
: LogEventLevel.Information;
var path = config["LogFilePath"];
var rolling = config["RollingInterval"];
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Is(level)
.WriteTo.Console()
.WriteTo.File(path, rollingInterval: (RollingInterval)Enum.Parse(typeof(RollingInterval), rolling))
.CreateLogger();
}
public static void Info(string message) => Log.Information(message);
public static void Warn(string message) => Log.Warning(message);
public static void Error(string message) => Log.Error(message);
public static void Close() => Log.CloseAndFlush();
public static void StartInfo()
{
// DLL(自身)のアセンブリ
var dllAssembly = Assembly.GetExecutingAssembly();
var dllVersion = dllAssembly.GetName().Version?.ToString();
var dllProduct = dllAssembly.GetCustomAttribute<AssemblyProductAttribute>()?.Product ?? "不明";
// EXE(呼び出し元)のアセンブリ
var exeAssembly = Assembly.GetEntryAssembly();
var exeVersion = exeAssembly?.GetName().Version?.ToString();
var exeProduct = exeAssembly?.GetCustomAttribute<AssemblyProductAttribute>()?.Product ?? "不明";
// ログ出力
Info($"[EXE] 製品名: {exeProduct}, バージョン: {exeVersion}");
Info($"[DLL] 製品名: {dllProduct}, バージョン: {dllVersion}");
}
/// <summary>
/// ログINI初期化(無ければ)
/// </summary>
/// <param name="path">ログINIファイルパス</param>
private static void EnsureIniExists(string path)
{
if (!File.Exists(path))
{
File.WriteAllLines(path, new[]
{
"[Logging]",
"LogLevel=Information",
"LogFilePath=log.txt",
"RollingInterval=Day"
});
}
}
}
}
+137
View File
@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Commons
{
public static class RetCodeUxer
{
/// <summary>
/// 戻り値(プロセス終了値)
/// </summary>
public enum RetCode
{
/// <summary>
/// 成功
/// </summary>
Success = 0,
/// <summary>
/// ファイルバックアップ時エラー
/// </summary>
FileBackupError = -1,
/// <summary>
/// ファイルクリーンナップエラー
/// </summary>
CleanupError = -2,
/// <summary>
/// 開始日エラー
/// </summary>
StartDateError = -3,
/// <summary>
/// DB接続エラー
/// </summary>
DbConnectError = -4,
/// <summary>
/// SQLフォルダパス未設定
/// </summary>
SqlFolderPathNoSetting = -5,
/// <summary>
/// SQLファイルロードエラー
/// </summary>
SqlFileLoadError = -6,
/// <summary>
/// CSVファイル名パターン群が未設定
/// </summary>
CsvFileNamePatternsNotSetting = -7,
/// <summary>
/// 設定ファイルの要素数エラー
/// </summary>
IniFileItemCountError = -8,
/// <summary>
/// 挿入前の削除時に例外発生
/// </summary>
DeleteBeforeInsertException = -9,
/// <summary>
/// CSVデータをDB登録時エラー
/// </summary>
InsertDbFromCsvFilesError = -10,
/// <summary>
/// CSVからDB登録時に例外発生
/// </summary>
CsvToDbException = -11,
/// <summary>
/// ファイル削除でフォルダパス未設定
/// </summary>
FileDeleteFolderPathNotSetting = -12,
/// <summary>
/// ファイル削除でフォルダパス未存在
/// </summary>
FileDeleteFolderPathNotExist = -13,
/// <summary>
/// ファイル削除でファイル名パターン未設定
/// </summary>
FileDeleteFileNamePatternNotSetting = -14,
/// <summary>
/// ファイル削除でファイル名パターン削除エラー
/// </summary>
FileDeletePatternFilesError = -15,
/// <summary>
/// SFTPオブジェクト生成エラー
/// </summary>
SftpObjectCreateError = -16,
/// <summary>
/// SFTPアップロードエラー
/// </summary>
SftpUploadError = -17,
/// <summary>
/// SFTPアップロードで入力フォルダ未存在
/// </summary>
SftpInFolderPathNotExist = -18,
/// <summary>
/// SFTPでCSVファイル名パターンが未設定
/// </summary>
SftpCsvFileNamePatternsNotSetting = -19,
/// <summary>
/// SFTPダウンロード時に例外発生
/// </summary>
SftpDownloadException = -20,
/// <summary>
/// SFTPファイル削除エラー
/// </summary>
SftpDeleteMatchingFilesError = -21,
/// <summary>
/// SFTPパターンマッチファイルダウンロード時エラー
/// </summary>
SftpMatchFilesDownloadError = -22,
/// <summary>
/// SFTP共通:テスト接続エラー
/// </summary>
SftpTestConnectError = -23,
}
}
}
+104
View File
@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Commons
{
public class StringUxer
{
public static string CreateACarInBikesString(
string bike,
string car,
string f1,
int count,
int luckyCount)
{
// 1. まず100個のバイクのリストを作成
List<string> list = Enumerable.Repeat(bike, count).ToList();
// 2. 0〜99のランダムな位置を1つ選ぶ
Random rand = new Random();
int randomIndex = rand.Next(0, count);
// 3. その位置を車に置き換える(ラッキー時はF1)
Random rand2 = new Random();
var lucky = rand2.Next(0, luckyCount) == 0;
list[randomIndex] = lucky ? f1 : car;
// 4. 文字列に結合
return string.Concat(list);
}
public static bool WildcardMatch(string input, string pattern)
{
if (string.IsNullOrEmpty(pattern)) return string.IsNullOrEmpty(input);
// "*" を ".*" に変換し、正規表現にする
string regexPattern = "^" + Regex.Escape(pattern).Replace("\\*", ".*") + "$";
return Regex.IsMatch(input, regexPattern, RegexOptions.IgnoreCase);
}
public static bool TryParseIniSignature(string iniValue, out string functionName, out List<string> args)
{
functionName = null;
args = null;
var pattern = @"^([a-zA-Z_][a-zA-Z0-9_]*)\((.*?)\)$";
var match = Regex.Match(iniValue.Trim(), pattern);
if (!match.Success)
return false;
functionName = match.Groups[1].Value;
var argsString = match.Groups[2].Value;
args = string.IsNullOrEmpty(argsString)
? new List<string>()
: argsString.Split(',').Select(arg => arg.Trim()).ToList();
return true;
}
public static bool TryExtractYearFromString(string str, out int year)
{
// var match = Regex.Match(str, @"\b(20\d{2})\b"); // 条件厳しめ
var match = Regex.Match(str, @"(20\d{2})"); // 条件緩め
year = match.Success ? int.Parse(match.Groups[1].Value) : -1;
return year != -1;
}
/// <summary>
/// CSVから文字列取得(インデックス指定:範囲外の時既定値)
/// </summary>
/// <param name="csv">CSV文字列(カンマ区切り)</param>
/// <param name="index">インデックス</param>
/// <param name="noString">範囲外の時の既定値</param>
/// <returns>取得した文字列</returns>
public static string GetStringByIndexFormCsv(string csv, int index, string noString = "(No name...)")
{
string[] strSplit = csv.Split(',');
if (index < 0 || index > strSplit.Length - 1) return noString;
return strSplit[index];
}
/// <summary>
/// 文字列中の改行コードのカット
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string CutKaigyo(string str)
{
return Regex.Replace(str,
// '\r'と'\n'とUnicode改行文字
// \u2028 (行区切り文字)
//  \u2029 (段落区切り文字)
//  \u0085 (次行文字)
// の正規表現
@"\r\n|[\r\n\u2028\u2029\u0085]",
"",
// 複数回行う時のためにコンパイルしておく
RegexOptions.Compiled);
}
}
}
+16
View File
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Commons
{
public static class VariableUxer
{
private static List<string> _args = new List<string>();
public static List<string> Args { get => _args; }
public static void SetArgs(string[] args) { _args = args.ToList(); }
}
}
+302
View File
@@ -0,0 +1,302 @@
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.Encryption;
using KssSmaPlaLib.IO.File;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Communications
{
public class SftpUxer
{
public const string INIDIC_KEY_HOST = "Host";
public const string INIDIC_KEY_PORT = "Port";
public const string INIDIC_KEY_USERNAME = "UserName";
public const string INIDIC_KEY_PRIVATE_KEY_FILE_PATH = "PrivateKeyFilePath";
public const string INIDIC_KEY_PASS_PHRASE = "PassPhrase";
private readonly string _host;
private readonly int _port;
private readonly string _username;
private readonly string _privateKeyPath; // PuTTY形式でもOK
private readonly string _passPhrase;
public static bool TryCreateByDic(Dictionary<string, string> iniDic, out SftpUxer sftp, out string resultMessage)
{
sftp = null;
resultMessage = string.Empty;
// ホスト名
var host = DictionaryUxer.GetValueOrDefault(iniDic, INIDIC_KEY_HOST, string.Empty);
if (string.IsNullOrEmpty(host))
{
resultMessage = $"SFTPのホスト名が指定されていません。[キー:{INIDIC_KEY_HOST}]";
return false;
}
// ポート番号
var strPort = DictionaryUxer.GetValueOrDefault(iniDic, INIDIC_KEY_PORT, string.Empty);
if (int.TryParse(strPort, out var portNo) == false)
{
LoggerUxer.Error($"SFTPのポート番号が未指定または数値でありません。[キー:{INIDIC_KEY_PORT},ポート番号:{strPort}]");
return false;
}
// ユーザ名
var username = DictionaryUxer.GetValueOrDefault(iniDic, INIDIC_KEY_USERNAME, string.Empty);
if (string.IsNullOrEmpty(username))
{
LoggerUxer.Error($"SFTPのユーザ名が指定されていません。[キー:{INIDIC_KEY_USERNAME}]");
return false;
}
// プライベートキーファイルパス
var privateKeyPath = DictionaryUxer.GetValueOrDefault(iniDic, INIDIC_KEY_PRIVATE_KEY_FILE_PATH, string.Empty);
if (string.IsNullOrEmpty(privateKeyPath))
{
LoggerUxer.Error($"SFTPのプライベートキーファイルパスが指定されていません。[キー:{INIDIC_KEY_PRIVATE_KEY_FILE_PATH}]");
return false;
}
if (!File.Exists(privateKeyPath))
{
LoggerUxer.Error($"SFTPのプライベートキーファイルパスが存在しません。[キー:{INIDIC_KEY_PRIVATE_KEY_FILE_PATH},パス:{privateKeyPath}]");
return false;
}
// パスフレーズ
var passPhrase = DictionaryUxer.GetValueOrDefault(iniDic, INIDIC_KEY_PASS_PHRASE, string.Empty);
// ↓パスフレーズなしの場合もあり(必須としない)
//if (string.IsNullOrEmpty(passPhrase))
//{
// LoggerUxer.Error($"SFTPのパスフレーズが指定されていません。[キー:{INIDIC_KEY_PASS_PHRASE}]");
// return false;
//}
var passPhraseDec = string.Empty;
if (!string.IsNullOrEmpty(passPhrase))
{
// パスフレーズの復号化
if (!SimpleEncryptUxer.Decrypt(passPhrase, out passPhraseDec, out string messageForMe))
{
LoggerUxer.Error($"SFTPのパスフレーズ復号化で失敗しました。[キー:{INIDIC_KEY_PASS_PHRASE},エラー内容:{messageForMe}]");
return false;
}
}
// オブジェクト生成
sftp = new SftpUxer(host, portNo, username, privateKeyPath, passPhraseDec);
return true;
}
private SftpUxer(string host, int port, string username, string privateKeyPath, string passPhrase)
{
_host = host;
_port = port;
_username = username;
_privateKeyPath = privateKeyPath;
_passPhrase = passPhrase;
}
public bool TestConnect(out string resultMessage)
{
resultMessage = string.Empty;
try
{
PrivateKeyFile keyFile;
if(!string.IsNullOrEmpty(_passPhrase))
{
// パスフレーズあり
keyFile = new PrivateKeyFile(_privateKeyPath, _passPhrase);
}
else
{
// パスフレーズなし
keyFile = new PrivateKeyFile(_privateKeyPath);
}
var keyFiles = new[] { keyFile };
using (var client = new SftpClient(_host, _port, _username, keyFiles))
{
client.Connect();
client.Disconnect();
}
return true;
}
catch (Exception ex)
{
resultMessage = $"SFTPのテスト接続に失敗しました。[ホスト:{_host},ポート:{_port},ユーザ名:{_username},プライベートキーファイルパス:{_privateKeyPath},エラー内容:{ex.Message}]";
return false;
}
}
public bool Upload(List<string> filePathList, string remotePath, out string resultMessage)
{
resultMessage = string.Empty;
if (string.IsNullOrEmpty(remotePath)) remotePath = ".";
try
{
if (!remotePath.EndsWith("/")) remotePath += "/";
PrivateKeyFile keyFile;
if (!string.IsNullOrEmpty(_passPhrase))
{
keyFile = new PrivateKeyFile(_privateKeyPath, _passPhrase);
}
else
{
keyFile = new PrivateKeyFile(_privateKeyPath);
}
var keyFiles = new[] { keyFile };
using (var client = new SftpClient(_host, _port, _username, keyFiles))
{
client.Connect();
foreach (var filePath in filePathList)
{
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
client.UploadFile(fileStream, remotePath + Path.GetFileName(filePath));
}
}
client.Disconnect();
}
return true;
}
catch (Exception ex)
{
resultMessage = $"SFTPのアップロードでエラーが発生しました。[ファイル:{string.Join(",", filePathList)},リモートパス:{remotePath},エラー内容:{ex.Message}]";
return false;
}
}
public bool Download(string remotePath, string localPath, out string resultMessage)
{
resultMessage = string.Empty;
try
{
var keyFile = new PrivateKeyFile(_privateKeyPath);
var keyFiles = new[] { keyFile };
using (var client = new SftpClient(_host, _port, _username, keyFiles))
{
client.Connect();
using (var fileStream = new FileStream(localPath, FileMode.Create))
{
client.DownloadFile(remotePath, fileStream);
}
client.Disconnect();
}
return true;
}
catch (Exception ex)
{
resultMessage = $"SFTPのダウンロード(Download)でエラーが発生しました。[エラー内容:{ex.Message}]";
return false;
}
}
public bool DownloadMatchingFiles(
string remoteDir,
string localDir,
out int downloadedFileCount,
out string resultMessage,
string pattern = "*.txt")
{
downloadedFileCount = 0;
resultMessage = string.Empty;
if (string.IsNullOrEmpty(remoteDir)) remoteDir = ".";
if (string.IsNullOrEmpty(localDir)) localDir = ".";
if (!Directory.Exists(localDir))
{
resultMessage = $"ダウンロード先のローカルフォルダが存在しません。[ローカルフォルダ:{localDir}]";
return false;
}
try
{
PrivateKeyFile keyFile;
if (!string.IsNullOrEmpty(_passPhrase))
{
keyFile = new PrivateKeyFile(_privateKeyPath, _passPhrase);
}
else
{
keyFile = new PrivateKeyFile(_privateKeyPath);
}
using (var client = new SftpClient(_host, _port, _username, keyFile))
{
client.Connect();
// リモートディレクトリ内のファイル一覧を取得
var files = client.ListDirectory(remoteDir)
.Where(f => !f.IsDirectory && StringUxer.WildcardMatch(f.Name, pattern));
foreach (var file in files)
{
string localPath = Path.Combine(localDir, file.Name);
using (var fs = new FileStream(localPath, FileMode.Create))
{
client.DownloadFile(file.FullName, fs);
Console.WriteLine($"1ファイルダウンロードしました。[ファイル名:{file.Name}]");
downloadedFileCount++;
}
}
client.Disconnect();
}
return true;
}
catch (Exception ex)
{
resultMessage = $"SFTPのダウンロード(DownloadMatchingFiles)でエラーが発生しました。[エラー内容:{ex.Message}]";
return false;
}
}
public bool DeleteMatchingFiles(
string remoteDir,
out int deletedFileCount,
out string resultMessage,
string pattern = "*.txt")
{
deletedFileCount = 0;
resultMessage = string.Empty;
try
{
var keyFile = new PrivateKeyFile(_privateKeyPath, _passPhrase);
using (var client = new SftpClient(_host, _port, _username, keyFile))
{
client.Connect();
// リモートディレクトリ内のファイル一覧を取得
var files = client.ListDirectory(remoteDir)
.Where(f => !f.IsDirectory && StringUxer.WildcardMatch(f.Name, pattern));
foreach (var file in files)
{
string remotePath = PathUxer.CombineUnixPath(remoteDir, file.Name);
client.DeleteFile(remotePath);
deletedFileCount++;
}
client.Disconnect();
}
return true;
}
catch (Exception ex)
{
resultMessage = $"SFTPのファイル削除でエラーが発生しました。[エラー内容:{ex.Message}]";
return false;
}
}
}
}
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.DtoMapping.Attributes
{
/// <summary>
/// Excel列レター属性(プロパティに付与)
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class ExcelColumnLetterAttribute : Attribute
{
/// <summary>
/// Excel対応列レター
/// </summary>
public string ColumnLetter { get; }
public ExcelColumnLetterAttribute(string columnLetter)
{
ColumnLetter = columnLetter;
}
}
}
+271
View File
@@ -0,0 +1,271 @@
using KssSmaPlaLib.Commons;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Encryption
{
public static class FIleEncryptUxer
{
public static bool TuckIntoMain(string[] args)
{
if (args.Length < 2) return false;
if (args[0].ToLower() == "/encfile")
{
var srcPath = args[1];
var descPath = args.Length >= 3 ? args[2] : args[1] + ".enc";
var password= args.Length >= 4 ? args[3] : string.Empty;
if (TryEncrypt(srcPath, descPath, out var messageForMe, password))
{
LoggerUxer.Info($"ファイル暗号化が成功しました。");
}
else
{
LoggerUxer.Error($"ファイル暗号化が失敗しました。[エラー内容:{messageForMe}]");
}
return true;
}
else if (args[0].ToLower() == "/decfile")
{
var srcPath = args[1];
var descPath = args.Length >= 3 ? args[2] : (srcPath.EndsWith(".enc") ? srcPath.TrimEnd(".enc".ToArray()) : srcPath + ".src");
var password = args.Length >= 4 ? args[3] : string.Empty;
if (TryDecrypt(srcPath, descPath, out var messageForMe, password))
{
Console.WriteLine($"ファイル複合化が成功しました。");
}
else
{
Console.WriteLine($"ファイル複合化が失敗しました。[エラー内容:{messageForMe}]");
}
return true;
}
else if (args[0].ToLower() == "/encbigfile")
{
var srcPath = args[1];
var descPath = args.Length >= 3 ? args[2] : args[1] + ".enc";
var password = args.Length >= 4 ? args[3] : string.Empty;
// テキストのみ方式
if (TryEncryptLargeFileToBase64(srcPath, descPath, out var messageForMe, true, password))
{
LoggerUxer.Info($"ファイル暗号化が成功しました。");
}
else
{
LoggerUxer.Error($"ファイル暗号化が失敗しました。[エラー内容:{messageForMe}]");
}
return true;
}
else if (args[0].ToLower() == "/decbigfile")
{
var srcPath = args[1];
var descPath = args.Length >= 3 ? args[2] : (srcPath.EndsWith(".enc") ? srcPath.TrimEnd(".enc".ToArray()) : srcPath + ".src");
var password = args.Length >= 4 ? args[3] : string.Empty;
if (TryDecryptLargeFileFromBase64(srcPath, descPath, out var messageForMe, true, password))
{
Console.WriteLine($"ファイル複合化が成功しました。");
}
else
{
Console.WriteLine($"ファイル複合化が失敗しました。[エラー内容:{messageForMe}]");
}
return true;
}
return false;
}
public static bool TryEncryptLargeFileToBase64(string inputFilePath, string outputTextFilePath, out string resultMessage, bool isAllText = false, string password = "")
{
if (string.IsNullOrEmpty(password)) password = SimpleEncryptUxer.FixedPassword;
try
{
byte[] key = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(password));
using (var aes = Aes.Create())
{
aes.Key = key;
aes.GenerateIV();
using (var inputStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read))
using (var outputStream = new FileStream(outputTextFilePath, FileMode.Create, FileAccess.Write))
{
if (isAllText)
{
using (var memoryStream = new MemoryStream())
using (var encryptor = aes.CreateEncryptor())
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
cryptoStream.Write(buffer, 0, bytesRead);
}
cryptoStream.FlushFinalBlock();
string ivBase64 = Convert.ToBase64String(aes.IV);
string cipherBase64 = Convert.ToBase64String(memoryStream.ToArray());
string outputText = $"{ivBase64}::{cipherBase64}";
byte[] outputBytes = Encoding.UTF8.GetBytes(outputText);
outputStream.Write(outputBytes, 0, outputBytes.Length);
}
}
else
{
// IVはバイナリで先頭に書き込む
outputStream.Write(aes.IV, 0, aes.IV.Length);
using (var base64Transform = new ToBase64Transform())
using (var cryptoStream = new CryptoStream(outputStream, base64Transform, CryptoStreamMode.Write))
using (var encryptor = aes.CreateEncryptor())
using (var aesStream = new CryptoStream(cryptoStream, encryptor, CryptoStreamMode.Write))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
aesStream.Write(buffer, 0, bytesRead);
}
aesStream.FlushFinalBlock();
}
}
}
}
resultMessage = "暗号化成功";
return true;
}
catch (Exception ex)
{
resultMessage = $"暗号化失敗: {ex.Message}";
return false;
}
}
public static bool TryDecryptLargeFileFromBase64(string inputTextFilePath, string outputFilePath, out string resultMessage, bool isAllText = false, string password = "")
{
resultMessage = string.Empty;
if (string.IsNullOrEmpty(password)) password = SimpleEncryptUxer.FixedPassword;
try
{
byte[] key = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(password));
using (var aes = Aes.Create())
{
aes.Key = key;
if (isAllText)
{
string inputText = File.ReadAllText(inputTextFilePath, Encoding.UTF8);
string[] parts = inputText.Split(new[] { "::" }, StringSplitOptions.None);
if (parts.Length != 2)
{
resultMessage = $"暗号ファイルの形式が不正です(::区切りが見つかりません)";
return false;
}
byte[] iv = Convert.FromBase64String(parts[0]);
byte[] cipherBytes = Convert.FromBase64String(parts[1]);
aes.IV = iv;
using (var decryptor = aes.CreateDecryptor())
using (var memoryStream = new MemoryStream(cipherBytes))
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
using (var outputStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, bytesRead);
}
}
}
else
{
using (var inputStream = new FileStream(inputTextFilePath, FileMode.Open, FileAccess.Read))
{
byte[] iv = new byte[16];
inputStream.Read(iv, 0, iv.Length);
aes.IV = iv;
using (var base64Transform = new FromBase64Transform())
using (var cryptoStream = new CryptoStream(inputStream, base64Transform, CryptoStreamMode.Read))
using (var decryptor = aes.CreateDecryptor())
using (var aesStream = new CryptoStream(cryptoStream, decryptor, CryptoStreamMode.Read))
using (var outputStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = aesStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, bytesRead);
}
}
}
}
}
return true;
}
catch (Exception ex)
{
resultMessage = $"ファイルの復号化に失敗しました。[エラー内容:{ex.Message}]";
return false;
}
}
public static bool TryEncrypt(string inputFilePath, string outputTextFilePath, out string resultMessage, string password = "")
{
try
{
string base64Data = Convert.ToBase64String(File.ReadAllBytes(inputFilePath));
bool success = SimpleEncryptUxer.Encrypt(base64Data, out var resultText, out var messageForMe, password);
resultMessage = messageForMe;
if (success)
{
File.WriteAllText(outputTextFilePath, resultText, Encoding.UTF8);
return true;
}
return false;
}
catch (Exception ex)
{
resultMessage = $"ファイル暗号化失敗: {ex.Message}";
return false;
}
}
public static bool TryDecrypt(string inputTextFilePath, string outputBinaryFilePath, out string resultMessage, string password = "")
{
try
{
string encryptedText = File.ReadAllText(inputTextFilePath, Encoding.UTF8);
bool success = SimpleEncryptUxer.Decrypt(encryptedText, out var resultText, out var messageForMe, password);
resultMessage = messageForMe;
if (success)
{
byte[] binaryData = Convert.FromBase64String(resultText);
File.WriteAllBytes(outputBinaryFilePath, binaryData);
return true;
}
return false;
}
catch (Exception ex)
{
resultMessage = $"ファイル復号化失敗: {ex.Message}";
return false;
}
}
}
}
+96
View File
@@ -0,0 +1,96 @@
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Encryption
{
public static class SimpleEncryptUxer
{
public static readonly string FixedPassword = "KssSmaPlaDxer!";
private static readonly byte[] FixedIV = new byte[16];
public static bool TuckIntoMain(string[] args)
{
if (args.Length != 2) return false;
if (args[0].ToLower() == "/enc")
{
if (SimpleEncryptUxer.Encrypt(args[1], out var resultText, out var resultMessage))
{
Console.WriteLine($"暗号化結果[{resultText}]");
}
else
{
Console.WriteLine(resultMessage);
}
return true;
}
else if (args[0].ToLower() == "/dec")
{
if (SimpleEncryptUxer.Decrypt(args[1], out var resultText, out var resultMessage))
{
Console.WriteLine($"複合化結果[{resultText}]");
}
else
{
Console.WriteLine(resultMessage);
}
return true;
}
return false;
}
public static bool Encrypt(string plainText, out string resultText, out string resultMessage, string password = "")
{
resultText = string.Empty;
resultMessage = string.Empty;
password = string.IsNullOrEmpty(password) ? FixedPassword : password;
try
{
byte[] key = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(password));
// 固定IV(簡易仕様とする)※IVはオールゼロ
using (var aes = new AesManaged { Key = key, IV = FixedIV })
using (var encryptor = aes.CreateEncryptor())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(plainText);
byte[] encryptedBytes = encryptor.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
resultText = Convert.ToBase64String(encryptedBytes);
return true;
}
}
catch (Exception ex)
{
resultMessage = $"暗号化に失敗しました。[エラー内容:{ex.Message}]";
return false;
}
}
public static bool Decrypt(string encryptedText, out string resultText, out string resultMessage, string password = "")
{
resultText = string.Empty;
resultMessage = string.Empty;
password = string.IsNullOrEmpty(password) ? FixedPassword : password;
try
{
byte[] key = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(password));
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
using (var aes = new AesManaged { Key = key, IV = FixedIV })
using (var decryptor = aes.CreateDecryptor())
{
byte[] decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
resultText = Encoding.UTF8.GetString(decryptedBytes);
return true;
}
}
catch (Exception ex)
{
resultMessage = $"複合化に失敗しました。[エラー内容:{ex.Message}]";
return false;
}
}
}
}
+153
View File
@@ -0,0 +1,153 @@
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.IO.Database;
using KssSmaPlaLib.IO.File;
using Org.BouncyCastle.Asn1.X509;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Exchange
{
public static class CsvDbSyncUxer
{
private const string INI_KEY_INSERT_PROCESSING_MODE = "InsertProcessingMode";
private const string INI_VALUE_INSERT_PROCESSING_MODE_BULK = "Bulk";
private const string INI_VALUE_INSERT_PROCESSING_MODE_ROW_BY_ROW = "RowByRow";
private const string INI_KEY_SQL_NAME_INSERT_BULK = "SqlNameInsertBulk";
public static bool InsertDbFromCsvFiles(
Dictionary<string, string> iniDic,
DbUxer con,
string csvFilePath,
string dupCheckSql,
string insertSqlName,
out string resultMessage,
EncodingUxer.EncodingType encodingType = EncodingUxer.EncodingType.Utf8WithoutBom)
{
var messageForMe = string.Empty;
resultMessage = string.Empty;
var mode = DictionaryUxer.GetValueOrDefault<string, string>(
iniDic,
INI_KEY_INSERT_PROCESSING_MODE,
INI_VALUE_INSERT_PROCESSING_MODE_ROW_BY_ROW);
//if (string.IsNullOrEmpty(mode))
//{
// resultMessage = $"挿入モードが設定されていません。[キー:{INI_KEY_INSERT_PROCESSING_MODE}]";
// return false;
//}
string[] validValues = {
INI_VALUE_INSERT_PROCESSING_MODE_BULK,
INI_VALUE_INSERT_PROCESSING_MODE_ROW_BY_ROW };
mode = mode.Trim();
if (!validValues.Contains(mode, StringComparer.OrdinalIgnoreCase))
{
resultMessage = $"挿入モードの値が不正です。[{INI_KEY_INSERT_PROCESSING_MODE}:{mode}]";
return false;
}
if (mode.ToUpper() == INI_VALUE_INSERT_PROCESSING_MODE_ROW_BY_ROW.ToUpper())
{
// 1行ずつ挿入(従来方式)
// CSV読み込み
if (!CsvUxer.ImportFromCsv(csvFilePath, out var rs, out messageForMe, encodingType))
{
resultMessage = messageForMe;
return false;
}
LoggerUxer.Info($"[CSV件数:{rs.Count}]");
if (string.IsNullOrEmpty(dupCheckSql))
{
LoggerUxer.Info($"重複チェックSQLが未指定のため重複チェックは行いません。");
}
else
{
LoggerUxer.Info($"重複チェックを行います。[SQLファイル:{dupCheckSql}]");
}
foreach (var rec in rs)
{
var recObj = rec.ToDictionary(kvp => kvp.Key, kvp => (object)kvp.Value);
if (!string.IsNullOrEmpty(dupCheckSql))
{
// 重複チェック
if (!con.ExecuteQuery(dupCheckSql, recObj, out var dupRs, out messageForMe))
{
resultMessage = "重複チェックエラー:" + messageForMe;
return false;
}
if (dupRs.Count != 1)
{
resultMessage = $"重複チェックで取得件数エラーです。[取得件数:{dupRs.Count}]";
return false;
}
// ↓COUNT(*)の結果型はintにあらず(ポスグレの場合long)ゆえに文字列化してint化する
if (!int.TryParse(dupRs[0].Values.ElementAt(0).ToString(), out var intCnt))
{
resultMessage = $"重複チェックで取得値(件数)が数値ではありません。[取得値:{dupRs[0].Values.ElementAt(0)}]";
return false;
}
// 重複レコードありの場合、飛ばす
if (intCnt > 0)
{
LoggerUxer.Info($"重複レコードのため、飛ばします。[該当件数:{intCnt}]");
continue;
}
LoggerUxer.Info($"重複チェックにて重複レコードは見つかりませんでした。");
}
// DB挿入
if (!string.IsNullOrEmpty(insertSqlName))
{
LoggerUxer.Info($"[DB挿入SQL名:{insertSqlName}]");
if (!con.ExecuteNonQuery(insertSqlName, recObj, out var resultCount, out messageForMe))
{
resultMessage = messageForMe;
return false;
}
LoggerUxer.Info($"[DB挿入件数:{resultCount}]");
}
else
{
LoggerUxer.Info($"DB挿入SQL名が未指定のためDB挿入は行いません。");
}
}
}
else
{
// バルク挿入
LoggerUxer.Info($"バルク挿入が指定されました。");
insertSqlName = DictionaryUxer.GetValueOrDefault<string, string>(
iniDic,
INI_KEY_SQL_NAME_INSERT_BULK,
string.Empty);
if (string.IsNullOrEmpty(insertSqlName))
{
resultMessage = $"バルク挿入SQLファイル名が指定されていません。[キー:{INI_KEY_SQL_NAME_INSERT_BULK}]";
return false;
}
LoggerUxer.Info($"[DBバルク挿入SQL名:{insertSqlName}]");
if (!con.BeginTextImport(insertSqlName, csvFilePath, out var resultCount, out messageForMe))
{
resultMessage = messageForMe;
return false;
}
LoggerUxer.Info($"[DBバルク挿入件数:{resultCount}]");
}
return true;
}
}
}
+14
View File
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Exchange.Interfaces
{
public interface ICsvExportableUxer
{
string CsvHeader { get; } // ヘッダー行
string ToCsvLine(); // データ行
}
}
+74
View File
@@ -0,0 +1,74 @@
using DocumentFormat.OpenXml.Wordprocessing;
using KssSmaPlaLib.Ini;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Color = System.Drawing.Color;
namespace KssSmaPlaLib.Forms
{
public static class ColorHelper
{
/// <summary>
/// 色選択
/// </summary>
/// <param name="form"></param>
/// <param name="defaultColor"></param>
/// <param name="iniKey"></param>
/// <returns></returns>
public static Color? SelectColor(Form form, Color defaultColor, string iniKey = "")
{
using (ColorDialog cd = new ColorDialog())
{
// 今の色を初期選択にしておく
cd.Color = defaultColor;
if (cd.ShowDialog(form) != DialogResult.OK) return null;
if (!string.IsNullOrEmpty(iniKey))
{
// 2. 🔥 Colorを16進数(#RRGGBB)に変換してINIに書き込み
string colorHex = ColorTranslator.ToHtml(cd.Color);
IniHelper.WriteValue(null, form.Name, iniKey, colorHex);
}
return cd.Color;
}
}
/// <summary>
/// Colorを汎用的なHTML色コード文字列に変換する
/// </summary>
/// <param name="color"></param>
/// <returns></returns>
public static string ColorToHtmlColorString(Color color)
{
return ColorTranslator.ToHtml(color);
}
/// <summary>
/// 汎用的なHTML色コード文字列からColorに変換する
/// </summary>
/// <param name="htmlColorString"></param>
/// <returns></returns>
public static Color HtmlColorStringToColor(string htmlColorString)
{
return ColorTranslator.FromHtml(htmlColorString);
}
/// <summary>
/// 背景色から最適な文字色(黒/白)を返すメソッド
/// </summary>
/// <param name="backColor"></param>
/// <returns></returns>
public static Color GetContrastColor(Color backColor)
{
// 輝度計算 (ITU-R BT.601)
double luminance = (0.299 * backColor.R) + (0.587 * backColor.G) + (0.114 * backColor.B);
return (luminance > 128) ? Color.Black : Color.White;
}
}
}
+74
View File
@@ -0,0 +1,74 @@
using KssSmaPlaLib.Ini;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Forms.ContextMenuFunction
{
public static class FontUxer
{
/// <summary>
/// フォント選択
/// </summary>
/// <param name="form"></param>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="defaultFont"></param>
/// <param name="resultFont"></param>
/// <returns></returns>
public static bool SelectFont(Form form, string section, string key, Font defaultFont, out Font resultFont)
{
// デフォルト値
resultFont = new Font(defaultFont, defaultFont.Style);
using (var dlg = new FontDialog())
{
var defaultFontCsv =
defaultFont.Name + "," +
defaultFont.Size.ToString() + "," +
defaultFont.Bold.ToString();
var iniFontCsv = IniHelper.ReadValue(null, section, key, defaultFontCsv);
var fontItems = iniFontCsv.Split(',');
if (fontItems.Length != 3) fontItems = defaultFontCsv.Split(',');
if (float.TryParse(fontItems[1], out var size) == false) size = defaultFont.Size;
if (bool.TryParse(fontItems[2], out var bold) == false) bold = defaultFont.Bold;
dlg.Font = new Font(fontItems[0], size, bold ? FontStyle.Bold : FontStyle.Regular);
dlg.AllowVerticalFonts = false;
// 文字飾り(取り消し線と下線)を表示させない
dlg.ShowEffects = false;
var result = dlg.ShowDialog(form);
if (result == DialogResult.Cancel) return false;
// INI保存
var fontCsv =
dlg.Font.Name + "," +
dlg.Font.Size.ToString() + "," +
dlg.Font.Bold.ToString();
IniHelper.WriteValue(null, section, key, fontCsv);
// 出力
resultFont = new Font(dlg.Font, dlg.Font.Style);
return true;
}
}
public static Font GetFont(string section, string key, Font defaultFont)
{
var defaultFontCsv =
defaultFont.Name + "," +
defaultFont.Size.ToString() + "," +
defaultFont.Bold.ToString();
var iniFontCsv = IniHelper.ReadValue(null, section, key, defaultFontCsv);
var fontItems = iniFontCsv.Split(',');
if (fontItems.Length != 3) fontItems = defaultFontCsv.Split(',');
if (float.TryParse(fontItems[1], out var size) == false) size = defaultFont.Size;
if (bool.TryParse(fontItems[2], out var bold) == false) bold = defaultFont.Bold;
return new Font(fontItems[0], size, bold ? FontStyle.Bold : FontStyle.Regular);
}
}
}
@@ -0,0 +1,197 @@
namespace KssSmaPlaLib.Forms.ContextMenuFunction.Gamen
{
partial class DgvColumnEditorForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.ColumnDgv = new System.Windows.Forms.DataGridView();
this.CancelButton2 = new System.Windows.Forms.Button();
this.OkButton = new System.Windows.Forms.Button();
this.colPropertyName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colDefaultDisplayName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colDisplayName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.UpButton = new System.Windows.Forms.Button();
this.DownButton = new System.Windows.Forms.Button();
this.PopupMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.EditDisplayNameMenu = new System.Windows.Forms.ToolStripMenuItem();
this.VisibleMenu = new System.Windows.Forms.ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.ColumnDgv)).BeginInit();
this.PopupMenu.SuspendLayout();
this.SuspendLayout();
//
// ColumnDgv
//
this.ColumnDgv.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ColumnDgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.ColumnDgv.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colPropertyName,
this.colDefaultDisplayName,
this.colDisplayName});
this.ColumnDgv.Location = new System.Drawing.Point(15, 16);
this.ColumnDgv.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7);
this.ColumnDgv.Name = "ColumnDgv";
this.ColumnDgv.RowHeadersWidth = 62;
this.ColumnDgv.RowTemplate.Height = 27;
this.ColumnDgv.Size = new System.Drawing.Size(505, 429);
this.ColumnDgv.TabIndex = 0;
this.ColumnDgv.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ColumnDgv_KeyDown);
//
// CancelButton2
//
this.CancelButton2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.CancelButton2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CancelButton2.Location = new System.Drawing.Point(346, 455);
this.CancelButton2.Name = "CancelButton2";
this.CancelButton2.Size = new System.Drawing.Size(177, 58);
this.CancelButton2.TabIndex = 1;
this.CancelButton2.Text = "キャンセル";
this.CancelButton2.UseVisualStyleBackColor = true;
//
// OkButton
//
this.OkButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.OkButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.OkButton.Location = new System.Drawing.Point(163, 455);
this.OkButton.Name = "OkButton";
this.OkButton.Size = new System.Drawing.Size(177, 58);
this.OkButton.TabIndex = 2;
this.OkButton.Text = "OK";
this.OkButton.UseVisualStyleBackColor = true;
this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
//
// colPropertyName
//
this.colPropertyName.HeaderText = "識別名";
this.colPropertyName.MinimumWidth = 8;
this.colPropertyName.Name = "colPropertyName";
this.colPropertyName.Width = 150;
//
// colDefaultDisplayName
//
this.colDefaultDisplayName.HeaderText = "デフォ表示名";
this.colDefaultDisplayName.MinimumWidth = 8;
this.colDefaultDisplayName.Name = "colDefaultDisplayName";
this.colDefaultDisplayName.Width = 150;
//
// colDisplayName
//
this.colDisplayName.HeaderText = "表示名";
this.colDisplayName.MinimumWidth = 8;
this.colDisplayName.Name = "colDisplayName";
this.colDisplayName.Width = 150;
//
// UpButton
//
this.UpButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.UpButton.Location = new System.Drawing.Point(15, 455);
this.UpButton.Name = "UpButton";
this.UpButton.Size = new System.Drawing.Size(59, 58);
this.UpButton.TabIndex = 3;
this.UpButton.Text = "👆";
this.UpButton.UseVisualStyleBackColor = true;
this.UpButton.Click += new System.EventHandler(this.UpButton_Click);
//
// DownButton
//
this.DownButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.DownButton.Location = new System.Drawing.Point(80, 455);
this.DownButton.Name = "DownButton";
this.DownButton.Size = new System.Drawing.Size(59, 58);
this.DownButton.TabIndex = 4;
this.DownButton.Text = "👇";
this.DownButton.UseVisualStyleBackColor = true;
this.DownButton.Click += new System.EventHandler(this.DownButton_Click);
//
// PopupMenu
//
this.PopupMenu.Font = new System.Drawing.Font("メイリオ", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.PopupMenu.ImageScalingSize = new System.Drawing.Size(24, 24);
this.PopupMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.EditDisplayNameMenu,
this.VisibleMenu});
this.PopupMenu.Name = "PopupMenu";
this.PopupMenu.Size = new System.Drawing.Size(394, 133);
//
// EditDisplayNameMenu
//
this.EditDisplayNameMenu.Name = "EditDisplayNameMenu";
this.EditDisplayNameMenu.Size = new System.Drawing.Size(393, 48);
this.EditDisplayNameMenu.Text = "表示名の編集...";
this.EditDisplayNameMenu.Click += new System.EventHandler(this.EditDisplayNameMenu_Click);
//
// VisibleMenu
//
this.VisibleMenu.Name = "VisibleMenu";
this.VisibleMenu.Size = new System.Drawing.Size(393, 48);
this.VisibleMenu.Text = "表示/非表示の切り替え";
this.VisibleMenu.Click += new System.EventHandler(this.VisibleMenu_Click);
//
// DgvColumnEditorForm
//
this.AcceptButton = this.OkButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(19F, 42F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.CancelButton = this.CancelButton2;
this.ClientSize = new System.Drawing.Size(535, 525);
this.ContextMenuStrip = this.PopupMenu;
this.Controls.Add(this.DownButton);
this.Controls.Add(this.UpButton);
this.Controls.Add(this.OkButton);
this.Controls.Add(this.CancelButton2);
this.Controls.Add(this.ColumnDgv);
this.Font = new System.Drawing.Font("メイリオ", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7);
this.Name = "DgvColumnEditorForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "列一覧💖";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.DgvColumnEditorForm_FormClosing);
this.Load += new System.EventHandler(this.DgvColumnEditorForm_Load);
((System.ComponentModel.ISupportInitialize)(this.ColumnDgv)).EndInit();
this.PopupMenu.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView ColumnDgv;
private System.Windows.Forms.Button CancelButton2;
private System.Windows.Forms.Button OkButton;
private System.Windows.Forms.DataGridViewTextBoxColumn colPropertyName;
private System.Windows.Forms.DataGridViewTextBoxColumn colDefaultDisplayName;
private System.Windows.Forms.DataGridViewTextBoxColumn colDisplayName;
private System.Windows.Forms.Button UpButton;
private System.Windows.Forms.Button DownButton;
private System.Windows.Forms.ContextMenuStrip PopupMenu;
private System.Windows.Forms.ToolStripMenuItem EditDisplayNameMenu;
private System.Windows.Forms.ToolStripMenuItem VisibleMenu;
}
}
@@ -0,0 +1,334 @@
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.Forms;
using KssSmaPlaLib.Ini;
using KssSmaPlaLib.Input.Gamen;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Forms.ContextMenuFunction.Gamen
{
public partial class DgvColumnEditorForm : Form
{
private const string COL_NAME_PROPERTY_NAME = "colPropertyName";
private const string COL_NAME_DEFAULT_DISPLAY_NAME = "colDefaultDisplayName";
private const string COL_NAME_DISPLAY_NAME = "colDisplayName";
/// <summary>
/// 対象のDGV
/// </summary>
private DataGridView _targetDgv = null;
/// <summary>
/// 対象DGVの列名から列インデックスを取得する辞書
/// (後ほど列インデックスが全てゼロになる事象が起きるため)
/// </summary>
private readonly Dictionary<string, int> _colNameToRowIndexDic = null;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="dgv"></param>
public DgvColumnEditorForm(DataGridView dgv)
{
InitializeComponent();
_targetDgv = dgv;
// 列名から列インデックスを取得する辞書の作成(後ほど列インデックスが全てゼロになる事象が起きるため)
_colNameToRowIndexDic = new Dictionary<string, int>();
foreach (DataGridViewColumn col in _targetDgv.Columns) _colNameToRowIndexDic.Add(col.Name, col.Index);
this.DialogResult = DialogResult.Cancel;
DgvHelper.Initialize(ColumnDgv);
ColumnDgv.Rows.Clear();
// 編集した表示名
var csv = IniHelper.ReadValue(null, _targetDgv.Parent.Name + "." + _targetDgv.Name, KEY_NAME_DISPLAY_NAME_CSV);
// 表示順のリストを作る
var cols = new DataGridViewColumn[_targetDgv.Columns.Count];
_targetDgv.Columns.CopyTo(cols, 0);
Array.Sort(cols, (a, b) => a.DisplayIndex.CompareTo(b.DisplayIndex));
foreach (var col in cols)
{
var index = ColumnDgv.Rows.Add();
string propertyName = string.Empty;
string defaultDisplayName = string.Empty;
bool visible = true;
var colIndex = col.Index;
var displayIndex = col.DisplayIndex;
if (col.Tag == null || !(col.Tag is PropertyDescriptor))
{
propertyName = col.Name;
defaultDisplayName = propertyName;
}
else
{
PropertyDescriptor pd = col.Tag as PropertyDescriptor;
propertyName = pd.Name;
defaultDisplayName = pd.DisplayName;
var browsableAttr = pd.Attributes.OfType<BrowsableAttribute>().FirstOrDefault();
if (browsableAttr != null && !browsableAttr.Browsable)
{
visible = false;
}
}
//string displayName = col.HeaderText;
string displayName =
StringUxer.GetStringByIndexFormCsv(csv, colIndex, string.Empty)
.Replace("@@@COMMA@@@", ",");
ColumnDgv.Rows[index].Tag = col;
ColumnDgv.Rows[index].Cells[COL_NAME_PROPERTY_NAME].Value = (!visible ? "【非】" : "") + propertyName;
ColumnDgv.Rows[index].Cells[COL_NAME_DEFAULT_DISPLAY_NAME].Value = defaultDisplayName;
ColumnDgv.Rows[index].Cells[COL_NAME_DISPLAY_NAME].Value = displayName == defaultDisplayName ? "" : displayName;
SetVisible(index, col.Visible);
}
//// タグに入れておく(PropertyDescriptor型)
//col.Tag = pd;
//// 列ヘッダーを [DisplayName] に
//col.HeaderText = pd.DisplayName;
//// [Browsable(false)] の列は非表示(AutoGenerateでも列が立つ場合の保険)
//var browsableAttr = pd.Attributes.OfType<BrowsableAttribute>().FirstOrDefault();
//if (browsableAttr != null && !browsableAttr.Browsable)
//{
// col.Visible = false;
// continue;
//}
// DGV列幅復元
DgvHelper.DgvLoadColWidth(ColumnDgv);
}
/// <summary>
/// フォームロード
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DgvColumnEditorForm_Load(object sender, EventArgs e)
{
// バウンズ復元
FormHelper.LoadFormBounds(this);
}
/// <summary>
/// 👆ボタンクリック時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UpButton_Click(object sender, EventArgs e)
{
// 対象外状況判断
if (ColumnDgv.SelectedRows.Count < 1) return;
if (ColumnDgv.SelectedRows[0].Index == 0) return;
// 事前取得
var row = ColumnDgv.SelectedRows[0];
var index = row.Index; // Removeしたら-1になるからその前に取得しておく
// 行移動の実行
ColumnDgv.Rows.Remove(row);
ColumnDgv.Rows.Insert(index - 1, row);
// 行選択
ColumnDgv.ClearSelection();
ColumnDgv.Rows[index - 1].Selected = true;
}
/// <summary>
/// 👇ボタンクリック時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DownButton_Click(object sender, EventArgs e)
{
// 対象外状況判断
if (ColumnDgv.SelectedRows.Count < 1) return;
if (ColumnDgv.SelectedRows[0].Index == ColumnDgv.RowCount - 1) return;
// 事前取得
var row = ColumnDgv.SelectedRows[0];
var index = row.Index; // Removeしたら-1になるからその前に取得しておく
// 行移動の実行
ColumnDgv.Rows.Remove(row);
ColumnDgv.Rows.Insert(index + 1, row);
// 行選択
ColumnDgv.ClearSelection();
ColumnDgv.Rows[index + 1].Selected = true;
}
/// <summary>
/// DGVキー押下イベント
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ColumnDgv_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down))
{
if (e.KeyCode == Keys.Up)
{
UpButton_Click(sender, e);
}
else
{
DownButton_Click(sender, e);
}
// 既定動作抑止(メニュー呼び/ビープを止める)
e.Handled = true;
e.SuppressKeyPress = true;
}
}
private const string KEY_NAME_DISPLAY_INDEX_CSV = "DisplayIndexCsv";
private const string KEY_NAME_COLUMN_VISIBLE_CSV = "ColumnVisibleCsv";
private const string KEY_NAME_DISPLAY_NAME_CSV = "DisplayNameCsv";
/// <summary>
/// OKボタンクリック時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OkButton_Click(object sender, EventArgs e)
{
//List<int> indexList = new List<int>();
//foreach (DataGridViewRow row in ColumnDgv.Rows) indexList.Add(((DataGridViewColumn)row.Tag).Index);
////MessageBox.Show(string.Join(" ", indexList));
//if (indexList.Max() != ColumnDgv.Rows.Count - 1)
if (_colNameToRowIndexDic.Values.Max() != ColumnDgv.Rows.Count - 1)
{
MessageBox.Show(this, $"_colNameToRowIndexDicがおかしい![_colNameToRowIndexDicのMax:{_colNameToRowIndexDic.Values.Max()},グリッド行数:{ColumnDgv.Rows.Count}]");
this.DialogResult = DialogResult.None;
return;
}
// 表示順
int[] displayIndexArray = new int[ColumnDgv.Rows.Count];
foreach (DataGridViewRow row in ColumnDgv.Rows)
displayIndexArray[_colNameToRowIndexDic[((DataGridViewRow)row).Cells[0].Value.ToString()]]
= ((DataGridViewRow)row).Index;
// INI書き込み
IniHelper.WriteValue(null, _targetDgv.Parent.Name + "." + _targetDgv.Name, KEY_NAME_DISPLAY_INDEX_CSV, string.Join(",", displayIndexArray));
// 表示非表示
bool[] visibleArray = new bool[ColumnDgv.Rows.Count];
foreach (DataGridViewRow row in ColumnDgv.Rows)
visibleArray[_colNameToRowIndexDic[((DataGridViewRow)row).Cells[0].Value.ToString()]]
= IsVisible(((DataGridViewRow)row).Index);
// INI書き込み
IniHelper.WriteValue(null, _targetDgv.Parent.Name + "." + _targetDgv.Name, KEY_NAME_COLUMN_VISIBLE_CSV, string.Join(",", visibleArray));
// 表示名称
string[] nameArray = new string[ColumnDgv.Rows.Count];
foreach (DataGridViewRow row in ColumnDgv.Rows)
{
var name = string.Empty;
if (row.Cells[COL_NAME_DISPLAY_NAME].Value.ToString() != row.Cells[COL_NAME_DEFAULT_DISPLAY_NAME].Value.ToString())
{
name = row.Cells[COL_NAME_DISPLAY_NAME]
.Value
.ToString()
.Replace(",", "@@@COMMA@@@");
}
nameArray[_colNameToRowIndexDic[((DataGridViewRow)row).Cells[0].Value.ToString()]] = name;
}
// INI書き込み
IniHelper.WriteValue(null, _targetDgv.Parent.Name + "." + _targetDgv.Name, KEY_NAME_DISPLAY_NAME_CSV, string.Join(",", nameArray));
}
/// <summary>
/// フォーム閉じるとき
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DgvColumnEditorForm_FormClosing(object sender, FormClosingEventArgs e)
{
// バウンズの保存
FormHelper.SaveFormBounds(this);
// DGV列幅保存
DgvHelper.DgvSaveColWidth(ColumnDgv);
}
/// <summary>
/// 表示名の編集メニュークリック
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void EditDisplayNameMenu_Click(object sender, EventArgs e)
{
if (ColumnDgv.SelectedRows.Count < 1) return;
var rowIndex = ColumnDgv.SelectedRows[0].Index;
var text = ColumnDgv[COL_NAME_DISPLAY_NAME,rowIndex].Value.ToString();
var defaultText= ColumnDgv[COL_NAME_DEFAULT_DISPLAY_NAME, rowIndex].Value.ToString();
if (string.IsNullOrEmpty(text)) text = defaultText;
using (var form = new TextInputForm(text))
{
if (form.ShowDialog() == DialogResult.Cancel) return;
ColumnDgv[COL_NAME_DISPLAY_NAME, rowIndex].Value = form.EditedText == defaultText ? "" : form.EditedText;
}
}
private void VisibleMenu_Click(object sender, EventArgs e)
{
if (ColumnDgv.SelectedRows.Count < 1) return;
var rowIndex = ColumnDgv.SelectedRows[0].Index;
SetVisible(rowIndex, !IsVisible(rowIndex));
}
private bool IsVisible(int rowIndex)
{
if (rowIndex < 0 || rowIndex >= ColumnDgv.Rows.Count) return true;
if (ColumnDgv.Rows[rowIndex].DefaultCellStyle == null) return true;
if (ColumnDgv.Rows[rowIndex].DefaultCellStyle.Font == null) return true;
var style = ColumnDgv.Rows[rowIndex].DefaultCellStyle.Font.Style;
return !((style & FontStyle.Strikeout) == FontStyle.Strikeout);
}
private void SetVisible(int rowIndex, bool visible)
{
if (rowIndex < 0 || rowIndex >= ColumnDgv.Rows.Count) return;
if (ColumnDgv.Rows[rowIndex].DefaultCellStyle == null) return;
Font font;
if (ColumnDgv.Rows[rowIndex].DefaultCellStyle.Font != null)
{
font = ColumnDgv.Rows[rowIndex].DefaultCellStyle.Font;
}
else
{
font = ColumnDgv.DefaultCellStyle.Font;
}
var style = font.Style;
if (visible)
{
style &= ~FontStyle.Strikeout;
}
else
{
style |= FontStyle.Strikeout;
}
ColumnDgv.Rows[rowIndex].DefaultCellStyle.Font = new Font(font, style);
// 背景色
ColumnDgv.Rows[rowIndex].DefaultCellStyle.BackColor = visible ? Color.Empty : Color.DarkGray;
}
}
}
@@ -0,0 +1,132 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="colPropertyName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colDefaultDisplayName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="colDisplayName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="PopupMenu.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>
+332
View File
@@ -0,0 +1,332 @@
using DocumentFormat.OpenXml.Office2010.CustomUI;
using KssSmaPlaLib.Forms.ContextMenuFunction;
using KssSmaPlaLib.Ini;
using KssSmaPlaLib.Input.Gamen;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Windows.UI.Popups;
namespace KssSmaPlaLib.Forms
{
public static class ContextMenuHelper
{
private const string INI_KEY_TITLE = "Title";
private const string INI_KEY_BACK_COLOR = "BackColor";
/// <summary>
/// フォーム背景色選択
/// </summary>
/// <param name="form"></param>
public static void SelectBackColor(Form form)
{
using (ColorDialog cd = new ColorDialog())
{
// 今の色を初期選択にしておく
cd.Color = form.BackColor;
if (cd.ShowDialog() == DialogResult.OK)
{
// 1. フォームの背景色を即時変更
form.BackColor = cd.Color;
// 2. 🔥 Colorを16進数(#RRGGBB)に変換してINIに書き込み
string colorHex = ColorTranslator.ToHtml(cd.Color);
IniHelper.WriteValue(null, form.Name, INI_KEY_BACK_COLOR, colorHex);
}
}
}
/// <summary>
/// 背景色をINIから取得して設定
/// </summary>
/// <param name="form"></param>
public static void SetBackColorFromIni(Form form)
{
var colorHex = IniHelper.ReadValue(null, form.Name, INI_KEY_BACK_COLOR, ColorTranslator.ToHtml(form.BackColor));
form.BackColor = ColorTranslator.FromHtml(colorHex);
}
/// <summary>
/// INIに登録されている色選択
/// </summary>
/// <param name="form"></param>
public static void SelectIniColor(Form form, string key, Color defaultColor)
{
var colorHex = IniHelper.ReadValue(null, form.Name, key, ColorTranslator.ToHtml(defaultColor));
var color = ColorTranslator.FromHtml(colorHex);
using (ColorDialog cd = new ColorDialog())
{
// 今の色を初期選択にしておく
cd.Color = color;
if (cd.ShowDialog() == DialogResult.OK)
{
// 2. 🔥 Colorを16進数(#RRGGBB)に変換してINIに書き込み
colorHex = ColorTranslator.ToHtml(cd.Color);
IniHelper.WriteValue(null, form.Name, key, colorHex);
}
}
}
/// <summary>
/// INIに設定されている色取得
/// </summary>
/// <param name="form"></param>
/// <param name="key"></param>
/// <param name="defaultColor"></param>
/// <returns></returns>
public static Color GetIniColor(Form form, string key, Color defaultColor)
{
var colorHex = IniHelper.ReadValue(null, form.Name, key, ColorTranslator.ToHtml(defaultColor));
return ColorTranslator.FromHtml(colorHex);
}
/// <summary>
/// チェックボックスのメニュー項目のチェック値のロード
/// </summary>
/// <param name="frm"></param>
/// <param name="menuItem"></param>
public static void MenuCheckBoxItemLoad(Form frm, ToolStripMenuItem menuItem)
{
menuItem.Checked =
//bool.TryParse(
// IniHelper.ReadValue(
// null, frm.Name, menuItem.Name, false.ToString()),
// out var boolVal) ? boolVal : false;
IniHelper.ReadBoolValue(null, frm.Name, menuItem.Name, false);
}
public static void LoadAllMenuStates(Form form, ContextMenuStrip contextMenu)
{
foreach (ToolStripItem item in contextMenu.Items)
ProcessMenuItemLoad(form, item);
}
private static void ProcessMenuItemLoad(Form form, ToolStripItem item)
{
// ToolStripMenuItem かつ CheckOnClick が true の場合のみ処理
if (item is ToolStripMenuItem menuItem && menuItem.CheckOnClick)
{
// 🚀 ご提示のヘルパーメソッドを1行呼び出すだけ!
ContextMenuHelper.MenuCheckBoxItemLoad(form, menuItem);
}
// 子メニュー(階層)がある場合は再帰的に奥まで処理
if (item is ToolStripDropDownItem dropDownItem && dropDownItem.HasDropDownItems)
{
foreach (ToolStripItem subItem in dropDownItem.DropDownItems)
ProcessMenuItemLoad(form, subItem);
}
}
/// <summary>
/// メニューのチェックボックスアイテムのクリック時
/// </summary>
/// <param name="frm"></param>
/// <param name="menuItem"></param>
public static void MenuCheckBoxItemClick(Form frm, ToolStripMenuItem menuItem)
{
menuItem.Checked = !menuItem.Checked;
IniHelper.WriteValue(null, frm.Name, menuItem.Name, menuItem.Checked.ToString());
}
/// <summary>
/// メニューのフォント設定
/// ※フォームロードでCallしてください
/// </summary>
/// <param name="form"></param>
/// <param name="menu"></param>
public static void SetFont(Form form, ContextMenuStrip menu)
{
menu.Font = FontUxer.GetFont(form.Name, menu.Name + ".Font", menu.Font);
}
/// <summary>
/// コントロール(ラベル等)のフォント設定
/// ※フォームロードでCallしてください
/// </summary>
/// <param name="form"></param>
/// <param name="menu"></param>
public static void SetControlFont(Form form, Control control)
{
control.Font = FontUxer.GetFont(form.Name, control.Name + ".Font", control.Font);
}
/// <summary>
/// メニュー自身のフォント選択
/// </summary>
/// <param name="form"></param>
/// <param name="menu"></param>
public static void SelectMenuFont(Form form, ContextMenuStrip menu)
{
if (FontUxer.SelectFont(form, form.Name, menu.Name + ".Font", menu.Font, out var font))
menu.Font = font;
}
/// <summary>
/// コントロール(ラベル等)のフォント選択
/// </summary>
/// <param name="form"></param>
/// <param name="control"></param>
public static void SelectControlFont(Form form, Control control)
{
if (FontUxer.SelectFont(form, form.Name, control.Name + ".Font", control.Font, out var font))
control.Font = font;
}
/// <summary>
/// フォームのタイトル設定
/// </summary>
/// <param name="form"></param>
public static void SetFormTitle(Form form)
{
var title = IniHelper.ReadValue(null, form.Name, INI_KEY_TITLE, form.Text);
using (var dlg = new TextInputForm(title))
{
if (dlg.ShowDialog() == DialogResult.Cancel) return;
IniHelper.WriteValue(null, form.Name, INI_KEY_TITLE, dlg.EditedText);
form.Text = IniHelper.ReadValue(null, form.Name, INI_KEY_TITLE, form.Text);
}
}
/// <summary>
/// バージョン表示
/// </summary>
/// <param name="menuItem"></param>
public static void DispVersion(ToolStripMenuItem menuItem, bool isDispCraftedBy = true)
{
// バージョン
menuItem.Font = new Font(menuItem.Font.FontFamily, 8.0f);
menuItem.Enabled = false;
menuItem.Text = "Ver." + Application.ProductVersion + (isDispCraftedBy ? " | Crafted by のぼぼ工房" : "");
}
/// <summary>
/// ショートカットキーで動作するようにする
/// ※フォームのKeyPreviewをtrueにして、
///  フォームのKeyDownイベントでCallしてください。
///  private void Form1_KeyDown(object sender, KeyEventArgs e)
//  {
//   // メニューのEnabledを制御している場合、そのOpeningを呼んでおく。
//   contextMenuStrip1_Opening(contextMenuStrip1, new System.ComponentModel.CancelEventArgs());
//
//   if (ExecuteShortcutWithEnabledCheck(contextMenuStrip1.Items, e.KeyData))
//   {
//   e.Handled = true;
//   }
//  }
/// </summary>
/// <param name="items"></param>
/// <param name="keyData"></param>
/// <returns></returns>
public static bool ExecuteShortcutWithEnabledCheck(ToolStripItemCollection items, Keys keyData)
{
foreach (ToolStripItem item in items)
{
if (item is ToolStripMenuItem menuItem)
{
// ショートカットが一致し、かつ「有効(Enabled)」な時だけ実行!
if (menuItem.ShortcutKeys == keyData && menuItem.Enabled)
{
menuItem.PerformClick();
return true;
}
if (menuItem.HasDropDownItems)
{
if (ExecuteShortcutWithEnabledCheck(menuItem.DropDownItems, keyData)) return true;
}
}
}
return false;
}
/// <summary>
/// コンボメニューの選択値をINIに保存
/// ToolStripComboBoxのSelectedIndexChangedでCallしてね!💖)
/// </summary>
/// <param name="form"></param>
/// <param name="combo"></param>
public static void SaveComboMenuToIni(Form form, ToolStripComboBox combo)
{
IniHelper.WriteValue(null, form.Name, combo.Name + ".Values", combo.Text);
}
/// <summary>
/// コンボメニューの選択値をINIから復元
/// FormのLoadでCallしてね💖)
/// </summary>
/// <param name="form"></param>
/// <param name="combo"></param>
/// <param name="defaultValue"></param>
public static void LoadComboMenuFromIni(Form form, ToolStripComboBox combo, string defaultValue)
{
combo.Text = IniHelper.ReadValue(null, form.Name, combo.Name + ".Values", defaultValue);
}
/// <summary>
/// コンボメニューの選択値をINIから取得
/// </summary>
/// <param name="form"></param>
/// <param name="combo"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string ComboMenuFromIni(Form form, ToolStripComboBox combo, string defaultValue)
{
return IniHelper.ReadValue(null, form.Name, combo.Name + ".Values", defaultValue);
}
/// <summary>
/// フォームガチャ
/// </summary>
/// <param name="form"></param>
/// <returns></returns>
public static async Task FormGacha(Form form)
{
// 現在の状態をバックアップ
var originalState = form.Controls.Cast<Control>()
.Select(c => new { Ctrl = c, Loc = c.Location, Txt = c.Text, Font = c.Font }).ToList();
var formLoc = form.Location;
Random rng = new Random();
// 5秒間の狂宴(癒し)
for (int i = 0; i < 100; i++)
{
// 1. フォーム自体が震える
form.Location = new Point(formLoc.X + rng.Next(-20, 21), formLoc.Y + rng.Next(-20, 21));
foreach (var item in originalState)
{
// 2. コントロールがバラバラに踊る
item.Ctrl.Location = new Point(item.Loc.X + rng.Next(-15, 16), item.Loc.Y + rng.Next(-15, 16));
// 3. ラベルが叫び、ボタンが点滅する
if (item.Ctrl is System.Windows.Forms.Label) item.Ctrl.Text = "がちゃ!";
item.Ctrl.BackColor = Color.FromArgb(rng.Next(256), rng.Next(256), rng.Next(256));
}
// 4. マウスカーソルを中央に拘束(逃がさない)
Cursor.Position = form.PointToScreen(new Point(form.Width / 2, form.Height / 2));
await Task.Delay(30);
}
// 祭りのあと(完全復旧)
form.Location = formLoc;
foreach (var item in originalState)
{
item.Ctrl.Location = item.Loc;
item.Ctrl.Text = item.Txt;
item.Ctrl.Font = item.Font;
item.Ctrl.BackColor = SystemColors.Control;
}
}
}
}
+79
View File
@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Forms.Controls
{
public class PoiDgv : DataGridView
{
private IContainer components;
[Category("Poi拡張"), Description("共通メニューを自動で追加するかどうか")]
public bool EnablePoiMenu { get; set; } = true;
/// <summary>
/// コンストラクタ
/// </summary>
public PoiDgv()
{
// これが今回の本命!
this.DoubleBuffered = true;
// DGB初期設定
this.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
this.RowHeadersVisible = false;
this.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.AllowUserToAddRows = false;
this.AllowUserToDeleteRows = false;
this.AllowUserToOrderColumns = true;
this.AllowUserToResizeColumns = true;
this.AllowUserToResizeRows = false;
this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
}
/// <summary>
/// コンテキストメニュー設定時
/// </summary>
/// <param name="e"></param>
protected override void OnContextMenuStripChanged(EventArgs e)
{
base.OnContextMenuStripChanged(e);
// ユーザーがデザイナーでセットしたメニューに「Poi」のスパイスを加える
if (EnablePoiMenu && this.ContextMenuStrip != null)
{
var menu = this.ContextMenuStrip;
//// 重複防止チェック
//if (menu.Items.Find("poiItem_AutoFit", true).Length == 0)
//{
// if (menu.Items.Count > 0) menu.Items.Add(new ToolStripSeparator());
// var fitItem = new ToolStripMenuItem("列幅をぽいっと自動調整");
// fitItem.Name = "poiItem_AutoFit";
// fitItem.Click += (s, ev) => this.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
// menu.Items.Add(fitItem);
//}
}
}
private void InitializeComponent()
{
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
this.SuspendLayout();
//
// PoiDgv
//
this.RowTemplate.Height = 21;
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
this.ResumeLayout(false);
}
}
}
+123
View File
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</metadata>
</root>
+588
View File
@@ -0,0 +1,588 @@
using DocumentFormat.OpenXml.VariantTypes;
using KssSmaPlaLib.Ini;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Windows.Media.Streaming.Adaptive;
namespace KssSmaPlaLib.Forms.Controls
{
/// <summary>
/// Poiメインフォーム
/// </summary>
public class PoiMainForm : Form
{
protected Label TitleLabel;
protected PoiDgv MainDgv;
protected ContextMenuStrip MainContextMenu;
protected ToolStripMenuItem TitleVisibleCheckMenu;
private ToolStripMenuItem _versionMenu;
private NumericUpDown _titleLabelYohakuHorizonNumeric = new NumericUpDown { Width = 60 };
private NumericUpDown _titleLabelYohakuVarticalNumeric = new NumericUpDown { Width = 60 };
// 👇遅延書き込みしようかと思ったがやめた!
//private Timer _saveDelayTimer = new Timer { Interval = 1000 };
private string _title = string.Empty;
/// <summary>
/// コンストラクタ
/// </summary>
public PoiMainForm(string title = "", string name = "")
{
// Name
this.Name = string.IsNullOrEmpty(name) ? this.GetType().Name : name;
// タイトル
_title = string.IsNullOrEmpty(title) ? this.Name : title;
this.Text = _title;
// フォームイベント
this.Load += PoiMainForm_Load;
this.FormClosing += PoiMainForm_FormClosing;
// コントロールの生成と配置
TitleLabel = new Label
{
Name = "TitleLabel",
AutoSize = true,
Dock = DockStyle.Top,
Text = "サンプルです💖",
};
TitleLabel.Padding = new Padding(20, 5, 8, 20);
MainDgv = new PoiDgv
{
Name = "MainDgv",
Dock = DockStyle.Fill
};
MainContextMenu = new ContextMenuStrip
{
Name = "MainContextMenu",
};
this.ContextMenuStrip = MainContextMenu;
this.Controls.Add(MainDgv);
this.Controls.Add(TitleLabel);
// デフォルトのメニュー項目登録
CreateDefaultMenu();
DgvHelper.DgvLoadFontFromIni(MainDgv);
//ContextMenuHelper.MenuCheckBoxItemLoad(this, TitleVisibleCheckMenu);
TitleLabel.Visible = TitleVisibleCheckMenu.Checked;
ContextMenuHelper.SetControlFont(this, TitleLabel);
ContextMenuHelper.DispVersion(_versionMenu);
// ソート無効
foreach (DataGridViewColumn column in MainDgv.Columns) column.SortMode = DataGridViewColumnSortMode.NotSortable;
//// 日の列はセンタリング
//for (var day = 1; day <= 31; day++) MainDgv.Columns[$"ColDay{day}"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
// TOTAL列は右寄せ
//MainDgv.Columns["ColTotal"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
// ヘッダ行のデザインはOSのデザインを反映させる機能を解除
MainDgv.EnableHeadersVisualStyles = false;
// 👇やろうかと思ったけどやめた!
//// 遅延書き込みタイマー
//_saveDelayTimer.Tick += (s, e) =>
//{
// _saveDelayTimer.Stop(); // タイマーを止める
// // 👑 ここでINIファイルへの書き込みを実行!
// // スピンボタン連打が「止まってから1秒後」に1回だけ綺麗に保存されます。
// aaaaaaa
//};
//LoadDataAsync();
// タイトル文字列設定
//TitleLabel.Text = GetTitle();
}
/// <summary>
/// フォームロード時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <exception cref="NotImplementedException"></exception>
private void PoiMainForm_Load(object sender, EventArgs e)
{
FormHelper.LoadFormBounds(this);
DgvHelper.DgvLoadFontFromIni(MainDgv);
DgvHelper.DgvLoadColWidth(MainDgv);
DgvHelper.DgvLoadHeaderHeight(MainDgv);
DgvHelper.DgvLoadColVisible(MainDgv);
DgvHelper.DgvLoadColDisplayIndex(MainDgv);
DgvHelper.DgvLoadColFrozen(MainDgv);
DgvHelper.DgvSetHeaderBackColorFromIni(this, MainDgv);
//DgvHelper.DgvSetHeaderBackColorFromIniWithNameMatch(this, MainDgv, "ColDay*", INI_KEY_HEADER_DAY_COLUMN_BACK_COLOR);
// 👇これはLoadでやらないと、子で作ってるメニューアイテムに反映されない!
ContextMenuHelper.LoadAllMenuStates(this, MainContextMenu);
ContextMenuHelper.SetFont(this, MainContextMenu);
var vertical =
int.TryParse(
IniHelper.ReadValue(null, this.Name, _titleLabelYohakuVarticalNumeric.Name, "0"),
out var intVal) ? intVal : 0;
var horizon =
int.TryParse(
IniHelper.ReadValue(null, this.Name, _titleLabelYohakuHorizonNumeric.Name, "0"),
out intVal) ? intVal : 0;
TitleLabel.Padding = new Padding(horizon, vertical, horizon, vertical);
}
/// <summary>
/// フォーム閉じるとき
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <exception cref="NotImplementedException"></exception>
private void PoiMainForm_FormClosing(object sender, FormClosingEventArgs e)
{
FormHelper.SaveFormBounds(this);
DgvHelper.DgvSaveFontToIni(MainDgv);
DgvHelper.DgvSaveColWidth(MainDgv);
DgvHelper.DgvSaveHeaderHeight(MainDgv);
DgvHelper.DgvSaveColVisible(MainDgv);
DgvHelper.DgvSaveColDisplayIndex(MainDgv);
DgvHelper.DgvSaveColFrozen(MainDgv);
IniHelper.WriteValue(
null, this.Name,
_titleLabelYohakuHorizonNumeric.Name,
_titleLabelYohakuHorizonNumeric.Value.ToString());
IniHelper.WriteValue(
null, this.Name,
_titleLabelYohakuVarticalNumeric.Name,
_titleLabelYohakuVarticalNumeric.Value.ToString());
}
/// <summary>
/// デフォルトのメニュー項目(表示設定など)を作成
/// </summary>
private void CreateDefaultMenu()
{
// 仕切り線
MainContextMenu.Items.Add(new ToolStripSeparator());
// 表示設定(親)
var hyojiSetteiMenu = new ToolStripMenuItem()
{
Name = "HyojiSetteiMenu",
Text = "表示設定",
};
MainContextMenu.Items.Add(hyojiSetteiMenu);
// メニューのフォント(クリック動作)
var menuFontMenu = new ToolStripMenuItem()
{
Name = "MenuFontMenu",
Text = "メニューのフォント...",
};
menuFontMenu.Click += (s, e)=>
{
ContextMenuHelper.SelectMenuFont(this, MainContextMenu);
};
hyojiSetteiMenu.DropDownItems.Add(menuFontMenu);
// グリッドメニュー(親)
var gridMenu = new ToolStripMenuItem()
{
Name = "GridMenu",
Text = "グリッド",
};
hyojiSetteiMenu.DropDownItems.Add(gridMenu);
// グリッドフォントメニュー(クリック動作)
var gridFontMenu = new ToolStripMenuItem()
{
Name = "GridFontMenu",
Text = "フォント...",
};
gridFontMenu.Click += (s, e) =>
{
DgvHelper.DgvSelectFont(this, MainDgv);
};
gridMenu.DropDownItems.Add(gridFontMenu);
// グリッド列非表示メニュー(クリック動作)
var gridColumnDisabledMenu = new ToolStripMenuItem()
{
Name = "GridColumnDisabledMenu",
Text = "この列を非表示にする",
};
gridColumnDisabledMenu.Click += (s, e) =>
{
if (MainDgv.CurrentCell is null) return;
MainDgv.Columns[MainDgv.CurrentCell.ColumnIndex].Visible = false;
};
gridMenu.DropDownItems.Add(gridColumnDisabledMenu);
// グリッド列再表示メニュー(クリック動作)
var gridColumnRedispMenu = new ToolStripMenuItem()
{
Name = "GridColumnRedispMenu",
Text = "列の再表示",
};
gridColumnRedispMenu.Click += (s, e) =>
{
DgvHelper.DgvRedispAllColumn(MainDgv);
};
gridMenu.DropDownItems.Add(gridColumnRedispMenu);
// グリッド列幅自動調整メニュー(クリック動作)
var columnWidthAutoAdjustMenu = new ToolStripMenuItem()
{
Name = "ColumnWidthAutoAdjustMenu",
Text = "列幅の自動調整",
};
columnWidthAutoAdjustMenu.Click += (s, e) =>
{
DgvHelper.DgvColumnWidthAutoAdjust(MainDgv);
};
gridMenu.DropDownItems.Add(columnWidthAutoAdjustMenu);
// グリッド列固定メニュー(クリック動作)
var gridColumnFixMenu = new ToolStripMenuItem()
{
Name = "GridColumnFixMenu",
Text = "列固定",
};
gridColumnFixMenu.Click += (s, e) =>
{
DgvHelper.DgvColumnFix(MainDgv);
};
gridMenu.DropDownItems.Add(gridColumnFixMenu);
// グリッド列固定解除メニュー(クリック動作)
var gridColumnFixKaijoMenu = new ToolStripMenuItem()
{
Name = "GridColumnFixKaijoMenu",
Text = "列固定解除",
};
gridColumnFixKaijoMenu.Click += (s, e) =>
{
DgvHelper.DgvColumnFixKaijo(MainDgv);
};
gridMenu.DropDownItems.Add(gridColumnFixKaijoMenu);
// グリッドのヘッダ(親)
//this.GridHeaderMenu});
var gridHeaderMenu = new ToolStripMenuItem()
{
Name = "GridHeaderMenu",
Text = "ヘッダ",
};
gridMenu.DropDownItems.Add(gridHeaderMenu);
// グリッドヘッダ背景色(クリック動作)
var gridHeaderBackColorMenu = new ToolStripMenuItem()
{
Name = "GridHeaderBackColorMenu",
Text = "ヘッダ背景色...",
};
gridHeaderBackColorMenu.Click += (s, e) =>
{
DgvHelper.DgvSelectHeaderBackColor(this, MainDgv);
};
gridHeaderMenu.DropDownItems.Add(gridHeaderBackColorMenu);
// グリッドヘッダの日の背景色(クリック動作)
var gridHeaderDayBackColorMenu = new ToolStripMenuItem()
{
Name = "GridHeaderDayBackColorMenu",
Text = "日の背景色...",
Enabled = false, // デフォルトは非活性
};
gridHeaderDayBackColorMenu.Click += (s, e) =>
{
DgvHelper.DgvSelectHeaderBackColorWithNameMatch(this, MainDgv, "ColDay*", gridHeaderDayBackColorMenu.Name);
};
gridHeaderMenu.DropDownItems.Add(gridHeaderDayBackColorMenu);
// グリッドヘッダの非稼働日の背景色(クリック動作)
var gridHeaderHikadobiBackColorMenu = new ToolStripMenuItem()
{
Name = "GridHeaderHikadobiBackColorMenu",
Text = "非稼働日の背景色...",
Enabled = false, // デフォルトは非活性
};
gridHeaderHikadobiBackColorMenu.Click += (s, e) =>
{
// Comming soon!
MessageBox.Show(this,"カミングスーン!",this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
};
gridHeaderMenu.DropDownItems.Add(gridHeaderHikadobiBackColorMenu);
//this.GridHeaderMenu.DropDownItems.AddRange(
// new System.Windows.Forms.ToolStripItem[] {
//this.,
//this.,
//this.});
// グリッドメニューを開くときの制御
gridMenu.DropDownOpening += (s, e) =>
{
// 「この列の非表示」はアクティブセルがあるときだけ有効
gridColumnDisabledMenu.Enabled = !(MainDgv.CurrentCell is null);
// 「列の再表示」は非表示列があるときだけ有効
gridColumnRedispMenu.Enabled =
MainDgv.Columns.GetColumnCount(DataGridViewElementStates.Visible)
!= MainDgv.Columns.Count;
// 「列固定」はアクティブセルがあるときだけ有効
gridColumnFixMenu.Enabled = !(MainDgv.CurrentCell is null);
// 「列固定解除」は列固定がされているときだけ有効
gridColumnFixKaijoMenu.Enabled = MainDgv.Columns
.Cast<DataGridViewColumn>()
.Any(c => c.Frozen);
};
// タイトル(親)
var titleMenu =
new ToolStripMenuItem()
{
Name = "TitleMenu",
Text = "タイトル",
};
hyojiSetteiMenu.DropDownItems.Add(titleMenu);
// タイトル表示(チェックボックス)
TitleVisibleCheckMenu =
new ToolStripMenuItem()
{
Name = "TitleVisibleCheckMenu",
Text = "タイトル表示?",
CheckOnClick = true,
};
TitleVisibleCheckMenu.CheckedChanged += (s, e) =>
{
var mi = (ToolStripMenuItem)s;
IniHelper.WriteBoolValue(null, this.Name, mi.Name,
mi.Checked);
TitleLabel.Visible = mi.Checked;
};
titleMenu.DropDownItems.Add(TitleVisibleCheckMenu);
// タイトルフォントメニュー(クリック動作)
var titleFontMenu =
new ToolStripMenuItem()
{
Name = "TitleFontMenu",
Text = "フォント...",
};
titleFontMenu.Click += (s, e) =>
{
ContextMenuHelper.SelectControlFont(this, TitleLabel);
};
titleMenu.DropDownItems.Add(titleFontMenu);
// タイトル余白(親)
var titleYohakuMenu = new ToolStripMenuItem()
{
Name = "TitleYohakuMenu",
Text = "余白",
};
titleMenu.DropDownItems.Add(titleYohakuMenu);
// 余白設定パネル
titleYohakuMenu.DropDownItems.Add(CreateYohakuPanelMenu());
// 仕切り線
MainContextMenu.Items.Add(new ToolStripSeparator());
// バージョン表示メニュー(表示のみ)
_versionMenu =
new ToolStripMenuItem()
{
Name = "VersionMenu",
Text = "バージョン情報",
};
MainContextMenu.Items.Add(_versionMenu);
//titleMenu.DropDownItems.Add(CreateYohakuPanelMenu());
//MainContextMenu.Items.Add(CreateYohakuPanelMenu());
// 実験!✨✨✨
//// NumericUpDownを生成して設定
//NumericUpDown numericUpDown = new NumericUpDown();
//numericUpDown.Minimum = 0;
//numericUpDown.Maximum = 100;
//numericUpDown.Value = 10;
//numericUpDown.Width = 60; // メニュー内で邪魔にならない幅に調整
//// ToolStripControlHostでラップしてメニューに追加
//ToolStripControlHost host = new ToolStripControlHost(numericUpDown);
//MainContextMenu.Items.Add(host); // または menuStrip1.Items.Add(host);
}
/// <summary>
/// 余白調整パネルメニュー作成
/// </summary>
/// <returns></returns>
private ToolStripControlHost CreateYohakuPanelMenu()
{
// 1. 土台となるパネル(縦方向にコントロールを並べる)
TableLayoutPanel miniDialog = new TableLayoutPanel();
miniDialog.ColumnCount = 2; // 2列のグリッド
miniDialog.RowCount = 2; // 3; // 3行
miniDialog.AutoSize = true;
miniDialog.Padding = new Padding(10); // 周囲に余白を作ってダイアログ感を出す
miniDialog.BackColor = Color.FromArgb(240, 240, 240); // ほんのり背景色を変える
// 2. コントロール達を作成
Label lblX = new Label { Text = "横余白:", AutoSize = true, Anchor = AnchorStyles.Left };
_titleLabelYohakuHorizonNumeric = new NumericUpDown
{
Name = "TitleLabelYohakuHorizonNumeric",
Width = 60,
TextAlign = HorizontalAlignment.Right,
};
_titleLabelYohakuHorizonNumeric.ValueChanged += (sender, e) =>
{
TitleLabel.Padding = new Padding(
(int)_titleLabelYohakuHorizonNumeric.Value,
TitleLabel.Padding.Top,
(int)_titleLabelYohakuHorizonNumeric.Value,
TitleLabel.Padding.Bottom);
// 🔥🌊INI書きはFormClosingで行う!
};
Label lblY = new Label { Text = "縦余白:", AutoSize = true, Anchor = AnchorStyles.Left };
_titleLabelYohakuVarticalNumeric = new NumericUpDown
{
Name = "TitleLabelYohakuVarticalNumeric",
Width = 60,
TextAlign = HorizontalAlignment.Right,
};
_titleLabelYohakuVarticalNumeric.ValueChanged += (sender, e) =>
{
TitleLabel.Padding = new Padding(
TitleLabel.Padding.Left,
(int)_titleLabelYohakuVarticalNumeric.Value,
TitleLabel.Padding.Right,
(int)_titleLabelYohakuVarticalNumeric.Value);
// 🔥🌊INI書きはFormClosingで行う!
};
//CheckBox chkAuto = new CheckBox { Text = "自動調整", AutoSize = true };
// 3. グリッドパネルに綺麗に配置
miniDialog.Controls.Add(lblX, 0, 0);
miniDialog.Controls.Add(_titleLabelYohakuHorizonNumeric, 1, 0);
miniDialog.Controls.Add(lblY, 0, 1);
miniDialog.Controls.Add(_titleLabelYohakuVarticalNumeric, 1, 1);
//// チェックボックスは2列分ぶち抜きで配置
//miniDialog.Controls.Add(chkAuto, 0, 2);
//miniDialog.SetColumnSpan(chkAuto, 2);
// 4. メニューにホストする
//ToolStripControlHost dialogHost = new ToolStripControlHost(miniDialog);
//MainContextMenu.Items.Add(dialogHost);
// 開くときの処理
var tssh = new ToolStripControlHost(miniDialog);
tssh.OwnerChanged += (sender, e) =>
{
// 親となるメニュー(ToolStripDropDown)を取得
if (tssh.Owner is ToolStripDropDown parentMenu)
{
// 親の「開く直前イベント」に、自分のメソッドをこっそり登録する!
parentMenu.Opening -= ParentMenu_Opening; // 二重登録防止
parentMenu.Opening += ParentMenu_Opening;
}
};
return tssh;
}
/// <summary>
/// 親メニュー開くときに追加する処理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ParentMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
//// フォントを親に合わせる(階層深いと反映されないため)
//_titleLabelYohakuHorizonNumeric.Font =
// _titleLabelYohakuVarticalNumeric.Font =
// MainContextMenu.Font;
// パネルの合わせ、再レイアウト(パネルが階層奥深くだと、なぜか反映されていなかったりする)
var parent = _titleLabelYohakuHorizonNumeric.Parent;
if (parent != null)
{
parent.Font = MainContextMenu.Font;
parent.PerformLayout();
}
// タイトルラベルの現在の余白をNumericUpDownに設定
_titleLabelYohakuHorizonNumeric.Value = TitleLabel.Padding.Left;
_titleLabelYohakuVarticalNumeric.Value = TitleLabel.Padding.Top;
}
/// <summary>
/// メニュー項目追加
/// </summary>
/// <param name="text"></param>
/// <param name="name"></param>
/// <param name="defaultValue"></param>
/// <param name="onCheckedChanged"></param>
/// <returns></returns>
protected ToolStripMenuItem AddCheckMenuItem(
int index,
string text,
string name,
bool defaultValue,
Action<bool> onCheckedChanged = null)
{
var item = new ToolStripMenuItem(text);
// チェックボックスとして機能する
item.CheckOnClick = true;
item.Name = name;
// 3. CheckedChanged イベントをここで一括で仕込む!
item.CheckedChanged += (sender, e) =>
{
var mi = (ToolStripMenuItem)sender;
// チェック値をINI保存
IniHelper.WriteBoolValue(null, this.Name, mi.Name, mi.Checked);
// イベントプロシージャ(あるとき)
onCheckedChanged?.Invoke(mi.Checked);
};
MainContextMenu.Items.Insert(index, item);
return item;
}
public enum PoiAlign
{
Left,
Right,
Center,
}
private DataGridViewContentAlignment GetDgvAlign(PoiAlign align)
{
switch (align)
{
case PoiAlign.Left: return DataGridViewContentAlignment.MiddleLeft;
case PoiAlign.Center: return DataGridViewContentAlignment.MiddleCenter;
case PoiAlign.Right: return DataGridViewContentAlignment.MiddleRight;
default: return DataGridViewContentAlignment.MiddleLeft;
}
}
/// <summary>
/// 列追加
/// </summary>
/// <param name="name"></param>
/// <param name="text"></param>
/// <param name="align"></param>
protected void AddColumn(string name, string text, PoiAlign align = PoiAlign.Left)
{
var col = new DataGridViewTextBoxColumn()
{
Name = name,
HeaderText = text,
ReadOnly = true,
};
col.DefaultCellStyle.Alignment = GetDgvAlign(align);
MainDgv.Columns.Add(col);
}
}
}
+172
View File
@@ -0,0 +1,172 @@
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Forms
{
public static class DataGridViewExporter
{
/// <summary>
/// DataGridView の「可視列・可視行のみ」を Excel へエクスポートします。
/// 列順は DisplayIndex 順/ヘッダー付き/自動調整/簡易罫線付き。
/// </summary>
public static void ExportVisibleToExcel(
DataGridView dgv,
string filePath,
string sheetName = "Export")
{
if (dgv == null) throw new ArgumentNullException(nameof(dgv));
if (string.IsNullOrWhiteSpace(filePath)) throw new ArgumentException("filePath is required.", nameof(filePath));
// 可視列のみ、DisplayIndex順に並べ替え
var visibleCols = dgv.Columns
.Cast<DataGridViewColumn>()
.Where(c => c.Visible)
.OrderBy(c => c.DisplayIndex)
.ToList();
// 可視行のみ(新規行除外)
var visibleRows = dgv.Rows
.Cast<DataGridViewRow>()
.Where(r => r.Visible && !r.IsNewRow)
.ToList();
using (var wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(string.IsNullOrWhiteSpace(sheetName) ? "Sheet1" : sheetName);
int row = 1;
int col = 1;
// ヘッダー行
foreach (var c in visibleCols)
{
ws.Cell(row, col).Value = c.HeaderText ?? c.Name;
// すこし見やすく
ws.Cell(row, col).Style.Font.Bold = true;
ws.Cell(row, col).Style.Fill.BackgroundColor = XLColor.LightGray;
ws.Cell(row, col).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
col++;
}
// データ行
row = 2;
foreach (var r in visibleRows)
{
col = 1;
foreach (var c in visibleCols)
{
var cell = r.Cells[c.Index];
var val = cell.Value;
if (val == null || val == DBNull.Value)
{
ws.Cell(row, col).Clear(); // 空セル(文字列""よりこちらが自然)
}
else
{
// ValueType を優先し、なければ実オブジェクトの型で判定
var vt = cell.ValueType ?? val.GetType();
if (vt == typeof(int) || vt == typeof(long) || vt == typeof(short) || vt == typeof(byte))
{
ws.Cell(row, col).Value = Convert.ToInt64(val); // 長整数に寄せると安全
// 必要なら桁区切りなど: ws.Cell(row, col).Style.NumberFormat.Format = "#,##0";
}
else if (vt == typeof(decimal))
{
ws.Cell(row, col).Value = Convert.ToDecimal(val);
// 書式例: ws.Cell(row, col).Style.NumberFormat.Format = "#,##0.####";
}
else if (vt == typeof(double) || vt == typeof(float))
{
ws.Cell(row, col).Value = Convert.ToDouble(val);
}
else if (vt == typeof(DateTime))
{
ws.Cell(row, col).Value = Convert.ToDateTime(val);
// 例: ws.Cell(row, col).Style.DateFormat.Format = "yyyy-mm-dd hh:mm";
}
else if (vt == typeof(TimeSpan))
{
// Excelは TimeSpan を日数として扱うので適宜書式を
var ts = (TimeSpan)val;
ws.Cell(row, col).Value = ts;
ws.Cell(row, col).Style.NumberFormat.Format = "[h]:mm:ss";
}
else if (vt == typeof(bool))
{
ws.Cell(row, col).Value = Convert.ToBoolean(val);
}
else
{
// それ以外は文字列にフォールバック(トリム等はお好みで)
ws.Cell(row, col).Value = val.ToString();
}
}
col++;
}
row++;
}
//// データ行
//row = 2;
//foreach (var r in visibleRows)
//{
// col = 1;
// foreach (var c in visibleCols)
// {
// object val = r.Cells[c.Index].Value;
// // Excel側でよく見えるように値をそのままセット
// ws.Cell(row, col).Value = val == null ? string.Empty : val.ToString();
// col++;
// }
// row++;
//}
// テーブルっぽく罫線&自動調整
var lastRow = row - 1;
var lastCol = visibleCols.Count;
if (lastCol > 0 && lastRow > 0)
{
var rng = ws.Range(1, 1, lastRow, lastCol);
rng.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
rng.Style.Border.InsideBorder = XLBorderStyleValues.Thin;
rng.SetAutoFilter(); // フィルターもあると便利
ws.Columns(1, lastCol).AdjustToContents();
}
// 保存
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
wb.SaveAs(filePath);
}
}
/// <summary>
/// SaveFileDialog 付きの簡便版。UIからサクッと呼び出す用。
/// </summary>
public static void ExportVisibleToExcelWithDialog(DataGridView dgv, string defaultFileName = "export.xlsx")
{
using (var sfd = new SaveFileDialog()
{
Filter = "Excel Workbook (*.xlsx)|*.xlsx",
FileName = defaultFileName,
OverwritePrompt = true,
AddExtension = true
})
{
if (sfd.ShowDialog() == DialogResult.OK)
{
ExportVisibleToExcel(dgv, sfd.FileName);
MessageBox.Show("Excelにエクスポートしました。", "完了", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
}
+58
View File
@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Forms
{
public static class DatePickerHelper
{
public static DateTime? ShowDateDialog(
DateTime? defaultDate = null,
string title = "日付を選択してください")
{
// 1. その場限りのフォームを作成
using (Form form = new Form())
{
DateTimePicker dtp = new DateTimePicker();
Button btnOk = new Button();
// フォームの設定
form.Text = title;
form.Size = new System.Drawing.Size(240, 120);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterParent;
form.MaximizeBox = false;
form.MinimizeBox = false;
// DateTimePickerの設定
dtp.Location = new System.Drawing.Point(10, 10);
dtp.Size = new System.Drawing.Size(200, 20);
dtp.Format = DateTimePickerFormat.Short;
// ★ ここで初期値をセット!
// 引数がnullなら今日の値を、あればその値をセットします。
dtp.Value = defaultDate ?? DateTime.Today;
// OKボタンの設定
btnOk.Text = "OK";
btnOk.DialogResult = DialogResult.OK; // これを押すとフォームが閉じる
btnOk.Location = new System.Drawing.Point(135, 45);
form.AcceptButton = btnOk; // EnterキーでOK
// コントロールを追加
form.Controls.Add(dtp);
form.Controls.Add(btnOk);
// 2. ダイアログとして表示
if (form.ShowDialog() == DialogResult.OK)
{
return dtp.Value; // 選択された日付を返す
}
}
return null; // キャンセルされた場合
}
}
}
+726
View File
@@ -0,0 +1,726 @@
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.Forms.ContextMenuFunction;
using KssSmaPlaLib.Ini;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Forms
{
public class DgvHelper
{
/// <summary>
/// 汎用的な初期化
/// </summary>
/// <param name="dgv"></param>
public static void Initialize(DataGridView dgv)
{
// 行選択
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
// 行ヘッダ消去
dgv.RowHeadersVisible = false;
// 編集不可
dgv.ReadOnly = true;
// ユーザ操作制限
dgv.AllowUserToAddRows = false;
dgv.AllowUserToDeleteRows = false;
dgv.AllowUserToOrderColumns = false;
dgv.AllowUserToResizeColumns = true;
dgv.AllowUserToResizeRows = false;
// 列ヘッダはセンタリング
dgv.ColumnHeadersDefaultCellStyle.Alignment=DataGridViewContentAlignment.MiddleCenter;
//// ソート用余白を消す
//dgv.ColumnHeadersDefaultCellStyle.Padding = new Padding(0);
// セル内余白(上下左右)をゼロに
dgv.DefaultCellStyle.Padding = new Padding(0);
// 行高さの自動調整
dgv.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
// ダブルバッファ(プロパティが隠れている)
var type = typeof(DataGridView);
var prop = type.GetProperty("DoubleBuffered",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
prop.SetValue(dgv, true, null);
}
/// <summary>
/// 列ヘッダのソート用余白を消す
/// ※列が確定してからCallすること
/// </summary>
/// <param name="dgv"></param>
//public static void ClearColumnHeaderSortYohaku(DataGridView dgv)
//{
// // 列ヘッダの幅にソート用の幅は不要
// //foreach (DataGridViewColumn col in dgv.Columns) col.SortMode = DataGridViewColumnSortMode.NotSortable;
// // 何をやってもダメなので、テキストの先頭に余白入れます!👉ダメ!orz
// //const string YOHAKU = "       ";
// //foreach (DataGridViewColumn col in dgv.Columns) col.HeaderText = YOHAKU + col.HeaderText;
//}
// どちらのDTOでも使える共通バインド関数
public static void BindListWithAttributeHeaders<T>(
DataGridView grid,
IList<T> source,
bool isForce = false)
{
// 強制でないとき、データソースありなら何もしない
if (!(grid.DataSource is null) && !isForce) return;
// データバインド完了後にヘッダー等を属性で上書き
grid.DataBindingComplete += (_, __) => ApplyAttributeHeaders<T>(grid);
// 「とりあえず ToString() で文字列表示」したい場合の統一フォーマット
grid.CellFormatting += (_, e) =>
{
try
{
// AutoGenerateColumnsだと各セルの Value はプロパティ値になります
// ここで ToString() 統一(nullは空文字に)
if (e.Value == null) { e.Value = string.Empty; e.FormattingApplied = true; return; }
// 文化依存や日付/数値の既定書式を崩したくなければコメントアウト推奨
if (!(e.Value is bool) &&
string.IsNullOrEmpty(grid.Columns[e.ColumnIndex].DefaultCellStyle.Format))
{
e.Value = e.Value.ToString();
e.FormattingApplied = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
};
grid.AutoGenerateColumns = true;
// 変更通知を効かせたい場合は BindingList に包む
var bindingList = source is BindingList<T> bl ? bl : new BindingList<T>(source);
// BindingSource 経由が安定
var bs = new BindingSource { DataSource = bindingList };
grid.DataSource = bs;
}
private const string KEY_NAME_DISPLAY_NAME_CSV = "DisplayNameCsv";
/// <summary>
/// プライベートな子関数
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="grid"></param>
public static void ApplyAttributeHeaders<T>(DataGridView grid)
{
// 編集した表示名
var csv = IniHelper.ReadValue(null, grid.Parent.Name + "." + grid.Name, KEY_NAME_DISPLAY_NAME_CSV);
var props = TypeDescriptor.GetProperties(typeof(T))
.Cast<PropertyDescriptor>()
.ToDictionary(p => p.Name);
foreach (DataGridViewColumn col in grid.Columns)
{
var key = col.DataPropertyName ?? col.Name;
if (key is null) continue;
if (props.TryGetValue(key, out var pd))
{
// タグに入れておく(PropertyDescriptor型)
col.Tag = pd;
// 列ヘッダーを [DisplayName] に
col.HeaderText = pd.DisplayName;
// 表示名を登録されてたら、置き換える
var editName = StringUxer.GetStringByIndexFormCsv(csv,col.Index,string.Empty);
if (!string.IsNullOrEmpty(editName)) col.HeaderText = editName;
// 文字寄せ
var alignment =
(col.HeaderText.IndexOf("[R]") >= 0 ? DataGridViewContentAlignment.MiddleRight :
(col.HeaderText.IndexOf("[C]") >= 0 ? DataGridViewContentAlignment.MiddleCenter :
DataGridViewContentAlignment.MiddleLeft));
col.DefaultCellStyle.Alignment = alignment;
col.HeaderText = col.HeaderText.Replace("[L]", "").Replace("[C]", "").Replace("[R]", "");
// [Browsable(false)] の列は非表示(AutoGenerateでも列が立つ場合の保険)
var browsableAttr = pd.Attributes.OfType<BrowsableAttribute>().FirstOrDefault();
if (browsableAttr != null && !browsableAttr.Browsable)
{
col.Visible = false;
continue;
}
// 読み取り専用属性の尊重
col.ReadOnly = pd.IsReadOnly;
// 便利系:ソートを自動に
// col.SortMode = DataGridViewColumnSortMode.Automatic;
// 必要なら列幅の初期値
// col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
}
}
private const string INI_KEY_COL_WIDTH_CSV = "ColWidthCsv";
/// <summary>
/// 列幅保存(FormのFormClosingにてCall
/// </summary>
/// <param name="dgv"></param>
public static void DgvSaveColWidth(DataGridView dgv)
{
var section = dgv.Parent.Name + "." + dgv.Name;
var list = new List<int>();
foreach(DataGridViewColumn col in dgv.Columns) list.Add(col.Width);
IniHelper.WriteValue(null, section, INI_KEY_COL_WIDTH_CSV, string.Join(",", list));
}
/// <summary>
/// 列幅復元(FormのコンストラクタにてCall)
/// </summary>
/// <param name="dgv"></param>
public static void DgvLoadColWidth(DataGridView dgv)
{
var section = dgv.Parent.Name + "." + dgv.Name;
var list = IniHelper.ReadValue(null, section,INI_KEY_COL_WIDTH_CSV).Split(',').ToList();
foreach (DataGridViewColumn col in dgv.Columns)
{
if (list.Count - 1 < col.Index) break;
if (!int.TryParse(list[col.Index], out int val)) break;
col.Width = val;
}
}
private const string INI_KEY_FONT_CSV = "Font";
public static void DgvSelectFont(Form form, DataGridView dgv)
{
if (!FontUxer.SelectFont(form, form.Name, dgv.Name + ".Font", dgv.DefaultCellStyle.Font, out var font)) return;
DgvSetFontFromFont(dgv, font);
DgvSaveFontToIni(dgv);
}
public static void DgvSetFontFromFont(DataGridView dgv, Font font)
{
var font2 = new Font(font.Name, font.Size, font.Bold ? FontStyle.Bold : FontStyle.Regular);
dgv.DefaultCellStyle.Font = font2;
dgv.ColumnHeadersDefaultCellStyle.Font = font2;
dgv.AutoResizeRows();
}
public static void DgvSaveFontToIni(DataGridView dgv)
{
var fontCsv =
dgv.ColumnHeadersDefaultCellStyle.Font.Name + "," +
dgv.ColumnHeadersDefaultCellStyle.Font.Size.ToString() + "," +
dgv.ColumnHeadersDefaultCellStyle.Font.Bold.ToString();
IniHelper.WriteValue(null, dgv.Parent.Name + "." + dgv.Name, INI_KEY_FONT_CSV, fontCsv);
}
public static void DgvLoadFontFromIni(DataGridView dgv)
{
var defaultFontCsv =
dgv.ColumnHeadersDefaultCellStyle.Font.Name + "," +
dgv.ColumnHeadersDefaultCellStyle.Font.Size.ToString() + "," +
dgv.ColumnHeadersDefaultCellStyle.Font.Bold.ToString();
var iniFontCsv = IniHelper.ReadValue(null, dgv.Parent.Name + "." + dgv.Name, INI_KEY_FONT_CSV, defaultFontCsv);
var fontItems = iniFontCsv.Split(',');
if (fontItems.Length != 3) fontItems = defaultFontCsv.Split(',');
if (float.TryParse(fontItems[1], out var size) == false) size = dgv.ColumnHeadersDefaultCellStyle.Font.Size;
if (bool.TryParse(fontItems[2], out var bold) == false) bold = dgv.ColumnHeadersDefaultCellStyle.Font.Bold;
var font = new Font(fontItems[0], size, bold ? FontStyle.Bold : FontStyle.Regular);
dgv.DefaultCellStyle.Font = font;
dgv.ColumnHeadersDefaultCellStyle.Font = font;
dgv.AutoResizeRows();
}
private const string KEY_NAME_DISPLAY_INDEX_CSV = "DisplayIndexCsv";
private const string KEY_NAME_COLUMN_VISIBLE_CSV = "ColumnVisibleCsv";
/// <summary>
/// INIの列表示順をDGVに反映
/// </summary>
/// <param name="dgv"></param>
public static void SetColumnDisplayIndexFromIni(DataGridView dgv)
{
// 表示順(DisplayIndex)の設定
var csv = IniHelper.ReadValue(null, dgv.Parent.Name + "." + dgv.Name, KEY_NAME_DISPLAY_INDEX_CSV);
if (string.IsNullOrEmpty(csv)) return;
var items = csv.Split(',');
if (items.Length != dgv.Columns.Count) return;
List<int> displayIndexList = new List<int>();
foreach ( var item in items) displayIndexList.Add(int.Parse(item));
for (var cnt = 0; cnt < dgv.Columns.Count; cnt++)
{
var index = displayIndexList.IndexOf(cnt);
dgv.Columns[index].DisplayIndex = cnt;
}
// 列の表示/非表示の設定
csv = IniHelper.ReadValue(null, dgv.Parent.Name + "." + dgv.Name, KEY_NAME_COLUMN_VISIBLE_CSV);
if (string.IsNullOrEmpty(csv)) return;
items = csv.Split(',');
if (items.Length != dgv.Columns.Count) return;
List<bool> visibleList = new List<bool>();
foreach (var item in items) visibleList.Add(bool.TryParse(item, out var boolValue) ? boolValue : true);
for (var cnt = 0; cnt < dgv.Columns.Count; cnt++)
{
dgv.Columns[cnt].Visible = visibleList[cnt];
}
}
public static void MoveRow(DataGridView dgv, int rowIndex, bool moveUp)
{
// 移動先のインデックスを計算
int targetIndex = moveUp ? rowIndex - 1 : rowIndex + 1;
// 範囲チェック(一番上より上、または一番下より下には行かない)
if (targetIndex < 0 || targetIndex >= dgv.Rows.Count - (dgv.AllowUserToAddRows ? 1 : 0))
{
return;
}
// 選択状態などを保持したい場合の準備
DataGridViewRow row = dgv.Rows[rowIndex];
// 一旦削除して挿入し直す
dgv.Rows.RemoveAt(rowIndex);
dgv.Rows.Insert(targetIndex, row);
// 移動後の行を選択状態にする(ユーザー体験向上)
dgv.ClearSelection();
dgv.Rows[targetIndex].Selected = true;
dgv.CurrentCell = dgv.Rows[targetIndex].Cells[0];
}
private const string INI_KEY_DGV_ROW_HEADER_HEIGHT = "DgvRowHeaderHeight";
/// <summary>
/// ヘッダ行の高さ保存
/// </summary>
/// <param name="dgv"></param>
public static void DgvSaveHeaderHeight(DataGridView dgv)
{
var section = dgv.Parent.Name + "." + dgv.Name;
IniHelper.WriteValue(null, section, INI_KEY_DGV_ROW_HEADER_HEIGHT, dgv.ColumnHeadersHeight.ToString());
}
/// <summary>
/// ヘッダ行の高さロード
/// </summary>
/// <param name="dgv"></param>
public static void DgvLoadHeaderHeight(DataGridView dgv)
{
var section = dgv.Parent.Name + "." + dgv.Name;
var str = IniHelper.ReadValue(null, section, INI_KEY_DGV_ROW_HEADER_HEIGHT, dgv.ColumnHeadersHeight.ToString());
dgv.ColumnHeadersHeight = int.TryParse(str, out var intValue) ? intValue : dgv.ColumnHeadersHeight;
}
/// <summary>
/// 非表示列の再表示
/// </summary>
/// <param name="dgv"></param>
public static void DgvRedispAllColumn(DataGridView dgv)
{
foreach (DataGridViewColumn col in dgv.Columns) col.Visible = true;
}
private const string INI_KEY_COL_VISIBLE_CSV = "ColVisibleCsv";
/// <summary>
/// 列の表示非表示を保存
/// </summary>
/// <param name="dgv"></param>
public static void DgvSaveColVisible(DataGridView dgv)
{
var section = dgv.Parent.Name + "." + dgv.Name;
var list = new List<bool>();
foreach (DataGridViewColumn col in dgv.Columns) list.Add(col.Visible);
IniHelper.WriteValue(null, section, INI_KEY_COL_VISIBLE_CSV, string.Join(",", list));
}
/// <summary>
/// 列の表示非表示をロード
/// </summary>
/// <param name="dgv"></param>
public static void DgvLoadColVisible(DataGridView dgv)
{
var section = dgv.Parent.Name + "." + dgv.Name;
var list = IniHelper.ReadValue(null, section, INI_KEY_COL_VISIBLE_CSV).Split(',').ToList();
foreach (DataGridViewColumn col in dgv.Columns)
{
if (list.Count - 1 < col.Index) break;
if (!bool.TryParse(list[col.Index], out bool val)) break;
col.Visible = val;
}
}
private const string INI_KEY_COL_DISPLAY_INDEX_CSV = "ColDisplayIndexCsv";
/// <summary>
/// 列の表示順インデックスを保存
/// </summary>
/// <param name="dgv"></param>
public static void DgvSaveColDisplayIndex(DataGridView dgv)
{
var section = dgv.Parent.Name + "." + dgv.Name;
var list = new List<string>();
foreach (DataGridViewColumn col in dgv.Columns) list.Add($"{col.Name}={col.DisplayIndex}");
IniHelper.WriteValue(null, section, INI_KEY_COL_DISPLAY_INDEX_CSV, string.Join(",", list));
}
/// <summary>
/// 列の表示順インデックスをロード
/// </summary>
/// <param name="dgv"></param>
public static void DgvLoadColDisplayIndex(DataGridView dgv)
{
var section = dgv.Parent.Name + "." + dgv.Name;
var list = IniHelper.ReadValue(null, section, INI_KEY_COL_DISPLAY_INDEX_CSV).Split(',').ToList();
if (list.Count == 1 && string.IsNullOrEmpty(list[0])) return;
Dictionary<int,string> dic = new Dictionary<int,string>();
foreach (var str in list)
{
dic.Add(int.Parse(str.Split('=')[1]), str.Split('=')[0]);
}
// DisplayIndexは小さい方から設定しないと崩れる
foreach (var di in dic.Keys.OrderBy(m => m))
{
dgv.Columns[dic[di]].DisplayIndex = di;
}
}
/// <summary>
/// 列幅の自動調整
/// </summary>
/// <param name="dgv"></param>
public static void DgvColumnWidthAutoAdjust(DataGridView dgv)
{
dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}
/// <summary>
/// 行高さの自動調整
/// </summary>
/// <param name="dgv"></param>
public static void DgvRowHeightAutoAdjust(DataGridView dgv)
{
dgv.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);
}
/// <summary>
/// 列固定
/// </summary>
/// <param name="dgv"></param>
public static void DgvColumnFix(DataGridView dgv)
{
if (dgv.CurrentCell == null) return;
// 1. 今クリックした列の「見た目の位置」を取得
int targetDisplayIndex = dgv.CurrentCell.OwningColumn.DisplayIndex;
// 2. いったん全列の固定を解除(これをしないとエラーになる場合がある)
DgvColumnFixKaijo(dgv);
// 3. 見た目の位置(DisplayIndex)が、ターゲット以下の列をすべて固定!
// ※DisplayIndexの小さい順(左側から順)にFrozenをかけていくのがコツ
var targetColumns = dgv.Columns.Cast<DataGridViewColumn>()
.OrderBy(c => c.DisplayIndex);
foreach (var col in targetColumns)
{
if (col.DisplayIndex <= targetDisplayIndex)
{
col.Frozen = true;
}
}
}
/// <summary>
/// 列固定解除
/// </summary>
/// <param name="dgv"></param>
public static void DgvColumnFixKaijo(DataGridView dgv)
{
// 2. いったん全列の固定を解除(これをしないとエラーになる場合がある)
foreach (DataGridViewColumn col in dgv.Columns)
{
col.Frozen = false;
}
}
private const string INI_KEY_COL_FROZEN_CSV = "ColFrozenCsv";
/// <summary>
/// 列の固定を保存
/// </summary>
/// <param name="dgv"></param>
public static void DgvSaveColFrozen(DataGridView dgv)
{
var section = dgv.Parent.Name + "." + dgv.Name;
var list = new List<bool>();
foreach (DataGridViewColumn col in dgv.Columns) list.Add(col.Frozen);
IniHelper.WriteValue(null, section, INI_KEY_COL_FROZEN_CSV, string.Join(",", list));
}
/// <summary>
/// 列の固定をロード
/// </summary>
/// <param name="dgv"></param>
public static void DgvLoadColFrozen(DataGridView dgv)
{
var section = dgv.Parent.Name + "." + dgv.Name;
var list = IniHelper.ReadValue(null, section, INI_KEY_COL_FROZEN_CSV).Split(',').ToList();
foreach (DataGridViewColumn col in dgv.Columns)
{
if (list.Count - 1 < col.Index) break;
if (!bool.TryParse(list[col.Index], out bool val)) break;
col.Frozen = val;
}
}
private const string INI_KEY_DGV_HEADER_BACK_COLOR = "DgvHeaderBackColor";
/// <summary>
/// ヘッダ背景色選択
/// </summary>
/// <param name="form"></param>
/// <param name="dgv"></param>
public static void DgvSelectHeaderBackColor(Form form, DataGridView dgv)
{
using (ColorDialog cd = new ColorDialog())
{
// 今の色を初期選択にしておく
cd.Color = dgv.ColumnHeadersDefaultCellStyle.BackColor;
if (cd.ShowDialog() == DialogResult.OK)
{
// 1. フォームの背景色を即時変更
dgv.ColumnHeadersDefaultCellStyle.BackColor = cd.Color;
// 文字色を計算して算出し設定
dgv.ColumnHeadersDefaultCellStyle.ForeColor = ColorHelper.GetContrastColor(dgv.ColumnHeadersDefaultCellStyle.BackColor);
// 2. 🔥 Colorを16進数(#RRGGBB)に変換してINIに書き込み
string colorHex = ColorTranslator.ToHtml(cd.Color);
IniHelper.WriteValue(null, form.Name, INI_KEY_DGV_HEADER_BACK_COLOR, colorHex);
}
}
}
/// <summary>
/// ヘッダ背景色(名前でマッチした列のみ)選択
/// </summary>
/// <param name="form"></param>
/// <param name="dgv"></param>
/// <param name="colNamePattern"></param>
/// <param name="iniKey"></param>
public static void DgvSelectHeaderBackColorWithNameMatch(Form form, DataGridView dgv, string colNamePattern, string iniKey)
{
// マッチする列を探し、現在の色を採取
Color? color = null;
foreach (DataGridViewColumn col in dgv.Columns)
{
if (StringUxer.WildcardMatch(col.Name, colNamePattern))
{
color = col.HeaderCell.Style.BackColor;
}
}
if (color == null)
{
MessageBox.Show(form, $"パターンにマッチする列なし[パターン:{colNamePattern}]");
return;
}
using (ColorDialog cd = new ColorDialog())
{
// 今の色を初期選択にしておく
cd.Color = (Color)color;
if (cd.ShowDialog() == DialogResult.OK)
{
var backColor = cd.Color;
// 文字色を計算して算出し設定
var foreColor = ColorHelper.GetContrastColor(backColor);
// DGVに反映
foreach (DataGridViewColumn col in dgv.Columns)
{
if (StringUxer.WildcardMatch(col.Name, colNamePattern))
{
col.HeaderCell.Style.BackColor = backColor;
col.HeaderCell.Style.ForeColor = foreColor;
}
}
// 2. 🔥 Colorを16進数(#RRGGBB)に変換してINIに書き込み
string colorHex = ColorTranslator.ToHtml(cd.Color);
IniHelper.WriteValue(null, form.Name, iniKey, colorHex);
}
}
}
/// <summary>
/// ヘッダ背景色をINIから取得して設定
/// </summary>
/// <param name="form"></param>
public static void DgvSetHeaderBackColorFromIni(Form form, DataGridView dgv)
{
var colorHex = IniHelper.ReadValue(null, form.Name, INI_KEY_DGV_HEADER_BACK_COLOR, ColorTranslator.ToHtml(dgv.ColumnHeadersDefaultCellStyle.BackColor));
dgv.ColumnHeadersDefaultCellStyle.BackColor = ColorTranslator.FromHtml(colorHex);
// 文字色を計算して算出し設定
dgv.ColumnHeadersDefaultCellStyle.ForeColor = ColorHelper.GetContrastColor(dgv.ColumnHeadersDefaultCellStyle.BackColor);
}
/// <summary>
/// ヘッダ背景色をINIから取得して設定(名前マッチング)
/// </summary>
/// <param name="form"></param>
/// <param name="dgv"></param>
/// <param name="colNamePattern"></param>
/// <param name="iniKey"></param>
public static void DgvSetHeaderBackColorFromIniWithNameMatch(Form form, DataGridView dgv, string colNamePattern, string iniKey)
{
// マッチする列を探し、現在の色を採取
Color? color = null;
foreach (DataGridViewColumn col in dgv.Columns)
{
if (StringUxer.WildcardMatch(col.Name, colNamePattern))
{
color = col.HeaderCell.Style.BackColor;
}
}
if (color == null)
{
MessageBox.Show(form, $"パターンにマッチする列なし[パターン:{colNamePattern}]");
return;
}
// INIから取得
var colorHex = IniHelper.ReadValue(null, form.Name, iniKey, ColorTranslator.ToHtml((Color)color));
var backColor = ColorTranslator.FromHtml(colorHex);
var foreColor = ColorHelper.GetContrastColor(backColor);
// マッチする列に設定
foreach (DataGridViewColumn col in dgv.Columns)
{
if (StringUxer.WildcardMatch(col.Name, colNamePattern))
{
col.HeaderCell.Style.BackColor = backColor;
col.HeaderCell.Style.ForeColor = foreColor;
}
}
}
public const string TSV_PATH = @".\@@@DGV@@@.tsv";
/// <summary>
/// DGVデータTSV保存
/// </summary>
/// <param name="form"></param>
/// <param name="dgv"></param>
public static void SaveGridDataToTsv(Form form, DataGridView dgv)
{
var path = TSV_PATH.Replace("@@@DGV@@@", $"{form.Name}.{dgv.Name}");
try
{
using (StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8))
{
foreach (DataGridViewRow row in dgv.Rows)
{
// 新規行(入力用の空行)はスキップ
if (row.IsNewRow) continue;
// 各セルの値をタブで結合
var cells = row.Cells.Cast<DataGridViewCell>().Select(c => c.Value?.ToString() ?? "");
sw.WriteLine(string.Join("\t", cells));
}
}
}
catch (Exception ex)
{
MessageBox.Show("DGVのTSV保存に失敗しました: " + ex.Message);
}
}
public static void LoadGridDataToTsv(Form form, DataGridView dgv)
{
var path = TSV_PATH.Replace("@@@DGV@@@", $"{form.Name}.{dgv.Name}");
if (!File.Exists(path)) return;
try
{
dgv.Rows.Clear();
string[] lines = File.ReadAllLines(path, Encoding.UTF8);
foreach (string line in lines)
{
if (string.IsNullOrWhiteSpace(line)) continue;
// タブで分割して行を追加
string[] values = line.Split('\t');
dgv.Rows.Add(values);
}
}
catch (Exception ex)
{
MessageBox.Show("DGVのTSVによる復元に失敗しました: " + ex.Message);
}
}
public static void SearchGrid(
DataGridView dgv,
string searchText,
bool forward)
{
if (string.IsNullOrEmpty(searchText)) return;
int rowCount = dgv.RowCount;
int colCount = dgv.ColumnCount;
// 現在のセルの位置を取得(選択されていなければ 0,0 から)
int startRow = dgv.CurrentCell?.RowIndex ?? 0;
int startCol = dgv.CurrentCell?.ColumnIndex ?? 0;
// 全セルをフラットなインデックスとして考えて計算
int totalCells = rowCount * colCount;
int startIndex = (startRow * colCount) + startCol;
for (int i = 1; i < totalCells; i++)
{
// forwardがtrueならプラス、falseならマイナス方向にずらす
int offset = forward ? i : -i;
int nextIndex = (startIndex + offset + totalCells) % totalCells;
int r = nextIndex / colCount;
int c = nextIndex % colCount;
DataGridViewCell cell = dgv[c, r];
if (cell.Value != null && cell.Value.ToString().Contains(searchText))
{
dgv.CurrentCell = cell;
return; // 見つかったら終了
}
}
MessageBox.Show("他には見つかりませんでしたにゃ!🐾");
}
}
}
+175
View File
@@ -0,0 +1,175 @@
using KssSmaPlaLib.Ini;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Forms
{
public static class FormHelper
{
/// <summary>
/// フォームのコンストラクタで行う処理集
/// </summary>
/// <param name="frm"></param>
public static void FormConstructorProc(Form frm)
{
frm.KeyPreview = true;
FormHelper.SetTitle(frm);
foreach (var control in frm.Controls)
{
if (control is DataGridView)
{
// DGVで行う共通処理
var dgv = control as DataGridView;
dgv.Dock = DockStyle.Fill;
dgv.AllowUserToResizeRows = false;
dgv.AllowUserToAddRows = false;
dgv.AllowUserToDeleteRows = false;
dgv.AllowUserToOrderColumns = false;
dgv.AllowUserToResizeColumns = true;
dgv.AllowUserToResizeRows = false;
dgv.ReadOnly = true;
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgv.RowHeadersVisible = false;
dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
// 列ヘッダのユーザによるソートを無効化する
foreach (DataGridViewColumn col in dgv.Columns) col.SortMode = DataGridViewColumnSortMode.NotSortable;
}
}
}
/// <summary>
/// フォームのロードで行う処理集
/// </summary>
/// <param name="frm"></param>
/// <param name="isDgvColAutoFit"></param>
public static void FormLoadProc(Form frm, ContextMenuStrip[] menus, bool isDgvColAutoFit = false)
{
FormHelper.LoadFormBounds(frm);
foreach (var control in frm.Controls)
{
if (control is DataGridView)
{
// DGVで行う共通処理
var dgv = control as DataGridView;
DgvHelper.DgvLoadColVisible(dgv);
DgvHelper.DgvLoadColDisplayIndex(dgv);
DgvHelper.DgvLoadColFrozen(dgv);
if (isDgvColAutoFit)
{
DgvHelper.DgvColumnWidthAutoAdjust(dgv);
}
else
{
DgvHelper.DgvLoadColWidth(dgv);
}
DgvHelper.DgvLoadFontFromIni(dgv);
}
}
foreach (var menu in menus)
{
ContextMenuHelper.SetFont(frm, menu);
}
}
/// <summary>
/// フォーム閉じるときの処理集
/// </summary>
/// <param name="frm"></param>
public static void FormClosingProc(Form frm)
{
FormHelper.SaveFormBounds(frm);
foreach (var control in frm.Controls)
{
if (control is DataGridView)
{
// DGVで行う共通処理
var dgv = control as DataGridView;
DgvHelper.DgvSaveColVisible(dgv);
DgvHelper.DgvSaveColDisplayIndex(dgv);
DgvHelper.DgvSaveColFrozen(dgv);
DgvHelper.DgvSaveColWidth(dgv);
DgvHelper.DgvSaveFontToIni(dgv);
}
}
}
private const string INI_KEY_RESTORE_BOUNDS_CSV = "RestoreBoundsCsv";
/// <summary>
/// フォームのバウンズ保存
/// ※フォームのClosingイベントでCallしてください。
/// </summary>
/// <param name="form"></param>
public static void SaveFormBounds(Form form)
{
var csv = string.Empty;
if (form.WindowState == FormWindowState.Maximized || form.WindowState == FormWindowState.Minimized)
{
csv = $"{form.RestoreBounds.Width},{form.RestoreBounds.Height},{form.RestoreBounds.Top},{form.RestoreBounds.Left},{form.WindowState == FormWindowState.Maximized}";
}
else
{
csv = $"{form.Bounds.Width},{form.Bounds.Height},{form.Bounds.Top},{form.Bounds.Left},{form.WindowState == FormWindowState.Maximized}";
}
IniHelper.WriteValue(null, form.Name, INI_KEY_RESTORE_BOUNDS_CSV, csv);
}
/// <summary>
/// フォームのバウンズ復元
/// ※フォームのLoadイベントでCallしてください。
/// </summary>
/// <param name="form"></param>
public static void LoadFormBounds(Form form)
{
var csv = IniHelper.ReadValue(null, form.Name, INI_KEY_RESTORE_BOUNDS_CSV);
if (string.IsNullOrEmpty(csv)) return;
var items = csv.Split(',');
if (items.Length != 5) return;
if (!int.TryParse(items[0], out var width)) return;
if (!int.TryParse(items[1], out var height)) return;
if (!int.TryParse(items[2], out var top)) return;
if (!int.TryParse(items[3], out var left)) return;
if (!bool.TryParse(items[4], out var isMaximum)) return;
form.Bounds = new System.Drawing.Rectangle(left, top, width, height);
if (isMaximum) form.WindowState = FormWindowState.Maximized;
}
private const string KEY_NAME_TITLE = "Title";
/// <summary>
/// タイトル設定(INI優先)
/// ※フォームのコンストラクタでCallしてください
/// </summary>
/// <param name="form"></param>
public static void SetTitle(Form form)
{
form.Text = IniHelper.ReadValue(null, form.Name, KEY_NAME_TITLE, form.Text);
}
/// <summary>
/// フォームの画面キャプチャを取得し画像ファイルに保存する
/// </summary>
/// <param name="form"></param>
/// <param name="bitmapFilePath"></param>
public static void GetCaptureAndSaveBitmap(Form form, string bitmapFilePath)
{
// フォームと同じサイズのBitmapを作成
Bitmap bitmap = new Bitmap(form.Width, form.Height);
// Bitmapにフォームの内容を描画
form.DrawToBitmap(bitmap, new Rectangle(0, 0, form.Width, form.Height));
// 画像ファイルとして保存
bitmap.Save(bitmapFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
// リソースの解放
bitmap.Dispose();
}
}
}
+181
View File
@@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Forms
{
public static class ToastNotifier
{
private const int WS_EX_NOACTIVATE = 0x08000000;
private const int WS_EX_TOPMOST = 0x00000008;
//public static void Show(Form owner, string message, Color backColor, int durationMs = 3000)
//{
// // 1. フォームの基本設定
// Form toast = new Form
// {
// FormBorderStyle = FormBorderStyle.None,
// StartPosition = FormStartPosition.Manual,
// BackColor = backColor,
// ShowInTaskbar = false,
// TopMost = true,
// Size = new Size(300, 60),
// Opacity = 0,
// Enabled = false // トースト自体は操作不能にしておく
// };
// Label lbl = new Label
// {
// Text = message,
// ForeColor = Color.White,
// Font = new Font("MS UI Gothic", 10, FontStyle.Bold),
// Dock = DockStyle.Fill,
// TextAlign = ContentAlignment.MiddleCenter
// };
// toast.Controls.Add(lbl);
// // オーナーの右下に配置
// toast.Location = new Point(
// owner.Location.X + owner.Width - toast.Width - 20,
// owner.Location.Y + owner.Height - toast.Height - 20
// );
// // 2. タイマーでアニメーションを管理
// Timer timer = new Timer { Interval = 10 };
// DateTime startTime = DateTime.Now;
// timer.Tick += (s, e) =>
// {
// double elapsed = (DateTime.Now - startTime).TotalMilliseconds;
// if (elapsed < 200) // 最初の0.2秒でフェードイン
// {
// toast.Opacity = elapsed / 200.0;
// }
// else if (elapsed < 200 + durationMs) // 指定時間はそのまま
// {
// toast.Opacity = 1.0;
// }
// else if (elapsed < 200 + durationMs + 200) // 最後の0.2秒でフェードアウト
// {
// toast.Opacity = 1.0 - (elapsed - (200 + durationMs)) / 200.0;
// }
// else // 終了処理
// {
// timer.Stop();
// timer.Dispose();
// toast.Close();
// toast.Dispose();
// }
// };
// // 3. 表示開始(ここを通った瞬間にメソッドは終了し、呼び出し元に戻ります)
// toast.Show();
// timer.Start();
//}
//public static async Task ShowAsync(Form owner, string message, Color backColor, int durationMs = 3000)
//{
// // 1. フォームの作成
// using (var toast = new Form
// {
// FormBorderStyle = FormBorderStyle.None,
// StartPosition = FormStartPosition.Manual,
// BackColor = backColor,
// ShowInTaskbar = false,
// TopMost = true,
// Size = new Size(300, 60),
// Opacity = 0
// })
// {
// // フォーカスを奪わないための設定(WinAPIをラップしたCreateParamsの上書き)
// // ※簡易的にリフレクションで設定するか、Formを継承したクラスを作るのが定石です
// Label lbl = new Label
// {
// Text = message,
// ForeColor = Color.White,
// Font = new Font("MS UI Gothic", 10, FontStyle.Bold),
// Dock = DockStyle.Fill,
// TextAlign = ContentAlignment.MiddleCenter
// };
// toast.Controls.Add(lbl);
// toast.Location = new Point(
// owner.Location.X + owner.Width - toast.Width - 20,
// owner.Location.Y + owner.Height - toast.Height - 20
// );
// // 表示(フォーカスを奪わずに表示)
// toast.Show();
// // フォーカスが移るのを防ぐための念押し(Activateさせない)
// // 2. アニメーション(async/await の真骨頂)
// for (int i = 0; i < 10; i++) { toast.Opacity += 0.1; await Task.Delay(10); }
// await Task.Delay(durationMs);
// for (int i = 0; i < 10; i++) { toast.Opacity -= 0.1; await Task.Delay(10); }
// toast.Close();
// }
//}
public static async Task ShowAsync(Form owner, string message, Color backColor, int durationMs = 3000)
{
// 【重要】SignalRなどの別スレッドから呼ばれても安全なように、UIスレッドへ強制バトンタッチ
if (owner.InvokeRequired)
{
owner.BeginInvoke(new Action(() => { _ = ShowAsync(owner, message, backColor, durationMs); }));
return;
}
// 1. フォームの作成(usingは使わず、Closeに任せる)
// フォーカスを奪わない(WS_EX_NOACTIVATE = 0x08000000)を仕込んだカスタムフォームをその場で定義
var toast = new NoActivateForm
{
FormBorderStyle = FormBorderStyle.None,
StartPosition = FormStartPosition.Manual,
BackColor = backColor,
ShowInTaskbar = false,
TopMost = true,
Size = new Size(300, 60),
Opacity = 0
};
Label lbl = new Label
{
Text = message,
ForeColor = Color.White,
Font = new Font("MS UI Gothic", 10, FontStyle.Bold),
Dock = DockStyle.Fill,
TextAlign = ContentAlignment.MiddleCenter
};
toast.Controls.Add(lbl);
// 右下のベストポジションに配置(オーナーフォーム基準)
toast.Location = new Point(
owner.Location.X + owner.Width - toast.Width - 20,
owner.Location.Y + owner.Height - toast.Height - 20
);
// 表示(フォーカスを絶対に奪わない)
toast.Show();
// 2. アニメーション(async/await の真骨頂!)
for (int i = 0; i < 10; i++) { toast.Opacity += 0.1; await Task.Delay(10); }
await Task.Delay(durationMs);
for (int i = 0; i < 10; i++) { toast.Opacity -= 0.1; await Task.Delay(10); }
// 閉じると同時に、WinFormsが自動でメモリを綺麗に解放(Dispose)してくれます
toast.Close();
}
}
// 【職人技】フォーカスを絶対に奪わないフォーム(CreateParamsの上書き)
public class NoActivateForm : Form
{
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x08000000; // WS_EX_NOACTIVATE(クリックしてもフォーカスが移らない魔法のフラグ)
return cp;
}
}
}
}
+684
View File
@@ -0,0 +1,684 @@
using Npgsql;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Office.Word;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using KssSmaPlaLib.Commons;
using Serilog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using static KssSmaPlaLib.IO.Database.DbUxer;
using Path = System.IO.Path;
namespace KssSmaPlaLib.IO.Database
{
/// <summary>
/// DBアクセスアシスタント
/// </summary>
public class DbUxer : IDisposable
{
public enum DbProvider
{
PostgreSQL,
SQLServer,
MySQL,
Oracle,
SQLite,
}
/// <summary>
/// プロバイダ名ディクショナリ
/// </summary>
private static readonly Dictionary<DbProvider, string> _providerNameDic = new Dictionary<DbProvider, string>()
{
{ DbProvider.PostgreSQL, "Npgsql" },
{ DbProvider.SQLServer, "System.Data.SqlClient" },
{ DbProvider.MySQL, "MySql.Data.MySqlClient" },
{ DbProvider.Oracle, "Oracle.ManagedDataAccess.Client" },
{ DbProvider.SQLite, "System.Data.SQLite" },
};
/// <summary>
/// プロバイダ名(文字列)からenum値に変更
/// </summary>
/// <param name="dbProviderName">プロバイダ名(文字列)</param>
/// <returns>enum値(該当なし時はnull</returns>
public static DbProvider? GetDbProviderEnumFromString(string dbProviderName = "PostgreSQL")
{
switch(dbProviderName.ToLower().Replace(" ",""))
{
case "postgresql":
case "ポスグレ":
return DbProvider.PostgreSQL;
case "sqlserver":
return DbProvider.SQLServer;
case "mysql":
return DbProvider.MySQL;
case "oracle":
case "oracledatabase":
return DbProvider.Oracle;
case "sqlite":
case "sqlite3":
return DbProvider.SQLite;
default:
return null;
}
}
/// <summary>
/// コミット済みフラグ
/// </summary>
private bool _isCommitted = false;
/// <summary>
/// SQLディクショナリ
/// </summary>
private static readonly Dictionary<string, string> _sqlDic = new Dictionary<string, string>();
/// <summary>
/// 指定フォルダからSQLファイルを読み込む(ディクショナリ保存)
/// </summary>
/// <param name="folderPath">フォルダパス</param>
/// <returns>成否</returns>
public static bool TryLoadSqlFromText(string folderPath, out string resultMessage)
{
resultMessage = string.Empty;
var fileCount = 0;
List<string> files = new List<string>();
try
{
if (string.IsNullOrEmpty(folderPath))
{
resultMessage = "フォルダパスが指定されていません。";
return false;
}
if (!Directory.Exists(folderPath))
{
resultMessage = $"フォルダが存在しません。[フォルダパス:{folderPath}]";
return false;
}
_sqlDic.Clear();
foreach (var file in Directory.GetFiles(folderPath, "*.sql.txt"))
{
_sqlDic.Add(Path.GetFileNameWithoutExtension(file).ToLower().Replace(".sql", ""), System.IO.File.ReadAllText(file));
files.Add(Path.GetFileNameWithoutExtension(file).Replace(".sql", ""));
fileCount++;
}
resultMessage = $"SQLファイルをロードしました。[ファイル数:{fileCount},ファイル:{string.Join(",", files)}]";
return true;
}
catch (Exception ex)
{
resultMessage = $"SQLファイル読み込み時にエラーが発生しました。[エラー内容:{ex.Message}]";
return false;
}
}
public static bool TestConnectByDic(Dictionary<string,string> iniDic, out string resultMessage)
{
const string KEY_DB_PROVIDER_NAME = "DbProviderName";
const string KEY_DB_CONNECTION_STRING = "DbConnectionString";
var dbProviderName = DictionaryUxer.GetValueOrDefault(iniDic, KEY_DB_PROVIDER_NAME, string.Empty);
var connectionString = DictionaryUxer.GetValueOrDefault(iniDic, KEY_DB_CONNECTION_STRING, string.Empty);
return TestConnect(dbProviderName, connectionString, out resultMessage);
}
/// <summary>
/// テスト接続
/// </summary>
/// <returns>成否</returns>
public static bool TestConnect(string dbPrividerName, string dbConnectionString, out string resultMessage)
{
// パラメータチェック&DBプロバイダ取得
if (!TryConnectParameter(dbPrividerName, dbConnectionString, out DbProvider? _, out resultMessage))
{
return false;
}
if (!TryCreate(dbPrividerName, dbConnectionString, out var dbUxer, out resultMessage, false))
{
return false;
}
dbUxer.Dispose();
return true;
}
/// <summary>
/// DB接続
/// </summary>
private DbConnection _con = null;
/// <summary>
/// トランザクション
/// </summary>
private DbTransaction _tran = null;
public static bool TryCreateByDic(Dictionary<string, string> iniDic, out DbUxer dbUxer, out string resultMessage, bool useTransaction = false)
{
const string KEY_DB_PROVIDER_NAME = "DbProviderName";
const string KEY_DB_CONNECTION_STRING = "DbConnectionString";
var dbProviderName = DictionaryUxer.GetValueOrDefault(iniDic, KEY_DB_PROVIDER_NAME, string.Empty);
var connectionString = DictionaryUxer.GetValueOrDefault(iniDic, KEY_DB_CONNECTION_STRING, string.Empty);
return TryCreate(dbProviderName, connectionString, out dbUxer, out resultMessage, useTransaction);
}
/// <summary>
/// 生成挑戦
/// </summary>
/// <param name="dbPrividerName"></param>
/// <param name="dbProvider"></param>
/// <param name="dbConnectionString"></param>
/// <param name="dbUxer"></param>
/// <param name="resultMessage"></param>
/// <returns></returns>
public static bool TryCreate(string dbPrividerName, string dbConnectionString, out DbUxer dbUxer, out string resultMessage, bool useTransaction = false)
{
dbUxer = null;
// パラメータチェック&DBプロバイダ取得
if (!TryConnectParameter(dbPrividerName, dbConnectionString, out DbProvider? dbp, out resultMessage))
{
return false;
}
DbProvider dbpp = (DbProvider)dbp;
try
{
// 生成
dbUxer = new DbUxer(dbpp, dbConnectionString, useTransaction);
return true;
}
catch (Exception ex)
{
// 接続NG回答
resultMessage = $"DB接続に失敗しました。[エラー内容:{ex.Message}]";
return false;
}
}
private static bool TryConnectParameter(string dbPrividerName, string dbConnectionString, out DbProvider? dbp, out string resultMessage)
{
dbp = DbProvider.PostgreSQL;
resultMessage = string.Empty;
if (string.IsNullOrEmpty(dbPrividerName))
{
// DBプロバイダ指定なしの場合、デフォルトはポスグレとする
// Infoメッセージ
resultMessage = "DBプロバイダ名が未指定のため、デフォルトのPostgreSQLを使用します。";
}
if (string.IsNullOrEmpty(dbConnectionString))
{
resultMessage = "接続文字列が設定されていません。";
return false;
}
if (!string.IsNullOrEmpty(dbPrividerName))
{
dbp = GetDbProviderEnumFromString(dbPrividerName);
}
if (dbp == null)
{
resultMessage = $"DBプロバイダ名が不正です。[DBプロバイダ名:{dbPrividerName}]";
return false;
}
return true;
}
/// <summary>
/// コンストラクタ(DB接続)
/// </summary>
/// <param name="dbProvider">DBプロバイダ(enum値)</param>
/// <param name="connectionString">接続文字列</param>
/// <param name="useTransaction">トランザクション有無</param>
private DbUxer(DbProvider dbProvider, string connectionString, bool useTransaction = false)
{
try
{
// DBプロバイダファクトリー作成
DbProviderFactory factory;
if (dbProvider == DbProvider.PostgreSQL)
{
// ポスグレの場合、Npgsqlのインスタンをを直接取得
factory = Npgsql.NpgsqlFactory.Instance;
}
else
{
factory = DbProviderFactories.GetFactory(_providerNameDic[dbProvider]);
}
// DB接続作成
_con = factory.CreateConnection();
// 接続文字列設定
_con.ConnectionString = connectionString;
// 接続
_con.Open();
// トランザクション
if (useTransaction) _tran = _con.BeginTransaction();
}
catch (Exception ex)
{
LoggerUxer.Error($"DB接続に失敗しました。[プロバイダ:{dbProvider},接続文字列:{connectionString},エラー内容:{ex.Message}]");
throw ex;
}
}
public bool ExecuteNonQuery(string sqlOrName, Dictionary<string, object> parameters, out int resultCount, out string resultMessage)
{
resultCount = 0;
resultMessage = string.Empty;
if (_con == null || _con.State != ConnectionState.Open)
{
resultMessage = "DBと接続されていません。";
return false;
}
try
{
using (var cmd = _con.CreateCommand())
{
// コパンドプロパティを注入
if (!TryInjectSoulToCmd(cmd, sqlOrName, parameters, out var messageForMe))
{
resultMessage = messageForMe;
return false;
}
resultCount = cmd.ExecuteNonQuery();
LoggerUxer.Info($"[Rec Count:{resultCount}]");
return true;
}
}
catch (Exception ex)
{
resultMessage = $"SQL実行でエラーが発生しました。[SQL名:{sqlOrName},エラー内容:{ex.Message}]";
return false;
}
}
public bool BeginTextImport(
string sqlOrName,
string csvFilePath,
out int resultCount,
out string resultMessage)
{
resultCount = 0;
resultMessage = string.Empty;
if (_con == null || _con.State != ConnectionState.Open)
{
resultMessage = "DBと接続されていません。";
return false;
}
try
{
// SQLの取得
sqlOrName = sqlOrName.ToLower();
var sql = _sqlDic.ContainsKey(sqlOrName) ? _sqlDic[sqlOrName] : sqlOrName;
// CSV有無
if (!System.IO.File.Exists(csvFilePath))
{
resultMessage = $"CSVファイルが存在しません。[ファイルパス:{csvFilePath}]";
return false;
}
// バルクインサート用のメソッドはポスグレの接続しか持たない
var pgConn = (NpgsqlConnection)_con;
var sqls = sql.Split(new[] { "-- SPLIT --" }, StringSplitOptions.RemoveEmptyEntries);
if (sqls.Length != 3)
{
resultMessage = $"バルク挿入SQLで分割数が正しくありません。[SQLファイル名:{sqlOrName},分割数:{sqls.Length}]";
return false;
}
// 1個目のSQL(一時テーブル作成)
if (!ExecuteNonQuery(sqls[0], new Dictionary<string, object>(), out var _, out var messageForMe))
{
resultMessage = $"バルク挿入SQL(1)が失敗しました。[詳細:{messageForMe}]";
return false;
}
// 2個目のSQL(一時テーブルにバルク挿入)
using (var writer = pgConn.BeginTextImport(sqls[1]))
{
using (var reader = new StreamReader(csvFilePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
writer.WriteLine(line);
//resultCount++; // ここで「1件、2件…」と数える!♨️
}
}
} // これで完了!1000件なら「シュンッ!」で終わります
// 3個目のSQL(一時テーブルから対象テーブルへコピー)
if (!ExecuteNonQuery(sqls[2], new Dictionary<string, object>(), out resultCount, out messageForMe))
{
resultMessage = $"バルク挿入SQL(2)が失敗しました。[詳細:{messageForMe}]";
return false;
}
LoggerUxer.Info($"[Rec Count:{resultCount}]");
return true;
}
catch (Exception ex)
{
resultMessage = $"SQL実行でエラーが発生しました。[SQL名:{sqlOrName},エラー内容:{ex.Message}]";
return false;
}
}
public bool ExecuteQuery(string sqlOrName, Dictionary<string, object> parameters, out List<Dictionary<string, object>> recordSet, out string resultMessage)
{
recordSet = new List<Dictionary<string, object>>();
resultMessage = string.Empty;
if (_con == null || _con.State != ConnectionState.Open)
{
resultMessage = "DBと接続されていません。";
return false;
}
try
{
using (var cmd = _con.CreateCommand())
{
// コパンドプロパティを注入
if (!TryInjectSoulToCmd(cmd, sqlOrName, parameters, out var messageForMe))
{
resultMessage = messageForMe;
return false;
}
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
row[reader.GetName(i)] = reader.GetValue(i);
}
recordSet.Add(row);
}
LoggerUxer.Info($"[Rec Count:{recordSet.Count}]");
}
}
return true;
}
catch (Exception ex)
{
resultMessage = $"DBからデータ取得時にエラーが発生しました。[SQL名:{sqlOrName},エラー内容:{ex.Message}]";
return false;
}
}
private bool TryInjectSoulToCmd(DbCommand cmd, string sqlOrName, Dictionary<string,object> parameters, out string resultMessage)
{
resultMessage = string.Empty;
// SQLの取得
sqlOrName = sqlOrName.ToLower();
var sql = _sqlDic.ContainsKey(sqlOrName) ? _sqlDic[sqlOrName] : sqlOrName;
//LoggerUxer.Info($"[SQL:{sql}]");
// SQL中のコマンドパラメータ名取得
var paraList = ExtractSqlParams(sql);
//oggerUxer.Info($"[SQL Para names:{string.Join(",", paraList)}]");
// コマンドパラメータ値の型変換
if (!TryChangeParamTypeFromSqlParams(ref parameters, ref paraList, out var messageForMe))
{
resultMessage = $"コマンドパラメータ値の型変換に失敗しました。[エラー内容:{messageForMe}]";
return false;
}
// SQL文中のコマンドパラメータ型定義をカット
cmd.CommandText = sql = CutParamTypeOfSQL(sql);
//LoggerUxer.Info($"[SQL(Param Type Cut):{sql}]");
// 再度、SQL中のコマンドパラメータ名取得
paraList = ExtractSqlParams(sql);
//LoggerUxer.Info($"[SQL Para names(Type cut):{string.Join(",", paraList)}]");
// SQLに合わせたコマンドパラメータ登録
foreach (var p in parameters)
{
if (!paraList.Contains(p.Key)) continue;
var param = cmd.CreateParameter();
param.ParameterName = p.Key;
param.Value = p.Value;
cmd.Parameters.Add(param);
}
//LoggerUxer.Info($"[SQL Params:{GetCommandParametersCsv(cmd)}]");
if (cmd.Parameters.Count != paraList.Count)
{
resultMessage = $"必要なパラメータが不足しています。[SQL名:{sqlOrName},SQL項目:{string.Join(",", paraList)}, CSV項目:{string.Join(",", parameters.Keys)}]";
return false;
}
return true;
}
public void Commit()
{
_tran?.Commit();
_isCommitted = true;
}
/// <summary>
/// 終了処理
/// </summary>
/// <exception cref="NotImplementedException"></exception>
public void Dispose()
{
if (_tran != null && !_isCommitted)
{
Log.Warning("トランザクション未コミット → 自動ロールバックされました");
_tran.Rollback(); // 明示的にロールバック
}
_con?.Dispose();
_con = null;
_tran = null;
}
public static List<string> ExtractSqlParams(string sql)
{
//var matches = System.Text.RegularExpressions.Regex.Matches(sql, @":([a-zA-Z_][a-zA-Z0-9_]*)");
//return matches.Cast<System.Text.RegularExpressions.Match>()
// .Select(m => m.Groups[1].Value)
// .Distinct()
// .ToList();
//var result = new List<string>();
//var lines = sql.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
//foreach (var line in lines)
//{
// // コメント部分を除去
// var codePart = line.Contains("--") ? line.Substring(0, line.IndexOf("--")) : line;
// // パラメータ抽出
// var matches = System.Text.RegularExpressions.Regex.Matches(
// codePart,
// @":(\[[a-zA-Z]\][a-zA-Z_][a-zA-Z0-9_]*)|:([a-zA-Z_][a-zA-Z0-9_]*)"
// );
// foreach (System.Text.RegularExpressions.Match match in matches)
// {
// var paramName = match.Groups[1].Success ? match.Groups[1].Value : match.Groups[2].Value;
// if (!result.Contains(paramName))
// result.Add(paramName);
// }
//}
//return result;
var result = new List<string>();
var lines = sql.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
foreach (var line in lines)
{
// コメント部分を除去
var codePart = line.Contains("--") ? line.Substring(0, line.IndexOf("--")) : line;
// パラメータ抽出(::で始まるものは除外)
var matches = System.Text.RegularExpressions.Regex.Matches(
codePart,
@"(?<!:):(\[[a-zA-Z]\][a-zA-Z_][a-zA-Z0-9_]*)|(?<!:):([a-zA-Z_][a-zA-Z0-9_]*)"
);
foreach (System.Text.RegularExpressions.Match match in matches)
{
var paramName = match.Groups[1].Success ? match.Groups[1].Value : match.Groups[2].Value;
if (!result.Contains(paramName))
result.Add(paramName);
}
}
return result;
}
public static string GetCommandParametersCsv(DbCommand command)
{
if (command == null || command.Parameters.Count == 0)
return string.Empty;
var list = new List<string>();
foreach (DbParameter param in command.Parameters)
{
string name = param.ParameterName?.TrimStart('@'); // @を除去(任意)
object value = param.Value;
string formattedValue;
if (value == null || value == DBNull.Value)
{
formattedValue = "NULL";
}
else if (value is string || value is char)
{
formattedValue = $"'{value}'"; // シングルクォートで括る
}
else if (value is DateTime dt)
{
formattedValue = $"'{dt:yyyy-MM-dd HH:mm:ss}'"; // 日付も文字列扱い
}
else
{
formattedValue = value.ToString();
}
list.Add($"{name}={formattedValue}");
}
return string.Join(",", list);
}
private static bool TryChangeParamTypeFromSqlParams(ref Dictionary<string, object> parameters, ref List<string> paraNameList, out string resultMessage)
{
resultMessage = string.Empty;
foreach (var key in parameters.Keys.ToList())
{
var name = paraNameList
.FirstOrDefault(m => m == key || m.Substring(0, 1) == "[" && m.Substring(3) == key);
if (name != null && name.Substring(0, 1) == "[")
{
switch (name.Substring(0, 3).ToUpper())
{
case "[I]":
if (string.IsNullOrEmpty(parameters[key].ToString()))
{
parameters[key] = DBNull.Value;
}
else if (int.TryParse(parameters[key].ToString(), out int intValue))
{
parameters[key] = intValue;
}
else
{
resultMessage = $"パラメータ値[I]型変換に失敗しました。[キー:{key}値:{parameters[key]}]";
return false;
}
break;
//case "[IN":
// if (string.IsNullOrEmpty(parameters[key].ToString()))
// {
// parameters[key] = DBNull.Value;
// }
// else if (int.TryParse(parameters[key].ToString(), out intValue))
// {
// parameters[key] = intValue;
// }
// else
// {
// resultMessage = $"パラメータ値[IN]型変換に失敗しました。[キー:{key}値:{parameters[key]}]";
// return false;
// }
// break;
case "[F]":
if (double.TryParse(parameters[key].ToString(), out double doubleValue))
{
parameters[key] = doubleValue;
}
else
{
resultMessage = $"パラメータ値[F]型変換に失敗しました。[キー:{key}値:{parameters[key]}]";
return false;
}
break;
case "[D]":
if (DateTime.TryParse(parameters[key].ToString(), out DateTime dtValue))
{
parameters[key] = dtValue;
}
else
{
resultMessage = $"パラメータ値[D]型変換に失敗しました。[キー:{key}値:{parameters[key]}]";
return false;
}
break;
case "[S]":
parameters[key] = parameters[key].ToString();
break;
}
}
}
return true;
}
// SQL文中のコマンドパラメータ型定義をカット
private static string CutParamTypeOfSQL(string sql)
{
string[] cutItems = new string[] { "[I]", "[F]", "[D]", "[S]" };
foreach (var cutItem in cutItems)
{
sql = sql.Replace(cutItem.ToUpper(), "");
sql = sql.Replace(cutItem.ToLower(), "");
}
return sql;
}
}
}
+60
View File
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.IO.Excel
{
public static class ExcelCellValidatorUxer
{
/// <summary>
/// ExcelのA1形式(例: "A1", "Z99", "AA1000")かどうかを判定します。
/// </summary>
/// <param name="cellRef">セル参照文字列</param>
/// <returns>有効なA1形式ならtrue、無効ならfalse</returns>
public static bool IsValidA1Format(string cellRef)
{
if (string.IsNullOrWhiteSpace(cellRef))
return false;
// 正規表現でA1形式をチェック(列: A〜XFD、行: 1〜1048576
var match = System.Text.RegularExpressions.Regex.Match(
cellRef.ToUpperInvariant(),
@"^([A-Z]{1,3})([1-9][0-9]{0,6})$"
);
if (!match.Success)
return false;
string colPart = match.Groups[1].Value;
string rowPart = match.Groups[2].Value;
// 列がXFD(Excel最大列)以内かチェック
if (ColumnNameToNumber(colPart) > 16384)
return false;
// 行がExcel最大行以内かチェック
if (int.TryParse(rowPart, out int row))
{
return row >= 1 && row <= 1048576;
}
return false;
}
/// <summary>
/// 列名(例: "A", "Z", "AA")を列番号に変換(例: 1, 26, 27)
/// </summary>
public static int ColumnNameToNumber(string columnName)
{
int sum = 0;
foreach (char c in columnName)
{
sum *= 26;
sum += (c - 'A' + 1);
}
return sum;
}
}
}
+26
View File
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.IO.Excel
{
public static class ExcelColumnHelperUxer
{
public static string GetExcelColumnLetter(int columnNumber)
{
if (columnNumber < 1)
throw new ArgumentOutOfRangeException(nameof(columnNumber), "Column number must be >= 1");
string columnLetter = string.Empty;
while (columnNumber > 0)
{
columnNumber--; // Adjust for 0-indexed calculation
columnLetter = (char)('A' + (columnNumber % 26)) + columnLetter;
columnNumber /= 26;
}
return columnLetter;
}
}
}
+95
View File
@@ -0,0 +1,95 @@
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace KssSmaPlaLib.IO.Excel
{
public class XlUxer
{
public static IXLCell GCell(IXLWorksheet sheet, string a1Address)
{
var cell = sheet.Cell(a1Address);
return GCell(cell);
}
public static IXLCell GCell(IXLWorksheet sheet, int row, int col)
{
var cell = sheet.Cell(row, col);
return GCell(cell);
}
public static IXLCell GCell(IXLCell cell)
{
return cell.IsMerged() ? cell.MergedRange().FirstCell() : cell;
}
public static bool TryValidateA1CellAddress(string a1Address, out string normalizedAddress)
{
normalizedAddress = null;
if (string.IsNullOrWhiteSpace(a1Address))
return false;
// 正規表現でA1形式(例:A1, B2, AA10など)をチェック
var regex = new Regex(@"^[A-Z]{1,3}[1-9][0-9]*$", RegexOptions.IgnoreCase);
if (!regex.IsMatch(a1Address))
return false;
// 正規化(大文字化)
normalizedAddress = a1Address.ToUpperInvariant();
return true;
}
/// <summary>
/// Shorter
/// </summary>
/// <param name="colLetter"></param>
/// <returns></returns>
public static int GetColNo(string colLetter)
{
if (!TryConvertColLetterToNumber(colLetter, out var no))
{
return int.MinValue;
}
return no;
}
/// <summary>
/// 列アルファベットを列番号(1オリジン)に変換
/// </summary>
/// <param name="colLetter">列アルファベット</param>
/// <param name="colNo">[出力]列番号(1オリジン)</param>
/// <returns>成否</returns>
public static bool TryConvertColLetterToNumber(string colLetter, out int colNo)
{
colNo = int.MinValue;
// バリデ(AXFD
if(!Regex.IsMatch(colLetter, @"^(?i)([A-Z]|[A-Z]{2}|[A-E][A-Z]{2})$"))
{
return false;
}
// 大文字化
colLetter = colLetter.ToUpper();
// アルファベット1文字ずつ見て列番号を算出
int no = 0;
foreach (char c in colLetter)
{
no = no * 26 + (c - 'A' + 1);
}
// 列番号範囲外なら失敗
if (no > 16384 || no < 1) return false;
// 成功
colNo = no;
return true;
}
}
}
+158
View File
@@ -0,0 +1,158 @@
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.Exchange.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace KssSmaPlaLib.IO.File
{
public class CsvUxer
{
public static bool ExportToCsv<T>(List<T> list, string filePath, out string resultMessage, EncodingUxer.EncodingType encodingType = EncodingUxer.EncodingType.Utf8WithoutBom) where T : ICsvExportableUxer
{
resultMessage = string.Empty;
try
{
var lines = new List<string> { list.FirstOrDefault()?.CsvHeader ?? "" };
lines.AddRange(list.Select(item => item.ToCsvLine()));
System.IO.File.WriteAllLines(filePath, lines, EncodingUxer.GetEncoding(encodingType));
return true;
}
catch (Exception ex)
{
resultMessage = $"CSV出力に失敗しました。[ファイルパス:{filePath},エラー内容:{ex.Message}]";
return false;
}
}
/// <summary>
/// CSVインポート
/// </summary>
/// <param name="csvFilePath">CSVファイルパス</param>
/// <param name="recordSet">[出力]レコードセット</param>
/// <param name="resultMessage">[出力]メッセージ</param>
/// <param name="encodingType">[オプション]エンコード</param>
/// <returns>成否</returns>
public static bool ImportFromCsv(string csvFilePath, out List<Dictionary<string, string>> recordSet, out string resultMessage, EncodingUxer.EncodingType encodingType = EncodingUxer.EncodingType.Utf8WithoutBom)
{
recordSet = new List<Dictionary<string, string>>();
resultMessage = string.Empty;
try
{
// 全行読み込み
var lines = System.IO.File.ReadAllLines(csvFilePath, EncodingUxer.GetEncoding(encodingType));
// データ行0件
if (lines.Length < 2) return true;
// ヘッダ行項目分割
var header = Regex.Split(lines[0], ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
for (var cnt = 0; cnt < header.Length; cnt++) header[cnt] = header[cnt].Trim('\"');
// データ行件数分
for (int i = 1; i < lines.Length; i++)
{
// 項目分割
var values = Regex.Split(lines[i], ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
for (var cnt = 0; cnt < values.Length; cnt++) values[cnt] = values[cnt].Trim('\"');
if (values.Length != header.Length)
{
resultMessage = $"CSV読み込みでヘッダの項目数とデータの項目数が異なります。[CSVファイルパス:{csvFilePath},行番号:{i + 1},ヘッダ行項目数:{header.Length},データ行項目数:{values.Length}]";
return false;
}
var record = new Dictionary<string, string>();
// 全項目
for (int j = 0; j < header.Length && j < values.Length; j++)
{
var key = header[j].Trim('\"');
var value = values[j].Trim('\"');
record[key] = value;
}
recordSet.Add(record);
}
return true;
}
catch (Exception ex)
{
resultMessage = $"CSV読み込み処理でエラーが発生しました。[CSVファイルパス:{csvFilePath},エラー内容:{ex.Message}]";
return false;
}
}
public static string Escape(string value) => $"\"{value.Replace("\"", "\"\"")}\"";
public static string Join(params object[] values) => string.Join(",", values.Select(m => Escape(m == null ? "" : m.ToString())));
/// <summary>
/// CSVファイルを読み込み、ディクショナリに変換します。
/// </summary>
/// <param name="path">CSVファイルのパス</param>
/// <param name="dic">出力されるディクショナリ(ファイル無しの場合は空)</param>
/// <param name="resultMessage"></param>
/// <returns>処理が成功した場合はtrue、例外発生時はfalse</returns>
public static bool TryGetDictionaryFromCsv(
string path,
out Dictionary<string, string> dic,
out string resultMessage)
{
resultMessage = string.Empty;
// 1. 最初に出力変数を空のディクショナリで初期化
dic = new Dictionary<string, string>();
try
{
// 2. ファイルが存在しない場合は空のままtrueで返す
if (!System.IO.File.Exists(path))
{
return true;
}
// 3. BOM付きUTF-8を指定してファイルを開く
// (Encoding.UTF8 はデフォルトでBOMの有無を自動判別して正しく読み込めます)
using (var reader = new StreamReader(path, Encoding.UTF8))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// 空行はスキップ
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
// カンマで分割 (単純な2列前提)
string[] parts = line.Split(',');
// 最低1列(キー)があれば処理する(2列未満の対策)
if (parts.Length > 0)
{
string key = parts[0];
// 2列目があればその値、なければ空文字
string value = parts.Length > 1 ? parts[1] : string.Empty;
// 重複キーは後勝ち(インデクサを使うことで上書き保存)
dic[key] = value;
}
}
}
return true;
}
catch (Exception ex)
{
// TODO: あたしがのちほどエラーメッセージ処理を入れる!
resultMessage = $"CSVファイル読み込みに失敗しました。[詳細:{ex.Message}]";
return false;
}
}
}
}
+141
View File
@@ -0,0 +1,141 @@
using DocumentFormat.OpenXml.Vml;
using KssSmaPlaLib.Commons;
using KssSmaPlaLib.Exchange.Interfaces;
using Org.BouncyCastle.Asn1;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Path = System.IO.Path;
namespace KssSmaPlaLib.IO.File
{
public static class FileUxer
{
/// <summary>
/// テキストファイル出力(全テキスト一括)
/// </summary>
/// <param name="allLineText">全テキスト</param>
/// <param name="filePath">ファイルパス</param>
/// <param name="resultMessage">メッセージ</param>
/// <param name="encodingType">文字コード</param>
/// <returns>成否</returns>
public static bool WriteAllText(string allLineText, string filePath, out string resultMessage, EncodingUxer.EncodingType encodingType = EncodingUxer.EncodingType.Utf8WithoutBom)
{
resultMessage = string.Empty;
try
{
System.IO.File.WriteAllText(filePath, allLineText, EncodingUxer.GetEncoding(encodingType));
return true;
}
catch (Exception ex)
{
resultMessage = $"CSV出力に失敗しました。[ファイルパス:{filePath},エラー内容:{ex.Message}]";
return false;
}
}
public static bool TryDeletePatternFiles(
string folderPath,
string fileNamePattern,
out int fileCount,
out string resultMessage)
{
fileCount = 0;
resultMessage = string.Empty;
if (!Directory.Exists(folderPath))
{
resultMessage = $"フォルダが存在しません。[フォルダパス:{folderPath}]";
return false;
}
try
{
var files = Directory.GetFiles(folderPath, fileNamePattern);
foreach (var filePath in files)
{
System.IO.File.Delete(filePath);
fileCount++;
}
return true;
}
catch (Exception ex)
{
resultMessage = $"ファイル削除中にエラーが発生しました。[フォルダパス:{folderPath},ファイル名パターン:{fileNamePattern},エラー内容:{ex.Message}]";
return false;
}
}
public static string GetTimestampedFileName(string originalName, DateTime dt, string prefixDtFormat, string suffixDtFormat)
{
string nameWithoutExt = Path.GetFileNameWithoutExtension(originalName);
string ext = Path.GetExtension(originalName);
string prefixDtStr = dt.ToString(prefixDtFormat);
string suffixDtStr = dt.ToString(suffixDtFormat);
string newName = prefixDtStr + nameWithoutExt + suffixDtStr;
return newName + ext;
}
public static bool CheckParentFolderExists(string folderPath, out string parentPath)
{
parentPath = Path.GetDirectoryName(folderPath);
return Directory.Exists(parentPath);
}
public static bool TryApplyActionToFiles<T>(
string folderPath,
Func<FileInfo, bool> condition,
Action<FileInfo> action,
out int fileCount,
out string resultMessage,
string actionName = "操作",
bool isDescending = true,
Func<FileInfo, T> sortKey = null,
int skip = 0)
{
fileCount = 0;
resultMessage = string.Empty;
try
{
// 条件未指定時は全件対象
condition = condition ?? (_ => true);
// 一旦条件で取得
var files = new DirectoryInfo(folderPath)
.GetFiles()
.Where(condition);
// ソートキー作成
var keySelector =
sortKey != null ? (Func<FileInfo, object>)
(f => sortKey(f)) : f => f.LastWriteTime;
// ソート+スキップ+リスト化
var filesList =
(isDescending ?
files.OrderByDescending(keySelector) :
files.OrderBy(keySelector))
.Skip(skip)
.ToList();
foreach (var file in filesList)
{
action(file);
LoggerUxer.Info($"{actionName}しました。[{file}]");
}
fileCount = filesList.Count;
return true;
}
catch (Exception ex)
{
resultMessage = $"ファイル群の{actionName}に失敗しました。[エラー内容:{ex.Message}]";
return false;
}
}
}
}
+206
View File
@@ -0,0 +1,206 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.IO.File
{
public static class JsonFileUxer
{
/// <summary>
/// JSONファイルのピンポイント1項目更新
/// </summary>
/// <param name="path">JSONファイルパス</param>
/// <param name="jsonPath">JSONノードパス</param>
/// <param name="newValue">更新値</param>
/// <exception cref="InvalidOperationException"></exception>
public static void UpdateJsonKeyAtomic(string path, string jsonPath, object newValue)
{
//// 使い方例:パスワード更新
//JsonFiileUxer.UpdateJsonKeyAtomic("config.json", "app.auth.password", "new_pw_2026-01");
var jtoken = JToken.FromObject(newValue);
// 1) 読み込み(UTF-8
var json = System.IO.File.ReadAllText(path, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
var jo = JObject.Parse(json);
// 2) ピンポイント更新(途中が無ければ作る)
var token = jo.SelectToken(jsonPath);
if (token is null)
{
// 例: "app.auth.password" を分解して動的に作る
var parts = jsonPath.Split('.');
JToken cur = jo;
for (int i = 0; i < parts.Length; i++)
{
var name = parts[i];
var obj = cur as JObject ?? throw new InvalidOperationException("親がオブジェクトではありません");
if (i == parts.Length - 1)
{
obj[name] = jtoken;
}
else
{
if (obj[name] == null) obj[name] = new JObject();
cur = obj[name];
}
}
}
else
{
token.Replace(jtoken);
}
// 3) 一時ファイルへ書き出し
var dir = System.IO.Path.GetDirectoryName(path) ?? ".";
var tmp = System.IO.Path.Combine(dir, ".tmp_config.json");
var backup = path + $"_{DateTime.Now.ToString("yyyyMMddHHmmss")}" + ".bak";
//var output = jo.ToString(Formatting.Indented) + Environment.NewLine;
var output = JsonConvert.SerializeObject(jo, Formatting.Indented) + Environment.NewLine;
System.IO.File.WriteAllText(tmp, output, new UTF8Encoding(false));
// 4) バックアップ作成 → 原子置換
if (System.IO.File.Exists(path)) System.IO.File.Copy(path, backup, overwrite: true);
System.IO.File.Replace(tmp, path, backup);
}
/// <summary>
/// JSONファイルから、jsonPathに一致する単一項目を取得します。
/// 取得に成功したら true を返し、 out value に JToken を設定します。
/// キーが見つからない・JSON無効・ファイル無し等は false を返し、 value は null。
/// </summary>
public static bool TryGetJsonKey(string path, string jsonPath, out JToken value)
{
value = null;
// 1) 読み込み(UTF-8 BOMなし)
string json;
try
{
json = System.IO.File.ReadAllText(path, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
}
catch (Exception)
{
// ファイルがない/読み取り不可
return false;
}
// 2) 解析
JObject jo;
try
{
jo = JObject.Parse(json);
}
catch (JsonReaderException)
{
// JSON不正
return false;
}
// 3) ピンポイント取得
// 例: "app.auth.password" / "items[0].name" / "users['alice'].age" 等
try
{
var token = jo.SelectToken(jsonPath);
if (token is null)
{
return false; // キー未存在
}
value = token; // JValue/JObject/JArray いずれもOK
return true;
}
catch (ArgumentException)
{
// JSONPathの書式誤り(SelectTokenが例外)
return false;
}
}
/// <summary>
/// 文字列として取得(JToken型を意識したくない場合の軽量ヘルパー)。
/// </summary>
public static bool TryGetJsonString(string path, string jsonPath, out string result)
{
result = null;
if (!TryGetJsonKey(path, jsonPath, out var token)) return false;
// JValue以外(オブジェクト/配列)の場合は ToString() を許容するか判断(ここではJValueのみ厳密)
if (token is JValue jv)
{
// 文字列ならそのまま
if (jv.Type == JTokenType.String)
{
result = (string)jv.Value;
return true;
}
// 数値・真偽・Null などは ToString() で返す設計でもOK
// ここでは文字列のみ厳密に true とします(お好みで分岐調整)
return false;
}
return false;
}
/// <summary>
/// 符号付き整数(Int64)で取得(intの範囲超えも想定)。
/// </summary>
public static bool TryGetJsonInt64(string path, string jsonPath, out long result)
{
result = default;
if (!TryGetJsonKey(path, jsonPath, out var token)) return false;
if (token is JValue jv)
{
// JValueが数値型なら long へ
if (jv.Type == JTokenType.Integer)
{
// Newtonsoftは内部的に long を持つのでキャスト可能
try
{
result = Convert.ToInt64(jv.Value);
return true;
}
catch
{
return false;
}
}
// 文字列数値を許可する場合("42" → 42
if (jv.Type == JTokenType.String && long.TryParse((string)jv.Value, out var parsed))
{
result = parsed;
return true;
}
}
return false;
}
/// <summary>
/// 任意型の既定値付き取得(存在しなければ defaultValue を返す)。
/// 例:GetJsonKeyOrDefault(path, "app.auth.retries", 3)
/// </summary>
public static T GetJsonKeyOrDefault<T>(string path, string jsonPath, T defaultValue)
{
if (!TryGetJsonKey(path, jsonPath, out var token) || token is null)
return defaultValue;
try
{
// JToken → 任意型に変換(失敗時は既定値)
var val = token.ToObject<T>();
return val == null ? defaultValue : val;
}
catch
{
return defaultValue;
}
}
}
}
+174
View File
@@ -0,0 +1,174 @@
using KssSmaPlaLib.Commons;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.IO.File
{
public static class PathUxer
{
public static string CreateFullPathEx(
string folderPath,
string fileName,
string dtPrefix = "",
string dtSuffix = "")
{
DateTime now = DateTime.Now;
// フォルダ:未指定時はカレントフォルダ
folderPath = string.IsNullOrEmpty(folderPath) ? "." : folderPath;
// ファイル名:未指定時は"noname.txt"とする
fileName = string.IsNullOrEmpty(fileName) ? "noname.txt" : fileName;
if (fileName.IndexOf('.') == -1)
{
// 拡張子がないとき、付与する
fileName += ".txt";
}
// ファイルパス
var path = Path.Combine(
Path.GetFullPath(folderPath),
(string.IsNullOrEmpty(dtPrefix) ? "" : now.ToString(dtPrefix)) +
fileName.Split('.')[0] +
(string.IsNullOrEmpty(dtSuffix) ? "" : now.ToString(dtSuffix)) +
"." +
fileName.Split('.')[1]);
return path;
}
public static string CombineUnixPath(params string[] parts)
{
return string.Join("/", parts.Select(p => p.Trim('/')));
}
/// <summary>
/// ファイル名(パス不可)を受け取り、存在すればフルパスを返す。
/// 探索順:①このDLLのフォルダ → ②エントリEXEのフォルダ → ③AppDomain.BaseDirectory
/// (C)昼コパソフトウェア㈱
/// </summary>
/// <param name="fileName">パスではないファイル名のみ(例: "config.json")。</param>
/// <param name="fullPath">見つかったファイルのフルパス。未発見時は null。</param>
/// <returns>発見した場合 true、未発見の場合 false。</returns>
public static bool TryResolveInAssemblyFolder(string fileName, out string fullPath)
{
fullPath = null;
// --- ガード:パスを排除(「ファイル名のみ」の前提を厳守) ---
if (string.IsNullOrWhiteSpace(fileName))
return false;
// ディレクトリ成分が入っていたら拒否
if (!string.Equals(fileName, Path.GetFileName(fileName), StringComparison.Ordinal))
return false;
// 予約文字の簡易チェック(Windows前提の一般的なNG文字)
foreach (var ch in Path.GetInvalidFileNameChars())
{
if (fileName.IndexOf(ch) >= 0)
return false;
}
// --- ① このメソッドを含むライブラリ(DLL)のフォルダ ---
var dllFolder = SafeGetDirectoryName(SafeGetAssemblyLocation(Assembly.GetExecutingAssembly()));
if (TryCombineAndExists(dllFolder, fileName, out fullPath))
return true;
// --- ② エントリアセンブリ(EXE)のフォルダ ---
string exeFolder = null;
var entry = Assembly.GetEntryAssembly();
if (entry != null)
{
exeFolder = SafeGetDirectoryName(SafeGetAssemblyLocation(entry));
}
else
{
// サービスや特殊ホストで EntryAssembly が null の場合のフォールバック
try
{
exeFolder = SafeGetDirectoryName(Process.GetCurrentProcess()?.MainModule?.FileName);
}
catch
{
// 取れないケースもあるので無理せず次へ
exeFolder = null;
}
}
if (TryCombineAndExists(exeFolder, fileName, out fullPath))
return true;
// --- ③ AppDomain 基準(ClickOnce等のケースでも安定) ---
var baseDir = AppDomain.CurrentDomain?.BaseDirectory;
if (TryCombineAndExists(baseDir, fileName, out fullPath))
return true;
// --- 未発見 ---
fullPath = null;
return false;
}
/// <summary>
/// 指定フォルダに fileName を結合し、存在すれば out に設定して true。
/// </summary>
private static bool TryCombineAndExists(string folder, string fileName, out string path)
{
path = null;
if (string.IsNullOrWhiteSpace(folder))
return false;
try
{
var candidate = Path.Combine(folder, fileName);
if (System.IO.File.Exists(candidate))
{
path = candidate;
return true;
}
}
catch
{
// パス結合や存在確認で例外が出てもスキップして未発見扱い
}
return false;
}
/// <summary>
/// Assembly.Location を安全に取得(Reflection-only / 影響ケースを考慮)。
/// </summary>
private static string SafeGetAssemblyLocation(Assembly asm)
{
try
{
return asm?.Location;
}
catch
{
return null;
}
}
/// <summary>
/// DirectoryName を安全に取得。
/// </summary>
private static string SafeGetDirectoryName(string path)
{
try
{
return string.IsNullOrEmpty(path) ? null : Path.GetDirectoryName(path);
}
catch
{
return null;
}
}
}
}
+21
View File
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.InBox
{
// インターフェース定義
public interface IFilterUxer<T>
{
// 単一:候補がフィルタを通過できるか?
bool CanPass(string candidate);
// 複数:1件でも通過できるか?(ガード句向け)
bool HasAnyPass(IEnumerable<string> candidates);
// 複数:通過したものだけを返す(既存流儀)
IEnumerable<string> ApplyFilter(IEnumerable<string> candidates);
}
}
+42
View File
@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.InBox
{
public class LineFilterUxer : IFilterUxer<string>
{
private readonly HashSet<string> includedLines;
private readonly HashSet<string> excludedLines;
public LineFilterUxer(IEnumerable<string> included, IEnumerable<string> excluded)
{
includedLines = new HashSet<string>(included ?? Enumerable.Empty<string>());
excludedLines = new HashSet<string>(excluded ?? Enumerable.Empty<string>());
}
public IEnumerable<string> ApplyFilter(IEnumerable<string> lineNames)
{
if (includedLines.Any())
{
// Included優先 → lineNamesの中でincludedに含まれるものだけ返す
return lineNames.Where(name => includedLines.Contains(name));
}
// Excluded適用 → lineNamesの中でexcludedに含まれないものだけ返す
return lineNames.Where(name => !excludedLines.Contains(name));
}
public bool CanPass(string lineName)
{
return HasAnyPass(new[] { lineName });
}
public bool HasAnyPass(IEnumerable<string> candidates)
{
return ApplyFilter(candidates).Any();
}
}
}
+72
View File
@@ -0,0 +1,72 @@
using KssSmaPlaLib.Commons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.InBox
{
public class SheetFilterUxer : IFilterUxer<string>
{
private readonly HashSet<string> includedSheets;
private readonly HashSet<string> excludedSheets;
public SheetFilterUxer(IEnumerable<string> included, IEnumerable<string> excluded)
{
includedSheets = new HashSet<string>(included ?? Enumerable.Empty<string>());
excludedSheets = new HashSet<string>(excluded ?? Enumerable.Empty<string>());
}
public IEnumerable<string> ApplyFilter(IEnumerable<string> sheetNames)
{
if (includedSheets.Any())
{
// Included優先 → lineNamesの中でincludedに含まれるものだけ返す
//return sheetNames.Where(name => includedSheets.Contains(name));
// ワイルドカード(*)ありとする!
List<string> listA = new List<string>();
foreach (var name in sheetNames)
{
foreach (var iName in includedSheets)
{
if (StringUxer.WildcardMatch(name, iName))
{
listA.Add(name);
break;
}
}
}
return listA;
}
// Excluded適用 → lineNamesの中でexcludedに含まれないものだけ返す
//return sheetNames.Where(name => !excludedSheets.Contains(name));
// ワイルドカード(*)ありとする!
List<string> listB = new List<string>();
foreach (var name in sheetNames)
{
var isMatch = false;
foreach (var eName in excludedSheets)
{
if (StringUxer.WildcardMatch(name, eName))
{
isMatch = true;
break;
}
}
if (!isMatch) listB.Add(name);
}
return listB;
}
public bool CanPass(string sheetName)
{
return HasAnyPass(new[] { sheetName });
}
public bool HasAnyPass(IEnumerable<string> sheetNames)
{
return ApplyFilter(sheetNames).Any();
}
}
}
+15
View File
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Ini
{
public class IniDto
{
public string Section { get; set; } = string.Empty;
public string Key { get; set; } = string.Empty;
public string Value { get; set; } = string.Empty;
}
}
+147
View File
@@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Ini
{
public static class IniHelper
{
public const string INI_PATH = @".\Settings.ini";
public static List<IniDto> IniList = new List<IniDto>();
// Win32 API宣言
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern int GetPrivateProfileString(
string lpAppName,
string lpKeyName,
string lpDefault,
StringBuilder lpReturnedString,
int nSize,
string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern bool WritePrivateProfileString(
string lpAppName,
string lpKeyName,
string lpString,
string lpFileName);
/// <summary>
/// INIファイルから値を読み込み(セクション+キー指定)
/// </summary>
public static string ReadValue(string iniPath, string section, string key, string defaultValue = "")
{
// もしINIリストにあったら、そこから返す
var value = IniList
.FirstOrDefault(m => m.Section == section && m.Key == key)
?.Value;
if (value != null) return (string)value;
if (string.IsNullOrEmpty(iniPath)) iniPath = INI_PATH;
var sb = new StringBuilder(1024);
GetPrivateProfileString(section, key, defaultValue, sb, sb.Capacity, iniPath);
var str = sb.ToString();
str = string.IsNullOrEmpty(str) ? defaultValue : str;
return str;
}
/// <summary>
/// bool値の読み込み
/// </summary>
/// <param name="iniPath"></param>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static bool ReadBoolValue(string iniPath, string section, string key, bool defaultValue = false)
{
var str = ReadValue(iniPath, section, key, defaultValue.ToString());
var boolValue = bool.TryParse(str, out var b) ? b : defaultValue;
return boolValue;
}
/// <summary>
/// 日付値の読み込み
/// </summary>
public static DateTime ReadDateValue(string iniPath, string section, string key, DateTime? defaultDate = null)
{
var defDate = defaultDate ?? DateTime.MinValue;
var str = ReadValue(iniPath, section, key, defDate.ToString("yyyy/MM/dd"));
var dateValue = DateTime.TryParse(str, out var d) ? d : defDate;
return dateValue;
}
/// <summary>
/// INIファイルに値を書き込み(セクション+キー+値指定)
/// </summary>
public static bool WriteValue(string iniPath, string section, string key, string value)
{
if (string.IsNullOrEmpty(iniPath)) iniPath = INI_PATH;
return WritePrivateProfileString(section, key, value, iniPath);
}
/// <summary>
/// bool値の書き込み
/// </summary>
/// <param name="iniPath"></param>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool WriteBoolValue(string iniPath, string section, string key, bool value)
{
return WriteValue(iniPath, section, key, value.ToString());
}
/// <summary>
/// 日付値の書き込み
/// </summary>
/// <param name="iniPath"></param>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool WriteDateValue(string iniPath, string section, string key, DateTime value)
{
return WriteValue(iniPath, section, key, value.ToString("yyyy/MM/dd"));
}
public static string OpenIni(string initialFolderPath = "")
{
using (var dlg = new OpenFileDialog())
{
dlg.Multiselect = false;
dlg.Title = "Settings.ini ファイルを選択してください。";
dlg.AddExtension = true;
dlg.CheckFileExists = true;
dlg.CheckPathExists = true;
dlg.RestoreDirectory = true;
dlg.Filter = "設定ファイル(*.ini)|*.ini";
if (!string.IsNullOrEmpty(initialFolderPath))
{
// 最初に見せるフォルダ(デスクトップなど)
dlg.InitialDirectory = initialFolderPath;
}
// ダイアログを表示して「OK」が押されたら処理
if (dlg.ShowDialog() == DialogResult.Cancel) return string.Empty;
// 選択されたファイルのパスを取得
return dlg.FileName;
}
}
public static object ReadValue(object value, string name, object iNI_KEY_ITAKUSAKI_MEI, string v)
{
throw new NotImplementedException();
}
}
}
+55
View File
@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KssSmaPlaLib.Commons;
namespace KssSmaPlaLib.Ini
{
/// <summary>
/// INIリーダー
/// </summary>
public static class IniReaderUxer
{
/// <summary>
/// 指定セクションのINI値読み込み
/// </summary>
/// <param name="path">INIパス</param>
/// <param name="section">セクション</param>
/// <returns>指定のディクショナリ</returns>
public static Dictionary<string, string> ReadSection(string path, string section)
{
var result = new Dictionary<string, string>();
var lines = File.ReadAllLines(path, System.Text.Encoding.GetEncoding("shift_jis"));
bool inSection = false;
foreach (var line in lines)
{
var trimmed = line.Trim();
// コメント行は飛ばす
if (trimmed.StartsWith(";")) continue;
if (trimmed.StartsWith("[") && trimmed.EndsWith("]"))
inSection = trimmed == $"[{section}]";
else if (inSection && trimmed.Contains("="))
{
var index = trimmed.IndexOf('=');
if (index > 0)
{
var key = trimmed.Substring(0, index).Trim();
var value = trimmed.Substring(index + 1).Trim();
result[key] = value;
}
}
}
return result;
}
public static bool IsEmptyByIniDic(Dictionary<string,string> iniDic,string key)
{
return string.IsNullOrEmpty(DictionaryUxer.GetValueOrDefault(iniDic, key, string.Empty));
}
}
}
+75
View File
@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Ini
{
public static class IniReferenceResolveUxer
{
public static Dictionary<string, string> ReadSectionWithReference(string path, string section, int maxDepth = 3)
{
var allLines = File.ReadAllLines(path, System.Text.Encoding.GetEncoding("shift_jis"));
var allSections = ParseAllSections(allLines);
var result = new Dictionary<string, string>();
if (!allSections.ContainsKey(section)) return result;
foreach (var kvp in allSections[section])
{
result[kvp.Key] = ResolveValue(allSections, kvp.Value, maxDepth);
}
return result;
}
private static Dictionary<string, Dictionary<string, string>> ParseAllSections(string[] lines)
{
var sections = new Dictionary<string, Dictionary<string, string>>();
string currentSection = null;
foreach (var line in lines)
{
var trimmed = line.Trim();
if (trimmed.StartsWith(";") || string.IsNullOrEmpty(trimmed)) continue;
if (trimmed.StartsWith("[") && trimmed.EndsWith("]"))
{
currentSection = trimmed.Substring(1, trimmed.Length - 2);
sections[currentSection] = new Dictionary<string, string>();
}
else if (currentSection != null && trimmed.Contains("="))
{
var index = trimmed.IndexOf('=');
var key = trimmed.Substring(0, index).Trim();
var value = trimmed.Substring(index + 1).Trim();
sections[currentSection][key] = value;
}
}
return sections;
}
private static string ResolveValue(Dictionary<string, Dictionary<string, string>> sections, string value, int depth)
{
if (depth <= 0 || string.IsNullOrEmpty(value)) return value;
var match = System.Text.RegularExpressions.Regex.Match(value, @"^\{\[(.+?)\](.+?)\}$");
if (match.Success)
{
var refSection = match.Groups[1].Value;
var refKey = match.Groups[2].Value;
if (sections.ContainsKey(refSection) && sections[refSection].ContainsKey(refKey))
{
var nextValue = sections[refSection][refKey];
return ResolveValue(sections, nextValue, depth - 1);
}
}
return value;
}
}
}
+106
View File
@@ -0,0 +1,106 @@
namespace KssSmaPlaLib.Input.Gamen
{
partial class NumericInputForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.CancelButton2 = new System.Windows.Forms.Button();
this.OkButton = new System.Windows.Forms.Button();
this.NumericUpDownNumeric = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.NumericUpDownNumeric)).BeginInit();
this.SuspendLayout();
//
// CancelButton2
//
this.CancelButton2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.CancelButton2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CancelButton2.Location = new System.Drawing.Point(255, 50);
this.CancelButton2.Name = "CancelButton2";
this.CancelButton2.Size = new System.Drawing.Size(170, 53);
this.CancelButton2.TabIndex = 2;
this.CancelButton2.Text = "キャンセル";
this.CancelButton2.UseVisualStyleBackColor = true;
//
// OkButton
//
this.OkButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.OkButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.OkButton.Location = new System.Drawing.Point(79, 50);
this.OkButton.Name = "OkButton";
this.OkButton.Size = new System.Drawing.Size(170, 53);
this.OkButton.TabIndex = 1;
this.OkButton.Text = "OK";
this.OkButton.UseVisualStyleBackColor = true;
this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
//
// NumericUpDownNumeric
//
this.NumericUpDownNumeric.Dock = System.Windows.Forms.DockStyle.Fill;
this.NumericUpDownNumeric.Location = new System.Drawing.Point(0, 0);
this.NumericUpDownNumeric.Maximum = new decimal(new int[] {
-727379969,
232,
0,
0});
this.NumericUpDownNumeric.Minimum = new decimal(new int[] {
1316134911,
2328,
0,
-2147483648});
this.NumericUpDownNumeric.Name = "NumericUpDownNumeric";
this.NumericUpDownNumeric.Size = new System.Drawing.Size(437, 49);
this.NumericUpDownNumeric.TabIndex = 0;
this.NumericUpDownNumeric.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// NumericInputForm
//
this.AcceptButton = this.OkButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(19F, 42F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.CancelButton2;
this.ClientSize = new System.Drawing.Size(437, 115);
this.Controls.Add(this.NumericUpDownNumeric);
this.Controls.Add(this.OkButton);
this.Controls.Add(this.CancelButton2);
this.Font = new System.Drawing.Font("メイリオ", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7);
this.Name = "NumericInputForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "数値入力";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.NumericInputForm_FormClosing);
this.Load += new System.EventHandler(this.NumericInputForm_Load);
((System.ComponentModel.ISupportInitialize)(this.NumericUpDownNumeric)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button CancelButton2;
private System.Windows.Forms.Button OkButton;
private System.Windows.Forms.NumericUpDown NumericUpDownNumeric;
}
}
+41
View File
@@ -0,0 +1,41 @@
using KssSmaPlaLib.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Core.Mapping;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Input.Gamen
{
public partial class NumericInputForm : Form
{
public decimal NumericNumeric { get; set; } = 0;
public NumericInputForm(decimal numeric)
{
InitializeComponent();
NumericUpDownNumeric.Value = numeric;
}
private void NumericInputForm_Load(object sender, EventArgs e)
{
FormHelper.LoadFormBounds(this);
}
private void NumericInputForm_FormClosing(object sender, FormClosingEventArgs e)
{
FormHelper.SaveFormBounds(this);
}
private void OkButton_Click(object sender, EventArgs e)
{
NumericNumeric = NumericUpDownNumeric.Value;
}
}
}
+120
View File
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
+95
View File
@@ -0,0 +1,95 @@
namespace KssSmaPlaLib.Input.Gamen
{
partial class TextInputForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.TextText = new System.Windows.Forms.TextBox();
this.CancelButton2 = new System.Windows.Forms.Button();
this.OkButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// TextText
//
this.TextText.Dock = System.Windows.Forms.DockStyle.Fill;
this.TextText.Location = new System.Drawing.Point(0, 0);
this.TextText.Name = "TextText";
this.TextText.Size = new System.Drawing.Size(437, 49);
this.TextText.TabIndex = 0;
//
// CancelButton2
//
this.CancelButton2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.CancelButton2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CancelButton2.Location = new System.Drawing.Point(255, 50);
this.CancelButton2.Name = "CancelButton2";
this.CancelButton2.Size = new System.Drawing.Size(170, 53);
this.CancelButton2.TabIndex = 1;
this.CancelButton2.Text = "キャンセル";
this.CancelButton2.UseVisualStyleBackColor = true;
//
// OkButton
//
this.OkButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.OkButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.OkButton.Location = new System.Drawing.Point(79, 50);
this.OkButton.Name = "OkButton";
this.OkButton.Size = new System.Drawing.Size(170, 53);
this.OkButton.TabIndex = 2;
this.OkButton.Text = "OK";
this.OkButton.UseVisualStyleBackColor = true;
this.OkButton.Click += new System.EventHandler(this.OkButton_Click);
//
// TextInputForm
//
this.AcceptButton = this.OkButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(19F, 42F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.CancelButton2;
this.ClientSize = new System.Drawing.Size(437, 115);
this.Controls.Add(this.OkButton);
this.Controls.Add(this.CancelButton2);
this.Controls.Add(this.TextText);
this.Font = new System.Drawing.Font("メイリオ", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7);
this.Name = "TextInputForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "テキスト入力";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.TextInputForm_FormClosing);
this.Load += new System.EventHandler(this.TextInputForm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox TextText;
private System.Windows.Forms.Button CancelButton2;
private System.Windows.Forms.Button OkButton;
}
}
+42
View File
@@ -0,0 +1,42 @@
using KssSmaPlaLib.Forms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Core.Mapping;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KssSmaPlaLib.Input.Gamen
{
public partial class TextInputForm : Form
{
public string EditedText { get; set; } = string.Empty;
public TextInputForm(string text, char passwordChar = (char)0)
{
InitializeComponent();
TextText.PasswordChar = passwordChar;
TextText.Text = text;
}
private void TextInputForm_Load(object sender, EventArgs e)
{
FormHelper.LoadFormBounds(this);
}
private void TextInputForm_FormClosing(object sender, FormClosingEventArgs e)
{
FormHelper.SaveFormBounds(this);
}
private void OkButton_Click(object sender, EventArgs e)
{
EditedText = TextText.Text;
}
}
}
+120
View File
@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
+233
View File
@@ -0,0 +1,233 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\EntityFramework.6.5.1\build\EntityFramework.props" Condition="Exists('..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\EntityFramework.6.5.1\build\EntityFramework.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4136CE96-10AA-4B55-B49F-68C80E9E3BC8}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>KssSmaPlaLib</RootNamespace>
<AssemblyName>KssSmaPlaLib</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>ラッキイ青透過版(せり様).ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualBasic" />
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Numerics" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="Alert\FullScreenAlertUxer.cs" />
<Compile Include="Alert\Gamen\AlertForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Alert\ToastUxer.cs" />
<Compile Include="Alert\WindowFlasherUxer.cs" />
<Compile Include="Backup\FileBackupUxer.cs" />
<Compile Include="Cleanup\FileCleanupUxer.cs" />
<Compile Include="Commons\Conversion\KanaConvertUxer.cs" />
<Compile Include="Commons\DateHelperUxer.cs" />
<Compile Include="Commons\DictionaryUxer.cs" />
<Compile Include="DtoMapping\Attributes\ExcelColumnLetterAttribute.cs" />
<Compile Include="Encryption\FIleEncryptUxer.cs" />
<Compile Include="Forms\ColorHelper.cs" />
<Compile Include="Forms\ContextMenuFunction\FontUxer.cs" />
<Compile Include="Forms\ContextMenuFunction\Gamen\DgvColumnEditorForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Forms\ContextMenuFunction\Gamen\DgvColumnEditorForm.Designer.cs">
<DependentUpon>DgvColumnEditorForm.cs</DependentUpon>
</Compile>
<Compile Include="Forms\ContextMenuHelper.cs" />
<Compile Include="Forms\Controls\PoiDgv.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Forms\Controls\PoiMainForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Forms\DataGridViewExporter.cs" />
<Compile Include="Forms\DatePickerHelper.cs" />
<Compile Include="Forms\DgvHelper.cs" />
<Compile Include="Forms\FormHelper.cs" />
<Compile Include="Forms\ToastNotifier.cs" />
<Compile Include="InBox\IFilterUxer.cs" />
<Compile Include="InBox\SheetFilterUxer.cs" />
<Compile Include="InBox\LineFilterUxer.cs" />
<Compile Include="Ini\IniDto.cs" />
<Compile Include="Ini\IniHelper.cs" />
<Compile Include="Ini\IniReaderUxer.cs" />
<Compile Include="Commons\IntUxer.cs" />
<Compile Include="Commons\LoggerUxer.cs" />
<Compile Include="Commons\RetCodeUxer.cs" />
<Compile Include="Commons\StringUxer.cs" />
<Compile Include="Communications\SftpUxer.cs" />
<Compile Include="Ini\IniReferenceResolveUxer.cs" />
<Compile Include="Input\Gamen\NumericInputForm.Designer.cs">
<DependentUpon>NumericInputForm.cs</DependentUpon>
</Compile>
<Compile Include="Input\Gamen\NumericInputForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Input\Gamen\TextInputForm.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Input\Gamen\TextInputForm.Designer.cs">
<DependentUpon>TextInputForm.cs</DependentUpon>
</Compile>
<Compile Include="IO\Database\DbUxer.cs" />
<Compile Include="Encryption\SimpleEncryptUxer.cs" />
<Compile Include="IO\Excel\ExcelCellValidatorUxer.cs" />
<Compile Include="IO\Excel\ExcelColumnHelperUxer.cs" />
<Compile Include="IO\Excel\XlUxer.cs" />
<Compile Include="Exchange\CsvDbSyncUxer.cs" />
<Compile Include="IO\File\CSVUxer.cs" />
<Compile Include="Commons\EncodingUxer.cs" />
<Compile Include="IO\File\FileUxer.cs" />
<Compile Include="Exchange\Interfaces\ICsvExportableUxer.cs" />
<Compile Include="IO\File\JsonFileUxer.cs" />
<Compile Include="IO\File\PathUxer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Batch\Backup\BackupStepHandlerUxer.cs" />
<Compile Include="Batch\Cleanup\CleanupStepHandlerUxer.cs" />
<Compile Include="Batch\Commons\CommonUxer.cs" />
<Compile Include="Batch\Dispatch\StepDispatcherUxer.cs" />
<Compile Include="Batch\DTO\StepDto.cs" />
<Compile Include="Batch\DTO\StepInfoDto.cs" />
<Compile Include="Batch\Exchange\CsvToDbStepHandlerUxer.cs" />
<Compile Include="Batch\Interface\IFuncResultDto.cs" />
<Compile Include="Batch\IO\FileStepHandlerUxer.cs" />
<Compile Include="Batch\Log\StepLogUxer.cs" />
<Compile Include="Batch\Sftp\SftpStepHandlerUxer.cs" />
<Compile Include="Batch\StepInfo\StepInfoUxer.cs" />
<Compile Include="Commons\VariableUxer.cs" />
<Compile Include="AutoTest\Command\Alias\CommandAliasUxer.cs" />
<Compile Include="AutoTest\Command\Alias\Ini\IniReaderUxer.cs" />
<Compile Include="AutoTest\Command\Alias\Loader\CommandAliasLoaderUxer.cs" />
<Compile Include="AutoTest\Command\Definition\CommandEnumUxer.cs" />
<Compile Include="AutoTest\Command\Definition\CommandParserUxer.cs" />
<Compile Include="AutoTest\Command\Translator\CommandTranslatorUxer.cs" />
<Compile Include="AutoTest\Core\StepTestRunnerUxer.cs" />
<Compile Include="AutoTest\Core\TestModeInitializerUxer.cs" />
<Compile Include="AutoTest\Core\TestModeUxer.cs" />
<Compile Include="AutoTest\Script\Load\LoadTryUxer.cs" />
<Compile Include="AutoTest\Script\Models\ParsedStepDTO.cs" />
<Compile Include="AutoTest\Script\Models\StepDTO.cs" />
<Compile Include="AutoTest\Script\Models\StepInfoDTO.cs" />
<Compile Include="AutoTest\Script\Parse\Function\FunctionTryUxer.cs" />
<Compile Include="AutoTest\Script\Parse\ParseTryUxer.cs" />
<Compile Include="AutoTest\Script\Storage\TestScriptStorageUxer.cs" />
<Compile Include="Tools\ClaraHack\NamespaceAdjust\NamespaceAdjusterUxer.cs" />
<Compile Include="Tools\FileHack\MergeSplitFilesUxer.cs" />
<Compile Include="Tools\FileHack\SplitFileBySizeUxer.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="CL_設計別府条項.md" />
</ItemGroup>
<ItemGroup>
<Folder Include="AutoTest\Db\" />
<Folder Include="AutoTest\Ui\" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Alert\Gamen\AlertForm.resx">
<DependentUpon>AlertForm.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\ContextMenuFunction\Gamen\DgvColumnEditorForm.resx">
<DependentUpon>DgvColumnEditorForm.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Forms\Controls\PoiDgv.resx">
<DependentUpon>PoiDgv.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Input\Gamen\NumericInputForm.resx">
<DependentUpon>NumericInputForm.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Input\Gamen\TextInputForm.resx">
<DependentUpon>TextInputForm.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="ClosedXML">
<Version>0.105.0</Version>
</PackageReference>
<PackageReference Include="EntityFramework">
<Version>6.5.1</Version>
</PackageReference>
<PackageReference Include="EntityFramework6.Npgsql">
<Version>3.1.1</Version>
</PackageReference>
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications">
<Version>7.1.3</Version>
</PackageReference>
<PackageReference Include="Microsoft.VisualBasic">
<Version>10.3.0</Version>
</PackageReference>
<PackageReference Include="Newtonsoft.Json">
<Version>13.0.4</Version>
</PackageReference>
<PackageReference Include="Npgsql">
<Version>4.1.8</Version>
</PackageReference>
<PackageReference Include="Serilog">
<Version>4.3.0</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.Console">
<Version>6.0.0</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.File">
<Version>7.0.0</Version>
</PackageReference>
<PackageReference Include="SSH.NET">
<Version>2025.0.0</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Content Include="ラッキイ青透過版(せり様).ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\Serilog.4.3.0\build\Serilog.targets" Condition="Exists('..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\Serilog.4.3.0\build\Serilog.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>このプロジェクトは、このコンピューター上にない NuGet パッケージを参照しています。それらのパッケージをダウンロードするには、[NuGet パッケージの復元] を使用します。詳細については、http://go.microsoft.com/fwlink/?LinkID=322105 を参照してください。見つからないファイルは {0} です。</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\Serilog.4.3.0\build\Serilog.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\Serilog.4.3.0\build\Serilog.targets'))" />
<Error Condition="!Exists('..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\EntityFramework.6.5.1\build\EntityFramework.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\EntityFramework.6.5.1\build\EntityFramework.props'))" />
<Error Condition="!Exists('..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\EntityFramework.6.5.1\build\EntityFramework.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\EntityFramework.6.5.1\build\EntityFramework.targets'))" />
</Target>
<Import Project="..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\EntityFramework.6.5.1\build\EntityFramework.targets" Condition="Exists('..\..\溶接加工ツール\src\ExcelToCsvToDb\packages\EntityFramework.6.5.1\build\EntityFramework.targets')" />
</Project>
+25
View File
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36401.2 d17.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KssSmaPlaLib", "KssSmaPlaLib.csproj", "{4136CE96-10AA-4B55-B49F-68C80E9E3BC8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4136CE96-10AA-4B55-B49F-68C80E9E3BC8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4136CE96-10AA-4B55-B49F-68C80E9E3BC8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4136CE96-10AA-4B55-B49F-68C80E9E3BC8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4136CE96-10AA-4B55-B49F-68C80E9E3BC8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {ABA22849-DFFB-4FFD-BCAF-E55D748F155A}
EndGlobalSection
EndGlobal
+40
View File
@@ -0,0 +1,40 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下を通して制御されます
// 制御されます。アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("KssSmaPlaLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("本田技研工業株式会社")]
[assembly: AssemblyProduct("KssSmaPlaLib")]
[assembly: AssemblyCopyright("Copyright © 本田技研工業株式会社 2025")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから
// 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("4136ce96-10aa-4b55-b49f-68c80e9e3bc8")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// リビジョン
//
[assembly: AssemblyVersion("1.0.8.0")]
[assembly: AssemblyFileVersion("1.0.8.0")]
// りれき💛
// 1.0.3.0 INIファイルパスをEXEパスにするためPathUxerにメソッド追加
// 1.0.4.0 ExcelToCsvToDb:新Excel書式対応
// 1.0.5.0 アラート画面:属性名変更メニューを追加
// 1.0.6.0 アラート画面:強烈モード調整
// 1.0.7.0 列編集画面のインデックス不正不具合修正
// 1.0.8.0 溶接ツール:新共通:DBの挿入前削除で対象データの再過去日から削除するよう修正
@@ -0,0 +1,95 @@
using KssSmaPlaLib.Encryption;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Tools.ClaraHack.NamespaceAdjust
{
public static class NamespaceAdjusterUxer
{
public static bool TuckIntoMain(string[] args)
{
if (args.Length != 3) return false;
if (args[0].ToLower() != "/namespaceadjuster") return false;
var projectTopFolderPath = args[1];
var projectName = args[2];
if (NamespaceAdjusterUxer.Try(
projectTopFolderPath,
projectName,
out var updatedCount,
out var resultMessage) == false)
{
Console.WriteLine(resultMessage);
}
else
{
Console.WriteLine($"namespace調整完了。[更新ファイル数:{updatedCount}]");
}
return true;
}
public static bool Try(
string projectRootPath,
string projectName,
out int updatedCount,
out string resultMessage)
{
updatedCount = 0;
resultMessage = string.Empty;
// フォルダバリデ
if (!Directory.Exists(projectRootPath))
{
resultMessage = $"プロジェクトルートフォルダが存在しません。[プロジェクトルートフォルダ:{projectRootPath}]";
return false;
}
// 配下全どり
var csFiles = Directory.GetFiles(
projectRootPath,
"*.cs",
SearchOption.AllDirectories);
foreach (var filePath in csFiles)
{
// トップ下相対フォルダパス
var relativeDir = Path.GetDirectoryName(filePath)?.Substring(projectRootPath.Length).TrimStart(Path.DirectorySeparatorChar);
// セパレータ変換('\'→'.'
var namespaceSuffix = relativeDir?.Replace(Path.DirectorySeparatorChar, '.');
// トップノード(PJ名)つけてフル化
var fullNamespace = string.IsNullOrEmpty(namespaceSuffix)
// PJ名のみ(カレントはトップ下)
? projectName
// PJ名+配下
: $"{projectName}.{namespaceSuffix}";
// フル読み
var content = File.ReadAllText(filePath);
// namespace行の置換
var newContent = Regex.Replace(
content,
@"namespace\s+[\w\.]+",
$"namespace {fullNamespace}");
if (newContent != content)
{
// 内容変わった時だけ書き込み
File.WriteAllText(filePath, newContent);
updatedCount++;
}
}
return true;
}
}
}
+63
View File
@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Tools.FileHack
{
public static class MergeSplitFilesUxer
{
public static bool TuckIntoMain(string[] args)
{
if (args.Length != 2) return false;
if (args[0].ToLower() != "/filemerge") return false;
var path = args[1];
if (!Try(path, out var messageForMe))
{
Console.WriteLine($"ファイル結合に失敗しました。[エラー内容:{messageForMe}]");
return false;
}
Console.WriteLine($"ファイル結合が成功しました。");
return true;
}
public static bool Try(string baseFilePath, out string resultMessage)
{
try
{
string folder = Path.GetDirectoryName(baseFilePath);
string fileName = Path.GetFileName(baseFilePath);
string outputPath = Path.Combine(folder, fileName);
int partNum = 1;
using (var output = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
{
while (true)
{
string partPath = Path.Combine(folder, $"{fileName}.{partNum:D3}");
if (!File.Exists(partPath)) break;
using (var input = new FileStream(partPath, FileMode.Open, FileAccess.Read))
{
input.CopyTo(output);
}
partNum++;
}
}
resultMessage = $"結合成功:{partNum - 1}個のパートを結合しました。";
return true;
}
catch (Exception ex)
{
resultMessage = $"結合失敗: {ex.Message}";
return false;
}
}
}
}
+69
View File
@@ -0,0 +1,69 @@
using KssSmaPlaLib.Tools.ClaraHack.NamespaceAdjust;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KssSmaPlaLib.Tools.FileHack
{
public static class SplitFileBySizeUxer
{
public static bool TuckIntoMain(string[] args)
{
if (args.Length != 3) return false;
if (args[0].ToLower() != "/filesplit") return false;
var path = args[1];
if (!int.TryParse(args[2], out var kb))
{
Console.WriteLine($"分割サイズ(KB)が数値でありません。[分割サイズ:{args[2]}]");
return false;
}
if (!Try(path, kb, out var messageForMe))
{
Console.WriteLine($"ファイル分割に失敗しました。[エラー内容:{messageForMe}]");
return false;
}
Console.WriteLine($"ファイル分割が成功しました。");
return true;
}
public static bool Try(string filePath, int sizeKB, out string resultMessage)
{
try
{
int partSize = sizeKB * 1024;
string folder = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileName(filePath);
int partNum = 1;
using (var input = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[partSize];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
string partPath = Path.Combine(folder, $"{fileName}.{partNum:D3}");
using (var output = new FileStream(partPath, FileMode.Create, FileAccess.Write))
{
output.Write(buffer, 0, bytesRead);
partNum++;
}
}
}
resultMessage = $"分割成功:{partNum - 1}個のパートに分割されました。";
return true;
}
catch (Exception ex)
{
resultMessage = $"分割失敗: {ex.Message}";
return false;
}
}
}
}
+58
View File
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.data>
<DbProviderFactories>
<add name="Npgsql Data Provider" invariant="Npgsql" description=".Net Framework Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql" />
</DbProviderFactories>
</system.data>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Serilog" publicKeyToken="24c2f752a8e58a10" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Npgsql" publicKeyToken="5d8b90d52f46fda7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.8.0" newVersion="4.1.8.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Bcl.AsyncInterfaces" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
</providers>
</entityFramework>
</configuration>
Binary file not shown.

After

Width:  |  Height:  |  Size: 228 KiB