From afab61a05be83c5ffd4fdf9a732791b6d9ec2291 Mon Sep 17 00:00:00 2001 From: Kenneth Hsu Date: Sun, 29 Sep 2019 20:16:28 -0700 Subject: [PATCH] Use pattern matching to simplify casts. --- .../CommandLine/BackendTester/Program.cs | 12 ++--- Duplicati/CommandLine/Program.cs | 5 +- .../Library/AutoUpdater/UpdaterManager.cs | 4 +- .../Library/Backend/AmazonCloudDrive/AmzCD.cs | 4 +- .../Backend/AzureBlob/AzureBlobWrapper.cs | 3 +- .../Library/Backend/Backblaze/B2AuthHelper.cs | 11 ++--- Duplicati/Library/Backend/Box/BoxBackend.cs | 3 +- .../Library/Backend/CloudFiles/CloudFiles.cs | 4 +- .../Library/Backend/Dropbox/DropboxHelper.cs | 10 ++-- .../GoogleServices/GoogleCloudStorage.cs | 4 +- .../Backend/GoogleServices/GoogleCommon.cs | 4 +- .../Library/Backend/Jottacloud/Jottacloud.cs | 5 +- .../Backend/OAuthHelper/JSONWebHelper.cs | 8 +-- .../Backend/OAuthHelper/OAuthHelper.cs | 8 +-- .../Backend/OpenStack/OpenStackStorage.cs | 6 +-- Duplicati/Library/Backend/Sia/Sia.cs | 4 +- .../Library/Backend/TahoeLAFS/TahoeBackend.cs | 5 +- Duplicati/Library/Backend/WEBDAV/WEBDAV.cs | 5 +- .../Library/Compression/FileArchiveZip.cs | 4 +- Duplicati/Library/Main/BackendManager.cs | 23 ++++----- Duplicati/Library/Main/Controller.cs | 21 ++++---- .../Library/Main/Database/LocalDatabase.cs | 5 +- .../Main/Database/LocalListChangesDatabase.cs | 5 +- .../Main/Database/LocalPurgeDatabase.cs | 5 +- .../Main/Database/LocalRestoreDatabase.cs | 5 +- .../Library/Main/Operation/BackupHandler.cs | 4 +- .../Main/Operation/FilelistProcessor.cs | 5 +- .../Main/Operation/ListFilesHandler.cs | 3 +- Duplicati/Library/Main/ResultClasses.cs | 8 +-- .../Library/Main/Volumes/VolumeReaderBase.cs | 4 +- .../Library/Main/Volumes/VolumeWriterBase.cs | 4 +- .../Library/Modules/Builtin/ReportHelper.cs | 4 +- .../DuplicatiFormatSerializer.cs | 6 +-- .../Library/Modules/Builtin/RunScript.cs | 4 +- .../Modules/Builtin/SendHttpMessage.cs | 10 ++-- Duplicati/Library/Snapshots/MSSQLUtility.cs | 20 ++++---- Duplicati/Library/UsageReporter/Reporter.cs | 4 +- Duplicati/Library/Utility/AsyncHttpRequest.cs | 26 +++++----- Duplicati/Library/Utility/FilterExpression.cs | 28 +++++------ Duplicati/Library/Utility/FilterGroups.cs | 16 +++--- .../Library/Utility/JoinedFilterExpression.cs | 4 +- Duplicati/Library/Utility/Utility.cs | 6 +-- Duplicati/Server/LogWriteHandler.cs | 9 ++-- Duplicati/Server/Runner.cs | 49 +++++++++---------- Duplicati/Server/WebServer/RESTHandler.cs | 22 ++++----- .../Server/WebServer/RESTMethods/Help.cs | 7 ++- .../WebServer/RESTMethods/RemoteOperation.cs | 4 +- 47 files changed, 208 insertions(+), 212 deletions(-) diff --git a/Duplicati/CommandLine/BackendTester/Program.cs b/Duplicati/CommandLine/BackendTester/Program.cs index b29031b32..3f4285ef0 100644 --- a/Duplicati/CommandLine/BackendTester/Program.cs +++ b/Duplicati/CommandLine/BackendTester/Program.cs @@ -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(); diff --git a/Duplicati/CommandLine/Program.cs b/Duplicati/CommandLine/Program.cs index 1cad210cf..b5e205f17 100644 --- a/Duplicati/CommandLine/Program.cs +++ b/Duplicati/CommandLine/Program.cs @@ -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)) diff --git a/Duplicati/Library/AutoUpdater/UpdaterManager.cs b/Duplicati/Library/AutoUpdater/UpdaterManager.cs index 813056294..771e81e90 100644 --- a/Duplicati/Library/AutoUpdater/UpdaterManager.cs +++ b/Duplicati/Library/AutoUpdater/UpdaterManager.cs @@ -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; diff --git a/Duplicati/Library/Backend/AmazonCloudDrive/AmzCD.cs b/Duplicati/Library/Backend/AmazonCloudDrive/AmzCD.cs index 83224913c..79f4c0c09 100644 --- a/Duplicati/Library/Backend/AmazonCloudDrive/AmzCD.cs +++ b/Duplicati/Library/Backend/AmazonCloudDrive/AmzCD.cs @@ -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 diff --git a/Duplicati/Library/Backend/AzureBlob/AzureBlobWrapper.cs b/Duplicati/Library/Backend/AzureBlob/AzureBlobWrapper.cs index ab237b79d..b05465713 100644 --- a/Duplicati/Library/Backend/AzureBlob/AzureBlobWrapper.cs +++ b/Duplicati/Library/Backend/AzureBlob/AzureBlobWrapper.cs @@ -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); diff --git a/Duplicati/Library/Backend/Backblaze/B2AuthHelper.cs b/Duplicati/Library/Backend/Backblaze/B2AuthHelper.cs index a18edb06c..a358924ed 100644 --- a/Duplicati/Library/Backend/Backblaze/B2AuthHelper.cs +++ b/Duplicati/Library/Backend/Backblaze/B2AuthHelper.cs @@ -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); } diff --git a/Duplicati/Library/Backend/Box/BoxBackend.cs b/Duplicati/Library/Backend/Box/BoxBackend.cs index dbb0bc86c..03d6f6bb0 100644 --- a/Duplicati/Library/Backend/Box/BoxBackend.cs +++ b/Duplicati/Library/Backend/Box/BoxBackend.cs @@ -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(); diff --git a/Duplicati/Library/Backend/CloudFiles/CloudFiles.cs b/Duplicati/Library/Backend/CloudFiles/CloudFiles.cs index 302ffea67..715166751 100644 --- a/Duplicati/Library/Backend/CloudFiles/CloudFiles.cs +++ b/Duplicati/Library/Backend/CloudFiles/CloudFiles.cs @@ -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; diff --git a/Duplicati/Library/Backend/Dropbox/DropboxHelper.cs b/Duplicati/Library/Backend/Dropbox/DropboxHelper.cs index 34a20a2fb..61b642309 100644 --- a/Duplicati/Library/Backend/Dropbox/DropboxHelper.cs +++ b/Duplicati/Library/Backend/Dropbox/DropboxHelper.cs @@ -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(); } diff --git a/Duplicati/Library/Backend/GoogleServices/GoogleCloudStorage.cs b/Duplicati/Library/Backend/GoogleServices/GoogleCloudStorage.cs index cb2f08592..1c63f0e06 100644 --- a/Duplicati/Library/Backend/GoogleServices/GoogleCloudStorage.cs +++ b/Duplicati/Library/Backend/GoogleServices/GoogleCloudStorage.cs @@ -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; diff --git a/Duplicati/Library/Backend/GoogleServices/GoogleCommon.cs b/Duplicati/Library/Backend/GoogleServices/GoogleCommon.cs index 5f61530af..b087be3f1 100644 --- a/Duplicati/Library/Backend/GoogleServices/GoogleCommon.cs +++ b/Duplicati/Library/Backend/GoogleServices/GoogleCommon.cs @@ -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) diff --git a/Duplicati/Library/Backend/Jottacloud/Jottacloud.cs b/Duplicati/Library/Backend/Jottacloud/Jottacloud.cs index cfc9f3763..e4a0f69f4 100644 --- a/Duplicati/Library/Backend/Jottacloud/Jottacloud.cs +++ b/Duplicati/Library/Backend/Jottacloud/Jottacloud.cs @@ -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; } diff --git a/Duplicati/Library/Backend/OAuthHelper/JSONWebHelper.cs b/Duplicati/Library/Backend/OAuthHelper/JSONWebHelper.cs index ef5e13a3e..f5c091cf3 100644 --- a/Duplicati/Library/Backend/OAuthHelper/JSONWebHelper.cs +++ b/Duplicati/Library/Backend/OAuthHelper/JSONWebHelper.cs @@ -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"; diff --git a/Duplicati/Library/Backend/OAuthHelper/OAuthHelper.cs b/Duplicati/Library/Backend/OAuthHelper/OAuthHelper.cs index 9eaf90247..027291cb9 100644 --- a/Duplicati/Library/Backend/OAuthHelper/OAuthHelper.cs +++ b/Duplicati/Library/Backend/OAuthHelper/OAuthHelper.cs @@ -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 diff --git a/Duplicati/Library/Backend/OpenStack/OpenStackStorage.cs b/Duplicati/Library/Backend/OpenStack/OpenStackStorage.cs index 86683be4a..a33dd93ad 100644 --- a/Duplicati/Library/Backend/OpenStack/OpenStackStorage.cs +++ b/Duplicati/Library/Backend/OpenStack/OpenStackStorage.cs @@ -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; diff --git a/Duplicati/Library/Backend/Sia/Sia.cs b/Duplicati/Library/Backend/Sia/Sia.cs index 4e1d0654c..97aed2e7f 100644 --- a/Duplicati/Library/Backend/Sia/Sia.cs +++ b/Duplicati/Library/Backend/Sia/Sia.cs @@ -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)); diff --git a/Duplicati/Library/Backend/TahoeLAFS/TahoeBackend.cs b/Duplicati/Library/Backend/TahoeLAFS/TahoeBackend.cs index eb5ab9b5b..e36e03ce9 100644 --- a/Duplicati/Library/Backend/TahoeLAFS/TahoeBackend.cs +++ b/Duplicati/Library/Backend/TahoeLAFS/TahoeBackend.cs @@ -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; diff --git a/Duplicati/Library/Backend/WEBDAV/WEBDAV.cs b/Duplicati/Library/Backend/WEBDAV/WEBDAV.cs index e9f955c2a..5e1f0b205 100644 --- a/Duplicati/Library/Backend/WEBDAV/WEBDAV.cs +++ b/Duplicati/Library/Backend/WEBDAV/WEBDAV.cs @@ -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; diff --git a/Duplicati/Library/Compression/FileArchiveZip.cs b/Duplicati/Library/Compression/FileArchiveZip.cs index d1514ce84..0f59b08f3 100644 --- a/Duplicati/Library/Compression/FileArchiveZip.cs +++ b/Duplicati/Library/Compression/FileArchiveZip.cs @@ -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); diff --git a/Duplicati/Library/Main/BackendManager.cs b/Duplicati/Library/Main/BackendManager.cs index dda104073..c4436d63f 100644 --- a/Duplicati/Library/Main/BackendManager.cs +++ b/Duplicati/Library/Main/BackendManager.cs @@ -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 { diff --git a/Duplicati/Library/Main/Controller.cs b/Duplicati/Library/Main/Controller.cs index 6a6243a68..684f19a67 100644 --- a/Duplicati/Library/Main/Controller.cs +++ b/Duplicati/Library/Main/Controller.cs @@ -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 /// The sink to use. 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 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 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 diff --git a/Duplicati/Library/Main/Database/LocalDatabase.cs b/Duplicati/Library/Main/Database/LocalDatabase.cs index aa1265559..ed7d4bb3d 100644 --- a/Duplicati/Library/Main/Database/LocalDatabase.cs +++ b/Duplicati/Library/Main/Database/LocalDatabase.cs @@ -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)) diff --git a/Duplicati/Library/Main/Database/LocalListChangesDatabase.cs b/Duplicati/Library/Main/Database/LocalListChangesDatabase.cs index 00222df26..ea964e8a2 100644 --- a/Duplicati/Library/Main/Database/LocalListChangesDatabase.cs +++ b/Duplicati/Library/Main/Database/LocalListChangesDatabase.cs @@ -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); diff --git a/Duplicati/Library/Main/Database/LocalPurgeDatabase.cs b/Duplicati/Library/Main/Database/LocalPurgeDatabase.cs index 11955752a..38571f15f 100644 --- a/Duplicati/Library/Main/Database/LocalPurgeDatabase.cs +++ b/Duplicati/Library/Main/Database/LocalPurgeDatabase.cs @@ -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)) { diff --git a/Duplicati/Library/Main/Database/LocalRestoreDatabase.cs b/Duplicati/Library/Main/Database/LocalRestoreDatabase.cs index b013e2c89..f6463a0a0 100644 --- a/Duplicati/Library/Main/Database/LocalRestoreDatabase.cs +++ b/Duplicati/Library/Main/Database/LocalRestoreDatabase.cs @@ -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)); diff --git a/Duplicati/Library/Main/Operation/BackupHandler.cs b/Duplicati/Library/Main/Operation/BackupHandler.cs index 89a88461c..7ffbefe4e 100644 --- a/Duplicati/Library/Main/Operation/BackupHandler.cs +++ b/Duplicati/Library/Main/Operation/BackupHandler.cs @@ -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; diff --git a/Duplicati/Library/Main/Operation/FilelistProcessor.cs b/Duplicati/Library/Main/Operation/FilelistProcessor.cs index ba1aed082..df20a9589 100644 --- a/Duplicati/Library/Main/Operation/FilelistProcessor.cs +++ b/Duplicati/Library/Main/Operation/FilelistProcessor.cs @@ -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; diff --git a/Duplicati/Library/Main/Operation/ListFilesHandler.cs b/Duplicati/Library/Main/Operation/ListFilesHandler.cs index 9ff3c619e..dae2ab929 100644 --- a/Duplicati/Library/Main/Operation/ListFilesHandler.cs +++ b/Duplicati/Library/Main/Operation/ListFilesHandler.cs @@ -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)) diff --git a/Duplicati/Library/Main/ResultClasses.cs b/Duplicati/Library/Main/ResultClasses.cs index 0016b5aae..fb38e13e2 100644 --- a/Duplicati/Library/Main/ResultClasses.cs +++ b/Duplicati/Library/Main/ResultClasses.cs @@ -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; } diff --git a/Duplicati/Library/Main/Volumes/VolumeReaderBase.cs b/Duplicati/Library/Main/Volumes/VolumeReaderBase.cs index 1011ac37d..99c684134 100644 --- a/Duplicati/Library/Main/Volumes/VolumeReaderBase.cs +++ b/Duplicati/Library/Main/Volumes/VolumeReaderBase.cs @@ -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)); } diff --git a/Duplicati/Library/Main/Volumes/VolumeWriterBase.cs b/Duplicati/Library/Main/Volumes/VolumeWriterBase.cs index 23dad62f0..b83a897b1 100644 --- a/Duplicati/Library/Main/Volumes/VolumeWriterBase.cs +++ b/Duplicati/Library/Main/Volumes/VolumeWriterBase.cs @@ -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(); } diff --git a/Duplicati/Library/Modules/Builtin/ReportHelper.cs b/Duplicati/Library/Modules/Builtin/ReportHelper.cs index ca83f31bc..75c71868a 100644 --- a/Duplicati/Library/Modules/Builtin/ReportHelper.cs +++ b/Duplicati/Library/Modules/Builtin/ReportHelper.cs @@ -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; diff --git a/Duplicati/Library/Modules/Builtin/ResultSerialization/DuplicatiFormatSerializer.cs b/Duplicati/Library/Modules/Builtin/ResultSerialization/DuplicatiFormatSerializer.cs index fb891ae64..8ce248d4c 100644 --- a/Duplicati/Library/Modules/Builtin/ResultSerialization/DuplicatiFormatSerializer.cs +++ b/Duplicati/Library/Modules/Builtin/ResultSerialization/DuplicatiFormatSerializer.cs @@ -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(); } diff --git a/Duplicati/Library/Modules/Builtin/RunScript.cs b/Duplicati/Library/Modules/Builtin/RunScript.cs index 7ab0ffaf7..1ae9b7601 100644 --- a/Duplicati/Library/Modules/Builtin/RunScript.cs +++ b/Duplicati/Library/Modules/Builtin/RunScript.cs @@ -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; diff --git a/Duplicati/Library/Modules/Builtin/SendHttpMessage.cs b/Duplicati/Library/Modules/Builtin/SendHttpMessage.cs index ec1363c1f..12d8c2892 100644 --- a/Duplicati/Library/Modules/Builtin/SendHttpMessage.cs +++ b/Duplicati/Library/Modules/Builtin/SendHttpMessage.cs @@ -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, diff --git a/Duplicati/Library/Snapshots/MSSQLUtility.cs b/Duplicati/Library/Snapshots/MSSQLUtility.cs index add7622fc..0e43a340d 100644 --- a/Duplicati/Library/Snapshots/MSSQLUtility.cs +++ b/Duplicati/Library/Snapshots/MSSQLUtility.cs @@ -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 { } diff --git a/Duplicati/Library/UsageReporter/Reporter.cs b/Duplicati/Library/UsageReporter/Reporter.cs index 7ef020e9f..84d3c0e36 100644 --- a/Duplicati/Library/UsageReporter/Reporter.cs +++ b/Duplicati/Library/UsageReporter/Reporter.cs @@ -111,8 +111,8 @@ namespace Duplicati.Library.UsageReporter /// Arguments. 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); } /// diff --git a/Duplicati/Library/Utility/AsyncHttpRequest.cs b/Duplicati/Library/Utility/AsyncHttpRequest.cs index f515f7b90..47ea5ad9f 100644 --- a/Duplicati/Library/Utility/AsyncHttpRequest.cs +++ b/Duplicati/Library/Utility/AsyncHttpRequest.cs @@ -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; + } } /// @@ -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; diff --git a/Duplicati/Library/Utility/FilterExpression.cs b/Duplicati/Library/Utility/FilterExpression.cs index 54a7bee3f..9fda2e89d 100644 --- a/Duplicati/Library/Utility/FilterExpression.cs +++ b/Duplicati/Library/Utility/FilterExpression.cs @@ -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())); diff --git a/Duplicati/Library/Utility/FilterGroups.cs b/Duplicati/Library/Utility/FilterGroups.cs index df82fdc8f..62be51008 100644 --- a/Duplicati/Library/Utility/FilterGroups.cs +++ b/Duplicati/Library/Utility/FilterGroups.cs @@ -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]; }) diff --git a/Duplicati/Library/Utility/JoinedFilterExpression.cs b/Duplicati/Library/Utility/JoinedFilterExpression.cs index 44501eba8..f50512d47 100644 --- a/Duplicati/Library/Utility/JoinedFilterExpression.cs +++ b/Duplicati/Library/Utility/JoinedFilterExpression.cs @@ -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); } diff --git a/Duplicati/Library/Utility/Utility.cs b/Duplicati/Library/Utility/Utility.cs index 8abb6efe3..a3e259e80 100644 --- a/Duplicati/Library/Utility/Utility.cs +++ b/Duplicati/Library/Utility/Utility.cs @@ -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 diff --git a/Duplicati/Server/LogWriteHandler.cs b/Duplicati/Server/LogWriteHandler.cs index c79024010..640886f66 100644 --- a/Duplicati/Server/LogWriteHandler.cs +++ b/Duplicati/Server/LogWriteHandler.cs @@ -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(); } } diff --git a/Duplicati/Server/Runner.cs b/Duplicati/Server/Runner.cs index f317b4de9..56bb6abb0 100644 --- a/Duplicati/Server/Runner.cs +++ b/Duplicati/Server/Runner.cs @@ -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) diff --git a/Duplicati/Server/WebServer/RESTHandler.cs b/Duplicati/Server/WebServer/RESTHandler.cs index caf7d3058..c591977f7 100644 --- a/Duplicati/Server/WebServer/RESTHandler.cs +++ b/Duplicati/Server/WebServer/RESTHandler.cs @@ -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; diff --git a/Duplicati/Server/WebServer/RESTMethods/Help.cs b/Duplicati/Server/WebServer/RESTMethods/Help.cs index f940bedb7..87433390c 100644 --- a/Duplicati/Server/WebServer/RESTMethods/Help.cs +++ b/Duplicati/Server/WebServer/RESTMethods/Help.cs @@ -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 diff --git a/Duplicati/Server/WebServer/RESTMethods/RemoteOperation.cs b/Duplicati/Server/WebServer/RESTMethods/RemoteOperation.cs index c0f6449d4..6996683f6 100644 --- a/Duplicati/Server/WebServer/RESTMethods/RemoteOperation.cs +++ b/Duplicati/Server/WebServer/RESTMethods/RemoteOperation.cs @@ -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(); } }