using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using SharpUtils;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using LaptopCommunications;
using System.Text;
using System.IO;
using System.Security;
using System.Security.Permissions;
using System.Net.Sockets;
namespace LaptopBackupService
{
public class BackUpService : System.ServiceProcess.ServiceBase
{
/// <summary>
/// Timer for checking when a backup is to be completed
/// </summary>
private System.Timers.Timer backupTimer;
/// <summary>
/// Log progess as u go
/// </summary>
private SimpleEventLog eventLog;
/// <summary>
/// control the amount of information written
/// </summary>
private DebugLevel debugLevel;
/// <summary>
/// set up a channel between the client and the server
/// </summary>
private TcpChannel commsChannel;
/// <summary>
/// Registry access
/// </summary>
private QuickRegistry reg;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private static bool bStarted = false;
private static bool bWorking = false;
/// <summary>
/// file details returned from the remote computer for file copying
/// </summary>
private FileDetails fileDetails;
/// <summary>
/// port number to use
/// </summary>
private string strPortNumber;
/// <summary>
/// local variables
/// </summary>
private string strComputerName;
private string strIPAddress;
public BackUpService()
{
// This call is required by the Windows.Forms Component Designer.
InitializeComponent();
/// set the debugging level to the current level set in the form
debugLevel = new DebugLevel( DebugLevel.currentLevel );
/// set up the eventlog writer
eventLog = new SimpleEventLog( "Laptop Backup", true );
reg = new QuickRegistry();
reg.OpenKey( "HKEY_LOCAL_MACHINE", "Software\\Laptop Backup", true );
if( reg.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteError( "Unable to open the registry key " + reg.ErrorMessage );
}
}
strPortNumber = ( string )reg.GetValue( "PortNumber" );
if( reg.Error == true || strPortNumber == null )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.WarningsAndErrors ) == true )
{
eventLog.WriteError( "Unable to get the number for Laptop Backup setting to default " );
}
strPortNumber = "8086";
}
commsChannel = new TcpChannel( Int32.Parse( strPortNumber ) );
ChannelServices.RegisterChannel( commsChannel );
RemotingConfiguration.RegisterWellKnownServiceType( typeof( CommunicationChannel ), "LaptopBackup", WellKnownObjectMode.SingleCall );
reg = new QuickRegistry();
}
// The main entry point for the process
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
// More than one user Service may run within the same process. To add
// another service to this process, change the following line to
// create a second service object. For example,
//
// ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
//
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new BackUpService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.backupTimer = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)(this.backupTimer)).BeginInit();
//
// backupTimer
//
this.backupTimer.Enabled = true;
this.backupTimer.Interval = 600000;
this.backupTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnBackUpTimerTick);
//
// BackUpService
//
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.ServiceName = "BackUpService";
((System.ComponentModel.ISupportInitialize)(this.backupTimer)).EndInit();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
protected override void OnStart(string[] args)
{
/// as stop and start can be controlled by the user set here as well
backupTimer.AutoReset = true;
backupTimer.Enabled = true;
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) )
{
eventLog.WriteInformation( "Starting Laptop Backup Service" );
}
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
backupTimer.AutoReset = false;
backupTimer.Enabled = false;
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) )
{
eventLog.WriteInformation( "Stopping Laptop Backup Service" );
}
/// original idea was that when the service is stopped as windows shuts down the days til
/// the next copy is done is decremented. This doesn't happen so changed below to decrementing
/// the days til check when a file/directory is denoted as not needing doing today
/// CheckRegistryKeys( 2 );
}
/// <summary>
/// Check that the required registry keys are present for the service if
/// not create them with default values
/// </summary>
/// <param name="nCheck">nCheck can be 0 for just a creation check 1 for a reset to starting position and 2 for</param>
private void CheckRegistryKeys( int nCheck )
{
QuickRegistry checkRegistry = new QuickRegistry();
StringBuilder buffer = new StringBuilder();
StringBuilder strTest = new StringBuilder();
StringBuilder strComputerName = new StringBuilder();
if( checkRegistry.OpenKey( "HKEY_LOCAL_MACHINE", "Software\\Laptop Backup", true ) == false )
{
/// unfortuanetly due to a bug in the registry code this may be needed
if( checkRegistry.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteError( "Unable to open the registry key " + checkRegistry.ErrorMessage );
}
}
}
else
{
string[] subKeys = checkRegistry.GetSubKeyNames();
if( checkRegistry.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.WarningsAndErrors ) == true )
{
eventLog.WriteWarning( "There are no keys setup on this computer " + checkRegistry.ErrorMessage );
}
}
string[] childSubKeys;
if( subKeys != null && subKeys.Length > 0 )
{
foreach( string strKey in subKeys )
{
strComputerName.Remove( 0, strComputerName.Length );
strComputerName.Append( strKey );
checkRegistry.OpenKeyFromCurrentKey( strComputerName.ToString(), false );
if( reg.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Open Error " + checkRegistry.ErrorMessage );
}
continue;
}
else
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Opened the Registry Key " + strKey );
}
}
childSubKeys = checkRegistry.GetSubKeyNames();
if( childSubKeys.Length > 0 )
{
QuickRegistry childReg = new QuickRegistry();
foreach( string strChildKey in childSubKeys )
{
buffer.Remove( 0, buffer.ToString().Length );
buffer.Append( "Software\\Laptop Backup" + "\\" + strComputerName.ToString() + "\\" + strChildKey );
if( childReg.OpenKey( "HKEY_LOCAL_MACHINE", buffer.ToString(), true ) == false )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Unable to open registry key " + strComputerName.ToString() + "\\" + strChildKey );
}
continue;
}
else
{
/// check for the service specific keys
/// based on the check value
/// if true its just a check if false a reset
if( nCheck == 0 )
{
/// create the key
childReg.SetValue( "Done", false );
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Created the done key for " + strComputerName.ToString() + "\\" + strChildKey );
}
}
else if( nCheck == 1 )
{
childReg.SetValue( "Done", true );
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Set the Done key to true for " + strComputerName.ToString() + "\\" + strChildKey );
}
}
else /// if( nCheck == 2 )
{
/// reduce the DaysTilCheckNumber if 0 replace with numdays as long as
/// today not equal to DateLastChecked
strTest.Remove( 0, strTest.Length );
strTest.Append( ( string )childReg.GetValue( "DateLastChecked" ) );
if( strTest.Length > 0 )
{
if( strTest.ToString() != DateTime.Today.ToShortDateString() )
{
int nCount = ( Int32 )childReg.GetValue( "DaysTilCheck" );
if( nCount == 0 && childReg.GetValue( "Done" ).ToString() == "True" )
{
childReg.SetValue( "DaysTilCheck", childReg.GetValue( "NumDays" ) );
}
else
{
DateTime dtTemp = ( DateTime )childReg.GetValue( "DateLastChecked" );
int nDaysCount = dtTemp.DayOfYear - DateTime.Today.DayOfYear;
if( nDaysCount > 1 )
{
nCount -= ( nDaysCount -1 );
}
nCount--;
childReg.SetValue( "DaysTilCheck", nCount );
}
}
}
}
}
}
}
checkRegistry.RevertToPrevious();
}
}
}
checkRegistry.Close( true );
}
private CommunicationChannel GetCommunicationsChannel()
{
StringBuilder buffer = new StringBuilder();
buffer.Append( "tcp://" );
buffer.Append( strIPAddress );
buffer.Append( ":" );
buffer.Append( strPortNumber );
buffer.Append( "/LaptopBackup" );
/// got all the information stored by the gui now do the service stuff
/// start by connecting to the computer
///
try
{
CommunicationChannel communicationsChannel;
communicationsChannel = ( CommunicationChannel )Activator.GetObject( typeof( CommunicationChannel ), buffer.ToString() );
return communicationsChannel;
}
catch( RemotingTimeoutException rtoExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "remoting time out exception " + rtoExp.Message );
}
}
catch( NullReferenceException nullExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "The url for the object is invalid " + nullExp.Message );
}
}
catch( RemotingException remExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "The object type is not defined properly, it needs to be derived for a remoting class " + remExp.Message );
}
}
catch( Exception exp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "An generic exception caught " + exp.Message );
}
}
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "communications channel established with " + buffer.ToString() );
}
return null;
}
/// <summary>
/// When the timer goes off check through all the items that are stored in the registry
/// if one is set to go off within this minute then
/// get the information from the registry
/// establish a communication with the remote machine
/// attempt to get the required file and copy it to this disk based on set parameters
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnBackUpTimerTick(object sender, System.Timers.ElapsedEventArgs e)
{
/// TODO check to see if any backups are to be performed at the moment
if( bStarted == false )
{
bStarted = true;
CheckRegistryKeys( 0 );
}
CommunicationChannel communicationsChannel = null;
/// if copying takes more than a minute then reject further
/// requests as if they are improtant they will be marked try til done
if( bWorking == false )
{
bWorking = true;
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Set working to true, accepting no more requests til finished " );
}
}
else
{
if( debugLevel.TestDebugLevel( DebugLevelSet.WarningsAndErrors ) == true )
{
eventLog.WriteWarning( "Rejecting the fired timer as program is currently busy " );
}
return;
}
StringBuilder buffer = new StringBuilder();
StringBuilder strName = new StringBuilder();
StringBuilder strFullPath = new StringBuilder();
StringBuilder strCheckedCopy = new StringBuilder();
StringBuilder strDirectoryCopy = new StringBuilder();
StringBuilder strHours = new StringBuilder();
StringBuilder strMinutes = new StringBuilder();
StringBuilder strLocation = new StringBuilder();
StringBuilder strDays = new StringBuilder();
StringBuilder strOnStart = new StringBuilder();
StringBuilder strTryTilDone = new StringBuilder();
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Back up Timer fired" );
}
if( reg.OpenKey( "HKEY_LOCAL_MACHINE", "Software\\Laptop Backup", true ) == false )
{
if( reg.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteError( "Unable to open the registry key " + reg.ErrorMessage );
}
}
}
else
{
string[] subKeys = reg.GetSubKeyNames();
if( reg.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.WarningsAndErrors ) == true )
{
eventLog.WriteWarning( "There are no keys setup on this computer " + reg.ErrorMessage );
}
}
string[] childSubKeys;
if( subKeys != null && subKeys.Length > 0 )
{
foreach( string strKey in subKeys )
{
strComputerName = strKey;
reg.OpenKeyFromCurrentKey( strComputerName, false );
if( reg.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Open Error " + reg.ErrorMessage );
}
continue;
}
else
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Opened the Registry Key " + strKey );
}
strIPAddress = reg.GetValue( "IPAddress" ).ToString();
communicationsChannel = GetCommunicationsChannel();
if( communicationsChannel == null )
{
/// error will have been reported
bWorking = false;
return;
}
/// get the details for each item
/// needs a new regkey
childSubKeys = reg.GetSubKeyNames();
if( childSubKeys.Length > 0 )
{
QuickRegistry childReg = new QuickRegistry();
foreach( string strChildKey in childSubKeys )
{
lock( this )
{
buffer.Remove( 0, buffer.ToString().Length );
buffer.Append( "Software\\Laptop Backup" + "\\" + strComputerName + "\\" + strChildKey );
if( childReg.OpenKey( "HKEY_LOCAL_MACHINE", buffer.ToString(), true ) == false )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Unable to open registry key " + strComputerName + "\\" + strChildKey );
}
continue;
}
else
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Opened registry key " + strComputerName + "\\" + strChildKey );
}
try
{
strName.Remove( 0, strName.ToString().Length );
strName.Append( childReg.GetValue( "Name" ).ToString() );
strFullPath.Remove( 0, strFullPath.ToString().Length );
strFullPath.Append( childReg.GetValue( "FullPath" ).ToString() );
/// The following are allowed to be null but tested individually
/// so one null doesn't mean all are null
try /// allow null
{
strCheckedCopy.Remove( 0, strCheckedCopy.ToString().Length );
strCheckedCopy.Append( childReg.GetValue( "CheckedCopy" ).ToString() );
}
catch( NullReferenceException nrefexp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Checked copy for " + strChildKey + " is null " + nrefexp.Message );
}
}
try /// allow null
{
strDirectoryCopy.Remove( 0, strDirectoryCopy.ToString().Length );
strDirectoryCopy.Append( childReg.GetValue( "DirectoryCopy" ).ToString() );
}
catch( NullReferenceException nrefexp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Directory Copy for " + strChildKey + " is null " + nrefexp.Message );
}
}
try /// allow null wont be once finished but earlier code didn't have it
{
strTryTilDone.Remove( 0, strTryTilDone.ToString().Length );
strTryTilDone.Append( childReg.GetValue( "TryTilDone" ).ToString() );
}
catch( NullReferenceException nrefExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Try Til Done for " + strChildKey + " is null " + nrefExp.Message );
}
}
strHours.Remove( 0, strHours.ToString().Length );
strHours.Append( childReg.GetValue( "Hours" ).ToString() );
strMinutes.Remove( 0, strMinutes.ToString().Length );
strMinutes.Append( childReg.GetValue( "Minutes" ).ToString() );
strLocation.Remove( 0, strLocation.ToString().Length );
strLocation.Append( childReg.GetValue( "Location" ).ToString() );
strDays.Remove( 0, strDays.ToString().Length );
strDays.Append( childReg.GetValue( "NumDays" ).ToString() );
strOnStart.Remove( 0, strOnStart.ToString().Length );
strOnStart.Append( childReg.GetValue( "CopyOnStart" ).ToString() );
}
catch( NullReferenceException nrefexp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error a required registry variable is set to false " + nrefexp.Message );
}
continue;
}
/* Test stuff
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Name for " + buffer.ToString() + " " + strName.ToString() );
eventLog.WriteInformation( "FullPath for " + buffer.ToString() + " " + strFullPath.ToString() );
eventLog.WriteInformation( "Checked Copy for " + buffer.ToString() + " " + strCheckedCopy.ToString() );
eventLog.WriteInformation( "DirectoryCopy for " + buffer.ToString() + " " + strDirectoryCopy.ToString() );
eventLog.WriteInformation( "Hours for " + buffer.ToString() + " " + strHours.ToString() );
eventLog.WriteInformation( "Minutes for " + buffer.ToString() + " " + strMinutes.ToString() );
eventLog.WriteInformation( "Location for " + buffer.ToString() + " " + strLocation.ToString() );
eventLog.WriteInformation( "Days for " + buffer.ToString() + " " + strDays.ToString() );
eventLog.WriteInformation( "OnStart for " + buffer.ToString() + " " + strOnStart.ToString() );
eventLog.WriteInformation( "TryTilDone for " + buffer.ToString() + " " + strTryTilDone.ToString() );
}
*/
///communicationsChannel = GetCommunicationsChannel();
/// if done get out now
if( childReg.GetValue( "Done" ).ToString() == "True" )
{
childReg.Close( false );
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "The key " + strName.ToString() + " is marked as done" );
}
continue;
}
int days = Int32.Parse( ( ( int )childReg.GetValue( "DaysTilCheck" ) ).ToString() );
/// if days to go is not equal 0 no point going any further mark it as done
if( days != 0 )
{
DateTime dtTemp = DateTime.Parse( ( string )childReg.GetValue( "DateLastChecked" ) );
eventLog.WriteInformation( "DateLastChecked = " + dtTemp.ToShortDateString() + " Todays date = " + DateTime.Now.ToShortDateString() );
eventLog.WriteInformation( "Days of year for date last checked = " + dtTemp.DayOfYear + " and for today = " + DateTime.Now.DayOfYear );
if( DateTime.Now.DayOfYear != dtTemp.DayOfYear )
{
eventLog.WriteInformation( "Updating Days Til Check" );
int nDaysCount = DateTime.Today.DayOfYear - dtTemp.DayOfYear;
if( nDaysCount > 0 )
{
childReg.SetValue( "DaysTilCheck", days - nDaysCount );
}
childReg.SetValue( "DateLastChecked", DateTime.Now.ToShortDateString() );
}
childReg.SetValue( "Done", true );
childReg.Close( false );
continue;
}
/// If try til done = true and days = 0 and done = false do it
/// If on start = true and done = false do it now ( on start doesn't use days )
/// If time matches and done = false and days = 0 do it now.
if( strTryTilDone.ToString() == "True" && days == 0 && childReg.GetValue( "Done" ).ToString() == "False" )
{
if( strDirectoryCopy.ToString() != "True" )
{
try
{
fileDetails = communicationsChannel.DoFileCopy( strFullPath.ToString() );
if( fileDetails.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error getting the file details for remote path " + strFullPath.ToString() + " " + fileDetails.ErrorMessage );
}
childReg.Close( false );
continue;
}
}
catch( SocketException socExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error communications channel is invalid, unable to get remote path " + strFullPath.ToString() + " reason " + socExp.Message );
}
childReg.Close( false );
bWorking = false;
continue;
}
catch( Exception exp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error accessing remote path " + strFullPath.ToString() + " caused an unknown error " + exp.Message );
}
childReg.Close( false );
bWorking = false;
continue;
}
}
}
else if( strOnStart.ToString() == "True" && childReg.GetValue( "Done" ).ToString() == "False" ) /// string value starts with a capital
{
if( strDirectoryCopy.ToString() != "True" )
{
try
{
fileDetails = communicationsChannel.DoFileCopy( strFullPath.ToString() );
if( fileDetails.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error getting the file details for remote path " + strFullPath + " " + fileDetails.ErrorMessage );
}
childReg.Close( false );
continue;
}
}
catch( SocketException socExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error communications channel is invalid, unable to get remote path " + strFullPath.ToString() + " reason " + socExp.Message );
}
childReg.Close( false );
bWorking = false;
continue;
}
catch( Exception exp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error accessing " + strFullPath.ToString() + " caused an unknown error " + exp.Message );
}
childReg.Close( false );
bWorking = false;
continue;
}
}
}
else if( childReg.GetValue( "Hours" ).ToString() == DateTime.Today.Hour.ToString() && childReg.GetValue( "Minutes" ).ToString() == DateTime.Today.Minute.ToString()
&& childReg.GetValue( "Done" ).ToString() == "False" && days == 0 )
{
try
{
if( strDirectoryCopy.ToString() != "True" )
{
fileDetails = communicationsChannel.DoFileCopy( strFullPath.ToString() );
}
if( fileDetails.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error getting the remote file details for " + strFullPath + " " + fileDetails.ErrorMessage );
}
childReg.Close( false );
continue;
}
}
catch( SocketException socExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error communications channel is invalid, unable to get " + strFullPath.ToString() + " on the remote computer " + " reason " + socExp.Message );
}
childReg.Close( false );
bWorking = false;
continue;
}
catch( Exception exp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error accessing " + strFullPath.ToString() + " caused an unknown error " + exp.Message );
}
childReg.Close( false );
bWorking = false;
continue;
}
}
/// straight unchecked file copy
if( strDirectoryCopy.ToString() != "True" )
{
/// copy the file if required
if( strCheckedCopy.ToString() == "False" )
{
FileStream stream = fileDetails.GetStream;
strLocation.Remove( 0, "Localhost\\".Length );
if( strLocation.ToString().EndsWith( strName.ToString() ) == false )
strLocation.Append( "\\" + strName.ToString() );
FileCopy copyFile = new FileCopy();
lock( this )
{
try
{
copyFile.CopyFile( stream, strLocation.ToString() );
}
catch( Exception exp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error Uncaught exception thrown in Copy File, reason " + exp.Message );
}
childReg.Close( false );
continue;
}
}
if( copyFile.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( copyFile.ErrorMessage );
}
childReg.Close( false );
continue;
}
else
{
childReg.SetValue( "Done", true );
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Setting " + childReg.GetCurrentKey.Name + " to done " );
}
}
fileDetails.Dispose();
}
else /// check the file dates
{
strLocation.Remove( 0, "LocalHost\\".Length );
if( strLocation.ToString().EndsWith( strName.ToString() ) == false )
strLocation.Append( "\\" + strName.ToString() );
FileDetails testLocal = new FileDetails( strLocation.ToString() );
FileCopy copyFile = new FileCopy();
lock( this )
{
try
{
copyFile.CopyCheckedFile( fileDetails, testLocal );
}
catch( Exception exp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error uncaught exception thrown in Copy Checked File, reason " + exp.Message );
}
childReg.Close( false );
bWorking = false;
continue;
}
}
if( copyFile.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( copyFile.ErrorMessage );
}
childReg.Close( false );
continue;
}
else
{
childReg.SetValue( "Done", true );
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Setting " + childReg.GetCurrentKey.Name + " to done " );
}
}
fileDetails.Dispose();
testLocal.Dispose();
}
}
else /// do a directory copy
{
/// straight copy first
if( strCheckedCopy.ToString() == "False" )
{
strLocation.Remove( 0, "LocalHost\\".Length );
strLocation.Append( "\\" );
try
{
DirectoryDetails details = communicationsChannel.GetDirectoryData( strFullPath.ToString() );
if( details.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( details.ErrorMessage );
}
childReg.Close( false );
continue;
}
/// do the files for the current directory
DirectoryInfo dirInfo = details.GetDirectoryInfo;
if( dirInfo.Exists == false )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error DirectoryInfo reports that directory " + dirInfo.FullName + " does not exist " );
}
childReg.Close( false );
continue;
}
FileInfo[] fileInfoArray = dirInfo.GetFiles();
if( fileInfoArray != null )
{
lock( this )
{
try
{
CopyFiles( fileInfoArray, strLocation.ToString() );
}
catch( Exception exp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error uncaught exception thrown in Copy Files, reason " + exp.Message );
}
childReg.Close( false );
bWorking = false;
return;
}
}
}
/// now do the directories off the current directory
DirectoryInfo[] directoryInfoArray = dirInfo.GetDirectories();
foreach( DirectoryInfo directoryInfo in directoryInfoArray )
{
/// lock out the directory copy until finished
lock( this )
{
try
{
bFirst = false;
CopyCheckedDirectories( directoryInfo, strLocation.ToString(), false, false );
}
catch( Exception exp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error uncaught exception thrown in Copy Directories, reason " + exp.Message );
}
childReg.Close( false );
bWorking = false;
return;
}
}
}
childReg.SetValue( "Done", true );
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Setting " + childReg.GetCurrentKey.Name + " to done " );
}
}
catch( SocketException socExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error communications channel is invalid, unable to get " + strFullPath.ToString() + " reason " + socExp.Message );
}
childReg.Close( false );
bWorking = false;
continue;
}
}
else /// check the file dates
{
if( strCheckedCopy.ToString() == "True" )
{
strLocation.Remove( 0, "LocalHost\\".Length );
strLocation.Append( "\\" );
DirectoryDetails details;
try
{
details = communicationsChannel.GetDirectoryData( strFullPath.ToString() );
if( details.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( details.ErrorMessage );
}
childReg.Close( false );
continue;
}
/// do the files for the current directory
DirectoryInfo dirInfo = details.GetDirectoryInfo;
if( dirInfo.Exists == false )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error DirectoryInfo reports that directory " + dirInfo.FullName + " does not exist " );
}
childReg.Close( false );
continue;
}
FileInfo[] fileInfoArray = dirInfo.GetFiles();
if( fileInfoArray.Length > 0 )
{
try
{
if( CopyCheckedFiles( fileInfoArray, strLocation.ToString() ) == false )
{
childReg.Close( false );
continue;
}
}
catch( Exception exp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error uncaught exception thrown in Copy Files reason " + exp.Message );
}
childReg.Close( false );
bWorking = false;
return;
}
}
/// now do the directories off the current directory
DirectoryInfo[] directoryInfoArray = dirInfo.GetDirectories();
foreach( DirectoryInfo directoryInfo in directoryInfoArray )
{
/// lock out the directory copy until finished
lock( this )
{
bFirst = false;
try
{
if( CopyCheckedDirectories( directoryInfo, strLocation.ToString(), false, true ) == false )
{
childReg.Close( false );
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error CopyCheckedDirectories failed and returned false" );
}
continue;
}
}
catch( Exception exp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error uncaught exception thrown in Copy Checked Directories reason " + exp.Message );
}
childReg.Close( false );
bWorking = false;
return;
}
}
}
childReg.SetValue( "Done", true );
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Setting " + childReg.GetCurrentKey.Name + " to done" );
}
}
catch( SocketException socExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Communications channel is invalid for " + buffer.ToString() + " reason " + socExp.Message );
}
childReg.Close( false );
continue;
}
catch( Exception exp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Unknown exception caught in " + exp.TargetSite + " Of Type " + exp.InnerException.ToString() + " error is " + exp.Message );
}
continue;
}
}
}
}
}
/// this one has been checked.
childReg.SetValue( "DateLastChecked", DateTime.Today.ToShortDateString() );
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Created the DateLastChecked key for " + strComputerName.ToString() + "\\" + strChildKey );
}
childReg.Close( false );
}
}
}
}
reg.RevertToPrevious();
}
}
}
bWorking = false;
reg.Close( true );
}
/// <summary>
/// Copy the files in the current directory
/// </summary>
/// <param name="fileInfoArray">Array of files to be copied</param>
private bool CopyFiles( FileInfo[] fileInfoArray, string strLocation )
{
StringBuilder strDestination = new StringBuilder();
CommunicationChannel communicationsChannel = GetCommunicationsChannel();
foreach( FileInfo file in fileInfoArray )
{
try
{
fileDetails = communicationsChannel.DoFileCopy( file.FullName );
if( fileDetails.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error getting the file details for " + file.FullName + " " + fileDetails.ErrorMessage );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
continue;
}
strDestination.Remove( 0, strDestination.Length );
strDestination.Append( strLocation );
strDestination.Append( file.Name );
FileCopy copyFile = new FileCopy();
copyFile.CopyFile( fileDetails.GetStream, strDestination.ToString() );
if( copyFile.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( copyFile.ErrorMessage );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
continue;
}
}
catch( SocketException socExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error the communications channel is invalid, unable to get " + file.FullName + " reason " + socExp.Message );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
return false;
}
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
return true;
}
/// <summary>
/// Do a checked copy on the files in the current directory
/// </summary>
/// <param name="fileInfoArray">Array of files to be copied</param>
private bool CopyCheckedFiles( FileInfo[] fileInfoArray, string strLocation )
{
StringBuilder strDestination = new StringBuilder();
CommunicationChannel communicationsChannel = GetCommunicationsChannel();
foreach( FileInfo file in fileInfoArray )
{
try
{
fileDetails = communicationsChannel.DoFileCopy( file.FullName );
if( fileDetails.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error getting the file details for " + file.FullName + " " + fileDetails.ErrorMessage );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
continue;
}
strDestination.Remove( 0, strDestination.Length );
strDestination.Append( strLocation );
strDestination.Append( file.Name );
FileCopy copyFile = new FileCopy();
FileDetails destDetails = new FileDetails( strDestination.ToString() );
copyFile.CopyCheckedFile( fileDetails, destDetails );
if( copyFile.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( copyFile.ErrorMessage );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
continue;
}
}
catch( SocketException socExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error the communications channel is invalid, unable to get " + file.FullName + " reason " + socExp.Message );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
return false;
}
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
return true;
}
/// <summary>
/// standard directory file copying with no checking
/// </summary>
/// <param name="directoryInfo"></param>
/// <param name="strLocation"></param>
/// <returns></returns>
public bool CopyDirectoryFiles( DirectoryInfo directoryInfo, string strLocation )
{
CommunicationChannel communicationsChannel = GetCommunicationsChannel();
/// copy the files for this directory
FileInfo[] fileInfoArray = directoryInfo.GetFiles();
foreach( FileInfo fileInfo in fileInfoArray )
{
try
{
fileDetails = communicationsChannel.DoFileCopy( fileInfo.FullName );
if( fileDetails.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error getting the file details for " + fileInfo.FullName + " " + fileDetails.ErrorMessage );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
continue;
}
FileDetails testLocal = new FileDetails();
bool bExists = false;
testLocal.Open( strLocation.ToString() + directoryInfo.Name + "\\" + fileInfo.Name);
if( testLocal.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "File " + strLocation.ToString() + fileInfo.Name + " does not exist, creating it " );
}
}
else
bExists = true;
FileCopy copyFile = new FileCopy();
if( bExists == true )
{
copyFile.CopyFile( fileDetails.GetStream, testLocal.GetStream );
}
else
{
copyFile.CopyFile( fileDetails.GetStream, strLocation.ToString() + fileInfo.Name );
}
if( copyFile.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( copyFile.ErrorMessage );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
continue;
}
}
catch( SocketException socExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error communications channel invalid, unable to get " + fileInfo.FullName + " reason " + socExp.Message );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
return false;
}
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
return true;
}
/// <summary>
/// copy the checked files for a directory
/// </summary>
/// <param name="directoryInfo"></param>
/// <param name="strLocation"></param>
public bool CopyCheckedDirectoryFiles( DirectoryInfo directoryInfo, string strLocation )
{
CommunicationChannel communicationsChannel = GetCommunicationsChannel();
/// copy the files for this directory
FileInfo[] fileInfoArray = directoryInfo.GetFiles();
foreach( FileInfo fileInfo in fileInfoArray )
{
try
{
fileDetails = communicationsChannel.DoFileCopy( fileInfo.FullName );
if( fileDetails.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error getting the file details for " + fileInfo.FullName + " " + fileDetails.ErrorMessage );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
continue;
}
FileDetails testLocal = new FileDetails();
bool bExists = false;
testLocal.Open( strLocation.ToString() + fileInfo.Name);
if( testLocal.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "File " + strLocation.ToString() + fileInfo.Name + " does not exist, creating it " );
}
}
else
bExists = true;
FileCopy copyFile = new FileCopy();
if( bExists == true )
{
copyFile.CopyCheckedFile( fileDetails, testLocal );
}
else
{
copyFile.CopyFile( fileDetails.GetStream, strLocation.ToString() + fileInfo.Name );
}
if( copyFile.Error == true )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( copyFile.ErrorMessage );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
if( testLocal != null && testLocal.GetStream != null )
testLocal.Dispose();
continue;
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
if( testLocal != null && testLocal.GetStream != null )
testLocal.Dispose();
}
catch( SocketException socExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error communications channel invalid, unable to get " + fileInfo.FullName + " reason " + socExp.Message );
}
if( fileDetails != null && fileDetails.GetStream != null )
fileDetails.Dispose();
return false;
}
}
return true;
}
/// <summary>
/// private static variables to keep track of the location parameter
/// </summary>
private static bool bFirst;
private StringBuilder strLocationHolder = new StringBuilder();
/// <summary>
/// recursive copy checked directories function to move through the directory listing.
/// will copy directories regardless. Only files are checked
/// </summary>
/// <param name="directoryInfoArray">Array of direcotories</param>
/// <param name="strLocation">starting location</param>
private bool CopyCheckedDirectories( DirectoryInfo directoryInfo, string strLocation, bool bRecursive, bool bChecked )
{
CommunicationChannel communicationsChannel = GetCommunicationsChannel();
StringBuilder strTempLocation = new StringBuilder();
if( bFirst == false )
{
strLocationHolder.Remove( 0, strLocationHolder.Length );
strLocationHolder.Append( strLocation );
bFirst = true;
}
DirectoryInfo[] tempDirectoryArray = directoryInfo.GetDirectories();
if( bRecursive == false )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "No further directories from " + directoryInfo.Name );
}
strTempLocation.Remove( 0, strTempLocation.Length );
if( bRecursive == false )
{
strTempLocation.Append( strLocationHolder.ToString() );
}
else
{
strTempLocation.Append( strLocation );
}
strTempLocation.Append( directoryInfo.Name + "\\" );
if( Directory.Exists( strTempLocation.ToString() ) == false )
{
DirectoryInfo createdDirInfo = Directory.CreateDirectory( strTempLocation.ToString() );
if( createdDirInfo != null )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Created the directory " + strTempLocation.ToString() );
}
}
if( bChecked == true )
CopyCheckedDirectoryFiles( directoryInfo, strTempLocation.ToString() );
else
CopyDirectoryFiles( directoryInfo, strTempLocation.ToString() );
}
else
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Directory " + strTempLocation.ToString() + " already exists " );
}
if( bChecked == true )
CopyCheckedDirectoryFiles( directoryInfo, strTempLocation.ToString() );
else
CopyDirectoryFiles( directoryInfo, strTempLocation.ToString() );
}
}
foreach( DirectoryInfo workingDirectory in tempDirectoryArray )
{
strTempLocation.Remove( 0, strTempLocation.Length );
if( bRecursive == false )
{
strTempLocation.Append( strLocationHolder.ToString() );
strTempLocation.Append( directoryInfo.Name + "\\" );
}
else
{
strTempLocation.Append( strLocation );
}
/// use recursion to get through the directory listing
DirectoryInfo[] childDirectoryArray = workingDirectory.GetDirectories();
strTempLocation.Append( workingDirectory.Name + "\\" );
try
{
if( Directory.Exists( strTempLocation.ToString() ) == false )
{
DirectoryInfo createdDirInfo = Directory.CreateDirectory( strTempLocation.ToString() );
if( createdDirInfo != null )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Created the directory " + strTempLocation.ToString() );
}
}
if( bChecked == true )
CopyCheckedDirectoryFiles( workingDirectory, strTempLocation.ToString() );
else
CopyDirectoryFiles( workingDirectory, strTempLocation.ToString() );
}
else
{
if( debugLevel.TestDebugLevel( DebugLevelSet.All ) == true )
{
eventLog.WriteInformation( "Directory " + strTempLocation.ToString() + " already exists " );
}
if( bChecked == true )
CopyCheckedDirectoryFiles( workingDirectory, strTempLocation.ToString() );
else
CopyDirectoryFiles( workingDirectory, strTempLocation.ToString() );
}
}
catch( SecurityException secExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error creating the directory, Security Exception " + strTempLocation.ToString() + " reason " + secExp.Message );
return false;
}
}
catch( ArgumentNullException argNullExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error creating the directory, Argument Null Exception " + strTempLocation.ToString() + " reason " + argNullExp.Message );
return false;
}
}
catch( ArgumentException argExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error creating the directory, Argument Exception " + strTempLocation.ToString() + " reason " + argExp.Message );
return false;
}
}
catch( PathTooLongException pathTooLExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error creating the directory, Path Too Long Exception " + strTempLocation.ToString() + " reason " + pathTooLExp.Message );
return false;
}
}
catch( DirectoryNotFoundException dirNFExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error creating the directory, Directory Not Found Exception " + strTempLocation.ToString() + " reason " + dirNFExp.Message );
return false;
}
}
catch( NotSupportedException notSupExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error creating the directory, Not Supported Exception " + strTempLocation.ToString() + " reason " + notSupExp.Message );
return false;
}
}
catch( IOException ioExp )
{
if( debugLevel.TestDebugLevel( DebugLevelSet.Errors ) == true )
{
eventLog.WriteError( "Error creating the directory, IO Exception " + strTempLocation.ToString() + " reason " + ioExp.Message );
return false;
}
}
if( childDirectoryArray.Length > 0 )
{
CopyCheckedDirectories( workingDirectory, strTempLocation.ToString(), true, bChecked );
}
}
return true;
}
}
}