Skip to content

Commit

Permalink
Merge pull request #28 from cubrr/refactoring
Browse files Browse the repository at this point in the history
Refactoring bulk string concats, Statistics class and EasyImgur.StatisticsMetrics
  • Loading branch information
bkeiren committed Jun 10, 2015
2 parents e254be3 + 70c9478 commit d6a3de3
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 47 deletions.
24 changes: 17 additions & 7 deletions EasyImgur/Form1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -733,17 +733,27 @@ private void buttonForceTokenRefresh_Click(object sender, EventArgs e)

private void buttonFormatHelp_Click(object sender, EventArgs e)
{
FormattingHelper.FormattingScheme[] formattingSchemes = FormattingHelper.GetSchemes();
string helpString = "You can use strings consisting of either static characters or the following dynamic symbols, or a combination of both:\n\n";
foreach (FormattingHelper.FormattingScheme scheme in formattingSchemes)
var sb = new StringBuilder(
"You can use strings consisting of either static characters or " +
"the following dynamic symbols, or a combination of both:\n\n");
foreach (FormattingHelper.FormattingScheme scheme in FormattingHelper.GetSchemes())
{
helpString += scheme.symbol + " : " + scheme.description + "\n";
sb.Append(scheme.symbol);
sb.Append(" : ");
sb.Append(scheme.description);
sb.Append('\n');
}
string exampleFormattedString = "Image_%date%_%time%";
helpString += "\n\nEx.: '" + exampleFormattedString + "' would become: '" + FormattingHelper.Format(exampleFormattedString, null);

const string exampleFormattedString = "Image_%date%_%time%";

sb.Append("\n\nEx.: '");
sb.Append(exampleFormattedString);
sb.Append("' would become: '");
sb.Append(FormattingHelper.Format(exampleFormattedString, null));

Point loc = this.Location;
loc.Offset(buttonFormatHelp.Location.X, buttonFormatHelp.Location.Y);
Help.ShowPopup(this, helpString, loc);
Help.ShowPopup(this, sb.ToString(), loc);
}

private void buttonForgetTokens_Click(object sender, EventArgs e)
Expand Down
32 changes: 18 additions & 14 deletions EasyImgur/Statistics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@

namespace EasyImgur
{
class Statistics
static class Statistics
{
private static Dictionary<String, StatisticsMetric> m_StatisticsMetrics = new Dictionary<String, StatisticsMetric>()
private const string m_StatisticsServerUrl = "http://bryankeiren.com/easyimgur/stats.php";
private static readonly Dictionary<String, StatisticsMetric> m_StatisticsMetrics = new Dictionary<String, StatisticsMetric>()
{
{"authorized", new MetricAuthorized()} // Whether the user has authorized EasyImgur.
,{"histsize", new MetricHistorySize()} // The size of the history list.
Expand All @@ -29,10 +30,8 @@ public static bool GatherAndSend()

try
{
Statistics stats = new Statistics();

String metricsString = String.Empty;
using (WebClient wc = new WebClient())
var sb = new StringBuilder();
using (var wc = new WebClient())
{
try
{
Expand All @@ -44,7 +43,13 @@ public static bool GatherAndSend()
if (value != null)
{
values.Add(metric.Key, value.ToString());
metricsString += "\r\n\t" + c.ToString() + "\t{" + metric.Key + ": " + value.ToString() + "}";
sb.Append("\r\n\t");
sb.Append(c);
sb.Append("\t{");
sb.Append(metric.Key);
sb.Append(": ");
sb.Append(value);
sb.Append('}');
++c;
}
else
Expand All @@ -53,26 +58,25 @@ public static bool GatherAndSend()
}
}

Log.Info("Uploading the following metrics to the server: " + metricsString);
Log.Info("Uploading the following metrics to the server: " + sb);

#if !DEBUG
String url = "http://bryankeiren.com/easyimgur/stats.php";
byte[] response = wc.UploadValues(url, "POST", values);
wc.UploadValues(m_StatisticsServerUrl, "POST", values);
//Log.Info("Response from stats server: \r\n" + Encoding.ASCII.GetString(response));
#else
Log.Info("Upload to server was not performed due to the application being a debug build.");
#endif
}
catch (System.Net.WebException ex)
catch (WebException ex)
{
HttpWebResponse response = (System.Net.HttpWebResponse)ex.Response;
Log.Error("Something went wrong while trying to upload statistics data.\r\n\tStatus code: " + response.StatusCode.ToString() + "\r\n\tException: " + ex.ToString());
var response = (HttpWebResponse)ex.Response;
Log.Error("Something went wrong while trying to upload statistics data.\r\n\tStatus code: " + response.StatusCode + "\r\n\tException: " + ex);
success = false;
}

if (success)
{
Log.Info("Successfully uploaded data of " + m_StatisticsMetrics.Count.ToString() + " metrics to the server.");
Log.Info("Successfully uploaded data of " + m_StatisticsMetrics.Count + " metrics to the server.");
}
}
}
Expand Down
58 changes: 32 additions & 26 deletions EasyImgur/StatisticsMetrics/Metrics.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;

namespace EasyImgur.StatisticsMetrics
{
class MetricHistorySize : StatisticsMetric
class MetricHistorySize : StatisticsMetric
{
protected override Object Gather()
{
return History.count;
}
}

class MetricHistoryAnonymousUploads : StatisticsMetric
class MetricHistoryAnonymousUploads : StatisticsMetric
{
protected override Object Gather()
{
Expand All @@ -33,39 +37,39 @@ class MetricOperatingSystem : StatisticsMetric
{
protected override Object Gather()
{
return System.Environment.OSVersion;
return Environment.OSVersion;
}
}

class MetricCLRVersion : StatisticsMetric
{
protected override Object Gather()
{
return System.Environment.Version;
return Environment.Version;
}
}

class MetricLanguageFull : StatisticsMetric
{
protected override Object Gather()
{
return System.Globalization.CultureInfo.CurrentUICulture.EnglishName;
return CultureInfo.CurrentUICulture.EnglishName;
}
}

class MetricLanguageISO : StatisticsMetric
{
protected override Object Gather()
{
return System.Globalization.CultureInfo.CurrentUICulture.ThreeLetterISOLanguageName;
return CultureInfo.CurrentUICulture.ThreeLetterISOLanguageName;
}
}

class MetricPortableMode : StatisticsMetric
{
protected override Object Gather()
{
return EasyImgur.Program.InPortableMode;
return Program.InPortableMode;
}
}

Expand All @@ -84,15 +88,14 @@ protected override Object Gather()
}

// Code obtained from http://www.codeproject.com/Articles/34309/Convert-String-to-64bit-Integer (Accessed 13-03-2015 @ 23:25).
private Int64 GetInt64HashCode(string strText)
private static Int64 GetInt64HashCode(string strText)
{
Int64 hashCode = 0;
if (!string.IsNullOrEmpty(strText))
{
//Unicode Encode Covering all characterset
byte[] byteContents = Encoding.Unicode.GetBytes(strText);
System.Security.Cryptography.SHA256 hash =
new System.Security.Cryptography.SHA256CryptoServiceProvider();
SHA256 hash = new SHA256CryptoServiceProvider();
byte[] hashText = hash.ComputeHash(byteContents);
//32Byte hashText separate
//hashCodeStart = 0~7 8Byte
Expand All @@ -104,22 +107,22 @@ private Int64 GetInt64HashCode(string strText)
Int64 hashCodeEnd = BitConverter.ToInt64(hashText, 24);
hashCode = hashCodeStart ^ hashCodeMedium ^ hashCodeEnd;
}
return (hashCode);
return hashCode;
}

private string GetUserNameString()
{
return System.Environment.UserName;
return Environment.UserName;
}

private string GetNICString()
{
// Use the physical address (MAC) of the first network interface that has a non-null MAC address.
System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
foreach (System.Net.NetworkInformation.NetworkInterface nic in nics)
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in nics)
{
System.Net.NetworkInformation.PhysicalAddress mac = nic.GetPhysicalAddress();
if (mac != System.Net.NetworkInformation.PhysicalAddress.None)
PhysicalAddress mac = nic.GetPhysicalAddress();
if (!mac.Equals(PhysicalAddress.None))
return mac.ToString();
}

Expand All @@ -141,26 +144,29 @@ private string GetHardDriveSerialNumberString()
return GetPropertiesOfWMIObjects("Win32_PhysicalMedia", "SerialNumber");
}

private string GetPropertiesOfWMIObjects(string _QueryTarget, string _PropertyName)
private string GetPropertiesOfWMIObjects(string queryTarget, string propertyName)
{
try
{
System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM " + _QueryTarget);
var sb = new StringBuilder();

string propertystring = string.Empty;
foreach (System.Management.ManagementObject wmi_object in searcher.Get())
using (var searcher = new ManagementObjectSearcher("SELECT * FROM " + queryTarget))
using (ManagementObjectCollection wmiCollection = searcher.Get())
{
Object property = wmi_object[_PropertyName];
if (property != null)
propertystring += property.ToString();
foreach (ManagementBaseObject wmiObject in wmiCollection)
{
Object property = wmiObject[propertyName];
if (property != null)
sb.Append(property);
}
}

return propertystring;
return sb.ToString();
}
catch (System.Exception ex)
catch (Exception ex)
{
// Do nothing except log.
Log.Error("An exception occurred while trying to obtain some WMI object properties: " + ex.Message);
Log.Error("An exception occurred while trying to obtain some WMI object properties: " + ex);
}

return string.Empty;
Expand Down

0 comments on commit d6a3de3

Please sign in to comment.