Lots of debugging.

feature-npv2
Icedream 2014-05-07 22:32:18 +02:00
parent 9ff5af65f9
commit 85951e961f
5 changed files with 60 additions and 14 deletions

View File

@ -18,6 +18,7 @@ namespace NPSharp
private readonly RPCClientStream _rpc; private readonly RPCClientStream _rpc;
private CancellationTokenSource _cancellationTokenSource; private CancellationTokenSource _cancellationTokenSource;
private CancellationToken _cancellationToken; private CancellationToken _cancellationToken;
private Task _procTask;
private readonly ILog _log; private readonly ILog _log;
/// <summary> /// <summary>
@ -48,25 +49,22 @@ namespace NPSharp
/// <returns>True if the connection succeeded, otherwise false.</returns> /// <returns>True if the connection succeeded, otherwise false.</returns>
public bool Connect() public bool Connect()
{ {
_log.Debug("Connect() start");
_cancellationTokenSource = new CancellationTokenSource(); _cancellationTokenSource = new CancellationTokenSource();
_cancellationToken = _cancellationTokenSource.Token; _cancellationToken = _cancellationTokenSource.Token;
if (!_rpc.Open()) if (!_rpc.Open())
return false; return false;
Task.Factory.StartNew(() => _procTask = Task.Factory.StartNew(() =>
{ {
_log.Debug("Now receiving RPC messages"); _log.Debug("Now receiving RPC messages");
try try
{ {
while (true) while (true)
{ {
var message = _rpc.Read(); _rpc.Read();
if (message == null)
continue;
// TODO: log4net
Console.WriteLine("Received packet ID {1} (type {0})", message.GetType().Name, message.MessageId);
} }
} }
catch (ProtocolViolationException error) catch (ProtocolViolationException error)
@ -78,6 +76,7 @@ namespace NPSharp
_log.Debug("Now not receiving RPC messages anymore"); _log.Debug("Now not receiving RPC messages anymore");
}, _cancellationToken); }, _cancellationToken);
_log.Debug("Connect() done");
return true; return true;
} }
@ -86,10 +85,15 @@ namespace NPSharp
/// </summary> /// </summary>
public void Disconnect() public void Disconnect()
{ {
_log.Debug("Disconnect() start");
_cancellationTokenSource.Cancel(true); // TODO: Find a cleaner way to cancel _processingTask (focus: _rpc.Read) _cancellationTokenSource.Cancel(true); // TODO: Find a cleaner way to cancel _processingTask (focus: _rpc.Read)
_procTask.Wait(_cancellationToken);
_rpc.Close(); _rpc.Close();
LoginId = 0; LoginId = 0;
_log.Debug("Disconnect() done");
} }
// TODO: Try to use an exception for failed action instead // TODO: Try to use an exception for failed action instead

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Sockets; using System.Net.Sockets;
using log4net;
using NPSharp.RPC.Packets; using NPSharp.RPC.Packets;
namespace NPSharp.RPC namespace NPSharp.RPC
@ -12,6 +13,7 @@ namespace NPSharp.RPC
{ {
private NetworkStream _ns; private NetworkStream _ns;
private uint _id; private uint _id;
private ILog _log;
private readonly string _host; private readonly string _host;
private readonly ushort _port; private readonly ushort _port;
@ -27,6 +29,7 @@ namespace NPSharp.RPC
{ {
_host = host; _host = host;
_port = port; _port = port;
_log = LogManager.GetLogger("RPC");
} }
/// <summary> /// <summary>
@ -98,6 +101,9 @@ namespace NPSharp.RPC
var buffer = message.Serialize(_id); var buffer = message.Serialize(_id);
_ns.Write(buffer, 0, buffer.Length); _ns.Write(buffer, 0, buffer.Length);
_ns.Flush();
_log.DebugFormat("Sent packet ID {1} (type {0})", message.GetType().Name, _id);
return _id++; return _id++;
} }
@ -122,6 +128,8 @@ namespace NPSharp.RPC
_callbacks[message.MessageId].Invoke(message); _callbacks[message.MessageId].Invoke(message);
_callbacks.Remove(message.MessageId); _callbacks.Remove(message.MessageId);
_log.DebugFormat("Received packet ID {1} (type {0})", message.GetType().Name, message.MessageId);
return message; return message;
} }
} }

View File

@ -1,5 +1,10 @@
using System; using System;
using System.Text; using System.Text;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using log4net.Layout;
using NPSharp.Authentication; using NPSharp.Authentication;
namespace NPSharp.CommandLine.MOTD namespace NPSharp.CommandLine.MOTD
@ -8,9 +13,25 @@ namespace NPSharp.CommandLine.MOTD
{ {
static void Main(string[] args) static void Main(string[] args)
{ {
// log4net setup
var appender = new ColoredConsoleAppender
{
Threshold = Level.Debug,
Layout = new PatternLayout("%level [%thread] %d{HH:mm:ss} - %message%newline"),
};
appender.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Debug, ForeColor = ColoredConsoleAppender.Colors.Cyan | ColoredConsoleAppender.Colors.HighIntensity });
appender.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Info, ForeColor = ColoredConsoleAppender.Colors.Green | ColoredConsoleAppender.Colors.HighIntensity });
appender.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Warn, ForeColor = ColoredConsoleAppender.Colors.Purple | ColoredConsoleAppender.Colors.HighIntensity });
appender.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Error, ForeColor = ColoredConsoleAppender.Colors.Red | ColoredConsoleAppender.Colors.HighIntensity });
appender.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Fatal, ForeColor = ColoredConsoleAppender.Colors.White | ColoredConsoleAppender.Colors.HighIntensity, BackColor = ColoredConsoleAppender.Colors.Red });
appender.ActivateOptions();
BasicConfigurator.Configure(new IAppender[]{appender,new DebugAppender{Layout=appender.Layout,Threshold=Level.All}});
var log = LogManager.GetLogger("Main");
if (args.Length < 4) if (args.Length < 4)
{ {
Console.Error.WriteLine("Needs 4 arguments: hostname port username password"); log.ErrorFormat("Needs 4 arguments: hostname port username password");
return; return;
} }
@ -20,10 +41,11 @@ namespace NPSharp.CommandLine.MOTD
var password = args[3]; var password = args[3];
// NP connection setup // NP connection setup
log.DebugFormat("Connecting to {0}:{1}...", hostname, port);
var np = new NPClient(hostname, port); var np = new NPClient(hostname, port);
if (!np.Connect()) if (!np.Connect())
{ {
Console.Error.WriteLine("Connection to NP server failed."); log.Error("Connection to NP server failed.");
return; return;
} }
@ -35,10 +57,11 @@ namespace NPSharp.CommandLine.MOTD
} }
catch (Exception err) catch (Exception err)
{ {
np.Disconnect();
#if DEBUG #if DEBUG
Console.Error.WriteLine("Could not authenticate: {0}", err); log.ErrorFormat("Could not authenticate: {0}", err);
#else #else
Console.Error.WriteLine("Could not authenticate: {0}", err.Message); log.ErrorFormat("Could not authenticate: {0}", err.Message);
#endif #endif
return; return;
} }
@ -51,9 +74,9 @@ namespace NPSharp.CommandLine.MOTD
catch (Exception err) catch (Exception err)
{ {
#if DEBUG #if DEBUG
Console.Error.WriteLine("Authenticated but session token was invalid. {0}", err); log.ErrorFormat("Authenticated but session token was invalid. {0}", err);
#else #else
Console.Error.WriteLine("Authenticated but session token was invalid ({0}).", err.Message); log.ErrorFormat("Authenticated but session token was invalid ({0}).", err.Message);
#endif #endif
return; return;
} }
@ -64,7 +87,7 @@ namespace NPSharp.CommandLine.MOTD
} }
catch catch
{ {
Console.Error.WriteLine("Could not read MOTD from NP server."); log.ErrorFormat("Could not read MOTD from NP server.");
} }

View File

@ -11,6 +11,8 @@
<AssemblyName>npmotd</AssemblyName> <AssemblyName>npmotd</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@ -37,6 +39,9 @@
<OutputPath>$(SolutionDir)\bin\$(Configuration)\$(Platform)\</OutputPath> <OutputPath>$(SolutionDir)\bin\$(Configuration)\$(Platform)\</OutputPath>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="log4net, Version=1.2.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\..\packages\log4net.2.0.3\lib\net40-full\log4net.dll</HintPath>
</Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
@ -47,6 +52,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="App.config" /> <None Include="App.config" />
<None Include="packages.config" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\libnpsharp\libnpsharp.csproj"> <ProjectReference Include="..\libnpsharp\libnpsharp.csproj">
@ -55,6 +61,7 @@
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- 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. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild"> <Target Name="BeforeBuild">

View File

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