diff --git a/ATXConfigTest/ATXConfigTest.csproj b/ATXConfigTest/ATXConfigTest.csproj index df442c4a425b7e5021594474e2679faa83e1eabc..f5d0375002890d60e62c428dc611d562d468454f 100644 --- a/ATXConfigTest/ATXConfigTest.csproj +++ b/ATXConfigTest/ATXConfigTest.csproj @@ -48,9 +48,9 @@ <None Include="App.config" /> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\ATXSerializables\ATXSerializables.csproj"> + <ProjectReference Include="..\ATXSerializables\ATXCommon.csproj"> <Project>{166D65D5-EE10-4364-8AA3-4D86BA5CE244}</Project> - <Name>ATXSerializables</Name> + <Name>ATXCommon</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> diff --git a/ATXConfigTest/AutoTxConfigTest.cs b/ATXConfigTest/AutoTxConfigTest.cs index a649bc0dec259e99a511d67800a8d3b439499ee2..100291fe1785b6e118a2fe5a4e6fb6d84314134d 100644 --- a/ATXConfigTest/AutoTxConfigTest.cs +++ b/ATXConfigTest/AutoTxConfigTest.cs @@ -1,6 +1,6 @@ using System; using System.IO; -using ATXSerializables; +using ATXCommon.Serializables; namespace ATXConfigTest { diff --git a/ATXSerializables/ATXSerializables.csproj b/ATXSerializables/ATXCommon.csproj similarity index 87% rename from ATXSerializables/ATXSerializables.csproj rename to ATXSerializables/ATXCommon.csproj index 0b6ec7c14655fd6bce4af74198b074db4b8e7b33..a282202c7235ec24cbd0da42d25422625a62eb58 100644 --- a/ATXSerializables/ATXSerializables.csproj +++ b/ATXSerializables/ATXCommon.csproj @@ -7,8 +7,8 @@ <ProjectGuid>{166D65D5-EE10-4364-8AA3-4D86BA5CE244}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> - <RootNamespace>ATXSerializables</RootNamespace> - <AssemblyName>ATXSerializables</AssemblyName> + <RootNamespace>ATXCommon</RootNamespace> + <AssemblyName>ATXCommon</AssemblyName> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> @@ -40,10 +40,12 @@ <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> - <Compile Include="DriveToCheck.cs" /> - <Compile Include="ServiceConfig.cs" /> + <Compile Include="FsUtils.cs" /> + <Compile Include="Serializables\DriveToCheck.cs" /> + <Compile Include="Serializables\ServiceConfig.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> - <Compile Include="ServiceStatus.cs" /> + <Compile Include="Serializables\ServiceStatus.cs" /> + <Compile Include="TimeUtils.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. diff --git a/ATXSerializables/FsUtils.cs b/ATXSerializables/FsUtils.cs new file mode 100644 index 0000000000000000000000000000000000000000..c6dadb1103b511605dce2bc7fd5673d085aa7c2f --- /dev/null +++ b/ATXSerializables/FsUtils.cs @@ -0,0 +1,19 @@ +using System.IO; +using System.Linq; + +namespace ATXCommon +{ + public static class FsUtils + { + /// <summary> + /// Recursively sum up size of all files under a given path. + /// </summary> + /// <param name="path">Full path of the directory.</param> + /// <returns>The total size in bytes.</returns> + public static long GetDirectorySize(string path) { + return new DirectoryInfo(path) + .GetFiles("*", SearchOption.AllDirectories) + .Sum(file => file.Length); + } + } +} diff --git a/ATXSerializables/DriveToCheck.cs b/ATXSerializables/Serializables/DriveToCheck.cs similarity index 93% rename from ATXSerializables/DriveToCheck.cs rename to ATXSerializables/Serializables/DriveToCheck.cs index 7d52e74420d89dd81a53bf5505e69c8ee2df1a52..35a0242343bca5da9695bdb907eb5e117ebd7819 100644 --- a/ATXSerializables/DriveToCheck.cs +++ b/ATXSerializables/Serializables/DriveToCheck.cs @@ -1,6 +1,6 @@ using System.Xml.Serialization; -namespace ATXSerializables +namespace ATXCommon.Serializables { /// <summary> /// Helper class for the nested SpaceMonitoring sections. diff --git a/ATXSerializables/ServiceConfig.cs b/ATXSerializables/Serializables/ServiceConfig.cs similarity index 99% rename from ATXSerializables/ServiceConfig.cs rename to ATXSerializables/Serializables/ServiceConfig.cs index 512e426421acc5e1e134447e86f1ba30dd267fd8..9f5e635c53a3fc2e1da3ccfd686c06ad9a693fb0 100644 --- a/ATXSerializables/ServiceConfig.cs +++ b/ATXSerializables/Serializables/ServiceConfig.cs @@ -4,7 +4,7 @@ using System.Configuration; using System.IO; using System.Xml.Serialization; -namespace ATXSerializables +namespace ATXCommon.Serializables { /// <summary> /// configuration class based on xml diff --git a/ATXSerializables/ServiceStatus.cs b/ATXSerializables/Serializables/ServiceStatus.cs similarity index 99% rename from ATXSerializables/ServiceStatus.cs rename to ATXSerializables/Serializables/ServiceStatus.cs index 5bdc52f41e790961ba74026e49fc70f909b4aa10..9d88b50b0949fa34673462e0f87441e5aaa2229d 100644 --- a/ATXSerializables/ServiceStatus.cs +++ b/ATXSerializables/Serializables/ServiceStatus.cs @@ -2,7 +2,7 @@ using System.IO; using System.Xml.Serialization; -namespace ATXSerializables +namespace ATXCommon.Serializables { [Serializable] public class ServiceStatus diff --git a/ATXSerializables/TimeUtils.cs b/ATXSerializables/TimeUtils.cs new file mode 100644 index 0000000000000000000000000000000000000000..04cc8fa2817d8ea8504fd237c452e3e474ada3e6 --- /dev/null +++ b/ATXSerializables/TimeUtils.cs @@ -0,0 +1,15 @@ +using System; + +namespace ATXCommon +{ + public static class TimeUtils + { + /// <summary> + /// Helper method to create timestamp strings in a consistent fashion. + /// </summary> + /// <returns>A timestamp string of the current time.</returns> + public static string Timestamp() { + return DateTime.Now.ToString("yyyy-MM-dd__HH-mm-ss"); + } + } +} diff --git a/ATXService.sln b/ATXService.sln index 59edaea57f66290c16fc86e657f476471404cd12..7ce63be1fa780b2bed144be4ebed8a6ba76180e9 100644 --- a/ATXService.sln +++ b/ATXService.sln @@ -5,10 +5,12 @@ VisualStudioVersion = 12.0.40629.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ATXProject", "AutoTx\ATXProject.csproj", "{5CB67E3A-E63A-4791-B90B-8CEF0027AEAD}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ATXSerializables", "ATXSerializables\ATXSerializables.csproj", "{166D65D5-EE10-4364-8AA3-4D86BA5CE244}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ATXCommon", "ATXSerializables\ATXCommon.csproj", "{166D65D5-EE10-4364-8AA3-4D86BA5CE244}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ATXConfigTest", "ATXConfigTest\ATXConfigTest.csproj", "{81E0A5AC-0E0D-4F98-B399-41A58612EF33}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ATXTray", "ATXTray\ATXTray.csproj", "{0CEB80C5-65DB-406B-BCFA-4D0474C2309B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -27,6 +29,10 @@ Global {81E0A5AC-0E0D-4F98-B399-41A58612EF33}.Debug|Any CPU.Build.0 = Debug|Any CPU {81E0A5AC-0E0D-4F98-B399-41A58612EF33}.Release|Any CPU.ActiveCfg = Release|Any CPU {81E0A5AC-0E0D-4F98-B399-41A58612EF33}.Release|Any CPU.Build.0 = Release|Any CPU + {0CEB80C5-65DB-406B-BCFA-4D0474C2309B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0CEB80C5-65DB-406B-BCFA-4D0474C2309B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0CEB80C5-65DB-406B-BCFA-4D0474C2309B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0CEB80C5-65DB-406B-BCFA-4D0474C2309B}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/ATXTray/ATXTray.csproj b/ATXTray/ATXTray.csproj new file mode 100644 index 0000000000000000000000000000000000000000..667121e89fab2f67985fc0fd4c524a9fcb09e2f6 --- /dev/null +++ b/ATXTray/ATXTray.csproj @@ -0,0 +1,105 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProjectGuid>{0CEB80C5-65DB-406B-BCFA-4D0474C2309B}</ProjectGuid> + <OutputType>WinExe</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>ATXTray</RootNamespace> + <AssemblyName>ATXTray</AssemblyName> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <PlatformTarget>AnyCPU</PlatformTarget> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup> + <ApplicationIcon>AutoTx.ico</ApplicationIcon> + </PropertyGroup> + <ItemGroup> + <Reference Include="Microsoft.WindowsAPICodePack, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL"> + <HintPath>..\packages\Microsoft.WindowsAPICodePack-Core.1.1.0.0\lib\Microsoft.WindowsAPICodePack.dll</HintPath> + <Private>True</Private> + </Reference> + <Reference Include="Microsoft.WindowsAPICodePack.Shell, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL"> + <HintPath>..\packages\Microsoft.WindowsAPICodePack-Shell.1.1.0.0\lib\Microsoft.WindowsAPICodePack.Shell.dll</HintPath> + <Private>True</Private> + </Reference> + <Reference Include="Microsoft.WindowsAPICodePack.ShellExtensions, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL"> + <HintPath>..\packages\Microsoft.WindowsAPICodePack-Shell.1.1.0.0\lib\Microsoft.WindowsAPICodePack.ShellExtensions.dll</HintPath> + <Private>True</Private> + </Reference> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="System.Xml.Linq" /> + <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="System.Data" /> + <Reference Include="System.Deployment" /> + <Reference Include="System.Drawing" /> + <Reference Include="System.Windows.Forms" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="AutoTxTray.cs" /> + <Compile Include="Program.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + <EmbeddedResource Include="Properties\Resources.resx"> + <Generator>ResXFileCodeGenerator</Generator> + <LastGenOutput>Resources.Designer.cs</LastGenOutput> + <SubType>Designer</SubType> + </EmbeddedResource> + <Compile Include="Properties\Resources.Designer.cs"> + <AutoGen>True</AutoGen> + <DependentUpon>Resources.resx</DependentUpon> + </Compile> + <None Include="packages.config" /> + <None Include="Properties\Settings.settings"> + <Generator>SettingsSingleFileGenerator</Generator> + <LastGenOutput>Settings.Designer.cs</LastGenOutput> + </None> + <Compile Include="Properties\Settings.Designer.cs"> + <AutoGen>True</AutoGen> + <DependentUpon>Settings.settings</DependentUpon> + <DesignTimeSharedInput>True</DesignTimeSharedInput> + </Compile> + </ItemGroup> + <ItemGroup> + <None Include="App.config" /> + </ItemGroup> + <ItemGroup> + <Content Include="AutoTx.ico" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\ATXSerializables\ATXCommon.csproj"> + <Project>{166D65D5-EE10-4364-8AA3-4D86BA5CE244}</Project> + <Name>ATXCommon</Name> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project> \ No newline at end of file diff --git a/ATXTray/App.config b/ATXTray/App.config new file mode 100644 index 0000000000000000000000000000000000000000..8e15646352ec1d9a84bbc6504ef6b46e16bf7823 --- /dev/null +++ b/ATXTray/App.config @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8" ?> +<configuration> + <startup> + <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> + </startup> +</configuration> \ No newline at end of file diff --git a/ATXTray/AutoTx.ico b/ATXTray/AutoTx.ico new file mode 100644 index 0000000000000000000000000000000000000000..86d3957ca994afc11765c905518831604be8b3fd Binary files /dev/null and b/ATXTray/AutoTx.ico differ diff --git a/ATXTray/AutoTxTray.cs b/ATXTray/AutoTxTray.cs new file mode 100644 index 0000000000000000000000000000000000000000..005212714490ea8709c7460c5fe54b85dba696e8 --- /dev/null +++ b/ATXTray/AutoTxTray.cs @@ -0,0 +1,306 @@ +using System; +using System.Diagnostics; +using System.Timers; +using System.Drawing; +using System.IO; +using System.Windows.Forms; +using ATXCommon.Serializables; +using Microsoft.WindowsAPICodePack.Dialogs; +using Timer = System.Timers.Timer; + +namespace ATXTray +{ + public class AutoTxTray : ApplicationContext + { + private static readonly string AppTitle = Path.GetFileNameWithoutExtension(Application.ExecutablePath); + private static readonly Timer AppTimer = new Timer(1000); + private static bool _terminate = false; + + private static readonly string BaseDir = AppDomain.CurrentDomain.BaseDirectory; + private static readonly string ConfigFile = Path.Combine(BaseDir, "configuration.xml"); + private static readonly string StatusFile = Path.Combine(BaseDir, "status.xml"); + private static DateTime _statusAge; + private static ServiceConfig _config; + private static ServiceStatus _status; + + private static bool _statusChanged = false; + private static bool _svcRunning = false; + private static bool _svcSuspended = true; + private static string _svcSuspendReason; + + private static bool _txInProgress = false; + private static long _txSize; + + private readonly NotifyIcon _notifyIcon = new NotifyIcon(); + private readonly Icon _tiDefault = new Icon("icon-default.ico"); + private readonly Icon _tiStopped = new Icon("icon-stopped.ico"); + private readonly Icon _tiSuspended = new Icon("icon-suspended.ico"); + private readonly Icon _tiTx0 = new Icon("icon-tx-0.ico"); + private readonly Icon _tiTx1 = new Icon("icon-tx-1.ico"); + private readonly ContextMenuStrip _cmStrip = new ContextMenuStrip(); + private readonly ToolStripMenuItem _miExit = new ToolStripMenuItem(); + private readonly ToolStripMenuItem _miTitle = new ToolStripMenuItem(); + private readonly ToolStripMenuItem _miSvcRunning = new ToolStripMenuItem(); + private readonly ToolStripMenuItem _miSvcSuspended = new ToolStripMenuItem(); + private readonly ToolStripMenuItem _miTxProgress = new ToolStripMenuItem(); + private readonly ToolStripMenuItem _miTxEnqueue = new ToolStripMenuItem(); + + public AutoTxTray() { + + _notifyIcon.Icon = _tiStopped; + _notifyIcon.Visible = true; + _notifyIcon.DoubleClick += StartNewTransfer; + + // this doesn't work properly, the menu will not close etc. so we disable it for now: + // _notifyIcon.Click += ShowContextMenu; + + try { + _config = ServiceConfig.Deserialize(ConfigFile); + ReadStatus(); + SetupContextMenu(); + } + catch (Exception ex) { + var msg = "Error during initialization: " + ex.Message; + _notifyIcon.ShowBalloonTip(5000, AppTitle, msg, ToolTipIcon.Error); + // we cannot terminate the message loop (Application.Run()) while the constructor + // is being run as it is not active yet - therefore we simply remember that we want + // to exit and evaluate this in the "Elapsed" handler: + _terminate = true; + System.Threading.Thread.Sleep(5000); + } + + AppTimer.Elapsed += AppTimerElapsed; + AppTimer.Enabled = true; + } + + private void SetupContextMenu() { + _miExit.Text = @"Exit"; + _miExit.Click += MiExitClick; + + _miTitle.Font = new Font(_cmStrip.Font, FontStyle.Bold); + _miTitle.Text = AppTitle; + _miTitle.Image = Image.FromFile("icon-default.ico"); + _miTitle.BackColor = Color.LightCoral; + _miTitle.Click += ShowContextMenu; + + _miSvcRunning.Text = @"Service NOT RUNNING!"; + _miSvcRunning.BackColor = Color.LightCoral; + _miSvcRunning.Click += ShowContextMenu; + + _miSvcSuspended.Text = @"No limits apply, service active."; + _miSvcSuspended.Click += ShowContextMenu; + + _miTxProgress.Text = @"No transfer running."; + _miTxProgress.Click += ShowContextMenu; + + _miTxEnqueue.Text = @"+++ Add new directory for transfer. +++"; + _miTxEnqueue.Click += StartNewTransfer; + + _cmStrip.Items.AddRange(new ToolStripItem[] { + _miTitle, + _miSvcRunning, + _miSvcSuspended, + _miTxProgress, + new ToolStripSeparator(), + _miTxEnqueue, + new ToolStripSeparator(), + _miExit + }); + + _notifyIcon.ContextMenuStrip = _cmStrip; + } + + private void AutoTxTrayExit() { + _notifyIcon.Visible = false; + Application.Exit(); + } + + /// <summary> + /// Update the tooltip making sure not to exceed the 63 characters limit. + /// </summary> + /// <param name="msg"></param> + private void UpdateHoverText(string msg) { + if (msg.Length > 63) { + msg = msg.Substring(0, 60) + "..."; + } + _notifyIcon.Text = msg; + } + + private void AppTimerElapsed(object sender, ElapsedEventArgs e) { + if (_terminate) { + AutoTxTrayExit(); + return; + } + + UpdateSvcRunning(); + + var heartBeat = "?"; + var serviceRunning = "stopped"; + var txProgress = "No"; + + if (_svcRunning) { + serviceRunning = "OK"; + ReadStatus(); + UpdateSvcSuspended(); + UpdateTxInProgress(); + if ((DateTime.Now - _status.LastStatusUpdate).TotalSeconds < 60) + heartBeat = "OK"; + if (_txInProgress) + txProgress = _txSize.ToString(); + } + + UpdateTrayIcon(); + + if (!_statusChanged) + return; + + UpdateHoverText(string.Format("AutoTx [svc={0}] [hb={1}] [tx={2}]", + serviceRunning, heartBeat, txProgress)); + } + + private void MiExitClick(object sender, EventArgs e) { + AutoTxTrayExit(); + } + + private void ShowContextMenu(object sender, EventArgs e) { + // just show the menu again, to avoid that clicking the menu item closes the context + // menu without having to disable the item (which would grey out the text and icon): + _notifyIcon.ContextMenuStrip.Show(); + } + + private static void StartNewTransfer(object sender, EventArgs e) { + var dirDialog = new CommonOpenFileDialog { + Title = @"Select directory to be transferred", + IsFolderPicker = true, + EnsurePathExists = true, + DefaultDirectory = _config.SourceDrive + }; + if (dirDialog.ShowDialog() == CommonFileDialogResult.Ok) { + MessageBox.Show("Directory\nselected:\n\n" + dirDialog.FileName + + "\n\nWARNING: adding new transfers is NOT YET IMPLEMENTED!", + "New transfer confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + } + } + + /// <summary> + /// Read (or re-read) the service status file if it has changed since last time. + /// </summary> + private static void ReadStatus() { + var age = new FileInfo(StatusFile).LastWriteTime; + if (age == _statusAge) + return; + + _statusAge = age; + _status = ServiceStatus.Deserialize(StatusFile, _config); + } + + /// <summary> + /// Check if a process with the expeced name of the service is currently running. + /// </summary> + /// <returns>True if such a process exists, false otherwise.</returns> + private static bool ServiceProcessRunning() { + var plist = Process.GetProcessesByName("AutoTx"); + return plist.Length > 0; + } + + private void UpdateSvcRunning() { + var curSvcRunState = ServiceProcessRunning(); + if (_svcRunning == curSvcRunState) + return; + + _statusChanged = true; + _svcRunning = curSvcRunState; + if (_svcRunning) { + _miSvcRunning.Text = @"Service running."; + _miSvcRunning.BackColor = Color.LightGreen; + _miTitle.BackColor = Color.LightGreen; + _miSvcSuspended.Enabled = true; + _notifyIcon.ShowBalloonTip(500, AppTitle, + "Service running.", ToolTipIcon.Info); + } else { + _miSvcRunning.Text = @"Service NOT RUNNING!"; + _miSvcRunning.BackColor = Color.LightCoral; + _miTitle.BackColor = Color.LightCoral; + _miSvcSuspended.Enabled = false; + _notifyIcon.ShowBalloonTip(500, AppTitle, + "Service stopped.", ToolTipIcon.Error); + } + } + + private void UpdateSvcSuspended() { + // first update the suspend reason as this can possibly change even if the service + // never leaves the suspended state and we should still display the correct reason: + if (_svcSuspendReason == _status.LimitReason && + _svcSuspended == _status.ServiceSuspended) + return; + + _statusChanged = true; + _svcSuspended = _status.ServiceSuspended; + _svcSuspendReason = _status.LimitReason; + if (_svcSuspended) { + _miSvcSuspended.Text = @"Service suspended, reason: " + _svcSuspendReason; + _miSvcSuspended.BackColor = Color.LightSalmon; + /* + _notifyIcon.ShowBalloonTip(500, "AutoTx Monitor", + "Service suspended: " + _status.LimitReason, ToolTipIcon.Warning); + */ + } else { + _miSvcSuspended.Text = @"No limits apply, service active."; + _miSvcSuspended.BackColor = Color.LightGreen; + /* + _notifyIcon.ShowBalloonTip(500, "AutoTx Monitor", + "Service resumed, no limits apply.", ToolTipIcon.Info); + */ + } + } + + private void UpdateTxInProgress() { + if (_txInProgress == _status.TransferInProgress && + _txSize == _status.CurrentTransferSize) + return; + + _statusChanged = true; + _txInProgress = _status.TransferInProgress; + _txSize = _status.CurrentTransferSize; + if (_txInProgress) { + _miTxProgress.Text = @"Transfer in progress (size: " + _txSize + ")"; + _miTxProgress.BackColor = Color.LightGreen; + _notifyIcon.ShowBalloonTip(500, AppTitle, + "New transfer started (size: " + _txSize + ").", ToolTipIcon.Info); + } else { + _miTxProgress.Text = @"No transfer running."; + _miTxProgress.ResetBackColor(); + _notifyIcon.ShowBalloonTip(500, AppTitle, + "Transfer completed.", ToolTipIcon.Info); + } + } + + private void UpdateTrayIcon() { + if (_txInProgress && + !_svcSuspended) { + if (DateTime.Now.Second % 2 == 0) { + _notifyIcon.Icon = _tiTx0; + } else { + _notifyIcon.Icon = _tiTx1; + } + } + + if (!_statusChanged) + return; + + if (!_svcRunning) { + _notifyIcon.Icon = _tiStopped; + return; + } + + if (_svcSuspended) { + _notifyIcon.Icon = _tiSuspended; + return; + } + + if (!_txInProgress) { + _notifyIcon.Icon = _tiDefault; + } + } + } +} diff --git a/ATXTray/Program.cs b/ATXTray/Program.cs new file mode 100644 index 0000000000000000000000000000000000000000..adc49d615e955b305191917ad0fcd0f16ea69527 --- /dev/null +++ b/ATXTray/Program.cs @@ -0,0 +1,18 @@ +using System; +using System.Windows.Forms; + +namespace ATXTray +{ + internal static class Program + { + /// <summary> + /// The main entry point for the application. + /// </summary> + [STAThread] + private static void Main() { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new AutoTxTray()); + } + } +} diff --git a/ATXTray/Properties/AssemblyInfo.cs b/ATXTray/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..0dfbe941ce8e7f9f65a066b7b9e5d1342c491d39 --- /dev/null +++ b/ATXTray/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ATXTray")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Universitaet Basel")] +[assembly: AssemblyProduct("ATXTray")] +[assembly: AssemblyCopyright("Copyright © Universitaet Basel 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("7598872a-83dd-47c3-bdcc-aa37313903c9")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ATXTray/Properties/Resources.Designer.cs b/ATXTray/Properties/Resources.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..5d0d9dcd7267cfa4b898f3c02466c0c380ef119b --- /dev/null +++ b/ATXTray/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// </auto-generated> +//------------------------------------------------------------------------------ + +namespace ATXTray.Properties +{ + + + /// <summary> + /// A strongly-typed resource class, for looking up localized strings, etc. + /// </summary> + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// <summary> + /// Returns the cached ResourceManager instance used by this class. + /// </summary> + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ATXTray.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// <summary> + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// </summary> + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/ATXTray/Properties/Resources.resx b/ATXTray/Properties/Resources.resx new file mode 100644 index 0000000000000000000000000000000000000000..af7dbebbacef595e3089c01c05671016c21a8304 --- /dev/null +++ b/ATXTray/Properties/Resources.resx @@ -0,0 +1,117 @@ +<?xml version="1.0" encoding="utf-8"?> +<root> + <!-- + Microsoft ResX Schema + + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + <resheader name="resmimetype">text/microsoft-resx</resheader> + <resheader name="version">2.0</resheader> + <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> + <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> + <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> + <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> + <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> + <value>[base64 mime encoded serialized .NET Framework object]</value> + </data> + <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> + <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> + <comment>This is a comment</comment> + </data> + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> +</root> \ No newline at end of file diff --git a/ATXTray/Properties/Settings.Designer.cs b/ATXTray/Properties/Settings.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..6eec4f8c6a77541ff8e20d1dd059a51f0cffe81b --- /dev/null +++ b/ATXTray/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// </auto-generated> +//------------------------------------------------------------------------------ + +namespace ATXTray.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/ATXTray/Properties/Settings.settings b/ATXTray/Properties/Settings.settings new file mode 100644 index 0000000000000000000000000000000000000000..39645652af62950ebf3b28ec3a5400dcec30b1c4 --- /dev/null +++ b/ATXTray/Properties/Settings.settings @@ -0,0 +1,7 @@ +<?xml version='1.0' encoding='utf-8'?> +<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)"> + <Profiles> + <Profile Name="(Default)" /> + </Profiles> + <Settings /> +</SettingsFile> diff --git a/ATXTray/icon-default.ico b/ATXTray/icon-default.ico new file mode 100644 index 0000000000000000000000000000000000000000..86d3957ca994afc11765c905518831604be8b3fd Binary files /dev/null and b/ATXTray/icon-default.ico differ diff --git a/ATXTray/icon-stopped.ico b/ATXTray/icon-stopped.ico new file mode 100644 index 0000000000000000000000000000000000000000..02d364443336f196074efd097d7ee755279f7275 Binary files /dev/null and b/ATXTray/icon-stopped.ico differ diff --git a/ATXTray/icon-suspended.ico b/ATXTray/icon-suspended.ico new file mode 100644 index 0000000000000000000000000000000000000000..55b7e1ce461aefb3ac004ce8d30f87d284bd1679 Binary files /dev/null and b/ATXTray/icon-suspended.ico differ diff --git a/ATXTray/icon-tx-0.ico b/ATXTray/icon-tx-0.ico new file mode 100644 index 0000000000000000000000000000000000000000..a0a4a78fe06861289a3d84142137ce7aa3ca0553 Binary files /dev/null and b/ATXTray/icon-tx-0.ico differ diff --git a/ATXTray/icon-tx-1.ico b/ATXTray/icon-tx-1.ico new file mode 100644 index 0000000000000000000000000000000000000000..c8da555da28babd247932ab7bf040f7a978f70a8 Binary files /dev/null and b/ATXTray/icon-tx-1.ico differ diff --git a/ATXTray/packages.config b/ATXTray/packages.config new file mode 100644 index 0000000000000000000000000000000000000000..e06f06e7fa0552bd8975b1b653293aca0059d869 --- /dev/null +++ b/ATXTray/packages.config @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="Microsoft.WindowsAPICodePack-Core" version="1.1.0.0" targetFramework="net45" /> + <package id="Microsoft.WindowsAPICodePack-Shell" version="1.1.0.0" targetFramework="net45" /> +</packages> \ No newline at end of file diff --git a/AutoTx/ATXProject.csproj b/AutoTx/ATXProject.csproj index 5d3ca82039312efa17dffc96974af331c30b88c0..15cfffa998cfbf6cd92f4988e80657a9b2fd6f1c 100644 --- a/AutoTx/ATXProject.csproj +++ b/AutoTx/ATXProject.csproj @@ -148,9 +148,9 @@ <None Include="Resources\BuildCommit.txt" /> </ItemGroup> <ItemGroup> - <ProjectReference Include="..\ATXSerializables\ATXSerializables.csproj"> + <ProjectReference Include="..\ATXSerializables\ATXCommon.csproj"> <Project>{166D65D5-EE10-4364-8AA3-4D86BA5CE244}</Project> - <Name>ATXSerializables</Name> + <Name>ATXCommon</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> diff --git a/AutoTx/AutoTx.cs b/AutoTx/AutoTx.cs index e2cacbcbfb1a7917bb44d7943bee8f43ad75776a..c6f7d84ce39dcb21d6cefc15b582ad35d2bf9d47 100644 --- a/AutoTx/AutoTx.cs +++ b/AutoTx/AutoTx.cs @@ -9,7 +9,8 @@ using System.Timers; using System.DirectoryServices.AccountManagement; using System.Globalization; using System.Management; -using ATXSerializables; +using ATXCommon.Serializables; +using ATXCommon; using RoboSharp; namespace AutoTx @@ -413,14 +414,6 @@ namespace AutoTx } } - /// <summary> - /// Helper method to create timestamp strings in a consistent fashion. - /// </summary> - /// <returns>A timestamp string of the current time.</returns> - private static string CreateTimestamp() { - return DateTime.Now.ToString("yyyy-MM-dd__HH-mm-ss"); - } - #endregion #region ActiveDirectory, email address, user name, ... @@ -733,7 +726,7 @@ namespace AutoTx var targetDir = Path.Combine( _managedPath, target, - CreateTimestamp(), + TimeUtils.Timestamp(), userDir.Name); if (MoveAllSubDirs(userDir, targetDir)) return; @@ -758,7 +751,7 @@ namespace AutoTx _managedPath, "DONE", sourceDirectory.Name, // the username directory - CreateTimestamp()); + TimeUtils.Timestamp()); // writeLogDebug("MoveToGraceLocation: src(" + sourceDirectory.FullName + ") dst(" + dstPath + ")"); try { @@ -787,6 +780,7 @@ namespace AutoTx /// </summary> /// <param name="sourceDir">The source path as DirectoryInfo object.</param> /// <param name="destPath">The destination path as a string.</param> + /// <param name="resetAcls">Whether to reset the ACLs on the moved subdirectories.</param> /// <returns>True on success, false otherwise.</returns> private bool MoveAllSubDirs(DirectoryInfo sourceDir, string destPath, bool resetAcls = false) { // TODO: check whether _transferState should be adjusted while moving dirs! @@ -803,7 +797,7 @@ namespace AutoTx var target = Path.Combine(destPath, subDir.Name); // make sure NOT to overwrite the subdirectories: if (Directory.Exists(target)) - target += "_" + CreateTimestamp(); + target += "_" + TimeUtils.Timestamp(); writeLogDebug(" - " + subDir.Name + " > " + target); subDir.MoveTo(target); @@ -848,7 +842,7 @@ namespace AutoTx if (unique == false) return dirPath; - dirPath = dirPath + "_" + CreateTimestamp(); + dirPath = dirPath + "_" + TimeUtils.Timestamp(); } Directory.CreateDirectory(dirPath); writeLogDebug("Created directory: " + dirPath); @@ -915,17 +909,6 @@ namespace AutoTx _lastUserDirCheck = DateTime.Now; } - /// <summary> - /// Recursively sum up size of all files under a given path. - /// </summary> - /// <param name="path">Full path of the directory.</param> - /// <returns>The total size in bytes.</returns> - public static long GetDirectorySize(string path) { - return new DirectoryInfo(path) - .GetFiles("*", SearchOption.AllDirectories) - .Sum(file => file.Length); - } - /// <summary> /// Generate a report on expired folders in the grace location. /// @@ -977,7 +960,7 @@ namespace AutoTx continue; long size = -1; try { - size = GetDirectorySize(subdir.FullName) / MegaBytes; + size = FsUtils.GetDirectorySize(subdir.FullName) / MegaBytes; } catch (Exception ex) { writeLog("ERROR getting directory size of " + subdir.FullName + diff --git a/AutoTx/RoboCommand.cs b/AutoTx/RoboCommand.cs index fa0233e3e9adbbac0c4a57d0c365ace0c0c31ed6..9c04350250e4c07fbf203f383ede0cc2c0a187cb 100644 --- a/AutoTx/RoboCommand.cs +++ b/AutoTx/RoboCommand.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Management; +using ATXCommon; using RoboSharp; namespace AutoTx @@ -22,7 +23,7 @@ namespace AutoTx return; _status.CurrentTransferSrc = sourcePath; - _status.CurrentTransferSize = GetDirectorySize(sourcePath); + _status.CurrentTransferSize = FsUtils.GetDirectorySize(sourcePath); // the user name is expected to be the last part of the path: _status.CurrentTargetTmp = new DirectoryInfo(sourcePath).Name;