Category Archives: .NET

Running .NET Core 2 MVC Application in NGINX Location

NGINX Configuration

In the following paragraphs, we suppose the ASP.NET MVC application is accessible from the URL: http://example.com/mvcmovie

In the /etc/nginx/sites-available/example.com configuration file, set the following location.

location /mvcmovie/ {
   proxy_pass http://127.0.0.1:5000/mvcmovie/;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection keep-alive;
   proxy_set_header Host $http_host;
   proxy_cache_bypass $http_upgrade;
}

The slash characters at the end of the location name and “proxy_pass” URL are necessary.

ASP.NET MVC Code

In the Configure method of the Startup class (Startup.cs file), add app.UsePathBase with the name of the location set up in the NGINX configuration file. Do not add a slash character at the end.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   app.UsePathBase("/mvcmovie");
   app .UseForwardedHeaders(newForwardedHeadersOptions
   {  ForwardedHeaders=ForwardedHeaders.XForwardedFor|ForwardedHeaders.XForwardedProto
   });
   if (env.IsDevelopment())
   {
      app.UseDeveloperExceptionPage();
   }
   else
   {
      app.UseExceptionHandler("/Home/Error");
   }
   app.UseStaticFiles();
   app.UseMvc(routes =>
   {
      routes.MapRoute(
         name: "default",
         template: "{controller=Home}/{action=Index}/{id?}");
   });
}

 

Deploy .NET Core 2 MVC Application on Linux ARM with NGINX

The following procedure has been used on Linux Mint 18.3 (Ubuntu 16.04 x86) for the development and Ubuntu 16.04.3 armv7l (Odroid HC1 device) for the deployment.

To develop a .NET Core 2 with Visual Studio Code on Linux x86, follow the Microsoft tutorial  here.

Publish your application for Linux ARM:

dotnet publish -c Release -r linux-arm

Copy the content of the “./bin/Release/netcoreapp2.0/linux-arm/publish” folder to your production server (Odroid for example).

Install nginx

sudo apt-get install nginx

Note

If optional nginx modules will be installed, building nginx from source might be required.


Use apt-get to install nginx. The installer creates a System V init script that runs nginx as daemon on system startup. Since nginx was installed for the first time, explicitly start it by running:

sudo service nginx start

Verify a browser displays the default landing page for nginx.

Configure nginx

To configure nginx as a reverse proxy to forward requests to our ASP.NET Core app, modify /etc/nginx/sites-available/default. Open it in a text editor, and replace the contents with the following:

server {
    listen 80;
    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
    }
}

This nginx configuration file forwards incoming public traffic from port 80 to port 5000.

Once the nginx configuration is established, run sudo nginx -t to verify the syntax of the configuration files. If the configuration file test is successful, force nginx to pick up the changes by running sudo nginx -s reload.

Monitoring the app

The server is setup to forward requests made to http://<serveraddress>:80 on to the ASP.NET Core app running on Kestrel at http://127.0.0.1:5000. However, nginx is not set up to manage the Kestrel process. systemd can be used to create a service file to start and monitor the underlying web app. systemd is an init system that provides many powerful features for starting, stopping, and managing processes.

Create the service file

Create the service definition file:

sudo nano /etc/systemd/system/kestrel-hellomvc.service

The following is an example service file for the app:

[Unit]
Description=Example .NET Web API App running on Ubuntu

[Service]
WorkingDirectory=/var/aspnetcore/hellomvc
ExecStart=/usr/bin/dotnet /var/aspnetcore/hellomvc/hellomvc.dll
Restart=always
RestartSec=10  # Restart service after 10 seconds if dotnet service crashes
SyslogIdentifier=dotnet-example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

Note: If the user www-data is not used by the configuration, the user defined here must be created first and given proper ownership for files.

Save the file and enable the service.

systemctl enable kestrel-hellomvc.service

Start the service and verify that it is running.

systemctl start kestrel-hellomvc.service
systemctl status kestrel-hellomvc.service

● kestrel-hellomvc.service - Example .NET Web API App running on Ubuntu
    Loaded: loaded (/etc/systemd/system/kestrel-hellomvc.service; enabled)
    Active: active (running) since Thu 2016-10-18 04:09:35 NZDT; 35s ago
Main PID: 9021 (dotnet)
    CGroup: /system.slice/kestrel-hellomvc.service
            └─9021 /usr/local/bin/dotnet /var/aspnetcore/hellomvc/hellomvc.dll

With the reverse proxy configured and Kestrel managed through systemd, the web app is fully configured and can be accessed from a browser on the local machine at http://localhost. It is also accessible from a remote machine, barring any firewall that might be blocking. Inspecting the response headers, the Server header shows the ASP.NET Core app being served by Kestrel.

HTTP/1.1 200 OK
Date: Tue, 11 Oct 2016 16:22:23 GMT
Server: Kestrel
Keep-Alive: timeout=5, max=98
Connection: Keep-Alive
Transfer-Encoding: chunked

Viewing logs

Since the web app using Kestrel is managed using systemd, all events and processes are logged to a centralized journal. However, this journal includes all entries for all services and processes managed by systemd. To view the kestrel-hellomvc.service-specific items, use the following command:

sudo journalctl -fu kestrel-hellomvc.service

For further filtering, time options such as --since today--until 1 hour ago or a combination of these can reduce the amount of entries returned.

sudo journalctl -fu kestrel-hellomvc.service --since "2016-10-18" --until "2016-10-18 04:00"

 

Install .NET Core 2 on Ubuntu 16.04 ARM

This post is an extract of the article “Installing Ubuntu 16.04 on a Raspberry Pi 3, installing .NET Core 2, and running a sample .NET Core 2 app” (here) written by Jeremy Lindsay.

He tested .NET Core 2 on Raspberry Pi 3. I tested the framework on ODROID-HC1.

.NET Core 2 Installation

# Update Ubuntu 16.04
sudo apt-get -y update

# Install the packages necessary for .NET Core
sudo apt-get -y install libunwind8 libunwind8-dev gettext libicu-dev liblttng-ust-dev libcurl4-openssl-dev libssl-dev uuid-dev

# Download the latest binaries for .NET Core 2
wget https://dotnetcli.blob.core.windows.net/dotnet/Runtime/release/2.0.0/dotnet-runtime-latest-linux-arm.tar.gz

# Make a directory for .NET Core to live in
sudo mkdir /usr/local/lib/dotnet

# Unzip the binaries into the directory we just created
sudo tar -xvf dotnet-runtime-latest-linux-arm.tar.gz -C /usr/local/lib/dotnet

# Now add the path to the dotnet executable to the environment path
# This ensures the next time you log in, the dotnet exe is on your path
echo "PATH=\$PATH:/usr/local/lib/dotnet" >> dotnetcore.sh
sudo mv dotnetcore.sh /etc/profile.d

Then run the command below to  add the path to the dotnet executable to the current session

PATH=$PATH:/usr/local/lib/dotnet

Test the .NET Core 2 installation

You can now test the framework.

dotnet --info

You should see the following information.

 

C# Asynchronous Download File with Progress

// Sample call : DownLoadFileInBackground2 ("http://www.contoso.com/logs/January.txt");

public static void DownLoadFileInBackground2(string address)
{
    WebClient client = new WebClient ();
    Uri uri = new Uri(address);

    // Specify that the DownloadFileCallback method gets called
    // when the download completes.
    client.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCallback2);

    // Specify a progress notification handler.
    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
    client.DownloadFileAsync (uri, "serverdata.txt");

}
private static void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
{

    // Displays the operation identifier, and the transfer progress.
    Console.WriteLine("{0}    uploaded {1} of {2} bytes. {3} % complete...", 
        (string)e.UserState, 
        e.BytesSent, 
        e.TotalBytesToSend,
        e.ProgressPercentage);

}
 

private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{    
     // Displays the operation identifier, and the transfer progress.    
     Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",         (string)e.UserState,         
        e.BytesReceived,         e.TotalBytesToReceive,                    e.ProgressPercentage);

}

Source: https://msdn.microsoft.com/en-us/library/ms144196(v=vs.110).aspx

Add an Application Shortcut to Windows File Explorer’s Context Menu

Context menu for right click on folders in left panel of Windows File Explorer or on background of a directory in right panel

  1. HKEY_CLASSES_ROOT\Directory\Background\shell if you are administrator
  2. HKEY_CURRENT_USER\Software\Classes\directory\Background\shell if you are a normal user

Context menu for right click on folders in right panel of Windows File Explorer

  1. HKEY_CLASSES_ROOT\Directory\shell if you are administrator
  2. HKEY_CURRENT_USER\Software\Classes\directory\shell if you are a normal user

Context menu for any file

  1. HKEY_CLASSES_ROOT\*\shell if you are administrator
  2. HKEY_CURRENT_USER\Software\Classes\*\shell if you are a normal user

In all cases:

  1. add a new key under “shell”, naming it as you want to name the context menu item
  2. add a new key inside this key, named command (mandatory name)
  3. edit the “default” property in “command” to myprogrampath\path\path\executable.exe %1 to pass the file path and name of the selected file to your custom program.

C# Example

Add a String Value to the key called “AppliesTo” and set its value to “under:{path}”

In my example, I want it to only look in the T Drive, so my String value is “AppliesTo”:”under:T:”.

In C#, this is easily accomplished with the following:

RegistryKey _key = Registry.ClassesRoot.OpenSubKey("Folder\\Shell", true);
RegistryKey newkey = _key.CreateSubKey("My Menu Item");
newkey.SetValue("AppliesTo", "under:T:");

RegistryKey subNewkey = newkey.CreateSubKey("Command");
subNewkey.SetValue("", "C:\\yourApplication.exe");
subNewkey.Close();

newkey.Close();
_key.Close();

Full Detailed Example

With a quick registry tweak, you can add any application to any Windows Explorer context menu. You can even add application shortcuts to your desktop’s context menu and launch your favorite applications just by right-clicking on your desktop.

Getting Started

First, launch regedit.exe from the Start menu.

Expand the HKEY_CLASSES_ROOT key.

Specific File Types

As an example, let’s add an option to the context menu for .gif files.

First, scroll down to the .gif key under HKEY_CLASSES_ROOT.

Select it and look at its “(Default)” value. In this case, the default value is “giffile”.

Head to down to the giffile\shell key, also under HKEY_CLASSES_ROOT.

First, right-click the shell key and create a new key. Name the key what you want the option to appear as in the menu. Next, right-click the key you just created and create a new subkey under it. Name the new key “command.”

Double-click the “(Default)” value in the command key and enter the path to the .exe file in the following format:

C:\\Program Files\\Something\\something.exe %1

Be sure to use the double backslashes and end the path with %1. The %1 passes the selected file name to the program.

The option will appear immediately.

Only When Pressing Shift

To have a shortcut appear only when you press Shift while right-clicking, create a string value named “Extended” in the action’s main key.

All File Types

The HKEY_CLASSES_ROOT\*\shell key holds options that appear when you right-click any type of file.

First, navigate to the *\shell key.

Next, create a key with the same structure.

You’ll see the option when you right-click any type of file.

Desktop Menu

Use the HKEY_CLASSES_ROOT\DesktopBackground\shell key to have a shortcut appear when you right-click the desktop.

Omit the %1 part of the command because you only want Windows to launch the app, not try to pass anything to it.

Folder Menus

Use the HKEY_CLASSES_ROOT\Directory\shell key to have the option appear when you right-click a directory.

Use the HKEY_CLASSES_ROOT\Directory\Background\shell key to have an option appear when you right-click the background of a directory in a Windows Explorer window.

Source: http://www.howtogeek.com/107965/how-to-add-any-application-shortcut-to-windows-explorers-context-menu/

 

Create html and chm documentation from C# or C++ Visual Studio source code

Products to be used

Doxygen

Doxygen (doxywizard.exe) is used to generate HTML documentation from source files. Furthermore, it generates the elements needed to create the .chm (compressed HTML) file too. Doxygen can be used under the terms of the GNU General Public License. Doxygen can be downloaded from www.doxygen.org.

Microsoft HTML Help Workshop ®

HTML Help Workshop (hhw.exe) is used to generate compressed HTML files (.chm). This tool is free and can be downloaded from here.

Procedure for generating the technical documentation

Generating HTML files

  • Execute Doxygen GUI frontend (doxywizard.exe).
  • Configure the parameters by using either “Wizard” or “Expert” mode.
  • In order to prepare the .chm file generating, in “Output” tab, it has to check “HTML” and “prepare for compressed HTML” in wizard mode. Whether the expert mode has been chosen, in “HTML” tab, it has to check “GENERATE_HTMLHELP” and to enter the .chm filename (with the extension) in “CHM_FILE” field.
  • Save the configuration file.
  • Run the generating process by clicking on the “Start” button.
  • Check the result by executing “index.html” in the “html” sub folder.
In addition of the html documentation, three more files are supposed to be generated in the “html” sub folder: “index.hhp”, “index.hhc” and “index.hhk”.

Generating compressed HTML file (.chm)

  • Execute HTML Help Workshop (hhw.exe).
  • Open the project file: index.hhp.
  • Eventually change the compiled file location to drop it in the “Doc” folder.
  • Compile the HTML files.
  • Outside HTLM Help Workshop, open the created file in order to  check it.

C# and C++ comments restrictions in Visual Studio ®

Doxygen recognize the C# and C++ comments tags like ///<summary></summary>,///<param></param>, ///<returns></returns> and the other ones. But, for example, under Windows version, it does not recognize the line feed in comments.
So, whether you want to go beyond these basic features and if you want  to format your comments, the best way is to use the Doxygen tags inside the standard comments tags (refer to Doxygen documentation for details).
The Visual Studio compiler does not send any warning about these, but, unfortunetly, these tags appear in the tooltips in the editor.
Below is a sample with “\n” tag for the line feed and, “\code” and “\endcode” to show the encapsulated text like code pattern in the output help file.
/// <summary>
/// Load a config XML file.
/// \n\n XML file format:
/// \code
/// <Parent>
///     <Child Name='ID' Type='Type1' />        
///     ...
/// </Parent>
/// \endcode
/// </summary>

 Visual Studio® and Html Help Workshop® are registered trademarks of Microsoft.