Saturday, 9 December 2017

Compressing files in a MVC environment

This article will present a way to compress files in a MVC environment. For compression, we will use the DotNetZip Nuget package, which is an open and free compression library hosted on Codeplex and supported also by Xceed. The DotNetZip produces of course Zip files. DotNetZip website We install this compression library by initiating the following Nuget command: Install-Package DotNetZip We then define a simple view in MVC that has got a file upload input and a submit button:

@model ZipAndMvc.Models.HomeViewModel
    ViewBag.Title = "Home Page";

<div class="jumbotron">
    <h2>Test out zipping a file</h2>   

<div class="row">

    @using (Html.BeginForm("ZipIt", "Home", FormMethod.Post, new {  enctype = "multipart/form-data" }))
        <div class="col-md-3">@Html.Label("Zip password") @Html.TextBoxFor(m => m.ZipPassword) </div>
        <div class="col-md-3"><input type="file" name="FileUpload" /> </div>
        <div>  <input type="submit" id="Submit" value="Upload and zip file" /> </div>

This view allows the user to type in a password for the file to compress, where the user also selects the file to compress. The user then hits the submit button. The HomeViewModel is very simple with a simple property for setting the zip password. Then we define the following code in the MVC controller:

        public FileStreamResult ZipIt(HomeViewModel viewmodel)
            if (Request.Files.Count > 0)
                using (var zip = new ZipFile())
                    zip.Encryption = EncryptionAlgorithm.PkzipWeak;
                    zip.Password = viewmodel.ZipPassword;
                    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default; 
                    var memoryStream = new MemoryStream();
                    zip.AddFile(Request.Files[0].FileName, "");
                    memoryStream.Position = 0;
                    return new FileStreamResult(memoryStream, contentType: "application/zip")
                        FileDownloadName = Path.ChangeExtension(Request.Files[0].FileName, "zip")
            return null;

The client posts the file to compress. The controller then inspects the Request.Files collection and selects the first file if there is present any files there. Here we return a FileStreamResult where the compressed data inside the memorystream is returned to the client. We use DotNetZip to do the compression. The benefit of DotNetZip compared to .Net built-in support for compression is more functionality. The code above should be sufficient for basic compression scenario in MVC. Feel free to experiment with DotNetZip. As you can see, you can specify compression level. You can also choose to add directories and much more. The reason for the second argument in AddFile method is to ensure that the file to be added to the zip package is put in the root folder of the zipped file. Also, set the values of Encryption and Password before adding files or directories (Folders) in the ZipFile. You can actually use different passwords also in the Zip file.

Friday, 8 December 2017

Finding old Git Branches with WSL and Bash

Finding old branches in Git

I had to find out which branches in a Git repository was old and output it to a file. An old branch is defined to have no commits the last four months. Here is the bash script I ended up with.


declare -i branchiteration=0
branchcount=$(git branch -a | wc -l)

if [ ! -e $branchfile ] ; then
 touch $branchfile

#empty the oldbranch file
: > $branchfile

for k in $(git branch -a | sed /\*/d); do

 if [ -z "$(git log -1 --since='4 months ago' -s $k)" ]; then
  echo $k | cut -d/ -f3 >> $branchfile
 percentage= bc <<< "scale=2;($branchiteration/$branchcount)*100"

 read -n 1 -t 0.1 input                  # so read doesn't hang
   if [[ $input = "q" ]] || [[ $input = "Q" ]]
      echo # to get a newline after 
echo -e "XXX\n$($percentage)\nAnalyzing $branchiteration of $branchcount $(bc <<< "scale=2;($branchiteration/$branchcount)*100") % done. \n(Exit: Q/q)... \nXXX"

done | whiptail --title "Resolving OpPlan 4 branch ages" --gauge "Analyzing.. (Press Q or q to exit)" 10 60 0


cat $branchfile

Saturday, 21 October 2017

X11 Subsystem running WSL Windows 10 subsystem for Linux

This article will look at running graphical Linux applications in Windows 10. As many of you know, Windows 10 can offer a subsystem for Linux running inside Windows 10. We need to download and install a X11 server to be able to run graphical applications that need more than the console, that is a graphical user interface. First off, download XMing for Windows Server from here:

XMing X Server for Windows Server
After installation of Xming, start Xming from your start button.
Now we need to install the Linux Subsystem itself, if you have not done this yet.
Inside Powershell, enter the following command as an administrator:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux 

If you are not a Windows Insider yet, you must join this program. See this page for a description how to obtain WSL or Windows Subsystem for Linux and install it.
Installation guide of WSL - Windows Subsystem for Linux After you have downloaded WSL and installed it using Powershell, select Launch and in the console Window after WSL is further installed and setup, enter a user in Linux you will use as administrator (in Linux terms, this is the root user). You can add another user using the adduser command as root in the Bash console. You can access WSL Linux inside Windows 10 by selecting the menu item Bash on Ubuntu on Windows.

Getting started using WSL

You probably want to update your WSL to the latest version. WSL is a specialized Ubuntu Linux distribiton. Enter the following command to upgrade Linux Kernel and applications, note that it will take time to download package and upgrade to latest versions:

apt-get update && apt-get upgrade The version of Linux distro can be found using this command:

lsb_release -irc 

As we see, I am running Ubuntu 16 Xenial. Next off, we are going to support X-Server. Download first the X11 apps.
root@tore# apt-cache search x11-apps x11-apps - X applications
Install X11-Apps. This will also download all required additional pacages. apt-get install X11-Apps
You need to do this as root or switching to a super user and use the sudo command. Next off, edit your ~/.bashrc file. This is similar to the $Profile file that Powershell uses. You are setting up your environment here to make sure you can use X-Server based Graphical User Interfaces. Such as Gimp, Firefox, Stellarium, Quake and so on - requiring a GUI. But we will start off with running a X11-app, such as Xeyes. Make sure your ~/.bashrc file got the following content. First download Nano if you do not want to use Vim or Vi. (apt-get install nano)
nano ~/.bashrc Next off, add the following line at least: export DISPLAY=:0 We can also add more nice colors and some additional information and offer to switch to a non-root user initally.
export DISPLAY=:0
export LS_COLORS
PS1='\e[37;1m\u@\e[35m\W\e[0m\$ '
echo "Welcome to Bash on Ubuntu on Windows. To switch to your user Tore :"
echo "su tore && cd /home/tore"
echo "Do this now? [y/n]"

read -rsn1 input
if [ "$input" = "y" ]; then
    cd /home/tore
    su tore
    ls -al

echo "To adjust profile file edit the file ~\.bashrc with Nano"

Last, we can test out everything, running Xeyes. Note that you can test out more advanced Linux applications such as Gimp by running: apt-get install gimp This will install Gimp, the Gnu Image Manipulation Program. Then just enter gimp from the console. You can also run such programs in the background by adding the ampersand (&): gimp &

Sometimes, we need to force an exit of such a Linux app with a GUI running from the console entering Ctrl+C to force exit the process.