Skip to content

Blog

Bash Prompt and ls Alias

Prompt: [2020-03-13][23:49:21] [pi@raspberry:~]

  • Add at the end of ~/.profile
##### modify standard command prompt
# \n = new line; \u = current username; \w = current working dir (home = ~)
##### Colors
# Black       0;30     Dark Gray     1;30
# Blue        0;34     Light Blue    1;34
# Green       0;32     Light Green   1;32
# Cyan        0;36     Light Cyan    1;36
# Red         0;31     Light Red     1;31
# Purple      0;35     Light Purple  1;35
# Brown       0;33     Yellow        1;33
# Light Gray  0;37     White         1;37

export PS1="\[\033[0;33m\][\D{%Y-%m-%d}][\t]\[\033[0;36m\] [\u\[\033[0;37m\]@\[\033[0;36m\]\h:\[\033[0;32m\]\w]\[\033[0m\] \n$ "

##### Modify default ls command
# -G colorizes output
# -h makes sizes human readable
# -F throws a / after a directory, * after an executable, and a @ after a symlink
# -l listing format (as opposed to default wide)
# -a shows all files (even hidden)
alias ls='ls -laGFh'

Python Script to Get Local IPs

Python 3 Script to Get IPs

#!/usr/bin/env python3

def getips():
    import re
    import subprocess

    # get ip(s) from ifconfig
    found_ips = []
    ips = re.findall( r'[0-9]+(?:\.[0-9]+){3}', subprocess.getoutput("/sbin/ifconfig"))
    for ip in ips:
        if ip.startswith("255") or ip.startswith("127") or ip.endswith("255"):
            continue
        found_ips.append(ip)

    return ", ".join(found_ips)

Check Speed of Dns Servers wtih Dig

Check the speed of OpenDNS and Google Public DNS servers

OpenDNS Server addresses:

  • 208.67.222.222
  • 208.67.220.220

Google Public DNS Server addresses:

  • 8.8.8.8
  • 8.8.4.4

Test Server: brooklyn-chess.com

echo OpenDNS ... ; 
dig @208.67.222.222 brooklyn-chess.com | grep Query;
dig @208.67.220.220 brooklyn-chess.com | grep Query;

echo Google DNS ... ; 
dig @8.8.8.8 brooklyn-chess.com | grep Query;
dig @8.8.4.4 brooklyn-chess.com | grep Query;

Python 3 Script to Send Mail via Gmail

Python 3 Script to Send eMail via GMail

def emailsend(subject_part, message_part):
    # usage: emailsend("Server is up", "")
    import time
    import smtplib
    import socket

    from datetime import datetime
    current_utc = datetime.utcnow().isoformat() + 'Z'

    ####--[CONFIGURATION]
    server = 'smtp.gmail.com'
    server_port = '587'
    username = 'INSERT-YOUR-USERNAME@gmail.com'
    password = 'INSERT-YOUR-PASSWORD'
    hostname = socket.gethostname()

    from_addr = 'INSERT-YOUR-FROM-NAME <INSERT-YOUR-FROM@gmail.com>'
    to_addr = 'INSERT-YOUR-TO-EMAIL'
    subject = 'INSERT-YOUR-SUBJECT-PREPEND | ' + hostname + ' | ' + subject_part
    message = 'INSERT-YOUR-MESSAGE-PREPEND | ' + hostname + ' | <br>' + message_part + '<br><br><br>Email Generated On (UTC): ' + current_utc
    ####--[/CONFIGURATION]

    headers = [
            "Subject: " + subject,
            "From: " + from_addr,
            "To: " + to_addr,
            "MIME-Version: 1.0",
            "Content-Type: text/html"
            ]
    headers = "\r\n".join(headers)

    server = smtplib.SMTP(server + ":" + server_port)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(username,password)
    server.sendmail(from_addr, to_addr, headers + "\r\n\r\n" + message)
    server.quit()

Start Dev IIS Express Server

Start Development IIS Express Server (tested on Win7 and Win10 with mapped network drives)

@echo off
REM Script will start IIS Express on the specific port with the folder FROM WHICH SCRIPT IS CALLED
REM 
REM IIS Express does the following:
REM * Copies default applicationhost.config file ("C:\Program Files\IIS Express\AppServer\applicationhost.config") to %TEMP%\IISEXPRESS\APPLICATIONHOST{TimeStampGoesHere}.CONFIG (where timestamp is current date+time with milliseconds)
REM * The copied config file is modified to specify the physical path (<application ...> --> <virtualDirectory ...> physicalPath property) and the port (<bindings> -> <binding ...> bindingInformation property) 
REM * Path to custom configuration file can also be provided in the command line using /config:{FullPathToIISApplicationHostCustomConfigFile}

set iisexpress_loc="C:\Program Files\IIS Express\iisexpress.exe"
set folder_loc=%cd%
set port_loc=2018

if [%1]==[--help] goto syntax
if [%1]==[/?] goto syntax

if [%1]==[] goto proceed
set port_loc=%1

:proceed
echo.
echo Make "%folder_loc%" accessible from "http://localhost:%port_loc%" ...
echo.

%iisexpress_loc% /path:"%folder_loc%" /port:%port_loc% /trace:w /systray:true

goto exit

:syntax
echo.
echo Syntax: %0 PortNumberGoesHere
echo         Default Port: %port_loc%
echo.
goto exit

:exit
echo.
echo.
echo.
pause

Bash Profile Settings 1

Bash has five prompt strings that can be customized:

  • PS0 -> displayed after each command before any output;
  • PS1 -> primary prompt which is displayed before each command;
  • PS2 -> secondary prompt displayed when a command needs more input (e.g. a multi-line command).
  • PS3 -> not very commonly used. It is the prompt displayed for Bash's select built-in which displays interactive menus. Unlike the other prompts, it does not expand Bash escape sequences. Usually you would customize it in the script where the select is used rather than in your .bashrc.
  • PS4 -> is also not commonly used. It is displayed when debugging bash scripts to indicate levels of indirection. The first character is repeated to indicate deeper levels.

PS1 Color Prompt for Bash

[2017-04-14][20:52:25] [username@hostname]:~
$
  • Modify .bash_profile, .profile, or .bashrc (if using bash)
.bash_profile
export PS1="\[\033[0;33m\][$(date +%Y-%m-%d)][\t]\[\033[0;36m\] [\u\[\033[0;37m\]@\[\033[0;36m\]\h]:\[\033[0;32m\]\w\[\033[0m\] \n$"

alias ls='ls -laGFh'
Colors and Prompt Variables
##### modify standard command prompt
# \n   = new line; 
# \u   = username; 
# \h   = hostname;
# \t   = time;
# \w   = current working dir (home = ~);
# \A   = current time;
# \$?  = exit code/status from previous command;
# \033 = starts all escape sequences (^[ or \x1B)


##### Colors
# Black       0;30     Dark Gray     1;30
# Blue        0;34     Light Blue    1;34
# Green       0;32     Light Green   1;32
# Cyan        0;36     Light Cyan    1;36
# Red         0;31     Light Red     1;31
# Purple      0;35     Light Purple  1;35
# Brown       0;33     Yellow        1;33
# Light Gray  0;37     White         1;37
Linux ls command modifications
##### Modify default ls command
# -G colorizes output
# -h makes sizes human readable
# -F throws a / after a directory, * after an executable, and a @ after a symlink
# -l listing format (as opposed to default wide)
# -a shows all files (even hidden)

More Info

Richtextbox Output Log4net Appender

Use RichTextBox as an output of Log4net Appender

Step 1


  • Create a Windows Forms Application project named "Sample" using Visual Studio (the code is in c#).

Step 2


  • Get log4net library by either downloading it from https://logging.apache.org/log4net/ or by installing the package through NuGet Package Manager.

Step 3


  • Create folder "lib" under the project and place files there.
  • Add reference to lib\log4net.dll

Step 4


  • Please rename default form to "FrmSample". On the default form add a button and a RichTextBox.
  • Please name the RichTextBox as "RtbOutput" and a button as "CmdGenerateTestLogs".

Step 5


  • In the root of the project folder create XML file: log4net.config
  • In Properties for the file set: Copy to Output Directory: Copy if newer
  • Populate file with following (log file appender will create a file in logs folder with the file name of output.log; once file size reaches 10MB, new file will be created. Maximum of 10 log files will be retained). Please change "Sample" with the name of your project namespace, form name "FrmSample" with the name of the windows form name, text box name "RtbOutput" with the name of the RichTextBox that would be used to output log4net messages:
<?xml version="1.0" encoding="utf-8" ?>
<log4net xmlns="urn:log4net">
  <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="file" value="logs\output.log" />
    <param name="appendToFile" value="true" />
    <param name="rollingStyle" value="Size" />
    <param name="maxSizeRollBackups" value="10" />
    <param name="maximumFileSize" value="10MB" />
    <param name="staticLogFileName" value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="conversionPattern" value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <appender name="RichTextBoxAppender" type="Sample.RichTextBoxAppender, Sample">
    <formName value="FrmSample"/>
    <textBoxName value="RtbOutput"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %-5level - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="DEBUG" />
    <appender-ref ref="LogFileAppender" />
    <appender-ref ref="ConsoleAppender" />
    <appender-ref ref="RichTextBoxAppender" />
  </root>
</log4net>

Step 6


  • To enable logging, under the Properties folder double-click on AssemblyInfo.cs and add the following line at the end of the file:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

Step 7


  • Add a new class RichTextBoxAppender.cs to the project. Paste the following into the class file replacing existing text:
using System.Drawing;
using System.Windows.Forms;
using log4net.Appender;
using log4net.Core;

namespace Sample
{
    public class RichTextBoxAppender : AppenderSkeleton
    {
        private RichTextBox _textBox;
        public RichTextBox AppenderTextBox { get { return _textBox; } set { _textBox = value; } }
        public string FormName { get; set; }
        public string TextBoxName { get; set; }

        private static Control FindControlRecursive(Control root, string textBoxName)
        {
            if (root.Name == textBoxName) return root;
            foreach (Control c in root.Controls)
            {
                var t = FindControlRecursive(c, textBoxName);
                if (t != null) return t;
            }
            return null;
        }

        protected override void Append(LoggingEvent loggingEvent)
        {
            if (_textBox == null)
            {
                if (string.IsNullOrEmpty(FormName) || string.IsNullOrEmpty(TextBoxName)) return;

                var form = Application.OpenForms[FormName];
                if (form == null) return;

                _textBox = (RichTextBox)FindControlRecursive(form, TextBoxName);
                if (_textBox == null) return;

                form.FormClosing += (s, e) => _textBox = null;
            }
            _textBox.BeginInvoke((MethodInvoker)delegate
            {
                if (loggingEvent.Level == Level.Debug)
                {
                    _textBox.SelectionStart = _textBox.TextLength;
                    _textBox.SelectionLength = 0;
                    _textBox.SelectionColor = Color.RoyalBlue;
                    _textBox.AppendText(RenderLoggingEvent(loggingEvent));
                    _textBox.SelectionColor = _textBox.ForeColor;
                }
                else if (loggingEvent.Level == Level.Info)
                {
                    _textBox.SelectionStart = _textBox.TextLength;
                    _textBox.SelectionLength = 0;
                    _textBox.SelectionColor = Color.ForestGreen;
                    _textBox.AppendText(RenderLoggingEvent(loggingEvent));
                    _textBox.SelectionColor = _textBox.ForeColor;
                }
                else if (loggingEvent.Level == Level.Warn)
                {
                    _textBox.SelectionStart = _textBox.TextLength;
                    _textBox.SelectionLength = 0;
                    _textBox.SelectionColor = Color.DarkOrange;
                    _textBox.AppendText(RenderLoggingEvent(loggingEvent));
                    _textBox.SelectionColor = _textBox.ForeColor;
                }
                else if (loggingEvent.Level == Level.Error)
                {
                    _textBox.SelectionStart = _textBox.TextLength;
                    _textBox.SelectionLength = 0;
                    _textBox.SelectionColor = Color.DarkRed;
                    _textBox.AppendText(RenderLoggingEvent(loggingEvent));
                    _textBox.SelectionColor = _textBox.ForeColor;
                }
                else if (loggingEvent.Level == Level.Fatal)
                {
                    _textBox.SelectionStart = _textBox.TextLength;
                    _textBox.SelectionLength = 0;
                    _textBox.SelectionColor = Color.Crimson;
                    _textBox.AppendText(RenderLoggingEvent(loggingEvent));
                    _textBox.SelectionColor = _textBox.ForeColor;
                }
                else
                {
                    _textBox.AppendText(RenderLoggingEvent(loggingEvent));
                }
            });
        }
    }
}

Step 8


  • Open the code behind the form by pressing F7 on the form and paste following code:
using System;
using System.Drawing;
using System.Windows.Forms;
using log4net;

namespace Sample
{
    public partial class FrmSample : Form
    {

        private static readonly ILog Log = LogManager.GetLogger(typeof(FrmSample));

        public FrmSample()
        {
            InitializeComponent();

            #region Set properties for RtbOutput as per your choice
            RtbOutput.BackColor = System.Drawing.SystemColors.Control;
            RtbOutput.HideSelection = false;
            RtbOutput.ReadOnly = true;
            RtbOutput.Text = "";
            RtbOutput.WordWrap = false;
            RtbOutput.Font = new Font(FontFamily.GenericMonospace, 9);
            #endregion
        }

        private void CmdGenerateTestLogs_Click(object sender, EventArgs e)
        {
            Log.Debug("This is a DEBUG message");
            Log.Info("This is a INFO message");
            Log.Warn("This is a WARN message");
            Log.Error("This is a ERROR message");
            Log.Fatal("This is a FATAL message");
        }
    }
}

Step 9


  • Running program and clicking on the button should print out the log (same log will appear in the output.log file under log folder - check the project output directory). Feel free to modify the properties of the RichTextBox as you fit.

Open Ports Verizon Router Fios G1100

Forward port on Verizon FiOS Router G1100

Information Required:

  • Local IP Address of FiOS Router (by default 192.168.1.1) : {IP_ADDRESS_OF_FIOS_ROUTER}
  • Username and Password to login to the FiOS Router (usually on the sticker on your router).
  • Local IP Address of the Device that should be servicing Forwarded Port.
  • Port to be forwarded.

Steps:

  • Open browser and type in the http://IP_ADDRESS_OF_FIOS_ROUTER.
  • Type in "User Name" and "Password" of your router.
  • Choose "Firewall" from the top menu.
  • Click "Yes" button on the "Warning / Any changes made in this section may affect your router's performance and configuration. / Do you want to proceed?" screen.
  • Click "Port Forwarding" link on the left menu.
  • Under "Create new port forwarding rule" in the first drop down box "Select IP from menu" to select an IP address of the device on your network that should be accepting the request from the remote computer.
  • Click on "Application To Forward..." dropdown and choose "Custom Ports".
  • Choose the protocol: TCP, UDP, or Both and overwrite port 65535 with the port number of your choice.
  • Click "Add".
  • Do NOT CLICK "Advanced>>" and choose port that way.
  • Click "Logout" link on the left menu.
  • The "Port Forwarding" is completed.

Remove Win10 Icon and Fix Auto Updates

Remove Windows 10 Icon and Fix Auto Updates

  • Run cmd as Administrator
C:\>powershell
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS C:\> get-hotfix -id KB3035583, KB2952664, KB2976978, KB3021917, KB3044374, KB2990214

Source        Description      HotFixID      InstalledBy          InstalledOn
------        -----------      --------      -----------          -----------
MYPCNAME      Update           KB2952664     NT AUTHORITY\SYSTEM  7/15/2015 12:00:00 AM
MYPCNAME      Update           KB2990214     NT AUTHORITY\SYSTEM  4/15/2015 12:00:00 AM
MYPCNAME      Update           KB3021917     NT AUTHORITY\SYSTEM  2/11/2015 12:00:00 AM
MYPCNAME      Update           KB3035583     NT AUTHORITY\SYSTEM  7/17/2015 12:00:00 AM

PS C:\> exit

C:\>wusa /uninstall /kb:2952664

C:\>wusa /uninstall /kb:2990214

C:\>wusa /uninstall /kb:3021917

C:\>wusa /uninstall /kb:3035583

C:\>

C# Log4net Min Usage

Log4Net Minimal Usage

Log4net - minimal info to start.

Step 1


  • Create a project using Visual Studio (the code is in c#).

Step 2


Step 3


  • Create folder lib under the project and place files there.
  • Add reference to lib\log4net.dll

Step 4


  • In the root of the project folder create XML file: log4net.config
  • In Properties for the file set: Copy to Output Directory: Copy if newer
  • Populate file with following
  • log file appender will create a file in logs folder with the file name of output.log;
  • once file size reaches 10MB, new file will be created
  • Maximum of 10 log files will beretained

Sample of log4net.config

<?xml version="1.0" encoding="utf-8" ?>
<log4net xmlns="urn:log4net">
  <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="file" value="logs\output.log" />
    <param name="appendToFile" value="true" />
    <param name="rollingStyle" value="size" />
    <param name="maxSizeRollBackups" value="10"/>
    <param name="maximumFileSize" value="10MB" />
    <param name="staticLogFileName" value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="conversionPattern" value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="DEBUG"/>
    <appender-ref ref="LogFileAppender"/>
  </root>
</log4net>

Step 5


  • Under the "Properties" of the project in Solution Explorer open up AssemblyInfo.cs
  • Add the following line at the end (ConfigFile points to the configuration file, Watch flag can be set to True to apply updates to the configuration file without restarting the program):
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

Step 6


  • In the file (eq: MyClass) where you want to use log functionality add the following (you can use any string you wish instead of typeof (MyClass). This, however, will indicate which project file was logging):
using log4net;

... class MyClass ...
{
  private readonly ILog Log = LogManager.GetLogger(typeof (MyClass));
  ...
}

Step 7


USAGE:

Log.Debug("This is a debug message");
Log.Info("This is an informational message");
Log.Warn("This is a warning message");
Log.Error("This is an error message");
Log.Fatal("This is a fatal error message");

Additional Comments


  • The log file can be placed anywhere in the filesystem by specifying the path in the log4net.config.
  • Make sure that running user has a CREATE and WRITE permission to logs folder (by default created in the app folder).
  • You can use NUGET to search for log4net. This will take care of steps 2 and 3.

Examples

More Info: http://logging.apache.org/log4net/