HTML 5 routing with Angular Cli on Ng server

If you are using Html 5 routing with old browsers (IE 11), probably you need special server side configuration (I am using this on IIS), . This article shows how to setup developer server routing in Angular Cli.

Using Angular Proxy to Backend

The Angular4 Cli is running on webpack dev server. Anyway Angular Cli natively supports only Proxy to backend configuration. It allows to setup which url pattern is being redirected internally by webserver. The configuration also allows to (redirect for example to localhost) and rewrite according to regex rules (provided by http=proxy=middleware module. The ng server needs configuration file, for example proxy.config.json and start ng serve with special parameter –proxy-config  to load configuration file.

The proxy.config.json file can look like this:

{
  "/": {
    "pathRewrite": {"^/(.+)": "/"},
    "target": "http://localhost:4200",
    "secure": false,
    "logLevel": "debug"
   }
}

The first line (with “/”) is asking to redirect all requests according to configuration in block.

The pathRewrite is doing to actual work. It changes url, which starts with / followed by some characters. The even better version could exclude strings with . (dot) like icon.gif from redirection, but this works well. Whatever is in form of slash and characters will be send to root “/” on server.

The target is the remote server, where your request is being proxied. It turns out this is required option. The original intent is to allow resending for example /api to another server. For our use we can use same server which ng server is hosting. In this case localhost.

To start ng server, with the config file use following argument:

ng serve --host localhost --proxy-config proxy.config.json --env dev --open

Common issues

If proxy doesnt work, verbose dev logging can be used to show redirections. Also, at the start lf ng serve, you should see two lines like:
[HPM] Proxy created: / -> http://localhost
[HPM] Proxy rewrite rule created: "^/(.+)" ~> "/"

Hopefully it helps.

Logging to a file with .NET Core

In the .net Core 1.0 the simple logging to a file is not included by default. I wanted to use the default logger infrastructure and also add support for TextWriterTraceListener. This article is showing how to do this.

Configuration in appsettings.json

The standard appsettings.json configuration file has Logging section, even with LogLevel subsection and looks like this:

"Logging": {
   "IncludeScopes": false,
   "LogLevel": {
   "Default": "Warning"
  }
 }
Let's reuse what we have and provide Log location here:
"LogFile": ".\\logs\\log.txt",

in the Application folder would need to be created logs folder. If you use IIS hosting with, you would need to add permissions to this folder for dynamic pool identity user.

The main configuration

In the Configure method, which is in Startup.cs, add these lines:

 

The AddTextWriter is adding TextWriter output to logger factory configuration – from the Configuration (appsettings.json). Then, we are creating concrete logger for this one class and log Info level message.

The AddTextWriter uses same Extensions based configuration style, so I have created ILoggerFactoryExtensions class to host them. Here is the whole class:

 

The AddTraceSource is reading from Configuration file, and tries to find full path to produced file – based on value in appsettings.json. Then creates new “old” TextWriterTraceListener, which passes as loggerFactory as new TraceSource

The loggerFactory’s AddTraceSource is only available if you add Nuget package “Microsoft.Extensions.Logging.TraceSource”.

The .net core LogLevel, used as level for TraceSource can have a bit different values, then SourceLevels enum, so I have simple conversion there.

The actual use is already shown in Configure method above. Once configured, its using standard .net core LoggerFactory, which can be injected in required methods.

Configuring EntityFramework for .NET Core

I will try to show some real example of .net core way of configuring Entity Framework Code First in this article. Microsoft documentation shows some examples, but the solution there creates one DbContext and stores it in DI container.

Downsize of that solution is that you cannot dispose container obtained from DI.

Better solution is to create a Factory class, store it as Singleton into Di container and create DbContext with this service.

public class MyDataContextFactory : IDataContextFactory
{
const string ConnectionStringName = "MyDbConn";
IConfigurationRoot configuration;
public DataContextFactory(IConfigurationRoot Configuration)
{
configuration = Configuration;
}
public DataContext Create()
{
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlServer(
configuration.GetConnectionString(ConnectionStringName));
return new MyDataContext(optionsBuilder.Options);
}
}

Also, for this class, we would create interface IMyDataContextFactory, which will look like this:

public interface IMyDataContextFactory
{
MyDataContext Create();
}

The meat of this class is the method Create, which reads from Configuration the Db connection string and creates particular instance of DbContext. In my case called MyDataContext. I am passing Sql connection string read from configuration.

The class is taking IConfigurationRoot as only parameter, so that it could read from .Net Core Configuration. This is usually appsettings.json, but its up to your application.

Configuration and registration of the service

When you look to your Program.cs, you can see it configured like for example this:

public class Program
{
public static IConfigurationRoot Configuration { get; set; }
public static void Main(string[] args = null)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
/// and so on...

Please notice Configuration is – when created to class member.
The next step is to add Factory method to .Net core dependency injection container. In the Startup.cs file, locate your existing ConfigureServices, which is used for these things and add our line for example to end of it:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Register MyDataContextFactory here
services.AddSingleton(
new DataContextFactory(Configuration));
}

How to use it in Controllers

The use is then similar to other Net Core DI services. We need to add our factory interface to particular Controller constructor, to get injected by DI automatically. It will look like this:

public class ValueController : Controller
{
private IMyDataContextFactory myDataContextFactory;
public ValueController(IMyDataContextFactory myDataContextFactory)
{
this.myDataContextFactory=myDataContextFactory;
}
// and so on

And use is then very simple, for example in same controller I can have method like:

public class ValueController : Controller
{
// ...
[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(long id)
{
using (var context = dataContextFactory.Create())
{
var item = context.TodoItems.FirstOrDefault(t => t.Id == id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
// ...

So it is, hopefully this will help someone.

Thanks for reading.

Queueing items to ThreadPool

The simplicity of this approach is astonishing. And it was in .net since .net 4, but our eyes are not always looking in the direction we should.

ThreadPool.QueueUserWorkItem

The method is offering overload with Action delegate and argument. Actually the argument is significant. If it is blocking function it will Queue the new action only when it stops blocking.

Thus the simple http server can only be:

while(true) {
   ThreadPool.QueueUserWorkItem(Process, listener.GetContext());    
 }

void Process(object o)
 {    var context = o as HttpListenerContext;
    // process request and make response
}

We are waiting until someone connects. And yes it only processes maximally pool-size amount of concurrent connections. But that is another story I think. I wanted to share the beauty of this solution.

Inspiration was from
https://codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server
https://stackoverflow.com/questions/9034721/handling-multiple-requests-with-c-sharp-httplistener

Inspecting Wix Managed Custom Actions

logo-black-hollow-xs

Wix Toolset allows creating .net managed Custom actions for the Windows Installers. Windows Installer only supports

Custom Actions in .exe, VBScript, JScript and .dll

The tool which marshals std call to native dll function into managed code is called Deployment Tools Foundation (DTF).

image

When you open an Msi with managed CA in Orca, you will see it as a native .dll in Binary table. You can also notice WixCA binary attachment named after your binary , which basically encapsulates all DTF code which extracts managed CA.

For example your binary in a .wxs file:

<Binary Id=”CustomActionBinary” SourceFile=”$(var.CA.TargetDir)$(var.CA.TargetName).CA.dll”/>

If you export your binary as .dll and open it in Dependency Walker you will see your Custom Action name as exported function in .dll

image

The CA binary is actually created by MakeSfxCA, which is actually attaching all CA managed binaries and WixCA in a .dll as Windows Cab file.

For example 7Zip can extract cabinet files to actual content:

image

And here is how it looks in ILSpy

image

Full HTTP/2 Support in Windows 10

The Windows 10 supports HTTP/2 not only in its IE12 browser, but also in its IIS. IIS will serve static & dynamic ASPX pages with the new protocol automatically without any additional settings.

Only drawback currently stated by MS here is that sites needs to support HTTPS.

The Browser support

The HTTP/2 is implemented as protocol in WinINet and can be enabled in the Internet Options (IE –> Tools -> Internet Options).

It means any other application when enabled can take advantage of consuming HTTP/2 content. (Namely WWA Hosted Metro applications)

Picture: Enabling HTTP/2 in Internet Options
image  

The Server Support

The server implementation of HTTP/2 is now full full IIS based implementation. It is quite improvement from already published HTTP/2 in Katana which is limited to just „TLSv1.2 and DHE or EDCHE with GCM cipher suite“.

The implementation is most probably inside the HTTP kernel driver called http.sys (as investigated here) and can be used by any HttpListener on Win 10 Tech Preview.

Picture: Internet Explorer 12 with a site using HTTP/2 hosted on IIS
image

Here is how to create simple HTTPS Site on Win10 IIS

1. Create SSL Certificate in IIS.
Open the IIS Manager, select the server name and from the Features open the Server Certificates
image

Then select Create Self Signed Certificate in the Right pane:
image

In the Create Self-Signed Certificate dialog, just fill the name:
image

 

2. Created new HTTPS Site in the IIS
Select Add Website from the IIS Hostname in the manager
image

Fill in the name, physical path, the binding type to HTTPS. The Hostname is usefull to fill in in case of remote access to your Win10. Then you have to select previously created certificate.
image

Now, we have created the new IIS Site. It will already serve the requests, but we dont have anything to serve yet. I crated simple index.aspx file in my WebSite path (c:\inetpub\testsite) with this content:

<form runat=”server”>
<% Response.Write(“Hello, World !”); %>
</form>

Other browsers:

I have also tried accessing using IE 11, which still uses just HTTPS for that site:

image

In the other hand, Firefox Nightly already implements the HTTP/2 correctly:

image

Windows 10 is one of first with the full stack implementation of HTTP/2 today. We can now experiment more with our ASPX applications speed.

Firefox Nightly in Visual Studio

Building Firefox nightly

The Mozilla’s documentation about compiling Firefox is pretty straightforward. On Windows, you basically need just

  1. Build prerequisities which mostly means some Visual Studio edition + MozillaBuild package.
  2. Second step is just to go to extracted MozillaBuild package folder and start apropriate command prompt (bash + some paths).
  3. In this new command window, get sources using hg (Mercurial client, which is part of MozillaBuild package & paths).
  4. Set to some folder where you would like to deploy Firefox sources and start hg. The command is:

    hg clone https://hg.mozilla.org/mozilla-central

  5. start the build in using:
    ./mach build
  6. Start the built Firefox, using
    ./mach run

Using Firefox nightly from Visual Studio

Now you should have Firefox running, built by the Mozilla scripts. There is no way how to build everything in Visual Studio, but you can open the browser in that and debug it. Its limited to just browser itself and some internal libraries are not included, for example NSS (library serving the work with HTTPS). To generate the Visual Studio project you need to return to your MozillaBuild prompt, (you should sill be in your mozilla sources folder) and enter:

./mach build-backend -b VisualStudio

after this command, you will get a .sln file generated in your Firefox sources folder under

.\obj-i686-pc-mingw32\msvc\mozilla.sln

You can open this in Visual Studio (2013 in my case) without a problem.

Enable logging of LOG messages

When you will be looking at code you will find, that there is a pretty amount of log messages being logged using LOG or LOG3 macros. These are actually logging if you enable logging for your module. If you want to log everything, just set these Windows variables before starting new firefox.exe:
set NSPR_LOG_FILE=%TEMP%\fflog.txt
set NSPR_LOG_MODULES=all:5

Then the log file is generated under %TEMP%\fflog.txt. To open just use

notepad.exe %TEMP%\fflog.txt

Debugging Firefox in Visual Studio

Its actually not a big deal, just attach your Visual Studio to running firefox.exe and set a breakpoint and you are good to go.