Reformatting/refactoring code

feature-npv2
Icedream 2014-05-30 20:27:58 +02:00
parent 11486ab8e4
commit 1c990f841b
21 changed files with 79 additions and 75 deletions

View File

@ -1,7 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using log4net;
using NPSharp.Master.Messages.Data;
using NPSharp.Master.Data;
namespace NPSharp.Master.Messages.Client
{
@ -18,10 +18,26 @@ namespace NPSharp.Master.Messages.Client
Log = LogManager.GetLogger(typeof (MasterGetServersMessage));
}
/// <summary>
/// The game for which servers should be fetched
/// </summary>
public string GameName { get; set; }
/// <summary>
/// The protocol version of the dedicated servers to search for
/// </summary>
public uint ProtocolVersion { get; set; }
/// <summary>
/// Extra keywords to take care of when generating the server list
/// </summary>
public List<MasterGetServersKeywords> Keywords { get; set; }
protected override string Serialize()
{
// I wonder if an extra useless space char at the end is okay in this case
return string.Format("{0} {1} {2} {3}", Name, GameName, ProtocolVersion, string.Join(" ", Keywords.Select(k => k.ToString())));
return string.Format("{0} {1} {2} {3}", Name, GameName, ProtocolVersion,
string.Join(" ", Keywords.Select(k => k.ToString())));
}
protected override void Deserialize(string[] arguments)
@ -44,20 +60,5 @@ namespace NPSharp.Master.Messages.Client
}
}
}
/// <summary>
/// The game for which servers should be fetched
/// </summary>
public string GameName { get; set; }
/// <summary>
/// The protocol version of the dedicated servers to search for
/// </summary>
public uint ProtocolVersion { get; set; }
/// <summary>
/// Extra keywords to take care of when generating the server list
/// </summary>
public List<MasterGetServersKeywords> Keywords { get; set; }
}
}

View File

@ -1,4 +1,4 @@
namespace NPSharp.Master.Messages.Data
namespace NPSharp.Master.Data
{
/// <summary>
/// Represents keywords for a master server standard serverlist request.

View File

@ -25,7 +25,8 @@ namespace NPSharp.Master
var buffer = new List<byte>();
if (standardFormat)
buffer.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(IP.GetHashCode()))); // TODO: GetHashCode == IP address as number???
buffer.AddRange(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(IP.GetHashCode())));
// TODO: GetHashCode == IP address as number???
else
{
// TODO: Implement extended serialization format for IP addresses!

View File

@ -71,7 +71,7 @@ namespace NPSharp.Master.Messages
{
var header = buffer.Take(4).ToArray();
var command = Encoding.ASCII.GetString(buffer, 4, buffer.Length - 4).Trim();
var commandSplit = command.Split(new[] { '\t', '\r', '\n', '\0', ' ' },
var commandSplit = command.Split(new[] {'\t', '\r', '\n', '\0', ' '},
StringSplitOptions.RemoveEmptyEntries);
var commandName = commandSplit[0];
@ -79,11 +79,11 @@ namespace NPSharp.Master.Messages
// Search for a message class which fits to the commandName
var message =
(MasterClientMessage)Activator.CreateInstance(Assembly.GetExecutingAssembly()
(MasterClientMessage) Activator.CreateInstance(Assembly.GetExecutingAssembly()
.GetTypes()
.Single(
t =>
t.IsSubclassOf(typeof(MasterClientMessage)) &&
t.IsSubclassOf(typeof (MasterClientMessage)) &&
t.GetCustomAttribute<MasterClientMessageAttribute>()
.Name.Equals(commandName, StringComparison.OrdinalIgnoreCase)));

View File

@ -194,7 +194,7 @@ namespace NPSharp.NP
/// <param name="targetpath">Path where to save the file</param>
public async void DownloadUserFileTo(string filename, string targetpath)
{
byte[] contents = await GetUserFile(filename);
var contents = await GetUserFile(filename);
File.WriteAllBytes(targetpath, contents);
}
@ -231,7 +231,7 @@ namespace NPSharp.NP
/// <param name="targetpath">Path where to save the file</param>
public async void DownloadPublisherFileTo(string filename, string targetpath)
{
byte[] contents = await GetPublisherFile(filename);
var contents = await GetPublisherFile(filename);
File.WriteAllBytes(targetpath, contents);
}

View File

@ -53,7 +53,7 @@
<ItemGroup>
<Compile Include="Authentication\SessionAuthenticationClient.cs" />
<Compile Include="Authentication\SessionAuthenticationResult.cs" />
<Compile Include="Master\Client\MasterGetServersKeywords.cs" />
<Compile Include="Master\Data\MasterGetServersKeywords.cs" />
<Compile Include="Master\Client\MasterGetServersMessage.cs" />
<Compile Include="Master\DedicatedServerEntry.cs" />
<Compile Include="Master\MasterClientMessage.cs" />

View File

@ -5,6 +5,7 @@ using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("NPSharp client library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
@ -17,9 +18,11 @@ using System.Runtime.InteropServices;
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("eb49c20b-b649-42fa-bff4-f62aba36e0b0")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
@ -32,8 +35,10 @@ using System.Runtime.InteropServices;
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0")]
// Make internals visible to the server counterpart of this library
[assembly: InternalsVisibleTo("npsharp_server")]

View File

@ -31,9 +31,17 @@ namespace NPSharp.RPC.Messages.Data
if (time.HasValue)
Time = time.Value;
else
Time = (uint)DateTime.Now.ToUniversalTime().ToBinary();
Time = (uint) DateTime.Now.ToUniversalTime().ToBinary();
}
public uint Version { get; private set; }
public ulong ClientID { get; private set; }
public ulong ServerID { get; private set; }
public uint Time { get; private set; }
public byte[] Serialize()
{
using (var ms = new MemoryStream(sizeof (uint) + (sizeof (ulong)*2) + sizeof (uint)))
@ -49,13 +57,5 @@ namespace NPSharp.RPC.Messages.Data
}
}
}
public uint Version { get; private set; }
public ulong ClientID { get; private set; }
public ulong ServerID { get; private set; }
public uint Time { get; private set; }
}
}

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="2.0.3" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" />

View File

@ -24,7 +24,7 @@ namespace NPSharp.CommandLine.File
public Task Handle(IHttpContext context, Func<Task> next)
{
string uri = context.Request.QueryString.Any()
var uri = context.Request.QueryString.Any()
? null
: string.Join("/", context.Request.Uri.OriginalString.Split('/').Skip(2));
if (uri == null)
@ -38,7 +38,7 @@ namespace NPSharp.CommandLine.File
}
_log.InfoFormat("Requesting publisher file {0}", uri);
Task<byte[]> task = _np.GetPublisherFile(uri);
var task = _np.GetPublisherFile(uri);
try
{
task.Wait();

View File

@ -24,7 +24,7 @@ namespace NPSharp.CommandLine.File
public Task Handle(IHttpContext context, Func<Task> next)
{
string uri = context.Request.QueryString.Any()
var uri = context.Request.QueryString.Any()
? null
: string.Join("/", context.Request.Uri.OriginalString.Split('/').Skip(2));
if (uri == null)
@ -38,7 +38,7 @@ namespace NPSharp.CommandLine.File
}
_log.InfoFormat("Requesting user file {0}", uri);
Task<byte[]> task = _np.GetUserFile(uri);
var task = _np.GetUserFile(uri);
try
{
task.Wait();

View File

@ -14,7 +14,6 @@ using uhttpsharp.Handlers;
using uhttpsharp.Headers;
using uhttpsharp.Listeners;
using uhttpsharp.RequestProviders;
using HttpResponse = uhttpsharp.HttpResponse;
namespace NPSharp.CommandLine.File
{
@ -96,9 +95,9 @@ namespace NPSharp.CommandLine.File
Console.ReadKey();
}
}
private static void SetupLog4Net()
{
if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
{
var appender = new ConsoleAppender
@ -110,7 +109,8 @@ namespace NPSharp.CommandLine.File
#endif
Layout = new PatternLayout("<%d{HH:mm:ss}> [%logger:%thread] %level: %message%newline"),
};
BasicConfigurator.Configure(new IAppender[] { appender, new DebugAppender { Layout = appender.Layout, Threshold = Level.All } });
BasicConfigurator.Configure(new IAppender[]
{appender, new DebugAppender {Layout = appender.Layout, Threshold = Level.All}});
}
else
{
@ -150,10 +150,9 @@ namespace NPSharp.CommandLine.File
BackColor = ColoredConsoleAppender.Colors.Red
});
appender.ActivateOptions();
BasicConfigurator.Configure(new IAppender[] { appender, new DebugAppender { Layout = appender.Layout, Threshold = Level.All } });
BasicConfigurator.Configure(new IAppender[]
{appender, new DebugAppender {Layout = appender.Layout, Threshold = Level.All}});
}
}
}
}

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="2.0.3" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" />

View File

@ -3,29 +3,27 @@ using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using log4net;
using NPSharp.Master.Messages;
using NPSharp.Master.Messages.Client;
using NPSharp.NP;
namespace NPSharp.Master
{
public class MasterServer
{
// TODO: !! Avoid socket fail if stopping then restarting
private readonly Socket _socket4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private readonly Socket _socket6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
private readonly ILog _log;
private readonly ushort _port;
private readonly List<KeyValuePair<Type, Action<MasterClientMessage>>> _callbacks =
new List<KeyValuePair<Type, Action<MasterClientMessage>>>();
private readonly ILog _log;
private readonly ushort _port;
// TODO: Use the same kind of interfaces as in NP server to handle server addition and deletion
private readonly List<DedicatedServerEntry> _registeredServers = new List<DedicatedServerEntry>();
private readonly Socket _socket4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private readonly Socket _socket6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
public MasterServer(ushort port = 20810)
{
@ -33,18 +31,15 @@ namespace NPSharp.Master
_log = LogManager.GetLogger("MasterServer");
// Internal callbacks
AddCallback<MasterGetServersMessage>(messages =>
{
});
AddCallback<MasterGetServersMessage>(messages => { });
}
internal void AddCallback<T>(Action<T> callback) where T : MasterClientMessage
{
_callbacks.Add(
new KeyValuePair<Type, Action<MasterClientMessage>>(
typeof(T),
msg => callback.Invoke((T)msg)));
typeof (T),
msg => callback.Invoke((T) msg)));
}
/// <summary>
@ -86,7 +81,7 @@ namespace NPSharp.Master
while (true)
{
var buffer = new byte[1400];
var clientEndPoint = (EndPoint)new IPEndPoint(IPAddress.IPv6Any, 0);
var clientEndPoint = (EndPoint) new IPEndPoint(IPAddress.IPv6Any, 0);
var recvLength = _socket6.ReceiveFrom(buffer, ref clientEndPoint);
if (recvLength <= buffer.Length)
mergedBuffer.AddRange(buffer);
@ -118,6 +113,5 @@ namespace NPSharp.Master
_log.DebugFormat("Not handling client {0} anymore", ep);
}
}
}

View File

@ -34,10 +34,10 @@ namespace NPSharp.Master.Messages
internal static MasterServerMessage Deserialize(byte[] buffer)
{
var header = buffer.Take(4).ToArray();
var command = Encoding.ASCII.GetString(buffer, 4, buffer.Length - 4).Trim();
var commandSplit = command.Split(new[] { '\t', '\r', '\n', '\0', ' ' }, // TODO: Response consists of multipart messages separated by \ instead of <space>?? Try to be stay as close to client messages as possible.
var commandSplit = command.Split(new[] {'\t', '\r', '\n', '\0', ' '},
// TODO: Response consists of multipart messages separated by \ instead of <space>?? Try to be stay as close to client messages as possible.
StringSplitOptions.RemoveEmptyEntries);
var commandName = commandSplit[0];
@ -45,11 +45,11 @@ namespace NPSharp.Master.Messages
// Search for a message class which fits to the commandName
var message =
(MasterServerMessage)Activator.CreateInstance(Assembly.GetExecutingAssembly()
(MasterServerMessage) Activator.CreateInstance(Assembly.GetExecutingAssembly()
.GetTypes()
.Single(
t =>
t.IsSubclassOf(typeof(MasterServerMessage)) &&
t.IsSubclassOf(typeof (MasterServerMessage)) &&
t.GetCustomAttribute<MasterServerMessageAttribute>()
.Name.Equals(commandName, StringComparison.OrdinalIgnoreCase)));

View File

@ -168,7 +168,7 @@ namespace NPSharp.NP
_log.Debug("Async accept (IPv6) client start");
allDone.Set();
var serverSocket = (Socket)ar.AsyncState;
var serverSocket = (Socket) ar.AsyncState;
var clientSocket = serverSocket.EndAccept(ar);
var npsc = new NPServerClient(this, new RPCServerStream(clientSocket));

View File

@ -4,6 +4,7 @@ using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("NPSharp server library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">