diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/.gitignore @@ -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 \ No newline at end of file diff --git a/Alert/FullScreenAlertUxer.cs b/Alert/FullScreenAlertUxer.cs new file mode 100644 index 0000000..e3cd096 --- /dev/null +++ b/Alert/FullScreenAlertUxer.cs @@ -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); // モーダルで前面確実化 + } + } + } +} diff --git a/Alert/Gamen/AlertForm.cs b/Alert/Gamen/AlertForm.cs new file mode 100644 index 0000000..fa97486 --- /dev/null +++ b/Alert/Gamen/AlertForm.cs @@ -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; + + /// + /// コンストラクタ + /// + /// ログのエラー行 + /// 日時 + /// 強烈画面 + /// 自動で閉じる秒数 + 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); + } + + /// + /// フォームロード時 + /// + /// + /// + 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); + + } + + /// + /// ボーダーメニュークリック時 + /// + /// + /// + 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(); + } + } + + /// + /// タイトルメニュークリック時 + /// + /// + /// + 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, "重大エラー検知"); + } + + /// + /// フォーム閉じるとき + /// + /// + /// + 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; + } + } + + /// + /// 所属メニュークリック時 + /// + /// + /// + 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); + } + } + + /// + /// 強烈モードメニュークリック時 + /// + /// + /// + private void KyoretsuModeMenu_Click(object sender, EventArgs e) + { + IniHelper.WriteValue(null, this.Name, "KyoretsuMode", KyoretsuModeMenu.Checked ? "0" : "1"); + } + + /// + /// ポップアップメニュー開くとき + /// + /// + /// + 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; + // } + //} + } +} diff --git a/Alert/Gamen/AlertForm.resx b/Alert/Gamen/AlertForm.resx new file mode 100644 index 0000000..37ff906 --- /dev/null +++ b/Alert/Gamen/AlertForm.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/Alert/ToastUxer.cs b/Alert/ToastUxer.cs new file mode 100644 index 0000000..f1bf081 --- /dev/null +++ b/Alert/ToastUxer.cs @@ -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(); + } + } +} diff --git a/Alert/WindowFlasherUxer.cs b/Alert/WindowFlasherUxer.cs new file mode 100644 index 0000000..c43256b --- /dev/null +++ b/Alert/WindowFlasherUxer.cs @@ -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); + } + } +} diff --git a/AutoTest/Command/Alias/CommandAliasUxer.cs b/AutoTest/Command/Alias/CommandAliasUxer.cs new file mode 100644 index 0000000..c880db5 --- /dev/null +++ b/AutoTest/Command/Alias/CommandAliasUxer.cs @@ -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 _reverseMap = new Dictionary(); + + public static void SetAleiasDic(Dictionary dic) + { + _reverseMap = dic; + } + + public static bool TryTranslate(string userCommand, out CommandEnumUxer.Command command) + => _reverseMap.TryGetValue(userCommand, out command); + } +} diff --git a/AutoTest/Command/Alias/Ini/IniReaderUxer.cs b/AutoTest/Command/Alias/Ini/IniReaderUxer.cs new file mode 100644 index 0000000..7d8f9e4 --- /dev/null +++ b/AutoTest/Command/Alias/Ini/IniReaderUxer.cs @@ -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 dic, out string resultMessage) + { + dic = new Dictionary(); + 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; + } + } + } +} diff --git a/AutoTest/Command/Alias/Loader/CommandAliasLoaderUxer.cs b/AutoTest/Command/Alias/Loader/CommandAliasLoaderUxer.cs new file mode 100644 index 0000000..23cf8bb --- /dev/null +++ b/AutoTest/Command/Alias/Loader/CommandAliasLoaderUxer.cs @@ -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 Dictionarydic, out string resultMessage) + { + resultMessage = string.Empty; + + if (!IniReaderUxer.Try(COMMAND_ALIAS_FILE_PATH, out dic, out var messageForMe)) + { + resultMessage = messageForMe; + return false; + } + return true; + } + } +} diff --git a/AutoTest/Command/Definition/CommandEnumUxer.cs b/AutoTest/Command/Definition/CommandEnumUxer.cs new file mode 100644 index 0000000..1769652 --- /dev/null +++ b/AutoTest/Command/Definition/CommandEnumUxer.cs @@ -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 + { + /// + /// UIステップテストコマンド + /// + public enum Command + { + None, + Sleep, + SetText, + PushButton, + TryDbMoshimoshi + } + } +} diff --git a/AutoTest/Command/Definition/CommandParserUxer.cs b/AutoTest/Command/Definition/CommandParserUxer.cs new file mode 100644 index 0000000..f65b5aa --- /dev/null +++ b/AutoTest/Command/Definition/CommandParserUxer.cs @@ -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 _map = new Dictionary() + { + { "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); + } +} diff --git a/AutoTest/Command/Translator/CommandTranslatorUxer.cs b/AutoTest/Command/Translator/CommandTranslatorUxer.cs new file mode 100644 index 0000000..15ad947 --- /dev/null +++ b/AutoTest/Command/Translator/CommandTranslatorUxer.cs @@ -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 _reverseMap = new Dictionary() + { + { "寝る", 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); + } +} diff --git a/AutoTest/Core/StepTestRunnerUxer.cs b/AutoTest/Core/StepTestRunnerUxer.cs new file mode 100644 index 0000000..2ec9d11 --- /dev/null +++ b/AutoTest/Core/StepTestRunnerUxer.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace KssSmaPlaLib.AutoTest.Core +{ + /// + /// 全体統括・ステップ順実行・ログ出力 + /// + public static class StepTestRunnerUxer + { + /// + /// 起動パラメータのUIテスト指定 + /// + private const string KIDOU_PARA_UITEST = "--uitest"; + + /// + /// メインPJのエントリーポイント用: + /// 起動パラよりUIテストモード判定 + /// + /// 起動パラメータ + /// UIテストモード? + public static bool IsModeByArgs(string[] args) + { + // 起動パラ判定 + return args.Any(m => m.ToLower() == KIDOU_PARA_UITEST); + } + } +} diff --git a/AutoTest/Core/TestModeInitializerUxer.cs b/AutoTest/Core/TestModeInitializerUxer.cs new file mode 100644 index 0000000..69d1a79 --- /dev/null +++ b/AutoTest/Core/TestModeInitializerUxer.cs @@ -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; + } + } +} diff --git a/AutoTest/Core/TestModeUxer.cs b/AutoTest/Core/TestModeUxer.cs new file mode 100644 index 0000000..fd20776 --- /dev/null +++ b/AutoTest/Core/TestModeUxer.cs @@ -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; + } + } +} diff --git a/AutoTest/Script/Load/LoadTryUxer.cs b/AutoTest/Script/Load/LoadTryUxer.cs new file mode 100644 index 0000000..de24f83 --- /dev/null +++ b/AutoTest/Script/Load/LoadTryUxer.cs @@ -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 +{ + /// + /// UIテストスクリプトローダー + /// + public static class LoadTryUxer + { + /// + /// スクリプトファイルパス + /// + private const string UITEST_SCRIPT_FILE_PATH = "./test_script.ini"; + + /// + /// スクリプトロード + /// + /// [出力]テストスクリプトデータ + /// [出力]メッセージ + /// 成否 + 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; + } + } + } +} diff --git a/AutoTest/Script/Models/ParsedStepDTO.cs b/AutoTest/Script/Models/ParsedStepDTO.cs new file mode 100644 index 0000000..6537a5e --- /dev/null +++ b/AutoTest/Script/Models/ParsedStepDTO.cs @@ -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 +{ + /// + /// パース済みのステップDTO(1ステップの情報) + /// + public class ParsedStepDTO + { + public string StepNo => Raw.StepNo; + public CommandEnumUxer.Command Command { get; set; } + public List Parameters { get; set; } + public StepDTO Raw { get; } + + public ParsedStepDTO(StepDTO raw) + { + Raw = raw; + } + } +} diff --git a/AutoTest/Script/Models/StepDTO.cs b/AutoTest/Script/Models/StepDTO.cs new file mode 100644 index 0000000..a7fc8f0 --- /dev/null +++ b/AutoTest/Script/Models/StepDTO.cs @@ -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 +{ + /// + /// ステップDTO(1ステップの情報) + /// + public class StepDTO + { + /// + /// ステップ番号 + /// + public string StepNo { get; set; } + + /// + /// ステップテキスト + /// + public string StepText { get; set; } + + public StepDTO(string stepNo, string stepText) + { this.StepNo = stepNo; this.StepText = stepText; } + } +} diff --git a/AutoTest/Script/Models/StepInfoDTO.cs b/AutoTest/Script/Models/StepInfoDTO.cs new file mode 100644 index 0000000..20c2245 --- /dev/null +++ b/AutoTest/Script/Models/StepInfoDTO.cs @@ -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 +{ + /// + /// UIテストステップ全体情報 + /// + public class StepInfoDTO + { + public List StepList { get; set; } = new List(); + public string InitialStepName { get; set; } // 最初に実行するステップ名 + public string Description { get; set; } // ステップ群の説明(任意) + } +} diff --git a/AutoTest/Script/Parse/Function/FunctionTryUxer.cs b/AutoTest/Script/Parse/Function/FunctionTryUxer.cs new file mode 100644 index 0000000..b0cde14 --- /dev/null +++ b/AutoTest/Script/Parse/Function/FunctionTryUxer.cs @@ -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 funcArgList,out string resultMessage) + { + functionName = ""; + funcArgList = new List(); + 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; + } + } +} diff --git a/AutoTest/Script/Parse/ParseTryUxer.cs b/AutoTest/Script/Parse/ParseTryUxer.cs new file mode 100644 index 0000000..c6ef885 --- /dev/null +++ b/AutoTest/Script/Parse/ParseTryUxer.cs @@ -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; + } + } +} diff --git a/AutoTest/Script/Storage/TestScriptStorageUxer.cs b/AutoTest/Script/Storage/TestScriptStorageUxer.cs new file mode 100644 index 0000000..7a5a08b --- /dev/null +++ b/AutoTest/Script/Storage/TestScriptStorageUxer.cs @@ -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; + } + } +} diff --git a/Batch/Cleanup/CleanupStepHandlerUxer.cs b/Batch/Cleanup/CleanupStepHandlerUxer.cs new file mode 100644 index 0000000..8d4ee23 --- /dev/null +++ b/Batch/Cleanup/CleanupStepHandlerUxer.cs @@ -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; + } + } +} diff --git a/Batch/Commons/CommonUxer.cs b/Batch/Commons/CommonUxer.cs new file mode 100644 index 0000000..7a31069 --- /dev/null +++ b/Batch/Commons/CommonUxer.cs @@ -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 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; + } + + /// + /// 終了日のオフセット指定があるときだけ、終了日を取得する + /// + /// + /// + /// + /// + /// + public static bool TryGetEndDate(Dictionary 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; + } + } +} diff --git a/Batch/DTO/StepDto.cs b/Batch/DTO/StepDto.cs new file mode 100644 index 0000000..8ae2754 --- /dev/null +++ b/Batch/DTO/StepDto.cs @@ -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; + } +} diff --git a/Batch/DTO/StepInfoDto.cs b/Batch/DTO/StepInfoDto.cs new file mode 100644 index 0000000..22af7b8 --- /dev/null +++ b/Batch/DTO/StepInfoDto.cs @@ -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 StepList { get; set; } = new List(); + } +} diff --git a/Batch/Dispatch/StepDispatcherUxer.cs b/Batch/Dispatch/StepDispatcherUxer.cs new file mode 100644 index 0000000..6135851 --- /dev/null +++ b/Batch/Dispatch/StepDispatcherUxer.cs @@ -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> _handlers; + + public StepDispatcherUxer() + { + _handlers = new Dictionary>() + { + { "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; + } +} diff --git a/Batch/Exchange/CsvToDbStepHandlerUxer.cs b/Batch/Exchange/CsvToDbStepHandlerUxer.cs new file mode 100644 index 0000000..f36ebe3 --- /dev/null +++ b/Batch/Exchange/CsvToDbStepHandlerUxer.cs @@ -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(); + // CSV読み込み+最小値取得 + if (!GetMinValueByKeyFromCsvFiles(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() + { + { "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() + { + { "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; + } + + /// + /// CSVよりキー毎に最小値を取得し辞書で返す + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool GetMinValueByKeyFromCsvFiles( + string csvFilePath, + string keyColName, + string valueColName, + ref Dictionary minDic, + out string resultMessage, + EncodingUxer.EncodingType encodingType = EncodingUxer.EncodingType.Utf8WithoutBom) + where TKeyType : IComparable + where TValueType : IComparable + { + // 👇参照型(追記とする)ゆえやめた + //minDic = new Dictionary(); + 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.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; + } +} diff --git a/Batch/IO/FileStepHandlerUxer.cs b/Batch/IO/FileStepHandlerUxer.cs new file mode 100644 index 0000000..a5022a0 --- /dev/null +++ b/Batch/IO/FileStepHandlerUxer.cs @@ -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; + } +} \ No newline at end of file diff --git a/Batch/Interface/IFuncResultDto.cs b/Batch/Interface/IFuncResultDto.cs new file mode 100644 index 0000000..5c66524 --- /dev/null +++ b/Batch/Interface/IFuncResultDto.cs @@ -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; } + } +} diff --git a/Batch/Sftp/SftpStepHandlerUxer.cs b/Batch/Sftp/SftpStepHandlerUxer.cs new file mode 100644 index 0000000..a68e13c --- /dev/null +++ b/Batch/Sftp/SftpStepHandlerUxer.cs @@ -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(); + 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; + } + } +} diff --git a/Batch/StepInfo/StepInfoUxer.cs b/Batch/StepInfo/StepInfoUxer.cs new file mode 100644 index 0000000..67a5f44 --- /dev/null +++ b/Batch/StepInfo/StepInfoUxer.cs @@ -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 iniDic, + out StepInfoDto stepInfo, + out string resultMessage) + { + stepInfo = new StepInfoDto + { + StepList = new List() + }; + 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; + } + } +} diff --git a/CL_設計別府条項.md b/CL_設計別府条項.md new file mode 100644 index 0000000..aee5ce6 --- /dev/null +++ b/CL_設計別府条項.md @@ -0,0 +1,29 @@ +# CL設計ガイドライン:別府条項(試作版) + +このドキュメントは、CL資産化における設計思想「別府条項」をまとめたものです。 +今後、気づきや発見があるたびに追記していく「Smapla DP(Design Pattern)」の母体となります。 + +--- + +## 🧠 条項一覧 + +### 1. クラス名はCL内で一意であるべき +- **理由**:インテリセンス選択ミスによる論理エラーの潜在化を防ぐため。 +- **背景**:同一名クラスが存在すると、シグネチャ一致による誤参照が発生しやすく、静的解析でも検出困難。 +- **別府度**:Smapla別府(高度PGX別府) + +### 2. メソッド名のCL内重複は歓迎(意味合いが確定している場合) +- **理由**:同名メソッドが意味合いで区別される設計はPGX的に直感的でわかりやすい。 +- **例**:`System.IO.File.Exists` と `System.IO.Directory.Exists` +- **別府度**:まそさん別府(PGX別府) + +--- + +## 🔥 今後の運用 +- 本ファイルはプロジェクトルートに配置し、随時追記可能とする。 +- 新たな思想・発見があれば、条項として追加し「Smapla DP」として昇華。 + +--- + +## 📝 編集履歴 +- 2025-10-16: 初版作成 by 小佐井 昇 & 昼コパ \ No newline at end of file diff --git a/Cleanup/FileCleanupUxer.cs b/Cleanup/FileCleanupUxer.cs new file mode 100644 index 0000000..8525adb --- /dev/null +++ b/Cleanup/FileCleanupUxer.cs @@ -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 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(folderPath, f => f.LastWriteTime < thresholdDate, f => f.Delete(), out var deleteFileCount, out var messageForMe, "日数超過削除")) + { + resultMessage = $"バックアップフォルダ過去ファイル削除(期間制限):{messageForMe}"; + return false; + } + + // バックアップフォルダの最大ファイル数超過時に古いファイルから削除 + if (!FileUxer.TryApplyActionToFiles(folderPath, f => true, f => f.Delete(), out deleteFileCount, out messageForMe, "ファイル数超過削除", true, null, maxFileCount)) + { + resultMessage = $"バックアップフォルダ過去ファイル削除(ファイル数制限):{messageForMe}"; + return false; + } + return true; + } + } +} diff --git a/Commons/Conversion/KanaConvertUxer.cs b/Commons/Conversion/KanaConvertUxer.cs new file mode 100644 index 0000000..58fbd9d --- /dev/null +++ b/Commons/Conversion/KanaConvertUxer.cs @@ -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 + { + /// + /// 半角カタカナを全角カタカナに変換します。 + /// 空文字やnullはそのまま返却します。 + /// + 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; + } + + /// + /// 全角カタカナを半角カタカナに変換します。 + /// 空文字やnullはそのまま返却します。 + /// + 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; + } + } +} diff --git a/Commons/DateHelperUxer.cs b/Commons/DateHelperUxer.cs new file mode 100644 index 0000000..974dfee --- /dev/null +++ b/Commons/DateHelperUxer.cs @@ -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 + { + + + /// + /// 指定した年と月の末日を返します。 + /// + /// 年(例: 2025) + /// 月(1~12) + /// 末日(28~31) + 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; + } + } +} diff --git a/Commons/DictionaryUxer.cs b/Commons/DictionaryUxer.cs new file mode 100644 index 0000000..af42634 --- /dev/null +++ b/Commons/DictionaryUxer.cs @@ -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 + { + /// + /// 指定されたキーに対応する値(string)を取得します。キーが存在しない場合は 指定されたデフォルト値(未指定時はnull) を返します。 + /// + public static TValue GetValueOrDefault( + Dictionary dict, + TKey key, + TValue defaultValue = default) + { + return dict.TryGetValue(key, out TValue value) ? value : defaultValue; + } + + public static bool CreateNameToIdDic(string pcsv, out Dictionary dic, out string resultMessage) + { + resultMessage = string.Empty; + dic = new Dictionary(); + + 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; + } + } +} diff --git a/Commons/EncodingUxer.cs b/Commons/EncodingUxer.cs new file mode 100644 index 0000000..7c3381d --- /dev/null +++ b/Commons/EncodingUxer.cs @@ -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"); // ANSI(Windows-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; + } + } +} diff --git a/Commons/IntUxer.cs b/Commons/IntUxer.cs new file mode 100644 index 0000000..3c5a28c --- /dev/null +++ b/Commons/IntUxer.cs @@ -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; + } + } + } +} diff --git a/Commons/LoggerUxer.cs b/Commons/LoggerUxer.cs new file mode 100644 index 0000000..db60004 --- /dev/null +++ b/Commons/LoggerUxer.cs @@ -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 +{ + /// + /// ロガー + /// + public static class LoggerUxer + { + /// + /// 初期化 + /// + /// ログINIファイルパス + 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()?.Product ?? "不明"; + + // EXE(呼び出し元)のアセンブリ + var exeAssembly = Assembly.GetEntryAssembly(); + var exeVersion = exeAssembly?.GetName().Version?.ToString(); + var exeProduct = exeAssembly?.GetCustomAttribute()?.Product ?? "不明"; + + // ログ出力 + Info($"[EXE] 製品名: {exeProduct}, バージョン: {exeVersion}"); + Info($"[DLL] 製品名: {dllProduct}, バージョン: {dllVersion}"); + } + + /// + /// ログINI初期化(無ければ) + /// + /// ログINIファイルパス + private static void EnsureIniExists(string path) + { + if (!File.Exists(path)) + { + File.WriteAllLines(path, new[] + { + "[Logging]", + "LogLevel=Information", + "LogFilePath=log.txt", + "RollingInterval=Day" + }); + } + } + } +} diff --git a/Commons/RetCodeUxer.cs b/Commons/RetCodeUxer.cs new file mode 100644 index 0000000..41f70f0 --- /dev/null +++ b/Commons/RetCodeUxer.cs @@ -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 + { + /// + /// 戻り値(プロセス終了値) + /// + public enum RetCode + { + /// + /// 成功 + /// + Success = 0, + + /// + /// ファイルバックアップ時エラー + /// + FileBackupError = -1, + + /// + /// ファイルクリーンナップエラー + /// + CleanupError = -2, + + /// + /// 開始日エラー + /// + StartDateError = -3, + + /// + /// DB接続エラー + /// + DbConnectError = -4, + + /// + /// SQLフォルダパス未設定 + /// + SqlFolderPathNoSetting = -5, + + /// + /// SQLファイルロードエラー + /// + SqlFileLoadError = -6, + + /// + /// CSVファイル名パターン群が未設定 + /// + CsvFileNamePatternsNotSetting = -7, + + /// + /// 設定ファイルの要素数エラー + /// + IniFileItemCountError = -8, + + /// + /// 挿入前の削除時に例外発生 + /// + DeleteBeforeInsertException = -9, + + /// + /// CSVデータをDB登録時エラー + /// + InsertDbFromCsvFilesError = -10, + + /// + /// CSVからDB登録時に例外発生 + /// + CsvToDbException = -11, + + /// + /// ファイル削除でフォルダパス未設定 + /// + FileDeleteFolderPathNotSetting = -12, + + /// + /// ファイル削除でフォルダパス未存在 + /// + FileDeleteFolderPathNotExist = -13, + + /// + /// ファイル削除でファイル名パターン未設定 + /// + FileDeleteFileNamePatternNotSetting = -14, + + /// + /// ファイル削除でファイル名パターン削除エラー + /// + FileDeletePatternFilesError = -15, + + /// + /// SFTPオブジェクト生成エラー + /// + SftpObjectCreateError = -16, + + /// + /// SFTPアップロードエラー + /// + SftpUploadError = -17, + + /// + /// SFTPアップロードで入力フォルダ未存在 + /// + SftpInFolderPathNotExist = -18, + + /// + /// SFTPでCSVファイル名パターンが未設定 + /// + SftpCsvFileNamePatternsNotSetting = -19, + + /// + /// SFTPダウンロード時に例外発生 + /// + SftpDownloadException = -20, + + /// + /// SFTPファイル削除エラー + /// + SftpDeleteMatchingFilesError = -21, + + /// + /// SFTPパターンマッチファイルダウンロード時エラー + /// + SftpMatchFilesDownloadError = -22, + + /// + /// SFTP共通:テスト接続エラー + /// + SftpTestConnectError = -23, + } + } +} diff --git a/Commons/StringUxer.cs b/Commons/StringUxer.cs new file mode 100644 index 0000000..dd0d972 --- /dev/null +++ b/Commons/StringUxer.cs @@ -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 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 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() + : 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; + } + + /// + /// CSVから文字列取得(インデックス指定:範囲外の時既定値) + /// + /// CSV文字列(カンマ区切り) + /// インデックス + /// 範囲外の時の既定値 + /// 取得した文字列 + 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]; + } + + /// + /// 文字列中の改行コードのカット + /// + /// + /// + 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); + } + } +} diff --git a/Commons/VariableUxer.cs b/Commons/VariableUxer.cs new file mode 100644 index 0000000..f563e7e --- /dev/null +++ b/Commons/VariableUxer.cs @@ -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 _args = new List(); + + public static List Args { get => _args; } + public static void SetArgs(string[] args) { _args = args.ToList(); } + } +} diff --git a/Communications/SftpUxer.cs b/Communications/SftpUxer.cs new file mode 100644 index 0000000..c0631a3 --- /dev/null +++ b/Communications/SftpUxer.cs @@ -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 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 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; + } + } + } +} diff --git a/DtoMapping/Attributes/ExcelColumnLetterAttribute.cs b/DtoMapping/Attributes/ExcelColumnLetterAttribute.cs new file mode 100644 index 0000000..1d6b304 --- /dev/null +++ b/DtoMapping/Attributes/ExcelColumnLetterAttribute.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace KssSmaPlaLib.DtoMapping.Attributes +{ + /// + /// Excel列レター属性(プロパティに付与) + /// + [AttributeUsage(AttributeTargets.Property)] + public class ExcelColumnLetterAttribute : Attribute + { + /// + /// Excel対応列レター + /// + public string ColumnLetter { get; } + + public ExcelColumnLetterAttribute(string columnLetter) + { + ColumnLetter = columnLetter; + } + } +} diff --git a/Encryption/FIleEncryptUxer.cs b/Encryption/FIleEncryptUxer.cs new file mode 100644 index 0000000..adaa866 --- /dev/null +++ b/Encryption/FIleEncryptUxer.cs @@ -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; + } + } + } +} diff --git a/Encryption/SimpleEncryptUxer.cs b/Encryption/SimpleEncryptUxer.cs new file mode 100644 index 0000000..9090d35 --- /dev/null +++ b/Encryption/SimpleEncryptUxer.cs @@ -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; + } + } + } +} diff --git a/Exchange/CsvDbSyncUxer.cs b/Exchange/CsvDbSyncUxer.cs new file mode 100644 index 0000000..edab912 --- /dev/null +++ b/Exchange/CsvDbSyncUxer.cs @@ -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 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( + 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( + 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; + } + } +} diff --git a/Exchange/Interfaces/ICsvExportableUxer.cs b/Exchange/Interfaces/ICsvExportableUxer.cs new file mode 100644 index 0000000..ad07172 --- /dev/null +++ b/Exchange/Interfaces/ICsvExportableUxer.cs @@ -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(); // データ行 + } +} diff --git a/Forms/ColorHelper.cs b/Forms/ColorHelper.cs new file mode 100644 index 0000000..9f4eeff --- /dev/null +++ b/Forms/ColorHelper.cs @@ -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 + { + /// + /// 色選択 + /// + /// + /// + /// + /// + 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; + } + } + + /// + /// Colorを汎用的なHTML色コード文字列に変換する + /// + /// + /// + public static string ColorToHtmlColorString(Color color) + { + return ColorTranslator.ToHtml(color); + } + + /// + /// 汎用的なHTML色コード文字列からColorに変換する + /// + /// + /// + public static Color HtmlColorStringToColor(string htmlColorString) + { + return ColorTranslator.FromHtml(htmlColorString); + } + + /// + /// 背景色から最適な文字色(黒/白)を返すメソッド + /// + /// + /// + 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; + } + } +} diff --git a/Forms/ContextMenuFunction/FontUxer.cs b/Forms/ContextMenuFunction/FontUxer.cs new file mode 100644 index 0000000..5dde394 --- /dev/null +++ b/Forms/ContextMenuFunction/FontUxer.cs @@ -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 + { + /// + /// フォント選択 + /// + /// + /// + /// + /// + /// + /// + 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); + } + } +} diff --git a/Forms/ContextMenuFunction/Gamen/DgvColumnEditorForm.Designer.cs b/Forms/ContextMenuFunction/Gamen/DgvColumnEditorForm.Designer.cs new file mode 100644 index 0000000..14d1423 --- /dev/null +++ b/Forms/ContextMenuFunction/Gamen/DgvColumnEditorForm.Designer.cs @@ -0,0 +1,197 @@ +namespace KssSmaPlaLib.Forms.ContextMenuFunction.Gamen +{ + partial class DgvColumnEditorForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + 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; + } +} \ No newline at end of file diff --git a/Forms/ContextMenuFunction/Gamen/DgvColumnEditorForm.cs b/Forms/ContextMenuFunction/Gamen/DgvColumnEditorForm.cs new file mode 100644 index 0000000..847eece --- /dev/null +++ b/Forms/ContextMenuFunction/Gamen/DgvColumnEditorForm.cs @@ -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"; + + /// + /// 対象のDGV + /// + private DataGridView _targetDgv = null; + + /// + /// 対象DGVの列名から列インデックスを取得する辞書 + /// (後ほど列インデックスが全てゼロになる事象が起きるため) + /// + private readonly Dictionary _colNameToRowIndexDic = null; + + /// + /// コンストラクタ + /// + /// + public DgvColumnEditorForm(DataGridView dgv) + { + InitializeComponent(); + + _targetDgv = dgv; + + // 列名から列インデックスを取得する辞書の作成(後ほど列インデックスが全てゼロになる事象が起きるため) + _colNameToRowIndexDic = new Dictionary(); + 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().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().FirstOrDefault(); + //if (browsableAttr != null && !browsableAttr.Browsable) + //{ + // col.Visible = false; + // continue; + //} + + // DGV列幅復元 + DgvHelper.DgvLoadColWidth(ColumnDgv); + } + + /// + /// フォームロード + /// + /// + /// + private void DgvColumnEditorForm_Load(object sender, EventArgs e) + { + // バウンズ復元 + FormHelper.LoadFormBounds(this); + } + + /// + /// 👆ボタンクリック時 + /// + /// + /// + 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; + } + + /// + /// 👇ボタンクリック時 + /// + /// + /// + 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; + } + + /// + /// DGVキー押下イベント + /// + /// + /// + 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"; + + /// + /// OKボタンクリック時 + /// + /// + /// + private void OkButton_Click(object sender, EventArgs e) + { + //List indexList = new List(); + //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)); + } + + /// + /// フォーム閉じるとき + /// + /// + /// + private void DgvColumnEditorForm_FormClosing(object sender, FormClosingEventArgs e) + { + // バウンズの保存 + FormHelper.SaveFormBounds(this); + + // DGV列幅保存 + DgvHelper.DgvSaveColWidth(ColumnDgv); + } + + /// + /// 表示名の編集メニュークリック + /// + /// + /// + 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; + } + } +} diff --git a/Forms/ContextMenuFunction/Gamen/DgvColumnEditorForm.resx b/Forms/ContextMenuFunction/Gamen/DgvColumnEditorForm.resx new file mode 100644 index 0000000..fb7e121 --- /dev/null +++ b/Forms/ContextMenuFunction/Gamen/DgvColumnEditorForm.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + True + + + True + + + 17, 17 + + \ No newline at end of file diff --git a/Forms/ContextMenuHelper.cs b/Forms/ContextMenuHelper.cs new file mode 100644 index 0000000..df99cb8 --- /dev/null +++ b/Forms/ContextMenuHelper.cs @@ -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"; + + /// + /// フォーム背景色選択 + /// + /// + 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); + } + } + } + + /// + /// 背景色をINIから取得して設定 + /// + /// + 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); + } + + /// + /// INIに登録されている色選択 + /// + /// + 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); + } + } + } + + /// + /// INIに設定されている色取得 + /// + /// + /// + /// + /// + 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); + } + + /// + /// チェックボックスのメニュー項目のチェック値のロード + /// + /// + /// + 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); + } + } + + /// + /// メニューのチェックボックスアイテムのクリック時 + /// + /// + /// + public static void MenuCheckBoxItemClick(Form frm, ToolStripMenuItem menuItem) + { + menuItem.Checked = !menuItem.Checked; + IniHelper.WriteValue(null, frm.Name, menuItem.Name, menuItem.Checked.ToString()); + } + + /// + /// メニューのフォント設定 + /// ※フォームロードでCallしてください + /// + /// + /// + public static void SetFont(Form form, ContextMenuStrip menu) + { + menu.Font = FontUxer.GetFont(form.Name, menu.Name + ".Font", menu.Font); + } + + /// + /// コントロール(ラベル等)のフォント設定 + /// ※フォームロードでCallしてください + /// + /// + /// + public static void SetControlFont(Form form, Control control) + { + control.Font = FontUxer.GetFont(form.Name, control.Name + ".Font", control.Font); + } + + /// + /// メニュー自身のフォント選択 + /// + /// + /// + 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; + } + + /// + /// コントロール(ラベル等)のフォント選択 + /// + /// + /// + 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; + } + + /// + /// フォームのタイトル設定 + /// + /// + 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); + } + } + + /// + /// バージョン表示 + /// + /// + 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 のぼぼ工房" : ""); + } + + /// + /// ショートカットキーで動作するようにする + /// ※フォームの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; + //   } + //  } + /// + /// + /// + /// + 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; + } + + /// + /// コンボメニューの選択値をINIに保存 + /// (ToolStripComboBoxのSelectedIndexChangedでCallしてね!💖) + /// + /// + /// + public static void SaveComboMenuToIni(Form form, ToolStripComboBox combo) + { + IniHelper.WriteValue(null, form.Name, combo.Name + ".Values", combo.Text); + } + + /// + /// コンボメニューの選択値をINIから復元 + /// (FormのLoadでCallしてね💖) + /// + /// + /// + /// + public static void LoadComboMenuFromIni(Form form, ToolStripComboBox combo, string defaultValue) + { + combo.Text = IniHelper.ReadValue(null, form.Name, combo.Name + ".Values", defaultValue); + } + + /// + /// コンボメニューの選択値をINIから取得 + /// + /// + /// + /// + /// + public static string ComboMenuFromIni(Form form, ToolStripComboBox combo, string defaultValue) + { + return IniHelper.ReadValue(null, form.Name, combo.Name + ".Values", defaultValue); + } + + /// + /// フォームガチャ + /// + /// + /// + public static async Task FormGacha(Form form) + { + // 現在の状態をバックアップ + var originalState = form.Controls.Cast() + .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; + } + } + } +} diff --git a/Forms/Controls/PoiDgv.cs b/Forms/Controls/PoiDgv.cs new file mode 100644 index 0000000..f894690 --- /dev/null +++ b/Forms/Controls/PoiDgv.cs @@ -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; + + /// + /// コンストラクタ + /// + 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; + } + + /// + /// コンテキストメニュー設定時 + /// + /// + 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); + + } + } +} + diff --git a/Forms/Controls/PoiDgv.resx b/Forms/Controls/PoiDgv.resx new file mode 100644 index 0000000..e5858cc --- /dev/null +++ b/Forms/Controls/PoiDgv.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + False + + \ No newline at end of file diff --git a/Forms/Controls/PoiMainForm.cs b/Forms/Controls/PoiMainForm.cs new file mode 100644 index 0000000..abb2a04 --- /dev/null +++ b/Forms/Controls/PoiMainForm.cs @@ -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 +{ + /// + /// Poiメインフォーム + /// + 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; + + /// + /// コンストラクタ + /// + 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(); + } + + /// + /// フォームロード時 + /// + /// + /// + /// + 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); + } + + /// + /// フォーム閉じるとき + /// + /// + /// + /// + 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()); + } + + /// + /// デフォルトのメニュー項目(表示設定など)を作成 + /// + 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() + .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); + } + + /// + /// 余白調整パネルメニュー作成 + /// + /// + 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; + } + + /// + /// 親メニュー開くときに追加する処理 + /// + /// + /// + 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; + } + + /// + /// メニュー項目追加 + /// + /// + /// + /// + /// + /// + protected ToolStripMenuItem AddCheckMenuItem( + int index, + string text, + string name, + bool defaultValue, + Action 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; + } + } + + /// + /// 列追加 + /// + /// + /// + /// + 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); + } + } +} diff --git a/Forms/DataGridViewExporter.cs b/Forms/DataGridViewExporter.cs new file mode 100644 index 0000000..1615c94 --- /dev/null +++ b/Forms/DataGridViewExporter.cs @@ -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 + { + + /// + /// DataGridView の「可視列・可視行のみ」を Excel へエクスポートします。 + /// 列順は DisplayIndex 順/ヘッダー付き/自動調整/簡易罫線付き。 + /// + 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() + .Where(c => c.Visible) + .OrderBy(c => c.DisplayIndex) + .ToList(); + + // 可視行のみ(新規行除外) + var visibleRows = dgv.Rows + .Cast() + .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); + } + } + + /// + /// SaveFileDialog 付きの簡便版。UIからサクッと呼び出す用。 + /// + 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); + } + } + } + } +} diff --git a/Forms/DatePickerHelper.cs b/Forms/DatePickerHelper.cs new file mode 100644 index 0000000..d432353 --- /dev/null +++ b/Forms/DatePickerHelper.cs @@ -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; // キャンセルされた場合 + } + } +} diff --git a/Forms/DgvHelper.cs b/Forms/DgvHelper.cs new file mode 100644 index 0000000..2221eb1 --- /dev/null +++ b/Forms/DgvHelper.cs @@ -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 + { + /// + /// 汎用的な初期化 + /// + /// + 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); + } + + /// + /// 列ヘッダのソート用余白を消す + /// ※列が確定してからCallすること + /// + /// + //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( + DataGridView grid, + IList source, + bool isForce = false) + { + // 強制でないとき、データソースありなら何もしない + if (!(grid.DataSource is null) && !isForce) return; + + // データバインド完了後にヘッダー等を属性で上書き + grid.DataBindingComplete += (_, __) => ApplyAttributeHeaders(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 bl ? bl : new BindingList(source); + + // BindingSource 経由が安定 + var bs = new BindingSource { DataSource = bindingList }; + grid.DataSource = bs; + } + + private const string KEY_NAME_DISPLAY_NAME_CSV = "DisplayNameCsv"; + + /// + /// プライベートな子関数 + /// + /// + /// + public static void ApplyAttributeHeaders(DataGridView grid) + { + // 編集した表示名 + var csv = IniHelper.ReadValue(null, grid.Parent.Name + "." + grid.Name, KEY_NAME_DISPLAY_NAME_CSV); + + var props = TypeDescriptor.GetProperties(typeof(T)) + .Cast() + .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().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"; + + /// + /// 列幅保存(FormのFormClosingにてCall) + /// + /// + public static void DgvSaveColWidth(DataGridView dgv) + { + var section = dgv.Parent.Name + "." + dgv.Name; + var list = new List(); + foreach(DataGridViewColumn col in dgv.Columns) list.Add(col.Width); + IniHelper.WriteValue(null, section, INI_KEY_COL_WIDTH_CSV, string.Join(",", list)); + } + + /// + /// 列幅復元(FormのコンストラクタにてCall) + /// + /// + 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"; + + /// + /// INIの列表示順をDGVに反映 + /// + /// + 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 displayIndexList = new List(); + 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 visibleList = new List(); + 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"; + + /// + /// ヘッダ行の高さ保存 + /// + /// + 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()); + } + + /// + /// ヘッダ行の高さロード + /// + /// + 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; + } + + /// + /// 非表示列の再表示 + /// + /// + public static void DgvRedispAllColumn(DataGridView dgv) + { + foreach (DataGridViewColumn col in dgv.Columns) col.Visible = true; + } + + private const string INI_KEY_COL_VISIBLE_CSV = "ColVisibleCsv"; + + /// + /// 列の表示非表示を保存 + /// + /// + public static void DgvSaveColVisible(DataGridView dgv) + { + var section = dgv.Parent.Name + "." + dgv.Name; + var list = new List(); + foreach (DataGridViewColumn col in dgv.Columns) list.Add(col.Visible); + IniHelper.WriteValue(null, section, INI_KEY_COL_VISIBLE_CSV, string.Join(",", list)); + } + + /// + /// 列の表示非表示をロード + /// + /// + 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"; + + /// + /// 列の表示順インデックスを保存 + /// + /// + public static void DgvSaveColDisplayIndex(DataGridView dgv) + { + var section = dgv.Parent.Name + "." + dgv.Name; + var list = new List(); + 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)); + } + + /// + /// 列の表示順インデックスをロード + /// + /// + 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 dic = new Dictionary(); + 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; + } + } + + /// + /// 列幅の自動調整 + /// + /// + public static void DgvColumnWidthAutoAdjust(DataGridView dgv) + { + dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); + } + + /// + /// 行高さの自動調整 + /// + /// + public static void DgvRowHeightAutoAdjust(DataGridView dgv) + { + dgv.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells); + } + + /// + /// 列固定 + /// + /// + 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() + .OrderBy(c => c.DisplayIndex); + + foreach (var col in targetColumns) + { + if (col.DisplayIndex <= targetDisplayIndex) + { + col.Frozen = true; + } + } + } + + /// + /// 列固定解除 + /// + /// + 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"; + + /// + /// 列の固定を保存 + /// + /// + public static void DgvSaveColFrozen(DataGridView dgv) + { + var section = dgv.Parent.Name + "." + dgv.Name; + var list = new List(); + foreach (DataGridViewColumn col in dgv.Columns) list.Add(col.Frozen); + IniHelper.WriteValue(null, section, INI_KEY_COL_FROZEN_CSV, string.Join(",", list)); + } + + /// + /// 列の固定をロード + /// + /// + 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"; + + /// + /// ヘッダ背景色選択 + /// + /// + /// + 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); + } + } + } + + /// + /// ヘッダ背景色(名前でマッチした列のみ)選択 + /// + /// + /// + /// + /// + 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); + } + } + } + + /// + /// ヘッダ背景色をINIから取得して設定 + /// + /// + 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); + } + + /// + /// ヘッダ背景色をINIから取得して設定(名前マッチング) + /// + /// + /// + /// + /// + 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"; + + /// + /// DGVデータTSV保存 + /// + /// + /// + 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().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("他には見つかりませんでしたにゃ!🐾"); + } + } +} diff --git a/Forms/FormHelper.cs b/Forms/FormHelper.cs new file mode 100644 index 0000000..ec24d17 --- /dev/null +++ b/Forms/FormHelper.cs @@ -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 + { + /// + /// フォームのコンストラクタで行う処理集 + /// + /// + 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; + } + } + } + + /// + /// フォームのロードで行う処理集 + /// + /// + /// + 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); + } + } + + /// + /// フォーム閉じるときの処理集 + /// + /// + 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"; + + /// + /// フォームのバウンズ保存 + /// ※フォームのClosingイベントでCallしてください。 + /// + /// + 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); + } + + /// + /// フォームのバウンズ復元 + /// ※フォームのLoadイベントでCallしてください。 + /// + /// + 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"; + + /// + /// タイトル設定(INI優先) + /// ※フォームのコンストラクタでCallしてください + /// + /// + public static void SetTitle(Form form) + { + form.Text = IniHelper.ReadValue(null, form.Name, KEY_NAME_TITLE, form.Text); + } + + /// + /// フォームの画面キャプチャを取得し画像ファイルに保存する + /// + /// + /// + 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(); + } + } +} diff --git a/Forms/ToastNotifier.cs b/Forms/ToastNotifier.cs new file mode 100644 index 0000000..b2ea235 --- /dev/null +++ b/Forms/ToastNotifier.cs @@ -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; + } + } + } +} diff --git a/IO/Database/DbUxer.cs b/IO/Database/DbUxer.cs new file mode 100644 index 0000000..ad11157 --- /dev/null +++ b/IO/Database/DbUxer.cs @@ -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 +{ + /// + /// DBアクセスアシスタント + /// + public class DbUxer : IDisposable + { + public enum DbProvider + { + PostgreSQL, + SQLServer, + MySQL, + Oracle, + SQLite, + } + + /// + /// プロバイダ名ディクショナリ + /// + private static readonly Dictionary _providerNameDic = new Dictionary() + { + { DbProvider.PostgreSQL, "Npgsql" }, + { DbProvider.SQLServer, "System.Data.SqlClient" }, + { DbProvider.MySQL, "MySql.Data.MySqlClient" }, + { DbProvider.Oracle, "Oracle.ManagedDataAccess.Client" }, + { DbProvider.SQLite, "System.Data.SQLite" }, + }; + + /// + /// プロバイダ名(文字列)からenum値に変更 + /// + /// プロバイダ名(文字列) + /// enum値(該当なし時はnull) + 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; + } + } + + /// + /// コミット済みフラグ + /// + private bool _isCommitted = false; + + /// + /// SQLディクショナリ + /// + private static readonly Dictionary _sqlDic = new Dictionary(); + + /// + /// 指定フォルダからSQLファイルを読み込む(ディクショナリ保存) + /// + /// フォルダパス + /// 成否 + public static bool TryLoadSqlFromText(string folderPath, out string resultMessage) + { + resultMessage = string.Empty; + var fileCount = 0; + List files = new List(); + + 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 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); + } + + /// + /// テスト接続 + /// + /// 成否 + 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; + } + + /// + /// DB接続 + /// + private DbConnection _con = null; + + /// + /// トランザクション + /// + private DbTransaction _tran = null; + + public static bool TryCreateByDic(Dictionary 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); + } + + /// + /// 生成挑戦 + /// + /// + /// + /// + /// + /// + /// + 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; + } + + /// + /// コンストラクタ(DB接続) + /// + /// DBプロバイダ(enum値) + /// 接続文字列 + /// トランザクション有無 + 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 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(), 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(), 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 parameters, out List> recordSet, out string resultMessage) + { + recordSet = new List>(); + 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(); + 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 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; + } + + /// + /// 終了処理 + /// + /// + public void Dispose() + { + if (_tran != null && !_isCommitted) + { + Log.Warning("トランザクション未コミット → 自動ロールバックされました"); + _tran.Rollback(); // 明示的にロールバック + } + _con?.Dispose(); + _con = null; + _tran = null; + } + + public static List ExtractSqlParams(string sql) + { + //var matches = System.Text.RegularExpressions.Regex.Matches(sql, @":([a-zA-Z_][a-zA-Z0-9_]*)"); + //return matches.Cast() + // .Select(m => m.Groups[1].Value) + // .Distinct() + // .ToList(); + + //var result = new List(); + //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(); + 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, + @"(?(); + + 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 parameters, ref List 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; + } + } +} diff --git a/IO/Excel/ExcelCellValidatorUxer.cs b/IO/Excel/ExcelCellValidatorUxer.cs new file mode 100644 index 0000000..346aed6 --- /dev/null +++ b/IO/Excel/ExcelCellValidatorUxer.cs @@ -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 + { + /// + /// ExcelのA1形式(例: "A1", "Z99", "AA1000")かどうかを判定します。 + /// + /// セル参照文字列 + /// 有効なA1形式ならtrue、無効ならfalse + 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; + } + + /// + /// 列名(例: "A", "Z", "AA")を列番号に変換(例: 1, 26, 27) + /// + public static int ColumnNameToNumber(string columnName) + { + int sum = 0; + foreach (char c in columnName) + { + sum *= 26; + sum += (c - 'A' + 1); + } + return sum; + } + } +} diff --git a/IO/Excel/ExcelColumnHelperUxer.cs b/IO/Excel/ExcelColumnHelperUxer.cs new file mode 100644 index 0000000..44b261a --- /dev/null +++ b/IO/Excel/ExcelColumnHelperUxer.cs @@ -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; + } + } +} diff --git a/IO/Excel/XlUxer.cs b/IO/Excel/XlUxer.cs new file mode 100644 index 0000000..569bbc9 --- /dev/null +++ b/IO/Excel/XlUxer.cs @@ -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; + } + + /// + /// Shorter + /// + /// + /// + public static int GetColNo(string colLetter) + { + if (!TryConvertColLetterToNumber(colLetter, out var no)) + { + return int.MinValue; + } + return no; + } + + /// + /// 列アルファベットを列番号(1オリジン)に変換 + /// + /// 列アルファベット + /// [出力]列番号(1オリジン) + /// 成否 + public static bool TryConvertColLetterToNumber(string colLetter, out int colNo) + { + colNo = int.MinValue; + + // バリデ(A~XFD) + 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; + } + } +} diff --git a/IO/File/CSVUxer.cs b/IO/File/CSVUxer.cs new file mode 100644 index 0000000..ed7307f --- /dev/null +++ b/IO/File/CSVUxer.cs @@ -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(List list, string filePath, out string resultMessage, EncodingUxer.EncodingType encodingType = EncodingUxer.EncodingType.Utf8WithoutBom) where T : ICsvExportableUxer + { + resultMessage = string.Empty; + try + { + var lines = new List { 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; + } + } + + /// + /// CSVインポート + /// + /// CSVファイルパス + /// [出力]レコードセット + /// [出力]メッセージ + /// [オプション]エンコード + /// 成否 + public static bool ImportFromCsv(string csvFilePath, out List> recordSet, out string resultMessage, EncodingUxer.EncodingType encodingType = EncodingUxer.EncodingType.Utf8WithoutBom) + { + recordSet = new List>(); + 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(); + + // 全項目 + 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()))); + + /// + /// CSVファイルを読み込み、ディクショナリに変換します。 + /// + /// CSVファイルのパス + /// 出力されるディクショナリ(ファイル無しの場合は空) + /// + /// 処理が成功した場合はtrue、例外発生時はfalse + public static bool TryGetDictionaryFromCsv( + string path, + out Dictionary dic, + out string resultMessage) + { + resultMessage = string.Empty; + + // 1. 最初に出力変数を空のディクショナリで初期化 + dic = new Dictionary(); + + 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; + } + } + } +} diff --git a/IO/File/FileUxer.cs b/IO/File/FileUxer.cs new file mode 100644 index 0000000..6d22ef1 --- /dev/null +++ b/IO/File/FileUxer.cs @@ -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 + { + /// + /// テキストファイル出力(全テキスト一括) + /// + /// 全テキスト + /// ファイルパス + /// メッセージ + /// 文字コード + /// 成否 + 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( + string folderPath, + Func condition, + Action action, + out int fileCount, + out string resultMessage, + string actionName = "操作", + bool isDescending = true, + Func 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) + (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; + } + } + } +} diff --git a/IO/File/JsonFileUxer.cs b/IO/File/JsonFileUxer.cs new file mode 100644 index 0000000..d666448 --- /dev/null +++ b/IO/File/JsonFileUxer.cs @@ -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 + { + /// + /// JSONファイルのピンポイント1項目更新 + /// + /// JSONファイルパス + /// JSONノードパス + /// 更新値 + /// + 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); + } + + /// + /// JSONファイルから、jsonPathに一致する単一項目を取得します。 + /// 取得に成功したら true を返し、 out value に JToken を設定します。 + /// キーが見つからない・JSON無効・ファイル無し等は false を返し、 value は null。 + /// + 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; + } + } + + /// + /// 文字列として取得(JToken型を意識したくない場合の軽量ヘルパー)。 + /// + 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; + } + + /// + /// 符号付き整数(Int64)で取得(intの範囲超えも想定)。 + /// + 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; + } + + /// + /// 任意型の既定値付き取得(存在しなければ defaultValue を返す)。 + /// 例:GetJsonKeyOrDefault(path, "app.auth.retries", 3) + /// + public static T GetJsonKeyOrDefault(string path, string jsonPath, T defaultValue) + { + if (!TryGetJsonKey(path, jsonPath, out var token) || token is null) + return defaultValue; + + try + { + // JToken → 任意型に変換(失敗時は既定値) + var val = token.ToObject(); + return val == null ? defaultValue : val; + } + catch + { + return defaultValue; + } + } + } +} diff --git a/IO/File/PathUxer.cs b/IO/File/PathUxer.cs new file mode 100644 index 0000000..f92619d --- /dev/null +++ b/IO/File/PathUxer.cs @@ -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('/'))); + } + + + /// + /// ファイル名(パス不可)を受け取り、存在すればフルパスを返す。 + /// 探索順:①このDLLのフォルダ → ②エントリEXEのフォルダ → ③AppDomain.BaseDirectory + /// (C)昼コパソフトウェア㈱ + /// + /// パスではないファイル名のみ(例: "config.json")。 + /// 見つかったファイルのフルパス。未発見時は null。 + /// 発見した場合 true、未発見の場合 false。 + 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; + } + + /// + /// 指定フォルダに fileName を結合し、存在すれば out に設定して true。 + /// + 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; + } + + /// + /// Assembly.Location を安全に取得(Reflection-only / 影響ケースを考慮)。 + /// + private static string SafeGetAssemblyLocation(Assembly asm) + { + try + { + return asm?.Location; + } + catch + { + return null; + } + } + + /// + /// DirectoryName を安全に取得。 + /// + private static string SafeGetDirectoryName(string path) + { + try + { + return string.IsNullOrEmpty(path) ? null : Path.GetDirectoryName(path); + } + catch + { + return null; + } + } + } +} diff --git a/InBox/IFilterUxer.cs b/InBox/IFilterUxer.cs new file mode 100644 index 0000000..6344e66 --- /dev/null +++ b/InBox/IFilterUxer.cs @@ -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 + { + // 単一:候補がフィルタを通過できるか? + bool CanPass(string candidate); + + // 複数:1件でも通過できるか?(ガード句向け) + bool HasAnyPass(IEnumerable candidates); + + // 複数:通過したものだけを返す(既存流儀) + IEnumerable ApplyFilter(IEnumerable candidates); + } +} diff --git a/InBox/LineFilterUxer.cs b/InBox/LineFilterUxer.cs new file mode 100644 index 0000000..18d1527 --- /dev/null +++ b/InBox/LineFilterUxer.cs @@ -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 + { + private readonly HashSet includedLines; + private readonly HashSet excludedLines; + + public LineFilterUxer(IEnumerable included, IEnumerable excluded) + { + includedLines = new HashSet(included ?? Enumerable.Empty()); + excludedLines = new HashSet(excluded ?? Enumerable.Empty()); + } + + public IEnumerable ApplyFilter(IEnumerable 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 candidates) + { + return ApplyFilter(candidates).Any(); + } + } +} diff --git a/InBox/SheetFilterUxer.cs b/InBox/SheetFilterUxer.cs new file mode 100644 index 0000000..50ced9c --- /dev/null +++ b/InBox/SheetFilterUxer.cs @@ -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 + { + private readonly HashSet includedSheets; + private readonly HashSet excludedSheets; + + public SheetFilterUxer(IEnumerable included, IEnumerable excluded) + { + includedSheets = new HashSet(included ?? Enumerable.Empty()); + excludedSheets = new HashSet(excluded ?? Enumerable.Empty()); + } + + public IEnumerable ApplyFilter(IEnumerable sheetNames) + { + if (includedSheets.Any()) + { + // Included優先 → lineNamesの中でincludedに含まれるものだけ返す + //return sheetNames.Where(name => includedSheets.Contains(name)); + // ワイルドカード(*)ありとする! + List listA = new List(); + 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 listB = new List(); + 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 sheetNames) + { + return ApplyFilter(sheetNames).Any(); + } + } +} diff --git a/Ini/IniDto.cs b/Ini/IniDto.cs new file mode 100644 index 0000000..481a79e --- /dev/null +++ b/Ini/IniDto.cs @@ -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; + } +} diff --git a/Ini/IniHelper.cs b/Ini/IniHelper.cs new file mode 100644 index 0000000..f5a7fe6 --- /dev/null +++ b/Ini/IniHelper.cs @@ -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 IniList = new List(); + + // 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); + + /// + /// INIファイルから値を読み込み(セクション+キー指定) + /// + 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; + } + + /// + /// bool値の読み込み + /// + /// + /// + /// + /// + /// + 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; + } + + /// + /// 日付値の読み込み + /// + 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; + } + + /// + /// INIファイルに値を書き込み(セクション+キー+値指定) + /// + 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); + } + + /// + /// bool値の書き込み + /// + /// + /// + /// + /// + /// + public static bool WriteBoolValue(string iniPath, string section, string key, bool value) + { + return WriteValue(iniPath, section, key, value.ToString()); + } + + /// + /// 日付値の書き込み + /// + /// + /// + /// + /// + /// + 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(); + } + } +} diff --git a/Ini/IniReaderUxer.cs b/Ini/IniReaderUxer.cs new file mode 100644 index 0000000..fb57f16 --- /dev/null +++ b/Ini/IniReaderUxer.cs @@ -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 +{ + /// + /// INIリーダー + /// + public static class IniReaderUxer + { + /// + /// 指定セクションのINI値読み込み + /// + /// INIパス + /// セクション + /// 指定のディクショナリ + public static Dictionary ReadSection(string path, string section) + { + var result = new Dictionary(); + 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 iniDic,string key) + { + return string.IsNullOrEmpty(DictionaryUxer.GetValueOrDefault(iniDic, key, string.Empty)); + } + } +} diff --git a/Ini/IniReferenceResolveUxer.cs b/Ini/IniReferenceResolveUxer.cs new file mode 100644 index 0000000..cfe0fe0 --- /dev/null +++ b/Ini/IniReferenceResolveUxer.cs @@ -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 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(); + + 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> ParseAllSections(string[] lines) + { + var sections = new Dictionary>(); + 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(); + } + 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> 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; + } + } +} diff --git a/Input/Gamen/NumericInputForm.Designer.cs b/Input/Gamen/NumericInputForm.Designer.cs new file mode 100644 index 0000000..413736d --- /dev/null +++ b/Input/Gamen/NumericInputForm.Designer.cs @@ -0,0 +1,106 @@ +namespace KssSmaPlaLib.Input.Gamen +{ + partial class NumericInputForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + 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; + } +} \ No newline at end of file diff --git a/Input/Gamen/NumericInputForm.cs b/Input/Gamen/NumericInputForm.cs new file mode 100644 index 0000000..c7dd021 --- /dev/null +++ b/Input/Gamen/NumericInputForm.cs @@ -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; + } + } +} diff --git a/Input/Gamen/NumericInputForm.resx b/Input/Gamen/NumericInputForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/Input/Gamen/NumericInputForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Input/Gamen/TextInputForm.Designer.cs b/Input/Gamen/TextInputForm.Designer.cs new file mode 100644 index 0000000..60e94c2 --- /dev/null +++ b/Input/Gamen/TextInputForm.Designer.cs @@ -0,0 +1,95 @@ +namespace KssSmaPlaLib.Input.Gamen +{ + partial class TextInputForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + 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; + } +} \ No newline at end of file diff --git a/Input/Gamen/TextInputForm.cs b/Input/Gamen/TextInputForm.cs new file mode 100644 index 0000000..79aa73c --- /dev/null +++ b/Input/Gamen/TextInputForm.cs @@ -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; + } + } +} diff --git a/Input/Gamen/TextInputForm.resx b/Input/Gamen/TextInputForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/Input/Gamen/TextInputForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/KssSmaPlaLib.csproj b/KssSmaPlaLib.csproj new file mode 100644 index 0000000..a2e04eb --- /dev/null +++ b/KssSmaPlaLib.csproj @@ -0,0 +1,233 @@ + + + + + + Debug + AnyCPU + {4136CE96-10AA-4B55-B49F-68C80E9E3BC8} + Library + Properties + KssSmaPlaLib + KssSmaPlaLib + v4.8 + 512 + true + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + ラッキイ青透過版(せり様).ico + + + + + + + + + + + + + + + + + + + + + Form + + + + + + + + + + + + + + Form + + + DgvColumnEditorForm.cs + + + + Component + + + Form + + + + + + + + + + + + + + + + + + + + NumericInputForm.cs + + + Form + + + Form + + + TextInputForm.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + AlertForm.cs + + + DgvColumnEditorForm.cs + + + PoiDgv.cs + + + NumericInputForm.cs + + + TextInputForm.cs + + + + + 0.105.0 + + + 6.5.1 + + + 3.1.1 + + + 7.1.3 + + + 10.3.0 + + + 13.0.4 + + + 4.1.8 + + + 4.3.0 + + + 6.0.0 + + + 7.0.0 + + + 2025.0.0 + + + + + + + + + + このプロジェクトは、このコンピューター上にない NuGet パッケージを参照しています。それらのパッケージをダウンロードするには、[NuGet パッケージの復元] を使用します。詳細については、http://go.microsoft.com/fwlink/?LinkID=322105 を参照してください。見つからないファイルは {0} です。 + + + + + + + \ No newline at end of file diff --git a/KssSmaPlaLib.sln b/KssSmaPlaLib.sln new file mode 100644 index 0000000..4793086 --- /dev/null +++ b/KssSmaPlaLib.sln @@ -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 diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..73a7943 --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -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の挿入前削除で対象データの再過去日から削除するよう修正 diff --git a/Tools/ClaraHack/NamespaceAdjust/NamespaceAdjusterUxer.cs b/Tools/ClaraHack/NamespaceAdjust/NamespaceAdjusterUxer.cs new file mode 100644 index 0000000..3170fd7 --- /dev/null +++ b/Tools/ClaraHack/NamespaceAdjust/NamespaceAdjusterUxer.cs @@ -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; + } + } +} diff --git a/Tools/FileHack/MergeSplitFilesUxer.cs b/Tools/FileHack/MergeSplitFilesUxer.cs new file mode 100644 index 0000000..47b2591 --- /dev/null +++ b/Tools/FileHack/MergeSplitFilesUxer.cs @@ -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; + } + } + } +} diff --git a/Tools/FileHack/SplitFileBySizeUxer.cs b/Tools/FileHack/SplitFileBySizeUxer.cs new file mode 100644 index 0000000..81b0a5c --- /dev/null +++ b/Tools/FileHack/SplitFileBySizeUxer.cs @@ -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; + } + } + } +} diff --git a/app.config b/app.config new file mode 100644 index 0000000..050af3f --- /dev/null +++ b/app.config @@ -0,0 +1,58 @@ + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ラッキイ青透過版(せり様).ico b/ラッキイ青透過版(せり様).ico new file mode 100644 index 0000000..3554ad9 Binary files /dev/null and b/ラッキイ青透過版(せり様).ico differ