mirror of
https://github.com/Radarr/Radarr.git
synced 2024-08-17 07:49:45 +02:00
New: Enable Sentry Analytics (#3669)
This commit is contained in:
parent
64ec751938
commit
71c398f0fc
@ -60,33 +60,35 @@ function createMiddleware() {
|
||||
|
||||
export default function createSentryMiddleware() {
|
||||
const {
|
||||
// analytics,
|
||||
analytics,
|
||||
branch,
|
||||
version,
|
||||
release,
|
||||
userHash,
|
||||
isProduction
|
||||
} = window.Radarr;
|
||||
|
||||
// TODO update with Radarr Sentry dsn if used.
|
||||
// if (!analytics) {
|
||||
if (true) {
|
||||
console.log(window.Radarr);
|
||||
|
||||
if (!analytics) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dsn = isProduction ? 'https://b80ca60625b443c38b242e0d21681eb7@sentry.sonarr.tv/13' :
|
||||
'https://8dbaacdfe2ff4caf97dc7945aecf9ace@sentry.sonarr.tv/12';
|
||||
const dsn = isProduction ? 'https://cf0559cfe5c84ccfae3d907daef1b6bb@sentry.io/1523530' :
|
||||
'https://df167d10dc51480b9e4f22e4e77c7315@sentry.io/1523531';
|
||||
|
||||
sentry.init({
|
||||
dsn,
|
||||
environment: isProduction ? 'production' : 'development',
|
||||
environment: branch,
|
||||
release,
|
||||
sendDefaultPii: true,
|
||||
beforeSend: cleanseData
|
||||
});
|
||||
|
||||
sentry.configureScope((scope) => {
|
||||
scope.setTag('branch', branch);
|
||||
scope.setUser({ username: userHash });
|
||||
scope.setTag('version', version);
|
||||
scope.setTag('production', isProduction);
|
||||
});
|
||||
|
||||
return createMiddleware();
|
||||
|
@ -1,648 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Configuration;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
|
||||
namespace LogentriesCore
|
||||
{
|
||||
public class AsyncLogger
|
||||
{
|
||||
#region Constants
|
||||
|
||||
// Current version number.
|
||||
protected const String Version = "2.6.0";
|
||||
|
||||
// Size of the internal event queue.
|
||||
protected const int QueueSize = 32768;
|
||||
|
||||
// Minimal delay between attempts to reconnect in milliseconds.
|
||||
protected const int MinDelay = 100;
|
||||
|
||||
// Maximal delay between attempts to reconnect in milliseconds.
|
||||
protected const int MaxDelay = 10000;
|
||||
|
||||
// Appender signature - used for debugging messages.
|
||||
protected const String LeSignature = "LE: ";
|
||||
|
||||
// Legacy Logentries configuration names.
|
||||
protected const String LegacyConfigTokenName = "LOGENTRIES_TOKEN";
|
||||
protected const String LegacyConfigAccountKeyName = "LOGENTRIES_ACCOUNT_KEY";
|
||||
protected const String LegacyConfigLocationName = "LOGENTRIES_LOCATION";
|
||||
|
||||
// New Logentries configuration names.
|
||||
protected const String ConfigTokenName = "Logentries.Token";
|
||||
protected const String ConfigAccountKeyName = "Logentries.AccountKey";
|
||||
protected const String ConfigLocationName = "Logentries.Location";
|
||||
|
||||
// Error message displayed when invalid token is detected.
|
||||
protected const String InvalidTokenMessage = "\n\nIt appears your LOGENTRIES_TOKEN value is invalid or missing.\n\n";
|
||||
|
||||
// Error message displayed when invalid account_key or location parameters are detected.
|
||||
protected const String InvalidHttpPutCredentialsMessage = "\n\nIt appears your LOGENTRIES_ACCOUNT_KEY or LOGENTRIES_LOCATION values are invalid or missing.\n\n";
|
||||
|
||||
// Error message deisplayed when queue overflow occurs.
|
||||
protected const String QueueOverflowMessage = "\n\nLogentries buffer queue overflow. Message dropped.\n\n";
|
||||
|
||||
// Newline char to trim from message for formatting.
|
||||
protected static char[] TrimChars = { '\r', '\n' };
|
||||
|
||||
/** Non-Unix and Unix Newline */
|
||||
protected static string[] posix_newline = { "\r\n", "\n" };
|
||||
|
||||
/** Unicode line separator character */
|
||||
protected static string line_separator = "\u2028";
|
||||
|
||||
// Restricted symbols that should not appear in host name.
|
||||
// See http://support.microsoft.com/kb/228275/en-us for details.
|
||||
private static Regex ForbiddenHostNameChars = new Regex(@"[/\\\[\]\""\:\;\|\<\>\+\=\,\?\* _]{1,}", RegexOptions.Compiled);
|
||||
|
||||
/** Regex used to validate GUID in .NET3.5 */
|
||||
private static Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Singletons
|
||||
|
||||
// UTF-8 output character set.
|
||||
protected static readonly UTF8Encoding UTF8 = new UTF8Encoding();
|
||||
|
||||
// ASCII character set used by HTTP.
|
||||
protected static readonly ASCIIEncoding ASCII = new ASCIIEncoding();
|
||||
|
||||
//static list of all the queues the le appender might be managing.
|
||||
private static ConcurrentBag<BlockingCollection<string>> _allQueues = new ConcurrentBag<BlockingCollection<string>>();
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the queue is empty after waiting the specified waitTime.
|
||||
/// Returns true or false if the underlying queues are empty.
|
||||
/// </summary>
|
||||
/// <param name="waitTime">The length of time the method should block before giving up waiting for it to empty.</param>
|
||||
/// <returns>True if the queue is empty, false if there are still items waiting to be written.</returns>
|
||||
public static bool AreAllQueuesEmpty(TimeSpan waitTime)
|
||||
{
|
||||
var start = DateTime.UtcNow;
|
||||
var then = DateTime.UtcNow;
|
||||
|
||||
while (start.Add(waitTime) > then)
|
||||
{
|
||||
if (_allQueues.All(x => x.Count == 0))
|
||||
return true;
|
||||
|
||||
Thread.Sleep(100);
|
||||
then = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
return _allQueues.All(x => x.Count == 0);
|
||||
}
|
||||
#endregion
|
||||
|
||||
public AsyncLogger()
|
||||
{
|
||||
Queue = new BlockingCollection<string>(QueueSize);
|
||||
_allQueues.Add(Queue);
|
||||
|
||||
WorkerThread = new Thread(Run);
|
||||
WorkerThread.Name = "Logentries Log4net Appender";
|
||||
WorkerThread.IsBackground = true;
|
||||
}
|
||||
|
||||
#region Configuration properties
|
||||
|
||||
private String m_Token = "";
|
||||
private String m_AccountKey = "";
|
||||
private String m_Location = "";
|
||||
private bool m_ImmediateFlush = false;
|
||||
private bool m_Debug = false;
|
||||
private bool m_UseHttpPut = false;
|
||||
private bool m_UseSsl = false;
|
||||
|
||||
// Properties for defining location of DataHub instance if one is used.
|
||||
private bool m_UseDataHub = false; // By default Logentries service is used instead of DataHub instance.
|
||||
private String m_DataHubAddr = "";
|
||||
private int m_DataHubPort = 0;
|
||||
|
||||
// Properties to define host name of user's machine and define user-specified log ID.
|
||||
private bool m_UseHostName = false; // Defines whether to prefix log message with HostName or not.
|
||||
private String m_HostName = ""; // User-defined or auto-defined host name (if not set in config. file)
|
||||
private String m_LogID = ""; // User-defined log ID to be prefixed to the log message.
|
||||
|
||||
// Sets DataHub usage flag.
|
||||
public void setIsUsingDataHub(bool useDataHub)
|
||||
{
|
||||
m_UseDataHub = useDataHub;
|
||||
}
|
||||
|
||||
public bool getIsUsingDataHab()
|
||||
{
|
||||
return m_UseDataHub;
|
||||
}
|
||||
|
||||
// Sets DataHub instance address.
|
||||
public void setDataHubAddr(String dataHubAddr)
|
||||
{
|
||||
m_DataHubAddr = dataHubAddr;
|
||||
}
|
||||
|
||||
public String getDataHubAddr()
|
||||
{
|
||||
return m_DataHubAddr;
|
||||
}
|
||||
|
||||
// Sets the port on which DataHub instance is waiting for log messages.
|
||||
public void setDataHubPort(int port)
|
||||
{
|
||||
m_DataHubPort = port;
|
||||
}
|
||||
|
||||
public int getDataHubPort()
|
||||
{
|
||||
return m_DataHubPort;
|
||||
}
|
||||
|
||||
public void setToken(String token)
|
||||
{
|
||||
m_Token = token;
|
||||
}
|
||||
|
||||
public String getToken()
|
||||
{
|
||||
return m_Token;
|
||||
}
|
||||
|
||||
public void setAccountKey(String accountKey)
|
||||
{
|
||||
m_AccountKey = accountKey;
|
||||
}
|
||||
|
||||
public string getAccountKey()
|
||||
{
|
||||
return m_AccountKey;
|
||||
}
|
||||
|
||||
public void setLocation(String location)
|
||||
{
|
||||
m_Location = location;
|
||||
}
|
||||
|
||||
public String getLocation()
|
||||
{
|
||||
return m_Location;
|
||||
}
|
||||
|
||||
public void setImmediateFlush(bool immediateFlush)
|
||||
{
|
||||
m_ImmediateFlush = immediateFlush;
|
||||
}
|
||||
|
||||
public bool getImmediateFlush()
|
||||
{
|
||||
return m_ImmediateFlush;
|
||||
}
|
||||
|
||||
public void setDebug(bool debug)
|
||||
{
|
||||
m_Debug = debug;
|
||||
}
|
||||
|
||||
public bool getDebug()
|
||||
{
|
||||
return m_Debug;
|
||||
}
|
||||
|
||||
public void setUseHttpPut(bool useHttpPut)
|
||||
{
|
||||
m_UseHttpPut = useHttpPut;
|
||||
}
|
||||
|
||||
public bool getUseHttpPut()
|
||||
{
|
||||
return m_UseHttpPut;
|
||||
}
|
||||
|
||||
public void setUseSsl(bool useSsl)
|
||||
{
|
||||
m_UseSsl = useSsl;
|
||||
}
|
||||
|
||||
public bool getUseSsl()
|
||||
{
|
||||
return m_UseSsl;
|
||||
}
|
||||
|
||||
public void setUseHostName(bool useHostName)
|
||||
{
|
||||
m_UseHostName = useHostName;
|
||||
}
|
||||
|
||||
public bool getUseHostName()
|
||||
{
|
||||
return m_UseHostName;
|
||||
}
|
||||
|
||||
public void setHostName(String hostName)
|
||||
{
|
||||
m_HostName = hostName;
|
||||
}
|
||||
|
||||
public String getHostName()
|
||||
{
|
||||
return m_HostName;
|
||||
}
|
||||
|
||||
public void setLogID(String logID)
|
||||
{
|
||||
m_LogID = logID;
|
||||
}
|
||||
|
||||
public String getLogID()
|
||||
{
|
||||
return m_LogID;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
protected readonly BlockingCollection<string> Queue;
|
||||
protected readonly Thread WorkerThread;
|
||||
protected readonly Random Random = new Random();
|
||||
|
||||
private LeClient LeClient = null;
|
||||
protected bool IsRunning = false;
|
||||
|
||||
#region Protected methods
|
||||
|
||||
protected virtual void Run()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Open connection.
|
||||
ReopenConnection();
|
||||
|
||||
string logMessagePrefix = String.Empty;
|
||||
|
||||
if (m_UseHostName)
|
||||
{
|
||||
// If LogHostName is set to "true", but HostName is not defined -
|
||||
// try to get host name from Environment.
|
||||
if (m_HostName == String.Empty)
|
||||
{
|
||||
try
|
||||
{
|
||||
WriteDebugMessages("HostName parameter is not defined - trying to get it from System.Environment.MachineName");
|
||||
m_HostName = "HostName=" + System.Environment.MachineName + " ";
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Cannot get host name automatically, so assume that HostName is not used
|
||||
// and log message is sent without it.
|
||||
m_UseHostName = false;
|
||||
WriteDebugMessages("Failed to get HostName parameter using System.Environment.MachineName. Log messages will not be prefixed by HostName");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!CheckIfHostNameValid(m_HostName))
|
||||
{
|
||||
// If user-defined host name is incorrect - we cannot use it
|
||||
// and log message is sent without it.
|
||||
m_UseHostName = false;
|
||||
WriteDebugMessages("HostName parameter contains prohibited characters. Log messages will not be prefixed by HostName");
|
||||
}
|
||||
else
|
||||
{
|
||||
m_HostName = "HostName=" + m_HostName + " ";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (m_LogID != String.Empty)
|
||||
{
|
||||
logMessagePrefix = m_LogID + " ";
|
||||
}
|
||||
|
||||
if (m_UseHostName)
|
||||
{
|
||||
logMessagePrefix += m_HostName;
|
||||
}
|
||||
|
||||
// Flag that is set if logMessagePrefix is empty.
|
||||
bool isPrefixEmpty = (logMessagePrefix == String.Empty);
|
||||
|
||||
// Send data in queue.
|
||||
while (true)
|
||||
{
|
||||
// Take data from queue.
|
||||
var line = Queue.Take();
|
||||
|
||||
// Replace newline chars with line separator to format multi-line events nicely.
|
||||
foreach (String newline in posix_newline)
|
||||
{
|
||||
line = line.Replace(newline, line_separator);
|
||||
}
|
||||
|
||||
// If m_UseDataHub == true (logs are sent to DataHub instance) then m_Token is not
|
||||
// appended to the message.
|
||||
string finalLine = ((!m_UseHttpPut && !m_UseDataHub) ? this.m_Token + line : line) + '\n';
|
||||
|
||||
// Add prefixes: LogID and HostName if they are defined.
|
||||
if (!isPrefixEmpty)
|
||||
{
|
||||
finalLine = logMessagePrefix + finalLine;
|
||||
}
|
||||
|
||||
byte[] data = UTF8.GetBytes(finalLine);
|
||||
|
||||
// Send data, reconnect if needed.
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
this.LeClient.Write(data, 0, data.Length);
|
||||
|
||||
if (m_ImmediateFlush)
|
||||
this.LeClient.Flush();
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Reopen the lost connection.
|
||||
ReopenConnection();
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (ThreadInterruptedException ex)
|
||||
{
|
||||
WriteDebugMessages("Logentries asynchronous socket client was interrupted.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void OpenConnection()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (LeClient == null)
|
||||
{
|
||||
// Create LeClient instance providing all needed parameters. If DataHub-related properties
|
||||
// have not been overridden by log4net or NLog configurators, then DataHub is not used,
|
||||
// because m_UseDataHub == false by default.
|
||||
LeClient = new LeClient(m_UseHttpPut, m_UseSsl, m_UseDataHub, m_DataHubAddr, m_DataHubPort);
|
||||
}
|
||||
|
||||
LeClient.Connect();
|
||||
|
||||
if (m_UseHttpPut)
|
||||
{
|
||||
var header = String.Format("PUT /{0}/hosts/{1}/?realtime=1 HTTP/1.1\r\n\r\n", m_AccountKey, m_Location);
|
||||
LeClient.Write(ASCII.GetBytes(header), 0, header.Length);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new IOException("An error occurred while opening the connection.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void ReopenConnection()
|
||||
{
|
||||
CloseConnection();
|
||||
|
||||
var rootDelay = MinDelay;
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
OpenConnection();
|
||||
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (m_Debug)
|
||||
{
|
||||
WriteDebugMessages("Unable to connect to Logentries API.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
rootDelay *= 2;
|
||||
if (rootDelay > MaxDelay)
|
||||
rootDelay = MaxDelay;
|
||||
|
||||
var waitFor = rootDelay + Random.Next(rootDelay);
|
||||
|
||||
try
|
||||
{
|
||||
Thread.Sleep(waitFor);
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw new ThreadInterruptedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void CloseConnection()
|
||||
{
|
||||
if (LeClient != null)
|
||||
LeClient.Close();
|
||||
}
|
||||
|
||||
public static bool IsNullOrWhiteSpace(String value)
|
||||
{
|
||||
if (value == null) return true;
|
||||
|
||||
for (int i = 0; i < value.Length; i++)
|
||||
{
|
||||
if (!Char.IsWhiteSpace(value[i])) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private string retrieveSetting(String name)
|
||||
{
|
||||
string value;
|
||||
|
||||
|
||||
value = ConfigurationManager.AppSettings[name];
|
||||
|
||||
if (IsNullOrWhiteSpace(value))
|
||||
{
|
||||
try
|
||||
{
|
||||
value = Environment.GetEnvironmentVariable(name);
|
||||
}
|
||||
catch (SecurityException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/*
|
||||
* Use CloudConfigurationManager with .NET4.0 and fallback to System.Configuration for previous frameworks.
|
||||
*
|
||||
* NOTE: This is not entirely clear with regards to the above comment, but this block of code uses a compiler directive NET4_0
|
||||
* which is not set by default anywhere, so most uses of this code will default back to the "pre-.Net4.0" code branch, even
|
||||
* if you are using .Net4.0 or .Net4.5.
|
||||
*
|
||||
* The second issue is that there are two appsetting keys for each setting - the "legacy" key, such as "LOGENTRIES_TOKEN"
|
||||
* and the "non-legacy" key, such as "Logentries.Token". Again, I'm not sure of the reasons behind this, so the code below checks
|
||||
* both the legacy and non-legacy keys, defaulting to the legacy keys if they are found.
|
||||
*
|
||||
* It probably should be investigated whether the fallback to ConfigurationManager is needed at all, as CloudConfigurationManager
|
||||
* will retrieve settings from appSettings in a non-Azure environment.
|
||||
*/
|
||||
protected virtual bool LoadCredentials()
|
||||
{
|
||||
if (!m_UseHttpPut)
|
||||
{
|
||||
if (GetIsValidGuid(m_Token))
|
||||
return true;
|
||||
|
||||
var configToken = retrieveSetting(LegacyConfigTokenName) ?? retrieveSetting(ConfigTokenName);
|
||||
|
||||
if (!String.IsNullOrEmpty(configToken) && GetIsValidGuid(configToken))
|
||||
{
|
||||
m_Token = configToken;
|
||||
return true;
|
||||
}
|
||||
|
||||
WriteDebugMessages(InvalidTokenMessage);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (m_AccountKey != "" && GetIsValidGuid(m_AccountKey) && m_Location != "")
|
||||
return true;
|
||||
|
||||
var configAccountKey = ConfigurationManager.AppSettings[LegacyConfigAccountKeyName] ?? ConfigurationManager.AppSettings[ConfigAccountKeyName];
|
||||
if (!String.IsNullOrEmpty(configAccountKey) && GetIsValidGuid(configAccountKey))
|
||||
{
|
||||
m_AccountKey = configAccountKey;
|
||||
|
||||
var configLocation = ConfigurationManager.AppSettings[LegacyConfigLocationName] ?? ConfigurationManager.AppSettings[ConfigLocationName];
|
||||
if (!String.IsNullOrEmpty(configLocation))
|
||||
{
|
||||
m_Location = configLocation;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
WriteDebugMessages(InvalidHttpPutCredentialsMessage);
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool CheckIfHostNameValid(String hostName)
|
||||
{
|
||||
return !ForbiddenHostNameChars.IsMatch(hostName); // Returns false if reg.ex. matches any of forbidden chars.
|
||||
}
|
||||
|
||||
static bool IsGuid(string candidate, out Guid output)
|
||||
{
|
||||
bool isValid = false;
|
||||
output = Guid.Empty;
|
||||
|
||||
if (isGuid.IsMatch(candidate))
|
||||
{
|
||||
output = new Guid(candidate);
|
||||
isValid = true;
|
||||
}
|
||||
return isValid;
|
||||
}
|
||||
|
||||
protected virtual bool GetIsValidGuid(string guidString)
|
||||
{
|
||||
if (String.IsNullOrEmpty(guidString))
|
||||
return false;
|
||||
|
||||
System.Guid newGuid = System.Guid.NewGuid();
|
||||
return IsGuid(guidString, out newGuid);
|
||||
}
|
||||
|
||||
protected virtual void WriteDebugMessages(string message, Exception ex)
|
||||
{
|
||||
if (!m_Debug)
|
||||
return;
|
||||
|
||||
message = LeSignature + message;
|
||||
string[] messages = { message, ex.ToString() };
|
||||
foreach (var msg in messages)
|
||||
{
|
||||
// Use below line instead when compiling with log4net1.2.10.
|
||||
//LogLog.Debug(msg);
|
||||
|
||||
//LogLog.Debug(typeof(LogentriesAppender), msg);
|
||||
|
||||
Debug.WriteLine(message);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void WriteDebugMessages(string message)
|
||||
{
|
||||
if (!m_Debug)
|
||||
return;
|
||||
|
||||
message = LeSignature + message;
|
||||
|
||||
// Use below line instead when compiling with log4net1.2.10.
|
||||
//LogLog.Debug(message);
|
||||
|
||||
//LogLog.Debug(typeof(LogentriesAppender), message);
|
||||
Debug.WriteLine(message);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region publicMethods
|
||||
|
||||
public virtual void AddLine(string line)
|
||||
{
|
||||
if (!IsRunning)
|
||||
{
|
||||
// We need to load user credentials only
|
||||
// if the configuration does not state that DataHub is used;
|
||||
// credentials needed only if logs are sent to LE service directly.
|
||||
bool credentialsLoaded = false;
|
||||
if(!m_UseDataHub)
|
||||
{
|
||||
credentialsLoaded = LoadCredentials();
|
||||
}
|
||||
|
||||
// If in DataHub mode credentials are ignored.
|
||||
if (credentialsLoaded || m_UseDataHub)
|
||||
{
|
||||
WriteDebugMessages("Starting Logentries asynchronous socket client.");
|
||||
WorkerThread.Start();
|
||||
IsRunning = true;
|
||||
}
|
||||
}
|
||||
|
||||
WriteDebugMessages("Queueing: " + line);
|
||||
|
||||
String trimmedEvent = line.TrimEnd(TrimChars);
|
||||
|
||||
// Try to append data to queue.
|
||||
if (!Queue.TryAdd(trimmedEvent))
|
||||
{
|
||||
Queue.Take();
|
||||
if (!Queue.TryAdd(trimmedEvent))
|
||||
WriteDebugMessages(QueueOverflowMessage);
|
||||
}
|
||||
}
|
||||
|
||||
public void interruptWorker()
|
||||
{
|
||||
WorkerThread.Interrupt();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
@ -1,103 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace LogentriesCore
|
||||
{
|
||||
class LeClient
|
||||
{
|
||||
// Logentries API server address.
|
||||
protected const String LeApiUrl = "api.logentries.com";
|
||||
|
||||
// Port number for token logging on Logentries API server.
|
||||
protected const int LeApiTokenPort = 10000;
|
||||
|
||||
// Port number for TLS encrypted token logging on Logentries API server
|
||||
protected const int LeApiTokenTlsPort = 20000;
|
||||
|
||||
// Port number for HTTP PUT logging on Logentries API server.
|
||||
protected const int LeApiHttpPort = 80;
|
||||
|
||||
// Port number for SSL HTTP PUT logging on Logentries API server.
|
||||
protected const int LeApiHttpsPort = 443;
|
||||
|
||||
// Creates LeClient instance. If do not define useServerUrl and/or useOverrideProt during call
|
||||
// LeClient will be configured to work with api.logentries.com server; otherwise - with
|
||||
// defined server on defined port.
|
||||
public LeClient(bool useHttpPut, bool useSsl, bool useDataHub, String serverAddr, int port)
|
||||
{
|
||||
|
||||
// Override port number and server address to send logs to DataHub instance.
|
||||
if (useDataHub)
|
||||
{
|
||||
m_UseSsl = false; // DataHub does not support receiving log messages over SSL for now.
|
||||
m_TcpPort = port;
|
||||
m_ServerAddr = serverAddr;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_UseSsl = useSsl;
|
||||
|
||||
if (!m_UseSsl)
|
||||
m_TcpPort = useHttpPut ? LeApiHttpPort : LeApiTokenPort;
|
||||
else
|
||||
m_TcpPort = useHttpPut ? LeApiHttpsPort : LeApiTokenTlsPort;
|
||||
}
|
||||
}
|
||||
|
||||
private bool m_UseSsl = false;
|
||||
private int m_TcpPort;
|
||||
private TcpClient m_Client = null;
|
||||
private Stream m_Stream = null;
|
||||
private SslStream m_SslStream = null;
|
||||
private String m_ServerAddr = LeApiUrl; // By default m_ServerAddr points to api.logentries.com if useDataHub is not set to true.
|
||||
|
||||
private Stream ActiveStream
|
||||
{
|
||||
get
|
||||
{
|
||||
return m_UseSsl ? m_SslStream : m_Stream;
|
||||
}
|
||||
}
|
||||
|
||||
public void Connect()
|
||||
{
|
||||
m_Client = new TcpClient(m_ServerAddr, m_TcpPort);
|
||||
m_Client.NoDelay = true;
|
||||
|
||||
m_Stream = m_Client.GetStream();
|
||||
|
||||
if (m_UseSsl)
|
||||
{
|
||||
m_SslStream = new SslStream(m_Stream);
|
||||
m_SslStream.AuthenticateAsClient(m_ServerAddr);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
ActiveStream.Write(buffer, offset, count);
|
||||
}
|
||||
|
||||
public void Flush()
|
||||
{
|
||||
ActiveStream.Flush();
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
if (m_Client != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_Client.Close();
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,83 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>8.0.30703</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{90D6E9FC-7B88-4E1B-B018-8FA742274558}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>LogentriesCore</RootNamespace>
|
||||
<AssemblyName>LogentriesCore</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
|
||||
<RestorePackages>true</RestorePackages>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x86\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
|
||||
<OutputPath>bin\x86\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.configuration" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="AsyncLogger.cs" />
|
||||
<Compile Include="LeClient.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>
|
||||
</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
@ -1,35 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("LogentriesCore")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("LogentriesCore")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2013")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("14055980-6937-4745-9449-dabf47c1d892")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("2.6.0.0")]
|
||||
[assembly: AssemblyFileVersion("2.6.0.0")]
|
@ -1,4 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Microsoft.WindowsAzure.ConfigurationManager" version="2.0.1.0" targetFramework="net40" />
|
||||
</packages>
|
@ -1,100 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>8.0.30703</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>LogentriesNLog</RootNamespace>
|
||||
<AssemblyName>LogentriesNLog</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
|
||||
<RestorePackages>true</RestorePackages>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x86\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
|
||||
<OutputPath>bin\x86\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NLog.4.5.0-rc06\lib\net40-client\NLog.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Configuration" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Runtime.Serialization" />
|
||||
<Reference Include="System.ServiceModel" />
|
||||
<Reference Include="System.Transactions" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="fastJSON\Getters.cs" />
|
||||
<Compile Include="fastJSON\JSON.cs" />
|
||||
<Compile Include="fastJSON\JsonParser.cs" />
|
||||
<Compile Include="fastJSON\JsonSerializer.cs" />
|
||||
<Compile Include="fastJSON\SafeDictionary.cs" />
|
||||
<Compile Include="LogentriesTarget.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LogentriesCore\LogentriesCore.csproj">
|
||||
<Project>{90D6E9FC-7B88-4E1B-B018-8FA742274558}</Project>
|
||||
<Name>LogentriesCore</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="fastJSON\license.txt" />
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent>
|
||||
</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
@ -1,150 +0,0 @@
|
||||
using System;
|
||||
using LogentriesCore;
|
||||
using LogentriesNLog.fastJSON;
|
||||
using NLog;
|
||||
using NLog.Targets;
|
||||
|
||||
namespace LogentriesNLog
|
||||
{
|
||||
[Target("Logentries")]
|
||||
public sealed class LogentriesTarget : TargetWithLayout
|
||||
{
|
||||
private AsyncLogger logentriesAsync;
|
||||
|
||||
public LogentriesTarget()
|
||||
{
|
||||
logentriesAsync = new AsyncLogger();
|
||||
logentriesAsync.setImmediateFlush(true);
|
||||
}
|
||||
|
||||
|
||||
/** Debug flag. */
|
||||
public bool Debug
|
||||
{
|
||||
get { return logentriesAsync.getDebug(); }
|
||||
set { logentriesAsync.setDebug(value); }
|
||||
}
|
||||
|
||||
/** Is using DataHub parameter flag. - ste to true if it is needed to send messages to DataHub instance. */
|
||||
public bool IsUsingDataHub
|
||||
{
|
||||
get { return logentriesAsync.getIsUsingDataHab(); }
|
||||
set { logentriesAsync.setIsUsingDataHub(value); }
|
||||
}
|
||||
|
||||
/** DataHub server address */
|
||||
public String DataHubAddr
|
||||
{
|
||||
get { return logentriesAsync.getDataHubAddr(); }
|
||||
set { logentriesAsync.setDataHubAddr(value); }
|
||||
}
|
||||
|
||||
/** DataHub server port */
|
||||
public int DataHubPort
|
||||
{
|
||||
get { return logentriesAsync.getDataHubPort(); }
|
||||
set { logentriesAsync.setDataHubPort(value); }
|
||||
}
|
||||
|
||||
/** Option to set Token programmatically or in Appender Definition */
|
||||
public string Token
|
||||
{
|
||||
get { return logentriesAsync.getToken(); }
|
||||
set { logentriesAsync.setToken(value); }
|
||||
}
|
||||
|
||||
/** HTTP PUT Flag */
|
||||
public bool HttpPut
|
||||
{
|
||||
get { return logentriesAsync.getUseHttpPut(); }
|
||||
set { logentriesAsync.setUseHttpPut(value); }
|
||||
}
|
||||
|
||||
/** SSL/TLS parameter flag */
|
||||
public bool Ssl
|
||||
{
|
||||
get { return logentriesAsync.getUseSsl(); }
|
||||
set { logentriesAsync.setUseSsl(value); }
|
||||
}
|
||||
|
||||
/** ACCOUNT_KEY parameter for HTTP PUT logging */
|
||||
public String Key
|
||||
{
|
||||
get { return logentriesAsync.getAccountKey(); }
|
||||
set { logentriesAsync.setAccountKey(value); }
|
||||
}
|
||||
|
||||
/** LOCATION parameter for HTTP PUT logging */
|
||||
public String Location
|
||||
{
|
||||
get { return logentriesAsync.getLocation(); }
|
||||
set { logentriesAsync.setLocation(value); }
|
||||
}
|
||||
|
||||
/* LogHostname - switch that defines whether add host name to the log message */
|
||||
public bool LogHostname
|
||||
{
|
||||
get { return logentriesAsync.getUseHostName(); }
|
||||
set { logentriesAsync.setUseHostName(value); }
|
||||
}
|
||||
|
||||
/* HostName - user-defined host name. If empty the library will try to obtain it automatically */
|
||||
public String HostName
|
||||
{
|
||||
get { return logentriesAsync.getHostName(); }
|
||||
set { logentriesAsync.setHostName(value); }
|
||||
}
|
||||
|
||||
/* User-defined log message ID */
|
||||
public String LogID
|
||||
{
|
||||
get { return logentriesAsync.getLogID(); }
|
||||
set { logentriesAsync.setLogID(value); }
|
||||
}
|
||||
|
||||
public bool KeepConnection { get; set; }
|
||||
|
||||
protected override void Write(LogEventInfo logEvent)
|
||||
{
|
||||
//Render message content
|
||||
var log = new Log
|
||||
{
|
||||
Level = logEvent.Level.ToString(),
|
||||
Logger = logEvent.LoggerName,
|
||||
Message = logEvent.FormattedMessage,
|
||||
Time = logEvent.TimeStamp,
|
||||
};
|
||||
|
||||
//NLog can pass null references of Exception
|
||||
if (logEvent.Exception != null)
|
||||
{
|
||||
log.Exception = logEvent.Exception.ToString();
|
||||
log.ExceptionType = logEvent.Exception.GetType().ToString();
|
||||
}
|
||||
|
||||
logentriesAsync.AddLine(JSON.Instance.ToJSON(log));
|
||||
}
|
||||
|
||||
protected override void CloseTarget()
|
||||
{
|
||||
base.CloseTarget();
|
||||
|
||||
logentriesAsync.interruptWorker();
|
||||
}
|
||||
}
|
||||
|
||||
public class Log
|
||||
{
|
||||
public string Message { get; set; }
|
||||
|
||||
public DateTime Time { get; set; }
|
||||
|
||||
public string Logger { get; set; }
|
||||
|
||||
public string Exception { get; set; }
|
||||
|
||||
public string ExceptionType { get; set; }
|
||||
|
||||
public String Level { get; set; }
|
||||
}
|
||||
}
|
@ -1,35 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("LogentriesNLog")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("LogentriesNLog")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2013")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("7e04ff2d-ea59-4b62-969d-72bd3e37c684")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("2.4.0.0")]
|
||||
[assembly: AssemblyFileVersion("2.4.0.0")]
|
@ -1,21 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LogentriesNLog.fastJSON
|
||||
{
|
||||
internal class Getters
|
||||
{
|
||||
public string Name;
|
||||
public JSON.GenericGetter Getter;
|
||||
public Type propertyType;
|
||||
}
|
||||
|
||||
internal class DatasetSchema
|
||||
{
|
||||
public List<string> Info { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
@ -1,821 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace LogentriesNLog.fastJSON
|
||||
{
|
||||
|
||||
internal class JSON
|
||||
{
|
||||
public readonly static JSON Instance = new JSON();
|
||||
|
||||
private JSON()
|
||||
{
|
||||
UseSerializerExtension = false;
|
||||
SerializeNullValues = false;
|
||||
UseOptimizedDatasetSchema = false;
|
||||
UsingGlobalTypes = false;
|
||||
UseUTCDateTime = true;
|
||||
}
|
||||
public bool UseOptimizedDatasetSchema = true;
|
||||
public bool UseFastGuid = true;
|
||||
public bool UseSerializerExtension = true;
|
||||
public bool IndentOutput = false;
|
||||
public bool SerializeNullValues = true;
|
||||
public bool UseUTCDateTime = false;
|
||||
public bool ShowReadOnlyProperties = false;
|
||||
public bool UsingGlobalTypes = true;
|
||||
|
||||
public string ToJSON(object obj)
|
||||
{
|
||||
return ToJSON(obj, UseSerializerExtension, UseFastGuid, UseOptimizedDatasetSchema, SerializeNullValues);
|
||||
}
|
||||
|
||||
|
||||
public string ToJSON(object obj,
|
||||
bool enableSerializerExtensions,
|
||||
bool enableFastGuid,
|
||||
bool enableOptimizedDatasetSchema,
|
||||
bool serializeNullValues)
|
||||
{
|
||||
return new JSONSerializer(enableOptimizedDatasetSchema, enableFastGuid, enableSerializerExtensions, serializeNullValues, IndentOutput).ConvertToJSON(obj);
|
||||
}
|
||||
|
||||
|
||||
public T ToObject<T>(string json)
|
||||
{
|
||||
return (T)ToObject(json, typeof(T));
|
||||
}
|
||||
|
||||
|
||||
public object ToObject(string json, Type type)
|
||||
{
|
||||
var ht = new JsonParser(json).Decode() as Dictionary<string, object>;
|
||||
if (ht == null) return null;
|
||||
return ParseDictionary(ht, null, type);
|
||||
}
|
||||
|
||||
#if CUSTOMTYPE
|
||||
internal SafeDictionary<Type, Serialize> _customSerializer = new SafeDictionary<Type, Serialize>();
|
||||
internal SafeDictionary<Type, Deserialize> _customDeserializer = new SafeDictionary<Type, Deserialize>();
|
||||
|
||||
public void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer)
|
||||
{
|
||||
if (type != null && serializer != null && deserializer != null)
|
||||
{
|
||||
_customSerializer.Add(type, serializer);
|
||||
_customDeserializer.Add(type, deserializer);
|
||||
// reset property cache
|
||||
_propertycache = new SafeDictionary<string, SafeDictionary<string, myPropInfo>>();
|
||||
}
|
||||
}
|
||||
|
||||
internal bool IsTypeRegistered(Type t)
|
||||
{
|
||||
Serialize s;
|
||||
return _customSerializer.TryGetValue(t, out s);
|
||||
}
|
||||
#endif
|
||||
|
||||
#region [ PROPERTY GET SET CACHE ]
|
||||
|
||||
readonly SafeDictionary<Type, string> _tyname = new SafeDictionary<Type, string>();
|
||||
internal string GetTypeAssemblyName(Type t)
|
||||
{
|
||||
string val = "";
|
||||
if (_tyname.TryGetValue(t, out val))
|
||||
return val;
|
||||
string s = t.AssemblyQualifiedName;
|
||||
_tyname.Add(t, s);
|
||||
return s;
|
||||
}
|
||||
|
||||
readonly SafeDictionary<string, Type> _typecache = new SafeDictionary<string, Type>();
|
||||
private Type GetTypeFromCache(string typename)
|
||||
{
|
||||
Type val = null;
|
||||
if (_typecache.TryGetValue(typename, out val))
|
||||
return val;
|
||||
Type t = Type.GetType(typename);
|
||||
_typecache.Add(typename, t);
|
||||
return t;
|
||||
}
|
||||
|
||||
readonly SafeDictionary<Type, CreateObject> _constrcache = new SafeDictionary<Type, CreateObject>();
|
||||
private delegate object CreateObject();
|
||||
private object FastCreateInstance(Type objtype)
|
||||
{
|
||||
try
|
||||
{
|
||||
CreateObject c = null;
|
||||
if (_constrcache.TryGetValue(objtype, out c))
|
||||
{
|
||||
return c();
|
||||
}
|
||||
DynamicMethod dynMethod = new DynamicMethod("_", objtype, null, true);
|
||||
ILGenerator ilGen = dynMethod.GetILGenerator();
|
||||
|
||||
ilGen.Emit(OpCodes.Newobj, objtype.GetConstructor(Type.EmptyTypes));
|
||||
ilGen.Emit(OpCodes.Ret);
|
||||
c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
|
||||
_constrcache.Add(objtype, c);
|
||||
return c();
|
||||
}
|
||||
catch (Exception exc)
|
||||
{
|
||||
throw new Exception(string.Format("Failed to fast create instance for type '{0}' from assemebly '{1}'",
|
||||
objtype.FullName, objtype.AssemblyQualifiedName), exc);
|
||||
}
|
||||
}
|
||||
|
||||
private struct myPropInfo
|
||||
{
|
||||
public bool filled;
|
||||
public Type pt;
|
||||
public Type bt;
|
||||
public Type changeType;
|
||||
public bool isDictionary;
|
||||
public bool isValueType;
|
||||
public bool isGenericType;
|
||||
public bool isArray;
|
||||
public bool isByteArray;
|
||||
public bool isGuid;
|
||||
#if !SILVERLIGHT
|
||||
public bool isDataSet;
|
||||
public bool isDataTable;
|
||||
public bool isHashtable;
|
||||
#endif
|
||||
public GenericSetter setter;
|
||||
public bool isEnum;
|
||||
public bool isDateTime;
|
||||
public Type[] GenericTypes;
|
||||
public bool isInt;
|
||||
public bool isLong;
|
||||
public bool isString;
|
||||
public bool isBool;
|
||||
public bool isClass;
|
||||
public GenericGetter getter;
|
||||
public bool isStringDictionary;
|
||||
public string Name;
|
||||
#if CUSTOMTYPE
|
||||
public bool isCustomType;
|
||||
#endif
|
||||
public bool CanWrite;
|
||||
}
|
||||
|
||||
readonly SafeDictionary<string, SafeDictionary<string, myPropInfo>> _propertycache = new SafeDictionary<string, SafeDictionary<string, myPropInfo>>();
|
||||
private SafeDictionary<string, myPropInfo> Getproperties(Type type, string typename)
|
||||
{
|
||||
SafeDictionary<string, myPropInfo> sd = null;
|
||||
if (_propertycache.TryGetValue(typename, out sd))
|
||||
{
|
||||
return sd;
|
||||
}
|
||||
sd = new SafeDictionary<string, myPropInfo>();
|
||||
var pr = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
|
||||
foreach (var p in pr)
|
||||
{
|
||||
myPropInfo d = CreateMyProp(p.PropertyType, p.Name);
|
||||
d.CanWrite = p.CanWrite;
|
||||
d.setter = CreateSetMethod(p);
|
||||
d.getter = CreateGetMethod(p);
|
||||
sd.Add(p.Name, d);
|
||||
}
|
||||
|
||||
_propertycache.Add(typename, sd);
|
||||
return sd;
|
||||
}
|
||||
|
||||
private myPropInfo CreateMyProp(Type t, string name)
|
||||
{
|
||||
myPropInfo d = new myPropInfo();
|
||||
d.filled = true;
|
||||
d.CanWrite = true;
|
||||
d.pt = t;
|
||||
d.Name = name;
|
||||
d.isDictionary = t.Name.Contains("Dictionary");
|
||||
if (d.isDictionary)
|
||||
d.GenericTypes = t.GetGenericArguments();
|
||||
d.isValueType = t.IsValueType;
|
||||
d.isGenericType = t.IsGenericType;
|
||||
d.isArray = t.IsArray;
|
||||
if (d.isArray)
|
||||
d.bt = t.GetElementType();
|
||||
if (d.isGenericType)
|
||||
d.bt = t.GetGenericArguments()[0];
|
||||
d.isByteArray = t == typeof(byte[]);
|
||||
d.isGuid = (t == typeof(Guid) || t == typeof(Guid?));
|
||||
#if !SILVERLIGHT
|
||||
d.isHashtable = t == typeof(Hashtable);
|
||||
d.isDataSet = t == typeof(DataSet);
|
||||
d.isDataTable = t == typeof(DataTable);
|
||||
#endif
|
||||
|
||||
d.changeType = GetChangeType(t);
|
||||
d.isEnum = t.IsEnum;
|
||||
d.isDateTime = t == typeof(DateTime) || t == typeof(DateTime?);
|
||||
d.isInt = t == typeof(int) || t == typeof(int?);
|
||||
d.isLong = t == typeof(long) || t == typeof(long?);
|
||||
d.isString = t == typeof(string);
|
||||
d.isBool = t == typeof(bool) || t == typeof(bool?);
|
||||
d.isClass = t.IsClass;
|
||||
|
||||
if (d.isDictionary && d.GenericTypes.Length > 0 && d.GenericTypes[0] == typeof(string))
|
||||
d.isStringDictionary = true;
|
||||
|
||||
#if CUSTOMTYPE
|
||||
if (IsTypeRegistered(t))
|
||||
d.isCustomType = true;
|
||||
#endif
|
||||
return d;
|
||||
}
|
||||
|
||||
private delegate void GenericSetter(object target, object value);
|
||||
|
||||
private static GenericSetter CreateSetMethod(PropertyInfo propertyInfo)
|
||||
{
|
||||
MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
|
||||
if (setMethod == null)
|
||||
return null;
|
||||
|
||||
var arguments = new Type[2];
|
||||
arguments[0] = arguments[1] = typeof(object);
|
||||
|
||||
DynamicMethod setter = new DynamicMethod("_", typeof(void), arguments, true);
|
||||
ILGenerator il = setter.GetILGenerator();
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
|
||||
if (propertyInfo.PropertyType.IsClass)
|
||||
il.Emit(OpCodes.Castclass, propertyInfo.PropertyType);
|
||||
else
|
||||
il.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
|
||||
|
||||
il.EmitCall(OpCodes.Callvirt, setMethod, null);
|
||||
il.Emit(OpCodes.Ret);
|
||||
|
||||
return (GenericSetter)setter.CreateDelegate(typeof(GenericSetter));
|
||||
}
|
||||
|
||||
internal delegate object GenericGetter(object obj);
|
||||
|
||||
|
||||
private GenericGetter CreateGetMethod(PropertyInfo propertyInfo)
|
||||
{
|
||||
MethodInfo getMethod = propertyInfo.GetGetMethod();
|
||||
if (getMethod == null)
|
||||
return null;
|
||||
|
||||
var arguments = new Type[1];
|
||||
arguments[0] = typeof(object);
|
||||
|
||||
DynamicMethod getter = new DynamicMethod("_", typeof(object), arguments, true);
|
||||
ILGenerator il = getter.GetILGenerator();
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
|
||||
il.EmitCall(OpCodes.Callvirt, getMethod, null);
|
||||
|
||||
if (!propertyInfo.PropertyType.IsClass)
|
||||
il.Emit(OpCodes.Box, propertyInfo.PropertyType);
|
||||
|
||||
il.Emit(OpCodes.Ret);
|
||||
|
||||
return (GenericGetter)getter.CreateDelegate(typeof(GenericGetter));
|
||||
}
|
||||
|
||||
readonly SafeDictionary<Type, List<Getters>> _getterscache = new SafeDictionary<Type, List<Getters>>();
|
||||
internal List<Getters> GetGetters(Type type)
|
||||
{
|
||||
List<Getters> val = null;
|
||||
if (_getterscache.TryGetValue(type, out val))
|
||||
return val;
|
||||
|
||||
var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
|
||||
var getters = new List<Getters>();
|
||||
foreach (var p in props)
|
||||
{
|
||||
if (!p.CanWrite && ShowReadOnlyProperties == false) continue;
|
||||
|
||||
var att = p.GetCustomAttributes(typeof(XmlIgnoreAttribute), false);
|
||||
if (att != null && att.Length > 0)
|
||||
continue;
|
||||
|
||||
GenericGetter g = CreateGetMethod(p);
|
||||
if (g != null)
|
||||
{
|
||||
Getters gg = new Getters();
|
||||
gg.Name = p.Name;
|
||||
gg.Getter = g;
|
||||
gg.propertyType = p.PropertyType;
|
||||
getters.Add(gg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
_getterscache.Add(type, getters);
|
||||
return getters;
|
||||
}
|
||||
|
||||
private object ChangeType(object value, Type conversionType)
|
||||
{
|
||||
if (conversionType == typeof(int))
|
||||
return (int)CreateLong((string)value);
|
||||
|
||||
if (conversionType == typeof(long))
|
||||
return CreateLong((string)value);
|
||||
|
||||
if (conversionType == typeof(string))
|
||||
return value;
|
||||
|
||||
if (conversionType == typeof(Guid))
|
||||
return CreateGuid((string)value);
|
||||
|
||||
if (conversionType.IsEnum)
|
||||
return CreateEnum(conversionType, (string)value);
|
||||
|
||||
return Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture);
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
private object ParseDictionary(Dictionary<string, object> d, Dictionary<string, object> globaltypes, Type type)
|
||||
{
|
||||
object tn = "";
|
||||
if (d.TryGetValue("$types", out tn))
|
||||
{
|
||||
UsingGlobalTypes = true;
|
||||
globaltypes = new Dictionary<string, object>();
|
||||
foreach (var kv in (Dictionary<string, object>)tn)
|
||||
{
|
||||
globaltypes.Add((string)kv.Value, kv.Key);
|
||||
}
|
||||
}
|
||||
|
||||
bool found = d.TryGetValue("$type", out tn);
|
||||
#if !SILVERLIGHT
|
||||
if (found == false && type == typeof(Object))
|
||||
{
|
||||
return CreateDataset(d, globaltypes);
|
||||
}
|
||||
#endif
|
||||
if (found)
|
||||
{
|
||||
if (UsingGlobalTypes)
|
||||
{
|
||||
object tname = "";
|
||||
if (globaltypes.TryGetValue((string)tn, out tname))
|
||||
tn = tname;
|
||||
}
|
||||
type = GetTypeFromCache((string)tn);
|
||||
}
|
||||
|
||||
if (type == null)
|
||||
throw new Exception("Cannot determine type");
|
||||
|
||||
string typename = type.FullName;
|
||||
object o = FastCreateInstance(type);
|
||||
var props = Getproperties(type, typename);
|
||||
foreach (var name in d.Keys)
|
||||
{
|
||||
if (name == "$map")
|
||||
{
|
||||
ProcessMap(o, props, (Dictionary<string, object>)d[name]);
|
||||
continue;
|
||||
}
|
||||
myPropInfo pi;
|
||||
if (props.TryGetValue(name, out pi) == false)
|
||||
continue;
|
||||
if (pi.filled)
|
||||
{
|
||||
object v = d[name];
|
||||
|
||||
if (v != null)
|
||||
{
|
||||
object oset = null;
|
||||
|
||||
if (pi.isInt)
|
||||
oset = (int)CreateLong((string)v);
|
||||
#if CUSTOMTYPE
|
||||
else if (pi.isCustomType)
|
||||
oset = CreateCustom((string)v, pi.pt);
|
||||
#endif
|
||||
else if (pi.isLong)
|
||||
oset = CreateLong((string)v);
|
||||
|
||||
else if (pi.isString)
|
||||
oset = v;
|
||||
|
||||
else if (pi.isBool)
|
||||
oset = (bool)v;
|
||||
|
||||
else if (pi.isGenericType && pi.isValueType == false && pi.isDictionary == false)
|
||||
#if SILVERLIGHT
|
||||
oset = CreateGenericList((List<object>)v, pi.pt, pi.bt, globaltypes);
|
||||
#else
|
||||
oset = CreateGenericList((ArrayList)v, pi.pt, pi.bt, globaltypes);
|
||||
#endif
|
||||
else if (pi.isByteArray)
|
||||
oset = Convert.FromBase64String((string)v);
|
||||
|
||||
else if (pi.isArray && pi.isValueType == false)
|
||||
#if SILVERLIGHT
|
||||
oset = CreateArray((List<object>)v, pi.pt, pi.bt, globaltypes);
|
||||
#else
|
||||
oset = CreateArray((ArrayList)v, pi.pt, pi.bt, globaltypes);
|
||||
#endif
|
||||
else if (pi.isGuid)
|
||||
oset = CreateGuid((string)v);
|
||||
#if !SILVERLIGHT
|
||||
else if (pi.isDataSet)
|
||||
oset = CreateDataset((Dictionary<string, object>)v, globaltypes);
|
||||
|
||||
else if (pi.isDataTable)
|
||||
oset = CreateDataTable((Dictionary<string, object>)v, globaltypes);
|
||||
#endif
|
||||
|
||||
else if (pi.isStringDictionary)
|
||||
oset = CreateStringKeyDictionary((Dictionary<string, object>)v, pi.pt, pi.GenericTypes, globaltypes);
|
||||
|
||||
#if !SILVERLIGHT
|
||||
else if (pi.isDictionary || pi.isHashtable)
|
||||
oset = CreateDictionary((ArrayList)v, pi.pt, pi.GenericTypes, globaltypes);
|
||||
#else
|
||||
else if (pi.isDictionary)
|
||||
oset = CreateDictionary((List<object>)v, pi.pt, pi.GenericTypes, globaltypes);
|
||||
#endif
|
||||
|
||||
else if (pi.isEnum)
|
||||
oset = CreateEnum(pi.pt, (string)v);
|
||||
|
||||
else if (pi.isDateTime)
|
||||
oset = CreateDateTime((string)v);
|
||||
|
||||
else if (pi.isClass && v is Dictionary<string, object>)
|
||||
oset = ParseDictionary((Dictionary<string, object>)v, globaltypes, pi.pt);
|
||||
|
||||
else if (pi.isValueType)
|
||||
oset = ChangeType(v, pi.changeType);
|
||||
|
||||
#if SILVERLIGHT
|
||||
else if (v is List<object>)
|
||||
oset = CreateArray((List<object>)v, pi.pt, typeof(object), globaltypes);
|
||||
#else
|
||||
else if (v is ArrayList)
|
||||
oset = CreateArray((ArrayList)v, pi.pt, typeof(object), globaltypes);
|
||||
#endif
|
||||
else
|
||||
oset = v;
|
||||
|
||||
if (pi.CanWrite)
|
||||
pi.setter(o, oset);
|
||||
}
|
||||
}
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
#if CUSTOMTYPE
|
||||
private object CreateCustom(string v, Type type)
|
||||
{
|
||||
Deserialize d;
|
||||
_customDeserializer.TryGetValue(type, out d);
|
||||
return d(v);
|
||||
}
|
||||
#endif
|
||||
|
||||
private void ProcessMap(object obj, SafeDictionary<string, myPropInfo> props, Dictionary<string, object> dic)
|
||||
{
|
||||
foreach (var kv in dic)
|
||||
{
|
||||
myPropInfo p = props[kv.Key];
|
||||
object o = p.getter(obj);
|
||||
Type t = Type.GetType((string)kv.Value);
|
||||
if (t == typeof(Guid))
|
||||
p.setter(obj, CreateGuid((string)o));
|
||||
}
|
||||
}
|
||||
|
||||
private long CreateLong(string s)
|
||||
{
|
||||
long num = 0;
|
||||
bool neg = false;
|
||||
foreach (var cc in s)
|
||||
{
|
||||
if (cc == '-')
|
||||
neg = true;
|
||||
else if (cc == '+')
|
||||
neg = false;
|
||||
else
|
||||
{
|
||||
num *= 10;
|
||||
num += (cc - '0');
|
||||
}
|
||||
}
|
||||
|
||||
return neg ? -num : num;
|
||||
}
|
||||
|
||||
private object CreateEnum(Type pt, string v)
|
||||
{
|
||||
// TODO : optimize create enum
|
||||
#if !SILVERLIGHT
|
||||
return Enum.Parse(pt, v);
|
||||
#else
|
||||
return Enum.Parse(pt, v, true);
|
||||
#endif
|
||||
}
|
||||
|
||||
private Guid CreateGuid(string s)
|
||||
{
|
||||
if (s.Length > 30)
|
||||
return new Guid(s);
|
||||
return new Guid(Convert.FromBase64String(s));
|
||||
}
|
||||
|
||||
private DateTime CreateDateTime(string value)
|
||||
{
|
||||
bool utc = false;
|
||||
// 0123456789012345678
|
||||
// datetime format = yyyy-MM-dd HH:mm:ss
|
||||
int year = (int)CreateLong(value.Substring(0, 4));
|
||||
int month = (int)CreateLong(value.Substring(5, 2));
|
||||
int day = (int)CreateLong(value.Substring(8, 2));
|
||||
int hour = (int)CreateLong(value.Substring(11, 2));
|
||||
int min = (int)CreateLong(value.Substring(14, 2));
|
||||
int sec = (int)CreateLong(value.Substring(17, 2));
|
||||
|
||||
if (value.EndsWith("Z"))
|
||||
utc = true;
|
||||
|
||||
if (UseUTCDateTime == false && utc == false)
|
||||
return new DateTime(year, month, day, hour, min, sec);
|
||||
return new DateTime(year, month, day, hour, min, sec, DateTimeKind.Utc).ToLocalTime();
|
||||
}
|
||||
|
||||
#if SILVERLIGHT
|
||||
private object CreateArray(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
Array col = Array.CreateInstance(bt, data.Count);
|
||||
// create an array of objects
|
||||
for (int i = 0; i < data.Count; i++)// each (object ob in data)
|
||||
{
|
||||
object ob = data[i];
|
||||
if (ob is IDictionary)
|
||||
col.SetValue(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt), i);
|
||||
else
|
||||
col.SetValue(ChangeType(ob, bt), i);
|
||||
}
|
||||
|
||||
return col;
|
||||
}
|
||||
#else
|
||||
private object CreateArray(ArrayList data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
ArrayList col = new ArrayList();
|
||||
// create an array of objects
|
||||
foreach (var ob in data)
|
||||
{
|
||||
if (ob is IDictionary)
|
||||
col.Add(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt));
|
||||
else
|
||||
col.Add(ChangeType(ob, bt));
|
||||
}
|
||||
return col.ToArray(bt);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#if SILVERLIGHT
|
||||
private object CreateGenericList(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
#else
|
||||
private object CreateGenericList(ArrayList data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
#endif
|
||||
{
|
||||
IList col = (IList)FastCreateInstance(pt);
|
||||
// create an array of objects
|
||||
foreach (var ob in data)
|
||||
{
|
||||
if (ob is IDictionary)
|
||||
col.Add(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt));
|
||||
#if SILVERLIGHT
|
||||
else if (ob is List<object>)
|
||||
col.Add(((List<object>)ob).ToArray());
|
||||
#else
|
||||
else if (ob is ArrayList)
|
||||
col.Add(((ArrayList)ob).ToArray());
|
||||
#endif
|
||||
else
|
||||
col.Add(ChangeType(ob, bt));
|
||||
}
|
||||
return col;
|
||||
}
|
||||
|
||||
private object CreateStringKeyDictionary(Dictionary<string, object> reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
var col = (IDictionary)FastCreateInstance(pt);
|
||||
Type t1 = null;
|
||||
Type t2 = null;
|
||||
if (types != null)
|
||||
{
|
||||
t1 = types[0];
|
||||
t2 = types[1];
|
||||
}
|
||||
|
||||
foreach (var values in reader)
|
||||
{
|
||||
var key = values.Key;//ChangeType(values.Key, t1);
|
||||
object val = null;
|
||||
if (values.Value is Dictionary<string, object>)
|
||||
val = ParseDictionary((Dictionary<string, object>)values.Value, globalTypes, t2);
|
||||
else
|
||||
val = ChangeType(values.Value, t2);
|
||||
col.Add(key, val);
|
||||
}
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
#if SILVERLIGHT
|
||||
private object CreateDictionary(List<object> reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
|
||||
#else
|
||||
private object CreateDictionary(ArrayList reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
|
||||
#endif
|
||||
{
|
||||
IDictionary col = (IDictionary)FastCreateInstance(pt);
|
||||
Type t1 = null;
|
||||
Type t2 = null;
|
||||
if (types != null)
|
||||
{
|
||||
t1 = types[0];
|
||||
t2 = types[1];
|
||||
}
|
||||
|
||||
foreach (Dictionary<string, object> values in reader)
|
||||
{
|
||||
object key = values["k"];
|
||||
object val = values["v"];
|
||||
|
||||
if (key is Dictionary<string, object>)
|
||||
key = ParseDictionary((Dictionary<string, object>)key, globalTypes, t1);
|
||||
else
|
||||
key = ChangeType(key, t1);
|
||||
|
||||
if (val is Dictionary<string, object>)
|
||||
val = ParseDictionary((Dictionary<string, object>)val, globalTypes, t2);
|
||||
else
|
||||
val = ChangeType(val, t2);
|
||||
|
||||
col.Add(key, val);
|
||||
}
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
private Type GetChangeType(Type conversionType)
|
||||
{
|
||||
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
|
||||
return conversionType.GetGenericArguments()[0];
|
||||
|
||||
return conversionType;
|
||||
}
|
||||
#if !SILVERLIGHT
|
||||
private DataSet CreateDataset(Dictionary<string, object> reader, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
DataSet ds = new DataSet();
|
||||
ds.EnforceConstraints = false;
|
||||
ds.BeginInit();
|
||||
|
||||
// read dataset schema here
|
||||
ReadSchema(reader, ds, globalTypes);
|
||||
|
||||
foreach (var pair in reader)
|
||||
{
|
||||
if (pair.Key == "$type" || pair.Key == "$schema") continue;
|
||||
|
||||
ArrayList rows = (ArrayList)pair.Value;
|
||||
if (rows == null) continue;
|
||||
|
||||
DataTable dt = ds.Tables[pair.Key];
|
||||
ReadDataTable(rows, dt);
|
||||
}
|
||||
|
||||
ds.EndInit();
|
||||
|
||||
return ds;
|
||||
}
|
||||
|
||||
private void ReadSchema(Dictionary<string, object> reader, DataSet ds, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
var schema = reader["$schema"];
|
||||
|
||||
if (schema is string)
|
||||
{
|
||||
TextReader tr = new StringReader((string)schema);
|
||||
ds.ReadXmlSchema(tr);
|
||||
}
|
||||
else
|
||||
{
|
||||
DatasetSchema ms = (DatasetSchema)ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema));
|
||||
ds.DataSetName = ms.Name;
|
||||
for (int i = 0; i < ms.Info.Count; i += 3)
|
||||
{
|
||||
if (ds.Tables.Contains(ms.Info[i]) == false)
|
||||
ds.Tables.Add(ms.Info[i]);
|
||||
ds.Tables[ms.Info[i]].Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ReadDataTable(ArrayList rows, DataTable dt)
|
||||
{
|
||||
dt.BeginInit();
|
||||
dt.BeginLoadData();
|
||||
var guidcols = new List<int>();
|
||||
var datecol = new List<int>();
|
||||
|
||||
foreach (DataColumn c in dt.Columns)
|
||||
{
|
||||
if (c.DataType == typeof(Guid) || c.DataType == typeof(Guid?))
|
||||
guidcols.Add(c.Ordinal);
|
||||
if (UseUTCDateTime && (c.DataType == typeof(DateTime) || c.DataType == typeof(DateTime?)))
|
||||
datecol.Add(c.Ordinal);
|
||||
}
|
||||
|
||||
foreach (ArrayList row in rows)
|
||||
{
|
||||
var v = new object[row.Count];
|
||||
row.CopyTo(v, 0);
|
||||
foreach (var i in guidcols)
|
||||
{
|
||||
string s = (string)v[i];
|
||||
if (s != null && s.Length < 36)
|
||||
v[i] = new Guid(Convert.FromBase64String(s));
|
||||
}
|
||||
if (UseUTCDateTime)
|
||||
{
|
||||
foreach (var i in datecol)
|
||||
{
|
||||
string s = (string)v[i];
|
||||
if (s != null)
|
||||
v[i] = CreateDateTime(s);
|
||||
}
|
||||
}
|
||||
dt.Rows.Add(v);
|
||||
}
|
||||
|
||||
dt.EndLoadData();
|
||||
dt.EndInit();
|
||||
}
|
||||
|
||||
DataTable CreateDataTable(Dictionary<string, object> reader, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
var dt = new DataTable();
|
||||
|
||||
// read dataset schema here
|
||||
var schema = reader["$schema"];
|
||||
|
||||
if (schema is string)
|
||||
{
|
||||
TextReader tr = new StringReader((string)schema);
|
||||
dt.ReadXmlSchema(tr);
|
||||
}
|
||||
else
|
||||
{
|
||||
var ms = (DatasetSchema)ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema));
|
||||
dt.TableName = ms.Info[0];
|
||||
for (int i = 0; i < ms.Info.Count; i += 3)
|
||||
{
|
||||
dt.Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2]));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var pair in reader)
|
||||
{
|
||||
if (pair.Key == "$type" || pair.Key == "$schema")
|
||||
continue;
|
||||
|
||||
var rows = (ArrayList)pair.Value;
|
||||
if (rows == null)
|
||||
continue;
|
||||
|
||||
if (!dt.TableName.Equals(pair.Key, StringComparison.InvariantCultureIgnoreCase))
|
||||
continue;
|
||||
|
||||
ReadDataTable(rows, dt);
|
||||
}
|
||||
|
||||
return dt;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
@ -1,409 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LogentriesNLog.fastJSON
|
||||
{
|
||||
/// <summary>
|
||||
/// This class encodes and decodes JSON strings.
|
||||
/// Spec. details, see http://www.json.org/
|
||||
///
|
||||
/// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
|
||||
/// All numbers are parsed to doubles.
|
||||
/// </summary>
|
||||
internal class JsonParser
|
||||
{
|
||||
enum Token
|
||||
{
|
||||
None = -1, // Used to denote no Lookahead available
|
||||
Curly_Open,
|
||||
Curly_Close,
|
||||
Squared_Open,
|
||||
Squared_Close,
|
||||
Colon,
|
||||
Comma,
|
||||
String,
|
||||
Number,
|
||||
True,
|
||||
False,
|
||||
Null
|
||||
}
|
||||
|
||||
readonly char[] json;
|
||||
readonly StringBuilder s = new StringBuilder();
|
||||
Token lookAheadToken = Token.None;
|
||||
int index;
|
||||
|
||||
internal JsonParser(string json)
|
||||
{
|
||||
this.json = json.ToCharArray();
|
||||
}
|
||||
|
||||
public object Decode()
|
||||
{
|
||||
return ParseValue();
|
||||
}
|
||||
|
||||
private Dictionary<string, object> ParseObject()
|
||||
{
|
||||
var table = new Dictionary<string, object>();
|
||||
|
||||
ConsumeToken(); // {
|
||||
|
||||
while (true)
|
||||
{
|
||||
switch (LookAhead())
|
||||
{
|
||||
|
||||
case Token.Comma:
|
||||
ConsumeToken();
|
||||
break;
|
||||
|
||||
case Token.Curly_Close:
|
||||
ConsumeToken();
|
||||
return table;
|
||||
|
||||
default:
|
||||
{
|
||||
|
||||
// name
|
||||
string name = ParseString();
|
||||
|
||||
// :
|
||||
if (NextToken() != Token.Colon)
|
||||
{
|
||||
throw new Exception("Expected colon at index " + index);
|
||||
}
|
||||
|
||||
// value
|
||||
object value = ParseValue();
|
||||
|
||||
table[name] = value;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if SILVERLIGHT
|
||||
private List<object> ParseArray()
|
||||
{
|
||||
List<object> array = new List<object>();
|
||||
#else
|
||||
private ArrayList ParseArray()
|
||||
{
|
||||
ArrayList array = new ArrayList();
|
||||
#endif
|
||||
ConsumeToken(); // [
|
||||
|
||||
while (true)
|
||||
{
|
||||
switch (LookAhead())
|
||||
{
|
||||
|
||||
case Token.Comma:
|
||||
ConsumeToken();
|
||||
break;
|
||||
|
||||
case Token.Squared_Close:
|
||||
ConsumeToken();
|
||||
return array;
|
||||
|
||||
default:
|
||||
{
|
||||
array.Add(ParseValue());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private object ParseValue()
|
||||
{
|
||||
switch (LookAhead())
|
||||
{
|
||||
case Token.Number:
|
||||
return ParseNumber();
|
||||
|
||||
case Token.String:
|
||||
return ParseString();
|
||||
|
||||
case Token.Curly_Open:
|
||||
return ParseObject();
|
||||
|
||||
case Token.Squared_Open:
|
||||
return ParseArray();
|
||||
|
||||
case Token.True:
|
||||
ConsumeToken();
|
||||
return true;
|
||||
|
||||
case Token.False:
|
||||
ConsumeToken();
|
||||
return false;
|
||||
|
||||
case Token.Null:
|
||||
ConsumeToken();
|
||||
return null;
|
||||
}
|
||||
|
||||
throw new Exception("Unrecognized token at index" + index);
|
||||
}
|
||||
|
||||
private string ParseString()
|
||||
{
|
||||
ConsumeToken(); // "
|
||||
|
||||
s.Length = 0;
|
||||
|
||||
int runIndex = -1;
|
||||
|
||||
while (index < json.Length)
|
||||
{
|
||||
var c = json[index++];
|
||||
|
||||
if (c == '"')
|
||||
{
|
||||
if (runIndex != -1)
|
||||
{
|
||||
if (s.Length == 0)
|
||||
return new string(json, runIndex, index - runIndex - 1);
|
||||
|
||||
s.Append(json, runIndex, index - runIndex - 1);
|
||||
}
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
if (c != '\\')
|
||||
{
|
||||
if (runIndex == -1)
|
||||
runIndex = index - 1;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (index == json.Length) break;
|
||||
|
||||
if (runIndex != -1)
|
||||
{
|
||||
s.Append(json, runIndex, index - runIndex - 1);
|
||||
runIndex = -1;
|
||||
}
|
||||
|
||||
switch (json[index++])
|
||||
{
|
||||
case '"':
|
||||
s.Append('"');
|
||||
break;
|
||||
|
||||
case '\\':
|
||||
s.Append('\\');
|
||||
break;
|
||||
|
||||
case '/':
|
||||
s.Append('/');
|
||||
break;
|
||||
|
||||
case 'b':
|
||||
s.Append('\b');
|
||||
break;
|
||||
|
||||
case 'f':
|
||||
s.Append('\f');
|
||||
break;
|
||||
|
||||
case 'n':
|
||||
s.Append('\n');
|
||||
break;
|
||||
|
||||
case 'r':
|
||||
s.Append('\r');
|
||||
break;
|
||||
|
||||
case 't':
|
||||
s.Append('\t');
|
||||
break;
|
||||
|
||||
case 'u':
|
||||
{
|
||||
int remainingLength = json.Length - index;
|
||||
if (remainingLength < 4) break;
|
||||
|
||||
// parse the 32 bit hex into an integer codepoint
|
||||
uint codePoint = ParseUnicode(json[index], json[index + 1], json[index + 2], json[index + 3]);
|
||||
s.Append((char)codePoint);
|
||||
|
||||
// skip 4 chars
|
||||
index += 4;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("Unexpectedly reached end of string");
|
||||
}
|
||||
|
||||
private uint ParseSingleChar(char c1, uint multipliyer)
|
||||
{
|
||||
uint p1 = 0;
|
||||
if (c1 >= '0' && c1 <= '9')
|
||||
p1 = (uint)(c1 - '0') * multipliyer;
|
||||
else if (c1 >= 'A' && c1 <= 'F')
|
||||
p1 = (uint)((c1 - 'A') + 10) * multipliyer;
|
||||
else if (c1 >= 'a' && c1 <= 'f')
|
||||
p1 = (uint)((c1 - 'a') + 10) * multipliyer;
|
||||
return p1;
|
||||
}
|
||||
|
||||
private uint ParseUnicode(char c1, char c2, char c3, char c4)
|
||||
{
|
||||
uint p1 = ParseSingleChar(c1, 0x1000);
|
||||
uint p2 = ParseSingleChar(c2, 0x100);
|
||||
uint p3 = ParseSingleChar(c3, 0x10);
|
||||
uint p4 = ParseSingleChar(c4, 1);
|
||||
|
||||
return p1 + p2 + p3 + p4;
|
||||
}
|
||||
|
||||
private string ParseNumber()
|
||||
{
|
||||
ConsumeToken();
|
||||
|
||||
// Need to start back one place because the first digit is also a token and would have been consumed
|
||||
var startIndex = index - 1;
|
||||
|
||||
do
|
||||
{
|
||||
var c = json[index];
|
||||
|
||||
if ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E')
|
||||
{
|
||||
if (++index == json.Length) throw new Exception("Unexpected end of string whilst parsing number");
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
} while (true);
|
||||
|
||||
return new string(json, startIndex, index - startIndex);
|
||||
}
|
||||
|
||||
private Token LookAhead()
|
||||
{
|
||||
if (lookAheadToken != Token.None) return lookAheadToken;
|
||||
|
||||
return lookAheadToken = NextTokenCore();
|
||||
}
|
||||
|
||||
private void ConsumeToken()
|
||||
{
|
||||
lookAheadToken = Token.None;
|
||||
}
|
||||
|
||||
private Token NextToken()
|
||||
{
|
||||
var result = lookAheadToken != Token.None ? lookAheadToken : NextTokenCore();
|
||||
|
||||
lookAheadToken = Token.None;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private Token NextTokenCore()
|
||||
{
|
||||
char c;
|
||||
|
||||
// Skip past whitespace
|
||||
do
|
||||
{
|
||||
c = json[index];
|
||||
|
||||
if (c > ' ') break;
|
||||
if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break;
|
||||
|
||||
} while (++index < json.Length);
|
||||
|
||||
if (index == json.Length)
|
||||
{
|
||||
throw new Exception("Reached end of string unexpectedly");
|
||||
}
|
||||
|
||||
c = json[index];
|
||||
|
||||
index++;
|
||||
|
||||
//if (c >= '0' && c <= '9')
|
||||
// return Token.Number;
|
||||
|
||||
switch (c)
|
||||
{
|
||||
case '{':
|
||||
return Token.Curly_Open;
|
||||
|
||||
case '}':
|
||||
return Token.Curly_Close;
|
||||
|
||||
case '[':
|
||||
return Token.Squared_Open;
|
||||
|
||||
case ']':
|
||||
return Token.Squared_Close;
|
||||
|
||||
case ',':
|
||||
return Token.Comma;
|
||||
|
||||
case '"':
|
||||
return Token.String;
|
||||
|
||||
case '0': case '1': case '2': case '3': case '4':
|
||||
case '5': case '6': case '7': case '8': case '9':
|
||||
case '-': case '+': case '.':
|
||||
return Token.Number;
|
||||
|
||||
case ':':
|
||||
return Token.Colon;
|
||||
|
||||
case 'f':
|
||||
if (json.Length - index >= 4 &&
|
||||
json[index + 0] == 'a' &&
|
||||
json[index + 1] == 'l' &&
|
||||
json[index + 2] == 's' &&
|
||||
json[index + 3] == 'e')
|
||||
{
|
||||
index += 4;
|
||||
return Token.False;
|
||||
}
|
||||
break;
|
||||
|
||||
case 't':
|
||||
if (json.Length - index >= 3 &&
|
||||
json[index + 0] == 'r' &&
|
||||
json[index + 1] == 'u' &&
|
||||
json[index + 2] == 'e')
|
||||
{
|
||||
index += 3;
|
||||
return Token.True;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'n':
|
||||
if (json.Length - index >= 3 &&
|
||||
json[index + 0] == 'u' &&
|
||||
json[index + 1] == 'l' &&
|
||||
json[index + 2] == 'l')
|
||||
{
|
||||
index += 3;
|
||||
return Token.Null;
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
throw new Exception("Could not find token at index " + --index);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,521 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace LogentriesNLog.fastJSON
|
||||
{
|
||||
internal class JSONSerializer
|
||||
{
|
||||
private readonly StringBuilder _output = new StringBuilder();
|
||||
readonly bool useMinimalDataSetSchema;
|
||||
readonly bool fastguid = true;
|
||||
readonly bool useExtension = true;
|
||||
readonly bool serializeNulls = true;
|
||||
readonly int _MAX_DEPTH = 10;
|
||||
readonly bool _Indent;
|
||||
readonly bool _useGlobalTypes = true;
|
||||
int _current_depth;
|
||||
private readonly Dictionary<string, int> _globalTypes = new Dictionary<string, int>();
|
||||
|
||||
internal JSONSerializer(bool UseMinimalDataSetSchema, bool UseFastGuid, bool UseExtensions, bool SerializeNulls, bool IndentOutput)
|
||||
{
|
||||
useMinimalDataSetSchema = UseMinimalDataSetSchema;
|
||||
fastguid = UseFastGuid;
|
||||
useExtension = UseExtensions;
|
||||
_Indent = IndentOutput;
|
||||
serializeNulls = SerializeNulls;
|
||||
if (useExtension == false)
|
||||
_useGlobalTypes = false;
|
||||
}
|
||||
|
||||
internal string ConvertToJSON(object obj)
|
||||
{
|
||||
WriteValue(obj);
|
||||
|
||||
string str = "";
|
||||
if (_useGlobalTypes)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("{\"$types\":{");
|
||||
bool pendingSeparator = false;
|
||||
foreach (var kv in _globalTypes)
|
||||
{
|
||||
if (pendingSeparator) sb.Append(',');
|
||||
pendingSeparator = true;
|
||||
sb.Append("\"");
|
||||
sb.Append(kv.Key);
|
||||
sb.Append("\":\"");
|
||||
sb.Append(kv.Value);
|
||||
sb.Append("\"");
|
||||
}
|
||||
sb.Append("},");
|
||||
str = sb + _output.ToString();
|
||||
}
|
||||
else
|
||||
str = _output.ToString();
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
private void WriteValue(object obj)
|
||||
{
|
||||
if (obj == null || obj is DBNull)
|
||||
_output.Append("null");
|
||||
|
||||
else if (obj is string || obj is char)
|
||||
WriteString((string)obj);
|
||||
|
||||
else if (obj is Guid)
|
||||
WriteGuid((Guid)obj);
|
||||
|
||||
else if (obj is bool)
|
||||
_output.Append(((bool)obj) ? "true" : "false"); // conform to standard
|
||||
|
||||
else if (
|
||||
obj is int || obj is long || obj is double ||
|
||||
obj is decimal || obj is float ||
|
||||
obj is byte || obj is short ||
|
||||
obj is sbyte || obj is ushort ||
|
||||
obj is uint || obj is ulong
|
||||
)
|
||||
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
|
||||
|
||||
else if (obj is DateTime)
|
||||
WriteDateTime((DateTime)obj);
|
||||
|
||||
else if (obj is IDictionary && obj.GetType().IsGenericType && obj.GetType().GetGenericArguments()[0] == typeof(string))
|
||||
WriteStringDictionary((IDictionary)obj);
|
||||
|
||||
else if (obj is IDictionary)
|
||||
WriteDictionary((IDictionary)obj);
|
||||
#if !SILVERLIGHT
|
||||
else if (obj is DataSet)
|
||||
WriteDataset((DataSet)obj);
|
||||
|
||||
else if (obj is DataTable)
|
||||
WriteDataTable((DataTable)obj);
|
||||
#endif
|
||||
else if (obj is byte[])
|
||||
WriteBytes((byte[])obj);
|
||||
|
||||
else if (obj is Array || obj is IList || obj is ICollection)
|
||||
WriteArray((IEnumerable)obj);
|
||||
|
||||
else if (obj is Enum)
|
||||
WriteEnum((Enum)obj);
|
||||
|
||||
#if CUSTOMTYPE
|
||||
else if (JSON.Instance.IsTypeRegistered(obj.GetType()))
|
||||
WriteCustom(obj);
|
||||
#endif
|
||||
else
|
||||
WriteObject(obj);
|
||||
}
|
||||
|
||||
#if CUSTOMTYPE
|
||||
private void WriteCustom(object obj)
|
||||
{
|
||||
Serialize s;
|
||||
JSON.Instance._customSerializer.TryGetValue(obj.GetType(), out s);
|
||||
WriteStringFast(s(obj));
|
||||
}
|
||||
#endif
|
||||
|
||||
private void WriteEnum(Enum e)
|
||||
{
|
||||
// TODO : optimize enum write
|
||||
WriteStringFast(e.ToString());
|
||||
}
|
||||
|
||||
private void WriteGuid(Guid g)
|
||||
{
|
||||
if (fastguid == false)
|
||||
WriteStringFast(g.ToString());
|
||||
else
|
||||
WriteBytes(g.ToByteArray());
|
||||
}
|
||||
|
||||
private void WriteBytes(byte[] bytes)
|
||||
{
|
||||
#if !SILVERLIGHT
|
||||
WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None));
|
||||
#else
|
||||
WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length));
|
||||
#endif
|
||||
}
|
||||
|
||||
private void WriteDateTime(DateTime dateTime)
|
||||
{
|
||||
// datetime format standard : yyyy-MM-dd HH:mm:ss
|
||||
DateTime dt = dateTime;
|
||||
if (JSON.Instance.UseUTCDateTime)
|
||||
dt = dateTime.ToUniversalTime();
|
||||
|
||||
_output.Append("\"");
|
||||
_output.Append(dt.Year.ToString("0000", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append("-");
|
||||
_output.Append(dt.Month.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append("-");
|
||||
_output.Append(dt.Day.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append(" ");
|
||||
_output.Append(dt.Hour.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append(":");
|
||||
_output.Append(dt.Minute.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append(":");
|
||||
_output.Append(dt.Second.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append(".");
|
||||
_output.Append(dt.Millisecond.ToString("000", NumberFormatInfo.InvariantInfo));
|
||||
|
||||
if (JSON.Instance.UseUTCDateTime)
|
||||
_output.Append("Z");
|
||||
|
||||
_output.Append("\"");
|
||||
}
|
||||
#if !SILVERLIGHT
|
||||
private DatasetSchema GetSchema(DataTable ds)
|
||||
{
|
||||
if (ds == null) return null;
|
||||
|
||||
DatasetSchema m = new DatasetSchema();
|
||||
m.Info = new List<string>();
|
||||
m.Name = ds.TableName;
|
||||
|
||||
foreach (DataColumn c in ds.Columns)
|
||||
{
|
||||
m.Info.Add(ds.TableName);
|
||||
m.Info.Add(c.ColumnName);
|
||||
m.Info.Add(c.DataType.ToString());
|
||||
}
|
||||
// TODO : serialize relations and constraints here
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
private DatasetSchema GetSchema(DataSet ds)
|
||||
{
|
||||
if (ds == null) return null;
|
||||
|
||||
DatasetSchema m = new DatasetSchema();
|
||||
m.Info = new List<string>();
|
||||
m.Name = ds.DataSetName;
|
||||
|
||||
foreach (DataTable t in ds.Tables)
|
||||
{
|
||||
foreach (DataColumn c in t.Columns)
|
||||
{
|
||||
m.Info.Add(t.TableName);
|
||||
m.Info.Add(c.ColumnName);
|
||||
m.Info.Add(c.DataType.ToString());
|
||||
}
|
||||
}
|
||||
// TODO : serialize relations and constraints here
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
private string GetXmlSchema(DataTable dt)
|
||||
{
|
||||
using (var writer = new StringWriter())
|
||||
{
|
||||
dt.WriteXmlSchema(writer);
|
||||
return dt.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteDataset(DataSet ds)
|
||||
{
|
||||
_output.Append('{');
|
||||
if (useExtension)
|
||||
{
|
||||
WritePair("$schema", useMinimalDataSetSchema ? (object)GetSchema(ds) : ds.GetXmlSchema());
|
||||
_output.Append(',');
|
||||
}
|
||||
bool tablesep = false;
|
||||
foreach (DataTable table in ds.Tables)
|
||||
{
|
||||
if (tablesep) _output.Append(",");
|
||||
tablesep = true;
|
||||
WriteDataTableData(table);
|
||||
}
|
||||
// end dataset
|
||||
_output.Append('}');
|
||||
}
|
||||
|
||||
private void WriteDataTableData(DataTable table)
|
||||
{
|
||||
_output.Append('\"');
|
||||
_output.Append(table.TableName);
|
||||
_output.Append("\":[");
|
||||
DataColumnCollection cols = table.Columns;
|
||||
bool rowseparator = false;
|
||||
foreach (DataRow row in table.Rows)
|
||||
{
|
||||
if (rowseparator) _output.Append(",");
|
||||
rowseparator = true;
|
||||
_output.Append('[');
|
||||
|
||||
bool pendingSeperator = false;
|
||||
foreach (DataColumn column in cols)
|
||||
{
|
||||
if (pendingSeperator) _output.Append(',');
|
||||
WriteValue(row[column]);
|
||||
pendingSeperator = true;
|
||||
}
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
void WriteDataTable(DataTable dt)
|
||||
{
|
||||
_output.Append('{');
|
||||
if (useExtension)
|
||||
{
|
||||
WritePair("$schema", useMinimalDataSetSchema ? (object)GetSchema(dt) : GetXmlSchema(dt));
|
||||
_output.Append(',');
|
||||
}
|
||||
|
||||
WriteDataTableData(dt);
|
||||
|
||||
// end datatable
|
||||
_output.Append('}');
|
||||
}
|
||||
#endif
|
||||
bool _firstWritten;
|
||||
private void WriteObject(object obj)
|
||||
{
|
||||
Indent();
|
||||
if (_useGlobalTypes == false)
|
||||
_output.Append('{');
|
||||
else
|
||||
{
|
||||
if (_firstWritten)
|
||||
_output.Append("{");
|
||||
}
|
||||
_firstWritten = true;
|
||||
_current_depth++;
|
||||
if (_current_depth > _MAX_DEPTH)
|
||||
throw new Exception("Serializer encountered maximum depth of " + _MAX_DEPTH);
|
||||
|
||||
|
||||
var map = new Dictionary<string, string>();
|
||||
Type t = obj.GetType();
|
||||
bool append = false;
|
||||
if (useExtension)
|
||||
{
|
||||
if (_useGlobalTypes == false)
|
||||
WritePairFast("$type", JSON.Instance.GetTypeAssemblyName(t));
|
||||
else
|
||||
{
|
||||
int dt = 0;
|
||||
string ct = JSON.Instance.GetTypeAssemblyName(t);
|
||||
if (_globalTypes.TryGetValue(ct, out dt) == false)
|
||||
{
|
||||
dt = _globalTypes.Count + 1;
|
||||
_globalTypes.Add(ct, dt);
|
||||
}
|
||||
WritePairFast("$type", dt.ToString());
|
||||
}
|
||||
append = true;
|
||||
}
|
||||
|
||||
var g = JSON.Instance.GetGetters(t);
|
||||
foreach (var p in g)
|
||||
{
|
||||
if (append)
|
||||
_output.Append(',');
|
||||
object o = p.Getter(obj);
|
||||
if ((o == null || o is DBNull) && serializeNulls == false)
|
||||
append = false;
|
||||
else
|
||||
{
|
||||
WritePair(p.Name, o);
|
||||
if (o != null && useExtension)
|
||||
{
|
||||
Type tt = o.GetType();
|
||||
if (tt == typeof(Object))
|
||||
map.Add(p.Name, tt.ToString());
|
||||
}
|
||||
append = true;
|
||||
}
|
||||
}
|
||||
if (map.Count > 0 && useExtension)
|
||||
{
|
||||
_output.Append(",\"$map\":");
|
||||
WriteStringDictionary(map);
|
||||
}
|
||||
_current_depth--;
|
||||
Indent();
|
||||
_output.Append('}');
|
||||
_current_depth--;
|
||||
|
||||
}
|
||||
|
||||
private void Indent()
|
||||
{
|
||||
Indent(false);
|
||||
}
|
||||
|
||||
private void Indent(bool dec)
|
||||
{
|
||||
if (_Indent)
|
||||
{
|
||||
_output.Append("\r\n");
|
||||
for (int i = 0; i < _current_depth - (dec ? 1 : 0); i++)
|
||||
_output.Append("\t");
|
||||
}
|
||||
}
|
||||
|
||||
private void WritePairFast(string name, string value)
|
||||
{
|
||||
if ((value == null) && serializeNulls == false)
|
||||
return;
|
||||
Indent();
|
||||
WriteStringFast(name);
|
||||
|
||||
_output.Append(':');
|
||||
|
||||
WriteStringFast(value);
|
||||
}
|
||||
|
||||
private void WritePair(string name, object value)
|
||||
{
|
||||
if ((value == null || value is DBNull) && serializeNulls == false)
|
||||
return;
|
||||
Indent();
|
||||
WriteStringFast(name);
|
||||
|
||||
_output.Append(':');
|
||||
|
||||
WriteValue(value);
|
||||
}
|
||||
|
||||
private void WriteArray(IEnumerable array)
|
||||
{
|
||||
Indent();
|
||||
_output.Append('[');
|
||||
|
||||
bool pendingSeperator = false;
|
||||
|
||||
foreach (var obj in array)
|
||||
{
|
||||
Indent();
|
||||
if (pendingSeperator) _output.Append(',');
|
||||
|
||||
WriteValue(obj);
|
||||
|
||||
pendingSeperator = true;
|
||||
}
|
||||
Indent();
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
private void WriteStringDictionary(IDictionary dic)
|
||||
{
|
||||
Indent();
|
||||
_output.Append('{');
|
||||
|
||||
bool pendingSeparator = false;
|
||||
|
||||
foreach (DictionaryEntry entry in dic)
|
||||
{
|
||||
if (pendingSeparator) _output.Append(',');
|
||||
|
||||
WritePair((string)entry.Key, entry.Value);
|
||||
|
||||
pendingSeparator = true;
|
||||
}
|
||||
Indent();
|
||||
_output.Append('}');
|
||||
}
|
||||
|
||||
private void WriteDictionary(IDictionary dic)
|
||||
{
|
||||
Indent();
|
||||
_output.Append('[');
|
||||
|
||||
bool pendingSeparator = false;
|
||||
|
||||
foreach (DictionaryEntry entry in dic)
|
||||
{
|
||||
if (pendingSeparator) _output.Append(',');
|
||||
Indent();
|
||||
_output.Append('{');
|
||||
WritePair("k", entry.Key);
|
||||
_output.Append(",");
|
||||
WritePair("v", entry.Value);
|
||||
Indent();
|
||||
_output.Append('}');
|
||||
|
||||
pendingSeparator = true;
|
||||
}
|
||||
Indent();
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
private void WriteStringFast(string s)
|
||||
{
|
||||
//Indent();
|
||||
_output.Append('\"');
|
||||
_output.Append(s);
|
||||
_output.Append('\"');
|
||||
}
|
||||
|
||||
private void WriteString(string s)
|
||||
{
|
||||
//Indent();
|
||||
_output.Append('\"');
|
||||
|
||||
int runIndex = -1;
|
||||
|
||||
for (var index = 0; index < s.Length; ++index)
|
||||
{
|
||||
var c = s[index];
|
||||
|
||||
if (c >= ' ' && c < 128 && c != '\"' && c != '\\')
|
||||
{
|
||||
if (runIndex == -1)
|
||||
{
|
||||
runIndex = index;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (runIndex != -1)
|
||||
{
|
||||
_output.Append(s, runIndex, index - runIndex);
|
||||
runIndex = -1;
|
||||
}
|
||||
|
||||
switch (c)
|
||||
{
|
||||
case '\t': _output.Append("\\t"); break;
|
||||
case '\r': _output.Append("\\r"); break;
|
||||
case '\n': _output.Append("\\n"); break;
|
||||
case '"':
|
||||
case '\\': _output.Append('\\'); _output.Append(c); break;
|
||||
default:
|
||||
_output.Append("\\u");
|
||||
_output.Append(((int)c).ToString("X4", NumberFormatInfo.InvariantInfo));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (runIndex != -1)
|
||||
{
|
||||
_output.Append(s, runIndex, s.Length - runIndex);
|
||||
}
|
||||
|
||||
_output.Append('\"');
|
||||
}
|
||||
}
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LogentriesNLog.fastJSON
|
||||
{
|
||||
internal class SafeDictionary<TKey, TValue>
|
||||
{
|
||||
private readonly object _Padlock = new object();
|
||||
private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();
|
||||
|
||||
|
||||
internal bool TryGetValue(TKey key, out TValue value)
|
||||
{
|
||||
return _Dictionary.TryGetValue(key, out value);
|
||||
}
|
||||
|
||||
internal TValue this[TKey key]
|
||||
{
|
||||
get
|
||||
{
|
||||
return _Dictionary[key];
|
||||
}
|
||||
}
|
||||
|
||||
internal void Add(TKey key, TValue value)
|
||||
{
|
||||
lock (_Padlock)
|
||||
{
|
||||
if (_Dictionary.ContainsKey(key) == false)
|
||||
_Dictionary.Add(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,87 +0,0 @@
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
||||
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
@ -1,4 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="NLog" version="4.5.0-rc06" targetFramework="net40" />
|
||||
</packages>
|
@ -18,6 +18,14 @@
|
||||
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /></startup></configuration>
|
||||
|
@ -14,6 +14,14 @@
|
||||
<assemblyIdentity name="Microsoft.Practices.ServiceLocation" publicKeyToken="31bf3856ad364e35" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /></startup></configuration>
|
||||
|
@ -1,73 +0,0 @@
|
||||
using System.ComponentModel;
|
||||
using System.Configuration;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron.Configuration
|
||||
{
|
||||
|
||||
public class ExceptronConfiguration : ConfigurationSection
|
||||
{
|
||||
public ExceptronConfiguration()
|
||||
{
|
||||
Host = "http://exceptron.azurewebsites.net/api/v1/";
|
||||
IncludeMachineName = true;
|
||||
}
|
||||
|
||||
public static ExceptronConfiguration ReadConfig(string sectionName = "exceptron")
|
||||
{
|
||||
var configSection = ConfigurationManager.GetSection(sectionName);
|
||||
|
||||
if (configSection == null)
|
||||
{
|
||||
throw new ConfigurationErrorsException("ExceptronConfiguration section missing.");
|
||||
}
|
||||
|
||||
return (ExceptronConfiguration)configSection;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// exceptron api address. Do not modify this property.
|
||||
/// </summary>
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public string Host { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// If ExceptronClinet should throw exceptions in case of an error. Default: <see cref="bool.False"/>
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Its recommended that this flag is set to True during development and <see cref="bool.False"/> in production systems.
|
||||
/// If an exception is thrown while this flag is set to <see cref="bool.False"/> the thrown exception will be returned in <see cref="ExceptionResponse.Exception"/>
|
||||
/// </remarks>
|
||||
[ConfigurationProperty("throwExceptions", DefaultValue = false)]
|
||||
public bool ThrowExceptions
|
||||
{
|
||||
get { return (bool)this["throwExceptions"]; }
|
||||
set { this["throwExceptions"] = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The API of this application. Can find your API key in application settings page.
|
||||
/// </summary>
|
||||
[ConfigurationProperty("apiKey")]
|
||||
public string ApiKey
|
||||
{
|
||||
get { return (string)this["apiKey"]; }
|
||||
set { this["apiKey"] = value; }
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// If the machine name should be attached to the exception report
|
||||
/// </summary>
|
||||
/// <remarks>Machine name can be usefull in webfarm enviroments when multiple
|
||||
/// servers are running the same app and the issue could be machine specific.
|
||||
/// Hoewever, You might want to disable this feature for privacy reasons.</remarks>
|
||||
[ConfigurationProperty("includeMachineName", DefaultValue = true)]
|
||||
public bool IncludeMachineName
|
||||
{
|
||||
get { return (bool)this["includeMachineName"]; }
|
||||
set { this["includeMachineName"] = value; }
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents information that will be used to construct an exception report.
|
||||
/// </summary>
|
||||
public class ExceptionData
|
||||
{
|
||||
/// <summary>
|
||||
/// Exception that is being reported
|
||||
/// </summary>
|
||||
public Exception Exception { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Component that experianced this exception.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It is common to use the logger name that was used to log the exception as the component.
|
||||
/// </remarks>
|
||||
/// <example>
|
||||
/// DataAccess, Configuration, Registration, etc.
|
||||
/// </example>
|
||||
public string Component { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// ID that will uniquely identify the user
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This Id does not have to be tied to the user's identity.
|
||||
/// You can use a system generated unique ID such as GUID.
|
||||
/// This field is used to report how many unique users are experiencing an error.
|
||||
/// </remarks>
|
||||
/// <example>
|
||||
/// "62E5C8EF-0CA2-43AB-B278-FC6994F776ED"
|
||||
/// "Timmy@aol.com"
|
||||
/// "26437"
|
||||
/// </example>
|
||||
public string UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Any message that should be attached to this exceptions
|
||||
/// </summary>
|
||||
/// <example>
|
||||
/// Something went wrong while checking for application updates.
|
||||
/// </example>
|
||||
public string Message { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Severity of the exception being reported
|
||||
/// </summary>
|
||||
public ExceptionSeverity Severity { get; set; }
|
||||
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
namespace NzbDrone.Common.Exceptron
|
||||
{
|
||||
/// <summary>
|
||||
/// Severity of the exception being reported
|
||||
/// </summary>
|
||||
public enum ExceptionSeverity
|
||||
{
|
||||
/// <summary>
|
||||
/// Excepted Error. Can be ignored
|
||||
/// </summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Error that can be handled gracefully
|
||||
/// </summary>
|
||||
Warning = 1,
|
||||
|
||||
/// <summary>
|
||||
/// Blocking user from completing their intended action
|
||||
/// </summary>
|
||||
Error = 2,
|
||||
|
||||
/// <summary>
|
||||
/// Will most likely cause the application to crash
|
||||
/// </summary>
|
||||
Fatal = 3
|
||||
}
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron
|
||||
{
|
||||
public class ExceptronApiException : Exception
|
||||
{
|
||||
public ExceptronApiException(WebException innerException, string message)
|
||||
: base(message, innerException)
|
||||
{
|
||||
Response = (HttpWebResponse)innerException.Response;
|
||||
}
|
||||
|
||||
public HttpWebResponse Response { get; private set; }
|
||||
}
|
||||
}
|
@ -1,285 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using NzbDrone.Common.Exceptron.Configuration;
|
||||
using NzbDrone.Common.Exceptron.Message;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron
|
||||
{
|
||||
public class ExceptronClient : IExceptronClient
|
||||
{
|
||||
internal IRestClient RestClient { private get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Version of Client
|
||||
/// </summary>
|
||||
public string ClientVersion => Assembly.GetExecutingAssembly().GetName().Version.ToString();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Name of Client
|
||||
/// </summary>
|
||||
public string ClientName => "Official .NET";
|
||||
|
||||
/// <summary>
|
||||
/// Client Configuration
|
||||
/// </summary>
|
||||
public ExceptronConfiguration Configuration { get; private set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Framework Type of the Host Application (.Net/mono)
|
||||
/// </summary>
|
||||
public string FrameworkType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of <see cref="ExceptronClient"/>
|
||||
/// Loads <see cref="ExceptronConfiguration"/> from application config file.
|
||||
/// </summary>
|
||||
/// <param name="applicationVersion">Version of the currently running application</param>
|
||||
public ExceptronClient(Version applicationVersion)
|
||||
: this(ExceptronConfiguration.ReadConfig(), applicationVersion)
|
||||
{
|
||||
FrameworkType = ".Net";
|
||||
}
|
||||
|
||||
private readonly string _applicationVersion;
|
||||
private readonly string _maxFrameworkVersion;
|
||||
|
||||
|
||||
/// <param name="exceptronConfiguration">exceptron client configuration</param>
|
||||
/// <param name="applicationVersion"> </param>
|
||||
public ExceptronClient(ExceptronConfiguration exceptronConfiguration, Version applicationVersion)
|
||||
{
|
||||
if (exceptronConfiguration == null)
|
||||
throw new ArgumentNullException("exceptronConfiguration");
|
||||
|
||||
if (applicationVersion == null)
|
||||
throw new ArgumentNullException("applicationVersion");
|
||||
|
||||
if (string.IsNullOrEmpty(exceptronConfiguration.ApiKey))
|
||||
throw new ArgumentException("An API Key was not provided");
|
||||
|
||||
Configuration = exceptronConfiguration;
|
||||
|
||||
RestClient = new RestClient();
|
||||
|
||||
_applicationVersion = applicationVersion.ToString();
|
||||
|
||||
_maxFrameworkVersion = GetMaximumFrameworkVersion();
|
||||
|
||||
FrameworkType = ".Net";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Submit an exception to exceptron Servers.
|
||||
/// </summary>
|
||||
/// <param name="exception">Exception that is being reported</param>
|
||||
/// <param name="component"
|
||||
/// example="DataAccess, Configuration, Registration, etc."
|
||||
/// remarks="It is common to use the logger name that was used to log the exception as the component.">Component that experienced this exception.</param>
|
||||
|
||||
/// <param name="severity">Severity of the exception being reported</param>
|
||||
/// <param name="message"
|
||||
/// example="Something went wrong while checking for application updates.">Any message that should be attached to this exceptions</param>
|
||||
/// <param name="userId"
|
||||
/// remarks="This Id does not have to be tied to the user's identity.
|
||||
/// You can use a system generated unique ID such as GUID.
|
||||
/// This field is used to report how many unique users are experiencing an error."
|
||||
/// example="
|
||||
/// 62E5C8EF-0CA2-43AB-B278-FC6994F776ED
|
||||
/// Timmy@aol.com
|
||||
/// 26437
|
||||
/// ">ID that will uniquely identify the user</param>
|
||||
/// <param name="httpContext"><see cref="System.Web.HttpContext"/> in which the exception occurred. If no <see cref="System.Web.HttpContext"/> is provided
|
||||
/// <see cref="ExceptronClient"/> will try to get the current <see cref="System.Web.HttpContext"/> from <see cref="System.Web.HttpContext.Current"/></param>
|
||||
/// <returns></returns>
|
||||
public ExceptionResponse SubmitException(Exception exception, string component, ExceptionSeverity severity = ExceptionSeverity.None, string message = null, string userId = null)
|
||||
{
|
||||
var exceptionData = new ExceptionData
|
||||
{
|
||||
Exception = exception,
|
||||
Component = component,
|
||||
Severity = severity,
|
||||
Message = message,
|
||||
UserId = userId
|
||||
};
|
||||
|
||||
return SubmitException(exceptionData);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Submit an exception to exceptron Servers.
|
||||
/// </summary>
|
||||
/// <param name="exceptionData">Exception data to be reported to the server</param>
|
||||
public ExceptionResponse SubmitException(ExceptionData exceptionData)
|
||||
{
|
||||
try
|
||||
{
|
||||
ValidateState(exceptionData);
|
||||
|
||||
var report = new ExceptionReport();
|
||||
|
||||
report.ap = Configuration.ApiKey;
|
||||
report.dn = ClientName;
|
||||
report.dv = ClientVersion;
|
||||
report.aver = _applicationVersion;
|
||||
|
||||
report.ext = exceptionData.Exception.GetType().FullName;
|
||||
report.stk = ConvertToFrames(exceptionData.Exception);
|
||||
report.exm = exceptionData.Exception.Message;
|
||||
|
||||
report.cmp = exceptionData.Component;
|
||||
report.uid = exceptionData.UserId;
|
||||
report.msg = exceptionData.Message;
|
||||
report.sv = (int)exceptionData.Severity;
|
||||
report.fv = _maxFrameworkVersion;
|
||||
report.ft = FrameworkType;
|
||||
|
||||
SetEnviromentInfo(report);
|
||||
|
||||
var exceptionResponse = RestClient.Put<ExceptionResponse>(Configuration.Host, report);
|
||||
|
||||
exceptionData.Exception.Data["et"] = exceptionResponse.RefId;
|
||||
|
||||
return exceptionResponse;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Trace.WriteLine("Unable to submit exception to exceptron. ", e.ToString());
|
||||
|
||||
if (Configuration.ThrowExceptions)
|
||||
{
|
||||
//throw;
|
||||
}
|
||||
|
||||
return new ExceptionResponse { Exception = e };
|
||||
}
|
||||
}
|
||||
|
||||
private void ValidateState(ExceptionData exceptionData)
|
||||
{
|
||||
if (string.IsNullOrEmpty(Configuration.ApiKey))
|
||||
throw new InvalidOperationException("ApiKey has not been provided for this client.");
|
||||
|
||||
if (exceptionData == null)
|
||||
throw new ArgumentNullException("exceptionData");
|
||||
|
||||
if (exceptionData.Exception == null)
|
||||
throw new ArgumentException("ExceptionData.Exception Cannot be null.", "exceptionData");
|
||||
}
|
||||
|
||||
private void SetEnviromentInfo(ExceptionReport report)
|
||||
{
|
||||
report.cul = Thread.CurrentThread.CurrentCulture.Name;
|
||||
|
||||
if (string.IsNullOrEmpty(report.cul))
|
||||
report.cul = "en";
|
||||
|
||||
try
|
||||
{
|
||||
report.os = Environment.OSVersion.VersionString;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
if (Configuration.ThrowExceptions) throw;
|
||||
}
|
||||
|
||||
if (Configuration.IncludeMachineName)
|
||||
{
|
||||
try
|
||||
{
|
||||
report.hn = Environment.MachineName;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
if (Configuration.ThrowExceptions) throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
internal static List<Frame> ConvertToFrames(Exception exception)
|
||||
{
|
||||
if (exception == null) return null;
|
||||
|
||||
var stackTrace = new StackTrace(exception, true);
|
||||
|
||||
var frames = stackTrace.GetFrames();
|
||||
|
||||
if (frames == null) return null;
|
||||
|
||||
var result = new List<Frame>();
|
||||
|
||||
for (int index = 0; index < frames.Length; index++)
|
||||
{
|
||||
var frame = frames[index];
|
||||
var method = frame.GetMethod();
|
||||
var declaringType = method.DeclaringType;
|
||||
|
||||
var fileName = frame.GetFileName();
|
||||
|
||||
var currentFrame = new Frame
|
||||
{
|
||||
i = index,
|
||||
fn = fileName,
|
||||
ln = frame.GetFileLineNumber(),
|
||||
m = method.ToString(),
|
||||
};
|
||||
|
||||
currentFrame.m = currentFrame.m.Substring(currentFrame.m.IndexOf(' ')).Trim();
|
||||
|
||||
|
||||
if (declaringType != null)
|
||||
{
|
||||
currentFrame.c = declaringType.FullName;
|
||||
}
|
||||
|
||||
result.Add(currentFrame);
|
||||
}
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private string GetMaximumFrameworkVersion()
|
||||
{
|
||||
var clrVersion = Environment.Version;
|
||||
|
||||
if (clrVersion.Major == 2)
|
||||
{
|
||||
//Check if 2.0 or 3.5
|
||||
try
|
||||
{
|
||||
Assembly.Load("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
|
||||
return "3.5";
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
|
||||
return "2.0";
|
||||
}
|
||||
|
||||
if (clrVersion.Major == 4)
|
||||
{
|
||||
//Check if 4.0 or 4.5
|
||||
try
|
||||
{
|
||||
Assembly.Load("System.Threading.Tasks.Parallel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
|
||||
return "4.5";
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
|
||||
return "4.0";
|
||||
}
|
||||
|
||||
return "Unknown";
|
||||
}
|
||||
}
|
||||
}
|
@ -1,44 +0,0 @@
|
||||
using System;
|
||||
using NzbDrone.Common.Exceptron.Configuration;
|
||||
using NzbDrone.Common.Exceptron.Message;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron
|
||||
{
|
||||
public interface IExceptronClient
|
||||
{
|
||||
/// <summary>
|
||||
/// Client Configuration
|
||||
/// </summary>
|
||||
ExceptronConfiguration Configuration { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Submit an exception to exceptron Servers.
|
||||
/// </summary>
|
||||
/// <param name="exceptionData">Exception data to be reported to the server</param>
|
||||
ExceptionResponse SubmitException(ExceptionData exceptionData);
|
||||
|
||||
/// <summary>
|
||||
/// Submit an exception to exceptron Servers.
|
||||
/// </summary>
|
||||
/// <param name="exception">Exception that is being reported</param>
|
||||
/// <param name="component"
|
||||
/// example="DataAccess, Configuration, Registration, etc."
|
||||
/// remarks="It is common to use the logger name that was used to log the exception as the component.">Component that experienced this exception.</param>
|
||||
/// <param name="severity">Severity of the exception being reported</param>
|
||||
/// <param name="message"
|
||||
/// example="Something went wrong while checking for application updates.">Any message that should be attached to this exceptions</param>
|
||||
/// <param name="userId"
|
||||
/// remarks="This Id does not have to be tied to the user's identity.
|
||||
/// You can use a system generated unique ID such as GUID.
|
||||
/// This field is used to report how many unique users are experiencing an error."
|
||||
/// example="
|
||||
/// 62E5C8EF-0CA2-43AB-B278-FC6994F776ED
|
||||
/// Timmy@aol.com
|
||||
/// 26437
|
||||
/// ">ID that will uniquely identify the user</param>
|
||||
/// <param name="httpContext"><see cref="System.Web.HttpContext"/> in which the exception occurred. If no <see cref="System.Web.HttpContext"/> is provided
|
||||
/// <see cref="ExceptronClient"/> will try to get the current <see cref="System.Web.HttpContext"/> from <see cref="System.Web.HttpContext.Current"/></param>
|
||||
/// <returns></returns>
|
||||
ExceptionResponse SubmitException(Exception exception, string component, ExceptionSeverity severity = ExceptionSeverity.None, string message = null, string userId = null);
|
||||
}
|
||||
}
|
@ -1,7 +0,0 @@
|
||||
namespace NzbDrone.Common.Exceptron
|
||||
{
|
||||
internal interface IRestClient
|
||||
{
|
||||
TResponse Put<TResponse>(string url, object report) where TResponse : class, new();
|
||||
}
|
||||
}
|
@ -1,111 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron.Message
|
||||
{
|
||||
internal class ExceptionReport
|
||||
{
|
||||
/// <summary>
|
||||
/// API key
|
||||
/// </summary>
|
||||
public string ap { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Application Version
|
||||
/// </summary>
|
||||
public string aver { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Exception Severity
|
||||
/// </summary>
|
||||
public int sv { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// User or Instance ID
|
||||
/// </summary>
|
||||
public string uid { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Type of exception
|
||||
/// </summary>
|
||||
public string ext { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Exception message
|
||||
/// </summary>
|
||||
public string exm { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// List of frames that make up the StackTrace of the exception
|
||||
/// </summary>
|
||||
public List<Frame> stk { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Component that experienced this exception
|
||||
/// </summary>
|
||||
public string cmp { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Message that was logged along with the exception.
|
||||
/// </summary>
|
||||
public string msg { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// User's culture in
|
||||
/// </summary>
|
||||
/// <remarks>http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.name.aspx</remarks>
|
||||
public string cul { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// OS Version
|
||||
/// </summary>
|
||||
public string os { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Name of the Client that generated and is sending this message
|
||||
/// </summary>
|
||||
public string dn { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Version of the Client that generated and is sending this message
|
||||
/// </summary>
|
||||
public string dv { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Host name of the machine that encountered this exception
|
||||
/// </summary>
|
||||
public string hn { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Request url
|
||||
/// <remarks>Only used for exception in context of a web request/</remarks>
|
||||
public string url { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Browser useragent
|
||||
/// </summary>
|
||||
/// <remarks>Only used for exception in context of a web request/</remarks>
|
||||
public string ua { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// HTTP response status code
|
||||
/// </summary>
|
||||
/// <remarks>Only used for exception in context of a web request/</remarks>
|
||||
public int sc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Indicates the HTTP data transfer method used by the client.
|
||||
/// </summary>
|
||||
/// <example>GET, POST, PUT, DELETE</example>
|
||||
public string hm { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Framework Version (CLR) of the Host Application
|
||||
/// </summary>
|
||||
public string fv { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Framework Type of the Host Application
|
||||
/// </summary>
|
||||
public string ft { get; set; }
|
||||
}
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron.Message
|
||||
{
|
||||
public class ExceptionResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// Exception report reference ID. This ID will be shared across
|
||||
/// similar exceptions
|
||||
/// </summary>
|
||||
public string RefId { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Was the report successfully processed on the server
|
||||
/// </summary>
|
||||
public bool Successful => !string.IsNullOrEmpty(RefId);
|
||||
|
||||
/// <summary>
|
||||
/// Exception that caused the message to fail.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This property will only be populated if <see cref="ExceptronConfiguration.ThrowExceptions"/> is set to <see cref="bool.False"/>/>
|
||||
/// Exception is thrown if <see cref="ExceptronConfiguration.ThrowExceptions"/> is set to <see cref="bool.True"/>.
|
||||
/// </remarks>
|
||||
public Exception Exception { get; internal set; }
|
||||
}
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
namespace NzbDrone.Common.Exceptron.Message
|
||||
{
|
||||
internal class Frame
|
||||
{
|
||||
/// <summary>
|
||||
/// Order of current frame
|
||||
/// </summary>
|
||||
public int i { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Line number of the current frame
|
||||
/// </summary>
|
||||
public int ln { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Method name for current frame
|
||||
/// </summary>
|
||||
public string m { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Class name for current frame
|
||||
/// </summary>
|
||||
public string c { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// File name for current frame
|
||||
/// </summary>
|
||||
public string fn { get; set; }
|
||||
}
|
||||
}
|
@ -1,72 +0,0 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using NzbDrone.Common.Exceptron.fastJSON;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron
|
||||
{
|
||||
public sealed class RestClient : IRestClient
|
||||
{
|
||||
public TResponse Put<TResponse>(string url, object content) where TResponse : class ,new()
|
||||
{
|
||||
|
||||
if (content == null)
|
||||
throw new ArgumentNullException("content can not be null", "content");
|
||||
|
||||
if (string.IsNullOrEmpty(url))
|
||||
throw new ArgumentNullException("url can not be null or empty", "url");
|
||||
|
||||
Trace.WriteLine("Attempting PUT to " + url);
|
||||
|
||||
var json = JSON.Instance.ToJSON(content);
|
||||
|
||||
var bytes = Encoding.UTF8.GetBytes(json);
|
||||
var request = (HttpWebRequest)WebRequest.Create(url);
|
||||
request.Timeout = 10000;
|
||||
request.Method = "PUT";
|
||||
request.ContentType = "application/json";
|
||||
request.ContentLength = bytes.Length;
|
||||
request.Accept = "application/json";
|
||||
|
||||
var dataStream = request.GetRequestStream();
|
||||
dataStream.Write(bytes, 0, bytes.Length);
|
||||
dataStream.Close();
|
||||
|
||||
string responseContent = string.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
var webResponse = request.GetResponse();
|
||||
responseContent = ReadResponse(webResponse);
|
||||
var response = JSON.Instance.ToObject<TResponse>(responseContent);
|
||||
|
||||
return response;
|
||||
}
|
||||
catch (WebException e)
|
||||
{
|
||||
Trace.WriteLine(e.ToString());
|
||||
responseContent = ReadResponse(e.Response);
|
||||
throw new ExceptronApiException(e, responseContent);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Trace.WriteLine(responseContent);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static string ReadResponse(WebResponse webResponse)
|
||||
{
|
||||
if (webResponse == null) return string.Empty;
|
||||
|
||||
var responseStream = webResponse.GetResponseStream();
|
||||
|
||||
if (responseStream == null) return string.Empty;
|
||||
|
||||
var decodedStream = new StreamReader(responseStream, Encoding.GetEncoding(1252));
|
||||
return decodedStream.ReadToEnd();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron.fastJSON
|
||||
{
|
||||
internal class Getters
|
||||
{
|
||||
public string Name;
|
||||
public JSON.GenericGetter Getter;
|
||||
public Type propertyType;
|
||||
}
|
||||
|
||||
internal class DatasetSchema
|
||||
{
|
||||
public List<string> Info { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
@ -1,820 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron.fastJSON
|
||||
{
|
||||
|
||||
internal class JSON
|
||||
{
|
||||
public readonly static JSON Instance = new JSON();
|
||||
|
||||
private JSON()
|
||||
{
|
||||
UseSerializerExtension = false;
|
||||
SerializeNullValues = false;
|
||||
UseOptimizedDatasetSchema = false;
|
||||
UsingGlobalTypes = false;
|
||||
}
|
||||
public bool UseOptimizedDatasetSchema = true;
|
||||
public bool UseFastGuid = true;
|
||||
public bool UseSerializerExtension = true;
|
||||
public bool IndentOutput = false;
|
||||
public bool SerializeNullValues = true;
|
||||
public bool UseUTCDateTime = false;
|
||||
public bool ShowReadOnlyProperties = false;
|
||||
public bool UsingGlobalTypes = true;
|
||||
|
||||
public string ToJSON(object obj)
|
||||
{
|
||||
return ToJSON(obj, UseSerializerExtension, UseFastGuid, UseOptimizedDatasetSchema, SerializeNullValues);
|
||||
}
|
||||
|
||||
|
||||
public string ToJSON(object obj,
|
||||
bool enableSerializerExtensions,
|
||||
bool enableFastGuid,
|
||||
bool enableOptimizedDatasetSchema,
|
||||
bool serializeNullValues)
|
||||
{
|
||||
return new JSONSerializer(enableOptimizedDatasetSchema, enableFastGuid, enableSerializerExtensions, serializeNullValues, IndentOutput).ConvertToJSON(obj);
|
||||
}
|
||||
|
||||
|
||||
public T ToObject<T>(string json)
|
||||
{
|
||||
return (T)ToObject(json, typeof(T));
|
||||
}
|
||||
|
||||
|
||||
public object ToObject(string json, Type type)
|
||||
{
|
||||
var ht = new JsonParser(json).Decode() as Dictionary<string, object>;
|
||||
if (ht == null) return null;
|
||||
return ParseDictionary(ht, null, type);
|
||||
}
|
||||
|
||||
#if CUSTOMTYPE
|
||||
internal SafeDictionary<Type, Serialize> _customSerializer = new SafeDictionary<Type, Serialize>();
|
||||
internal SafeDictionary<Type, Deserialize> _customDeserializer = new SafeDictionary<Type, Deserialize>();
|
||||
|
||||
public void RegisterCustomType(Type type, Serialize serializer, Deserialize deserializer)
|
||||
{
|
||||
if (type != null && serializer != null && deserializer != null)
|
||||
{
|
||||
_customSerializer.Add(type, serializer);
|
||||
_customDeserializer.Add(type, deserializer);
|
||||
// reset property cache
|
||||
_propertycache = new SafeDictionary<string, SafeDictionary<string, myPropInfo>>();
|
||||
}
|
||||
}
|
||||
|
||||
internal bool IsTypeRegistered(Type t)
|
||||
{
|
||||
Serialize s;
|
||||
return _customSerializer.TryGetValue(t, out s);
|
||||
}
|
||||
#endif
|
||||
|
||||
#region [ PROPERTY GET SET CACHE ]
|
||||
|
||||
readonly SafeDictionary<Type, string> _tyname = new SafeDictionary<Type, string>();
|
||||
internal string GetTypeAssemblyName(Type t)
|
||||
{
|
||||
string val = "";
|
||||
if (_tyname.TryGetValue(t, out val))
|
||||
return val;
|
||||
string s = t.AssemblyQualifiedName;
|
||||
_tyname.Add(t, s);
|
||||
return s;
|
||||
}
|
||||
|
||||
readonly SafeDictionary<string, Type> _typecache = new SafeDictionary<string, Type>();
|
||||
private Type GetTypeFromCache(string typename)
|
||||
{
|
||||
Type val = null;
|
||||
if (_typecache.TryGetValue(typename, out val))
|
||||
return val;
|
||||
Type t = Type.GetType(typename);
|
||||
_typecache.Add(typename, t);
|
||||
return t;
|
||||
}
|
||||
|
||||
readonly SafeDictionary<Type, CreateObject> _constrcache = new SafeDictionary<Type, CreateObject>();
|
||||
private delegate object CreateObject();
|
||||
private object FastCreateInstance(Type objtype)
|
||||
{
|
||||
try
|
||||
{
|
||||
CreateObject c = null;
|
||||
if (_constrcache.TryGetValue(objtype, out c))
|
||||
{
|
||||
return c();
|
||||
}
|
||||
DynamicMethod dynMethod = new DynamicMethod("_", objtype, null, true);
|
||||
ILGenerator ilGen = dynMethod.GetILGenerator();
|
||||
|
||||
ilGen.Emit(OpCodes.Newobj, objtype.GetConstructor(Type.EmptyTypes));
|
||||
ilGen.Emit(OpCodes.Ret);
|
||||
c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
|
||||
_constrcache.Add(objtype, c);
|
||||
return c();
|
||||
}
|
||||
catch (Exception exc)
|
||||
{
|
||||
throw new Exception(string.Format("Failed to fast create instance for type '{0}' from assemebly '{1}'",
|
||||
objtype.FullName, objtype.AssemblyQualifiedName), exc);
|
||||
}
|
||||
}
|
||||
|
||||
private struct myPropInfo
|
||||
{
|
||||
public bool filled;
|
||||
public Type pt;
|
||||
public Type bt;
|
||||
public Type changeType;
|
||||
public bool isDictionary;
|
||||
public bool isValueType;
|
||||
public bool isGenericType;
|
||||
public bool isArray;
|
||||
public bool isByteArray;
|
||||
public bool isGuid;
|
||||
#if !SILVERLIGHT
|
||||
public bool isDataSet;
|
||||
public bool isDataTable;
|
||||
public bool isHashtable;
|
||||
#endif
|
||||
public GenericSetter setter;
|
||||
public bool isEnum;
|
||||
public bool isDateTime;
|
||||
public Type[] GenericTypes;
|
||||
public bool isInt;
|
||||
public bool isLong;
|
||||
public bool isString;
|
||||
public bool isBool;
|
||||
public bool isClass;
|
||||
public GenericGetter getter;
|
||||
public bool isStringDictionary;
|
||||
public string Name;
|
||||
#if CUSTOMTYPE
|
||||
public bool isCustomType;
|
||||
#endif
|
||||
public bool CanWrite;
|
||||
}
|
||||
|
||||
readonly SafeDictionary<string, SafeDictionary<string, myPropInfo>> _propertycache = new SafeDictionary<string, SafeDictionary<string, myPropInfo>>();
|
||||
private SafeDictionary<string, myPropInfo> Getproperties(Type type, string typename)
|
||||
{
|
||||
SafeDictionary<string, myPropInfo> sd = null;
|
||||
if (_propertycache.TryGetValue(typename, out sd))
|
||||
{
|
||||
return sd;
|
||||
}
|
||||
sd = new SafeDictionary<string, myPropInfo>();
|
||||
var pr = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
|
||||
foreach (var p in pr)
|
||||
{
|
||||
myPropInfo d = CreateMyProp(p.PropertyType, p.Name);
|
||||
d.CanWrite = p.CanWrite;
|
||||
d.setter = CreateSetMethod(p);
|
||||
d.getter = CreateGetMethod(p);
|
||||
sd.Add(p.Name, d);
|
||||
}
|
||||
|
||||
_propertycache.Add(typename, sd);
|
||||
return sd;
|
||||
}
|
||||
|
||||
private myPropInfo CreateMyProp(Type t, string name)
|
||||
{
|
||||
myPropInfo d = new myPropInfo();
|
||||
d.filled = true;
|
||||
d.CanWrite = true;
|
||||
d.pt = t;
|
||||
d.Name = name;
|
||||
d.isDictionary = t.Name.Contains("Dictionary");
|
||||
if (d.isDictionary)
|
||||
d.GenericTypes = t.GetGenericArguments();
|
||||
d.isValueType = t.IsValueType;
|
||||
d.isGenericType = t.IsGenericType;
|
||||
d.isArray = t.IsArray;
|
||||
if (d.isArray)
|
||||
d.bt = t.GetElementType();
|
||||
if (d.isGenericType)
|
||||
d.bt = t.GetGenericArguments()[0];
|
||||
d.isByteArray = t == typeof(byte[]);
|
||||
d.isGuid = (t == typeof(Guid) || t == typeof(Guid?));
|
||||
#if !SILVERLIGHT
|
||||
d.isHashtable = t == typeof(Hashtable);
|
||||
d.isDataSet = t == typeof(DataSet);
|
||||
d.isDataTable = t == typeof(DataTable);
|
||||
#endif
|
||||
|
||||
d.changeType = GetChangeType(t);
|
||||
d.isEnum = t.IsEnum;
|
||||
d.isDateTime = t == typeof(DateTime) || t == typeof(DateTime?);
|
||||
d.isInt = t == typeof(int) || t == typeof(int?);
|
||||
d.isLong = t == typeof(long) || t == typeof(long?);
|
||||
d.isString = t == typeof(string);
|
||||
d.isBool = t == typeof(bool) || t == typeof(bool?);
|
||||
d.isClass = t.IsClass;
|
||||
|
||||
if (d.isDictionary && d.GenericTypes.Length > 0 && d.GenericTypes[0] == typeof(string))
|
||||
d.isStringDictionary = true;
|
||||
|
||||
#if CUSTOMTYPE
|
||||
if (IsTypeRegistered(t))
|
||||
d.isCustomType = true;
|
||||
#endif
|
||||
return d;
|
||||
}
|
||||
|
||||
private delegate void GenericSetter(object target, object value);
|
||||
|
||||
private static GenericSetter CreateSetMethod(PropertyInfo propertyInfo)
|
||||
{
|
||||
MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
|
||||
if (setMethod == null)
|
||||
return null;
|
||||
|
||||
var arguments = new Type[2];
|
||||
arguments[0] = arguments[1] = typeof(object);
|
||||
|
||||
DynamicMethod setter = new DynamicMethod("_", typeof(void), arguments, true);
|
||||
ILGenerator il = setter.GetILGenerator();
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
|
||||
il.Emit(OpCodes.Ldarg_1);
|
||||
|
||||
if (propertyInfo.PropertyType.IsClass)
|
||||
il.Emit(OpCodes.Castclass, propertyInfo.PropertyType);
|
||||
else
|
||||
il.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
|
||||
|
||||
il.EmitCall(OpCodes.Callvirt, setMethod, null);
|
||||
il.Emit(OpCodes.Ret);
|
||||
|
||||
return (GenericSetter)setter.CreateDelegate(typeof(GenericSetter));
|
||||
}
|
||||
|
||||
internal delegate object GenericGetter(object obj);
|
||||
|
||||
|
||||
private GenericGetter CreateGetMethod(PropertyInfo propertyInfo)
|
||||
{
|
||||
MethodInfo getMethod = propertyInfo.GetGetMethod();
|
||||
if (getMethod == null)
|
||||
return null;
|
||||
|
||||
var arguments = new Type[1];
|
||||
arguments[0] = typeof(object);
|
||||
|
||||
DynamicMethod getter = new DynamicMethod("_", typeof(object), arguments, true);
|
||||
ILGenerator il = getter.GetILGenerator();
|
||||
il.Emit(OpCodes.Ldarg_0);
|
||||
il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
|
||||
il.EmitCall(OpCodes.Callvirt, getMethod, null);
|
||||
|
||||
if (!propertyInfo.PropertyType.IsClass)
|
||||
il.Emit(OpCodes.Box, propertyInfo.PropertyType);
|
||||
|
||||
il.Emit(OpCodes.Ret);
|
||||
|
||||
return (GenericGetter)getter.CreateDelegate(typeof(GenericGetter));
|
||||
}
|
||||
|
||||
readonly SafeDictionary<Type, List<Getters>> _getterscache = new SafeDictionary<Type, List<Getters>>();
|
||||
internal List<Getters> GetGetters(Type type)
|
||||
{
|
||||
List<Getters> val = null;
|
||||
if (_getterscache.TryGetValue(type, out val))
|
||||
return val;
|
||||
|
||||
var props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
|
||||
var getters = new List<Getters>();
|
||||
foreach (var p in props)
|
||||
{
|
||||
if (!p.CanWrite && ShowReadOnlyProperties == false) continue;
|
||||
|
||||
var att = p.GetCustomAttributes(typeof(XmlIgnoreAttribute), false);
|
||||
if (att != null && att.Length > 0)
|
||||
continue;
|
||||
|
||||
GenericGetter g = CreateGetMethod(p);
|
||||
if (g != null)
|
||||
{
|
||||
Getters gg = new Getters();
|
||||
gg.Name = p.Name;
|
||||
gg.Getter = g;
|
||||
gg.propertyType = p.PropertyType;
|
||||
getters.Add(gg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
_getterscache.Add(type, getters);
|
||||
return getters;
|
||||
}
|
||||
|
||||
private object ChangeType(object value, Type conversionType)
|
||||
{
|
||||
if (conversionType == typeof(int))
|
||||
return (int)CreateLong((string)value);
|
||||
|
||||
if (conversionType == typeof(long))
|
||||
return CreateLong((string)value);
|
||||
|
||||
if (conversionType == typeof(string))
|
||||
return value;
|
||||
|
||||
if (conversionType == typeof(Guid))
|
||||
return CreateGuid((string)value);
|
||||
|
||||
if (conversionType.IsEnum)
|
||||
return CreateEnum(conversionType, (string)value);
|
||||
|
||||
return Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture);
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
private object ParseDictionary(Dictionary<string, object> d, Dictionary<string, object> globaltypes, Type type)
|
||||
{
|
||||
object tn = "";
|
||||
if (d.TryGetValue("$types", out tn))
|
||||
{
|
||||
UsingGlobalTypes = true;
|
||||
globaltypes = new Dictionary<string, object>();
|
||||
foreach (var kv in (Dictionary<string, object>)tn)
|
||||
{
|
||||
globaltypes.Add((string)kv.Value, kv.Key);
|
||||
}
|
||||
}
|
||||
|
||||
bool found = d.TryGetValue("$type", out tn);
|
||||
#if !SILVERLIGHT
|
||||
if (found == false && type == typeof(object))
|
||||
{
|
||||
return CreateDataset(d, globaltypes);
|
||||
}
|
||||
#endif
|
||||
if (found)
|
||||
{
|
||||
if (UsingGlobalTypes)
|
||||
{
|
||||
object tname = "";
|
||||
if (globaltypes.TryGetValue((string)tn, out tname))
|
||||
tn = tname;
|
||||
}
|
||||
type = GetTypeFromCache((string)tn);
|
||||
}
|
||||
|
||||
if (type == null)
|
||||
throw new Exception("Cannot determine type");
|
||||
|
||||
string typename = type.FullName;
|
||||
object o = FastCreateInstance(type);
|
||||
var props = Getproperties(type, typename);
|
||||
foreach (var name in d.Keys)
|
||||
{
|
||||
if (name == "$map")
|
||||
{
|
||||
ProcessMap(o, props, (Dictionary<string, object>)d[name]);
|
||||
continue;
|
||||
}
|
||||
myPropInfo pi;
|
||||
if (props.TryGetValue(name, out pi) == false)
|
||||
continue;
|
||||
if (pi.filled)
|
||||
{
|
||||
object v = d[name];
|
||||
|
||||
if (v != null)
|
||||
{
|
||||
object oset = null;
|
||||
|
||||
if (pi.isInt)
|
||||
oset = (int)CreateLong((string)v);
|
||||
#if CUSTOMTYPE
|
||||
else if (pi.isCustomType)
|
||||
oset = CreateCustom((string)v, pi.pt);
|
||||
#endif
|
||||
else if (pi.isLong)
|
||||
oset = CreateLong((string)v);
|
||||
|
||||
else if (pi.isString)
|
||||
oset = v;
|
||||
|
||||
else if (pi.isBool)
|
||||
oset = (bool)v;
|
||||
|
||||
else if (pi.isGenericType && pi.isValueType == false && pi.isDictionary == false)
|
||||
#if SILVERLIGHT
|
||||
oset = CreateGenericList((List<object>)v, pi.pt, pi.bt, globaltypes);
|
||||
#else
|
||||
oset = CreateGenericList((ArrayList)v, pi.pt, pi.bt, globaltypes);
|
||||
#endif
|
||||
else if (pi.isByteArray)
|
||||
oset = Convert.FromBase64String((string)v);
|
||||
|
||||
else if (pi.isArray && pi.isValueType == false)
|
||||
#if SILVERLIGHT
|
||||
oset = CreateArray((List<object>)v, pi.pt, pi.bt, globaltypes);
|
||||
#else
|
||||
oset = CreateArray((ArrayList)v, pi.pt, pi.bt, globaltypes);
|
||||
#endif
|
||||
else if (pi.isGuid)
|
||||
oset = CreateGuid((string)v);
|
||||
#if !SILVERLIGHT
|
||||
else if (pi.isDataSet)
|
||||
oset = CreateDataset((Dictionary<string, object>)v, globaltypes);
|
||||
|
||||
else if (pi.isDataTable)
|
||||
oset = CreateDataTable((Dictionary<string, object>)v, globaltypes);
|
||||
#endif
|
||||
|
||||
else if (pi.isStringDictionary)
|
||||
oset = CreateStringKeyDictionary((Dictionary<string, object>)v, pi.pt, pi.GenericTypes, globaltypes);
|
||||
|
||||
#if !SILVERLIGHT
|
||||
else if (pi.isDictionary || pi.isHashtable)
|
||||
oset = CreateDictionary((ArrayList)v, pi.pt, pi.GenericTypes, globaltypes);
|
||||
#else
|
||||
else if (pi.isDictionary)
|
||||
oset = CreateDictionary((List<object>)v, pi.pt, pi.GenericTypes, globaltypes);
|
||||
#endif
|
||||
|
||||
else if (pi.isEnum)
|
||||
oset = CreateEnum(pi.pt, (string)v);
|
||||
|
||||
else if (pi.isDateTime)
|
||||
oset = CreateDateTime((string)v);
|
||||
|
||||
else if (pi.isClass && v is Dictionary<string, object>)
|
||||
oset = ParseDictionary((Dictionary<string, object>)v, globaltypes, pi.pt);
|
||||
|
||||
else if (pi.isValueType)
|
||||
oset = ChangeType(v, pi.changeType);
|
||||
|
||||
#if SILVERLIGHT
|
||||
else if (v is List<object>)
|
||||
oset = CreateArray((List<object>)v, pi.pt, typeof(object), globaltypes);
|
||||
#else
|
||||
else if (v is ArrayList)
|
||||
oset = CreateArray((ArrayList)v, pi.pt, typeof(object), globaltypes);
|
||||
#endif
|
||||
else
|
||||
oset = v;
|
||||
|
||||
if (pi.CanWrite)
|
||||
pi.setter(o, oset);
|
||||
}
|
||||
}
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
#if CUSTOMTYPE
|
||||
private object CreateCustom(string v, Type type)
|
||||
{
|
||||
Deserialize d;
|
||||
_customDeserializer.TryGetValue(type, out d);
|
||||
return d(v);
|
||||
}
|
||||
#endif
|
||||
|
||||
private void ProcessMap(object obj, SafeDictionary<string, myPropInfo> props, Dictionary<string, object> dic)
|
||||
{
|
||||
foreach (var kv in dic)
|
||||
{
|
||||
myPropInfo p = props[kv.Key];
|
||||
object o = p.getter(obj);
|
||||
Type t = Type.GetType((string)kv.Value);
|
||||
if (t == typeof(Guid))
|
||||
p.setter(obj, CreateGuid((string)o));
|
||||
}
|
||||
}
|
||||
|
||||
private long CreateLong(string s)
|
||||
{
|
||||
long num = 0;
|
||||
bool neg = false;
|
||||
foreach (var cc in s)
|
||||
{
|
||||
if (cc == '-')
|
||||
neg = true;
|
||||
else if (cc == '+')
|
||||
neg = false;
|
||||
else
|
||||
{
|
||||
num *= 10;
|
||||
num += (cc - '0');
|
||||
}
|
||||
}
|
||||
|
||||
return neg ? -num : num;
|
||||
}
|
||||
|
||||
private object CreateEnum(Type pt, string v)
|
||||
{
|
||||
// TODO : optimize create enum
|
||||
#if !SILVERLIGHT
|
||||
return Enum.Parse(pt, v);
|
||||
#else
|
||||
return Enum.Parse(pt, v, true);
|
||||
#endif
|
||||
}
|
||||
|
||||
private Guid CreateGuid(string s)
|
||||
{
|
||||
if (s.Length > 30)
|
||||
return new Guid(s);
|
||||
return new Guid(Convert.FromBase64String(s));
|
||||
}
|
||||
|
||||
private DateTime CreateDateTime(string value)
|
||||
{
|
||||
bool utc = false;
|
||||
// 0123456789012345678
|
||||
// datetime format = yyyy-MM-dd HH:mm:ss
|
||||
int year = (int)CreateLong(value.Substring(0, 4));
|
||||
int month = (int)CreateLong(value.Substring(5, 2));
|
||||
int day = (int)CreateLong(value.Substring(8, 2));
|
||||
int hour = (int)CreateLong(value.Substring(11, 2));
|
||||
int min = (int)CreateLong(value.Substring(14, 2));
|
||||
int sec = (int)CreateLong(value.Substring(17, 2));
|
||||
|
||||
if (value.EndsWith("Z"))
|
||||
utc = true;
|
||||
|
||||
if (UseUTCDateTime == false && utc == false)
|
||||
return new DateTime(year, month, day, hour, min, sec);
|
||||
return new DateTime(year, month, day, hour, min, sec, DateTimeKind.Utc).ToLocalTime();
|
||||
}
|
||||
|
||||
#if SILVERLIGHT
|
||||
private object CreateArray(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
Array col = Array.CreateInstance(bt, data.Count);
|
||||
// create an array of objects
|
||||
for (int i = 0; i < data.Count; i++)// each (object ob in data)
|
||||
{
|
||||
object ob = data[i];
|
||||
if (ob is IDictionary)
|
||||
col.SetValue(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt), i);
|
||||
else
|
||||
col.SetValue(ChangeType(ob, bt), i);
|
||||
}
|
||||
|
||||
return col;
|
||||
}
|
||||
#else
|
||||
private object CreateArray(ArrayList data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
ArrayList col = new ArrayList();
|
||||
// create an array of objects
|
||||
foreach (var ob in data)
|
||||
{
|
||||
if (ob is IDictionary)
|
||||
col.Add(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt));
|
||||
else
|
||||
col.Add(ChangeType(ob, bt));
|
||||
}
|
||||
return col.ToArray(bt);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#if SILVERLIGHT
|
||||
private object CreateGenericList(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
#else
|
||||
private object CreateGenericList(ArrayList data, Type pt, Type bt, Dictionary<string, object> globalTypes)
|
||||
#endif
|
||||
{
|
||||
IList col = (IList)FastCreateInstance(pt);
|
||||
// create an array of objects
|
||||
foreach (var ob in data)
|
||||
{
|
||||
if (ob is IDictionary)
|
||||
col.Add(ParseDictionary((Dictionary<string, object>)ob, globalTypes, bt));
|
||||
#if SILVERLIGHT
|
||||
else if (ob is List<object>)
|
||||
col.Add(((List<object>)ob).ToArray());
|
||||
#else
|
||||
else if (ob is ArrayList)
|
||||
col.Add(((ArrayList)ob).ToArray());
|
||||
#endif
|
||||
else
|
||||
col.Add(ChangeType(ob, bt));
|
||||
}
|
||||
return col;
|
||||
}
|
||||
|
||||
private object CreateStringKeyDictionary(Dictionary<string, object> reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
var col = (IDictionary)FastCreateInstance(pt);
|
||||
Type t1 = null;
|
||||
Type t2 = null;
|
||||
if (types != null)
|
||||
{
|
||||
t1 = types[0];
|
||||
t2 = types[1];
|
||||
}
|
||||
|
||||
foreach (var values in reader)
|
||||
{
|
||||
var key = values.Key;//ChangeType(values.Key, t1);
|
||||
object val = null;
|
||||
if (values.Value is Dictionary<string, object>)
|
||||
val = ParseDictionary((Dictionary<string, object>)values.Value, globalTypes, t2);
|
||||
else
|
||||
val = ChangeType(values.Value, t2);
|
||||
col.Add(key, val);
|
||||
}
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
#if SILVERLIGHT
|
||||
private object CreateDictionary(List<object> reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
|
||||
#else
|
||||
private object CreateDictionary(ArrayList reader, Type pt, Type[] types, Dictionary<string, object> globalTypes)
|
||||
#endif
|
||||
{
|
||||
IDictionary col = (IDictionary)FastCreateInstance(pt);
|
||||
Type t1 = null;
|
||||
Type t2 = null;
|
||||
if (types != null)
|
||||
{
|
||||
t1 = types[0];
|
||||
t2 = types[1];
|
||||
}
|
||||
|
||||
foreach (Dictionary<string, object> values in reader)
|
||||
{
|
||||
object key = values["k"];
|
||||
object val = values["v"];
|
||||
|
||||
if (key is Dictionary<string, object>)
|
||||
key = ParseDictionary((Dictionary<string, object>)key, globalTypes, t1);
|
||||
else
|
||||
key = ChangeType(key, t1);
|
||||
|
||||
if (val is Dictionary<string, object>)
|
||||
val = ParseDictionary((Dictionary<string, object>)val, globalTypes, t2);
|
||||
else
|
||||
val = ChangeType(val, t2);
|
||||
|
||||
col.Add(key, val);
|
||||
}
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
private Type GetChangeType(Type conversionType)
|
||||
{
|
||||
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
|
||||
return conversionType.GetGenericArguments()[0];
|
||||
|
||||
return conversionType;
|
||||
}
|
||||
#if !SILVERLIGHT
|
||||
private DataSet CreateDataset(Dictionary<string, object> reader, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
DataSet ds = new DataSet();
|
||||
ds.EnforceConstraints = false;
|
||||
ds.BeginInit();
|
||||
|
||||
// read dataset schema here
|
||||
ReadSchema(reader, ds, globalTypes);
|
||||
|
||||
foreach (var pair in reader)
|
||||
{
|
||||
if (pair.Key == "$type" || pair.Key == "$schema") continue;
|
||||
|
||||
ArrayList rows = (ArrayList)pair.Value;
|
||||
if (rows == null) continue;
|
||||
|
||||
DataTable dt = ds.Tables[pair.Key];
|
||||
ReadDataTable(rows, dt);
|
||||
}
|
||||
|
||||
ds.EndInit();
|
||||
|
||||
return ds;
|
||||
}
|
||||
|
||||
private void ReadSchema(Dictionary<string, object> reader, DataSet ds, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
var schema = reader["$schema"];
|
||||
|
||||
if (schema is string)
|
||||
{
|
||||
TextReader tr = new StringReader((string)schema);
|
||||
ds.ReadXmlSchema(tr);
|
||||
}
|
||||
else
|
||||
{
|
||||
DatasetSchema ms = (DatasetSchema)ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema));
|
||||
ds.DataSetName = ms.Name;
|
||||
for (int i = 0; i < ms.Info.Count; i += 3)
|
||||
{
|
||||
if (ds.Tables.Contains(ms.Info[i]) == false)
|
||||
ds.Tables.Add(ms.Info[i]);
|
||||
ds.Tables[ms.Info[i]].Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ReadDataTable(ArrayList rows, DataTable dt)
|
||||
{
|
||||
dt.BeginInit();
|
||||
dt.BeginLoadData();
|
||||
var guidcols = new List<int>();
|
||||
var datecol = new List<int>();
|
||||
|
||||
foreach (DataColumn c in dt.Columns)
|
||||
{
|
||||
if (c.DataType == typeof(Guid) || c.DataType == typeof(Guid?))
|
||||
guidcols.Add(c.Ordinal);
|
||||
if (UseUTCDateTime && (c.DataType == typeof(DateTime) || c.DataType == typeof(DateTime?)))
|
||||
datecol.Add(c.Ordinal);
|
||||
}
|
||||
|
||||
foreach (ArrayList row in rows)
|
||||
{
|
||||
var v = new object[row.Count];
|
||||
row.CopyTo(v, 0);
|
||||
foreach (var i in guidcols)
|
||||
{
|
||||
string s = (string)v[i];
|
||||
if (s != null && s.Length < 36)
|
||||
v[i] = new Guid(Convert.FromBase64String(s));
|
||||
}
|
||||
if (UseUTCDateTime)
|
||||
{
|
||||
foreach (var i in datecol)
|
||||
{
|
||||
string s = (string)v[i];
|
||||
if (s != null)
|
||||
v[i] = CreateDateTime(s);
|
||||
}
|
||||
}
|
||||
dt.Rows.Add(v);
|
||||
}
|
||||
|
||||
dt.EndLoadData();
|
||||
dt.EndInit();
|
||||
}
|
||||
|
||||
DataTable CreateDataTable(Dictionary<string, object> reader, Dictionary<string, object> globalTypes)
|
||||
{
|
||||
var dt = new DataTable();
|
||||
|
||||
// read dataset schema here
|
||||
var schema = reader["$schema"];
|
||||
|
||||
if (schema is string)
|
||||
{
|
||||
TextReader tr = new StringReader((string)schema);
|
||||
dt.ReadXmlSchema(tr);
|
||||
}
|
||||
else
|
||||
{
|
||||
var ms = (DatasetSchema)ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema));
|
||||
dt.TableName = ms.Info[0];
|
||||
for (int i = 0; i < ms.Info.Count; i += 3)
|
||||
{
|
||||
dt.Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2]));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var pair in reader)
|
||||
{
|
||||
if (pair.Key == "$type" || pair.Key == "$schema")
|
||||
continue;
|
||||
|
||||
var rows = (ArrayList)pair.Value;
|
||||
if (rows == null)
|
||||
continue;
|
||||
|
||||
if (!dt.TableName.Equals(pair.Key, StringComparison.InvariantCultureIgnoreCase))
|
||||
continue;
|
||||
|
||||
ReadDataTable(rows, dt);
|
||||
}
|
||||
|
||||
return dt;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
@ -1,409 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron.fastJSON
|
||||
{
|
||||
/// <summary>
|
||||
/// This class encodes and decodes JSON strings.
|
||||
/// Spec. details, see http://www.json.org/
|
||||
///
|
||||
/// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
|
||||
/// All numbers are parsed to doubles.
|
||||
/// </summary>
|
||||
internal class JsonParser
|
||||
{
|
||||
enum Token
|
||||
{
|
||||
None = -1, // Used to denote no Lookahead available
|
||||
Curly_Open,
|
||||
Curly_Close,
|
||||
Squared_Open,
|
||||
Squared_Close,
|
||||
Colon,
|
||||
Comma,
|
||||
String,
|
||||
Number,
|
||||
True,
|
||||
False,
|
||||
Null
|
||||
}
|
||||
|
||||
readonly char[] json;
|
||||
readonly StringBuilder s = new StringBuilder();
|
||||
Token lookAheadToken = Token.None;
|
||||
int index;
|
||||
|
||||
internal JsonParser(string json)
|
||||
{
|
||||
this.json = json.ToCharArray();
|
||||
}
|
||||
|
||||
public object Decode()
|
||||
{
|
||||
return ParseValue();
|
||||
}
|
||||
|
||||
private Dictionary<string, object> ParseObject()
|
||||
{
|
||||
var table = new Dictionary<string, object>();
|
||||
|
||||
ConsumeToken(); // {
|
||||
|
||||
while (true)
|
||||
{
|
||||
switch (LookAhead())
|
||||
{
|
||||
|
||||
case Token.Comma:
|
||||
ConsumeToken();
|
||||
break;
|
||||
|
||||
case Token.Curly_Close:
|
||||
ConsumeToken();
|
||||
return table;
|
||||
|
||||
default:
|
||||
{
|
||||
|
||||
// name
|
||||
string name = ParseString();
|
||||
|
||||
// :
|
||||
if (NextToken() != Token.Colon)
|
||||
{
|
||||
throw new Exception("Expected colon at index " + index);
|
||||
}
|
||||
|
||||
// value
|
||||
object value = ParseValue();
|
||||
|
||||
table[name] = value;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if SILVERLIGHT
|
||||
private List<object> ParseArray()
|
||||
{
|
||||
List<object> array = new List<object>();
|
||||
#else
|
||||
private ArrayList ParseArray()
|
||||
{
|
||||
ArrayList array = new ArrayList();
|
||||
#endif
|
||||
ConsumeToken(); // [
|
||||
|
||||
while (true)
|
||||
{
|
||||
switch (LookAhead())
|
||||
{
|
||||
|
||||
case Token.Comma:
|
||||
ConsumeToken();
|
||||
break;
|
||||
|
||||
case Token.Squared_Close:
|
||||
ConsumeToken();
|
||||
return array;
|
||||
|
||||
default:
|
||||
{
|
||||
array.Add(ParseValue());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private object ParseValue()
|
||||
{
|
||||
switch (LookAhead())
|
||||
{
|
||||
case Token.Number:
|
||||
return ParseNumber();
|
||||
|
||||
case Token.String:
|
||||
return ParseString();
|
||||
|
||||
case Token.Curly_Open:
|
||||
return ParseObject();
|
||||
|
||||
case Token.Squared_Open:
|
||||
return ParseArray();
|
||||
|
||||
case Token.True:
|
||||
ConsumeToken();
|
||||
return true;
|
||||
|
||||
case Token.False:
|
||||
ConsumeToken();
|
||||
return false;
|
||||
|
||||
case Token.Null:
|
||||
ConsumeToken();
|
||||
return null;
|
||||
}
|
||||
|
||||
throw new Exception("Unrecognized token at index" + index);
|
||||
}
|
||||
|
||||
private string ParseString()
|
||||
{
|
||||
ConsumeToken(); // "
|
||||
|
||||
s.Length = 0;
|
||||
|
||||
int runIndex = -1;
|
||||
|
||||
while (index < json.Length)
|
||||
{
|
||||
var c = json[index++];
|
||||
|
||||
if (c == '"')
|
||||
{
|
||||
if (runIndex != -1)
|
||||
{
|
||||
if (s.Length == 0)
|
||||
return new string(json, runIndex, index - runIndex - 1);
|
||||
|
||||
s.Append(json, runIndex, index - runIndex - 1);
|
||||
}
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
if (c != '\\')
|
||||
{
|
||||
if (runIndex == -1)
|
||||
runIndex = index - 1;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (index == json.Length) break;
|
||||
|
||||
if (runIndex != -1)
|
||||
{
|
||||
s.Append(json, runIndex, index - runIndex - 1);
|
||||
runIndex = -1;
|
||||
}
|
||||
|
||||
switch (json[index++])
|
||||
{
|
||||
case '"':
|
||||
s.Append('"');
|
||||
break;
|
||||
|
||||
case '\\':
|
||||
s.Append('\\');
|
||||
break;
|
||||
|
||||
case '/':
|
||||
s.Append('/');
|
||||
break;
|
||||
|
||||
case 'b':
|
||||
s.Append('\b');
|
||||
break;
|
||||
|
||||
case 'f':
|
||||
s.Append('\f');
|
||||
break;
|
||||
|
||||
case 'n':
|
||||
s.Append('\n');
|
||||
break;
|
||||
|
||||
case 'r':
|
||||
s.Append('\r');
|
||||
break;
|
||||
|
||||
case 't':
|
||||
s.Append('\t');
|
||||
break;
|
||||
|
||||
case 'u':
|
||||
{
|
||||
int remainingLength = json.Length - index;
|
||||
if (remainingLength < 4) break;
|
||||
|
||||
// parse the 32 bit hex into an integer codepoint
|
||||
uint codePoint = ParseUnicode(json[index], json[index + 1], json[index + 2], json[index + 3]);
|
||||
s.Append((char)codePoint);
|
||||
|
||||
// skip 4 chars
|
||||
index += 4;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("Unexpectedly reached end of string");
|
||||
}
|
||||
|
||||
private uint ParseSingleChar(char c1, uint multipliyer)
|
||||
{
|
||||
uint p1 = 0;
|
||||
if (c1 >= '0' && c1 <= '9')
|
||||
p1 = (uint)(c1 - '0') * multipliyer;
|
||||
else if (c1 >= 'A' && c1 <= 'F')
|
||||
p1 = (uint)((c1 - 'A') + 10) * multipliyer;
|
||||
else if (c1 >= 'a' && c1 <= 'f')
|
||||
p1 = (uint)((c1 - 'a') + 10) * multipliyer;
|
||||
return p1;
|
||||
}
|
||||
|
||||
private uint ParseUnicode(char c1, char c2, char c3, char c4)
|
||||
{
|
||||
uint p1 = ParseSingleChar(c1, 0x1000);
|
||||
uint p2 = ParseSingleChar(c2, 0x100);
|
||||
uint p3 = ParseSingleChar(c3, 0x10);
|
||||
uint p4 = ParseSingleChar(c4, 1);
|
||||
|
||||
return p1 + p2 + p3 + p4;
|
||||
}
|
||||
|
||||
private string ParseNumber()
|
||||
{
|
||||
ConsumeToken();
|
||||
|
||||
// Need to start back one place because the first digit is also a token and would have been consumed
|
||||
var startIndex = index - 1;
|
||||
|
||||
do
|
||||
{
|
||||
var c = json[index];
|
||||
|
||||
if ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E')
|
||||
{
|
||||
if (++index == json.Length) throw new Exception("Unexpected end of string whilst parsing number");
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
} while (true);
|
||||
|
||||
return new string(json, startIndex, index - startIndex);
|
||||
}
|
||||
|
||||
private Token LookAhead()
|
||||
{
|
||||
if (lookAheadToken != Token.None) return lookAheadToken;
|
||||
|
||||
return lookAheadToken = NextTokenCore();
|
||||
}
|
||||
|
||||
private void ConsumeToken()
|
||||
{
|
||||
lookAheadToken = Token.None;
|
||||
}
|
||||
|
||||
private Token NextToken()
|
||||
{
|
||||
var result = lookAheadToken != Token.None ? lookAheadToken : NextTokenCore();
|
||||
|
||||
lookAheadToken = Token.None;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private Token NextTokenCore()
|
||||
{
|
||||
char c;
|
||||
|
||||
// Skip past whitespace
|
||||
do
|
||||
{
|
||||
c = json[index];
|
||||
|
||||
if (c > ' ') break;
|
||||
if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break;
|
||||
|
||||
} while (++index < json.Length);
|
||||
|
||||
if (index == json.Length)
|
||||
{
|
||||
throw new Exception("Reached end of string unexpectedly");
|
||||
}
|
||||
|
||||
c = json[index];
|
||||
|
||||
index++;
|
||||
|
||||
//if (c >= '0' && c <= '9')
|
||||
// return Token.Number;
|
||||
|
||||
switch (c)
|
||||
{
|
||||
case '{':
|
||||
return Token.Curly_Open;
|
||||
|
||||
case '}':
|
||||
return Token.Curly_Close;
|
||||
|
||||
case '[':
|
||||
return Token.Squared_Open;
|
||||
|
||||
case ']':
|
||||
return Token.Squared_Close;
|
||||
|
||||
case ',':
|
||||
return Token.Comma;
|
||||
|
||||
case '"':
|
||||
return Token.String;
|
||||
|
||||
case '0': case '1': case '2': case '3': case '4':
|
||||
case '5': case '6': case '7': case '8': case '9':
|
||||
case '-': case '+': case '.':
|
||||
return Token.Number;
|
||||
|
||||
case ':':
|
||||
return Token.Colon;
|
||||
|
||||
case 'f':
|
||||
if (json.Length - index >= 4 &&
|
||||
json[index + 0] == 'a' &&
|
||||
json[index + 1] == 'l' &&
|
||||
json[index + 2] == 's' &&
|
||||
json[index + 3] == 'e')
|
||||
{
|
||||
index += 4;
|
||||
return Token.False;
|
||||
}
|
||||
break;
|
||||
|
||||
case 't':
|
||||
if (json.Length - index >= 3 &&
|
||||
json[index + 0] == 'r' &&
|
||||
json[index + 1] == 'u' &&
|
||||
json[index + 2] == 'e')
|
||||
{
|
||||
index += 3;
|
||||
return Token.True;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'n':
|
||||
if (json.Length - index >= 3 &&
|
||||
json[index + 0] == 'u' &&
|
||||
json[index + 1] == 'l' &&
|
||||
json[index + 2] == 'l')
|
||||
{
|
||||
index += 3;
|
||||
return Token.Null;
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
throw new Exception("Could not find token at index " + --index);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,519 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron.fastJSON
|
||||
{
|
||||
internal class JSONSerializer
|
||||
{
|
||||
private readonly StringBuilder _output = new StringBuilder();
|
||||
readonly bool useMinimalDataSetSchema;
|
||||
readonly bool fastguid = true;
|
||||
readonly bool useExtension = true;
|
||||
readonly bool serializeNulls = true;
|
||||
readonly int _MAX_DEPTH = 10;
|
||||
readonly bool _Indent;
|
||||
readonly bool _useGlobalTypes = true;
|
||||
int _current_depth;
|
||||
private readonly Dictionary<string, int> _globalTypes = new Dictionary<string, int>();
|
||||
|
||||
internal JSONSerializer(bool UseMinimalDataSetSchema, bool UseFastGuid, bool UseExtensions, bool SerializeNulls, bool IndentOutput)
|
||||
{
|
||||
useMinimalDataSetSchema = UseMinimalDataSetSchema;
|
||||
fastguid = UseFastGuid;
|
||||
useExtension = UseExtensions;
|
||||
_Indent = IndentOutput;
|
||||
serializeNulls = SerializeNulls;
|
||||
if (useExtension == false)
|
||||
_useGlobalTypes = false;
|
||||
}
|
||||
|
||||
internal string ConvertToJSON(object obj)
|
||||
{
|
||||
WriteValue(obj);
|
||||
|
||||
string str = "";
|
||||
if (_useGlobalTypes)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("{\"$types\":{");
|
||||
bool pendingSeparator = false;
|
||||
foreach (var kv in _globalTypes)
|
||||
{
|
||||
if (pendingSeparator) sb.Append(',');
|
||||
pendingSeparator = true;
|
||||
sb.Append("\"");
|
||||
sb.Append(kv.Key);
|
||||
sb.Append("\":\"");
|
||||
sb.Append(kv.Value);
|
||||
sb.Append("\"");
|
||||
}
|
||||
sb.Append("},");
|
||||
str = sb + _output.ToString();
|
||||
}
|
||||
else
|
||||
str = _output.ToString();
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
private void WriteValue(object obj)
|
||||
{
|
||||
if (obj == null || obj is DBNull)
|
||||
_output.Append("null");
|
||||
|
||||
else if (obj is string || obj is char)
|
||||
WriteString((string)obj);
|
||||
|
||||
else if (obj is Guid)
|
||||
WriteGuid((Guid)obj);
|
||||
|
||||
else if (obj is bool)
|
||||
_output.Append(((bool)obj) ? "true" : "false"); // conform to standard
|
||||
|
||||
else if (
|
||||
obj is int || obj is long || obj is double ||
|
||||
obj is decimal || obj is float ||
|
||||
obj is byte || obj is short ||
|
||||
obj is sbyte || obj is ushort ||
|
||||
obj is uint || obj is ulong
|
||||
)
|
||||
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
|
||||
|
||||
else if (obj is DateTime)
|
||||
WriteDateTime((DateTime)obj);
|
||||
|
||||
else if (obj is IDictionary && obj.GetType().IsGenericType && obj.GetType().GetGenericArguments()[0] == typeof(string))
|
||||
WriteStringDictionary((IDictionary)obj);
|
||||
|
||||
else if (obj is IDictionary)
|
||||
WriteDictionary((IDictionary)obj);
|
||||
#if !SILVERLIGHT
|
||||
else if (obj is DataSet)
|
||||
WriteDataset((DataSet)obj);
|
||||
|
||||
else if (obj is DataTable)
|
||||
WriteDataTable((DataTable)obj);
|
||||
#endif
|
||||
else if (obj is byte[])
|
||||
WriteBytes((byte[])obj);
|
||||
|
||||
else if (obj is Array || obj is IList || obj is ICollection)
|
||||
WriteArray((IEnumerable)obj);
|
||||
|
||||
else if (obj is Enum)
|
||||
WriteEnum((Enum)obj);
|
||||
|
||||
#if CUSTOMTYPE
|
||||
else if (JSON.Instance.IsTypeRegistered(obj.GetType()))
|
||||
WriteCustom(obj);
|
||||
#endif
|
||||
else
|
||||
WriteObject(obj);
|
||||
}
|
||||
|
||||
#if CUSTOMTYPE
|
||||
private void WriteCustom(object obj)
|
||||
{
|
||||
Serialize s;
|
||||
JSON.Instance._customSerializer.TryGetValue(obj.GetType(), out s);
|
||||
WriteStringFast(s(obj));
|
||||
}
|
||||
#endif
|
||||
|
||||
private void WriteEnum(Enum e)
|
||||
{
|
||||
// TODO : optimize enum write
|
||||
WriteStringFast(e.ToString());
|
||||
}
|
||||
|
||||
private void WriteGuid(Guid g)
|
||||
{
|
||||
if (fastguid == false)
|
||||
WriteStringFast(g.ToString());
|
||||
else
|
||||
WriteBytes(g.ToByteArray());
|
||||
}
|
||||
|
||||
private void WriteBytes(byte[] bytes)
|
||||
{
|
||||
#if !SILVERLIGHT
|
||||
WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None));
|
||||
#else
|
||||
WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length));
|
||||
#endif
|
||||
}
|
||||
|
||||
private void WriteDateTime(DateTime dateTime)
|
||||
{
|
||||
// datetime format standard : yyyy-MM-dd HH:mm:ss
|
||||
DateTime dt = dateTime;
|
||||
if (JSON.Instance.UseUTCDateTime)
|
||||
dt = dateTime.ToUniversalTime();
|
||||
|
||||
_output.Append("\"");
|
||||
_output.Append(dt.Year.ToString("0000", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append("-");
|
||||
_output.Append(dt.Month.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append("-");
|
||||
_output.Append(dt.Day.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append(" ");
|
||||
_output.Append(dt.Hour.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append(":");
|
||||
_output.Append(dt.Minute.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
_output.Append(":");
|
||||
_output.Append(dt.Second.ToString("00", NumberFormatInfo.InvariantInfo));
|
||||
|
||||
if (JSON.Instance.UseUTCDateTime)
|
||||
_output.Append("Z");
|
||||
|
||||
_output.Append("\"");
|
||||
}
|
||||
#if !SILVERLIGHT
|
||||
private DatasetSchema GetSchema(DataTable ds)
|
||||
{
|
||||
if (ds == null) return null;
|
||||
|
||||
DatasetSchema m = new DatasetSchema();
|
||||
m.Info = new List<string>();
|
||||
m.Name = ds.TableName;
|
||||
|
||||
foreach (DataColumn c in ds.Columns)
|
||||
{
|
||||
m.Info.Add(ds.TableName);
|
||||
m.Info.Add(c.ColumnName);
|
||||
m.Info.Add(c.DataType.ToString());
|
||||
}
|
||||
// TODO : serialize relations and constraints here
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
private DatasetSchema GetSchema(DataSet ds)
|
||||
{
|
||||
if (ds == null) return null;
|
||||
|
||||
DatasetSchema m = new DatasetSchema();
|
||||
m.Info = new List<string>();
|
||||
m.Name = ds.DataSetName;
|
||||
|
||||
foreach (DataTable t in ds.Tables)
|
||||
{
|
||||
foreach (DataColumn c in t.Columns)
|
||||
{
|
||||
m.Info.Add(t.TableName);
|
||||
m.Info.Add(c.ColumnName);
|
||||
m.Info.Add(c.DataType.ToString());
|
||||
}
|
||||
}
|
||||
// TODO : serialize relations and constraints here
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
private string GetXmlSchema(DataTable dt)
|
||||
{
|
||||
using (var writer = new StringWriter())
|
||||
{
|
||||
dt.WriteXmlSchema(writer);
|
||||
return dt.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteDataset(DataSet ds)
|
||||
{
|
||||
_output.Append('{');
|
||||
if (useExtension)
|
||||
{
|
||||
WritePair("$schema", useMinimalDataSetSchema ? (object)GetSchema(ds) : ds.GetXmlSchema());
|
||||
_output.Append(',');
|
||||
}
|
||||
bool tablesep = false;
|
||||
foreach (DataTable table in ds.Tables)
|
||||
{
|
||||
if (tablesep) _output.Append(",");
|
||||
tablesep = true;
|
||||
WriteDataTableData(table);
|
||||
}
|
||||
// end dataset
|
||||
_output.Append('}');
|
||||
}
|
||||
|
||||
private void WriteDataTableData(DataTable table)
|
||||
{
|
||||
_output.Append('\"');
|
||||
_output.Append(table.TableName);
|
||||
_output.Append("\":[");
|
||||
DataColumnCollection cols = table.Columns;
|
||||
bool rowseparator = false;
|
||||
foreach (DataRow row in table.Rows)
|
||||
{
|
||||
if (rowseparator) _output.Append(",");
|
||||
rowseparator = true;
|
||||
_output.Append('[');
|
||||
|
||||
bool pendingSeperator = false;
|
||||
foreach (DataColumn column in cols)
|
||||
{
|
||||
if (pendingSeperator) _output.Append(',');
|
||||
WriteValue(row[column]);
|
||||
pendingSeperator = true;
|
||||
}
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
void WriteDataTable(DataTable dt)
|
||||
{
|
||||
_output.Append('{');
|
||||
if (useExtension)
|
||||
{
|
||||
WritePair("$schema", useMinimalDataSetSchema ? (object)GetSchema(dt) : GetXmlSchema(dt));
|
||||
_output.Append(',');
|
||||
}
|
||||
|
||||
WriteDataTableData(dt);
|
||||
|
||||
// end datatable
|
||||
_output.Append('}');
|
||||
}
|
||||
#endif
|
||||
bool _firstWritten;
|
||||
private void WriteObject(object obj)
|
||||
{
|
||||
Indent();
|
||||
if (_useGlobalTypes == false)
|
||||
_output.Append('{');
|
||||
else
|
||||
{
|
||||
if (_firstWritten)
|
||||
_output.Append("{");
|
||||
}
|
||||
_firstWritten = true;
|
||||
_current_depth++;
|
||||
if (_current_depth > _MAX_DEPTH)
|
||||
throw new Exception("Serializer encountered maximum depth of " + _MAX_DEPTH);
|
||||
|
||||
|
||||
var map = new Dictionary<string, string>();
|
||||
Type t = obj.GetType();
|
||||
bool append = false;
|
||||
if (useExtension)
|
||||
{
|
||||
if (_useGlobalTypes == false)
|
||||
WritePairFast("$type", JSON.Instance.GetTypeAssemblyName(t));
|
||||
else
|
||||
{
|
||||
int dt = 0;
|
||||
string ct = JSON.Instance.GetTypeAssemblyName(t);
|
||||
if (_globalTypes.TryGetValue(ct, out dt) == false)
|
||||
{
|
||||
dt = _globalTypes.Count + 1;
|
||||
_globalTypes.Add(ct, dt);
|
||||
}
|
||||
WritePairFast("$type", dt.ToString());
|
||||
}
|
||||
append = true;
|
||||
}
|
||||
|
||||
var g = JSON.Instance.GetGetters(t);
|
||||
foreach (var p in g)
|
||||
{
|
||||
if (append)
|
||||
_output.Append(',');
|
||||
object o = p.Getter(obj);
|
||||
if ((o == null || o is DBNull) && serializeNulls == false)
|
||||
append = false;
|
||||
else
|
||||
{
|
||||
WritePair(p.Name, o);
|
||||
if (o != null && useExtension)
|
||||
{
|
||||
Type tt = o.GetType();
|
||||
if (tt == typeof(object))
|
||||
map.Add(p.Name, tt.ToString());
|
||||
}
|
||||
append = true;
|
||||
}
|
||||
}
|
||||
if (map.Count > 0 && useExtension)
|
||||
{
|
||||
_output.Append(",\"$map\":");
|
||||
WriteStringDictionary(map);
|
||||
}
|
||||
_current_depth--;
|
||||
Indent();
|
||||
_output.Append('}');
|
||||
_current_depth--;
|
||||
|
||||
}
|
||||
|
||||
private void Indent()
|
||||
{
|
||||
Indent(false);
|
||||
}
|
||||
|
||||
private void Indent(bool dec)
|
||||
{
|
||||
if (_Indent)
|
||||
{
|
||||
_output.Append("\r\n");
|
||||
for (int i = 0; i < _current_depth - (dec ? 1 : 0); i++)
|
||||
_output.Append("\t");
|
||||
}
|
||||
}
|
||||
|
||||
private void WritePairFast(string name, string value)
|
||||
{
|
||||
if ((value == null) && serializeNulls == false)
|
||||
return;
|
||||
Indent();
|
||||
WriteStringFast(name);
|
||||
|
||||
_output.Append(':');
|
||||
|
||||
WriteStringFast(value);
|
||||
}
|
||||
|
||||
private void WritePair(string name, object value)
|
||||
{
|
||||
if ((value == null || value is DBNull) && serializeNulls == false)
|
||||
return;
|
||||
Indent();
|
||||
WriteStringFast(name);
|
||||
|
||||
_output.Append(':');
|
||||
|
||||
WriteValue(value);
|
||||
}
|
||||
|
||||
private void WriteArray(IEnumerable array)
|
||||
{
|
||||
Indent();
|
||||
_output.Append('[');
|
||||
|
||||
bool pendingSeperator = false;
|
||||
|
||||
foreach (var obj in array)
|
||||
{
|
||||
Indent();
|
||||
if (pendingSeperator) _output.Append(',');
|
||||
|
||||
WriteValue(obj);
|
||||
|
||||
pendingSeperator = true;
|
||||
}
|
||||
Indent();
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
private void WriteStringDictionary(IDictionary dic)
|
||||
{
|
||||
Indent();
|
||||
_output.Append('{');
|
||||
|
||||
bool pendingSeparator = false;
|
||||
|
||||
foreach (DictionaryEntry entry in dic)
|
||||
{
|
||||
if (pendingSeparator) _output.Append(',');
|
||||
|
||||
WritePair((string)entry.Key, entry.Value);
|
||||
|
||||
pendingSeparator = true;
|
||||
}
|
||||
Indent();
|
||||
_output.Append('}');
|
||||
}
|
||||
|
||||
private void WriteDictionary(IDictionary dic)
|
||||
{
|
||||
Indent();
|
||||
_output.Append('[');
|
||||
|
||||
bool pendingSeparator = false;
|
||||
|
||||
foreach (DictionaryEntry entry in dic)
|
||||
{
|
||||
if (pendingSeparator) _output.Append(',');
|
||||
Indent();
|
||||
_output.Append('{');
|
||||
WritePair("k", entry.Key);
|
||||
_output.Append(",");
|
||||
WritePair("v", entry.Value);
|
||||
Indent();
|
||||
_output.Append('}');
|
||||
|
||||
pendingSeparator = true;
|
||||
}
|
||||
Indent();
|
||||
_output.Append(']');
|
||||
}
|
||||
|
||||
private void WriteStringFast(string s)
|
||||
{
|
||||
//Indent();
|
||||
_output.Append('\"');
|
||||
_output.Append(s);
|
||||
_output.Append('\"');
|
||||
}
|
||||
|
||||
private void WriteString(string s)
|
||||
{
|
||||
//Indent();
|
||||
_output.Append('\"');
|
||||
|
||||
int runIndex = -1;
|
||||
|
||||
for (var index = 0; index < s.Length; ++index)
|
||||
{
|
||||
var c = s[index];
|
||||
|
||||
if (c >= ' ' && c < 128 && c != '\"' && c != '\\')
|
||||
{
|
||||
if (runIndex == -1)
|
||||
{
|
||||
runIndex = index;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (runIndex != -1)
|
||||
{
|
||||
_output.Append(s, runIndex, index - runIndex);
|
||||
runIndex = -1;
|
||||
}
|
||||
|
||||
switch (c)
|
||||
{
|
||||
case '\t': _output.Append("\\t"); break;
|
||||
case '\r': _output.Append("\\r"); break;
|
||||
case '\n': _output.Append("\\n"); break;
|
||||
case '"':
|
||||
case '\\': _output.Append('\\'); _output.Append(c); break;
|
||||
default:
|
||||
_output.Append("\\u");
|
||||
_output.Append(((int)c).ToString("X4", NumberFormatInfo.InvariantInfo));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (runIndex != -1)
|
||||
{
|
||||
_output.Append(s, runIndex, s.Length - runIndex);
|
||||
}
|
||||
|
||||
_output.Append('\"');
|
||||
}
|
||||
}
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
//http://fastjson.codeplex.com/
|
||||
//http://fastjson.codeplex.com/license
|
||||
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace NzbDrone.Common.Exceptron.fastJSON
|
||||
{
|
||||
internal class SafeDictionary<TKey, TValue>
|
||||
{
|
||||
private readonly object _Padlock = new object();
|
||||
private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();
|
||||
|
||||
|
||||
internal bool TryGetValue(TKey key, out TValue value)
|
||||
{
|
||||
return _Dictionary.TryGetValue(key, out value);
|
||||
}
|
||||
|
||||
internal TValue this[TKey key] => _Dictionary[key];
|
||||
|
||||
internal void Add(TKey key, TValue value)
|
||||
{
|
||||
lock (_Padlock)
|
||||
{
|
||||
if (_Dictionary.ContainsKey(key) == false)
|
||||
_Dictionary.Add(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,87 +0,0 @@
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
||||
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
@ -1,4 +1,5 @@
|
||||
using NLog;
|
||||
using NLog;
|
||||
using NLog.Fluent;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Extensions
|
||||
{
|
@ -0,0 +1,55 @@
|
||||
using System.Linq;
|
||||
using NLog;
|
||||
using NLog.Fluent;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Extensions
|
||||
{
|
||||
public static class SentryLoggerExtensions
|
||||
{
|
||||
public static readonly Logger SentryLogger = LogManager.GetLogger("Sentry");
|
||||
|
||||
public static LogBuilder SentryFingerprint(this LogBuilder logBuilder, params string[] fingerprint)
|
||||
{
|
||||
return logBuilder.Property("Sentry", fingerprint);
|
||||
}
|
||||
|
||||
public static LogBuilder WriteSentryDebug(this LogBuilder logBuilder, params string[] fingerprint)
|
||||
{
|
||||
return LogSentryMessage(logBuilder, LogLevel.Debug, fingerprint);
|
||||
}
|
||||
|
||||
public static LogBuilder WriteSentryInfo(this LogBuilder logBuilder, params string[] fingerprint)
|
||||
{
|
||||
return LogSentryMessage(logBuilder, LogLevel.Info, fingerprint);
|
||||
}
|
||||
|
||||
public static LogBuilder WriteSentryWarn(this LogBuilder logBuilder, params string[] fingerprint)
|
||||
{
|
||||
return LogSentryMessage(logBuilder, LogLevel.Warn, fingerprint);
|
||||
}
|
||||
|
||||
public static LogBuilder WriteSentryError(this LogBuilder logBuilder, params string[] fingerprint)
|
||||
{
|
||||
return LogSentryMessage(logBuilder, LogLevel.Error, fingerprint);
|
||||
}
|
||||
|
||||
private static LogBuilder LogSentryMessage(LogBuilder logBuilder, LogLevel level, string[] fingerprint)
|
||||
{
|
||||
SentryLogger.Log(level)
|
||||
.CopyLogEvent(logBuilder.LogEventInfo)
|
||||
.SentryFingerprint(fingerprint)
|
||||
.Write();
|
||||
|
||||
return logBuilder.Property("Sentry", null);
|
||||
}
|
||||
|
||||
private static LogBuilder CopyLogEvent(this LogBuilder logBuilder, LogEventInfo logEvent)
|
||||
{
|
||||
return logBuilder.LoggerName(logEvent.LoggerName)
|
||||
.TimeStamp(logEvent.TimeStamp)
|
||||
.Message(logEvent.Message, logEvent.Parameters)
|
||||
.Properties(logEvent.Properties.ToDictionary(v => v.Key, v => v.Value))
|
||||
.Exception(logEvent.Exception);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,12 +1,13 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using LogentriesNLog;
|
||||
using System.Linq;
|
||||
using NLog;
|
||||
using NLog.Config;
|
||||
using NLog.Targets;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Common.Extensions;
|
||||
using NzbDrone.Common.Instrumentation.Sentry;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation
|
||||
{
|
||||
@ -38,13 +39,11 @@ public static void Register(IStartupContext startupContext, bool updateApp, bool
|
||||
RegisterDebugger();
|
||||
}
|
||||
|
||||
//Disabling for now - until its fixed or we yank it out
|
||||
//RegisterExceptron();
|
||||
RegisterSentry(updateApp);
|
||||
|
||||
if (updateApp)
|
||||
{
|
||||
RegisterUpdateFile(appFolderInfo);
|
||||
RegisterLogEntries();
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -59,17 +58,47 @@ public static void Register(IStartupContext startupContext, bool updateApp, bool
|
||||
LogManager.ReconfigExistingLoggers();
|
||||
}
|
||||
|
||||
private static void RegisterLogEntries()
|
||||
public static void UnRegisterRemoteLoggers()
|
||||
{
|
||||
var target = new LogentriesTarget();
|
||||
target.Name = "logentriesTarget";
|
||||
target.Token = "7688c9ac-015f-45c7-bfee-73f370f5f380";
|
||||
target.LogHostname = true;
|
||||
target.Debug = false;
|
||||
var sentryRules = LogManager.Configuration.LoggingRules.Where(r => r.Targets.Any(t => t.Name == "sentryTarget"));
|
||||
|
||||
var loggingRule = new LoggingRule("*", LogLevel.Info, target);
|
||||
LogManager.Configuration.AddTarget("logentries", target);
|
||||
foreach (var rules in sentryRules)
|
||||
{
|
||||
rules.Targets.Clear();
|
||||
}
|
||||
|
||||
LogManager.ReconfigExistingLoggers();
|
||||
}
|
||||
|
||||
private static void RegisterSentry(bool updateClient)
|
||||
{
|
||||
string dsn;
|
||||
|
||||
if (updateClient)
|
||||
{
|
||||
dsn = "https://89744ec1d2a14a36856f601bdf78e69f@sentry.io/1523535";
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
dsn = RuntimeInfo.IsProduction
|
||||
? "https://fd45b801b1af445f919dbca8ca0ead89@sentry.io/1485284"
|
||||
: "https://e4e7bfd3cc0e45a4814613a096c79cc3@sentry.io/1523529";
|
||||
}
|
||||
|
||||
var target = new SentryTarget(dsn)
|
||||
{
|
||||
Name = "sentryTarget",
|
||||
Layout = "${message}"
|
||||
};
|
||||
|
||||
var loggingRule = new LoggingRule("*", updateClient ? LogLevel.Trace : LogLevel.Warn, target);
|
||||
LogManager.Configuration.AddTarget("sentryTarget", target);
|
||||
LogManager.Configuration.LoggingRules.Add(loggingRule);
|
||||
|
||||
// Events logged to Sentry go only to Sentry.
|
||||
var loggingRuleSentry = new LoggingRule("Sentry", LogLevel.Debug, target) { Final = true };
|
||||
LogManager.Configuration.LoggingRules.Insert(0, loggingRuleSentry);
|
||||
}
|
||||
|
||||
private static void RegisterDebugger()
|
||||
@ -83,7 +112,6 @@ private static void RegisterDebugger()
|
||||
LogManager.Configuration.LoggingRules.Add(loggingRule);
|
||||
}
|
||||
|
||||
|
||||
private static void RegisterConsole()
|
||||
{
|
||||
var level = LogLevel.Trace;
|
||||
@ -99,7 +127,7 @@ private static void RegisterConsole()
|
||||
LogManager.Configuration.LoggingRules.Add(loggingRule);
|
||||
}
|
||||
|
||||
const string FILE_LOG_LAYOUT = @"${date:format=yy-M-d HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}[v${assembly-version}] ${exception:format=ToString}${newline}}";
|
||||
private const string FILE_LOG_LAYOUT = @"${date:format=yy-M-d HH\:mm\:ss.f}|${level}|${logger}|${message}${onexception:inner=${newline}${newline}[v${assembly-version}] ${exception:format=ToString}${newline}}";
|
||||
|
||||
private static void RegisterAppFile(IAppFolderInfo appFolderInfo)
|
||||
{
|
||||
@ -108,7 +136,7 @@ private static void RegisterAppFile(IAppFolderInfo appFolderInfo)
|
||||
RegisterAppFile(appFolderInfo, "appFileTrace", "radarr.trace.txt", 50, LogLevel.Off);
|
||||
}
|
||||
|
||||
private static LoggingRule RegisterAppFile(IAppFolderInfo appFolderInfo, string name, string fileName, int maxArchiveFiles, LogLevel minLogLevel)
|
||||
private static void RegisterAppFile(IAppFolderInfo appFolderInfo, string name, string fileName, int maxArchiveFiles, LogLevel minLogLevel)
|
||||
{
|
||||
var fileTarget = new NzbDroneFileTarget();
|
||||
|
||||
@ -129,8 +157,6 @@ private static LoggingRule RegisterAppFile(IAppFolderInfo appFolderInfo, string
|
||||
|
||||
LogManager.Configuration.AddTarget(name, fileTarget);
|
||||
LogManager.Configuration.LoggingRules.Add(loggingRule);
|
||||
|
||||
return loggingRule;
|
||||
}
|
||||
|
||||
private static void RegisterUpdateFile(IAppFolderInfo appFolderInfo)
|
||||
|
85
src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs
Normal file
85
src/NzbDrone.Common/Instrumentation/Sentry/SentryCleanser.cs
Normal file
@ -0,0 +1,85 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Sentry;
|
||||
using Sentry.Protocol;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Sentry
|
||||
{
|
||||
public static class SentryCleanser
|
||||
{
|
||||
public static SentryEvent CleanseEvent(SentryEvent sentryEvent)
|
||||
{
|
||||
try
|
||||
{
|
||||
sentryEvent.Message = CleanseLogMessage.Cleanse(sentryEvent.Message);
|
||||
|
||||
if (sentryEvent.Fingerprint != null)
|
||||
{
|
||||
var fingerprint = sentryEvent.Fingerprint.Select(x => CleanseLogMessage.Cleanse(x)).ToList();
|
||||
sentryEvent.SetFingerprint(fingerprint);
|
||||
}
|
||||
|
||||
if (sentryEvent.Extra != null)
|
||||
{
|
||||
var extras = sentryEvent.Extra.ToDictionary(x => x.Key, y => (object)CleanseLogMessage.Cleanse((string)y.Value));
|
||||
sentryEvent.SetExtras(extras);
|
||||
}
|
||||
|
||||
foreach (var exception in sentryEvent.SentryExceptions)
|
||||
{
|
||||
exception.Value = CleanseLogMessage.Cleanse(exception.Value);
|
||||
foreach (var frame in exception.Stacktrace.Frames)
|
||||
{
|
||||
frame.FileName = ShortenPath(frame.FileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
return sentryEvent;
|
||||
}
|
||||
|
||||
public static Breadcrumb CleanseBreadcrumb(Breadcrumb b)
|
||||
{
|
||||
try
|
||||
{
|
||||
var message = CleanseLogMessage.Cleanse(b.Message);
|
||||
var data = b.Data?.ToDictionary(x => x.Key, y => CleanseLogMessage.Cleanse(y.Value));
|
||||
return new Breadcrumb(message, b.Type, data, b.Category, b.Level);
|
||||
}
|
||||
catch(Exception)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
private static string ShortenPath(string path)
|
||||
{
|
||||
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// the paths in the stacktrace depend on where it was compiled,
|
||||
// not the current OS
|
||||
var rootDirs = new [] { "\\src\\", "/src/" };
|
||||
foreach (var rootDir in rootDirs)
|
||||
{
|
||||
var index = path.IndexOf(rootDir, StringComparison.Ordinal);
|
||||
|
||||
if (index > 0)
|
||||
{
|
||||
return path.Substring(index + rootDir.Length - 1);
|
||||
}
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
}
|
||||
}
|
38
src/NzbDrone.Common/Instrumentation/Sentry/SentryDebounce.cs
Normal file
38
src/NzbDrone.Common/Instrumentation/Sentry/SentryDebounce.cs
Normal file
@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using NzbDrone.Common.Cache;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Sentry
|
||||
{
|
||||
public class SentryDebounce
|
||||
{
|
||||
private readonly TimeSpan _ttl;
|
||||
private readonly Cached<bool> _cache;
|
||||
|
||||
public SentryDebounce()
|
||||
{
|
||||
_cache = new Cached<bool>();
|
||||
_ttl = RuntimeInfo.IsProduction ? TimeSpan.FromHours(1) : TimeSpan.FromSeconds(10);
|
||||
}
|
||||
|
||||
public bool Allowed(IEnumerable<string> fingerPrint)
|
||||
{
|
||||
var key = string.Join("|", fingerPrint);
|
||||
var exists = _cache.Find(key);
|
||||
|
||||
if (exists)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_cache.Set(key, true, _ttl);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_cache.Clear();
|
||||
}
|
||||
}
|
||||
}
|
280
src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs
Normal file
280
src/NzbDrone.Common/Instrumentation/Sentry/SentryTarget.cs
Normal file
@ -0,0 +1,280 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using NLog;
|
||||
using NLog.Common;
|
||||
using NLog.Targets;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using Sentry;
|
||||
using Sentry.Protocol;
|
||||
|
||||
namespace NzbDrone.Common.Instrumentation.Sentry
|
||||
{
|
||||
[Target("Sentry")]
|
||||
public class SentryTarget : TargetWithLayout
|
||||
{
|
||||
// use string and not Type so we don't need a reference to the project
|
||||
// where these are defined
|
||||
private static readonly HashSet<string> FilteredExceptionTypeNames = new HashSet<string> {
|
||||
// UnauthorizedAccessExceptions will just be user configuration issues
|
||||
"UnauthorizedAccessException",
|
||||
// Filter out people stuck in boot loops
|
||||
"CorruptDatabaseException",
|
||||
// This also filters some people in boot loops
|
||||
"TinyIoCResolutionException"
|
||||
};
|
||||
|
||||
public static readonly List<string> FilteredExceptionMessages = new List<string> {
|
||||
// Swallow the many, many exceptions flowing through from Jackett
|
||||
"Jackett.Common.IndexerException",
|
||||
// Fix openflixr being stupid with permissions
|
||||
"openflixr"
|
||||
};
|
||||
|
||||
// exception types in this list will additionally have the exception message added to the
|
||||
// sentry fingerprint. Make sure that this message doesn't vary by exception
|
||||
// (e.g. containing a path or a url) so that the sentry grouping is sensible
|
||||
private static readonly HashSet<string> IncludeExceptionMessageTypes = new HashSet<string> {
|
||||
"SQLiteException"
|
||||
};
|
||||
|
||||
private static readonly IDictionary<LogLevel, SentryLevel> LoggingLevelMap = new Dictionary<LogLevel, SentryLevel>
|
||||
{
|
||||
{LogLevel.Debug, SentryLevel.Debug},
|
||||
{LogLevel.Error, SentryLevel.Error},
|
||||
{LogLevel.Fatal, SentryLevel.Fatal},
|
||||
{LogLevel.Info, SentryLevel.Info},
|
||||
{LogLevel.Trace, SentryLevel.Debug},
|
||||
{LogLevel.Warn, SentryLevel.Warning},
|
||||
};
|
||||
|
||||
private static readonly IDictionary<LogLevel, BreadcrumbLevel> BreadcrumbLevelMap = new Dictionary<LogLevel, BreadcrumbLevel>
|
||||
{
|
||||
{LogLevel.Debug, BreadcrumbLevel.Debug},
|
||||
{LogLevel.Error, BreadcrumbLevel.Error},
|
||||
{LogLevel.Fatal, BreadcrumbLevel.Critical},
|
||||
{LogLevel.Info, BreadcrumbLevel.Info},
|
||||
{LogLevel.Trace, BreadcrumbLevel.Debug},
|
||||
{LogLevel.Warn, BreadcrumbLevel.Warning},
|
||||
};
|
||||
|
||||
private readonly IDisposable _sdk;
|
||||
private bool _disposed;
|
||||
|
||||
private readonly SentryDebounce _debounce;
|
||||
private bool _unauthorized;
|
||||
|
||||
public bool FilterEvents { get; set; }
|
||||
public string UpdateBranch { get; set; }
|
||||
public Version DatabaseVersion { get; set; }
|
||||
public int DatabaseMigration { get; set; }
|
||||
|
||||
public SentryTarget(string dsn)
|
||||
{
|
||||
_sdk = SentrySdk.Init(o =>
|
||||
{
|
||||
o.Dsn = new Dsn(dsn);
|
||||
o.AttachStacktrace = true;
|
||||
o.MaxBreadcrumbs = 200;
|
||||
o.SendDefaultPii = true;
|
||||
o.Debug = false;
|
||||
o.DiagnosticsLevel = SentryLevel.Debug;
|
||||
o.Release = BuildInfo.Release;
|
||||
o.BeforeSend = x => SentryCleanser.CleanseEvent(x);
|
||||
o.BeforeBreadcrumb = x => SentryCleanser.CleanseBreadcrumb(x);
|
||||
});
|
||||
|
||||
SentrySdk.ConfigureScope(scope =>
|
||||
{
|
||||
scope.User = new User {
|
||||
Username = HashUtil.AnonymousToken()
|
||||
};
|
||||
|
||||
scope.SetTag("osfamily", OsInfo.Os.ToString());
|
||||
scope.SetTag("runtime", PlatformInfo.PlatformName);
|
||||
scope.SetTag("culture", Thread.CurrentThread.CurrentCulture.Name);
|
||||
scope.SetTag("branch", BuildInfo.Branch);
|
||||
scope.SetTag("version", BuildInfo.Version.ToString());
|
||||
scope.SetTag("production", RuntimeInfo.IsProduction.ToString());
|
||||
});
|
||||
|
||||
_debounce = new SentryDebounce();
|
||||
|
||||
// initialize to true and reconfigure later
|
||||
// Otherwise it will default to false and any errors occuring
|
||||
// before config file gets read will not be filtered
|
||||
FilterEvents = true;
|
||||
}
|
||||
|
||||
private void OnError(Exception ex)
|
||||
{
|
||||
var webException = ex as WebException;
|
||||
|
||||
if (webException != null)
|
||||
{
|
||||
var response = webException.Response as HttpWebResponse;
|
||||
var statusCode = response?.StatusCode;
|
||||
if (statusCode == HttpStatusCode.Unauthorized)
|
||||
{
|
||||
_unauthorized = true;
|
||||
_debounce.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
InternalLogger.Error(ex, "Unable to send error to Sentry");
|
||||
}
|
||||
|
||||
private static List<string> GetFingerPrint(LogEventInfo logEvent)
|
||||
{
|
||||
if (logEvent.Properties.ContainsKey("Sentry"))
|
||||
{
|
||||
return ((string[])logEvent.Properties["Sentry"]).ToList();
|
||||
}
|
||||
|
||||
var fingerPrint = new List<string>
|
||||
{
|
||||
logEvent.Level.ToString(),
|
||||
logEvent.LoggerName,
|
||||
logEvent.Message
|
||||
};
|
||||
|
||||
var ex = logEvent.Exception;
|
||||
|
||||
if (ex != null)
|
||||
{
|
||||
fingerPrint.Add(ex.GetType().FullName);
|
||||
fingerPrint.Add(ex.TargetSite.ToString());
|
||||
if (ex.InnerException != null)
|
||||
{
|
||||
fingerPrint.Add(ex.InnerException.GetType().FullName);
|
||||
}
|
||||
else if (IncludeExceptionMessageTypes.Contains(ex.GetType().Name))
|
||||
{
|
||||
fingerPrint.Add(ex?.Message);
|
||||
}
|
||||
}
|
||||
|
||||
return fingerPrint;
|
||||
}
|
||||
|
||||
public bool IsSentryMessage(LogEventInfo logEvent)
|
||||
{
|
||||
if (logEvent.Properties.ContainsKey("Sentry"))
|
||||
{
|
||||
return logEvent.Properties["Sentry"] != null;
|
||||
}
|
||||
|
||||
if (logEvent.Level >= LogLevel.Error && logEvent.Exception != null)
|
||||
{
|
||||
if (FilterEvents)
|
||||
{
|
||||
if (FilteredExceptionTypeNames.Contains(logEvent.Exception.GetType().Name))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (FilteredExceptionMessages.Any(x => logEvent.Exception.Message.Contains(x)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
protected override void Write(LogEventInfo logEvent)
|
||||
{
|
||||
if (_unauthorized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
SentrySdk.AddBreadcrumb(logEvent.FormattedMessage, logEvent.LoggerName, level: BreadcrumbLevelMap[logEvent.Level]);
|
||||
|
||||
// don't report non-critical events without exceptions
|
||||
if (!IsSentryMessage(logEvent))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var fingerPrint = GetFingerPrint(logEvent);
|
||||
if (!_debounce.Allowed(fingerPrint))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var extras = logEvent.Properties.ToDictionary(x => x.Key.ToString(), x => (object)x.Value.ToString());
|
||||
extras.Remove("Sentry");
|
||||
|
||||
if (logEvent.Exception != null)
|
||||
{
|
||||
foreach (DictionaryEntry data in logEvent.Exception.Data)
|
||||
{
|
||||
extras.Add(data.Key.ToString(), data.Value.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
var sentryEvent = new SentryEvent(logEvent.Exception)
|
||||
{
|
||||
Level = LoggingLevelMap[logEvent.Level],
|
||||
Logger = logEvent.LoggerName,
|
||||
Message = logEvent.FormattedMessage,
|
||||
Environment = UpdateBranch
|
||||
};
|
||||
|
||||
sentryEvent.SetExtras(extras);
|
||||
sentryEvent.SetFingerprint(fingerPrint);
|
||||
|
||||
// this can't be in the constructor as at that point OsInfo won't have
|
||||
// populated these values yet
|
||||
var osName = Environment.GetEnvironmentVariable("OS_NAME");
|
||||
var osVersion = Environment.GetEnvironmentVariable("OS_VERSION");
|
||||
var isDocker = Environment.GetEnvironmentVariable("OS_IS_DOCKER");
|
||||
var runTimeVersion = Environment.GetEnvironmentVariable("RUNTIME_VERSION");
|
||||
|
||||
sentryEvent.SetTag("os_name", osName);
|
||||
sentryEvent.SetTag("os_version", $"{osName} {osVersion}");
|
||||
sentryEvent.SetTag("is_docker", isDocker);
|
||||
sentryEvent.SetTag("runtime_version", $"{PlatformInfo.PlatformName} {runTimeVersion}");
|
||||
sentryEvent.SetTag("sqlite_version", $"{DatabaseVersion}");
|
||||
sentryEvent.SetTag("database_migration", $"{DatabaseMigration}");
|
||||
|
||||
SentrySdk.CaptureEvent(sentryEvent);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
OnError(e);
|
||||
}
|
||||
}
|
||||
|
||||
// https://stackoverflow.com/questions/2496311/implementing-idisposable-on-a-subclass-when-the-parent-also-implements-idisposab
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
// Only do something if we're not already disposed
|
||||
if (_disposed)
|
||||
{
|
||||
// If disposing == true, we're being called from a call to base.Dispose(). In this case, we Dispose() our logger
|
||||
// If we're being called from a finalizer, our logger will get finalized as well, so no need to do anything.
|
||||
if (disposing)
|
||||
{
|
||||
_sdk?.Dispose();
|
||||
}
|
||||
// Flag us as disposed. This allows us to handle multiple calls to Dispose() as well as ObjectDisposedException
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
// This should always be safe to call multiple times!
|
||||
// We could include it in the check for disposed above, but I left it out to demonstrate that it's safe
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
}
|
@ -53,16 +53,33 @@
|
||||
<Reference Include="Org.Mentalis, Version=1.0.0.1, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\DotNet4.SocksProxy.1.3.4.0\lib\net40\Org.Mentalis.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Sentry, Version=1.2.0.0, Culture=neutral, PublicKeyToken=fba2ec45388e2af0, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Sentry.1.2.0\lib\net461\Sentry.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Sentry.PlatformAbstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=fba2ec45388e2af0, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Sentry.PlatformAbstractions.1.0.0\lib\net45\Sentry.PlatformAbstractions.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Sentry.Protocol, Version=1.0.6.0, Culture=neutral, PublicKeyToken=fba2ec45388e2af0, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Sentry.Protocol.1.0.6\lib\net46\Sentry.Protocol.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="SocksWebProxy, Version=1.3.4.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\DotNet4.SocksProxy.1.3.4.0\lib\net40\SocksWebProxy.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Collections.Immutable, Version=1.2.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Collections.Immutable.1.5.0\lib\netstandard2.0\System.Collections.Immutable.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Configuration" />
|
||||
<Reference Include="System.Configuration.Install" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Drawing" />
|
||||
<Reference Include="System.IO.Compression" />
|
||||
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Runtime.Serialization" />
|
||||
<Reference Include="System.ServiceModel" />
|
||||
<Reference Include="System.ServiceProcess" />
|
||||
@ -71,6 +88,7 @@
|
||||
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51">
|
||||
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\portable-net40+sl4+win8+wp8\System.ValueTuple.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Web" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
</ItemGroup>
|
||||
@ -140,22 +158,6 @@
|
||||
<Compile Include="EnvironmentInfo\StartupContext.cs" />
|
||||
<Compile Include="Exceptions\NotParentException.cs" />
|
||||
<Compile Include="Exceptions\NzbDroneException.cs" />
|
||||
<Compile Include="Exceptron\Configuration\ExceptronConfiguration.cs" />
|
||||
<Compile Include="Exceptron\ExceptionData.cs" />
|
||||
<Compile Include="Exceptron\ExceptionSeverity.cs" />
|
||||
<Compile Include="Exceptron\ExceptronApiException.cs" />
|
||||
<Compile Include="Exceptron\ExceptronClient.cs" />
|
||||
<Compile Include="Exceptron\fastJSON\Getters.cs" />
|
||||
<Compile Include="Exceptron\fastJSON\JSON.cs" />
|
||||
<Compile Include="Exceptron\fastJSON\JsonParser.cs" />
|
||||
<Compile Include="Exceptron\fastJSON\JsonSerializer.cs" />
|
||||
<Compile Include="Exceptron\fastJSON\SafeDictionary.cs" />
|
||||
<Compile Include="Exceptron\IExceptronClient.cs" />
|
||||
<Compile Include="Exceptron\IRestClient.cs" />
|
||||
<Compile Include="Exceptron\Message\ExceptionReport.cs" />
|
||||
<Compile Include="Exceptron\Message\ExceptionResponse.cs" />
|
||||
<Compile Include="Exceptron\Message\Frame.cs" />
|
||||
<Compile Include="Exceptron\RestClient.cs" />
|
||||
<Compile Include="Expansive\CircularReferenceException.cs" />
|
||||
<Compile Include="Expansive\Expansive.cs" />
|
||||
<Compile Include="Expansive\PatternStyle.cs" />
|
||||
@ -210,11 +212,15 @@
|
||||
<Compile Include="Http\UserAgentBuilder.cs" />
|
||||
<Compile Include="Instrumentation\CleanseLogMessage.cs" />
|
||||
<Compile Include="Instrumentation\CleansingJsonVisitor.cs" />
|
||||
<Compile Include="Instrumentation\Extensions\LoggerProgressExtensions.cs" />
|
||||
<Compile Include="Instrumentation\Extensions\LoggerExtensions.cs" />
|
||||
<Compile Include="Instrumentation\Extensions\SentryLoggerExtensions.cs" />
|
||||
<Compile Include="Instrumentation\GlobalExceptionHandlers.cs" />
|
||||
<Compile Include="Instrumentation\LogEventExtensions.cs" />
|
||||
<Compile Include="Instrumentation\NzbDroneFileTarget.cs" />
|
||||
<Compile Include="Instrumentation\NzbDroneLogger.cs" />
|
||||
<Compile Include="Instrumentation\Sentry\SentryCleanser.cs" />
|
||||
<Compile Include="Instrumentation\Sentry\SentryDebounce.cs" />
|
||||
<Compile Include="Instrumentation\Sentry\SentryTarget.cs" />
|
||||
<Compile Include="Instrumentation\VersionLayoutRenderer.cs" />
|
||||
<Compile Include="Extensions\LevenstheinExtensions.cs" />
|
||||
<Compile Include="Messaging\IEvent.cs" />
|
||||
@ -258,7 +264,6 @@
|
||||
<EmbeddedResource Include="EnsureThat\Resources\ExceptionMessages.resx" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="Exceptron\fastJSON\license.txt" />
|
||||
<Content Include="Expansive\license.txt" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
@ -1,11 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<runtime>
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0"/>
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/></startup></configuration>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /></startup></configuration>
|
||||
|
@ -4,5 +4,10 @@
|
||||
<package id="ICSharpCode.SharpZipLib.Patched" version="0.86.5" targetFramework="net461" />
|
||||
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net461" />
|
||||
<package id="NLog" version="4.5.0-rc06" targetFramework="net461" />
|
||||
<package id="Sentry" version="1.2.0" targetFramework="net461" />
|
||||
<package id="Sentry.PlatformAbstractions" version="1.0.0" targetFramework="net461" />
|
||||
<package id="Sentry.Protocol" version="1.0.6" targetFramework="net461" />
|
||||
<package id="System.Collections.Immutable" version="1.5.0" targetFramework="net461" />
|
||||
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net461" />
|
||||
<package id="System.ValueTuple" version="4.5.0" targetFramework="net461" />
|
||||
</packages>
|
@ -15,7 +15,7 @@ public void should_return_int_when_saving_int_to_db()
|
||||
{
|
||||
var i = 5;
|
||||
|
||||
Subject.ToDB(5).Should().Be(5);
|
||||
Subject.ToDB(i).Should().Be(5);
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
@ -17,6 +17,6 @@ public AnalyticsService(IConfigFileProvider configFileProvider)
|
||||
_configFileProvider = configFileProvider;
|
||||
}
|
||||
|
||||
public bool IsEnabled => _configFileProvider.AnalyticsEnabled && RuntimeInfo.IsProduction;
|
||||
public bool IsEnabled => _configFileProvider.AnalyticsEnabled;
|
||||
}
|
||||
}
|
@ -1,15 +1,23 @@
|
||||
<?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.1"/></startup>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /></startup>
|
||||
<runtime>
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0"/>
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="FluentMigrator" publicKeyToken="aacfc7de5acabf05" culture="neutral"/>
|
||||
<bindingRedirect oldVersion="0.0.0.0-1.3.1.0" newVersion="1.3.1.0"/>
|
||||
<assemblyIdentity name="FluentMigrator" publicKeyToken="aacfc7de5acabf05" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-1.3.1.0" newVersion="1.3.1.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
|
@ -364,6 +364,11 @@ public void HandleAsync(ApplicationStartedEvent message)
|
||||
{
|
||||
EnsureDefaultConfigFile();
|
||||
DeleteOldValues();
|
||||
|
||||
if (!AnalyticsEnabled)
|
||||
{
|
||||
NzbDroneLogger.UnRegisterRemoteLoggers();
|
||||
}
|
||||
}
|
||||
|
||||
public void Execute(ResetApiKeyCommand message)
|
||||
|
@ -154,6 +154,7 @@ public static string FormatAudioCodec(MediaInfoModel mediaInfo, string sceneName
|
||||
|
||||
Logger.Debug()
|
||||
.Message("Unknown audio format: '{0}' in '{1}'.", string.Join(", ", audioFormat, audioCodecID, audioProfile, audioCodecLibrary), sceneName)
|
||||
.WriteSentryWarn("UnknownAudioFormat", mediaInfo.ContainerFormat, audioFormat, audioCodecID)
|
||||
.Write();
|
||||
|
||||
return audioFormat;
|
||||
@ -330,7 +331,10 @@ public static string FormatVideoCodec(MediaInfoModel mediaInfo, string sceneName
|
||||
return "XviD";
|
||||
}
|
||||
|
||||
Logger.Debug("Unknown video format: '{0}' in '{1}'.", string.Join(", ", videoFormat, videoCodecID, videoProfile, videoCodecLibrary), sceneName);
|
||||
Logger.Debug()
|
||||
.Message("Unknown video format: '{0}' in '{1}'.", string.Join(", ", videoFormat, videoCodecID, videoProfile, videoCodecLibrary), sceneName)
|
||||
.WriteSentryWarn("UnknownVideoFormat", mediaInfo.ContainerFormat, videoFormat, videoCodecID)
|
||||
.Write();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
@ -4,7 +4,6 @@
|
||||
using System.Linq;
|
||||
using NLog;
|
||||
using NzbDrone.Common.Disk;
|
||||
using NzbDrone.Common.Exceptron;
|
||||
using NzbDrone.Common.Extensions;
|
||||
using NzbDrone.Common.Instrumentation.Extensions;
|
||||
using NzbDrone.Core.Configuration;
|
||||
|
@ -94,20 +94,16 @@ public System.Linq.Expressions.Expression<Func<Movie, bool>> ConstructFilterExpr
|
||||
{
|
||||
case "released":
|
||||
return v => v.Status == MovieStatusType.Released;
|
||||
break;
|
||||
case "inCinemas":
|
||||
return v => v.Status == MovieStatusType.InCinemas;
|
||||
break;
|
||||
case "announced":
|
||||
return v => v.Status == MovieStatusType.Announced;
|
||||
break;
|
||||
case "available":
|
||||
return v => v.Monitored == true &&
|
||||
((v.MinimumAvailability == MovieStatusType.Released && v.Status >= MovieStatusType.Released) ||
|
||||
(v.MinimumAvailability == MovieStatusType.InCinemas && v.Status >= MovieStatusType.InCinemas) ||
|
||||
(v.MinimumAvailability == MovieStatusType.Announced && v.Status >= MovieStatusType.Announced) ||
|
||||
(v.MinimumAvailability == MovieStatusType.PreDB && v.Status >= MovieStatusType.Released || v.HasPreDBEntry == true));
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if (FilterKey == "downloaded")
|
||||
|
@ -36,6 +36,14 @@
|
||||
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
</configuration>
|
||||
|
@ -14,6 +14,14 @@
|
||||
<assemblyIdentity name="Microsoft.Practices.ServiceLocation" publicKeyToken="31bf3856ad364e35" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /></startup></configuration>
|
||||
|
@ -22,6 +22,14 @@
|
||||
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /></startup></configuration>
|
||||
|
@ -6,6 +6,14 @@
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
</configuration>
|
@ -18,6 +18,14 @@
|
||||
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /></startup></configuration>
|
||||
|
@ -33,6 +33,14 @@
|
||||
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /></startup></configuration>
|
||||
|
@ -43,7 +43,6 @@ public void Backup()
|
||||
_diskProvider.CreateFolder(backupFolderAppData);
|
||||
}
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
_diskTransferService.TransferFile(_appFolderInfo.GetConfigPath(), _appFolderInfo.GetUpdateBackupConfigFile(), TransferMode.Copy);
|
||||
|
@ -24,7 +24,7 @@ public AppType GetAppType()
|
||||
{
|
||||
if (OsInfo.IsNotWindows)
|
||||
{
|
||||
//Tehcnically it is the console, but it has been renamed for mono (Linux/OS X)
|
||||
// Technically it is the console, but it has been renamed for mono (Linux/OS X)
|
||||
return AppType.Normal;
|
||||
}
|
||||
|
||||
|
@ -1,17 +1,25 @@
|
||||
<?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.1"/>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
|
||||
</startup>
|
||||
<runtime>
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="NLog" publicKeyToken="5120e14c03d0593c" culture="neutral"/>
|
||||
<bindingRedirect oldVersion="0.0.0.0-2.0.1.0" newVersion="2.0.1.0"/>
|
||||
<assemblyIdentity name="NLog" publicKeyToken="5120e14c03d0593c" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-2.0.1.0" newVersion="2.0.1.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0"/>
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
|
@ -22,6 +22,14 @@
|
||||
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /></startup></configuration>
|
||||
|
@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<runtime>
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
@ -6,6 +6,14 @@
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
</configuration>
|
@ -18,6 +18,14 @@
|
||||
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /></startup></configuration>
|
||||
|
@ -2,6 +2,7 @@
|
||||
using System.Text;
|
||||
using Nancy;
|
||||
using Nancy.Responses;
|
||||
using NzbDrone.Common;
|
||||
using NzbDrone.Common.EnvironmentInfo;
|
||||
using NzbDrone.Core.Analytics;
|
||||
using NzbDrone.Core.Configuration;
|
||||
@ -63,6 +64,7 @@ private string GetContent()
|
||||
builder.AppendLine($" version: '{BuildInfo.Version.ToString()}',");
|
||||
builder.AppendLine($" branch: '{_configFileProvider.Branch.ToLower()}',");
|
||||
builder.AppendLine($" analytics: {_analyticsService.IsEnabled.ToString().ToLowerInvariant()},");
|
||||
builder.AppendLine($" userHash: '{HashUtil.AnonymousToken()}',");
|
||||
builder.AppendLine($" urlBase: '{_urlBase}',");
|
||||
builder.AppendLine($" isProduction: {RuntimeInfo.IsProduction.ToString().ToLowerInvariant()}");
|
||||
builder.AppendLine("};");
|
||||
|
@ -14,6 +14,14 @@
|
||||
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.2.0" newVersion="4.0.2.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
</configuration>
|
@ -1,7 +1,7 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 15
|
||||
VisualStudioVersion = 15.0.27130.2010
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.29025.244
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.Console", "NzbDrone.Console\NzbDrone.Console.csproj", "{3DCA7B58-B8B3-49AC-9D9E-56F4A0460976}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
@ -47,9 +47,6 @@ EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.Update", "NzbDrone.Update\NzbDrone.Update.csproj", "{4CCC53CD-8D5E-4CC4-97D2-5C9312AC2BD7}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.Common", "NzbDrone.Common\NzbDrone.Common.csproj", "{F2BE0FDF-6E47-4827-A420-DD4EF82407F8}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB} = {9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{1E6B3CBE-1578-41C1-9BF9-78D818740BE9}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
@ -84,13 +81,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.Mono.Test", "NzbDr
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonoTorrent", "MonoTorrent\MonoTorrent.csproj", "{411A9E0E-FDC6-4E25-828A-0C2CD1CD96F8}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LogentriesCore", "LogentriesCore\LogentriesCore.csproj", "{90D6E9FC-7B88-4E1B-B018-8FA742274558}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LogentriesNLog", "LogentriesNLog\LogentriesNLog.csproj", "{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{90D6E9FC-7B88-4E1B-B018-8FA742274558} = {90D6E9FC-7B88-4E1B-B018-8FA742274558}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CurlSharp", "ExternalModules\CurlSharp\CurlSharp\CurlSharp.csproj", "{74420A79-CC16-442C-8B1E-7C1B913844F0}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Radarr.Http", "Radarr.Http\Radarr.Http.csproj", "{C5953DAB-89DB-46D9-A401-D620F54B776E}"
|
||||
@ -253,18 +243,6 @@ Global
|
||||
{411A9E0E-FDC6-4E25-828A-0C2CD1CD96F8}.Mono|x86.Build.0 = Release|x86
|
||||
{411A9E0E-FDC6-4E25-828A-0C2CD1CD96F8}.Release|x86.ActiveCfg = Release|x86
|
||||
{411A9E0E-FDC6-4E25-828A-0C2CD1CD96F8}.Release|x86.Build.0 = Release|x86
|
||||
{90D6E9FC-7B88-4E1B-B018-8FA742274558}.Debug|x86.ActiveCfg = Debug|x86
|
||||
{90D6E9FC-7B88-4E1B-B018-8FA742274558}.Debug|x86.Build.0 = Debug|x86
|
||||
{90D6E9FC-7B88-4E1B-B018-8FA742274558}.Mono|x86.ActiveCfg = Release|x86
|
||||
{90D6E9FC-7B88-4E1B-B018-8FA742274558}.Mono|x86.Build.0 = Release|x86
|
||||
{90D6E9FC-7B88-4E1B-B018-8FA742274558}.Release|x86.ActiveCfg = Release|x86
|
||||
{90D6E9FC-7B88-4E1B-B018-8FA742274558}.Release|x86.Build.0 = Release|x86
|
||||
{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB}.Debug|x86.ActiveCfg = Debug|x86
|
||||
{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB}.Debug|x86.Build.0 = Debug|x86
|
||||
{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB}.Mono|x86.ActiveCfg = Release|x86
|
||||
{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB}.Mono|x86.Build.0 = Release|x86
|
||||
{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB}.Release|x86.ActiveCfg = Release|x86
|
||||
{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB}.Release|x86.Build.0 = Release|x86
|
||||
{74420A79-CC16-442C-8B1E-7C1B913844F0}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{74420A79-CC16-442C-8B1E-7C1B913844F0}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{74420A79-CC16-442C-8B1E-7C1B913844F0}.Mono|x86.ActiveCfg = Release|Any CPU
|
||||
@ -311,13 +289,11 @@ Global
|
||||
{80B51429-7A0E-46D6-BEE3-C80DCB1C4EAA} = {4EACDBBC-BCD7-4765-A57B-3E08331E4749}
|
||||
{40D72824-7D02-4A77-9106-8FE0EEA2B997} = {4EACDBBC-BCD7-4765-A57B-3E08331E4749}
|
||||
{411A9E0E-FDC6-4E25-828A-0C2CD1CD96F8} = {F6E3A728-AE77-4D02-BAC8-82FBC1402DDA}
|
||||
{90D6E9FC-7B88-4E1B-B018-8FA742274558} = {F6E3A728-AE77-4D02-BAC8-82FBC1402DDA}
|
||||
{9DC31DE3-79FF-47A8-96B4-6BA18F6BB1CB} = {F6E3A728-AE77-4D02-BAC8-82FBC1402DDA}
|
||||
{74420A79-CC16-442C-8B1E-7C1B913844F0} = {F6E3A728-AE77-4D02-BAC8-82FBC1402DDA}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
EnterpriseLibraryConfigurationToolBinariesPath = packages\Unity.2.1.505.0\lib\NET35;packages\Unity.2.1.505.2\lib\NET35
|
||||
SolutionGuid = {2955716E-0882-41EC-935D-C95694C5C30F}
|
||||
EnterpriseLibraryConfigurationToolBinariesPath = packages\Unity.2.1.505.0\lib\NET35;packages\Unity.2.1.505.2\lib\NET35
|
||||
EndGlobalSection
|
||||
GlobalSection(MonoDevelopProperties) = preSolution
|
||||
StartupItem = NzbDrone.Console\NzbDrone.Console.csproj
|
||||
|
Loading…
Reference in New Issue
Block a user