Windows Archive - CraftCoders.app https://craftcoders.app/category/windows/ Jira and Confluence apps Wed, 14 Aug 2024 12:27:55 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 https://craftcoders.app/wp-content/uploads/2020/02/cropped-craftcoders-blue-logo-1-32x32.png Windows Archive - CraftCoders.app https://craftcoders.app/category/windows/ 32 32 5 Things I love about WSL https://craftcoders.app/5-things-i-love-about-wsl/ Mon, 17 Sep 2018 08:00:48 +0000 https://craftcoders.app/?p=683 Read More]]> I got a new PC and love it! But a new PC also means a whole new setup and a lot of work. One of the first things I’ve setup has been the Windows Subsystem for Linux. I know I am a developer and most of you would not expect me to work on a windows machine. Guys I must tell you windows is fucking awesome and with WSL it’s just getting more awesome! Here five things I really love about WSL

1. Interoperability

Starting with Windows build 14951 Microsoft added the possibility to (1) invoke Linux binaries from the Windows Console (2) invoke Windows binaries from the Linux Console and (3) sharing environment variables between Windows and Linux. Furthermore, with the Fall creates Update Microsoft include the windows path in the Linux $Path so it is easy to call windows binaries from Linux. So, to call Windows binaries from windows you just must type:

[binaries name].exe

For instance, you could open the windows file explorer at the current location of your windows console by simply calling:

 explorer.exe .
launching explorer from the Linux Console

2. Docker

Okay now I gonna cheat but its so cool it deserves to be its own point. Due to the Interoperability between WSL and Windows you do not need to expose some creepy port or build complicated relay between WSL and Windows. You can just run “docker.exe” to use docker for windows inside your Linux console. Ok I admit this is not very practical since you have always to type “.exe”. But Linux is awesome and lets you define aliases so such things. All you need to do is:

  1. Open ~/.bashrc
  2. Go to the end of the file
  3. Add following lines (at the end)
    alias docker=docker.exe
    alias docker-compose=docker-compose.exe
Docker

3. WSLGIT

As mentioned in (1) you can execute windows binaries from the Linux console. As a result, you can open VSCode from the Linux Console. Here´s the catch: VSCode would still use Git for Windows. This is not really a problem and works. I really love to use git inside my Linux console, but I don’t want to manage two git installations on the same machine. One could argue that you could do the same trick as we did with docker and that’s true but this time we do is the other way round. There is a GitHub Project from andy-5 that is called WSLGIT. Basically, this project aims to provide a small executable that forwards arguments to git running inside Bash on Windows. All that needs to be done is:

  1. Download the executable
  2. Save the .exe somewhere
  3. Change the settings of your IDEs to use wslgit.exe as git executable

4. X-Server for Windows

So, what can’t be done with WSL? Right you can not run graphical applications. Can`t you? That’s just partial true: You can use an implementation of X-Server for windows and forward it inside your bash. I use the Xming X Server. Simply download it and install it. After installation open XLaunch, select “Multiple Windows” and “Display Number 0” at the first screen. Select “Start no client” at the second screen. Select “Clipboard” and go forward. Now you can save this configuration and add it to your autostart folder. That why you never have to configure it again (even when we just used the default configuration ?). Inside your Linux console you just must run

export DISPLAY=:0

and you are ready to go. Now you can start graphical applications!

Fixing HDPI

You may encounter the same problem as I did. My new PC got a UHD resolution and graphical applications running with Xming X Server are blurry. This is the fault of the windows compatibility mode that is scaling the application. To fix it you need:

1. Navigate to the installation folder of Xming 
2. Open the Properties of Xming.exe
3. Click on compatibility
4. Click on HDPI-Settings
5. Override HDPI-Setting with application defaults

DPI-Settings



So, every Linux application is really small ?. But don’t mind we can fix that inside Linux! If we use GTK application, we can just increase the GTK scaling factor by typing:

export GDK_SCALE=3

The power of X-Server

5. Seamlessly using Linux

This sums it up, but I will show you what I mean by example. We gonna run Tilix, a tiling terminal emulator for Linux using GTK+ 3, as it would be a ordinary windows application. Note to do that, you need to follow the instructions under point (4). I’m assuming you already did that. To install Tilix we just need to type

sudo add-apt-repository ppa:webupd8team/terminix
sudo apt-get update
sudo apt-get install tilix

You might encounter some problems regarding the dbus service. For instance you could get a error message like this:

failed to commit changes to dconf: Failed to execute child process “dbus-launch” (No such file or directory)

 

Dont you worry child! It is easy to fix. We just need to install the dbus-service and run execute it:

sudo apt-get install dbus-x11
sudo service dbus start

That’s all! The make it more convenient to use we are going to write a small script to launch it. Just open VSCode and copy and paste following:

args = "-c" & " -l " & """GDK_SCALE=3 DISPLAY=:0 tilix"""

WScript.CreateObject("Shell.Application").ShellExecute "bash", args, "", "open", 0

NOTE: if you don’t have UDH resolution you can remove following GDK_SCALE=3. Save the script under …Programms/Tilix and name it tilix.vbs. Now we need a second script a simple bat file that we use to invoke our first script:

WScript tilix.vbs

Almost done! We can now send the bat script to the deskop and get a nice clickable icon that can be used to launch Tilix. If you put it in the Startmenu folder you can even use it from the Startmenu in windows 10!

running tilix
]]>
Do it yourself filesystem with Dokan https://craftcoders.app/do-it-yourself-filesystem-with-dokan/ Mon, 13 Aug 2018 08:00:00 +0000 https://craftcoders.app/?p=498 Read More]]> What’s up guys?! A week has passed and its time for a new Blogpost. This time I am gonna give you a small introduction to Dokan. You don’t have a clue? Never heard of Dokan before? No problem… I haven’t either. But in the life as a student there comes the moment where one must write his Bachelor thesis. No matter how much you procrastinate. As a part of my thesis, I had to write a filesystem and this is exactly where Dokan came into play to save my ass.

WHAT IN THE HELL IS DOKAN?!

So let’s start from the beginning. As I mentioned before, I had to implement my own Filesystem. Yeah, basically you could write your own filesystem driver. But that would be like writing a compiler to print a simple “Hello World”. But there is a really cool concept which is heavily used in the Linux world. Its called FUSE (Filesystem in Userspace). With FUSE everyone is able to create their own Filesystem without writing a Kernel component. FUSE empowers you to write a Filesystem in the same manner as a user-mode application. So what is Dokan?! Dokan is simply FUSE for Windows. It is as simple as that. You could even use Dokan to run a filesystem which has been written with FUSE under windows.

Okay cool… How does this magic work?!

So you are right. Without a kernel component, there is no way to implement a filesystem. But you don’t have to write it, because Dokan did. So Dokan ships with two components: (1) dokan1.sys alias “Dokan File System Driver” (2) dokan1.dll which is used in a “Filesystem Application”. So take a look at the picture below

First, a random Application is running. It could be Word, Visual Studio, IntelliJ or your web browser rendering a website that is trying to write a virus into a file ?. Let’s assume it is the web browser. If the web browser tries to write some content x to a file y its gonna fire a I/O-request.
This I/O-request is processed by the Windows I/O Subsystem. Note that by passing the I/O-request to the Windows I/O Subsystem we leave the user mode and enter the kernel mode of Windows (this is 1 in the picture above).

Secondly, the Windows I/O Subsystem will delegate the I/O-request to a Driver responsible for the filesystem. In our case that would be the Dokan File System Driver. Which is dokan1.sys. Please note that we did not write any code for that driver, it just needs to be installed (this is 2 in the picture above).

Third, our Filesystem Application which has registered itself in the Dokan File System Driver gets notified about the I/O-Request. By implementing the interface which comes in the dokan1.dll, our Filesystem Application is now responsible for computing the I/O-Request. Whatever has to be done needs to be done by our Filesystem Application. And as you might already guess: Yes this is the part we need to write! The Filesystem Application than invokes a callback function and the Dokan File System Driver is back in line (this is 3-4 in the picture).

Last but not least, the Dokan File System Driver receives the I/O-Response created by our Filesystem Application and invokes the callback routine of the Windows I/O Subsystem. The Windows I/O Subsystem than forwards the result to the application which created the I/O-Request. In our case the Web browser with the porno site (this is 5-6 in the picture).

Just do it! Writing a simple Filesystem

Scope

Okay, we are actually not going to implement a complete Filesystem ?. That would be too much for a blog post. We are doing something simple. Let’s create a Filesystem that contains a fake file which can be read with a editor.

Warmup: Preparations

As I already mentioned before, we need to install the Dokan File System Driver. It is used as a proxy for our Filesystem Application. You can get the latest Version here.
As soon as we have the Dokan File System Driver installed, we can create a blank C# Console Application. Please note that you could also use Dokan with other languages. As always, you can find my solution on GitHub. After we’ve created the Console Application, which will be our Filesystem Application, we need to add the Dokan library (dokan1.dll). Luckily there is a NuGet package.
Everything settled? Let the game begin!

Mount the FS

First of all, we need to implement the IDokanOperations from the dokan1.dll. Since this is for learning purposes I didn’t create a second class. So everything is in one class. In the Main()-Method I create a new instance of the class and mount the Filesystem.

static void Main(string[] args)
{
    var m = new StupidFS();
    // mounting point, dokan options, num of threads
    m.Mount("s:\\", DokanOptions.DebugMode, 5);
}

1..2..3.. and it crashed! What happened? As you can see from the Console output, several I/O-request failed. First, the GetVolumeInformation-Operation failed and then the Mounted-Operation. They failed because we did not implement them yet. But it’s simple: in the GetVolumeInformation-Request we just need to provide some information for the OS. Basically, this is just some Meta information for our filesystem. Like its name, how long a path can get and which feature it supports. Let’s implement it:

[...]

public NtStatus GetVolumeInformation(...)
{
       volumeLabel = "CraftCode Crew";
       features = FileSystemFeatures.None;
       fileSystemName = "CCCFS";
       maximumComponentLength = 256;

       return DokanResult.Success;
}

[...] 

public NtStatus Mounted(DokanFileInfo info)
{
       return DokanResult.Success;
}

But it won’t work yet. We also need to “implement” the CreateFile-Methode:

public NtStatus CreateFile(...)
{
      return DokanResult.Success;
}

Did you notice how every method returns a NtStatus? This status indicates wherever a request has failed (and why) or succeeded. You might wonder why we need to return a Success in the CreateFile-Methode for mounting the filesystem. As soon as we mount the filesystem, it tries to create some fileproxis. If we throw an exception, our filesystem ends up in a bad state.

Faking a file

Whenever the filesystem has to list files there a two possible request: FindFilesWithPattern and FindFiles. Luckily, we just need to implement one and suppress the other one. We are going to implement the FindFiles-Methode. Therefore we will return a DokanResult.NotImplemented in FindFilesWithPattern, so whenever the filesystem gets this request it will be rerouted to FindFiles.
One of the parameters in FindFiles is a list of FileInformation objects. We are just going to fake one item and add it to a list which will be set to the parameter files.

public NtStatus FindFilesWithPattern(...)
{
   files = null;

   return DokanResult.NotImplemented;
}

public NtStatus FindFiles(...)
{
   var  fileInfo = new FileInformation
   {
         FileName = "carftCodeCrew.txt",
         CreationTime = DateTime.Now,
         LastAccessTime = DateTime.Now,
         LastWriteTime = DateTime.Now,
         Length =  FileContent.Length * 8,
   };

   files = new List<FileInformation> {fileInfo};

   return DokanResult.Success;
}

And we did it! Our filesystem now shows one file!
Did you notice FileContent? It’s just a global string containing the content of our textfile.

Reading with the good old Editor

Let’s read data from our filesystem! We want to read the string FileContent with the good old Editor. So, first of all, we need to make changes to the CreateFile-Methode. Whenever we need to open a file or dir, the CreateFile-Methode gets invoked. We need to provide the DokanFileInfo object with a context. In case of a read operation, the context is a stream where the data is located. Since we want to read a string, we are going to use a MemoryStream.

public NtStatus CreateFile(...)
{
     if (fileName.Equals(@"\carftCodeCrew.txt"))
     {
       info.Context = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(FileContent));
     }

       return DokanResult.Success;
}

We are close but not quite there. When an application like Editor tries to open a file it also wants to read the meta information of the file. For example, to set the window title. Therefore we need to implement the GetFileInformation-Methode. Since our filesystem just has one file it is really trivial:

public NtStatus GetFileInformation(...)
{
     fileInfo = new FileInformation
     {
            FileName = "carftCodeCrew.txt",
            Attributes = 0,
            CreationTime = DateTime.Now,
            LastAccessTime = DateTime.Now,
            LastWriteTime = DateTime.Now,
            Length =  FileContent.Length * 8,
     };

     return DokanResult.Success;
}

Now we are really close ? We just need to implement the ReadFile-Methode(). In this method, we get the Stream from the DokanFileInfo.Context and then read the bytes that have been requested. It is really as simple as this.

public NtStatus ReadFile(...)
{
      bytesRead = 0;

      if (info.Context is MemoryStream stream)
      {
          stream.Position = offset;
          bytesRead = stream.Read(buffer, 0, buffer.Length);
      }

      return DokanResult.Success;
}

The lovely CraftCodeCrewFS

]]>