cURL Project Application in C Sharp

Over time, and out of necessity, I have been throwing together a few different tools over time using C# to help me cut down the amount of time it takes me to do certain things. As I create those I make them code generic so as to not include anything company wise and I like to share those projects so that others learning to code or who might be searching for code or projects might find them beneficial.

Testing in a QA/eCommerce environment, I use cURL pretty much daily for clearing Varnish cache when testing web pages across different staging servers and was curious about creating a wrapper for the curl.exe in C# that I could include within my standalone portable tool set. I did some research and although I did find several great resources I chose to stick it out with a Microsoft article I found titled How To Write a Wrapper for a Command-Line Tool with Visual C# .NET. The article gives a great explanation of creating a class file and adding it to a project.

The cURL Project Application

My cURL project simply needs to fulfill the function of issuing a purge command at whatever URL I give it so its geared with this specific task in mind. Normally I would stick the folder to the curl.exe file in my system PATH environment variable, open a command prompt and issue curl -X PURGE v1.cms.servername.com but the task, for me, is to include this within my “forms” tools that I created in c#.

Using CMD

Issuing the curl -X PURGE command in the command console would yield the results below. I just need the same thing in my tool which I can do using return “t” + output in the class file start.cs.

 

curl_cmd

Using cURL Tool

The URL field is for the URL on the server I want to clear varnish cache for. The drop down boxes, respectively, retain the switch and command that I want to issue. The PURGE button simply runs the app and on success will give me a message dialog as shown in the second cURL graphic below. the drop down boxes actually have the switch and command respectively listed three times via loading an array in the form_load event. It’s because I may add a couple more items. If not then I will break these out of an array but still load them in the event.

Code follows as well as a ZIP file to download that contains the project and executable. Enjoy.

mycurlapp

 

curl_app01

Start.cs file based on the Microsoft article

The class can really just get by with using System.Diagnostics and using System.IO. Modify as you see fit for your project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;

namespace MyCurlApp
{
    public class start
    {
        internal static string Run(string exeName, string argsLine, int timeoutSeconds)
        {
            StreamReader outputStream = StreamReader.Null;
            string output = "";
            bool success = false;

            try
            {
                Process newProcess = new Process();
                newProcess.StartInfo.FileName = exeName;
                newProcess.StartInfo.Arguments = argsLine;
                newProcess.StartInfo.UseShellExecute = false;
                newProcess.StartInfo.CreateNoWindow = true;
                newProcess.StartInfo.RedirectStandardOutput = true;
                newProcess.Start();

                if (0 == timeoutSeconds)
                {
                    outputStream = newProcess.StandardOutput;
                    output = outputStream.ReadToEnd();
                    newProcess.WaitForExit();
                }
                else
                {
                    success = newProcess.WaitForExit(timeoutSeconds * 1000);

                    if (success)
                    {
                        outputStream = newProcess.StandardOutput;
                        output = outputStream.ReadToEnd();
                    }
                    else
                    {
                        output = "Timed out at " + timeoutSeconds + " seconds waiting for " + exeName + " to exit.";
                    }
                }

            }
            catch (Exception e)
            {
                throw (new Exception("An error occurred running " + exeName + ".", e));
            }
            finally
            {
                outputStream.Close();
            }
            return "t" + output;

        }
    }
}

Main Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;

namespace MyCurlApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] myList = new string[3];
            myList[0] = "-X";
            myList[1] = "-X";
            myList[2] = "-X";
            comboBox1.Items.AddRange(myList);
            comboBox1.SelectedIndex = 0;

            string[] myList2 = new string[3];
            myList2[0] = "PURGE";
            myList2[1] = "PURGE";
            myList2[2] = "PURGE";
            comboBox2.Items.AddRange(myList2);
            comboBox2.SelectedIndex = 0;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                string output;
                string arg1 = comboBox1.Text;
                string arg2 = comboBox2.Text;
                string arg3 = textBox1.Text;

                // My draconian error control. maybe use a switch case if ever using another paramter
                // than -X. I only purge with this.

                if (textBox1.Text == "" || comboBox1.SelectedItem.ToString() == null || comboBox2.SelectedItem.ToString() == null)
                {
                    //MB works good if textBox is empty
                    MessageBox.Show("Select a valid parameter or URL!");
                    return;
                }
                else
                {
                    // run if all is cool
                    output = start.Run("Curl.exe", " " + arg1 + " " + arg2 + " " + textBox1.Text, 10);
                    MessageBox.Show(output + "If blank, check the URL");
                }

            }
                //If fields are blank otherwise show any exceptions
                //Should always include basic try and catch in case an error occurs
                catch (NullReferenceException ex)
                {
                    MessageBox.Show("nPerhaps you forgot to select something?n" + ex.Message);
                }

                catch (Exception ex)
                {
                    MessageBox.Show("Well this isn't good! " + "rn" + ex.Message);
                }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            string getcb = Clipboard.GetText(TextDataFormat.UnicodeText);
            textBox1.Text = getcb;
        }

    }
}

REFERENCES

Microsoft – How To Write a Wrapper for a Command-Line Tool with Visual C# .NET

DOWNLOAD

Advertisements

Preventing comments on the image attachment pages in WordPress

I think Don’t Tread On Me has pretty much lost its meaning these days, especially with regard to spamming. I really hate spam and wish nothing but wicked things to those who do it. In any event, lately I had started seeing spam type comments cropping up on image attachment pages of my site and in checking them out I had no idea that comments could even be placed on these pages. Perhaps I missed that in reading the WordPress Codex at some point or I just plain forgot.

I’m not sure why WordPress does not have a central settings area specifically for controlling comments but it would be nice. Essentially this is left to configuring by way of manual editing of code or using third party plug-ins and I question the necessity of the latter since it seems like a no-brainer to just add the functionality.

The way WordPress handles comments currently allows someone to click on a thumbnail of an image and that in turn displays the image as a post along with a comment area under it. I guess comments on individual images is valuable in some way?

picturespam_40

In any regard, it really drove me nuts whenever I would get a comment notification, review it and find it was on the image page in Russian, jibberish or just nonsense text so I decided to review some of the php files to look for anything related to comments.

I’m currently using the Misty Lake theme by Automattic and noticed in the Image Attachment Template (the image.php file) that towards the bottom it instantiated a call to comments_templates.

mistylake code_60

After making a backup of the image.php file, backups are always recommended, I used the editor in WordPress to removed the line, updated it, and now the comment area no longer appears on image attachment posts.

I will need to remember this moving forward should I ever update the theme as I am sure at some point the image.php file will be updated and I will need to manually remove the line again. Equally, should I change themes I will need to remember to double-check comments. It has actually been a few weeks since I made this manual modification and I have not experienced the spam as I was before. Hopefully the info will help someone.

Well, as an update to this, I decided to create my own custom-functions.php and add a function to do the above.

function DisableMediaComments( $open, $post_id ) {
$post = get_post( $post_id );
if ( 'attachment' == $post->post_type ) {
$open = false;
}
return $open;
}
add_filter( 'comments_open', 'DisableMediaComments', 10, 2 );

The code above should generically work within any theme. There is also another way, based on the comments_template line I removed from the theme I am using. Change the comments_template line from this:

<?php comments_template(); ?>

To this which will only show a Comments form if the parent post has comments enabled:

<?php if (comments_open($post->post_parent)) {
 comments_template();
} ?>

So with the above, if your post is enabled for comments then so will any attached images. Otherwise, if comments are disabled in the post, they will also be disabled for attached images. I believe I Googled the aforementioned and saw it on a few websites/forums so kudos go to whomever posted it first.

In any regard, I still elected for the function in my custom-functions.php file. To me its just easier that way and I don’t have to worry about any code changes to the theme.

Programming out of need – Getting IP and MAC Addresses

getipmac-ipThis is my C Sharp project for getting IP and MAC addresses. Code kudos go out to respective developers and websites, such as MSDN, stackoverflow, C# Corner and others I have left out but all code is in the public domain and modified by me to fit my needs.

As far as I am concerned my projects are as-is and there is nothing code efficient in my projects so please don’t beat me up too bad over any of it.

I am not a professional programmer in any regard but do consider myself a coder, this is just my slapped together get ‘er done tool befitting my personal need. If you want to comment on my project offline send me an email at stevegossett (AT) outlook.com

NOTE
You will need .NET 4.5 installed for this C# project and you will need to right-click on the
project name from within the IDE and add references to:

  • System.Management
  • System.Management.Instrumentation


Download Project



CSGetIPMAC

 

Nexus 7 First Gen (2012) – Flashing Lollipop Factory image

I got tired of waiting for Android Lollipop to become available for my Nexus 7 (2012) so decided to grab the factory image and flash it myself. I was pleasantly surprised at how easy this was to accomplish and so far I have not had any issues with Android 5.0. I even dare say that it seems faster than KitKat 4.4.4. I will run a Geekbench on it at some point.

First I downloaded the Android SDK and unzipped it to the root of my D: drive. I chose this location because it has been my experience that the folders run a bit deep and Windows Explorer will eventually bomb out on copying files. Unzipping to the root folder keeps the character count and folder names to a minimum.

nexus_ss2

Installing Google USB Driver

Once unzipped, I ran the SDK Manager under the root of the adt-bundle-windows-x86_64-20140702 folder, the folder name as of version currently available.

In the SDK Manager, I left what was currently checked, scrolled down to Extras, checked the box for Google USB Driver and clicked to install the packages.

When the packages were finished installing, I needed to install the Android USB driver on my system with Windows 7 Professional.

There is a guide for installing the Google USB driver on the various platforms of Windows here.

  1. Click on Start, right-click on Computer and select Manage.
  2. Select Device Manager on the left.
  3. On the right, under list of items under the computer name, look for Other device. It should already be expanded.
  4. Right-click the item name and select Update Driver. This will launch the Hardware Update Wizard.
  5. Select Browse my computer for driver software and click Next.
  6. Click Browse and navigate to the USB driver folder located in <sdk folder location>extrasgoogleusb_driver.) As an example, for me it was D:adt-bundle-windows-x86_64-20140702sdkextrasgoogleusb_driver.
  7. Click Next to install the driver.
  8. I rebooted the system but don’t know that I exactly needed to.

Next I downloaded the factory image from Android Nexus images page under Factory Images “nakasi” for Nexus 7 (Wi-Fi) and then 5.0 (LRX21P) and unzipped it to the root of my D: drive (D:nakasi-lrx21p-factory-93daa4d3) as well.

nexus_ss1

Add folder to Path System Variables

Now, I needed to start my Nexus in fastboot mode and opted to use the keys on the tablet rather than the adb tool in the Android SDK.

I know I’m going to use that tool later and opted to enter its folder location in my PATH system variable so I can run adb commands no matter what folder I was in.

I powered off my Nexus 7 and then pressed the volume up/down and power buttons at the same time until I saw the fastboot screen.

Opening a command console (CMD) as administrator on my computer I typed in the command to unlock the boot loader (This erases all data on the device):

At command line: fastboot oem unlock

I could see the confirmation on my Nexus 7 and saw the red text at lower left reflected it is now unlocked.

Next, in the command console window I navigated to the system image directory I unzipped earlier (for me D:nakasi-lrx21p-factory-93daa4d3nakasi-lrx21p) and typed the fast install command which started the flash process of the 5.0 image to my Nexus and waited out the process until it was done.

At command line: flash-all.bat

When the flash process is finished the command prompt will show to click any key to finish, the Nexus rebooted and I had a nice clean version of 5.0 Lollipop.

Before doing anything I re-locked the boot loader by turning off the tablet, booting to fastboot mode and from the command prompt issuing the command

At command line: fastboot oem lock

The text at the lower left confirms the lock was successful.

 

Resources

https://developer.android.com/sdk

https://developers.google.com/android/nexus/images

http://developer.android.com/tools/device.html

http://forum.xda-developers.com/showthread.php?t=1907796

Bitnami WordPress Virtual Machine

bitnami-wp-greyWhen pushing websites, even my own personal, I would rather screw up in a staged environment rather than pushing something live and finding out the site is hosed or dysfunctional in some way. I recently came across Bitnami’s site and saw that they had a free self-contained WordPress virtual machine (virtual appliance) so I thought I would give that a try and share a bit of the experience.  I currently run WordPress on my domain but simply wanted something I could use and stage on even if I lost connection with the net. Among using it as my stage environment, I can also use it for other things such as theme or plugin development.

How It Works

Essentially, the way this works is you are using a server that is running on your local computer, which the virtual machine is providing, and using your internet browser to log into that server like you would to log into any WordPress site but by its IP address (ex: http://123.123.123.123/wp-login) rather than a domain name like http://www.mysite.com.

The virtual machine contains a minimal Linux OS (Ubuntu Server 14.04.01 LTS) and a fully configured Bitnami application stack, meaning it has a group of all applications necessary to get started right away with WordPress such as the latest ready to run versions of WordPress, Apache, MySQL, Varnish, PHP and phpMyAdmin. You simply start the server, point your web browser to it and log in.

Caveat – Sort Of 

Ubuntu Server does not include a GUI but a command line by default so I decided to install as thin a desktop as possible that would be light on resources and give me basic functions in the OS and went with the lightweight Lubuntu LXDE desktop environment. The VM will only be used on my home network so security wise I’m only concerned with local login to the VM, and having the desktop will let me do admin stuff on the fly.

To install minimal Lubuntu desktop without all the recommended applications, once booted to the command line of the virtual machine:

  1. Type: sudo apt-get install –no-install-recommends lubuntu-desktop
  2. Click ENTER

If you get an error then drop to the root prompt and try it like below (you will be prompted for the admin login):

  1. Type: sudo su
  2. Click ENTER
  3. Type: apt-get install –no-install-recommends lubuntu-desktop
  4. Click ENTER

You will get a few prompts to answer, the VM will reboot and you will see the desktop login prompt. If you don’t see a blank username prompt to log into then click the drop down box and select Other.

bitnami1

Lubuntu Desktop Login

 

 

 

 

 

 

 

 

 

 

Access the Server (Virtual Appliance)

As explained on the Bitnami WordPress Virtual Machine webpage the default username and password are both “bitnami”. You may have seen a reminder of this during the first time the VM booted up. Once you have logged in the first time, you will be prompted for a new password so use that to log into the virtual machine.

Getting Started

Open a web browser and type in the IP address of the virtual machine. If you do not know it, look on the Bitnami command console window (if you did not install a desktop) or log into the server, go to System Tools > XTerm and type ifconfig at the terminal command prompt.

Your IP address will be listed as inet addr:XXX.XXX.XXX.XXX. On success, you will land on a very  plain and very bland sample WordPress page with Hello World in it. Under the META section, click on Log in or append /wp-admin.php to the end of the IP to get the WordPress login page (http://123.123.123.123/wp-login.php). From here, log in with the username: user and the password: bitnami to get to the WordPress dashboard, configure your settings, import data, install themes, etc., and you are off and running.

wp_login

WordPress Logon

 

 

 

 

 

 

 

 

 

I have a free WordPress account on WordPress.com but since getting my website some time ago I don’t use it as frequently since it lacks the ability of plugins and the flexibility that I need unless I pay a premium. For the cost of a premium account I can have my own so made no sense. I exported all the data from the free WordPress site using their export tool and imported into my website when I started it to save me some time. I used the same exported data, logging into the virtual machine and importing it from within WordPress. This gave me my content to work with and saved me quite a bit of time.

 

RESOURCES

Bitnami Learn More

Bitnami WordPress

Bitnami WordPress Wiki

Bitnami Virtual Applicance Quick Start Guide

How to Export and Import a WordPress Blog

WordPress Tools Export Screen

 

REQUIREMENTS

To install Bitnami WordPress Stack you will need:

  • Intel x86 or compatible processor
  • Minimum of 256 MB RAM
  • Minimum of 150 MB hard drive space
  • Compatible operating systems:
    • x86 or x64 Linux operating system.
    • Windows XP, Vista, 7, Windows 8 or Windows Server 2003 or greater.
    • OS X operating system.
  • VMware Workstation, VMware Player, or VirtualBox

 

Mavericks Virtual Machine

OSX10.9.5Not long ago my interest was peaked in learning OSX so I could become familiar in supporting the OS as well as learn OSX/iOS programming with XCode.

In my earlier years of work experience, back in the mid-90’s, working at Earthlink I had supported various versions of the Macintosh OS but the OS was not as developed as it is now. So I knew I had a learning curve to get over.

Not being super rich like most Apple users who could afford to purchase Mac Pro’s, Mac Mini’s, MacBook’s and the like, I had read quite a bit on building hackintosh systems but never gave it a go. I have a pair of Intel based machines not being used and might try that still.

Last year I stumbled on how to make a Macintosh VM in VMware so pursued the endeavor, eventually creating and using a Mountain Lion VM until I got comfortable enough to try updating to Mavericks once it was out. That epically failed so I knew I had to start out from scratch.

I did some research on the web and came across a couple of tech articles on installing Mavericks but settled on the guide from Sysprobs website since it was very forward to follow. I would need the install files from the Mavericks.app update on my Mountain Lion VM to accomplish creating an install disk so luckily i still had that.

The Sysprobs guide to installing Mavericks will take several hours to complete so make sure you have the time for it. All in all, the end result was a fully functional Mavericks VM that I could play around in and dabble with some programming.

The Mavericks VM will not be display friendly at first, being stuck at a lower resolution, so follow Sysprobs second article on installing a driver to add additional screen resolutions.

I can only attest that the instructions work and I have a functioning OSX Mavericks VM that I can use and learn with. If you follow the instructions you should also. The steps may equally work for Yosemite but I haven’t tried that yet. Soon though.

RESOURCES (credit to Dinesh)

Install OS X 10.9 Mavericks on VMware Workstation with Windows 7 or Windows 8

Increase Screen Resolution with Wide Screen support for Mac OS X Virtual Machine in VMware Player and Workstation

Mac VGA driver for VMware