SynchronizeDirectories refactoring and other minor changes

This commit is contained in:
olegkap_cp
2012-12-19 19:11:36 +00:00
parent 552a9f0cc3
commit a89085dc5a
6 changed files with 163 additions and 147 deletions
@@ -634,6 +634,9 @@
<Compile Include="..\Renci.SshNet\SftpClient.cs">
<Link>SftpClient.cs</Link>
</Compile>
<Compile Include="..\Renci.SshNet\SftpClient.NET.cs">
<Link>SftpClient.NET.cs</Link>
</Compile>
<Compile Include="..\Renci.SshNet\Sftp\Flags.cs">
<Link>Sftp\Flags.cs</Link>
</Compile>
@@ -12,10 +12,6 @@
<AssemblyName>Renci.SshNet</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -135,6 +131,7 @@
<SubType>Code</SubType>
</Compile>
<Compile Include="ConnectionInfo.cs" />
<Compile Include="SftpClient.NET.cs" />
<Compile Include="KeyboardInteractiveAuthenticationMethod.cs">
<SubType>Code</SubType>
</Compile>
+1 -6
View File
@@ -183,12 +183,7 @@ namespace Renci.SshNet
{
get
{
return (!this._isDisconnecting
&& this._socket != null
&& this._socket.Connected
&& this._isAuthenticated
&& this._messageListenerCompleted != null);
//&& !(this._socket.Poll(10, SelectMode.SelectRead));
return (!this._isDisconnecting && this._socket != null && this._socket.Connected && this._isAuthenticated && this._messageListenerCompleted != null) && !(this._socket.Poll(10, SelectMode.SelectRead));
}
}
@@ -6,7 +6,10 @@ using Renci.SshNet.Common;
using System.IO;
namespace Renci.SshNet.Sftp
{
{
/// <summary>
/// Encapsulates the results of an asynchronous directory synchronization operation.
/// </summary>
public class SftpSynchronizeDirectoriesAsyncResult : AsyncResult<IEnumerable<FileInfo>>
{
/// <summary>
@@ -0,0 +1,153 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using Renci.SshNet.Sftp;
using System.Text;
using Renci.SshNet.Common;
using System.Globalization;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
namespace Renci.SshNet
{
/// <summary>
/// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
/// </summary>
public partial class SftpClient : BaseClient
{
#region SynchronizeDirectories
public IEnumerable<FileInfo> SynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern)
{
return InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, null);
}
public IAsyncResult BeginSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, AsyncCallback asyncCallback, object state)
{
if (sourcePath == null)
throw new ArgumentNullException("sourceDir");
if (destinationPath.IsNullOrWhiteSpace())
throw new ArgumentException("destDir");
// Ensure that connection is established.
this.EnsureConnection();
var asyncResult = new SftpSynchronizeDirectoriesAsyncResult(asyncCallback, state);
this.ExecuteThread(() =>
{
try
{
var result = this.InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, asyncResult);
asyncResult.SetAsCompleted(result, false);
}
catch (Exception exp)
{
asyncResult.SetAsCompleted(exp, false);
}
});
return asyncResult;
}
public IEnumerable<FileInfo> EndSynchronizeDirectories(IAsyncResult asyncResult)
{
var ar = asyncResult as SftpSynchronizeDirectoriesAsyncResult;
if (ar == null || ar.EndInvokeCalled)
throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
// Wait for operation to complete, then return result or throw exception
return ar.EndInvoke();
}
private IEnumerable<FileInfo> InternalSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, SftpSynchronizeDirectoriesAsyncResult asynchResult)
{
if (destinationPath.IsNullOrWhiteSpace())
throw new ArgumentException("destinationPath");
if (!Directory.Exists(sourcePath))
throw new FileNotFoundException(string.Format("Source directory not found: {0}", sourcePath));
IList<FileInfo> uploadedFiles = new List<FileInfo>();
DirectoryInfo sourceDirectory = new DirectoryInfo(sourcePath);
#if SILVERLIGHT
var sourceFiles = sourceDirectory.EnumerateFiles(searchPattern);
#else
var sourceFiles = sourceDirectory.GetFiles(searchPattern);
#endif
if (sourceFiles == null || sourceFiles.Count() <= 0)
return uploadedFiles;
try
{
#region Existing Files at The Destination
var destFiles = InternalListDirectory(destinationPath, null);
Dictionary<string, SftpFile> destDict = new Dictionary<string, SftpFile>();
foreach (var destFile in destFiles)
{
if (destFile.IsDirectory)
continue;
destDict.Add(destFile.Name, destFile);
}
#endregion
#region Upload the difference
bool isDifferent = false;
Flags uploadFlag = Flags.Write | Flags.Truncate | Flags.CreateNewOrOpen;
foreach (var localFile in sourceFiles)
{
isDifferent = !destDict.ContainsKey(localFile.Name);
if (!isDifferent)
{
SftpFile temp = destDict[localFile.Name];
// TODO: Use md5 to detect a difference
//ltang: File exists at the destination => Using filesize to detect the difference
isDifferent = localFile.Length != temp.Length;
}
if (isDifferent)
{
var remoteFileName = string.Format(CultureInfo.InvariantCulture, @"{0}/{1}", destinationPath, localFile.Name);
try
{
using (var file = File.OpenRead(localFile.FullName))
{
this.InternalUploadFile(file, remoteFileName, null, uploadFlag);
}
uploadedFiles.Add(localFile);
if (asynchResult != null)
{
asynchResult.Update(uploadedFiles.Count);
}
}
catch (Exception ex)
{
throw new Exception(string.Format("Failed to upload {0} to {1}", localFile.FullName, remoteFileName), ex);
}
}
}
#endregion
}
catch
{
throw;
}
return uploadedFiles;
}
#endregion
}
}
+1 -136
View File
@@ -346,141 +346,6 @@ namespace Renci.SshNet
return ar.EndInvoke();
}
#region SynchronizeDirectories
#if (!WINDOWS_PHONE)
public IEnumerable<FileInfo> SynchronizeDirectories(string sourceDir
, string destDir
, string searchPattern)
{
return InternalSynchronizeDirectories(sourceDir, destDir, searchPattern, null);
}
public IAsyncResult BeginSynchronizeDirectories(string sourceDir
, string destDir
, string searchPattern, AsyncCallback asyncCallback, object state)
{
if (sourceDir == null)
throw new ArgumentNullException("sourceDir");
if (destDir.IsNullOrWhiteSpace())
throw new ArgumentException("destDir");
// Ensure that connection is established.
this.EnsureConnection();
var asyncResult = new SftpSynchronizeDirectoriesAsyncResult(asyncCallback, state);
this.ExecuteThread(() =>
{
try
{
var result = this.InternalSynchronizeDirectories(sourceDir, destDir, searchPattern, asyncResult);
asyncResult.SetAsCompleted(result, false);
}
catch (Exception exp)
{
asyncResult.SetAsCompleted(exp, false);
}
});
return asyncResult;
}
public IEnumerable<FileInfo> EndSynchronizeDirectories(IAsyncResult asyncResult)
{
var ar = asyncResult as SftpSynchronizeDirectoriesAsyncResult;
if (ar == null || ar.EndInvokeCalled)
throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
// Wait for operation to complete, then return result or throw exception
return ar.EndInvoke();
}
private IEnumerable<FileInfo> InternalSynchronizeDirectories(string sourceDir,
string destDir,
string searchPattern,
SftpSynchronizeDirectoriesAsyncResult asynchResult)
{
if (destDir.IsNullOrWhiteSpace())
throw new ArgumentException("destDir");
if (!Directory.Exists(sourceDir))
throw new FileNotFoundException(string.Format("Source directory not found: {0}", sourceDir));
IList<FileInfo> uploadedFiles = new List<FileInfo>();
DirectoryInfo source = new DirectoryInfo(sourceDir);
#if (SILVERLIGHT)
var sourceFiles = source.EnumerateFiles(searchPattern);
#else
var sourceFiles = source.GetFiles(searchPattern);
#endif
if (sourceFiles == null || sourceFiles.Count() <= 0)
return uploadedFiles;
try
{
#region Existing Files at The Destination
var destFiles = InternalListDirectory(destDir, null);
Dictionary<string, SftpFile> destDict = new Dictionary<string, SftpFile>();
foreach (var destFile in destFiles)
{
if (destFile.IsDirectory)
continue;
destDict.Add(destFile.Name, destFile);
}
#endregion
#region Upload the difference
string remoteFileName;
bool isDifferent = false;
Flags uploadFlag = Flags.Write | Flags.Truncate | Flags.CreateNewOrOpen;
foreach (var localFile in sourceFiles)
{
isDifferent = !destDict.ContainsKey(localFile.Name);
if (!isDifferent)
{
SftpFile temp = destDict[localFile.Name];
//ltang: File exists at the destination => Using filesize to detect the difference
isDifferent = localFile.Length != temp.Length;
}
if (isDifferent)
{
remoteFileName = string.Format(CultureInfo.InvariantCulture, @"{0}/{1}", destDir, localFile.Name);
try
{
using (var file = File.OpenRead(localFile.FullName))
{
InternalUploadFile(file, remoteFileName, null, uploadFlag);
}
uploadedFiles.Add(localFile);
if (asynchResult != null)
{
asynchResult.Update(uploadedFiles.Count);
}
}
catch (Exception ex)
{
throw new Exception(string.Format("Failed to upload {0} to {1}", localFile.FullName, remoteFileName), ex);
}
}
}
#endregion
}
catch
{
throw;
}
return uploadedFiles;
}
#endif
#endregion
/// <summary>
/// Gets reference to remote file or directory.
/// </summary>
@@ -1415,7 +1280,7 @@ namespace Renci.SshNet
if (bytesRead < this.BufferSize)
{
var data = new byte[bytesRead];
Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
using (var wait = new AutoResetEvent(false))
{
this._sftpSession.RequestWrite(handle, offset, data, wait);