Skip to content

Commit

Permalink
memo2
Browse files Browse the repository at this point in the history
  • Loading branch information
contactsamie committed Feb 25, 2020
1 parent f5ab76d commit e7092c5
Show file tree
Hide file tree
Showing 6 changed files with 115 additions and 13 deletions.
1 change: 1 addition & 0 deletions ServeMe.Tests/when_serve_me_runs_in_memory_setup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public void comment2()
}
catch (Exception e)
{

}
}

Expand Down
8 changes: 7 additions & 1 deletion ServeMeLib/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ private static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message + " " + e.InnerException?.Message);
ServeMe._onError?.Invoke(e, "");
}
}
while (true);
Expand Down Expand Up @@ -658,6 +659,7 @@ others to try
}
catch (Exception e)
{
ServeMe._onError?.Invoke(e, "");
Console.WriteLine(e);
}

Expand Down Expand Up @@ -982,6 +984,7 @@ PLINQ is different. Some important Standard Query Operators in PLINQ require com
catch (Exception e)
{
Console.WriteLine(e);
ServeMe._onError?.Invoke(e, "");
}

willRunAgain = isForever || --repeatCount > 0;
Expand Down Expand Up @@ -1190,6 +1193,7 @@ public static int ExecuteCommand(string Command, int Timeout)
}
catch (Exception e)
{
ServeMe._onError?.Invoke(e, "Error Processing ExecuteCommand : " + e.Message);
Console.WriteLine("Error Processing ExecuteCommand : " + e.Message);
}

Expand Down Expand Up @@ -1259,6 +1263,7 @@ private static void StartProcessQueue()
}
catch (Exception e)
{
ServeMe._onError?.Invoke(e,"");
Console.WriteLine(e);
}
}
Expand Down Expand Up @@ -1370,8 +1375,9 @@ public static void TryRunAsAdmin(string[] args)
{
Process.Start(proc);
}
catch
catch(Exception e)
{
ServeMe._onError?.Invoke(e, "This application needs to run as admin");
ConsoleWriteLine("This application needs to run as admin");
}
}
Expand Down
11 changes: 10 additions & 1 deletion ServeMeLib/ServeMe.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@

public class ServeMe : IDisposable
{
public static string Version = "0.35.0";
public static string Version = "0.36.0";

internal static Action<Exception, string> _onError = null;
public static void OnError(Action<Exception,string> handler)
{
_onError = handler;
}

public string CurrentPath = null;

Expand Down Expand Up @@ -233,6 +239,7 @@ internal string ExecuteTemplate(string input)
{
Console.WriteLine("Error while trying to perform replacements using " + data[1]);
Console.WriteLine(e);
ServeMe._onError?.Invoke(e, "Error while trying to perform replacements using " + data[1]);
}
}

Expand All @@ -259,6 +266,7 @@ internal bool Log(params string[] log)
{
Console.WriteLine("Error while trying to log to " + data[1]);
Console.WriteLine(e);
ServeMe._onError?.Invoke(e, "Error while trying to log to " + data[1]);
}
}

Expand Down Expand Up @@ -456,6 +464,7 @@ public List<string> Start(string serverCsv = null, int? port = null, Func<string
}
catch (Exception e)
{
ServeMe._onError?.Invoke(e, "");
Console.WriteLine(e);
return new List<string>();
}
Expand Down
1 change: 1 addition & 0 deletions ServeMeLib/ServeMeLib.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
<Compile Include="SimpleHttpServer.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StringExtensions.cs" />
<Compile Include="TestHelper.cs" />
</ItemGroup>
<ItemGroup>
Expand Down
69 changes: 58 additions & 11 deletions ServeMeLib/SimpleHttpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ Prefixes must end in a forward slash ("/"). The HttpListener object with the pre
{
try
{
ServeMe._onError?.Invoke(ex, "");
this.ServeMe.Log(ex.Message + " " + ex.InnerException?.Message);
//Console.WriteLine(ex);
if (context?.Response != null)
Expand All @@ -209,6 +210,8 @@ Prefixes must end in a forward slash ("/"). The HttpListener object with the pre
{
Console.WriteLine(e);
this.ServeMe.Log("FATAL ERROR :" + e.Message + " " + e.InnerException?.Message);
ServeMe._onError?.Invoke(e, "FATAL ERROR :" + e.Message + " " + e.InnerException?.Message);

}
}
}
Expand Down Expand Up @@ -429,10 +432,24 @@ private void Process(HttpListenerContext context)
Directory.CreateDirectory(saveFile);
}

var finalExtension = string.IsNullOrEmpty(ext) ? "json" : ext;
var finalExtension = string.IsNullOrEmpty(ext) ? ".json" : ext;

saveFile = saveFile + "\\{{flatpath}}" + $"{appendFile}.{finalExtension}";
saveFile = saveFile + "\\{{flatpathdir}}" + $"{appendFile}";
saveFile = replaceTokensForTo(saveFile, context);
if (string.IsNullOrEmpty(saveFile) || saveFile.EndsWith("/")|| saveFile.EndsWith("\\"))
{
saveFile = saveFile.TrimEnd('/');
saveFile = saveFile+ "index.html";
}
else
{
saveFile = saveFile + finalExtension;
}
var fileInfo = new FileInfo(saveFile);
if (!Directory.Exists(fileInfo.DirectoryName))
{
Directory.CreateDirectory(fileInfo.DirectoryName);
}
memoizationFile = saveFile;
}
}
Expand Down Expand Up @@ -637,10 +654,25 @@ private void Process(HttpListenerContext context)
isJsonP = true;
resturns = resturns.Split(new[] { '(' }, 2)[1].TrimEnd(')');
}

string medType=null;
if (File.Exists(memoizationFile + ".mediatype"))
{
medType = File.ReadAllText(memoizationFile + ".mediatype");
}
response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(resturns)
{
Headers = { }
}
};
if (!string.IsNullOrEmpty(medType))
{
response.Content.Headers.ContentType = new MediaTypeHeaderValue(medType);
}


}
//expectedMethod

Expand All @@ -650,7 +682,7 @@ private void Process(HttpListenerContext context)
if (response.Content.Headers.ContentType != null)
context.Response.ContentType = response.Content.Headers.ContentType.MediaType;
string mediaType = response.Content.Headers.ContentType?.MediaType?.ToLower() ?? "";
if (mediaType.Contains("text") || mediaType.Contains("json") || mediaType.Contains("javascript"))
if (mediaType.Contains("text") || mediaType.Contains("json") || mediaType.Contains("javascript") || mediaType.Contains("xml"))
{
string stringResponse = response.Content.ReadAsStringAsync().Result;

Expand Down Expand Up @@ -695,6 +727,11 @@ private void Process(HttpListenerContext context)
lock (this.PadLock)
{
this.ServeMe.WriteAllTextToFile(saveFile, stringResponse);
//string mediaType = response.Content.Headers.ContentType?.MediaType?.ToLower() ?? "";
if (!string.IsNullOrEmpty(mediaType))
{
this.ServeMe.WriteAllTextToFile(saveFile+$".mediatype", mediaType);
}
}
}

Expand Down Expand Up @@ -820,6 +857,7 @@ private void Process(HttpListenerContext context)
{
this.ServeMe.Log($"Error occured while returning resource {filename} : {ex.Message} {ex.InnerException?.Message}");
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
ServeMe._onError?.Invoke(ex, $"Error occured while returning resource {filename} : {ex.Message} {ex.InnerException?.Message}");
}
}
}
Expand All @@ -840,10 +878,11 @@ private static string replaceTokensForTo(string to, HttpListenerContext context)
}

var query = context.Request.Url.Query != null ? context.Request.Url.Query.Replace("?", "") : "";

var nflatapp = context.Request.Url.AbsolutePath.AppTrimEnd(Path.GetExtension(context.Request.Url.AbsolutePath));
to = to.Replace("{{query}}", query);
to = to.Replace("{{file}}", context.Request.Url.Segments.Last().Replace("/", "").Replace("?", ""));
to = to.Replace("{{flatpath}}", context.Request.Url.AbsolutePath.TrimStart('/').TrimEnd('/').Replace("/", "_"));
to = to.Replace("{{flatpath}}", nflatapp.TrimStart('/').TrimEnd('/').Replace("/", "_"));
to = to.Replace("{{flatpathdir}}", nflatapp);
to = to.Replace("{{root}}", context.Request.Url.Scheme + "://" + context.Request.Url.Authority);
to = to.Replace("{{port}}", context.Request.Url.Port.ToString());
to = to.Replace("{{scheme}}", context.Request.Url.Scheme.ToString());
Expand Down Expand Up @@ -938,9 +977,10 @@ public HttpResponseMessage Send(
string errorMessage = e.Message;
if (e.InnerException != null)
errorMessage += " - " + e.InnerException.Message;

Log(new[] { $"{e.GetType().Name} Error while sending {request.Method} request to {request?.RequestUri}", errorMessage });
var msg = $"{e.GetType().Name} Error while sending {request.Method} request to {request?.RequestUri}";
Log(new[] {msg , errorMessage });
onError?.Invoke(e);
ServeMe._onError?.Invoke(e,msg);
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.BadGateway,
Expand All @@ -951,8 +991,10 @@ public HttpResponseMessage Send(
{
// For instance, on some OSes, .NET Core doesn't yet
// support ServerCertificateCustomValidationCallback
Log(new[] { $"{e.GetType().Name} Error while sending {request.Method} request to {request?.RequestUri}" });
var msg = $"{e.GetType().Name} Error while sending {request.Method} request to {request?.RequestUri}";
Log(new[] { msg });
onError?.Invoke(e);
ServeMe._onError?.Invoke(e, msg);
return new HttpResponseMessage
{
StatusCode = 0,
Expand All @@ -961,8 +1003,10 @@ public HttpResponseMessage Send(
}
catch (TaskCanceledException e)
{
Log(new[] { $"{e.GetType().Name} Error while sending {request.Method} request to {request?.RequestUri}" });
var msg = $"{e.GetType().Name} Error while sending {request.Method} request to {request?.RequestUri}";
Log(new[] { msg });
onError?.Invoke(e);
ServeMe._onError?.Invoke(e, msg);
return new HttpResponseMessage
{
StatusCode = 0,
Expand All @@ -977,8 +1021,9 @@ public HttpResponseMessage Send(
if (ex.InnerException != null)
message += ':' + ex.InnerException.Message;

Log(new[] { $"{ex.GetType().Name} Error while sending {request.Method} request to {request?.RequestUri}", message });

var msg = $"{ex.GetType().Name} Error while sending {request.Method} request to {request?.RequestUri}";
Log(new[] { msg, message });
ServeMe._onError?.Invoke(ex, msg);
response.Content = new StringContent(message);
Trace.TraceError("Error:{0}", message);
onError?.Invoke(ex);
Expand Down Expand Up @@ -1175,6 +1220,8 @@ public class " + className + @"
}
catch (Exception e)
{
ServeMe._onError?.Invoke(e,"");

return e;
}
}
Expand Down
38 changes: 38 additions & 0 deletions ServeMeLib/StringExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System;

namespace ServeMeLib
{
public static class StringExtensions
{
public static string AppTrimStart(this string inputText, string value, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase)
{
if (!string.IsNullOrEmpty(value))
{
while (!string.IsNullOrEmpty(inputText) && inputText.StartsWith(value, comparisonType))
{
inputText = inputText.Substring(value.Length - 1);
}
}

return inputText;
}

public static string AppTrimEnd(this string inputText, string value, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase)
{
if (!string.IsNullOrEmpty(value))
{
while (!string.IsNullOrEmpty(inputText) && inputText.EndsWith(value, comparisonType))
{
inputText = inputText.Substring(0, (inputText.Length - value.Length));
}
}

return inputText;
}

public static string AppTrim(this string inputText, string value, StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase)
{
return AppTrimStart(AppTrimEnd(inputText, value, comparisonType), value, comparisonType);
}
}
}

0 comments on commit e7092c5

Please sign in to comment.