Take Screenshot in C#

First Set Process DPI Aware:

Get Screen Size on C#
https://pupli.net/2020/03/get-screen-size-on-c/

Install-Package System.Drawing.Common -Version 7.0.0

Take screenshot and save to file

using System;
using System.Drawing;
using System.Windows.Forms;

namespace ScreenshotExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the bounds of the screen
            Rectangle bounds = Screen.PrimaryScreen.Bounds;

            // Create a bitmap object to store the screenshot
            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                // Create a graphics object from the bitmap
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    // Capture the screen
                    g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
                }

                // Save the screenshot as a PNG file
                bitmap.Save("screenshot.png");
            }

            Console.WriteLine("Screenshot saved as screenshot.png");
        }
    }
}

Take screenshot and save to memory

using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace ScreenshotToMemory
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the bounds of the screen
            Rectangle bounds = Screen.PrimaryScreen.Bounds;

            // Create a bitmap object to store the screenshot
            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                // Create a graphics object from the bitmap
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    // Capture the screen
                    g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
                }

                // Store the screenshot in memory using MemoryStream
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);

                    // Convert the MemoryStream to byte array
                    byte[] screenshotBytes = memoryStream.ToArray();

                    // Now the screenshot is stored in screenshotBytes, you can use it as needed
                    // For demonstration, let's output the length of the byte array
                    Console.WriteLine($"Screenshot captured. Byte array length: {screenshotBytes.Length}");
                }
            }
        }
    }
}

 

Get Screen Size on C#

The process is running under DPI virtualization. So we should apply the DPI aware manifest option to stop DPI virtualization

[DllImport("user32.dll", SetLastError=true)]
static extern bool SetProcessDPIAware();

Then

public enum SystemMetric
{
    VirtualScreenWidth = 78, // CXVIRTUALSCREEN 0x0000004E 
    VirtualScreenHeight = 79, // CYVIRTUALSCREEN 0x0000004F 
}

[DllImport("user32.dll")]
public static extern int GetSystemMetrics(SystemMetric metric);

public static Size GetVirtualDisplaySize()
{
    var width = GetSystemMetrics(SystemMetric.VirtualScreenWidth);
    var height = GetSystemMetrics(SystemMetric.VirtualScreenHeight);

    return new Size(width, height);
}

References
https://stackoverflow.com/questions/28339257/getsystemmetrics-and-tscreen-returns-wrong-value
https://www.pinvoke.net/default.aspx/user32/SetProcessDPIAware.html
https://stackoverflow.com/questions/1317235/c-get-complete-desktop-size
https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setprocessdpiaware

Set Up WireGuard VPN on Ubuntu 18.04

Server Installation

wget https://raw.githubusercontent.com/complexorganizations/wireguard-install/master/wireguard-server.sh -P /etc/wireguard/
bash /etc/wireguard/wireguard-server.sh

Client Installation

wget https://raw.githubusercontent.com/complexorganizations/wireguard-install/master/wireguard-client.sh -P /etc/wireguard/
bash /etc/wireguard/wireguard-client.sh

Or

apt-get update
apt-get install software-properties-common -y
add-apt-repository ppa:wireguard/wireguard -y
apt-get update
apt-get install linux-headers-"$(uname -r)" -y
apt-get install wireguard qrencode haveged resolvconf -y

Run Client

# Install the config file to the WireGuard configuration directory on your
# Linux client:
sudo install -o root -g root -m 600 <username>.conf /etc/wireguard/wg0.conf

# Start the WireGuard VPN:
sudo systemctl start wg-quick@wg0

# Check that it started properly:
sudo systemctl status wg-quick@wg0

# Verify the connection to the AlgoVPN:
sudo wg

# See that your client is using the IP address of your AlgoVPN:
curl ipv4.icanhazip.com

# Optionally configure the connection to come up at boot time:
sudo systemctl enable wg-quick@wg0

References
https://github.com/complexorganizations/wireguard-install
https://trailofbits.github.io/algo/client-linux-wireguard.html

Pass a value to the Resolver on Angular

{
  path: 'project/:id',
  component: ProjectComponent,
  resolve: { data: DataResolver },
  data: { path: 'project/:id' }
}

class DataResolve implements Resolve<string> {
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return route.data['path'];
  }
}
return new Observable<Item>(subscriber => {
  // tslint:disable-next-line
  const itemId = route.params.id;
  this.db.findItemByItemId2(itemId).subscribe(value => {
    subscriber.next(value);
    subscriber.complete();
  });
});

References
https://stackoverflow.com/questions/40297165/angular-2-pass-a-value-to-the-route-data-resolve/49171861

Reloading current route in Angular

@ngModule({
 imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
 exports: [RouterModule],
 })
export const routes: Routes = [
 {
   path: ‘invites’,
   component: InviteComponent,
   children: [
     {
       path: ‘’,
       loadChildren: ‘./pages/invites/invites.module#InvitesModule’,
     },
   ],
   canActivate: [AuthenticationGuard],
   runGuardsAndResolvers: ‘always’,
 }
]
export class InviteComponent implements OnInit, OnDestroy{
 // ... your class variables here
 navigationSubscription;
 constructor(
   // … your declarations here
   private router: Router,
  ) {
   // subscribe to the router events - storing the subscription so
   // we can unsubscribe later. 
   this.navigationSubscription = this.router.events.subscribe((e: any) => {
     // If it is a NavigationEnd event re-initalise the component
     if (e instanceof NavigationEnd) {
       this.initialiseInvites();
     }
   });
 }
 
 initialiseInvites() {
   // Set default values and re-fetch any data you need.
 }
 ngOnDestroy() {
    // avoid memory leaks here by cleaning up after ourselves. If we  
    // don't then we will continue to run our initialiseInvites()   
    // method on every navigationEnd event.
    if (this.navigationSubscription) {  
       this.navigationSubscription.unsubscribe();
    }
  }
}

References
https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

Angular Component Inheritance

Base Component

// ...
import { Router } from '@angular/router';

constructor(public router: Router) { }

Take note of the accessibility level. It’s important to keep this declaration “public” due to the inheritance.

Inherited Components

export class PageoneComponent 
  extends BaseComponent
  implements OnInit {
    // ...
}
constructor(public router: Router) {
  super(router);
}

References
https://alligator.io/angular/component-inheritance/

Mapping Multiple Domains into Single Instance of WordPress

Approach Taken & Implemented

  • Installed the WordPress into parent domain myjeeva.com
  • Configured various plugins for my blog
  • Pointed second domain myjeeva.mobi into parent domain IP through A record in DNS zone editor
  • Edited wp-config.php for two domain names according while accessing i.e. to reflect Site URL and  Site Home to respectivel

Editing wp-config.php

  • Go to WordPress installed root directory and look for wp-config.php file
  • Place below lines after the table_prefix line; order is very important in wp-config.php
/*
 * Handle multi domain into single instance of wordpress installation
 */
define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST']);
define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST']);
  • Go to wordpress admin page and take a look at Settings -> General. You will have WordPress Address (URL) and Site Address (URL) will be in disabled state.  It means your wordpress installation dynamic enoungh to accomadate both domain address

References
https://myjeeva.com/mapping-multiple-domains-into-single-instance-of-wordpress.html

Base64 Encoding and Decoding in Java

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>
String originalInput = "test input";
String encodedString = new String(Base64.encodeBase64(originalInput.getBytes()));
String decodedString = new String(Base64.decodeBase64(encodedString.getBytes()));

References
https://www.baeldung.com/java-base64-encode-and-decode
https://www.base64encode.org/
https://www.base64decode.org/