Merge pull request #3399 from duplicati/remove_unused_variables_assignments

Remove unused variables, fields, and unnecessary assignments
This commit is contained in:
Rune Henriksen
2018-10-01 23:19:37 +02:00
committed by GitHub
28 changed files with 29 additions and 130 deletions
@@ -31,7 +31,9 @@ namespace Duplicati.CommandLine.BackendTester
/// <summary>
/// Used to maintain a reference to initialized system settings.
/// </summary>
#pragma warning disable CS0414 // The private field `Duplicati.CommandLine.BackendTester.Program.SystemSettings' is assigned but its value is never used
private static IDisposable SystemSettings;
#pragma warning restore CS0414 // The private field `Duplicati.CommandLine.BackendTester.Program.SystemSettings' is assigned but its value is never used
class TempFile
{
+1 -1
View File
@@ -1052,7 +1052,7 @@ namespace Duplicati.CommandLine
using (var i = new Library.Main.Controller(args[0], options, console))
{
setup(i);
var res = i.PurgeBrokenFiles(filter);
i.PurgeBrokenFiles(filter);
}
return 0;
@@ -176,9 +176,11 @@ namespace Duplicati.GUI.TrayIcon
var ch = ChannelManager.CreateChannel<string>();
m_toRumps = ch.AsWriteOnly();
WriteChannel(m_rumpsProcess.StandardInput, ch.AsReadOnly());
var standardOutputTask = ReadChannel(m_rumpsProcess.StandardOutput);
var standardErrorTask = ReadChannel(m_rumpsProcess.StandardError);
WriteChannel(m_rumpsProcess.StandardInput, ch.AsReadOnly());
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
ReadChannel(m_rumpsProcess.StandardOutput);
ReadChannel(m_rumpsProcess.StandardError);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
m_toRumps.WriteNoWait(JsonConvert.SerializeObject(new {Action = "background"}));
//m_toRumps.WriteNoWait(JsonConvert.SerializeObject(new {Action = "setappicon", Image = GetIcon(m_lastIcon)}));
@@ -119,7 +119,6 @@ namespace Duplicati.Library.Backend.AzureBlob
if (x is CloudBlockBlob)
{
var cb = (CloudBlockBlob)x;
var modified = cb.Properties.LastModified;
var lastModified = new System.DateTime();
if (cb.Properties.LastModified != null)
lastModified = new System.DateTime(cb.Properties.LastModified.Value.Ticks, System.DateTimeKind.Utc);
@@ -101,8 +101,6 @@ namespace Duplicati.Library.Backend.Backblaze
}
catch (Exception ex)
{
var msg = ex.Message;
var clienterror = false;
try
@@ -341,7 +341,7 @@ namespace Duplicati.Library.Backend
var response = this.m_client.PutAsync(string.Format("{0}/root:{1}{2}:/content", this.DrivePrefix, this.m_path, NormalizeSlashes(remotename)), streamContent).Await();
// Make sure this response is a valid drive item, though we don't actually use it for anything currently.
var result = this.ParseResponse<DriveItem>(response);
this.ParseResponse<DriveItem>(response);
}
else
{
@@ -353,7 +353,7 @@ namespace Duplicati.Library.Backend
HttpRequestMessage createSessionRequest = new HttpRequestMessage(HttpMethod.Post, string.Format("{0}/root:{1}{2}:/createUploadSession", this.DrivePrefix, this.m_path, NormalizeSlashes(remotename)));
// Indicate that we want to replace any existing content with this new data we're uploading
StringContent createSessionContent = this.PrepareContent(new UploadSession() { Item = new DriveItem() { ConflictBehavior = ConflictBehavior.Replace } });
this.PrepareContent(new UploadSession() { Item = new DriveItem() { ConflictBehavior = ConflictBehavior.Replace } });
HttpResponseMessage createSessionResponse = this.m_client.SendAsync(createSessionRequest).Await();
UploadSession uploadSession = this.ParseResponse<UploadSession>(createSessionResponse);
@@ -384,7 +384,7 @@ namespace Duplicati.Library.Backend
response = this.m_client.SendAsync(request, false).Await();
// Note: On the last request, the json result includes the default properties of the item that was uploaded
var result = this.ParseResponse<UploadSession>(response);
this.ParseResponse<UploadSession>(response);
}
catch (MicrosoftGraphException ex)
{
@@ -446,7 +446,7 @@ namespace Duplicati.Library.Backend
try
{
string rootPath = string.Format("{0}/root:{1}", this.DrivePrefix, this.m_path);
DriveItem rootFolder = this.Get<DriveItem>(rootPath);
this.Get<DriveItem>(rootPath);
}
catch (DriveItemNotFoundException ex)
{
-2
View File
@@ -248,7 +248,6 @@ namespace Duplicati.Library.Main
private readonly LocalDatabase m_database;
private readonly System.Threading.Thread m_callerThread;
private List<IDbEntry> m_dbqueue;
private readonly IBackendWriter m_stats;
private interface IDbEntry { }
@@ -276,7 +275,6 @@ namespace Duplicati.Library.Main
public DatabaseCollector(LocalDatabase database, IBackendWriter stats)
{
m_database = database;
m_stats = stats;
m_dbqueue = new List<IDbEntry>();
if (m_database != null)
m_callerThread = System.Threading.Thread.CurrentThread;
@@ -410,7 +410,7 @@ namespace Duplicati.Library.Main.Database
m_insertblockCommand.SetParameterValue(0, key);
m_insertblockCommand.SetParameterValue(1, volumeid);
m_insertblockCommand.SetParameterValue(2, size);
r = m_insertblockCommand.ExecuteScalarInt64(m_logQueries);
m_insertblockCommand.ExecuteScalarInt64(m_logQueries);
if (m_blockCache != null)
m_blockCache.Add(key, size);
return true;
@@ -1301,7 +1301,6 @@ ORDER BY
{
yield return new Tuple<string, byte[], int>(curHash, buffer, index);
buffer = new byte[blocksize];
curHash = null;
index = 0;
}
@@ -426,7 +426,6 @@ namespace Duplicati.Library.Main.Database
// Add to table
c3.ExecuteNonQuery(null, blocksetid, ix, blkeyfinal);
ix++;
}
}
}
@@ -100,7 +100,7 @@ namespace Duplicati.Library.Main.Database
, m_fileprogtable, m_tempfiletable, m_tempblocktable);
// Will be one row per file.
int fileCnt = cmd.ExecuteNonQuery(sql);
cmd.ExecuteNonQuery(sql);
sql = string.Format(
@"INSERT INTO ""{0}"" ("
@@ -115,7 +115,7 @@ namespace Duplicati.Library.Main.Database
, m_totalprogtable, m_fileprogtable);
// Will result in a single line (no support to also track metadata)
int totalStatRowCount = cmd.ExecuteNonQuery(sql);
cmd.ExecuteNonQuery(sql);
// Finally we create TRIGGERs to keep all our statistics up to date.
// This is lightning fast, as SQLite uses internal hooks and our indices to do the update magic.
+1 -9
View File
@@ -88,10 +88,9 @@ namespace Duplicati.Library.Main
string type = uri.Scheme;
int port = uri.Port;
string username = uri.Username;
string password = uri.Password;
string prefix = options.Prefix;
if (username == null || password == null)
if (username == null || uri.Password == null)
{
var sopts = DynamicLoader.BackendLoader.GetSupportedCommands(backend);
var ropts = new Dictionary<string, string>(options.RawOptions);
@@ -104,23 +103,16 @@ namespace Duplicati.Library.Main
{
if (username == null && o.Aliases != null && o.Aliases.Contains("auth-username", StringComparer.OrdinalIgnoreCase) && ropts.ContainsKey(o.Name))
username = ropts[o.Name];
if (password == null && o.Aliases != null && o.Aliases.Contains("auth-password", StringComparer.OrdinalIgnoreCase) && ropts.ContainsKey(o.Name))
password = ropts[o.Name];
}
foreach(var o in sopts)
{
if (username == null && o.Name.Equals("auth-username", StringComparison.OrdinalIgnoreCase) && ropts.ContainsKey("auth-username"))
username = ropts["auth-username"];
if (password == null && o.Name.Equals("auth-password", StringComparison.OrdinalIgnoreCase) && ropts.ContainsKey("auth-password"))
password = ropts["auth-password"];
}
}
}
if (password != null)
password = Library.Utility.Utility.ByteArrayAsHexString(System.Security.Cryptography.SHA256.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(password + "!" + uri.Scheme + "!" + uri.HostAndPath)));
//Now find the one that matches :)
var matches = (from n in configs
where
@@ -47,8 +47,6 @@ namespace Duplicati.Library.Main.Operation.Backup
async self =>
{
var blocksize = options.Blocksize;
while (await taskreader.ProgressAsync)
{
var e = await self.Input.ReadAsync();
@@ -47,8 +47,6 @@ namespace Duplicati.Library.Main.Operation.Backup
async self =>
{
var EMPTY_METADATA = Utility.WrapMetadata(new Dictionary<string, string>(), options);
var blocksize = options.Blocksize;
// Pre-cache the option variables here to simplify and
// speed up repeated option access below
@@ -67,7 +67,6 @@ namespace Duplicati.Library.Main.Operation.Backup
{
var send_close = false;
var filesize = 0L;
var filename = string.Empty;
var e = await self.Input.ReadAsync();
var cur = e.Result;
@@ -93,7 +93,6 @@ namespace Duplicati.Library.Main.Operation.Backup
{
var s = 1;
var fileTime = incompleteSet.Value + TimeSpan.FromSeconds(s);
var oldFilesetID = incompleteSet.Key;
// Probe for an unused filename
while (s < 60)
@@ -66,13 +66,13 @@ namespace Duplicati.Library.Main.Operation
var useLocalDb = !m_options.NoLocalDb && System.IO.File.Exists(m_options.Dbpath);
baseVersion = string.IsNullOrEmpty(baseVersion) ? "1" : baseVersion;
compareVersion = string.IsNullOrEmpty(compareVersion) ? "0" : compareVersion;
long baseVersionIndex = -1;
long compareVersionIndex = -1;
DateTime baseVersionTime = new DateTime(0);
DateTime compareVersionTime = new DateTime(0);
compareVersion = string.IsNullOrEmpty(compareVersion) ? "0" : compareVersion;
long baseVersionIndex;
long compareVersionIndex;
DateTime baseVersionTime;
DateTime compareVersionTime;
using(var tmpdb = useLocalDb ? null : new Library.Utility.TempFile())
using(var db = new Database.LocalListChangesDatabase(useLocalDb ? m_options.Dbpath : (string)tmpdb))
@@ -114,71 +114,14 @@ namespace Duplicati.Library.Main.Operation
{
using(var metadatastorage = new RestoreHandlerMetadataStorage())
{
System.Security.Cryptography.HashAlgorithm blockhasher = null;
System.Security.Cryptography.HashAlgorithm filehasher = null;
bool first = true;
RecreateDatabaseHandler.BlockVolumePostProcessor localpatcher =
(key, rd) =>
{
if (first)
{
Utility.UpdateOptionsFromDb(database, m_options);
m_blockbuffer = new byte[m_options.Blocksize];
//Figure out what files are to be patched, and what blocks are needed
PrepareBlockAndFileList(database, m_options, filter, m_result);
blockhasher = Library.Utility.HashAlgorithmHelper.Create(m_options.BlockHashAlgorithm);
filehasher = Library.Utility.HashAlgorithmHelper.Create(m_options.FileHashAlgorithm);
if (blockhasher == null)
throw new UserInformationException(Strings.Common.InvalidHashAlgorithm(m_options.BlockHashAlgorithm), "BlockHashAlgorithmNotSupported");
if (!blockhasher.CanReuseTransform)
throw new UserInformationException(Strings.Common.InvalidCryptoSystem(m_options.BlockHashAlgorithm), "BlockHashAlgorithmNotSupported");
if (filehasher == null)
throw new UserInformationException(Strings.Common.InvalidHashAlgorithm(m_options.FileHashAlgorithm), "FileHashAlgorithmNotSupported");
if (!filehasher.CanReuseTransform)
throw new UserInformationException(Strings.Common.InvalidCryptoSystem(m_options.FileHashAlgorithm), "FileHashAlgorithmNotSupported");
// Don't run this again
first = false;
}
else
{
// Patch the missing blocks list to include the newly discovered blocklists
//UpdateMissingBlocksTable(key);
}
if (m_result.TaskControlRendevouz() == TaskControlState.Stop)
return;
CreateDirectoryStructure(database, m_options, m_result);
//If we are patching an existing target folder, do not touch stuff that is already updated
ScanForExistingTargetBlocks(database, m_blockbuffer, blockhasher, filehasher, m_options, m_result);
if (m_result.TaskControlRendevouz() == TaskControlState.Stop)
return;
// If other local files already have the blocks we want, we use them instead of downloading
if (!m_options.NoLocalBlocks)
ScanForExistingSourceBlocks(database, m_options, m_blockbuffer, blockhasher, m_result, metadatastorage);
if (m_result.TaskControlRendevouz() == TaskControlState.Stop)
return;
//Update files with data
PatchWithBlocklist(database, rd, m_options, m_result, m_blockbuffer, metadatastorage);
};
// TODO: When UpdateMissingBlocksTable is implemented, the localpatcher can be activated
// TODO: When UpdateMissingBlocksTable is implemented, the localpatcher
// (removed in revision 9ce1e807 ("Remove unused variables and fields") can be activated
// and this will reduce the need for multiple downloads of the same volume
// TODO: This will need some work to preserve the missing block list for use with --fh-dryrun
m_result.RecreateDatabaseResults = new RecreateDatabaseResults(m_result);
using(new Logging.Timer(LOGTAG, "RecreateTempDbForRestore", "Recreate temporary database for restore"))
new RecreateDatabaseHandler(m_backendurl, m_options, (RecreateDatabaseResults)m_result.RecreateDatabaseResults)
.DoRun(database, false, filter, filelistfilter, /*localpatcher*/null);
.DoRun(database, false, filter, filelistfilter, null);
if (!m_options.SkipMetadata)
ApplyStoredMetadata(database, m_options, m_result, metadatastorage);
@@ -42,7 +42,6 @@ namespace Duplicati.Library.Main.Operation
public void Run(string[] sources, Library.Utility.IFilter filter)
{
var storeSymlinks = m_options.SymlinkPolicy == Options.SymlinkStrategy.Store;
var sourcefilter = new Library.Utility.FilterExpression(sources, true);
using(var snapshot = BackupHandler.GetSnapshot(sources, m_options))
@@ -159,9 +159,6 @@ namespace Duplicati.Library.Modules.Builtin
/// </summary>
private bool m_isConfigured;
/// <summary>
/// A value indicating if this instance has been disposed
/// </summary>
private bool m_isDisposed;
/// <summary>
/// The mail subject
/// </summary>
@@ -399,12 +399,9 @@ namespace Duplicati.Library.Utility
/// </summary>
public class DataPump
{
/// <summary> Minimum buffer size for pumping </summary>
public const int MINBUFSIZE = 1 << 10; // 1K
/// <summary> Default buffer size for pumping </summary>
public const int DEFAULTBUFSIZE = 1 << 14; // 16K
private readonly int m_bufsize;
private readonly bool m_closeInputWhenDone, m_closeOutputWhenDone;
private readonly Action<DataPump> m_callbackFinalizePumping = null;
private Stream m_input, m_output;
@@ -415,7 +412,6 @@ namespace Duplicati.Library.Utility
/// <summary> Creates and configures a new DataPump instance. </summary>
/// <param name="input"> The stream to read data from. </param>
/// <param name="output"> The stream to write data to. </param>
/// <param name="bufsize"> The internal buffer size for reading/writing. </param>
/// <param name="callbackFinalizePumping"> A callback to issue when pumping is done but before streams are closed. e.g. Can add data to output. </param>
/// <param name="dontCloseInputWhenDone"> Disable auto close of input stream when pumping is done. </param>
/// <param name="dontCloseOutputWhenDone"> Disable auto close of output stream when pumping is done. </param>
@@ -425,7 +421,6 @@ namespace Duplicati.Library.Utility
{
this.m_input = input;
this.m_output = output;
this.m_bufsize = Math.Max(MINBUFSIZE, bufsize);
this.m_callbackFinalizePumping = callbackFinalizePumping;
this.m_closeInputWhenDone = !dontCloseInputWhenDone;
this.m_closeOutputWhenDone = !dontCloseOutputWhenDone;
@@ -453,7 +448,6 @@ namespace Duplicati.Library.Utility
/// <summary> Actually transfers stream data. </summary>
private long doRun(bool rethrowException)
{
Exception hadException = null;
byte[] buf = new byte[1 << 14]; int c;
try
{
@@ -469,9 +463,8 @@ namespace Duplicati.Library.Utility
catch { }
}
}
catch (Exception ex)
catch (Exception)
{
hadException = ex;
if (rethrowException) throw;
}
finally
@@ -52,7 +52,6 @@ namespace Duplicati.Library.Utility
private readonly bool m_acceptAll = false;
private readonly string[] m_validHashes = null;
private Exception m_uncastException = null;
public bool ValidateServerCertficate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
@@ -79,7 +78,6 @@ namespace Duplicati.Library.Utility
throw new Exception(Strings.SslCertificateValidator.VerifyCertificateHashError(ex, sslPolicyErrors), ex);
}
m_uncastException = new InvalidCertificateException(certHash, sslPolicyErrors);
return false;
}
}
+1 -9
View File
@@ -133,11 +133,6 @@ namespace Duplicati.Server
private static System.Threading.Timer PurgeTempFilesTimer = null;
/// <summary>
/// Used to maintain a reference to initialized system settings.
/// </summary>
private static IDisposable SystemSettings;
public static int ServerPort
{
get
@@ -209,7 +204,7 @@ namespace Duplicati.Server
if (commandlineOptions.ContainsKey("tempdir") && !string.IsNullOrEmpty(commandlineOptions["tempdir"]))
Library.Utility.SystemContextSettings.DefaultTempPath = commandlineOptions["tempdir"];
SystemSettings = Duplicati.Library.Utility.SystemContextSettings.StartSession();
Library.Utility.SystemContextSettings.StartSession();
// Check if a parameters-file was provided. Skip if help was already specified
if (!commandlineOptions.ContainsKey("help"))
@@ -255,9 +250,6 @@ namespace Duplicati.Server
try
{
// Setup the log redirect
var logscope = Library.Logging.Log.StartScope(Program.LogHandler, null);
if (commandlineOptions.ContainsKey("log-file"))
{
#if DEBUG
@@ -41,7 +41,6 @@ namespace Duplicati.Server.WebServer.RESTMethods
public void POST(string key, RequestInfo info)
{
var input = info.Request.Form;
switch ((key ?? "").ToLowerInvariant())
{
case "suppressdonationmessages":
@@ -37,7 +37,6 @@ namespace Duplicati.Server.WebServer.RESTMethods
return;
}
task = tasks.Where(x => x.TaskID == taskid).FirstOrDefault();
if (tasks.Where(x => x.TaskID == taskid).FirstOrDefault() == null)
{
KeyValuePair<long, Exception>[] matches;
-1
View File
@@ -53,7 +53,6 @@ namespace Duplicati.Service
private void Run()
{
var self_exec = System.Reflection.Assembly.GetExecutingAssembly().Location;
var path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var exec = System.IO.Path.Combine(path, "Duplicati.Server.exe");
var cmdargs = "--ping-pong-keepalive=true";
+1 -1
View File
@@ -234,7 +234,7 @@ namespace Duplicati.UnitTest
using(var c = new Library.Main.Controller("file://" + TARGETFOLDER, testopts.Expand(new { version = 0 }), null))
{
var r = c.List("*");
c.List("*");
//Console.WriteLine("In first backup:");
//Console.WriteLine(string.Join(Environment.NewLine, r.Files.Select(x => x.Path)));
}
-3
View File
@@ -175,7 +175,6 @@ namespace Duplicati.UnitTest
var round1 = filenames.Take(filenames.Count / 3).ToArray();
var round2 = filenames.Take((filenames.Count / 3) * 2).ToArray();
var round3 = filenames;
using (var c = new Library.Main.Controller("file://" + TARGETFOLDER, testopts, null))
{
@@ -204,8 +203,6 @@ namespace Duplicati.UnitTest
Assert.AreEqual(filenames.Count - round2.Length, res.AddedFiles);
}
var last_ts = DateTime.Now;
File.Delete(dblock_file);
long[] affectedfiles;