From 1106d4ad4c9952a4de9ca97e3b68983927e05186 Mon Sep 17 00:00:00 2001
From: Starbeamrainbowlabs <sbrl@starbeamrainbowlabs.com>
Date: Tue, 5 Jul 2016 21:22:34 +0100
Subject: [PATCH] Initial commit. End of first dev session.

---
 GalleryShare.sln                        | 17 ++++++
 GalleryShare/GalleryServer.cs           | 72 +++++++++++++++++++++++++
 GalleryShare/GalleryShare.csproj        | 42 +++++++++++++++
 GalleryShare/Program.cs                 | 39 ++++++++++++++
 GalleryShare/Properties/AssemblyInfo.cs | 27 ++++++++++
 GalleryShare/Utilities.cs               | 36 +++++++++++++
 6 files changed, 233 insertions(+)
 create mode 100644 GalleryShare.sln
 create mode 100644 GalleryShare/GalleryServer.cs
 create mode 100644 GalleryShare/GalleryShare.csproj
 create mode 100644 GalleryShare/Program.cs
 create mode 100644 GalleryShare/Properties/AssemblyInfo.cs
 create mode 100644 GalleryShare/Utilities.cs

diff --git a/GalleryShare.sln b/GalleryShare.sln
new file mode 100644
index 0000000..b50bd11
--- /dev/null
+++ b/GalleryShare.sln
@@ -0,0 +1,17 @@
+﻿
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 2012
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GalleryShare", "GalleryShare\GalleryShare.csproj", "{806258ED-F088-44A1-A6BE-2B8E4D1007E5}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|x86 = Debug|x86
+		Release|x86 = Release|x86
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{806258ED-F088-44A1-A6BE-2B8E4D1007E5}.Debug|x86.ActiveCfg = Debug|x86
+		{806258ED-F088-44A1-A6BE-2B8E4D1007E5}.Debug|x86.Build.0 = Debug|x86
+		{806258ED-F088-44A1-A6BE-2B8E4D1007E5}.Release|x86.ActiveCfg = Release|x86
+		{806258ED-F088-44A1-A6BE-2B8E4D1007E5}.Release|x86.Build.0 = Release|x86
+	EndGlobalSection
+EndGlobal
diff --git a/GalleryShare/GalleryServer.cs b/GalleryShare/GalleryServer.cs
new file mode 100644
index 0000000..ee2dc04
--- /dev/null
+++ b/GalleryShare/GalleryServer.cs
@@ -0,0 +1,72 @@
+﻿using System;
+using System.Net;
+using System.Threading.Tasks;
+using System.Runtime.InteropServices;
+using System.IO;
+
+namespace GalleryShare
+{
+	class GalleryServer 
+	{
+		HttpListener server = new HttpListener();
+		string prefix;
+		int port;
+
+		public int Port { get { return port; } }
+
+
+		public GalleryServer(int inPort)
+		{
+			port = inPort;
+
+			prefix = string.Format("http://*:{0}/", Port);
+			server.Prefixes.Add(prefix);
+		}
+
+		/// <summary>
+		/// Synchronously starrts the server listening for requests.
+		/// </summary>
+		public void StartSync()
+		{
+			Task.WaitAll(Start());
+		}
+
+		/// <summary>
+		/// Asynchronously starts the server listening for requests.
+		/// </summary>
+		public async Task Start()
+		{
+			server.Start();
+			Console.WriteLine("Listening for requests on {0}.", prefix);
+			Console.WriteLine("Browser url: http://localhost:{0}/", Port);
+
+			while (true)
+			{
+				Utilities.ForgetTask(Handle(await server.GetContextAsync()));
+			}
+		}
+
+		/// <summary>
+		/// Handles the specified Http request.
+		/// </summary>
+		/// <param name="cycle">The Http request to handle.</param>
+		private async Task Handle(HttpListenerContext cycle)
+		{
+			StreamWriter responseData = new StreamWriter(cycle.Response.OutputStream);
+
+			await responseData.WriteLineAsync(string.Format("You requested {0}", cycle.Request.RawUrl));
+
+			responseData.Close();
+			cycle.Response.Close();
+
+			Console.WriteLine("[{0}] [{1}] [{2}] {3} {4}",
+				DateTime.Now.ToString("hh:mm tt"),
+				cycle.Request.RemoteEndPoint,
+				cycle.Response.StatusCode,
+				cycle.Request.HttpMethod,
+				cycle.Request.RawUrl
+			);
+		}
+	}
+}
+
diff --git a/GalleryShare/GalleryShare.csproj b/GalleryShare/GalleryShare.csproj
new file mode 100644
index 0000000..9311340
--- /dev/null
+++ b/GalleryShare/GalleryShare.csproj
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
+    <ProjectGuid>{806258ED-F088-44A1-A6BE-2B8E4D1007E5}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <RootNamespace>GalleryShare</RootNamespace>
+    <AssemblyName>GalleryShare</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug</OutputPath>
+    <DefineConstants>DEBUG;</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <Externalconsole>true</Externalconsole>
+    <PlatformTarget>x86</PlatformTarget>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
+    <DebugType>full</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release</OutputPath>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <Externalconsole>true</Externalconsole>
+    <PlatformTarget>x86</PlatformTarget>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Program.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="GalleryServer.cs" />
+    <Compile Include="Utilities.cs" />
+  </ItemGroup>
+  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+</Project>
\ No newline at end of file
diff --git a/GalleryShare/Program.cs b/GalleryShare/Program.cs
new file mode 100644
index 0000000..42a9928
--- /dev/null
+++ b/GalleryShare/Program.cs
@@ -0,0 +1,39 @@
+﻿using System;
+using System.Collections.Generic;
+
+namespace GalleryShare
+{
+	class MainClass
+	{
+		public static int Main(string[] args)
+		{
+			int port = 3333;
+			List<string> extras = new List<string>();
+			for(int i = 0; i < args.Length; i++)
+			{
+				if (!args[i].StartsWith("-"))
+				{
+					extras.Add(args[i]);
+					continue;
+				}
+
+				string trimmedArg = args[i].Trim('-');
+				switch (trimmedArg)
+				{
+					case "port":
+					case "p":
+						port = int.Parse(args[++i]);
+						break;
+					default:
+						Console.Error.WriteLine("Error: Unknown argument '{0}'.", args[i]);
+						return 1;
+				}
+			}
+
+			GalleryServer gserver = new GalleryServer(port);
+			gserver.StartSync();
+
+			return 255;
+		}
+	}
+}
diff --git a/GalleryShare/Properties/AssemblyInfo.cs b/GalleryShare/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..ee1cd1a
--- /dev/null
+++ b/GalleryShare/Properties/AssemblyInfo.cs
@@ -0,0 +1,27 @@
+﻿using System.Reflection;
+using System.Runtime.CompilerServices;
+
+// Information about this assembly is defined by the following attributes.
+// Change them to the values specific to your project.
+
+[assembly: AssemblyTitle("GalleryShare")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("")]
+[assembly: AssemblyCopyright("Starbeamrainbowlabs")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
+// The form "{Major}.{Minor}.*" will automatically update the build and revision,
+// and "{Major}.{Minor}.{Build}.*" will update just the revision.
+
+[assembly: AssemblyVersion("1.0.*")]
+
+// The following attributes are used to specify the signing key for the assembly,
+// if desired. See the Mono documentation for more information about signing.
+
+//[assembly: AssemblyDelaySign(false)]
+//[assembly: AssemblyKeyFile("")]
+
diff --git a/GalleryShare/Utilities.cs b/GalleryShare/Utilities.cs
new file mode 100644
index 0000000..83d59b6
--- /dev/null
+++ b/GalleryShare/Utilities.cs
@@ -0,0 +1,36 @@
+﻿using System;
+using System.Threading.Tasks;
+using System.Linq;
+
+namespace GalleryShare
+{
+	public class Utilities
+	{
+		private Utilities()
+		{
+		}
+		
+		/// <summary>
+		/// Call this method to allow a given task to complete in the background.
+		/// Errors will be handled correctly.
+		/// Useful in fire-and-forget scenarios, like a TCP server for example.
+		/// From http://stackoverflow.com/a/22864616/1460422
+		/// </summary>
+		/// <param name="task">The task to forget about.</param>
+		/// <param name="acceptableExceptions">Acceptable exceptions. Exceptions specified here won't cause a crash.</param>
+		public static async void ForgetTask(Task task, params Type[] acceptableExceptions)
+		{
+			try
+			{
+				await task.ConfigureAwait(false);
+			}
+			catch (Exception ex)
+			{
+				// TODO: consider whether derived types are also acceptable.
+				if (!acceptableExceptions.Contains(ex.GetType()))
+					throw;
+			}
+		}
+	}
+}
+
