refactor: apply default vs transform to xproj

refactor(spa-services): clean code

refactor(node-services): clean code, extract classes nto separate files

refactor(angular-services): prime cache cleanup
This commit is contained in:
Andrei Tserakhau
2016-05-23 11:28:42 +03:00
parent 2c35945562
commit 95cba7f5dd
32 changed files with 621 additions and 448 deletions

View File

@@ -10,11 +10,11 @@
<ProjectGuid>1a74148f-9dc0-435d-b5ac-7d1b0d3d5e0b</ProjectGuid> <ProjectGuid>1a74148f-9dc0-435d-b5ac-7d1b0d3d5e0b</ProjectGuid>
<RootNamespace>MusicStore</RootNamespace> <RootNamespace>MusicStore</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath> <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\artifacts\bin\$(MSBuildProjectName)\</OutputPath> <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<DevelopmentServerPort>5068</DevelopmentServerPort> <DevelopmentServerPort>5068</DevelopmentServerPort>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project> </Project>

View File

@@ -10,11 +10,11 @@
<ProjectGuid>6d4bcdd6-7951-449b-be55-cb7f014b7430</ProjectGuid> <ProjectGuid>6d4bcdd6-7951-449b-be55-cb7f014b7430</ProjectGuid>
<RootNamespace>ES2015Transpilation</RootNamespace> <RootNamespace>ES2015Transpilation</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath> <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\bin\$(MSBuildProjectName)\</OutputPath> <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<DevelopmentServerPort>2018</DevelopmentServerPort> <DevelopmentServerPort>2018</DevelopmentServerPort>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project> </Project>

View File

@@ -10,11 +10,11 @@
<ProjectGuid>abf90a5b-f4e0-438c-a6e4-9549fb43690b</ProjectGuid> <ProjectGuid>abf90a5b-f4e0-438c-a6e4-9549fb43690b</ProjectGuid>
<RootNamespace>ReactGrid</RootNamespace> <RootNamespace>ReactGrid</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath> <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\..\..\artifacts\bin\$(MSBuildProjectName)\</OutputPath> <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<DevelopmentServerPort>2311</DevelopmentServerPort> <DevelopmentServerPort>2311</DevelopmentServerPort>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project> </Project>

View File

@@ -9,11 +9,10 @@
<ProjectGuid>421807e6-b62c-417b-b901-46c5dedaa8f1</ProjectGuid> <ProjectGuid>421807e6-b62c-417b-b901-46c5dedaa8f1</ProjectGuid>
<RootNamespace>Microsoft.AspNetCore.AngularServices</RootNamespace> <RootNamespace>Microsoft.AspNetCore.AngularServices</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath> <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\artifacts\bin\$(MSBuildProjectName)\</OutputPath> <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project> </Project>

View File

@@ -3,42 +3,51 @@ using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Html;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Microsoft.AspNetCore.AngularServices { namespace Microsoft.AspNetCore.AngularServices
public static class PrimeCacheHelper { {
public static async Task<HtmlString> PrimeCache(this IHtmlHelper html, string url) { public static class PrimeCacheHelper
{
public static async Task<HtmlString> PrimeCache(this IHtmlHelper html, string url)
{
// TODO: Consider deduplicating the PrimeCache calls (that is, if there are multiple requests to precache // TODO: Consider deduplicating the PrimeCache calls (that is, if there are multiple requests to precache
// the same URL, only return nonempty for one of them). This will make it easier to auto-prime-cache any // the same URL, only return nonempty for one of them). This will make it easier to auto-prime-cache any
// HTTP requests made during server-side rendering, without risking unnecessary duplicate requests. // HTTP requests made during server-side rendering, without risking unnecessary duplicate requests.
if (string.IsNullOrEmpty(url)) { if (string.IsNullOrEmpty(url))
{
throw new ArgumentException("Value cannot be null or empty", nameof(url)); throw new ArgumentException("Value cannot be null or empty", nameof(url));
} }
try { try
{
var request = html.ViewContext.HttpContext.Request; var request = html.ViewContext.HttpContext.Request;
var baseUri = new Uri(string.Concat(request.Scheme, "://", request.Host.ToUriComponent(), request.PathBase.ToUriComponent(), request.Path.ToUriComponent(), request.QueryString.ToUriComponent())); var baseUri =
new Uri(string.Concat(request.Scheme, "://", request.Host.ToUriComponent(),
request.PathBase.ToUriComponent(), request.Path.ToUriComponent(),
request.QueryString.ToUriComponent()));
var fullUri = new Uri(baseUri, url); var fullUri = new Uri(baseUri, url);
var response = await new HttpClient().GetAsync(fullUri.ToString()); var response = await new HttpClient().GetAsync(fullUri.ToString());
var responseBody = await response.Content.ReadAsStringAsync(); var responseBody = await response.Content.ReadAsStringAsync();
return new HtmlString(FormatAsScript(url, response.StatusCode, responseBody)); return new HtmlString(FormatAsScript(url, response.StatusCode, responseBody));
} catch (Exception ex) { }
var logger = (ILogger)html.ViewContext.HttpContext.RequestServices.GetService(typeof (ILogger)); catch (Exception ex)
if (logger != null) { {
logger.LogWarning("Error priming cache for URL: " + url, ex); var logger = (ILogger)html.ViewContext.HttpContext.RequestServices.GetService(typeof(ILogger));
} logger?.LogWarning("Error priming cache for URL: " + url, ex);
return new HtmlString(string.Empty); return new HtmlString(string.Empty);
} }
} }
private static string FormatAsScript(string url, HttpStatusCode responseStatusCode, string responseBody) private static string FormatAsScript(string url, HttpStatusCode responseStatusCode, string responseBody)
{ =>
return string.Format(@"<script>window.__preCachedResponses = window.__preCachedResponses || {{}}; window.__preCachedResponses[{0}] = {1};</script>", "<script>" +
JsonConvert.SerializeObject(url), "window.__preCachedResponses = window.__preCachedResponses || {{}}; " +
JsonConvert.SerializeObject(new { statusCode = responseStatusCode, body = responseBody }) $"window.__preCachedResponses[{JsonConvert.SerializeObject(url)}] " +
); $"= {JsonConvert.SerializeObject(new { statusCode = responseStatusCode, body = responseBody })};" +
} "</script>";
} }
} }

View File

@@ -2,31 +2,37 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions; using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
namespace Microsoft.AspNetCore.NodeServices { namespace Microsoft.AspNetCore.NodeServices
public static class Configuration { {
private readonly static string[] defaultWatchFileExtensions = new[] { ".js", ".jsx", ".ts", ".tsx", ".json", ".html" }; using System;
private readonly static NodeServicesOptions defaultOptions = new NodeServicesOptions {
public static class Configuration
{
private static readonly string[] DefaultWatchFileExtensions = {".js", ".jsx", ".ts", ".tsx", ".json", ".html"};
private static readonly NodeServicesOptions DefaultOptions = new NodeServicesOptions
{
HostingModel = NodeHostingModel.Http, HostingModel = NodeHostingModel.Http,
WatchFileExtensions = defaultWatchFileExtensions WatchFileExtensions = DefaultWatchFileExtensions
}; };
public static void AddNodeServices(this IServiceCollection serviceCollection) { public static void AddNodeServices(this IServiceCollection serviceCollection)
AddNodeServices(serviceCollection, defaultOptions); => AddNodeServices(serviceCollection, DefaultOptions);
}
public static void AddNodeServices(this IServiceCollection serviceCollection, NodeServicesOptions options) { public static void AddNodeServices(this IServiceCollection serviceCollection, NodeServicesOptions options)
serviceCollection.AddSingleton(typeof(INodeServices), (serviceProvider) => { => serviceCollection.AddSingleton(typeof(INodeServices), serviceProvider =>
{
var hostEnv = serviceProvider.GetRequiredService<IHostingEnvironment>(); var hostEnv = serviceProvider.GetRequiredService<IHostingEnvironment>();
if (string.IsNullOrEmpty(options.ProjectPath)) { if (string.IsNullOrEmpty(options.ProjectPath))
{
options.ProjectPath = hostEnv.ContentRootPath; options.ProjectPath = hostEnv.ContentRootPath;
} }
return CreateNodeServices(options); return CreateNodeServices(options);
}); });
}
public static INodeServices CreateNodeServices(NodeServicesOptions options) public static INodeServices CreateNodeServices(NodeServicesOptions options)
{ {
var watchFileExtensions = options.WatchFileExtensions ?? defaultWatchFileExtensions; var watchFileExtensions = options.WatchFileExtensions ?? DefaultWatchFileExtensions;
switch (options.HostingModel) switch (options.HostingModel)
{ {
case NodeHostingModel.Http: case NodeHostingModel.Http:
@@ -34,18 +40,8 @@ namespace Microsoft.AspNetCore.NodeServices {
case NodeHostingModel.InputOutputStream: case NodeHostingModel.InputOutputStream:
return new InputOutputStreamNodeInstance(options.ProjectPath); return new InputOutputStreamNodeInstance(options.ProjectPath);
default: default:
throw new System.ArgumentException("Unknown hosting model: " + options.HostingModel.ToString()); throw new ArgumentException("Unknown hosting model: " + options.HostingModel);
} }
} }
} }
}
public class NodeServicesOptions {
public NodeHostingModel HostingModel { get; set; }
public string ProjectPath { get; set; }
public string[] WatchFileExtensions { get; set; }
public NodeServicesOptions() {
this.HostingModel = NodeHostingModel.Http;
}
}
}

View File

@@ -7,66 +7,90 @@ using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
namespace Microsoft.AspNetCore.NodeServices { namespace Microsoft.AspNetCore.NodeServices
internal class HttpNodeInstance : OutOfProcessNodeInstance { {
private readonly static Regex PortMessageRegex = new Regex(@"^\[Microsoft.AspNetCore.NodeServices.HttpNodeHost:Listening on port (\d+)\]$"); internal class HttpNodeInstance : OutOfProcessNodeInstance
{
private static readonly Regex PortMessageRegex =
new Regex(@"^\[Microsoft.AspNetCore.NodeServices.HttpNodeHost:Listening on port (\d+)\]$");
private readonly static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings { private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver() ContractResolver = new CamelCasePropertyNamesContractResolver()
}; };
private int _portNumber; private int _portNumber;
public HttpNodeInstance(string projectPath, int port = 0, string[] watchFileExtensions = null) public HttpNodeInstance(string projectPath, int port = 0, string[] watchFileExtensions = null)
: base(EmbeddedResourceReader.Read(typeof(HttpNodeInstance), "/Content/Node/entrypoint-http.js"), projectPath, MakeCommandLineOptions(port, watchFileExtensions)) : base(
EmbeddedResourceReader.Read(
typeof(HttpNodeInstance),
"/Content/Node/entrypoint-http.js"),
projectPath,
MakeCommandLineOptions(port, watchFileExtensions))
{ {
} }
private static string MakeCommandLineOptions(int port, string[] watchFileExtensions) { private static string MakeCommandLineOptions(int port, string[] watchFileExtensions)
var result = "--port " + port.ToString(); {
if (watchFileExtensions != null && watchFileExtensions.Length > 0) { var result = "--port " + port;
if (watchFileExtensions != null && watchFileExtensions.Length > 0)
{
result += " --watch " + string.Join(",", watchFileExtensions); result += " --watch " + string.Join(",", watchFileExtensions);
} }
return result; return result;
} }
public override async Task<T> Invoke<T>(NodeInvocationInfo invocationInfo) { public override async Task<T> Invoke<T>(NodeInvocationInfo invocationInfo)
await this.EnsureReady(); {
await EnsureReady();
using (var client = new HttpClient()) { using (var client = new HttpClient())
{
// TODO: Use System.Net.Http.Formatting (PostAsJsonAsync etc.) // TODO: Use System.Net.Http.Formatting (PostAsJsonAsync etc.)
var payloadJson = JsonConvert.SerializeObject(invocationInfo, jsonSerializerSettings); var payloadJson = JsonConvert.SerializeObject(invocationInfo, JsonSerializerSettings);
var payload = new StringContent(payloadJson, Encoding.UTF8, "application/json"); var payload = new StringContent(payloadJson, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:" + this._portNumber, payload); var response = await client.PostAsync("http://localhost:" + _portNumber, payload);
var responseString = await response.Content.ReadAsStringAsync(); var responseString = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode) { if (!response.IsSuccessStatusCode)
{
throw new Exception("Call to Node module failed with error: " + responseString); throw new Exception("Call to Node module failed with error: " + responseString);
} }
var responseIsJson = response.Content.Headers.ContentType.MediaType == "application/json"; var responseIsJson = response.Content.Headers.ContentType.MediaType == "application/json";
if (responseIsJson) { if (responseIsJson)
{
return JsonConvert.DeserializeObject<T>(responseString); return JsonConvert.DeserializeObject<T>(responseString);
} else if (typeof(T) != typeof(string)) {
throw new System.ArgumentException("Node module responded with non-JSON string. This cannot be converted to the requested generic type: " + typeof(T).FullName);
} else {
return (T)(object)responseString;
} }
if (typeof(T) != typeof(string))
{
throw new ArgumentException(
"Node module responded with non-JSON string. This cannot be converted to the requested generic type: " +
typeof(T).FullName);
}
return (T)(object)responseString;
} }
} }
protected override void OnOutputDataReceived(string outputData) { protected override void OnOutputDataReceived(string outputData)
var match = this._portNumber != 0 ? null : PortMessageRegex.Match(outputData); {
if (match != null && match.Success) { var match = _portNumber != 0 ? null : PortMessageRegex.Match(outputData);
this._portNumber = int.Parse(match.Groups[1].Captures[0].Value); if (match != null && match.Success)
} else { {
_portNumber = int.Parse(match.Groups[1].Captures[0].Value);
}
else
{
base.OnOutputDataReceived(outputData); base.OnOutputDataReceived(outputData);
} }
} }
protected override void OnBeforeLaunchProcess() { protected override void OnBeforeLaunchProcess()
{
// Prepare to receive a new port number // Prepare to receive a new port number
this._portNumber = 0; _portNumber = 0;
} }
} }
} }

View File

@@ -4,55 +4,72 @@ using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
namespace Microsoft.AspNetCore.NodeServices { namespace Microsoft.AspNetCore.NodeServices
// This is just to demonstrate that other transports are possible. This implementation is extremely {
// dubious - if the Node-side code fails to conform to the expected protocol in any way (e.g., has an /// <summary>
// error), then it will just hang forever. So don't use this. /// This is just to demonstrate that other transports are possible. This implementation is extremely
// /// dubious - if the Node-side code fails to conform to the expected protocol in any way (e.g., has an
// But it's fast - the communication round-trip time is about 0.2ms (tested on OS X on a recent machine), /// error), then it will just hang forever. So don't use this.
// versus 2-3ms for the HTTP transport. ///
// /// But it's fast - the communication round-trip time is about 0.2ms (tested on OS X on a recent machine),
// Instead of directly using stdin/stdout, we could use either regular sockets (TCP) or use named pipes /// versus 2-3ms for the HTTP transport.
// on Windows and domain sockets on Linux / OS X, but either way would need a system for framing the ///
// requests, associating them with responses, and scheduling use of the comms channel. /// Instead of directly using stdin/stdout, we could use either regular sockets (TCP) or use named pipes
/// on Windows and domain sockets on Linux / OS X, but either way would need a system for framing the
/// requests, associating them with responses, and scheduling use of the comms channel.
/// </summary>
/// <seealso cref="Microsoft.AspNetCore.NodeServices.OutOfProcessNodeInstance" />
internal class InputOutputStreamNodeInstance : OutOfProcessNodeInstance internal class InputOutputStreamNodeInstance : OutOfProcessNodeInstance
{ {
private SemaphoreSlim _invocationSemaphore = new SemaphoreSlim(1); private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
private TaskCompletionSource<string> _currentInvocationResult; {
private readonly static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings {
ContractResolver = new CamelCasePropertyNamesContractResolver() ContractResolver = new CamelCasePropertyNamesContractResolver()
}; };
public InputOutputStreamNodeInstance(string projectPath) private TaskCompletionSource<string> _currentInvocationResult;
: base(EmbeddedResourceReader.Read(typeof(InputOutputStreamNodeInstance), "/Content/Node/entrypoint-stream.js"), projectPath) private readonly SemaphoreSlim _invocationSemaphore = new SemaphoreSlim(1);
public InputOutputStreamNodeInstance(string projectPath)
: base(
EmbeddedResourceReader.Read(
typeof(InputOutputStreamNodeInstance),
"/Content/Node/entrypoint-stream.js"),
projectPath)
{ {
} }
public override async Task<T> Invoke<T>(NodeInvocationInfo invocationInfo) { public override async Task<T> Invoke<T>(NodeInvocationInfo invocationInfo)
await this._invocationSemaphore.WaitAsync(); {
try { await _invocationSemaphore.WaitAsync();
await this.EnsureReady(); try
{
await EnsureReady();
var payloadJson = JsonConvert.SerializeObject(invocationInfo, jsonSerializerSettings); var payloadJson = JsonConvert.SerializeObject(invocationInfo, JsonSerializerSettings);
var nodeProcess = this.NodeProcess; var nodeProcess = NodeProcess;
this._currentInvocationResult = new TaskCompletionSource<string>(); _currentInvocationResult = new TaskCompletionSource<string>();
nodeProcess.StandardInput.Write("\ninvoke:"); nodeProcess.StandardInput.Write("\ninvoke:");
nodeProcess.StandardInput.WriteLine(payloadJson); // WriteLineAsync isn't supported cross-platform nodeProcess.StandardInput.WriteLine(payloadJson); // WriteLineAsync isn't supported cross-platform
var resultString = await this._currentInvocationResult.Task; var resultString = await _currentInvocationResult.Task;
return JsonConvert.DeserializeObject<T>(resultString); return JsonConvert.DeserializeObject<T>(resultString);
} finally { }
this._invocationSemaphore.Release(); finally
this._currentInvocationResult = null; {
_invocationSemaphore.Release();
_currentInvocationResult = null;
} }
} }
protected override void OnOutputDataReceived(string outputData) { protected override void OnOutputDataReceived(string outputData)
if (this._currentInvocationResult != null) { {
this._currentInvocationResult.SetResult(outputData); if (_currentInvocationResult != null)
} else { {
_currentInvocationResult.SetResult(outputData);
}
else
{
base.OnOutputDataReceived(outputData); base.OnOutputDataReceived(outputData);
} }
} }
} }
} }

View File

@@ -1,8 +1,9 @@
namespace Microsoft.AspNetCore.NodeServices { namespace Microsoft.AspNetCore.NodeServices
{
public class NodeInvocationInfo public class NodeInvocationInfo
{ {
public string ModuleName; public string ModuleName { get; set; }
public string ExportedFunctionName; public string ExportedFunctionName { get; set; }
public object[] Args; public object[] Args { get; set; }
} }
} }

View File

@@ -3,126 +3,42 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Microsoft.AspNetCore.NodeServices { namespace Microsoft.AspNetCore.NodeServices
/** {
* Class responsible for launching the Node child process, determining when it is ready to accept invocations, /// <summary>
* and finally killing it when the parent process exits. Also it restarts the child process if it dies. /// Class responsible for launching the Node child process, determining when it is ready to accept invocations,
*/ /// and finally killing it when the parent process exits. Also it restarts the child process if it dies.
public abstract class OutOfProcessNodeInstance : INodeServices { /// </summary>
private object _childProcessLauncherLock; /// <seealso cref="Microsoft.AspNetCore.NodeServices.INodeServices" />
private bool disposed; public abstract class OutOfProcessNodeInstance : INodeServices
private StringAsTempFile _entryPointScript; {
private string _projectPath; private readonly object _childProcessLauncherLock;
private string _commandLineArguments; private readonly string _commandLineArguments;
private Process _nodeProcess; private readonly StringAsTempFile _entryPointScript;
private TaskCompletionSource<bool> _nodeProcessIsReadySource; private TaskCompletionSource<bool> _nodeProcessIsReadySource;
private readonly string _projectPath;
protected Process NodeProcess { private bool _disposed;
get {
// This is only exposed to support the unreliable OutOfProcessNodeRunner, which is just to verify that
// other hosting/transport mechanisms are possible. This shouldn't really be exposed.
return this._nodeProcess;
}
}
public OutOfProcessNodeInstance(string entryPointScript, string projectPath, string commandLineArguments = null) public OutOfProcessNodeInstance(string entryPointScript, string projectPath, string commandLineArguments = null)
{ {
this._childProcessLauncherLock = new object(); _childProcessLauncherLock = new object();
this._entryPointScript = new StringAsTempFile(entryPointScript); _entryPointScript = new StringAsTempFile(entryPointScript);
this._projectPath = projectPath; _projectPath = projectPath;
this._commandLineArguments = commandLineArguments ?? string.Empty; _commandLineArguments = commandLineArguments ?? string.Empty;
} }
public abstract Task<T> Invoke<T>(NodeInvocationInfo invocationInfo); protected Process NodeProcess { get; private set; }
public Task<T> Invoke<T>(string moduleName, params object[] args) { public Task<T> Invoke<T>(string moduleName, params object[] args)
return this.InvokeExport<T>(moduleName, null, args); => InvokeExport<T>(moduleName, null, args);
}
public async Task<T> InvokeExport<T>(string moduleName, string exportedFunctionName, params object[] args) { public Task<T> InvokeExport<T>(string moduleName, string exportedFunctionName, params object[] args)
return await this.Invoke<T>(new NodeInvocationInfo { => Invoke<T>(new NodeInvocationInfo
{
ModuleName = moduleName, ModuleName = moduleName,
ExportedFunctionName = exportedFunctionName, ExportedFunctionName = exportedFunctionName,
Args = args Args = args
}); });
}
protected async Task EnsureReady() {
lock (this._childProcessLauncherLock) {
if (this._nodeProcess == null || this._nodeProcess.HasExited) {
var startInfo = new ProcessStartInfo("node") {
Arguments = "\"" + this._entryPointScript.FileName + "\" " + this._commandLineArguments,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = this._projectPath
};
// Append projectPath to NODE_PATH so it can locate node_modules
var existingNodePath = Environment.GetEnvironmentVariable("NODE_PATH") ?? string.Empty;
if (existingNodePath != string.Empty) {
existingNodePath += ":";
}
var nodePathValue = existingNodePath + Path.Combine(this._projectPath, "node_modules");
#if NET451
startInfo.EnvironmentVariables.Add("NODE_PATH", nodePathValue);
#else
startInfo.Environment.Add("NODE_PATH", nodePathValue);
#endif
this.OnBeforeLaunchProcess();
this._nodeProcess = Process.Start(startInfo);
this.ConnectToInputOutputStreams();
}
}
var task = this._nodeProcessIsReadySource.Task;
var initializationSucceeded = await task;
if (!initializationSucceeded) {
throw new InvalidOperationException("The Node.js process failed to initialize", task.Exception);
}
}
private void ConnectToInputOutputStreams() {
var initializationIsCompleted = false; // TODO: Make this thread-safe? (Interlocked.Exchange etc.)
this._nodeProcessIsReadySource = new TaskCompletionSource<bool>();
this._nodeProcess.OutputDataReceived += (sender, evt) => {
if (evt.Data == "[Microsoft.AspNetCore.NodeServices:Listening]" && !initializationIsCompleted) {
this._nodeProcessIsReadySource.SetResult(true);
initializationIsCompleted = true;
} else if (evt.Data != null) {
this.OnOutputDataReceived(evt.Data);
}
};
this._nodeProcess.ErrorDataReceived += (sender, evt) => {
if (evt.Data != null) {
this.OnErrorDataReceived(evt.Data);
if (!initializationIsCompleted) {
this._nodeProcessIsReadySource.SetResult(false);
initializationIsCompleted = true;
}
}
};
this._nodeProcess.BeginOutputReadLine();
this._nodeProcess.BeginErrorReadLine();
}
protected virtual void OnBeforeLaunchProcess() {
}
protected virtual void OnOutputDataReceived(string outputData) {
Console.WriteLine("[Node] " + outputData);
}
protected virtual void OnErrorDataReceived(string errorData) {
Console.WriteLine("[Node] " + errorData);
}
public void Dispose() public void Dispose()
{ {
@@ -130,23 +46,124 @@ namespace Microsoft.AspNetCore.NodeServices {
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
protected virtual void Dispose(bool disposing) public abstract Task<T> Invoke<T>(NodeInvocationInfo invocationInfo);
protected async Task EnsureReady()
{ {
if (!disposed) { lock (_childProcessLauncherLock)
if (disposing) { {
this._entryPointScript.Dispose(); if (NodeProcess == null || NodeProcess.HasExited)
} {
var startInfo = new ProcessStartInfo("node")
{
Arguments = "\"" + _entryPointScript.FileName + "\" " + _commandLineArguments,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = _projectPath
};
if (this._nodeProcess != null && !this._nodeProcess.HasExited) { // Append projectPath to NODE_PATH so it can locate node_modules
this._nodeProcess.Kill(); // TODO: Is there a more graceful way to end it? Or does this still let it perform any cleanup? var existingNodePath = Environment.GetEnvironmentVariable("NODE_PATH") ?? string.Empty;
} if (existingNodePath != string.Empty)
{
existingNodePath += ":";
}
disposed = true; var nodePathValue = existingNodePath + Path.Combine(_projectPath, "node_modules");
#if NET451
startInfo.EnvironmentVariables.Add("NODE_PATH", nodePathValue);
#else
startInfo.Environment.Add("NODE_PATH", nodePathValue);
#endif
OnBeforeLaunchProcess();
NodeProcess = Process.Start(startInfo);
ConnectToInputOutputStreams();
}
}
var task = _nodeProcessIsReadySource.Task;
var initializationSucceeded = await task;
if (!initializationSucceeded)
{
throw new InvalidOperationException("The Node.js process failed to initialize", task.Exception);
} }
} }
~OutOfProcessNodeInstance() { private void ConnectToInputOutputStreams()
Dispose (false); {
var initializationIsCompleted = false; // TODO: Make this thread-safe? (Interlocked.Exchange etc.)
_nodeProcessIsReadySource = new TaskCompletionSource<bool>();
NodeProcess.OutputDataReceived += (sender, evt) =>
{
if (evt.Data == "[Microsoft.AspNetCore.NodeServices:Listening]" && !initializationIsCompleted)
{
_nodeProcessIsReadySource.SetResult(true);
initializationIsCompleted = true;
}
else if (evt.Data != null)
{
OnOutputDataReceived(evt.Data);
}
};
NodeProcess.ErrorDataReceived += (sender, evt) =>
{
if (evt.Data != null)
{
OnErrorDataReceived(evt.Data);
if (!initializationIsCompleted)
{
_nodeProcessIsReadySource.SetResult(false);
initializationIsCompleted = true;
}
}
};
NodeProcess.BeginOutputReadLine();
NodeProcess.BeginErrorReadLine();
}
protected virtual void OnBeforeLaunchProcess()
{
}
protected virtual void OnOutputDataReceived(string outputData)
{
Console.WriteLine("[Node] " + outputData);
}
protected virtual void OnErrorDataReceived(string errorData)
{
Console.WriteLine("[Node] " + errorData);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_entryPointScript.Dispose();
}
if (NodeProcess != null && !NodeProcess.HasExited)
{
NodeProcess.Kill();
// TODO: Is there a more graceful way to end it? Or does this still let it perform any cleanup?
}
_disposed = true;
}
}
~OutOfProcessNodeInstance()
{
Dispose(false);
} }
} }
} }

View File

@@ -1,8 +1,10 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Microsoft.AspNetCore.NodeServices { namespace Microsoft.AspNetCore.NodeServices
public interface INodeServices : IDisposable { {
public interface INodeServices : IDisposable
{
Task<T> Invoke<T>(string moduleName, params object[] args); Task<T> Invoke<T>(string moduleName, params object[] args);
Task<T> InvokeExport<T>(string moduleName, string exportedFunctionName, params object[] args); Task<T> InvokeExport<T>(string moduleName, string exportedFunctionName, params object[] args);

View File

@@ -9,11 +9,10 @@
<ProjectGuid>b0fa4175-8b29-4904-9780-28b3c24b0567</ProjectGuid> <ProjectGuid>b0fa4175-8b29-4904-9780-28b3c24b0567</ProjectGuid>
<RootNamespace>Microsoft.AspNetCore.NodeServices</RootNamespace> <RootNamespace>Microsoft.AspNetCore.NodeServices</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath> <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\JavaScriptServices.sln\artifacts\bin\$(MSBuildProjectName)\</OutputPath> <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project> </Project>

View File

@@ -1,5 +1,7 @@
namespace Microsoft.AspNetCore.NodeServices { namespace Microsoft.AspNetCore.NodeServices
public enum NodeHostingModel { {
public enum NodeHostingModel
{
Http, Http,
InputOutputStream, InputOutputStream,
} }

View File

@@ -0,0 +1,14 @@
namespace Microsoft.AspNetCore.NodeServices
{
public class NodeServicesOptions
{
public NodeServicesOptions()
{
HostingModel = NodeHostingModel.Http;
}
public NodeHostingModel HostingModel { get; set; }
public string ProjectPath { get; set; }
public string[] WatchFileExtensions { get; set; }
}
}

View File

@@ -2,16 +2,20 @@ using System;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
namespace Microsoft.AspNetCore.NodeServices { namespace Microsoft.AspNetCore.NodeServices
public static class EmbeddedResourceReader { {
public static string Read(Type assemblyContainingType, string path) { public static class EmbeddedResourceReader
{
public static string Read(Type assemblyContainingType, string path)
{
var asm = assemblyContainingType.GetTypeInfo().Assembly; var asm = assemblyContainingType.GetTypeInfo().Assembly;
var embeddedResourceName = asm.GetName().Name + path.Replace("/", "."); var embeddedResourceName = asm.GetName().Name + path.Replace("/", ".");
using (var stream = asm.GetManifestResourceStream(embeddedResourceName)) using (var stream = asm.GetManifestResourceStream(embeddedResourceName))
using (var sr = new StreamReader(stream)) { using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd(); return sr.ReadToEnd();
} }
} }
} }
} }

View File

@@ -1,39 +1,45 @@
using System; using System;
using System.IO; using System.IO;
namespace Microsoft.AspNetCore.NodeServices { namespace Microsoft.AspNetCore.NodeServices
{
// Makes it easier to pass script files to Node in a way that's sure to clean up after the process exits // Makes it easier to pass script files to Node in a way that's sure to clean up after the process exits
public sealed class StringAsTempFile : IDisposable { public sealed class StringAsTempFile : IDisposable
public string FileName { get; private set; } {
private bool _disposedValue; private bool _disposedValue;
public StringAsTempFile(string content) { public StringAsTempFile(string content)
this.FileName = Path.GetTempFileName();
File.WriteAllText(this.FileName, content);
}
private void DisposeImpl(bool disposing)
{ {
if (!_disposedValue) { FileName = Path.GetTempFileName();
if (disposing) { File.WriteAllText(FileName, content);
// TODO: dispose managed state (managed objects).
}
File.Delete(this.FileName);
_disposedValue = true;
}
} }
public string FileName { get; }
public void Dispose() public void Dispose()
{ {
DisposeImpl(true); DisposeImpl(true);
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
~StringAsTempFile() { private void DisposeImpl(bool disposing)
DisposeImpl(false); {
if (!_disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
File.Delete(FileName);
_disposedValue = true;
}
}
~StringAsTempFile()
{
DisposeImpl(false);
} }
} }
} }

View File

@@ -9,11 +9,10 @@
<ProjectGuid>b04381de-991f-4831-a0b5-fe1bd3ef80c4</ProjectGuid> <ProjectGuid>b04381de-991f-4831-a0b5-fe1bd3ef80c4</ProjectGuid>
<RootNamespace>Microsoft.AspNetCore.ReactServices</RootNamespace> <RootNamespace>Microsoft.AspNetCore.ReactServices</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath> <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\artifacts\bin\$(MSBuildProjectName)\</OutputPath> <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project> </Project>

View File

@@ -9,11 +9,10 @@
<ProjectGuid>4624f728-6dff-44b6-93b5-3c7d9c94bf3f</ProjectGuid> <ProjectGuid>4624f728-6dff-44b6-93b5-3c7d9c94bf3f</ProjectGuid>
<RootNamespace>Microsoft.AspNetCore.SpaServices</RootNamespace> <RootNamespace>Microsoft.AspNetCore.SpaServices</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath> <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\artifacts\bin\$(MSBuildProjectName)\</OutputPath> <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project> </Project>

View File

@@ -0,0 +1,14 @@
namespace Microsoft.AspNetCore.SpaServices.Prerendering
{
public class JavaScriptModuleExport
{
public JavaScriptModuleExport(string moduleName)
{
this.ModuleName = moduleName;
}
public string ModuleName { get; private set; }
public string ExportName { get; set; }
public string WebpackConfig { get; set; }
}
}

View File

@@ -16,11 +16,31 @@ namespace Microsoft.AspNetCore.SpaServices.Prerendering
[HtmlTargetElement(Attributes = PrerenderModuleAttributeName)] [HtmlTargetElement(Attributes = PrerenderModuleAttributeName)]
public class PrerenderTagHelper : TagHelper public class PrerenderTagHelper : TagHelper
{ {
static INodeServices fallbackNodeServices; // Used only if no INodeServices was registered with DI private const string PrerenderModuleAttributeName = "asp-prerender-module";
private const string PrerenderExportAttributeName = "asp-prerender-export";
private const string PrerenderWebpackConfigAttributeName = "asp-prerender-webpack-config";
private static INodeServices _fallbackNodeServices; // Used only if no INodeServices was registered with DI
const string PrerenderModuleAttributeName = "asp-prerender-module"; private readonly string _applicationBasePath;
const string PrerenderExportAttributeName = "asp-prerender-export"; private readonly INodeServices _nodeServices;
const string PrerenderWebpackConfigAttributeName = "asp-prerender-webpack-config";
public PrerenderTagHelper(IServiceProvider serviceProvider)
{
var hostEnv = (IHostingEnvironment) serviceProvider.GetService(typeof(IHostingEnvironment));
_nodeServices = (INodeServices) serviceProvider.GetService(typeof(INodeServices)) ?? _fallbackNodeServices;
_applicationBasePath = hostEnv.ContentRootPath;
// Consider removing the following. Having it means you can get away with not putting app.AddNodeServices()
// in your startup file, but then again it might be confusing that you don't need to.
if (_nodeServices == null)
{
_nodeServices = _fallbackNodeServices = Configuration.CreateNodeServices(new NodeServicesOptions
{
HostingModel = NodeHostingModel.Http,
ProjectPath = _applicationBasePath
});
}
}
[HtmlAttributeName(PrerenderModuleAttributeName)] [HtmlAttributeName(PrerenderModuleAttributeName)]
public string ModuleName { get; set; } public string ModuleName { get; set; }
@@ -35,52 +55,37 @@ namespace Microsoft.AspNetCore.SpaServices.Prerendering
[ViewContext] [ViewContext]
public ViewContext ViewContext { get; set; } public ViewContext ViewContext { get; set; }
private string applicationBasePath;
private INodeServices nodeServices;
public PrerenderTagHelper(IServiceProvider serviceProvider)
{
var hostEnv = (IHostingEnvironment)serviceProvider.GetService(typeof (IHostingEnvironment));
this.nodeServices = (INodeServices)serviceProvider.GetService(typeof (INodeServices)) ?? fallbackNodeServices;
this.applicationBasePath = hostEnv.ContentRootPath;
// Consider removing the following. Having it means you can get away with not putting app.AddNodeServices()
// in your startup file, but then again it might be confusing that you don't need to.
if (this.nodeServices == null) {
this.nodeServices = fallbackNodeServices = Configuration.CreateNodeServices(new NodeServicesOptions {
HostingModel = NodeHostingModel.Http,
ProjectPath = this.applicationBasePath
});
}
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{ {
var request = this.ViewContext.HttpContext.Request; var request = ViewContext.HttpContext.Request;
var result = await Prerenderer.RenderToString( var result = await Prerenderer.RenderToString(
applicationBasePath: this.applicationBasePath, _applicationBasePath,
nodeServices: this.nodeServices, _nodeServices,
bootModule: new JavaScriptModuleExport(this.ModuleName) { new JavaScriptModuleExport(ModuleName)
exportName = this.ExportName, {
webpackConfig = this.WebpackConfigPath ExportName = ExportName,
WebpackConfig = WebpackConfigPath
}, },
requestAbsoluteUrl: UriHelper.GetEncodedUrl(request), request.GetEncodedUrl(),
requestPathAndQuery: request.Path + request.QueryString.Value); request.Path + request.QueryString.Value);
output.Content.SetHtmlContent(result.Html); output.Content.SetHtmlContent(result.Html);
// Also attach any specified globals to the 'window' object. This is useful for transferring // Also attach any specified globals to the 'window' object. This is useful for transferring
// general state between server and client. // general state between server and client.
if (result.Globals != null) { if (result.Globals != null)
{
var stringBuilder = new StringBuilder(); var stringBuilder = new StringBuilder();
foreach (var property in result.Globals.Properties()) { foreach (var property in result.Globals.Properties())
{
stringBuilder.AppendFormat("window.{0} = {1};", stringBuilder.AppendFormat("window.{0} = {1};",
property.Name, property.Name,
property.Value.ToString(Formatting.None)); property.Value.ToString(Formatting.None));
} }
if (stringBuilder.Length > 0) { if (stringBuilder.Length > 0)
output.PostElement.SetHtmlContent($"<script>{ stringBuilder.ToString() }</script>"); {
output.PostElement.SetHtmlContent($"<script>{stringBuilder}</script>");
} }
} }
} }
} }
} }

View File

@@ -1,42 +1,34 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.NodeServices; using Microsoft.AspNetCore.NodeServices;
using Newtonsoft.Json.Linq;
namespace Microsoft.AspNetCore.SpaServices.Prerendering namespace Microsoft.AspNetCore.SpaServices.Prerendering
{ {
public static class Prerenderer public static class Prerenderer
{ {
private static Lazy<StringAsTempFile> nodeScript; private static readonly Lazy<StringAsTempFile> NodeScript;
static Prerenderer() { static Prerenderer()
nodeScript = new Lazy<StringAsTempFile>(() => { {
NodeScript = new Lazy<StringAsTempFile>(() =>
{
var script = EmbeddedResourceReader.Read(typeof(Prerenderer), "/Content/Node/prerenderer.js"); var script = EmbeddedResourceReader.Read(typeof(Prerenderer), "/Content/Node/prerenderer.js");
return new StringAsTempFile(script); // Will be cleaned up on process exit return new StringAsTempFile(script); // Will be cleaned up on process exit
}); });
} }
public static async Task<RenderToStringResult> RenderToString(string applicationBasePath, INodeServices nodeServices, JavaScriptModuleExport bootModule, string requestAbsoluteUrl, string requestPathAndQuery) { public static async Task<RenderToStringResult> RenderToString(
return await nodeServices.InvokeExport<RenderToStringResult>(nodeScript.Value.FileName, "renderToString", string applicationBasePath,
INodeServices nodeServices,
JavaScriptModuleExport bootModule,
string requestAbsoluteUrl,
string requestPathAndQuery)
=> await nodeServices.InvokeExport<RenderToStringResult>(
NodeScript.Value.FileName,
"renderToString",
applicationBasePath, applicationBasePath,
bootModule, bootModule,
requestAbsoluteUrl, requestAbsoluteUrl,
requestPathAndQuery); requestPathAndQuery);
}
} }
}
public class JavaScriptModuleExport {
public string moduleName { get; private set; }
public string exportName { get; set; }
public string webpackConfig { get; set; }
public JavaScriptModuleExport(string moduleName) {
this.moduleName = moduleName;
}
}
public class RenderToStringResult {
public string Html;
public JObject Globals;
}
}

View File

@@ -0,0 +1,10 @@
using Newtonsoft.Json.Linq;
namespace Microsoft.AspNetCore.SpaServices.Prerendering
{
public class RenderToStringResult
{
public JObject Globals { get; set; }
public string Html { get; set; }
}
}

View File

@@ -1,5 +1,4 @@
using System; using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing;
@@ -7,26 +6,27 @@ namespace Microsoft.AspNetCore.SpaServices
{ {
internal class SpaRouteConstraint : IRouteConstraint internal class SpaRouteConstraint : IRouteConstraint
{ {
private readonly string clientRouteTokenName; private readonly string _clientRouteTokenName;
public SpaRouteConstraint(string clientRouteTokenName) { public SpaRouteConstraint(string clientRouteTokenName)
if (string.IsNullOrEmpty(clientRouteTokenName)) { {
throw new ArgumentException("Value cannot be null or empty", "clientRouteTokenName"); if (string.IsNullOrEmpty(clientRouteTokenName))
{
throw new ArgumentException("Value cannot be null or empty", nameof(clientRouteTokenName));
} }
this.clientRouteTokenName = clientRouteTokenName; _clientRouteTokenName = clientRouteTokenName;
} }
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) public bool Match(
{ HttpContext httpContext,
var clientRouteValue = (values[this.clientRouteTokenName] as string) ?? string.Empty; IRouter route,
return !HasDotInLastSegment(clientRouteValue); string routeKey,
} RouteValueDictionary values,
RouteDirection routeDirection)
=> !HasDotInLastSegment(values[_clientRouteTokenName] as string ?? string.Empty);
private bool HasDotInLastSegment(string uri) private bool HasDotInLastSegment(string uri)
{ => uri.IndexOf('.', uri.LastIndexOf('/') + 1) >= 0;
var lastSegmentStartPos = uri.LastIndexOf('/');
return uri.IndexOf('.', lastSegmentStartPos + 1) >= 0;
}
} }
} }

View File

@@ -4,18 +4,34 @@ using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.SpaServices; using Microsoft.AspNetCore.SpaServices;
// Putting in this namespace so it's always available whenever MapRoute is // Putting in this namespace so it's always available whenever MapRoute is
namespace Microsoft.AspNetCore.Builder namespace Microsoft.AspNetCore.Builder
{ {
public static class SpaRouteExtensions public static class SpaRouteExtensions
{ {
private const string ClientRouteTokenName = "clientRoute"; private const string ClientRouteTokenName = "clientRoute";
public static void MapSpaFallbackRoute(this IRouteBuilder routeBuilder, string name, object defaults, object constraints = null, object dataTokens = null) public static void MapSpaFallbackRoute(
{ this IRouteBuilder routeBuilder,
MapSpaFallbackRoute(routeBuilder, name, /* templatePrefix */ (string)null, defaults, constraints, dataTokens); string name,
} object defaults,
object constraints = null,
object dataTokens = null)
=> MapSpaFallbackRoute(
routeBuilder,
name,
/* templatePrefix */ null,
defaults,
constraints,
dataTokens);
public static void MapSpaFallbackRoute(this IRouteBuilder routeBuilder, string name, string templatePrefix, object defaults, object constraints = null, object dataTokens = null) public static void MapSpaFallbackRoute(
this IRouteBuilder routeBuilder,
string name,
string templatePrefix,
object defaults,
object constraints = null,
object dataTokens = null)
{ {
var template = CreateRouteTemplate(templatePrefix); var template = CreateRouteTemplate(templatePrefix);
@@ -29,25 +45,27 @@ namespace Microsoft.AspNetCore.Builder
{ {
templatePrefix = templatePrefix ?? string.Empty; templatePrefix = templatePrefix ?? string.Empty;
if (templatePrefix.Contains("?")) { if (templatePrefix.Contains("?"))
{
// TODO: Consider supporting this. The {*clientRoute} part should be added immediately before the '?' // TODO: Consider supporting this. The {*clientRoute} part should be added immediately before the '?'
throw new ArgumentException("SPA fallback route templates don't support querystrings"); throw new ArgumentException("SPA fallback route templates don't support querystrings");
} }
if (templatePrefix.Contains("#")) { if (templatePrefix.Contains("#"))
throw new ArgumentException("SPA fallback route templates should not include # characters. The hash part of a URI does not get sent to the server."); {
throw new ArgumentException(
"SPA fallback route templates should not include # characters. The hash part of a URI does not get sent to the server.");
} }
if (templatePrefix != string.Empty && !templatePrefix.EndsWith("/")) { if (templatePrefix != string.Empty && !templatePrefix.EndsWith("/"))
{
templatePrefix += "/"; templatePrefix += "/";
} }
return templatePrefix + $"{{*{ ClientRouteTokenName }}}"; return templatePrefix + $"{{*{ClientRouteTokenName}}}";
} }
private static IDictionary<string, object> ObjectToDictionary(object value) private static IDictionary<string, object> ObjectToDictionary(object value)
{ => value as IDictionary<string, object> ?? new RouteValueDictionary(value);
return value as IDictionary<string, object> ?? new RouteValueDictionary(value);
}
} }
} }

View File

@@ -8,65 +8,85 @@ using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.SpaServices.Webpack namespace Microsoft.AspNetCore.SpaServices.Webpack
{ {
// Based on https://github.com/aspnet/Proxy/blob/dev/src/Microsoft.AspNetCore.Proxy/ProxyMiddleware.cs /// <summary>
// Differs in that, if the proxied request returns a 404, we pass through to the next middleware in the chain /// Based on https://github.com/aspnet/Proxy/blob/dev/src/Microsoft.AspNetCore.Proxy/ProxyMiddleware.cs
// This is useful for Webpack middleware, because it lets you fall back on prebuilt files on disk for /// Differs in that, if the proxied request returns a 404, we pass through to the next middleware in the chain
// chunks not exposed by the current Webpack config (e.g., DLL/vendor chunks). /// This is useful for Webpack middleware, because it lets you fall back on prebuilt files on disk for
internal class ConditionalProxyMiddleware { /// chunks not exposed by the current Webpack config (e.g., DLL/vendor chunks).
private RequestDelegate next; /// </summary>
private ConditionalProxyMiddlewareOptions options; internal class ConditionalProxyMiddleware
private HttpClient httpClient; {
private string pathPrefix; private readonly HttpClient _httpClient;
private readonly RequestDelegate _next;
private readonly ConditionalProxyMiddlewareOptions _options;
private readonly string _pathPrefix;
public ConditionalProxyMiddleware(RequestDelegate next, string pathPrefix, ConditionalProxyMiddlewareOptions options) public ConditionalProxyMiddleware(
RequestDelegate next,
string pathPrefix,
ConditionalProxyMiddlewareOptions options)
{ {
this.next = next; _next = next;
this.pathPrefix = pathPrefix; _pathPrefix = pathPrefix;
this.options = options; _options = options;
this.httpClient = new HttpClient(new HttpClientHandler()); _httpClient = new HttpClient(new HttpClientHandler());
} }
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
if (context.Request.Path.StartsWithSegments(this.pathPrefix)) { if (context.Request.Path.StartsWithSegments(_pathPrefix))
{
var didProxyRequest = await PerformProxyRequest(context); var didProxyRequest = await PerformProxyRequest(context);
if (didProxyRequest) { if (didProxyRequest)
{
return; return;
} }
} }
// Not a request we can proxy // Not a request we can proxy
await this.next.Invoke(context); await _next.Invoke(context);
} }
private async Task<bool> PerformProxyRequest(HttpContext context) { private async Task<bool> PerformProxyRequest(HttpContext context)
{
var requestMessage = new HttpRequestMessage(); var requestMessage = new HttpRequestMessage();
// Copy the request headers // Copy the request headers
foreach (var header in context.Request.Headers) { foreach (var header in context.Request.Headers)
if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null) { {
if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()))
{
requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()); requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
} }
} }
requestMessage.Headers.Host = options.Host + ":" + options.Port; requestMessage.Headers.Host = _options.Host + ":" + _options.Port;
var uriString = $"{options.Scheme}://{options.Host}:{options.Port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}"; var uriString =
$"{_options.Scheme}://{_options.Host}:{_options.Port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
requestMessage.RequestUri = new Uri(uriString); requestMessage.RequestUri = new Uri(uriString);
requestMessage.Method = new HttpMethod(context.Request.Method); requestMessage.Method = new HttpMethod(context.Request.Method);
using (var responseMessage = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted)) { using (
if (responseMessage.StatusCode == HttpStatusCode.NotFound) { var responseMessage =
await
_httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead,
context.RequestAborted))
{
if (responseMessage.StatusCode == HttpStatusCode.NotFound)
{
// Let some other middleware handle this // Let some other middleware handle this
return false; return false;
} }
// We can handle this // We can handle this
context.Response.StatusCode = (int)responseMessage.StatusCode; context.Response.StatusCode = (int) responseMessage.StatusCode;
foreach (var header in responseMessage.Headers) { foreach (var header in responseMessage.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray(); context.Response.Headers[header.Key] = header.Value.ToArray();
} }
foreach (var header in responseMessage.Content.Headers) { foreach (var header in responseMessage.Content.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray(); context.Response.Headers[header.Key] = header.Value.ToArray();
} }
@@ -77,16 +97,4 @@ namespace Microsoft.AspNetCore.SpaServices.Webpack
} }
} }
} }
}
internal class ConditionalProxyMiddlewareOptions {
public string Scheme { get; private set; }
public string Host { get; private set; }
public string Port { get; private set; }
public ConditionalProxyMiddlewareOptions(string scheme, string host, string port) {
this.Scheme = scheme;
this.Host = host;
this.Port = port;
}
}
}

View File

@@ -0,0 +1,16 @@
namespace Microsoft.AspNetCore.SpaServices.Webpack
{
internal class ConditionalProxyMiddlewareOptions
{
public ConditionalProxyMiddlewareOptions(string scheme, string host, string port)
{
Scheme = scheme;
Host = host;
Port = port;
}
public string Scheme { get; }
public string Host { get; }
public string Port { get; }
}
}

View File

@@ -9,22 +9,31 @@ using Microsoft.Extensions.PlatformAbstractions;
using Newtonsoft.Json; using Newtonsoft.Json;
// Putting in this namespace so it's always available whenever MapRoute is // Putting in this namespace so it's always available whenever MapRoute is
namespace Microsoft.AspNetCore.Builder namespace Microsoft.AspNetCore.Builder
{ {
public static class WebpackDevMiddleware public static class WebpackDevMiddleware
{ {
const string WebpackDevMiddlewareScheme = "http"; private const string WebpackDevMiddlewareScheme = "http";
const string WebpackDevMiddlewareHostname = "localhost"; private const string WebpackDevMiddlewareHostname = "localhost";
const string WebpackHotMiddlewareEndpoint = "/__webpack_hmr"; private const string WebpackHotMiddlewareEndpoint = "/__webpack_hmr";
const string DefaultConfigFile = "webpack.config.js"; private const string DefaultConfigFile = "webpack.config.js";
public static void UseWebpackDevMiddleware(this IApplicationBuilder appBuilder, WebpackDevMiddlewareOptions options = null) { public static void UseWebpackDevMiddleware(
// Validate options this IApplicationBuilder appBuilder,
if (options == null) { WebpackDevMiddlewareOptions options = null)
{
// Prepare options
if (options == null)
{
options = new WebpackDevMiddlewareOptions(); options = new WebpackDevMiddlewareOptions();
} }
if (options.ReactHotModuleReplacement && !options.HotModuleReplacement) {
throw new ArgumentException("To enable ReactHotModuleReplacement, you must also enable HotModuleReplacement."); // Validate options
if (options.ReactHotModuleReplacement && !options.HotModuleReplacement)
{
throw new ArgumentException(
"To enable ReactHotModuleReplacement, you must also enable HotModuleReplacement.");
} }
// Unlike other consumers of NodeServices, WebpackDevMiddleware dosen't share Node instances, nor does it // Unlike other consumers of NodeServices, WebpackDevMiddleware dosen't share Node instances, nor does it
@@ -32,44 +41,55 @@ namespace Microsoft.AspNetCore.Builder
// because it must *not* restart when files change (if it did, you'd lose all the benefits of Webpack // because it must *not* restart when files change (if it did, you'd lose all the benefits of Webpack
// middleware). And since this is a dev-time-only feature, it doesn't matter if the default transport isn't // middleware). And since this is a dev-time-only feature, it doesn't matter if the default transport isn't
// as fast as some theoretical future alternative. // as fast as some theoretical future alternative.
var hostEnv = (IHostingEnvironment)appBuilder.ApplicationServices.GetService(typeof (IHostingEnvironment)); var hostEnv = (IHostingEnvironment)appBuilder.ApplicationServices.GetService(typeof(IHostingEnvironment));
var nodeServices = Configuration.CreateNodeServices(new NodeServicesOptions { var nodeServices = Configuration.CreateNodeServices(new NodeServicesOptions
{
HostingModel = NodeHostingModel.Http, HostingModel = NodeHostingModel.Http,
ProjectPath = hostEnv.ContentRootPath, ProjectPath = hostEnv.ContentRootPath,
WatchFileExtensions = new string[] {} // Don't watch anything WatchFileExtensions = new string[] { } // Don't watch anything
}); });
// Get a filename matching the middleware Node script // Get a filename matching the middleware Node script
var script = EmbeddedResourceReader.Read(typeof (WebpackDevMiddleware), "/Content/Node/webpack-dev-middleware.js"); var script = EmbeddedResourceReader.Read(typeof(WebpackDevMiddleware),
"/Content/Node/webpack-dev-middleware.js");
var nodeScript = new StringAsTempFile(script); // Will be cleaned up on process exit var nodeScript = new StringAsTempFile(script); // Will be cleaned up on process exit
// Tell Node to start the server hosting webpack-dev-middleware // Tell Node to start the server hosting webpack-dev-middleware
var devServerOptions = new { var devServerOptions = new
{
webpackConfigPath = Path.Combine(hostEnv.ContentRootPath, options.ConfigFile ?? DefaultConfigFile), webpackConfigPath = Path.Combine(hostEnv.ContentRootPath, options.ConfigFile ?? DefaultConfigFile),
suppliedOptions = options suppliedOptions = options
}; };
var devServerInfo = nodeServices.InvokeExport<WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer", JsonConvert.SerializeObject(devServerOptions)).Result; var devServerInfo =
nodeServices.InvokeExport<WebpackDevServerInfo>(nodeScript.FileName, "createWebpackDevServer",
JsonConvert.SerializeObject(devServerOptions)).Result;
// Proxy the corresponding requests through ASP.NET and into the Node listener // Proxy the corresponding requests through ASP.NET and into the Node listener
var proxyOptions = new ConditionalProxyMiddlewareOptions(WebpackDevMiddlewareScheme, WebpackDevMiddlewareHostname, devServerInfo.Port.ToString()); var proxyOptions = new ConditionalProxyMiddlewareOptions(WebpackDevMiddlewareScheme,
WebpackDevMiddlewareHostname, devServerInfo.Port.ToString());
appBuilder.UseMiddleware<ConditionalProxyMiddleware>(devServerInfo.PublicPath, proxyOptions); appBuilder.UseMiddleware<ConditionalProxyMiddleware>(devServerInfo.PublicPath, proxyOptions);
// While it would be nice to proxy the /__webpack_hmr requests too, these return an EventStream, // While it would be nice to proxy the /__webpack_hmr requests too, these return an EventStream,
// and the Microsoft.AspNetCore.Proxy code doesn't handle that entirely - it throws an exception after // and the Microsoft.AspNetCore.Proxy code doesn't handle that entirely - it throws an exception after
// a while. So, just serve a 302 for those. // a while. So, just serve a 302 for those.
appBuilder.Map(WebpackHotMiddlewareEndpoint, builder => { appBuilder.Map(WebpackHotMiddlewareEndpoint, builder =>
builder.Use(next => async ctx => { {
ctx.Response.Redirect($"{ WebpackDevMiddlewareScheme }://{ WebpackDevMiddlewareHostname }:{ devServerInfo.Port.ToString() }{ WebpackHotMiddlewareEndpoint }"); builder.Use(next => async ctx =>
{
ctx.Response.Redirect(
$"{WebpackDevMiddlewareScheme}://{WebpackDevMiddlewareHostname}:{devServerInfo.Port.ToString()}{WebpackHotMiddlewareEndpoint}");
await Task.Yield(); await Task.Yield();
}); });
}); });
} }
#pragma warning disable CS0649 #pragma warning disable CS0649
class WebpackDevServerInfo { class WebpackDevServerInfo
public int Port; {
public string PublicPath; public int Port { get; set; }
public string PublicPath { get; set; }
} }
#pragma warning restore CS0649
} }
#pragma warning restore CS0649
} }
}

View File

@@ -1,7 +1,9 @@
namespace Microsoft.AspNetCore.SpaServices.Webpack { namespace Microsoft.AspNetCore.SpaServices.Webpack
public class WebpackDevMiddlewareOptions { {
public class WebpackDevMiddlewareOptions
{
public bool HotModuleReplacement { get; set; } public bool HotModuleReplacement { get; set; }
public bool ReactHotModuleReplacement { get; set; } public bool ReactHotModuleReplacement { get; set; }
public string ConfigFile { get; set; } public string ConfigFile { get; set; }
} }
} }

View File

@@ -10,11 +10,11 @@
<ProjectGuid>8f5cb8a9-3086-4b49-a1c2-32a9f89bca11</ProjectGuid> <ProjectGuid>8f5cb8a9-3086-4b49-a1c2-32a9f89bca11</ProjectGuid>
<RootNamespace>Angular2Spa</RootNamespace> <RootNamespace>Angular2Spa</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath> <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\bin\$(MSBuildProjectName)\</OutputPath> <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<DevelopmentServerPort>2018</DevelopmentServerPort> <DevelopmentServerPort>2018</DevelopmentServerPort>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project> </Project>

View File

@@ -10,11 +10,11 @@
<ProjectGuid>dbfc6db0-a6d1-4694-a108-1c604b988da3</ProjectGuid> <ProjectGuid>dbfc6db0-a6d1-4694-a108-1c604b988da3</ProjectGuid>
<RootNamespace>ReactReduxSpa</RootNamespace> <RootNamespace>ReactReduxSpa</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath> <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\bin\$(MSBuildProjectName)\</OutputPath> <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<DevelopmentServerPort>2018</DevelopmentServerPort> <DevelopmentServerPort>2018</DevelopmentServerPort>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project> </Project>

View File

@@ -10,11 +10,11 @@
<ProjectGuid>e9d1a695-f0e6-46f2-b5e3-72f4af805387</ProjectGuid> <ProjectGuid>e9d1a695-f0e6-46f2-b5e3-72f4af805387</ProjectGuid>
<RootNamespace>ReactSpa</RootNamespace> <RootNamespace>ReactSpa</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath> <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\bin\$(MSBuildProjectName)\</OutputPath> <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<DevelopmentServerPort>2018</DevelopmentServerPort> <DevelopmentServerPort>2018</DevelopmentServerPort>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project> </Project>

View File

@@ -10,11 +10,11 @@
<ProjectGuid>cb4398d6-b7f1-449a-ae02-828769679232</ProjectGuid> <ProjectGuid>cb4398d6-b7f1-449a-ae02-828769679232</ProjectGuid>
<RootNamespace>WebApplicationBasic</RootNamespace> <RootNamespace>WebApplicationBasic</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath> <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\..\..\JavaScriptServices.sln\artifacts\bin\$(MSBuildProjectName)\</OutputPath> <OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<DevelopmentServerPort>2018</DevelopmentServerPort> <DevelopmentServerPort>2018</DevelopmentServerPort>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project> </Project>