TreeView context menus

Recently I wanted to add a right click context menu to a list of items in a TreeView control in C# and winforms.

It was relatively simple but there is one small thing that isn’t as obvious. That is that it is good to allow users to be able to right click an item and open it, delete it, run it or whatever you action is on the your context menu, without having to left click select it first. Less clicks == good.

So first create your TreeView, you can do this by dragging the control onto your form or custom control.

Now add a ContextMenuStrip item from the toolbox in the same way.

Go to the properties of the TreeView and set the ContextMenuStrip property to be the one which you just created.

Now add items to your context menu by click the small arrow drop down at the top right corner of it, see the image below:

contextMenuAddItems

You will then be able to click Edit Items:

contextMenuAddItems2

From you can add menu items, so add the ones you want and name them appropriately and change the menu text for them as well.

Now for the right clicking to actually work without a user selecting the item first we need to add this line of code somewhere sensible, i’ve put mine just after the InitializeComponent(); line in the form.

yourTreeView.NodeMouseClick += (sender, args) => yourTreeView.SelectedNode = args.Node;

This line of code means that the node you right click on will be selected as you right click, this is very important as in most cases you will want the actions in the context menu to be applicable to the item you have right clicked.

So now if you click your ContextMenuStrip control that you added your items to you should see your menu at the top of the form (while in design mode the context menu is just at the top of the form). Double click one of your items to add some functionaility.

One of my right click menu items is called openFile the click handler is below, this is where it is important to be able to have your SelectedNode set to the one you right clicked on.

// Code executed when a context menu item is clicked
private void openFile_Click(object sender, EventArgs e) {
    
    // Here we can now reference yourTreeView.SelectedNode
    DoSomething(yourTreeView.SelectedNode.Text);
}

 

If we did not have that first line of code ( the NodeMouseClick event handler ) the above code would throw an exception as the SelectedNode would be null (unless the user did a left click first).

Happy right clicking!

Gedit settings not saving

The Problem

(Just skip to the solution for the commands you need to run to fix this)

I use Gedit over SHH with Xming / X11 running quite regularly and I was not able to save my setting in Gedit. I am running a Red Hat based OS ( such as CentOS and Scientific Linux )

The first error I got was:

GLib-GIO-Message: Using the 'memory' GSettings backend. Your settings will not be saved or shared with other applications.

This tells us that Gedit cannot use the normal GSettings backend to save our settings to disk and is just going to save them to (volatile) memory so when we exit the applicaiton our settings are lost. Not a very clear message at all if you actually want to fix this bug as it gives you no clues that it really wants you to install various other packages (one of them is dconf as we’ll see below).

After searching around I found out i needed to install dconf. After which I got a new error message:

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

Again not very clear… but dconf wants us to install dbus, so I did that and found it was already installed! So I searched Yum and saw a package named dbus-x11. I installed this package and my settings now save.

The solution steps are below.

The Solution

yum install dconf
yum install dconf-editor
yum install dbus
yum install dbus-x11

I hope this helps someone!

 

Setup FTP on Red Hat based OSs

In this post I’ll go through the very basic steps of how to setup your FTP server on Red Hat based OSs such as CentOS and Scientific Linux.

yum install -y vsftpd
systemctl start vsftpd
systemctl enable vsftpd

Now we need to edit the configuration file here:

/etc/vsftpd/vsftpd.conf

Here is my file, the changes I have made are in red and bold.

# Example config file /etc/vsftpd/vsftpd.conf
#
# The default compiled in settings are fairly paranoid. This sample file
# loosens things up a bit, to make the ftp daemon more usable.
# Please see vsftpd.conf.5 for all compiled in defaults.
#
# READ THIS: This example file is NOT an exhaustive list of vsftpd options.
# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
# capabilities.
#
# Allow anonymous FTP? (Beware - allowed by default if you comment this out).
anonymous_enable=NO
#
# Uncomment this to allow local users to log in.
# When SELinux is enforcing check for SE bool ftp_home_dir
local_enable=YES
#
# Uncomment this to enable any form of FTP write command.
write_enable=YES
#
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
local_umask=022
#
# Uncomment this to allow the anonymous FTP user to upload files. This only
# has an effect if the above global write enable is activated. Also, you will
# obviously need to create a directory writable by the FTP user.
# When SELinux is enforcing check for SE bool allow_ftpd_anon_write, allow_ftpd_full_access
#anon_upload_enable=YES
#
# Uncomment this if you want the anonymous FTP user to be able to create
# new directories.
#anon_mkdir_write_enable=YES
#
# Activate directory messages - messages given to remote users when they
# go into a certain directory.
dirmessage_enable=YES
#
# Activate logging of uploads/downloads.
xferlog_enable=YES
#
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES
#
# If you want, you can arrange for uploaded anonymous files to be owned by
# a different user. Note! Using "root" for uploaded files is not
# recommended!
#chown_uploads=YES
#chown_username=whoever
#
# You may override where the log file goes if you like. The default is shown
# below.
#xferlog_file=/var/log/xferlog
#
# If you want, you can have your log file in standard ftpd xferlog format.
# Note that the default log file location is /var/log/xferlog in this case.
xferlog_std_format=YES
#
# You may change the default value for timing out an idle session.
#idle_session_timeout=600
#
# You may change the default value for timing out a data connection.
#data_connection_timeout=120
#
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
#nopriv_user=ftpsecure
#
# Enable this and the server will recognise asynchronous ABOR requests. Not
# recommended for security (the code is non-trivial). Not enabling it,
# however, may confuse older FTP clients.
#async_abor_enable=YES
#
# By default the server will pretend to allow ASCII mode but in fact ignore
# the request. Turn on the below options to have the server actually do ASCII
# mangling on files when in ASCII mode.
# Beware that on some FTP servers, ASCII support allows a denial of service
# attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd
# predicted this attack and has always been safe, reporting the size of the
# raw file.
# ASCII mangling is a horrible feature of the protocol.
ascii_upload_enable=YES
ascii_download_enable=YES
#
# You may fully customise the login banner string:
ftpd_banner=Your banner text here.
#
# You may specify a file of disallowed anonymous e-mail addresses. Apparently
# useful for combatting certain DoS attacks.
#deny_email_enable=YES
# (default follows)
#banned_email_file=/etc/vsftpd/banned_emails
#
# You may specify an explicit list of local users to chroot() to their home
# directory. If chroot_local_user is YES, then this list becomes a list of
# users to NOT chroot().
# (Warning! chroot'ing can be very dangerous. If using chroot, make sure that
# the user does not have write access to the top level directory within the
# chroot)
#chroot_local_user=YES
#chroot_list_enable=YES
# (default follows)
#chroot_list_file=/etc/vsftpd/chroot_list
#
# You may activate the "-R" option to the builtin ls. This is disabled by
# default to avoid remote users being able to cause excessive I/O on large
# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
# the presence of the "-R" option, so there is a strong case for enabling it.
#ls_recurse_enable=YES
#
# When "listen" directive is enabled, vsftpd runs in standalone mode and
# listens on IPv4 sockets. This directive cannot be used in conjunction
# with the listen_ipv6 directive.
listen=NO
#
# This directive enables listening on IPv6 sockets. By default, listening
# on the IPv6 "any" address (::) will accept connections from both IPv6
# and IPv4 clients. It is not necessary to listen on *both* IPv4 and IPv6
# sockets. If you want that (perhaps because you want to listen on specific
# addresses) then you must run two copies of vsftpd with two configuration
# files.
# Make sure, that one of the listen options is commented !!
listen_ipv6=YES
pam_service_name=vsftpd
userlist_enable=YES
tcp_wrappers=YES
use_localtime=YES

Now restart the FTP service:

systemctl restart vsftpd

Create a user for FTP access:

useradd ftpuser
passwd ftpuser

Now you should be able to connect to your FTP server using the above user account (root probably wont’ work, hence the new user). You will need your server IP, to get this you can run ifconfig.

I use FileZilla as an FTP client.

service command depreciated in RHEL based OSs

service

The service command is no longer valid in red hat based systems such as CentOS and Scientific Linux. You will probably see the message “Redirecting to /bin/systemctl” when you try and start / stop / status a service. So now we have to do it as below:

For example:

service httpd start

Would now be run as below:

systemctl start httpd

 

chkconfig

chkconfig has also been changed, for example:

chkconfig httpd on

becomes

systemctl enable httpd

… and …

chkconfig httpd off

becomes

systemctl disable httpd

… and …

chkconfig httpd

becomes

systemctl is-enabled httpd

… and …

The below command shows what services are enabled (chkconfig –list):

systemctl list-unit-files --type=service

 

Hope this helps someone!

 

Creating a WordPress All Posts Page

I wanted a page that would list all my posts, a site index basically. I tried a simple method and it was close but not what I wanted, it did not dynamically put the list of posts inside the content area of a page, so it looked very odd.

So here is a way to get your “All Posts” looking how it should on your WordPress site.

Example: http://tripsintech.com/all-posts/

Step 1 Child Theme

Make sure you are using a child theme on your WordPress site.
( You don’t have to do this but if you don’t use a child theme then when you update your theme then anything you do next will just be overwritten )

Step 2 Page Template

Create a page template. To do this create a php file in your active theme directory, mine is here:
“…/wp-content/themes/twentyfifteen-child/AllPostTemplate.php”

Now paste in the below code into  your AllPostTemplate.php file and save it.

<?php
/*
Template Name: All posts
*/
get_header(); ?>
 <div id="primary" class="content-area">
 <main id="main" class="site-main" role="main">

 <?php
 // Include the page content template.
 get_template_part( 'content', 'page' );
 
 $first = 0; //The first article to be displayed
 while(have_posts()) : the_post(); 
 ?>
<script>
 var x = document.getElementsByClassName("entry-content");
 if (x[0] != null) {
 x[0].innerHTML = "<ul> <?php $myposts = get_posts('numberposts=-1&offset=$first'); foreach($myposts as $post) : ?><li><?php the_time('d/m/Y') ?>: <a href='<?php the_permalink(); ?>'><?php the_title(); ?></a> </li><?php endforeach; ?></ul> <?php endwhile; ?>";
 }
</script>

 </main><!-- .site-main -->
 </div><!-- .content-area -->

<?php get_footer(); ?>

Step 3 Create Page

Now we need to actually create the all posts page, this is very simple and is done through the WordPress dashboard.

Go to pages, then create a new page and change the Page Template from default (or whatever else it is) to be “All posts”.

All done!

 

 

NB: This template has only been tested with the TwentyFifteen Theme, it should work for most though.

Decoding Meteor-M N2 LRPT Satellite Weather Images

Edit 25/4/2016:
There is a plugin for SDR sharp that now does a lot of this process for you and is all together a lot quicker. The SDR plugin way of doing it is less robust as I’ve compared both methods multiple times but the time savings are probably worth it. Here is an article to get you started.

Example Image (cropped)

My first visible light Meteor LRPT weather satellite image
My first visible light Meteor LRPT weather satellite image

Above is a cropped image from the Meteor-M N2 polar orbiting Russian weather satellite that was launched on 8th July 2014. From this satellite we can freely acquire Low Resolution Picture Transmission (LRPT) images.

Hardware Needed

  • A suitable SDR USB stick (e.g.  amazon.co.uk)
    cropped
  • Now comes a choice…. if you don’t have a proper aerial, for example a turnstile one, pictured against the sky below,  then you could, as a prototype, use something like this TV/Freeview aerial below which has a built-in amplifier:aerial-alternative

 

  • Now if you’re serious about getting good images you should get an aerial and dedicated amplifiers that are designed for the job:aerial-noexif

 

  • An amplifier (if using a ‘proper’ aerial with no built-in amplifier)
    • The signal is not very strong if you just use the dongle and the aerial. An amplifier is necessary between the antenna and the SDR dongle.
    • For best results you will need a low noise pre amplifier followed by a higher gain amplifier. All in you will need approximately 40-50db gain.

Software Needed

 

Steps

Step 1 – Setup your hardware

Setup your hardware. Put the aerial in a suitable location, outside away from metal structures is probably best. If not using a TV aerial with built-in amplifier then connect up the aerial to the first low noise pre-amp and then connect the output of the pre-amp to the input of your higher gain amplifier.

Attach your SDR USB dongle to the output of your amplifier and plug it into the a USB slot.

Everything is now wired up and ready for you to install and setup all the software.

Step 2 – Orbitron

Orbitron is the software which will allow us to track the satellites and know then they are close enough for us to hear them with our receiver.

Install Orbitron by downloading it and running the file.
We now need to setup Orbirton to get the correct Kepler elements needed to track the satellites.

Setup Orbitron by following these steps.
Set your location:
orbitronsetup3

Find the menu button which is hidden away at the top right, circled in red in this image:
orbitronsetup1
Click it and choose AutoUpdate TLE, click ok and let it update all the .txt files containing the orbital elements.

Click the menu again and choose load TLE, select Weather.txtorbitronsetup2
Now you will see a list of satellites on the right hand side. Tick the ones you want to see in this case we’re interested in Meteor M2. (you may also want to acquire the NOAA satellites too, they’re easier to get but lower resolution)

orbitronsetup4

Step 3 – Audacity

Download it and follow the installer.

Step 4 – LRPTRx & LRPTofflineDecoder

Both LRPTRx and LRPTofflineDecoder do not require installation, they can just be run BUT MUST BE RUN AS ADMINISTRATOR. (right click run as administrator, or set it permanently in the compatibility tab under properties)

Step 5 – SDR Sharp – part 1 (zadig.exe)

EDIT: If your SDR# (sharp) download did not come with the zadig.exe file then you can download it from here: http://zadig.akeo.ie/

Download SDR sharp and run the batch file in a CMD running as admin.
This will download the files needed for SDR Sharp to run.
Ensure the SDR dongle is plugged in and follow below to setup the SDR USB driver.

You must first run \sdr-install\sdrsharp\zadig.exe, again this must run as admin.

Select Options > List All Devices:
zadig1

Select Bulk-In interface 0:
zadig2

Choose WinUSB in the box to the right of the green arrow:
zadig3

Click Replace Driver.

Step 6 – SDR Sharp – part 2 (config)

Now, start up SDRSharp.exe and select RTL-SDR / USB in the source drop down.

sdrsharp1

We also want to make sure other settings are correct.
Correct IQ should be checked
WFM  (Wideband FM) should be selected
Bandwidth should be set to ~140000Hz
Recording LRPT signals requires that we select Baseband in the recording tab, not just the audio like we do with NOAA satellites.

sdrsharp2

The last part of the SDR setup is to set our frequency.
The Meteor M2 satellite is transmitting on two frequencies, we will be listening to the signal on 137.1MHz. So set your SDR sharp frequency to that.
sdrsharp3

Note: you may also need to increase your gain in SDR Sharp under the cog menu icon, mine is set to ~30db but this is something that will differ for every setup and should be tweaked to what looks good for you, i.e. increase the gain until the signal noise is increasing at the same rate.

Step 7 – Recording the transmission

So things start to get a little more interesting now. Once you click the run arrow icon you should start to see a spectrum of signals and noise in SDR Sharp.

sdrsharp4

Make sure the satellite is going over / close to your location.
( Look at the yellow circles on Orbitron to see when it will be in range, it will probably be a fair amount smaller than the circles in Orbitron in reality, depending on your aerial.)

You should then start to see a signal peak around 137.1MHz as shown below:

sdrsharp5

Make sure to click record! (baseband only for LRPT which is used on Meteor M2)

Step 8 – Decoding and preparing the files.

Find the file that was saved, usually saved in the same directory as the SDRSharp.exe you ran.
Open the .wav in audacity.
Change the project sample rate (bottom left) to be 140000Hz
Amplify (effects->amplify) the signal only if needed. The amplitude during the main signal should be approximately 2/3 of the maximum.
audacity1

Then export the audio (File > Export audio) and save it somewhere.

The next part of preprocessing the file is done by using LrptRx.exe (running as admin or else it will fail to write any files)

Open the file you exported from audacity with the LrptRx.exe application.
Check swap I/Q
Click run and eventually you should see the green dots in the 4 quadrant graph start to make 4 distinct constellations:
LRPTRx1
Let LrptRx.exe run until the progress bar in the middle gets to the end but beware it will not stop automatically so manually stop it near or at the end, no idea why the author did not make it auto stop, sigh.

Now find the output file generated by LrptRx.exe and start up LRPToffLineDecoder.exe as admin.

Tick the ignore RS check box.

Click the 72k button and open your .raw file, your image should slowly start to appear.

To save the image change the RGB drop downs to all match the column you want to save, e.g. set all to 3.5 – 4.1

Then click generate and save the image, below is my first ever M2 image, a bit broken up but not bad! Please do feel free to share yours here too, i’d like to see them.

m2-29-dec-2014.raw_222

Phew, that’s a lot of work but it’s worth it for the unique images we can get.

I will be investigating other ways to process the files as this method is very time consuming and requires many manual steps. Once I have an automated way of doing this with either the same or different software I will definitely post my method.

EDIT: Faster method

Move WordPress Site (same hosting different domain)

As I’ve recently done this myself and it wasn’t as straight forward as wordpress say it is here are a few things which may be of use to someone.

I’m assuming that:

  • You want to move your wordpress site ‘olddomain.com’ to ‘newdomain.com’
  • Both  ‘olddomain.com’ and ‘newdomain.com’ are hosted together.
  • That the ‘newdomain.com’ can access the database that ‘olddomain.com’ was using.

Step 1

Backup your site (Database and files)

Step 2

Copy all your files from your ‘olddomain.com’ directory to your ‘newdomain.com’ directory

Step 3

Go to your settings->general section of your new wordpress site e.g ‘newdomain.com/wp-admin/options-general.php’

Update both the fields for ‘WordPress Address’ and ‘Site Address’ to be ‘http://newdomain.com’

Step 4

By now your site will almost be working but some images and other media will not be working.

We need to change values in the database to stop them pointing to ‘olddomain.com’ for images as once you delete your old site files they will obvisouly not be accessible. You can do this manually or use this plugin I found that works well.

Go to your Plugins section and install the plugin: ‘Search & Replace’ the summary is: “A simple search to find strings in your database and replace those strings.”

Now go to tools and select ‘Search & Replace’ and select ‘Search and replace’ and enter your old domain in the ‘search for’ and your new domain in the ‘replace with’:searchAndReplacePlugin

Click go and you should be done.

Hope that  helped someone out there!