Skip to content
This repository has been archived by the owner on Mar 9, 2021. It is now read-only.

Commit

Permalink
Code refactoring
Browse files Browse the repository at this point in the history
- Addresses C# inspections found by ReSharper.
  • Loading branch information
johanneszab committed Oct 7, 2018
1 parent 40d40ac commit 5970aca
Show file tree
Hide file tree
Showing 154 changed files with 1,815 additions and 1,792 deletions.
4 changes: 2 additions & 2 deletions src/TumblThree/SharedAssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@

[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.MainAssembly)]
[assembly: AssemblyVersion("1.0.7.63")]
[assembly: AssemblyFileVersion("1.0.7.63")]
[assembly: AssemblyVersion("1.0.7.64")]
[assembly: AssemblyFileVersion("1.0.7.64")]
6 changes: 4 additions & 2 deletions src/TumblThree/TumblThree.Applications/App.config
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml
version="1.0"
encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
Expand All @@ -11,4 +13,4 @@
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true" />
</system.net>
</configuration>
</configuration>
35 changes: 22 additions & 13 deletions src/TumblThree/TumblThree.Applications/Auth/OAuth.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace TumblThree.Applications.Auth
{
Expand Down Expand Up @@ -135,6 +138,7 @@ public string this[string ix]
{
return _params[ix];
}

throw new ArgumentException(ix);
}
set
Expand All @@ -143,6 +147,7 @@ public string this[string ix]
{
throw new ArgumentException(ix);
}

_params[ix] = value;
}
}
Expand Down Expand Up @@ -203,7 +208,7 @@ private void NewRequest()
/// <returns>the nonce</returns>
private string GenerateNonce()
{
var sb = new System.Text.StringBuilder();
var sb = new StringBuilder();
for (var i = 0; i < 8; i++)
{
int g = _random.Next(3);
Expand All @@ -219,6 +224,7 @@ private string GenerateNonce()
break;
}
}

return sb.ToString();
}

Expand Down Expand Up @@ -284,7 +290,7 @@ private Dictionary<string, string> ExtractQueryParameters(string queryString)
/// <returns>the Url-encoded version of that string</returns>
public static string UrlEncode(string value)
{
var result = new System.Text.StringBuilder();
var result = new StringBuilder();
foreach (char symbol in value)
{
if (unreservedChars.IndexOf(symbol) != -1)
Expand All @@ -296,6 +302,7 @@ public static string UrlEncode(string value)
result.Append('%' + string.Format("{0:X2}", (int)symbol));
}
}

return result.ToString();
}

Expand Down Expand Up @@ -323,7 +330,7 @@ public static string UrlEncode(string value)
/// <returns>a string representing the parameters</returns>
private static string EncodeRequestParameters(ICollection<KeyValuePair<string, string>> p)
{
var sb = new System.Text.StringBuilder();
var sb = new StringBuilder();
foreach (KeyValuePair<string, string> item in p.OrderBy(x => x.Key))
{
if (!string.IsNullOrEmpty(item.Value) &&
Expand Down Expand Up @@ -383,13 +390,13 @@ public OAuthResponse AcquireRequestToken(string uri, string method)
NewRequest();
string authHeader = GetAuthorizationHeader(uri, method);
// prepare the token request
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Add("Authorization", authHeader);
request.Method = method;

using (var response = (System.Net.HttpWebResponse)request.GetResponse())
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
using (var reader = new StreamReader(response.GetResponseStream()))
{
var r = new OAuthResponse(reader.ReadToEnd());
this["token"] = r["oauth_token"];
Expand All @@ -407,6 +414,7 @@ public OAuthResponse AcquireRequestToken(string uri, string method)
catch
{
}

return r;
}
}
Expand Down Expand Up @@ -454,13 +462,13 @@ public OAuthResponse AcquireAccessToken(string uri, string method, string pin)
string authHeader = GetAuthorizationHeader(uri, method);

// prepare the token request
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Add("Authorization", authHeader);
request.Method = method;

using (var response = (System.Net.HttpWebResponse)request.GetResponse())
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
using (var reader = new StreamReader(response.GetResponseStream()))
{
var r = new OAuthResponse(reader.ReadToEnd());
this["token"] = r["oauth_token"];
Expand Down Expand Up @@ -517,7 +525,7 @@ private void Sign(string uri, string method)
string signatureBase = GetSignatureBase(uri, method);
HashAlgorithm hash = GetHash();

byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(signatureBase);
byte[] dataBuffer = Encoding.ASCII.GetBytes(signatureBase);
byte[] hashBytes = hash.ComputeHash(dataBuffer);

this["signature"] = Convert.ToBase64String(hashBytes);
Expand All @@ -541,7 +549,7 @@ private string GetSignatureBase(string url, string method)
normUrl += uri.AbsolutePath;

// the sigbase starts with the method and the encoded URI
var sb = new System.Text.StringBuilder();
var sb = new StringBuilder();
sb.Append(method)
.Append('&')
.Append(UrlEncode(normUrl))
Expand All @@ -566,7 +574,7 @@ private string GetSignatureBase(string url, string method)
}

// concat+format all those params
var sb1 = new System.Text.StringBuilder();
var sb1 = new StringBuilder();
foreach (KeyValuePair<string, string> item in p.OrderBy(x => x.Key))
{
// even "empty" params need to be encoded this way.
Expand All @@ -591,7 +599,7 @@ private HashAlgorithm GetHash()
UrlEncode(this["token_secret"]));
var hmacsha1 = new HMACSHA1
{
Key = System.Text.Encoding.ASCII.GetBytes(keystring)
Key = Encoding.ASCII.GetBytes(keystring)
};
return hmacsha1;
}
Expand All @@ -614,6 +622,7 @@ public OAuthResponse(string alltext)
string[] kv = pair.Split('=');
_params.Add(kv[0], kv[1]);
}

// expected keys:
// oauth_token, oauth_token_secret, user_id, screen_name, etc
}
Expand Down
1 change: 1 addition & 0 deletions src/TumblThree/TumblThree.Applications/ClipboardMonitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ protected virtual void Dispose(bool disposing)
hwndSource.RemoveHook(WndProc);
hwndSource.Dispose();
}

// Free any unmanaged objects here.
//
disposed = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
using System.Threading;
using System.Threading.Tasks;
using System.Waf.Applications;

using TumblThree.Applications.Crawler;
using TumblThree.Applications.DataModels;
using TumblThree.Applications.Services;
using TumblThree.Applications.ViewModels;
using TumblThree.Domain.Models;
using TumblThree.Domain.Models.Blogs;
using TumblThree.Domain.Queue;

namespace TumblThree.Applications.Controllers
Expand Down Expand Up @@ -71,11 +72,13 @@ public void Shutdown()
{
stopCommand.Execute(null);
}

Task.WaitAll(runningTasks.ToArray());
}
catch (AggregateException)
{
}

foreach (IBlog blog in managerService.BlogFiles)
{
if (blog.Dirty)
Expand Down Expand Up @@ -156,9 +159,18 @@ private async Task Crawl()
runningTasks.Add(Task.Run(() => RunCrawlerTasks(cancellation.Token, pause.Token)));
}

try { await Task.WhenAll(runningTasks.ToArray()); }
catch { }
finally { crawlerCancellationToken.Dispose(); runningTasks.Clear(); }
try
{
await Task.WhenAll(runningTasks.ToArray());
}
catch
{
}
finally
{
crawlerCancellationToken.Dispose();
runningTasks.Clear();
}
}

private async Task RunCrawlerTasks(CancellationToken ct, PauseToken pt)
Expand All @@ -176,13 +188,13 @@ private async Task RunCrawlerTasks(CancellationToken ct, PauseToken pt)
}

Monitor.Enter(lockObject);
if (crawlerService.ActiveItems.Count() < QueueManager.Items.Count())
if (crawlerService.ActiveItems.Count < QueueManager.Items.Count)
{
IEnumerable<QueueListItem> queueList = QueueManager.Items.Except(crawlerService.ActiveItems);
QueueListItem nextQueueItem = queueList.First();
IBlog blog = nextQueueItem.Blog;

ICrawler crawler = crawlerFactory.GetCrawler(blog, ct, pt, new Progress<DownloadProgress>(), shellService, crawlerService, managerService);
ICrawler crawler = crawlerFactory.GetCrawler(blog, ct, pt, new Progress<DownloadProgress>());
crawler.IsBlogOnlineAsync().Wait(4000);

if (crawlerService.ActiveItems.Any(item => item.Blog.Name.Equals(nextQueueItem.Blog.Name)))
Expand Down Expand Up @@ -217,7 +229,7 @@ private async Task StartSiteSpecificDownloader(QueueListItem queueListItem, Canc
blog.Dirty = true;
ProgressThrottler<DownloadProgress> progress = SetupThrottledQueueListProgress(queueListItem);

ICrawler crawler = crawlerFactory.GetCrawler(blog, ct, pt, progress, shellService, crawlerService, managerService);
ICrawler crawler = crawlerFactory.GetCrawler(blog, ct, pt, progress);
await crawler.CrawlAsync();

if (ct.IsCancellationRequested)
Expand All @@ -235,10 +247,10 @@ private async Task StartSiteSpecificDownloader(QueueListItem queueListItem, Canc
}
}

private ProgressThrottler<DataModels.DownloadProgress> SetupThrottledQueueListProgress(QueueListItem queueListItem)
private ProgressThrottler<DownloadProgress> SetupThrottledQueueListProgress(QueueListItem queueListItem)
{
var progressHandler = new Progress<DataModels.DownloadProgress>(value => { queueListItem.Progress = value.Progress; });
return new ProgressThrottler<DataModels.DownloadProgress>(progressHandler, shellService.Settings.ProgessUpdateInterval);
var progressHandler = new Progress<DownloadProgress>(value => { queueListItem.Progress = value.Progress; });
return new ProgressThrottler<DownloadProgress>(progressHandler, shellService.Settings.ProgessUpdateInterval);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
using System.ComponentModel.Composition;
using System.Linq;
using System.Reflection;

using TumblThree.Applications.Services;
using TumblThree.Applications.Views;
using TumblThree.Domain.Models;
using TumblThree.Domain.Models.Blogs;
using TumblThree.Domain.Queue;

namespace TumblThree.Applications.Controllers
Expand Down Expand Up @@ -44,6 +46,7 @@ public Lazy<IDetailsViewModel> GetViewModel(IBlog blog)
{
return viewModel;
}

throw new ArgumentException("Website is not supported!", "blogType");
}

Expand All @@ -55,14 +58,14 @@ public void SelectBlogFiles(IReadOnlyList<IBlog> blogFiles)

ClearBlogSelection();

if (blogFiles.Count() <= 1)
if (blogFiles.Count <= 1)
{
DetailsViewModel.Count = 1;
DetailsViewModel.BlogFile = blogFiles.FirstOrDefault();
}
else
{
DetailsViewModel.Count = blogFiles.Count();
DetailsViewModel.Count = blogFiles.Count;
DetailsViewModel.BlogFile = CreateFromMultiple(blogFiles.ToArray());
DetailsViewModel.BlogFile.PropertyChanged += ChangeBlogSettings;
}
Expand All @@ -72,14 +75,9 @@ private void UpdateViewModelBasedOnSelection(IReadOnlyList<IBlog> blogFiles)
{
if (blogFiles.Count == 0)
return;
if (blogFiles.Select(blog => blog.GetType()).Distinct().Count() < 2)
{
detailsViewModel = GetViewModel(blogFiles.FirstOrDefault());
}
else
{
detailsViewModel = GetViewModel(new Blog());
}
detailsViewModel = GetViewModel(blogFiles.Select(blog => blog.GetType()).Distinct().Count() < 2
? blogFiles.FirstOrDefault()
: new Blog());
shellService.DetailsView = DetailsViewModel.View;
shellService.UpdateDetailsView();
}
Expand All @@ -106,12 +104,12 @@ public void Shutdown()

public IBlog CreateFromMultiple(IEnumerable<IBlog> blogFiles)
{
if (!blogFiles.Any())
List<IBlog> sharedBlogFiles = blogFiles.ToList();
if (!sharedBlogFiles.Any())
{
throw new ArgumentException("The collection must have at least one item.", nameof(blogFiles));
}

IBlog[] sharedBlogFiles = blogFiles.ToArray();
foreach (IBlog blog in sharedBlogFiles)
{
blogsToSave.Add(blog);
Expand Down Expand Up @@ -195,14 +193,10 @@ private static T SetProperty<T>(IReadOnlyCollection<IBlog> blogs, string propert
{
PropertyInfo property = typeof(IBlog).GetProperty(propertyName);
var value = (T)property.GetValue(blogs.FirstOrDefault());
if (value != null)
{
bool equal = blogs.All(blog => property.GetValue(blog)?.Equals(value) ?? false);
if (equal)
return value;
if (value == null)
return default(T);
}
return default(T);
bool equal = blogs.All(blog => property.GetValue(blog)?.Equals(value) ?? false);
return equal ? value : default(T);
}

private static bool SetCheckBox(IReadOnlyCollection<IBlog> blogs, string propertyName)
Expand Down Expand Up @@ -232,6 +226,7 @@ private void SelectedBlogFilesCollectionChanged(object sender, NotifyCollectionC
{
DetailsViewModel.BlogFile.PropertyChanged -= ChangeBlogSettings;
}

SelectBlogFiles(selectionService.SelectedBlogFiles.ToArray());
}
}
Expand Down
Loading

0 comments on commit 5970aca

Please sign in to comment.