12 Commits
5 changed files with 328 additions and 262 deletions
+3
View File
@@ -0,0 +1,3 @@
/.vs
/Bot-Utils/obj
/Bot-Utils/bin
+49 -43
View File
@@ -1,43 +1,49 @@
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15 # Visual Studio 15
VisualStudioVersion = 15.0.28307.136 VisualStudioVersion = 15.0.28307.136
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bot-Utils", "Bot-Utils\Bot-Utils.csproj", "{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bot-Utils", "Bot-Utils\Bot-Utils.csproj", "{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "litjson_4.7.1", "..\..\Librarys\litjson\litjson\litjson_4.7.1.csproj", "{91A14CD2-2940-4500-8193-56D37EDDDBAA}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "litjson_4.7.1", "..\..\Librarys\litjson\litjson\litjson_4.7.1.csproj", "{91A14CD2-2940-4500-8193-56D37EDDDBAA}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils-IoT", "..\Utils-IoT\Utils-IoT\Utils-IoT.csproj", "{B870E4D5-6806-4A0B-B233-8907EEDC5AFC}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils-IoT", "..\Utils-IoT\Utils-IoT\Utils-IoT.csproj", "{B870E4D5-6806-4A0B-B233-8907EEDC5AFC}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils", "..\Utils\Utils\Utils.csproj", "{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils", "..\Utils\Utils\Utils.csproj", "{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}"
EndProject EndProject
Global Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.Posix", "..\..\Librarys\Mono.Posix\Mono.Posix\Mono.Posix.csproj", "{E2CA132E-E85C-40AD-BE94-B138AA68772B}"
GlobalSection(SolutionConfigurationPlatforms) = preSolution EndProject
Debug|Any CPU = Debug|Any CPU Global
Release|Any CPU = Release|Any CPU GlobalSection(SolutionConfigurationPlatforms) = preSolution
EndGlobalSection Debug|Any CPU = Debug|Any CPU
GlobalSection(ProjectConfigurationPlatforms) = postSolution Release|Any CPU = Release|Any CPU
{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU EndGlobalSection
{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Debug|Any CPU.Build.0 = Debug|Any CPU GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Release|Any CPU.ActiveCfg = Release|Any CPU {BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Release|Any CPU.Build.0 = Release|Any CPU {BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Debug|Any CPU.Build.0 = Debug|Any CPU {BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Release|Any CPU.Build.0 = Release|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Release|Any CPU.ActiveCfg = Release|Any CPU {91A14CD2-2940-4500-8193-56D37EDDDBAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Release|Any CPU.Build.0 = Release|Any CPU {91A14CD2-2940-4500-8193-56D37EDDDBAA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {91A14CD2-2940-4500-8193-56D37EDDDBAA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Debug|Any CPU.Build.0 = Debug|Any CPU {91A14CD2-2940-4500-8193-56D37EDDDBAA}.Release|Any CPU.Build.0 = Release|Any CPU
{B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Release|Any CPU.ActiveCfg = Release|Any CPU {B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Release|Any CPU.Build.0 = Release|Any CPU {B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.Build.0 = Debug|Any CPU {B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Release|Any CPU.Build.0 = Release|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.ActiveCfg = Release|Any CPU {FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.Build.0 = Release|Any CPU {FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.Build.0 = Debug|Any CPU
EndGlobalSection {FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.ActiveCfg = Release|Any CPU
GlobalSection(SolutionProperties) = preSolution {FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.Build.0 = Release|Any CPU
HideSolutionNode = FALSE {E2CA132E-E85C-40AD-BE94-B138AA68772B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
EndGlobalSection {E2CA132E-E85C-40AD-BE94-B138AA68772B}.Debug|Any CPU.Build.0 = Debug|Any CPU
GlobalSection(ExtensibilityGlobals) = postSolution {E2CA132E-E85C-40AD-BE94-B138AA68772B}.Release|Any CPU.ActiveCfg = Release|Any CPU
SolutionGuid = {99DB6F34-BD41-4AFF-82B7-E4B3EFDF56DC} {E2CA132E-E85C-40AD-BE94-B138AA68772B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
EndGlobal GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {99DB6F34-BD41-4AFF-82B7-E4B3EFDF56DC}
EndGlobalSection
EndGlobal
+83 -81
View File
@@ -1,82 +1,84 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}</ProjectGuid> <ProjectGuid>{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BlubbFish.Utils.IoT.Bots</RootNamespace> <RootNamespace>BlubbFish.Utils.IoT.Bots</RootNamespace>
<AssemblyName>Bot-Utils</AssemblyName> <AssemblyName>Bot-Utils</AssemblyName>
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion> <TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp> <NuGetPackageImportStamp>
</NuGetPackageImportStamp> </NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<StartupObject /> <StartupObject />
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Mono.Posix"> <Reference Include="System" />
<HintPath>..\..\Zway-Bot\packages\Mono.Posix.dll</HintPath> <Reference Include="System.Core" />
</Reference> <Reference Include="System.Web" />
<Reference Include="System" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Core" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Xml.Linq" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="System.Net.Http" />
<Reference Include="System.Data" /> <Reference Include="System.Xml" />
<Reference Include="System.Net.Http" /> </ItemGroup>
<Reference Include="System.Xml" /> <ItemGroup>
</ItemGroup> <Compile Include="Bot.cs" />
<ItemGroup> <Compile Include="Events\CronEvent.cs" />
<Compile Include="Bot.cs" /> <Compile Include="Events\ModulEventArgs.cs" />
<Compile Include="Events\CronEvent.cs" /> <Compile Include="Events\SenmlEvent.cs" />
<Compile Include="Events\ModulEventArgs.cs" /> <Compile Include="Events\MqttEvent.cs" />
<Compile Include="Events\SenmlEvent.cs" /> <Compile Include="Events\OvertakerEvent.cs" />
<Compile Include="Events\MqttEvent.cs" /> <Compile Include="Events\StatusPollingEvent.cs" />
<Compile Include="Events\OvertakerEvent.cs" /> <Compile Include="Interfaces\IForceLoad.cs" />
<Compile Include="Events\StatusPollingEvent.cs" /> <Compile Include="Moduls\AModul.cs" />
<Compile Include="Interfaces\IForceLoad.cs" /> <Compile Include="Moduls\CronJob.cs" />
<Compile Include="Moduls\AModul.cs" /> <Compile Include="Moduls\Mqtt.cs" />
<Compile Include="Moduls\CronJob.cs" /> <Compile Include="Moduls\Overtaker.cs" />
<Compile Include="Moduls\Mqtt.cs" /> <Compile Include="Moduls\Statuspolling.cs" />
<Compile Include="Moduls\Overtaker.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Moduls\Statuspolling.cs" /> <Compile Include="Webserver.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup>
<Compile Include="Webserver.cs" /> <ItemGroup>
</ItemGroup> <ProjectReference Include="..\..\..\Librarys\litjson\litjson\litjson_4.7.1.csproj">
<ItemGroup> <Project>{91a14cd2-2940-4500-8193-56d37edddbaa}</Project>
<ProjectReference Include="..\..\..\Librarys\litjson\litjson\litjson_4.7.1.csproj"> <Name>litjson_4.7.1</Name>
<Project>{91a14cd2-2940-4500-8193-56d37edddbaa}</Project> </ProjectReference>
<Name>litjson_4.7.1</Name> <ProjectReference Include="..\..\..\Librarys\Mono.Posix\Mono.Posix\Mono.Posix.csproj">
</ProjectReference> <Project>{e2ca132e-e85c-40ad-be94-b138aa68772b}</Project>
<ProjectReference Include="..\..\Utils-IoT\Utils-IoT\Utils-IoT.csproj"> <Name>Mono.Posix</Name>
<Project>{b870e4d5-6806-4a0b-b233-8907eedc5afc}</Project> </ProjectReference>
<Name>Utils-IoT</Name> <ProjectReference Include="..\..\Utils-IoT\Utils-IoT\Utils-IoT.csproj">
</ProjectReference> <Project>{b870e4d5-6806-4a0b-b233-8907eedc5afc}</Project>
<ProjectReference Include="..\..\Utils\Utils\Utils.csproj"> <Name>Utils-IoT</Name>
<Project>{fac8ce64-bf13-4ece-8097-aeb5dd060098}</Project> </ProjectReference>
<Name>Utils</Name> <ProjectReference Include="..\..\Utils\Utils\Utils.csproj">
</ProjectReference> <Project>{fac8ce64-bf13-4ece-8097-aeb5dd060098}</Project>
</ItemGroup> <Name>Utils</Name>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> </ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> </Project>
+48 -40
View File
@@ -1,40 +1,48 @@
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden // Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind. // die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("Bot-Utils")] [assembly: AssemblyTitle("Bot-Utils")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("Bot-Utils are helpers for programming a bot")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")] [assembly: AssemblyCompany("BlubbFish")]
[assembly: AssemblyProduct("Bot-Utils")] [assembly: AssemblyProduct("Bot-Utils")]
[assembly: AssemblyCopyright("Copyright © 2018 - 02.10.2018")] [assembly: AssemblyCopyright("Copyright © 2018 - 14.04.2019")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("© BlubbFish")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly
// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)] [assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("bb7bfcb5-3db0-49e1-802a-3ce3eecc59f9")] [assembly: Guid("bb7bfcb5-3db0-49e1-802a-3ce3eecc59f9")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
// //
// Hauptversion // Hauptversion
// Nebenversion // Nebenversion
// Buildnummer // Buildnummer
// Revision // Revision
// //
// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, // Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
// indem Sie "*" wie unten gezeigt eingeben: // indem Sie "*" wie unten gezeigt eingeben:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0")] [assembly: AssemblyVersion("1.1.7")]
[assembly: AssemblyFileVersion("1.1.0")] [assembly: AssemblyFileVersion("1.1.7")]
/* /*
* 1.1.0 Remove Helper from Bot-Utils * 1.1.0 Remove Helper from Bot-Utils
*/ * 1.1.1 Update to local librarys
* 1.1.2 Fixing bug for Contenttype
* 1.1.3 Variables parsing now as a String
* 1.1.4 add Woff as Binary type
* 1.1.5 add a function to send an object as json directly
* 1.1.6 rename functions and make SendFileResponse with a parameter for the folder (default resources),
* also put returntype boolean, add function that parse post params, if path is a dictionary try to load index.html
* 1.1.7 Restrucutre loading, so that all is init and after the listener is started, REQUEST_URL_HOST gives now host and port
*/
+145 -98
View File
@@ -1,98 +1,145 @@
using BlubbFish.Utils.IoT.Connector; using System;
using BlubbFish.Utils.IoT.Events; using System.Collections.Generic;
using System; using System.IO;
using System.Collections.Generic; using System.Net;
using System.IO; using System.Text;
using System.Linq; using System.Threading;
using System.Net; using System.Web;
using System.Text; using BlubbFish.Utils.IoT.Connector;
using System.Threading; using BlubbFish.Utils.IoT.Events;
using System.Threading.Tasks; using LitJson;
namespace BlubbFish.Utils.IoT.Bots namespace BlubbFish.Utils.IoT.Bots {
{ public abstract class Webserver
public abstract class Webserver {
{ protected Dictionary<String, String> config;
protected Dictionary<String, String> config; protected static InIReader requests;
protected InIReader requests; protected HttpListener httplistener;
protected HttpListener httplistener; protected ABackend databackend;
public Webserver(ABackend backend, Dictionary<String, String> settings, InIReader requests) { public Webserver(ABackend backend, Dictionary<String, String> settings, InIReader requestslookup) {
this.config = settings; this.config = settings;
this.requests = requests; requests = requestslookup;
backend.MessageIncomming += this.Backend_MessageIncomming; this.databackend = backend;
this.httplistener = new HttpListener(); }
this.httplistener.Prefixes.Add(this.config["prefix"]);
this.httplistener.Start(); protected void StartListen() {
ThreadPool.QueueUserWorkItem((o) => { this.databackend.MessageIncomming += this.Backend_MessageIncomming;
Console.WriteLine("Webserver is Running..."); this.httplistener = new HttpListener();
try { this.httplistener.Prefixes.Add(this.config["prefix"]);
while (this.httplistener.IsListening) { this.httplistener.Start();
ThreadPool.QueueUserWorkItem((state) => { ThreadPool.QueueUserWorkItem((o) => {
HttpListenerContext httplistenercontext = state as HttpListenerContext; Console.WriteLine("Webserver is Running...");
try { try {
this.SendResponse(httplistenercontext); while(this.httplistener.IsListening) {
} catch { } finally { ThreadPool.QueueUserWorkItem((state) => {
httplistenercontext.Response.OutputStream.Close(); HttpListenerContext httplistenercontext = state as HttpListenerContext;
} try {
}, this.httplistener.GetContext()); this.SendWebserverResponse(httplistenercontext);
} } catch { } finally {
} catch { }; httplistenercontext.Response.OutputStream.Close();
}); }
} }, this.httplistener.GetContext());
}
protected virtual void SendResponse(HttpListenerContext cont) { } catch { };
String restr = cont.Request.Url.PathAndQuery; });
if (restr.StartsWith("/")) { }
if(restr.IndexOf("?") != -1) {
restr = restr.Substring(1, restr.IndexOf("?")-1); public static Boolean SendFileResponse(HttpListenerContext cont, String folder = "resources") {
} else { String restr = cont.Request.Url.PathAndQuery;
restr = restr.Substring(1); if(restr.StartsWith("/")) {
} if(restr.IndexOf("?") != -1) {
if(restr == "") { restr = restr.Substring(1, restr.IndexOf("?") - 1);
restr = "index.html"; } else {
} restr = restr.Substring(1);
String end = restr.IndexOf('.') != -1 ? restr.Substring(restr.IndexOf('.')+1) : ""; }
if (File.Exists("resources/"+ restr)) { if(Directory.Exists(folder + "/" + restr)) {
try { restr += "/index.html";
if (end == "png" || end == ".jpg" || end == ".jpeg" || end == ".ico") { }
Byte[] output = File.ReadAllBytes("resources/" + restr); String end = restr.IndexOf('.') != -1 ? restr.Substring(restr.IndexOf('.') + 1) : "";
cont.Response.OutputStream.Write(output, 0, output.Length); if(File.Exists(folder + "/" + restr)) {
cont.Response.ContentType = "image/"+end; try {
return; if(end == "png" || end == "jpg" || end == "jpeg" || end == "ico" || end == "woff") {
} else { Byte[] output = File.ReadAllBytes(folder + "/" + restr);
String file = File.ReadAllText("resources/" + restr); switch(end) {
if (this.requests.GetSections(false).Contains(restr)) { case "ico":
Dictionary<String, String> vars = this.requests.GetSection(restr); cont.Response.ContentType = "image/x-ico";
foreach (KeyValuePair<String, String> item in vars) { break;
file = file.Replace("{%" + item.Key.ToUpper() + "%}", item.Value); case "woff":
} cont.Response.ContentType = "font/woff";
} break;
file = file.Replace("{%REQUEST_URL_HOST%}", cont.Request.Url.Host); }
Byte[] buf = Encoding.UTF8.GetBytes(file); cont.Response.OutputStream.Write(output, 0, output.Length);
cont.Response.ContentLength64 = buf.Length; return true;
cont.Response.OutputStream.Write(buf, 0, buf.Length); } else {
Console.WriteLine("200 - " + cont.Request.Url.PathAndQuery); String file = File.ReadAllText(folder + "/" + restr);
return; if(requests.GetSections(false).Contains(restr)) {
} Dictionary<String, String> vars = requests.GetSection(restr);
} catch(Exception e) { foreach(KeyValuePair<String, String> item in vars) {
Helper.WriteError("500 - " + e.Message); file = file.Replace("\"{%" + item.Key.ToUpper() + "%}\"", item.Value);
cont.Response.StatusCode = 500; }
return; }
} file = file.Replace("{%REQUEST_URL_HOST%}", cont.Request.Url.Host+":"+cont.Request.Url.Port);
} Byte[] buf = Encoding.UTF8.GetBytes(file);
Helper.WriteError("404 - " + cont.Request.Url.PathAndQuery + " not found!"); cont.Response.ContentLength64 = buf.Length;
cont.Response.StatusCode = 404; switch(end) {
return; case "css":
} cont.Response.ContentType = "text/css";
return; break;
} }
cont.Response.OutputStream.Write(buf, 0, buf.Length);
public void Dispose() { Console.WriteLine("200 - " + cont.Request.Url.PathAndQuery);
this.httplistener.Stop(); return true;
this.httplistener.Close(); }
} } catch(Exception e) {
Helper.WriteError("500 - " + e.Message);
protected abstract void Backend_MessageIncomming(Object sender, BackendEvent e); cont.Response.StatusCode = 500;
} return false;
} }
}
}
Helper.WriteError("404 - " + cont.Request.Url.PathAndQuery + " not found!");
cont.Response.StatusCode = 404;
return false;
}
public static Boolean SendJsonResponse(Object data, HttpListenerContext cont) {
try {
Byte[] buf = Encoding.UTF8.GetBytes(JsonMapper.ToJson(data));
cont.Response.ContentLength64 = buf.Length;
cont.Response.OutputStream.Write(buf, 0, buf.Length);
Console.WriteLine("200 - " + cont.Request.Url.PathAndQuery);
return true;
} catch { }
return false;
}
public static Dictionary<String, String> GetPostParams(HttpListenerRequest req) {
if(req.HttpMethod == "POST") {
if(req.HasEntityBody) {
StreamReader reader = new StreamReader(req.InputStream, req.ContentEncoding);
String rawData = reader.ReadToEnd();
req.InputStream.Close();
reader.Close();
Dictionary<String, String> ret = new Dictionary<String, String>();
foreach(String param in rawData.Split('&')) {
String[] kvPair = param.Split('=');
if(!ret.ContainsKey(kvPair[0])) {
ret.Add(kvPair[0], HttpUtility.UrlDecode(kvPair[1]));
}
}
return ret;
}
}
return new Dictionary<String, String>();
}
public void Dispose() {
this.httplistener.Stop();
this.httplistener.Close();
}
protected abstract void Backend_MessageIncomming(Object sender, BackendEvent e);
protected abstract Boolean SendWebserverResponse(HttpListenerContext cont);
}
}