Skip to content

Commit

Permalink
Fluent interface
Browse files Browse the repository at this point in the history
  • Loading branch information
geoperez committed May 14, 2015
1 parent 23eadc9 commit 43de13a
Show file tree
Hide file tree
Showing 16 changed files with 312 additions and 82 deletions.
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,55 @@ namespace Company.Project
}
```

Fluent Example:
---------------

```csharp
namespace Company.Project
{
using System;
using Unosquare.Labs.EmbedIO;

internal class Program
{
/// <summary>
/// Defines the entry point of the application.
/// </summary>
/// <param name="args">The arguments.</param>
private static void Main(string[] args)
{
var url = "http://localhost:9696/";
if (args.Length > 0)
url = args[0];

// Create Webserver with console logger and attach LocalSession and Static
// files module
var server = WebServer
.CreateWithConsole(url)
.WithLocalSession()
.WithStaticFolderAt("c:/web");

server.RunAsync();

// Fire up the browser to show the content if we are debugging!
#if DEBUG
var browser = new System.Diagnostics.Process()
{
StartInfo = new System.Diagnostics.ProcessStartInfo(url) {UseShellExecute = true}
};
browser.Start();
#endif
// Wait for any key to be pressed before disposing of our web server.
// In a service we'd manage the lifecycle of of our web server using
// something like a BackgroundWorker or a ManualResetEvent.
Console.ReadKey(true);

server.Dispose();
}
}
}
```

REST API Example:
-----------------

Expand Down
3 changes: 0 additions & 3 deletions Unosquare.Labs.EmbedIO.Command/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@
</startup>
<applicationSettings>
<Unosquare.Labs.EmbedIO.Command.Properties.Settings>
<setting name="ServerAddress" serializeAs="String">
<value>http://localhost:9696/</value>
</setting>
<setting name="HtmlDefaultDocument" serializeAs="String">
<value>index.html</value>
</setting>
Expand Down
5 changes: 3 additions & 2 deletions Unosquare.Labs.EmbedIO.Command/Options.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ internal class Options
[Option('p', "path", Required = true, HelpText = "WWW-root path.")]
public string RootPath { get; set; }

[Option('o', "port", HelpText = "HTTP port.", DefaultValue=9696)]
public int Port { get; set; }

[OptionList('a', "api", Separator = ',', HelpText = "Specify assemblies to load, separated by a comma.")]
public IList<string> ApiAssemblies { get; set; }

// TODO: Add url

[HelpOption]
public string GetUsage()
{
Expand Down
75 changes: 22 additions & 53 deletions Unosquare.Labs.EmbedIO.Command/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@
{
using CommandLine;
using System;
using System.Linq;
using System.Reflection;
using Unosquare.Labs.EmbedIO.Log;
using Unosquare.Labs.EmbedIO.Modules;

/// <summary>
/// Entry poing
/// </summary>
internal class Program
{
private static readonly SimpleConsoleLog Log = new SimpleConsoleLog();

/// <summary>
/// Load WebServer instance
/// </summary>
/// <param name="args"></param>
private static void Main(string[] args)
{
var options = new Options();
Expand All @@ -21,25 +24,22 @@ private static void Main(string[] args)

Console.WriteLine(" Command-Line Utility: Press any key to stop the server.");

using (var server = new WebServer(Properties.Settings.Default.ServerAddress, Log))
using (var server = WebServer.CreateWithConsole("http://localhost:" + options.Port + "/"))
{
if (Properties.Settings.Default.UseLocalSessionModule)
server.RegisterModule(new LocalSessionModule());
server.WithLocalSession();

var staticFilesModule = new StaticFilesModule(options.RootPath)
{
DefaultDocument = Properties.Settings.Default.HtmlDefaultDocument,
DefaultExtension = Properties.Settings.Default.HtmlDefaultExtension,
UseRamCache = Properties.Settings.Default.UseRamCache
};
server.WithStaticFolderAt(options.RootPath,
defaultDocument: Properties.Settings.Default.HtmlDefaultDocument);

server.RegisterModule(staticFilesModule);
server.Module<StaticFilesModule>().DefaultExtension = Properties.Settings.Default.HtmlDefaultExtension;
server.Module<StaticFilesModule>().UseRamCache = Properties.Settings.Default.UseRamCache;

if (options.ApiAssemblies != null && options.ApiAssemblies.Count > 0)
{
foreach (var api in options.ApiAssemblies)
{
Log.DebugFormat("Checking API {0}", api);
server.Log.DebugFormat("Registering Assembly {0}", api);
LoadApi(api, server);
}
}
Expand All @@ -50,6 +50,11 @@ private static void Main(string[] args)
}
}

/// <summary>
/// Load an Assembly
/// </summary>
/// <param name="apiPath"></param>
/// <param name="server"></param>
private static void LoadApi(string apiPath, WebServer server)
{
try
Expand All @@ -58,48 +63,12 @@ private static void LoadApi(string apiPath, WebServer server)

if (assembly == null) return;

var types = assembly.GetTypes();

// Load WebApiModules
var apiControllers =
types.Where(x => x.IsClass && !x.IsAbstract && x.IsSubclassOf(typeof (WebApiController))).ToArray();

if (apiControllers.Any())
{
server.RegisterModule(new WebApiModule());

foreach (var apiController in apiControllers)
{
server.Module<WebApiModule>().RegisterController(apiController);
Log.DebugFormat("Registering {0} WebAPI", apiController.Name);
}
}
else
{
Log.DebugFormat("{0} does not have any WebAPI", apiPath);
}

// Load WebSocketsModules
var sockerServers = types.Where(x => x.BaseType == typeof (WebSocketsServer)).ToArray();

if (sockerServers.Any())
{
server.RegisterModule(new WebSocketsModule());

foreach (var socketServer in sockerServers)
{
server.Module<WebSocketsModule>().RegisterWebSocketsServer(socketServer);
Log.DebugFormat("Registering {0} WebSocket", socketServer.Name);
}
}
else
{
Log.DebugFormat("{0} does not have any WebSocket", apiPath);
}
server.LoadApiControllers(assembly, true).LoadWebSockets(assembly, true);
}
catch (Exception ex)
{
Log.Error(ex.Message);
server.Log.Error(ex.Message);
server.Log.Error(ex.StackTrace);
}
}
}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions Unosquare.Labs.EmbedIO.Command/Properties/Settings.settings
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="Unosquare.Labs.EmbedIO.Command.Properties" GeneratedClassName="Settings">
<Profiles />
<Settings>
<Setting Name="ServerAddress" Type="System.String" Scope="Application">
<Value Profile="(Default)">http://localhost:9696/</Value>
</Setting>
<Setting Name="HtmlDefaultDocument" Type="System.String" Scope="Application">
<Value Profile="(Default)">index.html</Value>
</Setting>
Expand Down
4 changes: 2 additions & 2 deletions Unosquare.Labs.EmbedIO.Samples/WebSocketsSample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static void Setup(WebServer server)
{
server.RegisterModule(new WebSocketsModule());
server.Module<WebSocketsModule>().RegisterWebSocketsServer<WebSocketsChatServer>();
server.Module<WebSocketsModule>().RegisterWebSocketsServer<WebSocketsTerminalServer>("/terminal");
server.Module<WebSocketsModule>().RegisterWebSocketsServer<WebSocketsTerminalServer>();
}
}

Expand All @@ -27,7 +27,6 @@ public static void Setup(WebServer server)
[WebSocketHandler("/chat")]
public class WebSocketsChatServer : WebSocketsServer
{

public WebSocketsChatServer()
: base(true, 0)
{
Expand Down Expand Up @@ -99,6 +98,7 @@ protected override void OnClientDisconnected(WebSocketContext context)
/// <summary>
/// Define a command-line interface terminal
/// </summary>
[WebSocketHandler("/terminal")]
public class WebSocketsTerminalServer : WebSocketsServer
{

Expand Down
55 changes: 55 additions & 0 deletions Unosquare.Labs.EmbedIO.Tests/FluentTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
namespace Unosquare.Labs.EmbedIO.Tests
{
using NUnit.Framework;
using System.Net;
using Unosquare.Labs.EmbedIO.Modules;
using Unosquare.Labs.EmbedIO.Tests.Properties;

[TestFixture]
public class FluentTest
{
protected string RootPath;

[SetUp]
public void Init()
{
RootPath = TestHelper.SetupStaticFolder();
}

[Test]
public void FluentWithStaticFolder()
{
var webServer = WebServer.Create(Resources.ServerAddress)
.WithLocalSession()
.WithStaticFolderAt(RootPath);

Assert.AreEqual(webServer.Modules.Count, 2, "It has 2 modules loaded");
Assert.IsNotNull(webServer.Module<StaticFilesModule>(), "It has StaticFilesModule");
Assert.AreEqual(webServer.Module<StaticFilesModule>().FileSystemPath, RootPath, "StaticFilesModule root path is equal to RootPath");

webServer.RunAsync();

var request = (HttpWebRequest)WebRequest.Create(Resources.ServerAddress);

using (var response = (HttpWebResponse)request.GetResponse())
{
Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, "Status Code OK");
}

webServer.Dispose();
}

[Test]
public void FluentWithWebApi()
{
var webServer = WebServer.Create(Resources.ServerAddress)
.WithWebApi(autoload: true, assembly: typeof(FluentTest).Assembly);

Assert.AreEqual(webServer.Modules.Count, 1, "It has 1 modules loaded");
Assert.IsNotNull(webServer.Module<WebApiModule>(), "It has WebApiModule");
Assert.AreEqual(webServer.Module<WebApiModule>().ControllersCount, 1, "It has one controller");

webServer.Dispose();
}
}
}
2 changes: 2 additions & 0 deletions Unosquare.Labs.EmbedIO.Tests/TestController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

public class TestController : WebApiController
{
// TODO: Test Async mode

public class Person
{
public int Key { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="FluentTest.cs" />
<Compile Include="LocalSessionModuleTest.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
Expand Down
Loading

0 comments on commit 43de13a

Please sign in to comment.