Merge pull request #3951 from warwickmm/cast_with_pattern_matching

Use pattern matching to simplify casts
This commit is contained in:
Kenneth Skovhede
2019-10-21 08:35:28 +02:00
committed by GitHub
47 changed files with 208 additions and 212 deletions
@@ -342,11 +342,11 @@ namespace Duplicati.CommandLine.BackendTester
try
{
if (backend is Library.Interface.IStreamingBackend && !disableStreaming)
if (backend is IStreamingBackend streamingBackend && !disableStreaming)
{
using (System.IO.FileStream fs = new System.IO.FileStream(cf, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
using (NonSeekableStream nss = new NonSeekableStream(fs))
(backend as Library.Interface.IStreamingBackend).Get(files[i].remotefilename, nss);
streamingBackend.Get(files[i].remotefilename, nss);
}
else
backend.Get(files[i].remotefilename, cf);
@@ -453,8 +453,8 @@ namespace Duplicati.CommandLine.BackendTester
finally
{
foreach (Library.Interface.IGenericModule m in loadedModules)
if (m is IDisposable)
((IDisposable)m).Dispose();
if (m is IDisposable disposable)
disposable.Dispose();
}
return true;
@@ -467,11 +467,11 @@ namespace Duplicati.CommandLine.BackendTester
try
{
if (backend is Library.Interface.IStreamingBackend && !disableStreaming)
if (backend is IStreamingBackend streamingBackend && !disableStreaming)
{
using (System.IO.FileStream fs = new System.IO.FileStream(localfilename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
using (NonSeekableStream nss = new NonSeekableStream(fs))
(backend as Library.Interface.IStreamingBackend).PutAsync(remotefilename, nss, CancellationToken.None).Wait();
streamingBackend.PutAsync(remotefilename, nss, CancellationToken.None).Wait();
}
else
backend.PutAsync(remotefilename, localfilename, CancellationToken.None).Wait();
+3 -2
View File
@@ -22,6 +22,7 @@ using System.Collections.Generic;
using System.Linq;
using Duplicati.Library.Localization.Short;
using System.IO;
using Duplicati.Library.Interface;
using Duplicati.Library.Logging;
namespace Duplicati.CommandLine
@@ -242,10 +243,10 @@ namespace Duplicati.CommandLine
while (ex is System.Reflection.TargetInvocationException && ex.InnerException != null)
ex = ex.InnerException;
if (ex is Duplicati.Library.Interface.UserInformationException && !verboseErrors)
if (ex is UserInformationException exception && !verboseErrors)
{
errwriter.WriteLine();
errwriter.WriteLine("ErrorID: {0}", ((Duplicati.Library.Interface.UserInformationException)ex).HelpID);
errwriter.WriteLine("ErrorID: {0}", exception.HelpID);
errwriter.WriteLine(ex.Message);
}
else if (!(ex is Library.Interface.CancelException))
@@ -1123,8 +1123,8 @@ namespace Duplicati.Library.AutoUpdater
var cur = Environment.GetEnvironmentVariables();
foreach (var e in cur.Keys)
if (e is string)
pi.EnvironmentVariables[(string)e] = cur[(string)e] as string;
if (e is string s)
pi.EnvironmentVariables[s] = cur[s] as string;
pi.EnvironmentVariables[string.Format(BASEINSTALLDIR_ENVNAME_TEMPLATE, APPNAME)] = InstalledBaseDir;
pi.EnvironmentVariables["LOCALIZATION_FOLDER"] = InstalledBaseDir;
@@ -356,8 +356,8 @@ namespace Duplicati.Library.Backend.AmazonCloudDrive
catch(Exception ex)
{
#if DEBUG
if (ex is WebException)
using(var sr = new StreamReader((ex as WebException).Response.GetResponseStream()))
if (ex is WebException exception)
using(var sr = new StreamReader(exception.Response.GetResponseStream()))
Console.WriteLine(sr.ReadToEnd());
#endif
@@ -116,9 +116,8 @@ namespace Duplicati.Library.Backend.AzureBlob
try
{
if (x is CloudBlockBlob)
if (x is CloudBlockBlob cb)
{
var cb = (CloudBlockBlob)x;
var lastModified = new System.DateTime();
if (cb.Properties.LastModified != null)
lastModified = new System.DateTime(cb.Properties.LastModified.Value.Ticks, System.DateTimeKind.Utc);
@@ -106,9 +106,9 @@ namespace Duplicati.Library.Backend.Backblaze
try
{
// Only retry once on client errors
if (ex is WebException && (ex as WebException).Response is HttpWebResponse)
if (ex is WebException exception && exception.Response is HttpWebResponse response)
{
var sc = (int)((ex as WebException).Response as HttpWebResponse).StatusCode;
var sc = (int)response.StatusCode;
clienterror = (sc >= 400 && sc <= 499);
}
}
@@ -137,10 +137,9 @@ namespace Duplicati.Library.Backend.Backblaze
Exception newex = null;
try
{
if (ex is WebException && (ex as WebException).Response is HttpWebResponse)
if (ex is WebException exception && exception.Response is HttpWebResponse hs)
{
string rawdata = null;
var hs = (ex as WebException).Response as HttpWebResponse;
using(var rs = Library.Utility.AsyncHttpRequest.TrySetTimeout(hs.GetResponseStream()))
using(var sr = new System.IO.StreamReader(rs))
rawdata = sr.ReadToEnd();
@@ -166,8 +165,8 @@ namespace Duplicati.Library.Backend.Backblaze
public static HttpStatusCode GetExceptionStatusCode(Exception ex)
{
if (ex is WebException && (ex as WebException).Response is HttpWebResponse)
return ((ex as WebException).Response as HttpWebResponse).StatusCode;
if (ex is WebException exception && exception.Response is HttpWebResponse response)
return response.StatusCode;
else
return default(HttpStatusCode);
}
+1 -2
View File
@@ -60,10 +60,9 @@ namespace Duplicati.Library.Backend.Box
Exception newex = null;
try
{
if (ex is WebException && (ex as WebException).Response is HttpWebResponse)
if (ex is WebException exception && exception.Response is HttpWebResponse hs)
{
string rawdata = null;
var hs = (ex as WebException).Response as HttpWebResponse;
using(var rs = Library.Utility.AsyncHttpRequest.TrySetTimeout(hs.GetResponseStream()))
using(var sr = new System.IO.StreamReader(rs))
rawdata = sr.ReadToEnd();
@@ -153,7 +153,7 @@ namespace Duplicati.Library.Backend
catch (WebException wex)
{
if (markerUrl == "") //Only check on first itteration
if (wex.Response is HttpWebResponse && ((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
if (wex.Response is HttpWebResponse response && response.StatusCode == HttpStatusCode.NotFound)
throw new FolderMissingException(wex);
//Other error, just re-throw
@@ -228,7 +228,7 @@ namespace Duplicati.Library.Backend
}
catch (System.Net.WebException wex)
{
if (wex.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)wex.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
if (wex.Response is HttpWebResponse response && response.StatusCode == System.Net.HttpStatusCode.NotFound)
throw new FileMissingException(wex);
else
throw;
@@ -204,13 +204,13 @@ namespace Duplicati.Library.Backend
private void HandleDropboxException(Exception ex, bool filerequest)
{
if (ex is WebException)
if (ex is WebException exception)
{
string json = string.Empty;
try
{
using (var sr = new StreamReader(((WebException)ex).Response.GetResponseStream()))
using (var sr = new StreamReader(exception.Response.GetResponseStream()))
json = sr.ReadToEnd();
}
catch { }
@@ -218,10 +218,8 @@ namespace Duplicati.Library.Backend
// Special mapping for exceptions:
// https://www.dropbox.com/developers-v1/core/docs
if (((WebException)ex).Response is HttpWebResponse)
if (exception.Response is HttpWebResponse httpResp)
{
var httpResp = ((WebException)ex).Response as HttpWebResponse;
if (httpResp.StatusCode == HttpStatusCode.NotFound)
{
if (filerequest)
@@ -238,7 +236,7 @@ namespace Duplicati.Library.Backend
throw new Duplicati.Library.Interface.FolderMissingException(json);
}
if (httpResp.StatusCode == HttpStatusCode.Unauthorized)
ThrowAuthException(json, ex);
ThrowAuthException(json, exception);
if ((int)httpResp.StatusCode == 429 || (int)httpResp.StatusCode == 507)
ThrowOverQuotaError();
}
@@ -103,7 +103,7 @@ namespace Duplicati.Library.Backend.GoogleCloudStorage
}
catch (WebException wex)
{
if (wex.Response is HttpWebResponse && ((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
if (wex.Response is HttpWebResponse response && response.StatusCode == HttpStatusCode.NotFound)
throw new FolderMissingException();
else
throw;
@@ -259,7 +259,7 @@ namespace Duplicati.Library.Backend.GoogleCloudStorage
}
catch (WebException wex)
{
if (wex.Response is HttpWebResponse && ((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
if (wex.Response is HttpWebResponse response && response.StatusCode == HttpStatusCode.NotFound)
throw new FileMissingException();
else
throw;
@@ -212,9 +212,9 @@ namespace Duplicati.Library.Backend.GoogleServices
var retry = false;
// If we get a 5xx error, or some network issue, we retry
if (ex is WebException && ((WebException)ex).Response is HttpWebResponse)
if (ex is WebException exception && exception.Response is HttpWebResponse response)
{
var code = (int)((HttpWebResponse)((WebException)ex).Response).StatusCode;
var code = (int)response.StatusCode;
retry = code >= 500 && code <= 599;
}
else if (ex is System.Net.Sockets.SocketException || ex is System.IO.IOException || ex.InnerException is System.Net.Sockets.SocketException || ex.InnerException is System.IO.IOException)
@@ -22,6 +22,7 @@ using Duplicati.Library.Interface;
using Duplicati.Library.Localization.Short;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace Duplicati.Library.Backend
@@ -210,7 +211,7 @@ namespace Duplicati.Library.Backend
}
catch (System.Net.WebException wex)
{
if (wex.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)wex.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
if (wex.Response is HttpWebResponse response && response.StatusCode == System.Net.HttpStatusCode.NotFound)
throw new FolderMissingException(wex);
throw;
}
@@ -286,7 +287,7 @@ namespace Duplicati.Library.Backend
}
catch (System.Net.WebException wex)
{
if (wex.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)wex.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
if (wex.Response is HttpWebResponse response && response.StatusCode == System.Net.HttpStatusCode.NotFound)
throw new FileMissingException(wex);
throw;
}
@@ -17,6 +17,7 @@
using Duplicati.Library.Utility;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
@@ -321,8 +322,8 @@ namespace Duplicati.Library
}
catch(WebException wex)
{
if (wex.Response is HttpWebResponse)
return (HttpWebResponse)wex.Response;
if (wex.Response is HttpWebResponse response)
return response;
throw;
}
@@ -350,9 +351,8 @@ namespace Duplicati.Library
{
if (requestdata != null)
{
if (requestdata is System.IO.Stream)
if (requestdata is Stream stream)
{
var stream = requestdata as System.IO.Stream;
req.Request.ContentLength = stream.Length;
if (string.IsNullOrEmpty(req.Request.ContentType))
req.Request.ContentType = "application/octet-stream";
@@ -137,21 +137,21 @@ namespace Duplicati.Library
{
var msg = ex.Message;
var clienterror = false;
if (ex is WebException)
if (ex is WebException exception)
{
var resp = ((WebException)ex).Response as HttpWebResponse;
var resp = exception.Response as HttpWebResponse;
if (resp != null)
{
msg = resp.Headers["X-Reason"];
if (string.IsNullOrWhiteSpace(msg))
msg = resp.StatusDescription;
if (resp.StatusCode == HttpStatusCode.ServiceUnavailable)
{
if (msg == resp.StatusDescription)
throw new Duplicati.Library.Interface.UserInformationException(Strings.OAuthHelper.OverQuotaError, "OAuthOverQuotaError");
else
throw new Duplicati.Library.Interface.UserInformationException(Strings.OAuthHelper.AuthorizationFailure(msg, OAuthLoginUrl), "OAuthLoginError", ex);
throw new Duplicati.Library.Interface.UserInformationException(Strings.OAuthHelper.AuthorizationFailure(msg, OAuthLoginUrl), "OAuthLoginError", exception);
}
//Fail faster on client errors
@@ -25,7 +25,7 @@ using Newtonsoft.Json.Converters;
using Duplicati.Library.Strings;
using System.Net;
using System.Text;
using Duplicati.Library.Common.IO;
using Duplicati.Library.Common.IO;
using System.Threading;
using System.Threading.Tasks;
@@ -504,7 +504,7 @@ namespace Duplicati.Library.Backend.OpenStack
}
catch(WebException wex)
{
if (wex.Response is HttpWebResponse && ((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
if (wex.Response is HttpWebResponse response && response.StatusCode == HttpStatusCode.NotFound)
throw new FileMissingException();
else
throw;
@@ -522,7 +522,7 @@ namespace Duplicati.Library.Backend.OpenStack
}
catch (WebException wex)
{
if (wex.Response is HttpWebResponse && (((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound))
if (wex.Response is HttpWebResponse response && (response.StatusCode == HttpStatusCode.NotFound))
throw new FolderMissingException();
else
throw;
+2 -2
View File
@@ -388,7 +388,7 @@ namespace Duplicati.Library.Backend.Sia
}
catch (System.Net.WebException wex)
{
if (wex.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)wex.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
if (wex.Response is HttpWebResponse response && response.StatusCode == System.Net.HttpStatusCode.NotFound)
throw new FileMissingException(wex);
else
throw new Exception(getResponseBodyOnError(endpoint, wex));
@@ -419,7 +419,7 @@ namespace Duplicati.Library.Backend.Sia
}
catch (System.Net.WebException wex)
{
if (wex.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)wex.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
if (wex.Response is HttpWebResponse response && response.StatusCode == System.Net.HttpStatusCode.NotFound)
throw new FileMissingException(wex);
else
throw new Exception(getResponseBodyOnError(endpoint, wex));
@@ -17,12 +17,13 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#endregion
using Duplicati.Library.Common.IO;
using Duplicati.Library.Common.IO;
using Duplicati.Library.Interface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
@@ -232,7 +233,7 @@ namespace Duplicati.Library.Backend
}
catch (System.Net.WebException wex)
{
if (wex.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)wex.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
if (wex.Response is HttpWebResponse response && response.StatusCode == System.Net.HttpStatusCode.NotFound)
throw new FileMissingException(wex);
else
throw;
+3 -2
View File
@@ -17,10 +17,11 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#endregion
using Duplicati.Library.Common.IO;
using Duplicati.Library.Common.IO;
using Duplicati.Library.Interface;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
@@ -286,7 +287,7 @@ namespace Duplicati.Library.Backend
}
catch (System.Net.WebException wex)
{
if (wex.Response is System.Net.HttpWebResponse && ((System.Net.HttpWebResponse)wex.Response).StatusCode == System.Net.HttpStatusCode.NotFound)
if (wex.Response is HttpWebResponse response && response.StatusCode == System.Net.HttpStatusCode.NotFound)
throw new FileMissingException(wex);
else
throw;
@@ -329,8 +329,8 @@ namespace Duplicati.Library.Compression
if (ze == null)
return null;
if (ze is IArchiveEntry)
return ((IArchiveEntry)ze).OpenEntryStream();
if (ze is IArchiveEntry entry)
return entry.OpenEntryStream();
else if (ze is SharpCompress.Common.Zip.ZipEntry)
return GetStreamFromReader(ze);
+12 -11
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Duplicati.Library.Utility;
using Duplicati.Library.Main.Database;
@@ -325,17 +326,17 @@ namespace Duplicati.Library.Main
//As we replace the list, we can now freely access the elements without locking
foreach (var e in entries)
if (e is DbOperation)
db.LogRemoteOperation(((DbOperation)e).Action, ((DbOperation)e).File, ((DbOperation)e).Result, transaction);
else if (e is DbUpdate && ((DbUpdate)e).State == RemoteVolumeState.Deleted)
if (e is DbOperation operation)
db.LogRemoteOperation(operation.Action, operation.File, operation.Result, transaction);
else if (e is DbUpdate update && update.State == RemoteVolumeState.Deleted)
{
db.UpdateRemoteVolume(((DbUpdate)e).Remotename, RemoteVolumeState.Deleted, ((DbUpdate)e).Size, ((DbUpdate)e).Hash, true, TimeSpan.FromHours(2), transaction);
volsRemoved.Add(((DbUpdate)e).Remotename);
db.UpdateRemoteVolume(update.Remotename, RemoteVolumeState.Deleted, update.Size, update.Hash, true, TimeSpan.FromHours(2), transaction);
volsRemoved.Add(update.Remotename);
}
else if (e is DbUpdate)
db.UpdateRemoteVolume(((DbUpdate)e).Remotename, ((DbUpdate)e).State, ((DbUpdate)e).Size, ((DbUpdate)e).Hash, transaction);
else if (e is DbRename)
db.RenameRemoteFile(((DbRename)e).Oldname, ((DbRename)e).Newname, transaction);
else if (e is DbUpdate dbUpdate)
db.UpdateRemoteVolume(dbUpdate.Remotename, dbUpdate.State, dbUpdate.Size, dbUpdate.Hash, transaction);
else if (e is DbRename rename)
db.RenameRemoteFile(rename.Oldname, rename.Newname, transaction);
else if (e != null)
Logging.Log.WriteErrorMessage(LOGTAG, "InvalidQueueElement", null, "Queue had element of type: {0}, {1}", e.GetType(), e);
@@ -523,10 +524,10 @@ namespace Duplicati.Library.Main
throw;
}
if (ex is System.Net.WebException)
if (ex is WebException exception)
{
// Refresh DNS name if we fail to connect in order to prevent issues with incorrect DNS entries
if (((System.Net.WebException)ex).Status == System.Net.WebExceptionStatus.NameResolutionFailure)
if (exception.Status == System.Net.WebExceptionStatus.NameResolutionFailure)
{
try
{
+10 -11
View File
@@ -24,6 +24,7 @@ using System.Threading;
using Duplicati.Library.Utility;
using Duplicati.Library.Common.IO;
using Duplicati.Library.Common;
using Duplicati.Library.Interface;
namespace Duplicati.Library.Main
{
@@ -104,8 +105,8 @@ namespace Duplicati.Library.Main
/// <param name="sink">The sink to use.</param>
public void AppendSink(IMessageSink sink)
{
if (m_messageSink is MultiMessageSink)
((MultiMessageSink)m_messageSink).Append(sink);
if (this.m_messageSink is MultiMessageSink messageSink)
messageSink.Append(sink);
else
m_messageSink = new MultiMessageSink(m_messageSink, sink);
}
@@ -488,13 +489,13 @@ namespace Duplicati.Library.Main
if (m_options != null && m_options.LoadedModules != null)
{
foreach (KeyValuePair<bool, Library.Interface.IGenericModule> mx in m_options.LoadedModules)
if (mx.Key && mx.Value is Duplicati.Library.Interface.IGenericCallbackModule)
try { ((Duplicati.Library.Interface.IGenericCallbackModule)mx.Value).OnFinish(result); }
if (mx.Key && mx.Value is IGenericCallbackModule module)
try { module.OnFinish(result); }
catch (Exception ex) { Logging.Log.WriteWarningMessage(LOGTAG, $"OnFinishError{mx.Key}", ex, "OnFinish callback {0} failed: {1}", mx.Key, ex.Message); }
foreach (KeyValuePair<bool, Library.Interface.IGenericModule> mx in m_options.LoadedModules)
if (mx.Key && mx.Value is IDisposable)
try { ((IDisposable)mx.Value).Dispose(); }
if (mx.Key && mx.Value is IDisposable disposable)
try { disposable.Dispose(); }
catch (Exception ex) { Logging.Log.WriteWarningMessage(LOGTAG, $"DisposeError{mx.Key}", ex, "Dispose for {0} failed: {1}", mx.Key, ex.Message); }
m_options.LoadedModules.Clear();
@@ -575,10 +576,8 @@ namespace Duplicati.Library.Main
else
mx.Value.Configure(m_options.RawOptions);
if (mx.Value is Library.Interface.IGenericSourceModule)
if (mx.Value is IGenericSourceModule sourcemodule)
{
var sourcemodule = (Library.Interface.IGenericSourceModule)mx.Value;
if (sourcemodule.ContainFilesForBackup(paths))
{
var sourceoptions = sourcemodule.ParseSourcePaths(ref paths, ref pristinefilter, m_options.RawOptions);
@@ -588,8 +587,8 @@ namespace Duplicati.Library.Main
}
}
if (mx.Value is Library.Interface.IGenericCallbackModule)
((Library.Interface.IGenericCallbackModule)mx.Value).OnStart(result.MainOperation.ToString(), ref m_backend, ref paths);
if (mx.Value is IGenericCallbackModule module)
module.OnStart(result.MainOperation.ToString(), ref m_backend, ref paths);
}
// If the filters were changed by a module, read them back in
@@ -5,6 +5,7 @@ using System.Linq;
using System.Text;
using System.IO;
using Duplicati.Library.Modules.Builtin.ResultSerialization;
using Duplicati.Library.Utility;
namespace Duplicati.Library.Main.Database
{
@@ -1197,8 +1198,8 @@ ORDER BY
m_connection = connection;
Tablename = "Filenames-" + Library.Utility.Utility.ByteArrayAsHexString(Guid.NewGuid().ToByteArray());
var type = Library.Utility.FilterType.Regexp;
if (filter is Library.Utility.FilterExpression)
type = ((Library.Utility.FilterExpression)filter).Type;
if (filter is FilterExpression expression)
type = expression.Type;
// Bugfix: SQLite does not handle case-insensitive LIKE with non-ascii characters
if (type != Library.Utility.FilterType.Regexp && !Library.Utility.Utility.IsFSCaseSensitive && filter.ToString().Any(x => x > 127))
@@ -17,6 +17,7 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using Duplicati.Library.Utility;
namespace Duplicati.Library.Main.Database
{
@@ -143,12 +144,12 @@ namespace Duplicati.Library.Main.Database
// Simple case, select everything
cmd.ExecuteNonQuery(string.Format(@"INSERT INTO ""{0}"" (""Path"", ""FileHash"", ""MetaHash"", ""Size"", ""Type"") SELECT ""Path"", ""FileHash"", ""MetaHash"", ""Size"", ""Type"" FROM {1} A WHERE ""A"".""FilesetID"" = ? ", tablename, combined), filesetId);
}
else if (Library.Utility.Utility.IsFSCaseSensitive && filter is Library.Utility.FilterExpression && (filter as Library.Utility.FilterExpression).Type == Duplicati.Library.Utility.FilterType.Simple)
else if (Library.Utility.Utility.IsFSCaseSensitive && filter is FilterExpression expression && expression.Type == Duplicati.Library.Utility.FilterType.Simple)
{
// File list based
// unfortunately we cannot do this if the filesystem is case sensitive as
// SQLite only supports ASCII compares
var p = (filter as Library.Utility.FilterExpression).GetSimpleList();
var p = expression.GetSimpleList();
var filenamestable = "Filenames-" + Library.Utility.Utility.ByteArrayAsHexString(Guid.NewGuid().ToByteArray());
cmd.ExecuteNonQuery(string.Format(@"CREATE TEMPORARY TABLE ""{0}"" (""Path"" TEXT NOT NULL) ", filenamestable));
cmd.CommandText = string.Format(@"INSERT INTO ""{0}"" (""Path"") VALUES (?)", filenamestable);
@@ -16,6 +16,7 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using Duplicati.Library.Utility;
namespace Duplicati.Library.Main.Database
{
@@ -104,12 +105,12 @@ namespace Duplicati.Library.Main.Database
public void ApplyFilter(Library.Utility.IFilter filter)
{
if (Library.Utility.Utility.IsFSCaseSensitive && filter is Library.Utility.FilterExpression && (filter as Library.Utility.FilterExpression).Type == Duplicati.Library.Utility.FilterType.Simple)
if (Library.Utility.Utility.IsFSCaseSensitive && filter is FilterExpression expression && expression.Type == Duplicati.Library.Utility.FilterType.Simple)
{
// File list based
// unfortunately we cannot do this if the filesystem is not case-sensitive as
// SQLite only supports ASCII compares
var p = (filter as Library.Utility.FilterExpression).GetSimpleList();
var p = expression.GetSimpleList();
var filenamestable = "Filenames-" + Library.Utility.Utility.ByteArrayAsHexString(Guid.NewGuid().ToByteArray());
using (var cmd = m_connection.CreateCommand(m_transaction))
{
@@ -5,6 +5,7 @@ using System.Text;
using Duplicati.Library.Common;
using Duplicati.Library.Common.IO;
using Duplicati.Library.Main.Volumes;
using Duplicati.Library.Utility;
namespace Duplicati.Library.Main.Database
{
@@ -224,14 +225,14 @@ namespace Duplicati.Library.Main.Database
cmd.AddParameter(filesetId);
cmd.ExecuteNonQuery();
}
else if (Library.Utility.Utility.IsFSCaseSensitive && filter is Library.Utility.FilterExpression && (filter as Library.Utility.FilterExpression).Type == Duplicati.Library.Utility.FilterType.Simple)
else if (Library.Utility.Utility.IsFSCaseSensitive && filter is FilterExpression expression && expression.Type == Duplicati.Library.Utility.FilterType.Simple)
{
// If we get a list of filenames, the lookup table is faster
// unfortunately we cannot do this if the filesystem is case sensitive as
// SQLite only supports ASCII compares
using(var tr = m_connection.BeginTransaction())
{
var p = (filter as Library.Utility.FilterExpression).GetSimpleList();
var p = expression.GetSimpleList();
var m_filenamestable = "Filenames-" + guid;
cmd.Transaction = tr;
cmd.ExecuteNonQuery(string.Format(@"CREATE TEMPORARY TABLE ""{0}"" (""Path"" TEXT NOT NULL) ", m_filenamestable));
@@ -319,9 +319,9 @@ namespace Duplicati.Library.Main.Operation
// TODO: If we have a BackendManager, we should query through that
using (var backend = DynamicLoader.BackendLoader.GetBackend(m_backendurl, m_options.RawOptions))
{
if (backend is Library.Interface.IQuotaEnabledBackend)
if (backend is IQuotaEnabledBackend enabledBackend)
{
Library.Interface.IQuotaInfo quota = ((Library.Interface.IQuotaEnabledBackend)backend).Quota;
Library.Interface.IQuotaInfo quota = enabledBackend.Quota;
if (quota != null)
{
m_result.BackendWriter.TotalQuotaSpace = quota.TotalQuotaSpace;
@@ -19,6 +19,7 @@ using System;
using Duplicati.Library.Main.Database;
using System.Collections.Generic;
using System.Linq;
using Duplicati.Library.Interface;
namespace Duplicati.Library.Main.Operation
{
@@ -222,9 +223,9 @@ namespace Duplicati.Library.Main.Operation
// TODO: We should query through the backendmanager
using (var bk = DynamicLoader.BackendLoader.GetBackend(backend.BackendUrl, options.RawOptions))
if (bk is Library.Interface.IQuotaEnabledBackend)
if (bk is IQuotaEnabledBackend enabledBackend)
{
Library.Interface.IQuotaInfo quota = ((Library.Interface.IQuotaEnabledBackend)bk).Quota;
Library.Interface.IQuotaInfo quota = enabledBackend.Quota;
if (quota != null)
{
log.TotalQuotaSpace = quota.TotalQuotaSpace;
@@ -4,6 +4,7 @@ using System.Linq;
using System.Text;
using Duplicati.Library.Interface;
using Duplicati.Library.Main.Database;
using Duplicati.Library.Utility;
namespace Duplicati.Library.Main.Operation
{
@@ -29,7 +30,7 @@ namespace Duplicati.Library.Main.Operation
{
var parsedfilter = new Library.Utility.FilterExpression(filterstrings);
var filter = Library.Utility.JoinedFilterExpression.Join(parsedfilter, compositefilter);
var simpleList = !((filter is Library.Utility.FilterExpression && ((Library.Utility.FilterExpression)filter).Type == Library.Utility.FilterType.Simple) || m_options.AllVersions);
var simpleList = !((filter is FilterExpression expression && expression.Type == Library.Utility.FilterType.Simple) || m_options.AllVersions);
//Use a speedy local query
if (!m_options.NoLocalDb && System.IO.File.Exists(m_options.Dbpath))
+4 -4
View File
@@ -755,15 +755,15 @@ namespace Duplicati.Library.Main
{
get
{
if (m_parent != null && m_parent is BackupResults)
return ((BackupResults)m_parent).CompactResults;
if (m_parent != null && this.m_parent is BackupResults results)
return results.CompactResults;
return m_compactResults;
}
internal set
{
if (m_parent != null && m_parent is BackupResults)
((BackupResults)m_parent).CompactResults = value;
if (m_parent != null && this.m_parent is BackupResults results)
results.CompactResults = value;
m_compactResults = value;
}
@@ -21,8 +21,8 @@ namespace Duplicati.Library.Main.Volumes
if (tmp == null)
{
var name = "[stream]";
if (stream is FileStream)
name = ((FileStream)stream).Name;
if (stream is FileStream fileStream)
name = fileStream.Name;
throw new Exception(string.Format("Unable to create {0} decompressor on file {1}", compressor, name));
}
@@ -60,8 +60,8 @@ namespace Duplicati.Library.Main.Volumes
if (m_compression == null)
throw new UserInformationException(string.Format("Unsupported compression module: {0}", options.CompressionModule), "UnsupportedCompressionModule");
if ((this is IndexVolumeWriter || this is FilesetVolumeWriter) && m_compression is Library.Interface.ICompressionHinting)
((Library.Interface.ICompressionHinting)m_compression).LowOverheadMode = true;
if ((this is IndexVolumeWriter || this is FilesetVolumeWriter) && this.m_compression is ICompressionHinting hinting)
hinting.LowOverheadMode = true;
AddManifestFile();
}
@@ -386,8 +386,8 @@ namespace Duplicati.Library.Modules.Builtin
ParsedResultType level;
if (result is Exception)
level = ParsedResultType.Fatal;
else if (result != null && result is Library.Interface.IBasicResults)
level = ((IBasicResults)result).ParsedResult;
else if (result != null && result is IBasicResults results)
level = results.ParsedResult;
else
level = ParsedResultType.Error;
@@ -27,9 +27,8 @@ namespace Duplicati.Library.Modules.Builtin.ResultSerialization
{
sb.Append("null?");
}
else if (result is IEnumerable)
else if (result is IEnumerable resultEnumerable)
{
IEnumerable resultEnumerable = (IEnumerable)result;
IEnumerator resultEnumerator = resultEnumerable.GetEnumerator();
resultEnumerator.Reset();
@@ -78,10 +77,9 @@ namespace Duplicati.Library.Modules.Builtin.ResultSerialization
}
}
}
else if (result is Exception)
else if (result is Exception exception)
{
//No localization, must be parseable by script
Exception exception = (Exception)result;
sb.AppendFormat("Failed: {0}", exception.Message).AppendLine();
sb.AppendFormat("Details: {0}", exception).AppendLine();
}
@@ -181,8 +181,8 @@ namespace Duplicati.Library.Modules.Builtin
ParsedResultType level;
if (result is Exception)
level = ParsedResultType.Fatal;
else if (result != null && result is Library.Interface.IBasicResults)
level = ((IBasicResults)result).ParsedResult;
else if (result != null && result is IBasicResults results)
level = results.ParsedResult;
else
level = ParsedResultType.Error;
@@ -148,7 +148,7 @@ namespace Duplicati.Library.Modules.Builtin {
new CommandLineArgument(OPTION_MAX_LOG_LINES, CommandLineArgument.ArgumentType.Integer, Strings.ReportHelper.OptionmaxloglinesShort, Strings.ReportHelper.OptionmaxloglinesLong, DEFAULT_LOGLINES.ToString()),
new CommandLineArgument(OPTION_RESULT_FORMAT, CommandLineArgument.ArgumentType.Enumeration, Strings.ReportHelper.ResultFormatShort, Strings.ReportHelper.ResultFormatLong(Enum.GetNames(typeof(ResultExportFormat))), DEFAULT_EXPORT_FORMAT.ToString(), null, Enum.GetNames(typeof(ResultExportFormat))),
});
});
}
}
@@ -244,13 +244,11 @@ namespace Duplicati.Library.Modules.Builtin {
catch (Exception e)
{
ex = e;
if (ex is WebException && ((WebException)ex).Response is HttpWebResponse)
if (ex is WebException exception && exception.Response is HttpWebResponse response)
{
var response = ((WebException)ex).Response as HttpWebResponse;
Logging.Log.WriteWarningMessage(LOGTAG,
Logging.Log.WriteWarningMessage(LOGTAG,
"HttpResponseError",
ex,
exception,
"HTTP Response: {0} - {1}: {2}",
((int)response.StatusCode).ToString(),
response.StatusDescription,
+10 -10
View File
@@ -94,13 +94,13 @@ namespace Duplicati.Library.Snapshots
string[] arrInstalledInstances = null;
var installed = Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server", "InstalledInstances", "");
if (installed is string)
if (installed is string s)
{
if (!string.IsNullOrWhiteSpace(installed as string))
arrInstalledInstances = new string[] { installed as string };
if (!string.IsNullOrWhiteSpace(s))
arrInstalledInstances = new string[] { s };
}
else if (installed is string[])
arrInstalledInstances = (string[])installed;
else if (installed is string[] strings)
arrInstalledInstances = strings;
else if (installed != null)
try { arrInstalledInstances = (string[])installed; }
catch { }
@@ -108,13 +108,13 @@ namespace Duplicati.Library.Snapshots
if(Environment.Is64BitOperatingSystem && arrInstalledInstances == null)
{
var installed32on64 = Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server", "InstalledInstances", "");
if (installed32on64 is string)
if (installed32on64 is string on64)
{
if (!string.IsNullOrWhiteSpace(installed32on64 as string))
arrInstalledInstances = new string[] { installed32on64 as string };
if (!string.IsNullOrWhiteSpace(on64))
arrInstalledInstances = new string[] { on64 };
}
else if (installed32on64 is string[])
arrInstalledInstances = (string[])installed32on64;
else if (installed32on64 is string[] strings)
arrInstalledInstances = strings;
else if (installed32on64 != null)
try { arrInstalledInstances = (string[])installed32on64; }
catch { }
+2 -2
View File
@@ -111,8 +111,8 @@ namespace Duplicati.Library.UsageReporter
/// <param name="args">Arguments.</param>
private static void HandleUncaughtException(object sender, UnhandledExceptionEventArgs args)
{
if (args.ExceptionObject is Exception)
Report(args.ExceptionObject as Exception, ReportType.Crash);
if (args.ExceptionObject is Exception exception)
Report(exception, ReportType.Crash);
}
/// <summary>
+13 -13
View File
@@ -99,16 +99,16 @@ namespace Duplicati.Library.Utility
m_request.Timeout = System.Threading.Timeout.Infinite;
//Then we register custom settings
if (m_request is HttpWebRequest)
if (this.m_request is HttpWebRequest webRequest)
{
if (((HttpWebRequest)m_request).ReadWriteTimeout != System.Threading.Timeout.Infinite)
m_activity_timeout = ((HttpWebRequest)m_request).ReadWriteTimeout;
if (webRequest.ReadWriteTimeout != System.Threading.Timeout.Infinite)
m_activity_timeout = webRequest.ReadWriteTimeout;
((HttpWebRequest)m_request).ReadWriteTimeout = System.Threading.Timeout.Infinite;
webRequest.ReadWriteTimeout = System.Threading.Timeout.Infinite;
// Prevent in-memory buffering causing out-of-memory issues
((HttpWebRequest)m_request).AllowReadStreamBuffering = HttpContextSettings.BufferRequests;
}
webRequest.AllowReadStreamBuffering = HttpContextSettings.BufferRequests;
}
}
/// <summary>
@@ -129,12 +129,12 @@ namespace Duplicati.Library.Utility
public Stream GetRequestStream(long contentlength = -1)
{
// Prevent in-memory buffering causing out-of-memory issues
if (m_request is HttpWebRequest)
if (this.m_request is HttpWebRequest request)
{
if (contentlength >= 0)
((HttpWebRequest)m_request).ContentLength = contentlength;
if (m_request.ContentLength >= 0)
((HttpWebRequest)m_request).AllowWriteStreamBuffering = false;
request.ContentLength = contentlength;
if (request.ContentLength >= 0)
request.AllowWriteStreamBuffering = false;
}
if (m_state == RequestStates.GetRequest)
@@ -221,12 +221,12 @@ namespace Duplicati.Library.Utility
catch (Exception ex)
{
if (m_timedout)
m_exception = new WebException(string.Format("{0} timed out", m_isRequest ? "GetRequestStream" : "GetResponse"), ex, WebExceptionStatus.Timeout, ex is WebException ? ((WebException)ex).Response : null);
m_exception = new WebException(string.Format("{0} timed out", m_isRequest ? "GetRequestStream" : "GetResponse"), ex, WebExceptionStatus.Timeout, ex is WebException exception ? exception.Response : null);
else
{
// Workaround for: https://bugzilla.xamarin.com/show_bug.cgi?id=28287
var wex = ex;
if (ex is WebException && ((WebException)ex).Response == null)
if (ex is WebException exception && exception.Response == null)
{
WebResponse resp = null;
@@ -238,7 +238,7 @@ namespace Duplicati.Library.Utility
catch { }
if (resp != null)
wex = new WebException(ex.Message, ex.InnerException, ((WebException)ex).Status, resp);
wex = new WebException(exception.Message, exception.InnerException, exception.Status, resp);
}
m_exception = wex;
+14 -14
View File
@@ -212,10 +212,10 @@ namespace Duplicati.Library.Utility
{
inputPos = inputPosStack.Pop(); // Pop input and pattern positions from stack
patternPos = patternPosStack.Pop(); // Matching will succeed if rest of the input string matches rest of the pattern
// Modified from original version to match zero or more characters
//if (inputPos == input.Length && patternPos == pattern.Length)
if (inputPos == input.Length && (patternPos == pattern.Length || (patternPos == pattern.Length - 1 && pattern[patternPos] == MULTIPLE_WILDCARD)))
matched = true; // Reached end of both pattern and input string, hence matching is successful
else
@@ -519,17 +519,17 @@ namespace Duplicati.Library.Utility
var p = q.Dequeue();
if (p == null || p.Empty)
continue;
else if (p is FilterExpression)
else if (p is FilterExpression expression)
{
if (((FilterExpression)p).Result)
if (expression.Result)
includes = true;
else
excludes = true;
}
else if (p is JoinedFilterExpression)
else if (p is JoinedFilterExpression filterExpression)
{
q.Enqueue(((JoinedFilterExpression)p).First);
q.Enqueue(((JoinedFilterExpression)p).Second);
q.Enqueue(filterExpression.First);
q.Enqueue(filterExpression.Second);
}
}
@@ -609,8 +609,8 @@ namespace Duplicati.Library.Utility
if (first == null || first.Empty)
return second;
if (first is FilterExpression && second is FilterExpression && ((FilterExpression)first).Result == ((FilterExpression)second).Result)
return Combine((FilterExpression)first, (FilterExpression)second);
if (first is FilterExpression expression && second is FilterExpression filterExpression && expression.Result == filterExpression.Result)
return Combine(expression, filterExpression);
return new JoinedFilterExpression(first, second);
}
@@ -665,12 +665,12 @@ namespace Duplicati.Library.Utility
{
var f = work.Pop();
if (f is FilterExpression)
res = res.Union(((FilterExpression)f).Serialize());
else if (f is JoinedFilterExpression)
if (f is FilterExpression expression)
res = res.Union(expression.Serialize());
else if (f is JoinedFilterExpression filterExpression)
{
work.Push(((JoinedFilterExpression)f).Second);
work.Push(((JoinedFilterExpression)f).First);
work.Push(filterExpression.Second);
work.Push(filterExpression.First);
}
else
throw new Exception(string.Format("Cannot serialize filter instance of type: {0}", f.GetType()));
+8 -8
View File
@@ -17,7 +17,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Duplicati.Library.Common;
using Duplicati.Library.Localization.Short;
@@ -297,7 +297,7 @@ namespace Duplicati.Library.Utility
yield return FilterGroups.CreateWildcardFilter(@"*/Google/Chrome/Safe Browsing*");
yield return FilterGroups.CreateWildcardFilter(@"*/iPhoto Library/iPod Photo Cache/");
yield return FilterGroups.CreateWildcardFilter(@"*/Mozilla/Firefox/*cache*");
yield return FilterGroups.CreateWildcardFilter(@"*/cookies.sqlite-*"); // Journal for database used to store Firefox cookies between sessions
yield return FilterGroups.CreateWildcardFilter(@"*/cookies.sqlite-*"); // Journal for database used to store Firefox cookies between sessions
yield return FilterGroups.CreateWildcardFilter(@"*/permissions.sqlite-*"); // Journal for database used to store Firefox site-specific permissions
}
@@ -627,8 +627,8 @@ namespace Duplicati.Library.Utility
{
if (new string[] { "PathsExcluded", "ContentsExcluded", "FileContentsExcluded" }.Contains(n.Value, StringComparer.Ordinal))
{
if (n.NextNode is System.Xml.Linq.XContainer)
foreach (var p in ((System.Xml.Linq.XContainer)n.NextNode).Elements("string"))
if (n.NextNode is XContainer container)
foreach (var p in container.Elements("string"))
{
if (System.IO.File.Exists(p.Value))
res.Add(p.Value);
@@ -708,10 +708,10 @@ namespace Duplicati.Library.Utility
.SelectMany(x =>
{
var v = sk.GetValue(x);
if (v is string)
return new string[] { (string)v };
else if (v is string[])
return (string[])v;
if (v is string s)
return new string[] { s };
else if (v is string[] strings)
return strings;
else
return new string[0];
})
@@ -60,8 +60,8 @@ namespace Duplicati.Library.Utility
return first;
else
{
if (first is FilterExpression && second is FilterExpression && ((FilterExpression)first).Result == ((FilterExpression)second).Result)
return FilterExpression.Combine((FilterExpression)first, (FilterExpression)second);
if (first is FilterExpression expression && second is FilterExpression filterExpression && expression.Result == filterExpression.Result)
return FilterExpression.Combine(expression, filterExpression);
return new JoinedFilterExpression(first, second);
}
+3 -3
View File
@@ -1118,11 +1118,11 @@ namespace Duplicati.Library.Utility
if (IsPrimitiveTypeForSerialization(item.GetType()))
{
if (item is DateTime)
if (item is DateTime time)
{
writer.Write(((DateTime)item).ToLocalTime());
writer.Write(time.ToLocalTime());
writer.Write(" (");
writer.Write(ToUnixTimestamp((DateTime)item));
writer.Write(ToUnixTimestamp(time));
writer.Write(")");
}
else
+5 -4
View File
@@ -19,6 +19,7 @@ using System;
using System.Linq;
using Duplicati.Library.Logging;
using System.Collections.Generic;
using Duplicati.Library.Interface;
namespace Duplicati.Server
{
@@ -125,8 +126,8 @@ namespace Duplicati.Server
if (entry.Exception == null)
this.ExceptionID = null;
else if (entry.Exception is Library.Interface.UserInformationException)
this.ExceptionID = ((Library.Interface.UserInformationException)entry.Exception).HelpID;
else if (entry.Exception is UserInformationException exception)
this.ExceptionID = exception.HelpID;
else
this.ExceptionID = entry.Exception.GetType().FullName;
@@ -339,8 +340,8 @@ namespace Duplicati.Server
{
var sf = m_serverfile;
m_serverfile = null;
if (sf is IDisposable)
((IDisposable)sf).Dispose();
if (sf is IDisposable disposable)
disposable.Dispose();
}
}
+22 -27
View File
@@ -20,6 +20,7 @@
using System;
using System.Linq;
using System.Collections.Generic;
using Duplicati.Library.Interface;
using Duplicati.Server.Serialization;
namespace Duplicati.Server
@@ -424,15 +425,15 @@ namespace Duplicati.Server
public static Duplicati.Library.Interface.IBasicResults Run(IRunnerData data, bool fromQueue)
{
if (data is CustomRunnerTask)
if (data is CustomRunnerTask task)
{
try
{
var sink = new MessageSink(data.TaskID, null);
var sink = new MessageSink(task.TaskID, null);
Program.GenerateProgressState = sink.Copy;
Program.StatusEventNotifyer.SignalNewEvent();
((CustomRunnerTask)data).Run(sink);
task.Run(sink);
}
catch(Exception ex)
{
@@ -687,8 +688,8 @@ namespace Duplicati.Server
Program.DataConnection.SetMetadata(backup.Metadata, long.Parse(backup.ID), null);
string messageid = null;
if (ex is Library.Interface.UserInformationException)
messageid = ((Library.Interface.UserInformationException)ex).HelpID;
if (ex is UserInformationException exception)
messageid = exception.HelpID;
System.Threading.Interlocked.Increment(ref Program.LastDataUpdateID);
Program.DataConnection.RegisterNotification(
@@ -746,50 +747,44 @@ namespace Duplicati.Server
private static void UpdateMetadata(Duplicati.Server.Serialization.Interface.IBackup backup, Duplicati.Library.Interface.IBasicResults result)
{
if (result is Duplicati.Library.Interface.IRestoreResults)
if (result is IRestoreResults r1)
{
var r = (Duplicati.Library.Interface.IRestoreResults)result;
backup.Metadata["LastRestoreDuration"] = r.Duration.ToString();
backup.Metadata["LastRestoreDuration"] = r1.Duration.ToString();
backup.Metadata["LastRestoreStarted"] = Library.Utility.Utility.SerializeDateTime(result.BeginTime.ToUniversalTime());
backup.Metadata["LastRestoreFinished"] = Library.Utility.Utility.SerializeDateTime(result.EndTime.ToUniversalTime());
}
if (result is Duplicati.Library.Interface.IParsedBackendStatistics)
if (result is IParsedBackendStatistics r2)
{
var r = (Duplicati.Library.Interface.IParsedBackendStatistics)result;
UpdateMetadata(backup, r);
UpdateMetadata(backup, r2);
}
if (result is Duplicati.Library.Interface.IBackendStatsticsReporter)
if (result is IBackendStatsticsReporter r3)
{
var r = (Duplicati.Library.Interface.IBackendStatsticsReporter)result;
if (r.BackendStatistics is Duplicati.Library.Interface.IParsedBackendStatistics)
UpdateMetadata(backup, (Duplicati.Library.Interface.IParsedBackendStatistics)r.BackendStatistics);
if (r3.BackendStatistics is IParsedBackendStatistics statistics)
UpdateMetadata(backup, statistics);
}
if (result is Duplicati.Library.Interface.ICompactResults)
if (result is ICompactResults r4)
{
var r = (Duplicati.Library.Interface.ICompactResults)result;
UpdateMetadataLastCompact(backup, r);
UpdateMetadataLastCompact(backup, r4);
if (r.VacuumResults != null)
UpdateMetadataLastVacuum(backup, r.VacuumResults);
if (r4.VacuumResults != null)
UpdateMetadataLastVacuum(backup, r4.VacuumResults);
}
if (result is Duplicati.Library.Interface.IVacuumResults)
if (result is IVacuumResults r5)
{
var r = (Duplicati.Library.Interface.IVacuumResults)result;
UpdateMetadataLastVacuum(backup, r);
UpdateMetadataLastVacuum(backup, r5);
}
if (result is Duplicati.Library.Interface.IBackupResults)
if (result is IBackupResults r)
{
var r = (Duplicati.Library.Interface.IBackupResults)result;
backup.Metadata["SourceFilesSize"] = r.SizeOfExaminedFiles.ToString();
backup.Metadata["SourceFilesCount"] = r.ExaminedFiles.ToString();
backup.Metadata["SourceSizeString"] = Duplicati.Library.Utility.Utility.FormatSizeString(r.SizeOfExaminedFiles);
backup.Metadata["LastBackupStarted"] = Library.Utility.Utility.SerializeDateTime(result.BeginTime.ToUniversalTime());
backup.Metadata["LastBackupFinished"] = Library.Utility.Utility.SerializeDateTime(result.EndTime.ToUniversalTime());
backup.Metadata["LastBackupStarted"] = Library.Utility.Utility.SerializeDateTime(r.BeginTime.ToUniversalTime());
backup.Metadata["LastBackupFinished"] = Library.Utility.Utility.SerializeDateTime(r.EndTime.ToUniversalTime());
backup.Metadata["LastBackupDuration"] = r.Duration.ToString();
if (r.CompactResults != null)
+11 -11
View File
@@ -21,7 +21,7 @@ using System.Linq;
using HttpServer.HttpModules;
using Duplicati.Server.WebServer.RESTMethods;
namespace Duplicati.Server.WebServer
{
public class RESTHandler : HttpModule
@@ -144,7 +144,7 @@ namespace Duplicati.Server.WebServer
info.Response.Status = System.Net.HttpStatusCode.NotFound;
info.Response.Reason = "No such module";
}
else if (method == HttpServer.Method.Get && mod is IRESTMethodGET)
else if (method == HttpServer.Method.Get && mod is IRESTMethodGET get)
{
if (info.Request.Form != HttpServer.HttpForm.EmptyForm)
{
@@ -158,11 +158,11 @@ namespace Duplicati.Server.WebServer
if (!info.Request.QueryString.Contains(v.Name))
info.Request.QueryString.Add(v.Name, v.Value);
}
((IRESTMethodGET)mod).GET(key, info);
get.GET(key, info);
}
else if (method == HttpServer.Method.Put && mod is IRESTMethodPUT)
((IRESTMethodPUT)mod).PUT(key, info);
else if (method == HttpServer.Method.Post && mod is IRESTMethodPOST)
else if (method == HttpServer.Method.Put && mod is IRESTMethodPUT put)
put.PUT(key, info);
else if (method == HttpServer.Method.Post && mod is IRESTMethodPOST post)
{
if (info.Request.Form == HttpServer.HttpForm.EmptyForm || info.Request.Form == HttpServer.HttpInput.Empty)
{
@@ -175,12 +175,12 @@ namespace Duplicati.Server.WebServer
if (!info.Request.Form.Contains(v.Name))
info.Request.Form.Add(v.Name, v.Value);
}
((IRESTMethodPOST)mod).POST(key, info);
post.POST(key, info);
}
else if (method == HttpServer.Method.Delete && mod is IRESTMethodDELETE)
((IRESTMethodDELETE)mod).DELETE(key, info);
else if (method == "PATCH" && mod is IRESTMethodPATCH)
((IRESTMethodPATCH)mod).PATCH(key, info);
else if (method == HttpServer.Method.Delete && mod is IRESTMethodDELETE delete)
delete.DELETE(key, info);
else if (method == "PATCH" && mod is IRESTMethodPATCH patch)
patch.PATCH(key, info);
else
{
info.Response.Status = System.Net.HttpStatusCode.MethodNotAllowed;
@@ -35,8 +35,8 @@ namespace Duplicati.Server.WebServer.RESTMethods
continue;
var desc = mod.GetType().Name;
if (mod is IRESTMethodDocumented)
desc = ((IRESTMethodDocumented)mod).Description;
if (mod is IRESTMethodDocumented documented)
desc = documented.Description;
sb.AppendFormat(ITEM_TEMPLATE, RESTHandler.API_URI_PATH, m, mod.GetType().Name, desc);
}
@@ -60,9 +60,8 @@ namespace Duplicati.Server.WebServer.RESTMethods
else
{
var desc = "";
if (m is IRESTMethodDocumented)
if (m is IRESTMethodDocumented doc)
{
var doc = m as IRESTMethodDocumented;
desc = doc.Description;
foreach(var t in doc.Types)
sb.AppendFormat(METHOD_TEMPLATE, t.Key, JsonConvert.SerializeObject(t.Value)); //TODO: Format the type
@@ -115,8 +115,8 @@ namespace Duplicati.Server.WebServer.RESTMethods
finally
{
foreach (var n in modules)
if (n is IDisposable)
((IDisposable)n).Dispose();
if (n is IDisposable disposable)
disposable.Dispose();
}
}