Drag-Drop-Move

This commit is contained in:
2023-05-03 18:12:50 -07:00
parent 07ecbeb76c
commit e6acce3852
24 changed files with 853 additions and 160 deletions

26
Drag-Drop-Move/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,26 @@
{
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/net7.0-windows/win-x64/Drag-Drop-Explorer.dll",
"args": [],
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}

41
Drag-Drop-Move/.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,41 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/Drag-Drop-Explorer.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/Drag-Drop-Explorer.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/Drag-Drop-Explorer.csproj"
],
"problemMatcher": "$msCompile"
}
]
}

View File

@ -0,0 +1,50 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>10.0</LangVersion>
<Nullable>enable</Nullable>
<OutputType>WinExe</OutputType>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<TargetFramework>net7.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
<PropertyGroup>
<IsWindows Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows)))' == 'true'">true</IsWindows>
<IsOSX Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::OSX)))' == 'true'">true</IsOSX>
<IsLinux Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' == 'true'">true</IsLinux>
</PropertyGroup>
<PropertyGroup Condition="'$(IsWindows)'=='true'">
<DefineConstants>Windows</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(IsOSX)'=='true'">
<DefineConstants>OSX</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(IsLinux)'=='true'">
<DefineConstants>Linux</DefineConstants>
</PropertyGroup>
<ItemGroup Condition="'$(RuntimeIdentifier)' == 'browser-wasm'">
<SupportedPlatform Include="browser" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Humanizer.Core" Version="2.14.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="WindowsShortcutFactory" Version="1.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Shared\View-by-Distance.Shared.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="appsettings.Development.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

39
Drag-Drop-Move/DragDropMove.Designer.cs generated Normal file
View File

@ -0,0 +1,39 @@
namespace View_by_Distance.Drag_Drop_Explorer;
partial class DragDropMove
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(640, 100);
this.StartPosition = FormStartPosition.CenterScreen;
this.Text = "Drag Drop Explorer";
}
#endregion
}

View File

@ -0,0 +1,195 @@
using Microsoft.Extensions.Configuration;
using Phares.Shared;
using Serilog;
using System.Diagnostics;
using System.Reflection;
using System.Text.Json;
using View_by_Distance.Drag_Drop_Explorer.Models;
using View_by_Distance.Shared.Models.Stateless.Methods;
using WindowsShortcutFactory;
namespace View_by_Distance.Drag_Drop_Explorer;
public partial class DragDropMove : Form
{
private readonly ILogger _Logger;
private readonly TextBox _PathTextBox;
private readonly TextBox _JsonTextBox;
private readonly TextBox _FirstTextBox;
private readonly AppSettings _AppSettings;
private readonly ProgressBar _ProgressBar;
private readonly string _WorkingDirectory;
private readonly IsEnvironment _IsEnvironment;
public DragDropMove()
{
InitializeComponent();
ILogger logger;
AppSettings appSettings;
string workingDirectory;
IsEnvironment isEnvironment;
IConfigurationRoot configurationRoot;
LoggerConfiguration loggerConfiguration = new();
Assembly assembly = Assembly.GetExecutingAssembly();
bool debuggerWasAttachedAtLineZero = Debugger.IsAttached || assembly.Location.Contains(@"\bin\Debug");
isEnvironment = new(processesCount: null, nullASPNetCoreEnvironmentIsDevelopment: debuggerWasAttachedAtLineZero, nullASPNetCoreEnvironmentIsProduction: !debuggerWasAttachedAtLineZero);
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile(isEnvironment.AppSettingsFileName, optional: false, reloadOnChange: true);
configurationRoot = configurationBuilder.Build();
appSettings = Models.Binder.AppSettings.Get(configurationRoot);
if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName))
throw new Exception("Working path name must have parentDirectory value!");
workingDirectory = IWorkingDirectory.GetWorkingDirectory(assembly.GetName().Name, appSettings.WorkingDirectoryName);
Environment.SetEnvironmentVariable(nameof(workingDirectory), workingDirectory);
_ = ConfigurationLoggerConfigurationExtensions.Configuration(loggerConfiguration.ReadFrom, configurationRoot);
Log.Logger = loggerConfiguration.CreateLogger();
logger = Log.ForContext<DragDropMove>();
logger.Information("Complete");
_Logger = logger;
_AppSettings = appSettings;
_IsEnvironment = isEnvironment;
_WorkingDirectory = workingDirectory;
_ProgressBar = new() { TabIndex = 4, Location = new(5, 5), Dock = DockStyle.Top, Visible = false };
string json = JsonSerializer.Serialize(_AppSettings, new JsonSerializerOptions { WriteIndented = true });
_FirstTextBox = new() { TabIndex = 1, Text = _IsEnvironment.Profile, Location = new(5, 5), Dock = DockStyle.Top };
_PathTextBox = new() { TabIndex = 2, Text = _AppSettings.WorkingDirectoryName, Location = new(5, 5), Dock = DockStyle.Top };
_JsonTextBox = new() { TabIndex = 3, Text = json, Multiline = true, MinimumSize = new(1, 80), Location = new(5, 5), Dock = DockStyle.Top };
Load += new EventHandler(Form1_Load);
Controls.Add(_ProgressBar);
Controls.Add(_JsonTextBox);
Controls.Add(_PathTextBox);
Controls.Add(_FirstTextBox);
}
void Form1_Load(object? sender, EventArgs e)
{
try
{
AllowDrop = true;
DragDrop += new DragEventHandler(Form1_DragDrop);
DragEnter += new DragEventHandler(Form1_DragEnter);
_FirstTextBox.LostFocus += new EventHandler(TextBox_LostFocus);
_PathTextBox.LostFocus += new EventHandler(TextBox_LostFocus);
}
catch (Exception)
{
throw;
}
}
private static string GetConverted(string value)
{
string result = value.Length < 2 || value[1] != ':' ? value : value.Replace("\\\\", "/").Replace('\\', '/');
return result;
}
void TextBox_LostFocus(object? sender, EventArgs e)
{
try
{
if (sender is TextBox textBox)
{
textBox.Text = GetConverted(textBox.Text);
if (textBox.Text == "ps")
throw new NotImplementedException();
}
}
catch (Exception)
{
throw;
}
}
void Form1_DragEnter(object? sender, DragEventArgs e)
{
try
{
if (e.Data is not null && e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
catch (Exception)
{
throw;
}
}
private void MovePaths(string[] paths)
{
string file;
string checkFile;
string? directory;
string? relativePath;
string[] directories;
string? checkDirectory;
string? shellDirectory;
int rootDirectoryLength;
WindowsShortcut windowsShortcut;
_PathTextBox.Text = string.Empty;
_FirstTextBox.Text = GetConverted(paths[0]);
foreach (string path in paths.OrderBy(l => l))
{
relativePath = null;
shellDirectory = null;
if (!path.EndsWith(".lnk"))
file = path;
else
{
windowsShortcut = WindowsShortcut.Load(path);
if (windowsShortcut.Path is null)
continue;
file = windowsShortcut.Path;
windowsShortcut.Dispose();
}
directory = Path.GetDirectoryName(file);
if (string.IsNullOrEmpty(directory))
continue;
directories = IPath.GetDirectories(directory);
foreach (string directoryName in directories)
{
checkDirectory = $"{directoryName}-Shell";
if (!Directory.Exists(checkDirectory))
continue;
shellDirectory = checkDirectory;
rootDirectoryLength = directoryName.Length;
relativePath = file[rootDirectoryLength..];
break;
}
if (string.IsNullOrEmpty(shellDirectory) || string.IsNullOrEmpty(relativePath))
continue;
checkFile = string.Concat(shellDirectory, relativePath);
checkDirectory = Path.GetDirectoryName(checkFile);
if (string.IsNullOrEmpty(checkDirectory))
continue;
if (!Directory.Exists(checkDirectory))
_ = Directory.CreateDirectory(checkDirectory);
if (File.Exists(checkFile))
continue;
File.Move(file, checkFile);
}
}
void Form1_DragDrop(object? sender, DragEventArgs e)
{
try
{
if (e.Data is not null && e.Data.GetData(DataFormats.FileDrop) is string[] paths && paths.Any())
MovePaths(paths);
else
{
_FirstTextBox.Text = string.Empty;
_PathTextBox.Text = string.Empty;
_JsonTextBox.Text = string.Empty;
_Logger.Information("No data");
}
}
catch (Exception)
{
throw;
}
}
}

View File

@ -0,0 +1,27 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace View_by_Distance.Drag_Drop_Explorer.Models;
public class AppSettings
{
public string Company { init; get; }
public int MaxDegreeOfParallelism { init; get; }
public string WorkingDirectoryName { init; get; }
[JsonConstructor]
public AppSettings(string company, int maxDegreeOfParallelism, string workingDirectoryName)
{
Company = company;
MaxDegreeOfParallelism = maxDegreeOfParallelism;
WorkingDirectoryName = workingDirectoryName;
}
public override string ToString()
{
string result = JsonSerializer.Serialize(this, new JsonSerializerOptions() { WriteIndented = true });
return result;
}
}

View File

@ -0,0 +1,44 @@
using Microsoft.Extensions.Configuration;
using System.Text.Json;
namespace View_by_Distance.Drag_Drop_Explorer.Models.Binder;
public class AppSettings
{
#nullable disable
public string Company { get; set; }
public int? MaxDegreeOfParallelism { get; set; }
public string WorkingDirectoryName { get; set; }
#nullable restore
public override string ToString()
{
string result = JsonSerializer.Serialize(this, new JsonSerializerOptions() { WriteIndented = true });
return result;
}
private static Models.AppSettings Get(AppSettings? appSettings)
{
Models.AppSettings result;
if (appSettings?.MaxDegreeOfParallelism is null)
throw new NullReferenceException(nameof(appSettings.MaxDegreeOfParallelism));
result = new(
appSettings.Company,
appSettings.MaxDegreeOfParallelism.Value,
appSettings.WorkingDirectoryName
);
return result;
}
public static Models.AppSettings Get(IConfigurationRoot configurationRoot)
{
Models.AppSettings result;
AppSettings? appSettings = configurationRoot.Get<AppSettings>();
result = Get(appSettings);
return result;
}
}

15
Drag-Drop-Move/Program.cs Normal file
View File

@ -0,0 +1,15 @@
namespace View_by_Distance.Drag_Drop_Explorer;
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new DragDropMove());
}
}

View File

@ -0,0 +1,11 @@
{
"Logging": {
"LogLevel": {
"Log4netProvider": "Debug"
}
},
"MaxDegreeOfParallelism": 6,
"Serilog": {
"MinimumLevel": "Debug"
}
}

View File

@ -0,0 +1,50 @@
{
"Company": "Mike Phares",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Log4netProvider": "Debug",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"MaxDegreeOfParallelism": 6,
"Serilog": {
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.File"
],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "Debug",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{MethodName}) ({InstanceId}) ({RemoteIpAddress}) {Message}{NewLine}{Exception}"
}
},
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{MethodName}) ({InstanceId}) ({RemoteIpAddress}) {Message}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "%workingDirectory% - Log/log-.txt",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] ({SourceContext}.{MethodName}) ({InstanceId}) ({RemoteIpAddress}) {Message}{NewLine}{Exception}",
"rollingInterval": "Hour"
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId"
],
"Properties": {
"Application": "Sample"
}
},
"WorkingDirectoryName": "PharesApps"
}