C# – MVC Identity login with WebAPI

Having an existing C# MVC application with Idenity authorization there was a necessity to implement the same Identity authentication with WebAPI within the same web application and allow a desktop app to authenticate via WebAPI.

The way to get this working is to implement the MVC login authentication generated into the WebAPI controller. The last POST method is the one used to authenticate from the desktop app that uses HTTP Post. The way shown here, the username and password are accepted (and therefore have been submitted) in plain text JSON format. You need to implement your encryption method to get this secure.

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace MyAppNameSpace
    public class WebApiController : ApiController
        private ApplicationSignInManager _signInManager;
        private ApplicationUserManager _userManager;

        public WebApiController() { }

        public WebApiController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
            UserManager = userManager;
            SignInManager = signInManager;

        public ApplicationSignInManager SignInManager
                return _signInManager ?? HttpContext.Current.GetOwinContext().Get();
            private set
                _signInManager = value;

        public ApplicationUserManager UserManager
                return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager();
            private set
                _userManager = value;

        // GET: api/WebApi
        public IEnumerable Get()
            return new string[] { "value1", "value2" };

        public HttpResponseMessage Post([FromBody]JToken jsonbody)
            AccountController accountController = new AccountController();

            dynamic data = JObject.Parse(jsonbody.ToString());

            string userId = data.userid;
            string userPassword = data.password;

            var result = SignInManager.PasswordSignIn(userId, userPassword, false, false);

            if (result.Equals(SignInStatus.Success))
                return new HttpResponseMessage(HttpStatusCode.Accepted);
                return new HttpResponseMessage(HttpStatusCode.Forbidden);

Having the controller ready, the next step is to call the method via our desktop app to perform the login:

private void LoginPostRequest(string username, string password)
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("";
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                httpWebRequest.Accept = "application/json; charset=utf-8";

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                    string loginjson = new JavaScriptSerializer().Serialize(new
                        userid = username,
                        password = password


                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                        var result = streamReader.ReadToEnd();
            catch (Exception ex)
                throw new Exception(ex.Message);

VTK re-compile (for Python) with PowerCrust algorithm support

The following was performed with VTK 5.8 and Python 2.7.8 on Debian Wheezy x86_64.

  1. Get the VTK source-code: http://vtk.org/VTK/resources/software.html
  2. Get the Tim Hutton’s PowerCrust C++ source-code: https://github.com/timhutton/vtkpowercrust
  3. Unzip both archives
  4. Copy the C++ files (.cxx & .h) into VTK/Hybrid
  5. Edit VTK/Hybrib/CMakeLists.txt and add the PowerCrust .cxx file
  6. cd VTK; mkdir build; cd build; ccmake ..
  7. Set desired installation directory
  9. While on ccmake first configured [c] and then generate [g]
  10. make && make install
  11. cd Wrapping/Python; python setup.py install
  12. Assuming all go well export the VTK libraries: export LD_LIBRARY_PATH=/<installation_path>/lib/vtk-5.8

VTK export JPG from DICOM

Exporting .jpg image copy from .dcm input using VTK in Python.

# Iterate through .dcm files and export to .jpg
for image in os.listdir(PathDicom):
if (image.endswith(".dcm")):

# Need to cast before writing to .jpg
castFilter = vtk.vtkImageCast()

# .jpg file write
writer = vtk.vtkJPEGWriter()
jpg_filename = image.replace(“.dcm”, “.jpg”)

GoogleMaps API multiple markers

I have a database with some records that among other details they also declare a local (Greek) street addresses. The requirement is to retrieve all these records from the database and display them with markers on a Google Map. Before everything, if you want to get an idea on how the API works see the following links:

GoogleMaps API – Getting started
GoogleMaps API – Simple markers

The flow for my task has as follows:

– Connect to database
– Retrieve all the locations from DB
– Convert Greek characters to Latin for avoiding issues with the Web Service request [ code on code.loon.gr ]
– Use GoogleMaps API to retrieve GPS coordinates based on the given location
– Parse JSON response
– Use JavaScript to add the markers layers

Full code on GitHub.


Remote cPanel backup via FTP

Here is the scenario:

– Domain that needs to be backed up (public_html, mail, database).
– Only access available via cPanel and FTP.
– Need automated daily full backup.


– Take full backup on server and compress its contents (cronjob on remote server)
– Download via FTP the compressed file to the local machine (cronjob on local machine).
– Delete compressed file.

There might be tools that do this, although I didn’t come across any while looking on the web. I implemented a simple solution based on bash scripts that gets the task done.

backup.sh: Goes on the remote server to run as a cronjob.
ftp.sh: Runs locally (on the machine that will store the backup) as a cronjob.
.netrc: Defines the FTP account details (stored in /home/$user/.netrc)

Java HTTP library

Being in need to issue POST requests from within a Java application, and wanting re-usable code, I created a very simple Java library for issuing POST and GET requests to a remote server.

POST source codeGET source code

Usage (POST example):

POST post = new POST();
post.postRequest("http://www.myservice.com/service", "param1=foo&param2=bar", "Mozilla/5.0");

In other words, the arguments are:


The output can be manipulated as desired, depending on what you response you except you should use a corresponding element/object.

Java libary in Android project

If you have developed your Java library that you would like to use within your Android project, or you want to use an existing Java library, make sure that the library itself is compiled with Java 1.6 rather than 1.7. Have been always forgetting that and have wondering for a couple of days why am I getting “NoClassDefFoundError” error.

Assigning HTML “rel” attribute to all page images

Very briefly, in a CakePHP app, I want to apply the lightbox script on all the images that link from a thumbnail to a larger image. If there are more than two, I want them to appear as a lightbox group. I don’t want the user to mess with TinyMCE and HTML, therefore I automatically apply the rel attributed for every single image in a page that is a hyperlink. The following PHP bit is added in app/Plugin/Nodes/View/Nodes/view.ctp. With some small changes it can be used for any PHP compatible web site.

$body = $this->Nodes->body();
if (strpos($body, "img")) {
   $pattern ="/<a(.*?)href=('|\")(.*?).(jpeg|jpg|png)('|\")(.*?)>/i";
   $newLink = '<a$1href=$2$3.$4$5 rel="lightbox[group]".$6>';
   echo preg_replace($pattern, $newLink, $body);
} else {
   echo $body;

Java encrypt class

A simple implementation of an encryption class to be used in Java applications for either encrypting strings and calculating files’ fingerprint.

import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encrypt {

   private FileInputStream fis;

   public Encrypt() { }

   public String encryptString(String input, String salt, String algorithm) {
      String output = null;
      String fullInput = null;

      if (!salt.equals(null)) {
         fullInput = salt + input;
      } else {
         fullInput = input;

      try {
         MessageDigest digest = MessageDigest.getInstance(algorithm);
         digest.update(fullInput.getBytes(), 0, fullInput.length());
         output = new BigInteger(1, digest.digest()).toString(16);
      } catch (NoSuchAlgorithmException ex) {
      return output;

   // Based on: http://www.mkyong.com/java/how-to-generate-a-file-checksum-value-in-java/
   public String calculateFingerprint(String fileName, String algorithm) {
      StringBuffer sb = new StringBuffer();
      try {
         MessageDigest md = MessageDigest.getInstance(algorithm);
         fis = new FileInputStream(fileName);
         byte[] dataBytes = new byte[1024];
         int nread = 0;
         while ((nread = fis.read(dataBytes)) != -1) { md.update(dataBytes, 0, nread); }
         byte[] mdbytes = md.digest();
         for (int i = 0; i < mdbytes.length; i++) {
            sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
      } catch (Exception ex) {
      return sb.toString();

Link to GiHub repository. The class is intended to be used as a library within Java applications.

Example for encrypting a string:

Encrypt en = new Encrypt();
String encryptedString = en.encryptString(textField.getText().toString(), \
"salt goes here if you want", "md5")));

Example for calculating the fingerprint of a file:

Encrypt en = new Encrypt();
String fingerPrint = en.calculateFingerprint("/path/to/file", sha1);