101 for REST API with Swagger, ASP.NET and C#

Short summary about my lessons learned for a REST API with Swagger, ASP.NET and C#.

Configuration

Open the file SwaggerConfig.cs. For the first demo, we name our app and enable the UI:

GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion(“v1”, “API Demonstration”);
})
.EnableSwaggerUi();

SwaggerUI

The SwaggerUI can be found under:

http://localhost:%5BPORT_NUM%5D/swagger

Documentation

If you need documentation for you methods, parameters or controller, you have to enable the XML documentation file:

swagger_doku

Remember the path, you will have to add it to your Swagger configuration. This all the other configurations it should look like this:

GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion(“v1”, “API Demonstration”);
c.IncludeXmlComments(string.Format(@”{0}\App_Data\API-Test.XML”, System.AppDomain.CurrentDomain.BaseDirectory));
})
.EnableSwaggerUi();

To use the documentation, you can commentary to every method. Remember, you can use HTML formatting.

swagger_docu2

Path Parameters

Path parameters are fixed elements of the URL and are not optional. They can be set by the Route element. Every parameter is configured via {} brackets and have to match with the method parameters:

[HttpGet]
[Route(“test/route/{para1}/{para2}”)]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(String))]
[SwaggerResponse(HttpStatusCode.BadRequest, Description = “Bad Request”)]
[SwaggerResponse(HttpStatusCode.NotFound, Description = “Not found”)]

public string test(string para1, int para2)
{

The Request URL looks like this:

http://localhost:50283/test/route/Hello/7

Query Parameters

Query parameters are not part of the base URL. If tw want para2 to be a query parameter, just exclude it from the Route:

 

[HttpGet]
[Route(“test/route/{para1}”)]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(String))]
[SwaggerResponse(HttpStatusCode.BadRequest, Description = “Bad Request”)]
[SwaggerResponse(HttpStatusCode.NotFound, Description = “Not found”)]

public string test(string para1, int para2)
{

The Request URL looks like this:

http://localhost:50283/test/route/Hello?para2=7

(This can also be done with para1)

Optional Parameters

If you want optional parameter, just add a default value for the parameter.

[HttpGet]
[Route(“test/route/{para1}”)]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(String))]
[SwaggerResponse(HttpStatusCode.BadRequest, Description = “Bad Request”)]
[SwaggerResponse(HttpStatusCode.NotFound, Description = “Not found”)]

public string test(string para1, int para2=0)
{

Validating DateTime

You will get a 404 – Bad Request, if you use DateTime within a path parameter like this:

http://localhost:50283/test/route/2017-05-26T12:30:00

You have to options.

1. Use a query parameter like this: http://localhost:50283/test/route?time=2017-05-26T12:30:00

2. Change your web.config:

<configuration>

<system.web>

<httpRuntime requestPathInvalidCharacters=”” requestValidationMode=”2.0″ />
<pages validateRequest=”false” />
</system.web>
..
</configuration>

Tutorial – Using Oracle Managed Data Access in ASP.NET and C#

1. Install  Oracle.ManagedDataAccess via NuGet package managernuget.PNG

2. Define your data source

Open your Web.config and add to the configuration the following:

<oracle.manageddataaccess.client>
<version number=”*”>
<dataSources>
<dataSource alias=”EXAMPLE” descriptor=”(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=YOUR_HOST_NAME)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=YOUR_SERVICE_NAME)))” />
</dataSources>
</version>
</oracle.manageddataaccess.client>

Here you can read, how to get your HOST_NAME and SERVICE_NAME.

3. Connect to your Oracle

using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;

….

public OracleConnection connectOracle()
{
OracleConnection con = null;
OracleCommand cmd = null;
OracleDataReader reader = null;
try
{
string constr = “user id=YYYYYYY;password=XXXXXXX;data source=EXAMPLE”;
con = new OracleConnection(constr);
con.Open();
cmd = new OracleCommand(“select * from SOMETABLE t”, con);
cmd.CommandType = System.Data.CommandType.Text;

reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString(0)) //Just example
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace.ToString());
}
finally
{
if (reader != null && !reader.IsClosed)
reader.Close();
if (con != null && con.State == System.Data.ConnectionState.Open)
con.Close();
con.Dispose();
}
}

Fin.

Missing api-ms-win-crt-runtime-l1-1-0.dll

Problem

error

  • The api-ms-win-crt-runtime-l1-1-0.dll is missing
  • Sub problem: you can not install Visual C++ Redistributable for Visual Studio because Windows Update, especially on Windows Vista, doesn’t work. (it runs hour for hour and exits with an error)

Solution

Normally, you only have to install the VC++ Redistributable for your computer:

Visual C++ Redistributable for Visual Studio 2017 (64-bit)

Visual C++ Redistributable for Visual Studio 2017 (32-bit)

Windows Update

If you can not install VC++ it is most likely because of the broken Windows Update process:

Here is what i did:

  1. Uninstall VC++, by starting the installer and select Uninstall.
  2. Restart computer
  3. Open cmd as administrator
  4. Type: net stop wuauserv
  5. Install VC++

This installs VC++ without problems. You can restart Windows Update with net start wuauserv 

Restart failed program every 5 min

Problem

  • Your program fails regularly
  • You need to check if it is running and if not, restart it

Solution

Create a script:

nano restart.sh

Put in the code and replace htop with your program name:

#!/bin/sh

ps cax | grep htop > /dev/null
if [ $? -eq 0 ]; then
echo “Process running.”
else
echo “Process is down.”
fi

Make the script executable:

chmod +x restart.sh

Create a cron job:

crontab -e

Create a new line (replace /home/user/):

*/5 * * * * /home/user/restart.sh

Fin.

 

System wide proxy settings for Xubuntu (16.10)

Problem

  • You have to set http etc. proxy settings for all application
  • XUbuntu GUI is not helpful 😉

Solution

Step 1: Edit environment

sudo nano /etc/environment

Append these lines (fill in your proxy):

http_proxy=http://yourproxy:8080/
https_proxy=http://yourproxy:8080/
HTTP_PROXY=http://yourproxy:8080/
HTTPS_PROXY=http://yourproxy:8080/

To load the new variables:

source /etc/environment

Step 2: Edit apt

Go to /etc/apt/apt.conf.d/ and create a file named 95proxies.

sudo nano /etc/apt/apt.conf.d/95proxies

Fill in these lines:

Acquire::http::proxy “http://yourproxy:8080/&#8221;;
Acquire::ftp::proxy “ftp://yourproxy:8080/”;
Acquire::https::proxy “http://yourproxy:8080/&#8221;;

Fin.

Import GPX into Splunk

Problem

  • You want to import a GPX File into Splunk
  • You want to define a special sourcetype

Solution

This is the example

<?xml version=”1.0″ encoding=”UTF-8″?>
<gpx version=”1.1″ xsi:schemaLocation=”http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd&gt;
<trk>
<trkseg>
<trkpt lon=”13.7235536575317383″ lat=”51.0877876281738281″>
<ele>154.0</ele>
<time>2016-04-29T15:39:38.000Z</time>
</trkpt>
<trkpt lon=”13.7235345840454102″ lat=”51.0876770019531250″>
<ele>155.0</ele>
<time>2016-04-29T15:39:47.000Z</time>
</trkpt>
<trkpt lon=”13.7242536544799805″ lat=”51.0879554748535156″>
<ele>152.0</ele>
<time>2016-04-29T15:40:11.000Z</time>
</trkpt>
<trkpt lon=”13.7242536544799805″ lat=”51.0879554748535156″>
<ele>152.0</ele>
<time>2016-04-29T15:40:13.000Z</time>
</trkpt>
<trkpt lon=”13.7242908477783203″ lat=”51.0884094238281250″>
<ele>149.0</ele>
<time>2016-04-29T15:40:29.000Z</time>
</trkpt>
</trkseg>
</trk>
</gpx>

Go to the Splunk preferences and add a new sourcetype with the following properties:

BREAK_ONLY_BEFORE = <trkpt

KV_MODE = xml

NO_BINARY_CHECK = true

SHOULD_LINEMERGE = true

pulldown_type = true

FIELDALIAS-rootfields = trkpt.ele as Hight trkpt{@lat} as Latitude trkpt{@lon} as Longitude

This will create events based on TrackPoint. In addition, latitude, longitude and hight will be extracted as extra fields.

gpx

If you want to include RoutePoints (see GPX Wikipedia), you only have to change the BREAK_ONLY_BEFORE  from <trkpt to <\w\w\wpt 

timechart

Fin.