Skip to content

Commit 43de13a

Browse files
committed
Fluent interface
1 parent 23eadc9 commit 43de13a

File tree

16 files changed

+312
-82
lines changed

16 files changed

+312
-82
lines changed

README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,55 @@ namespace Company.Project
9191
}
9292
```
9393

94+
Fluent Example:
95+
---------------
96+
97+
```csharp
98+
namespace Company.Project
99+
{
100+
using System;
101+
using Unosquare.Labs.EmbedIO;
102+
103+
internal class Program
104+
{
105+
/// <summary>
106+
/// Defines the entry point of the application.
107+
/// </summary>
108+
/// <param name="args">The arguments.</param>
109+
private static void Main(string[] args)
110+
{
111+
var url = "http://localhost:9696/";
112+
if (args.Length > 0)
113+
url = args[0];
114+
115+
// Create Webserver with console logger and attach LocalSession and Static
116+
// files module
117+
var server = WebServer
118+
.CreateWithConsole(url)
119+
.WithLocalSession()
120+
.WithStaticFolderAt("c:/web");
121+
122+
server.RunAsync();
123+
124+
// Fire up the browser to show the content if we are debugging!
125+
#if DEBUG
126+
var browser = new System.Diagnostics.Process()
127+
{
128+
StartInfo = new System.Diagnostics.ProcessStartInfo(url) {UseShellExecute = true}
129+
};
130+
browser.Start();
131+
#endif
132+
// Wait for any key to be pressed before disposing of our web server.
133+
// In a service we'd manage the lifecycle of of our web server using
134+
// something like a BackgroundWorker or a ManualResetEvent.
135+
Console.ReadKey(true);
136+
137+
server.Dispose();
138+
}
139+
}
140+
}
141+
```
142+
94143
REST API Example:
95144
-----------------
96145

Unosquare.Labs.EmbedIO.Command/App.config

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,6 @@
1010
</startup>
1111
<applicationSettings>
1212
<Unosquare.Labs.EmbedIO.Command.Properties.Settings>
13-
<setting name="ServerAddress" serializeAs="String">
14-
<value>http://localhost:9696/</value>
15-
</setting>
1613
<setting name="HtmlDefaultDocument" serializeAs="String">
1714
<value>index.html</value>
1815
</setting>

Unosquare.Labs.EmbedIO.Command/Options.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,12 @@ internal class Options
1313
[Option('p', "path", Required = true, HelpText = "WWW-root path.")]
1414
public string RootPath { get; set; }
1515

16+
[Option('o', "port", HelpText = "HTTP port.", DefaultValue=9696)]
17+
public int Port { get; set; }
18+
1619
[OptionList('a', "api", Separator = ',', HelpText = "Specify assemblies to load, separated by a comma.")]
1720
public IList<string> ApiAssemblies { get; set; }
1821

19-
// TODO: Add url
20-
2122
[HelpOption]
2223
public string GetUsage()
2324
{

Unosquare.Labs.EmbedIO.Command/Program.cs

Lines changed: 22 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,18 @@
22
{
33
using CommandLine;
44
using System;
5-
using System.Linq;
65
using System.Reflection;
7-
using Unosquare.Labs.EmbedIO.Log;
86
using Unosquare.Labs.EmbedIO.Modules;
97

8+
/// <summary>
9+
/// Entry poing
10+
/// </summary>
1011
internal class Program
1112
{
12-
private static readonly SimpleConsoleLog Log = new SimpleConsoleLog();
13-
13+
/// <summary>
14+
/// Load WebServer instance
15+
/// </summary>
16+
/// <param name="args"></param>
1417
private static void Main(string[] args)
1518
{
1619
var options = new Options();
@@ -21,25 +24,22 @@ private static void Main(string[] args)
2124

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

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

29-
var staticFilesModule = new StaticFilesModule(options.RootPath)
30-
{
31-
DefaultDocument = Properties.Settings.Default.HtmlDefaultDocument,
32-
DefaultExtension = Properties.Settings.Default.HtmlDefaultExtension,
33-
UseRamCache = Properties.Settings.Default.UseRamCache
34-
};
32+
server.WithStaticFolderAt(options.RootPath,
33+
defaultDocument: Properties.Settings.Default.HtmlDefaultDocument);
3534

36-
server.RegisterModule(staticFilesModule);
35+
server.Module<StaticFilesModule>().DefaultExtension = Properties.Settings.Default.HtmlDefaultExtension;
36+
server.Module<StaticFilesModule>().UseRamCache = Properties.Settings.Default.UseRamCache;
3737

3838
if (options.ApiAssemblies != null && options.ApiAssemblies.Count > 0)
3939
{
4040
foreach (var api in options.ApiAssemblies)
4141
{
42-
Log.DebugFormat("Checking API {0}", api);
42+
server.Log.DebugFormat("Registering Assembly {0}", api);
4343
LoadApi(api, server);
4444
}
4545
}
@@ -50,6 +50,11 @@ private static void Main(string[] args)
5050
}
5151
}
5252

53+
/// <summary>
54+
/// Load an Assembly
55+
/// </summary>
56+
/// <param name="apiPath"></param>
57+
/// <param name="server"></param>
5358
private static void LoadApi(string apiPath, WebServer server)
5459
{
5560
try
@@ -58,48 +63,12 @@ private static void LoadApi(string apiPath, WebServer server)
5863

5964
if (assembly == null) return;
6065

61-
var types = assembly.GetTypes();
62-
63-
// Load WebApiModules
64-
var apiControllers =
65-
types.Where(x => x.IsClass && !x.IsAbstract && x.IsSubclassOf(typeof (WebApiController))).ToArray();
66-
67-
if (apiControllers.Any())
68-
{
69-
server.RegisterModule(new WebApiModule());
70-
71-
foreach (var apiController in apiControllers)
72-
{
73-
server.Module<WebApiModule>().RegisterController(apiController);
74-
Log.DebugFormat("Registering {0} WebAPI", apiController.Name);
75-
}
76-
}
77-
else
78-
{
79-
Log.DebugFormat("{0} does not have any WebAPI", apiPath);
80-
}
81-
82-
// Load WebSocketsModules
83-
var sockerServers = types.Where(x => x.BaseType == typeof (WebSocketsServer)).ToArray();
84-
85-
if (sockerServers.Any())
86-
{
87-
server.RegisterModule(new WebSocketsModule());
88-
89-
foreach (var socketServer in sockerServers)
90-
{
91-
server.Module<WebSocketsModule>().RegisterWebSocketsServer(socketServer);
92-
Log.DebugFormat("Registering {0} WebSocket", socketServer.Name);
93-
}
94-
}
95-
else
96-
{
97-
Log.DebugFormat("{0} does not have any WebSocket", apiPath);
98-
}
66+
server.LoadApiControllers(assembly, true).LoadWebSockets(assembly, true);
9967
}
10068
catch (Exception ex)
10169
{
102-
Log.Error(ex.Message);
70+
server.Log.Error(ex.Message);
71+
server.Log.Error(ex.StackTrace);
10372
}
10473
}
10574
}

Unosquare.Labs.EmbedIO.Command/Properties/Settings.Designer.cs

Lines changed: 0 additions & 9 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Unosquare.Labs.EmbedIO.Command/Properties/Settings.settings

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@
22
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="Unosquare.Labs.EmbedIO.Command.Properties" GeneratedClassName="Settings">
33
<Profiles />
44
<Settings>
5-
<Setting Name="ServerAddress" Type="System.String" Scope="Application">
6-
<Value Profile="(Default)">http://localhost:9696/</Value>
7-
</Setting>
85
<Setting Name="HtmlDefaultDocument" Type="System.String" Scope="Application">
96
<Value Profile="(Default)">index.html</Value>
107
</Setting>

Unosquare.Labs.EmbedIO.Samples/WebSocketsSample.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public static void Setup(WebServer server)
1717
{
1818
server.RegisterModule(new WebSocketsModule());
1919
server.Module<WebSocketsModule>().RegisterWebSocketsServer<WebSocketsChatServer>();
20-
server.Module<WebSocketsModule>().RegisterWebSocketsServer<WebSocketsTerminalServer>("/terminal");
20+
server.Module<WebSocketsModule>().RegisterWebSocketsServer<WebSocketsTerminalServer>();
2121
}
2222
}
2323

@@ -27,7 +27,6 @@ public static void Setup(WebServer server)
2727
[WebSocketHandler("/chat")]
2828
public class WebSocketsChatServer : WebSocketsServer
2929
{
30-
3130
public WebSocketsChatServer()
3231
: base(true, 0)
3332
{
@@ -99,6 +98,7 @@ protected override void OnClientDisconnected(WebSocketContext context)
9998
/// <summary>
10099
/// Define a command-line interface terminal
101100
/// </summary>
101+
[WebSocketHandler("/terminal")]
102102
public class WebSocketsTerminalServer : WebSocketsServer
103103
{
104104

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
namespace Unosquare.Labs.EmbedIO.Tests
2+
{
3+
using NUnit.Framework;
4+
using System.Net;
5+
using Unosquare.Labs.EmbedIO.Modules;
6+
using Unosquare.Labs.EmbedIO.Tests.Properties;
7+
8+
[TestFixture]
9+
public class FluentTest
10+
{
11+
protected string RootPath;
12+
13+
[SetUp]
14+
public void Init()
15+
{
16+
RootPath = TestHelper.SetupStaticFolder();
17+
}
18+
19+
[Test]
20+
public void FluentWithStaticFolder()
21+
{
22+
var webServer = WebServer.Create(Resources.ServerAddress)
23+
.WithLocalSession()
24+
.WithStaticFolderAt(RootPath);
25+
26+
Assert.AreEqual(webServer.Modules.Count, 2, "It has 2 modules loaded");
27+
Assert.IsNotNull(webServer.Module<StaticFilesModule>(), "It has StaticFilesModule");
28+
Assert.AreEqual(webServer.Module<StaticFilesModule>().FileSystemPath, RootPath, "StaticFilesModule root path is equal to RootPath");
29+
30+
webServer.RunAsync();
31+
32+
var request = (HttpWebRequest)WebRequest.Create(Resources.ServerAddress);
33+
34+
using (var response = (HttpWebResponse)request.GetResponse())
35+
{
36+
Assert.AreEqual(response.StatusCode, HttpStatusCode.OK, "Status Code OK");
37+
}
38+
39+
webServer.Dispose();
40+
}
41+
42+
[Test]
43+
public void FluentWithWebApi()
44+
{
45+
var webServer = WebServer.Create(Resources.ServerAddress)
46+
.WithWebApi(autoload: true, assembly: typeof(FluentTest).Assembly);
47+
48+
Assert.AreEqual(webServer.Modules.Count, 1, "It has 1 modules loaded");
49+
Assert.IsNotNull(webServer.Module<WebApiModule>(), "It has WebApiModule");
50+
Assert.AreEqual(webServer.Module<WebApiModule>().ControllersCount, 1, "It has one controller");
51+
52+
webServer.Dispose();
53+
}
54+
}
55+
}

Unosquare.Labs.EmbedIO.Tests/TestController.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88

99
public class TestController : WebApiController
1010
{
11+
// TODO: Test Async mode
12+
1113
public class Person
1214
{
1315
public int Key { get; set; }

Unosquare.Labs.EmbedIO.Tests/Unosquare.Labs.EmbedIO.Tests.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
<Reference Include="System.Xml" />
4848
</ItemGroup>
4949
<ItemGroup>
50+
<Compile Include="FluentTest.cs" />
5051
<Compile Include="LocalSessionModuleTest.cs" />
5152
<Compile Include="Properties\Resources.Designer.cs">
5253
<AutoGen>True</AutoGen>

0 commit comments

Comments
 (0)