Archive | June, 2013

Git: My First Foray

17 Jun

I have recently created a GitHub account and started trying to use version control in my coding – I usually manually make a copy and try new things or overwrite existing code, break it and have to start over. This post will show how to branch a code base using Git. Let me note, Git and GitHub are NOT the same. GitHub is a collaborative online repository and you can push and pull code to and from GitHub with Git.

First, download and install Git.

Create a directory on your machine.

Open a command prompt and change to that directory.

type ‘git init’ to initialize the repository. I added a file code myCode.txt in the directory.

Add all the files by typing ‘git add .’

Then commit them: ‘git commit -m “Some comments”‘

Now you are ready to branch the code!

To see there is only a master branch type ‘git branch’

To add a branch type ‘git branch Branch1’

Change the code and add new files.

Add them ‘git add .’

Then commit: ‘git commit -m “1st Commit of new branch”‘

To see that the master is intact “git checkout master”

open the directory and you should see the original file.

My Master

My Master

My Branch

My Branch

Interfaces in C#

13 Jun

I write code, but mostly single file “scripts.” I am familiar with Object Oriented Programming but rarely implement it – my programs are fairly simple tasks. In an attempt to expand my horizons and build more complex programs, I have attempted to learn some of the concepts of OOP that have confused me.

An interface seems like a simple thing – something that sits between two things and allows one to access the other. The gas pedal of your car is the interface to the cars engine. In programming, I understand an interface to be a contract that defines what a class must do. It can do more, and implement a number of interfaces, but must contain all the methods of each interface. I guess this allows you to replace classes and know that anything you put in will still have certain behaviors (methods). For my purposes, it is a good way to make sure that I define all the functionality I am supposed to – a kind of debugging check on my classes. I can define what a class should do in an interface and my debugger will hold me to it.

Here is a simple interface in C# (I like the idea of naming it a thing and the class a specific type of thing. One example I saw on a Java page named the interface bicycle and the class that implemented it SchwinnBicycle.)

interface Thing
{
void doSomething();
void doSomethingElse();

}

My class implementing the interface:

class SpecificThing : Thing
{
static void Main(string[] args)
{
SpecificThing it = new SpecificThing();
it.doSomething();
it.doSomethingElse();

}
public void doSomething()
{
Console.WriteLine(“I implement the Interface”);
}
public void doSomethingElse()
{
Console.WriteLine(“I implement the Interface too”);
}

}

If I do not implement the interface, I get an error in my debugger and cannot build.

I say it implements the interface but fail to include the methods.

I say it implements the interface but fail to include the methods.

When I add the methods doSomething() and doSomethingElse()

Add the methods and everything runs smoothly.

Add the methods and everything runs smoothly.

An interface defines the behavior of your class. It does NOT define how you must implement that behavior. A function doSomething() can do anything you want it to, but you must include it.

Embed Files in to a C# Executable

10 Jun

I needed to run some regedits on several computers and grab the IP Addresses. I was given all the scripts to run and had 2 options: include all the regedits in my C# code or execute the BAT that runs them all. I chose option 2 because I did not write them and wanted to keep them separate from my code. Also, I could not have users downloading multiple files or unzipping anything. So I chose to embed the files in an EXE, extract them when it runs, execute the BAT, email the IP, and delete them when done. I found the pieces of this code on StackOverflow.

To embed a file, you need to add it to your project in Visual Studio then under properties choose “embedded resource”.

Here is the full code. After you can find the code stripped to the bare minimum:

using System;
using System.Collections;
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;
using System.Net.Mail;
using System.Diagnostics;
using System.Reflection;
using System.IO;

namespace TSUnet
{
public partial class Form1 : Form
{
Assembly _assembly;
Stream _move;
Stream _move1;
Stream _move2;
Stream _move3;
Stream _move4;
Stream _cmd;
string os;
string printos;
public Form1()
{
InitializeComponent();
if (System.IO.File.Exists(“Quest_Move.reg”))
{

try
{
System.IO.File.Delete(“Quest_Move.reg”);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
return;
}
}
if (System.IO.File.Exists(“Quest_Move_1.reg”))
{

try
{
System.IO.File.Delete(“Quest_Move_1.reg”);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
return;
}
}
if (System.IO.File.Exists(“Quest_Move_2.reg”))
{

try
{
System.IO.File.Delete(“Quest_Move_2.reg”);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
return;
}
}
if (System.IO.File.Exists(“Quest_Move_3.reg”))
{

try
{
System.IO.File.Delete(“Quest_Move_3.reg”);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
return;
}
}
if (System.IO.File.Exists(“Quest_Move_4.reg”))
{

try
{
System.IO.File.Delete(“Quest_Move_4.reg”);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
return;
}
}
if (System.IO.File.Exists(“QuestMove.cmd”))
{

try
{
System.IO.File.Delete(“QuestMove.cmd”);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
return;
}
}
}

private void button1_Click(object sender, EventArgs e)
{
string name = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(name);
IPAddress[] addr = ipEntry.AddressList;

try
{
_assembly = Assembly.GetExecutingAssembly();
_move = _assembly.GetManifestResourceStream(“TSUnet.Quest_Move.reg”);
_move1 = _assembly.GetManifestResourceStream(“TSUnet.Quest_Move_1.reg”);
_move2 = _assembly.GetManifestResourceStream(“TSUnet.Quest_Move_2.reg”);
_move3 = _assembly.GetManifestResourceStream(“TSUnet.Quest_Move_3.reg”);
_move4 = _assembly.GetManifestResourceStream(“TSUnet.Quest_Move_4.reg”);
_cmd = _assembly.GetManifestResourceStream(“TSUnet.QuestMove.cmd”);

using (Stream file = File.OpenWrite(“Quest_Move.reg”))
{
CopyStream(_move, file);
}
using (Stream file = File.OpenWrite(“Quest_Move_1.reg”))
{
CopyStream(_move1, file);
}
using (Stream file = File.OpenWrite(“Quest_Move_2.reg”))
{
CopyStream(_move2, file);
}
using (Stream file = File.OpenWrite(“Quest_Move_3.reg”))
{
CopyStream(_move3, file);
}
using (Stream file = File.OpenWrite(“Quest_Move_4.reg”))
{
CopyStream(_move4, file);
}
using (Stream file = File.OpenWrite(“QuestMove.cmd”))
{
CopyStream(_cmd, file);
}

os = Environment.OSVersion.ToString();
if (os.Contains(“5.”))
{
printos = addr[addr.Length – 1].ToString();
}
else
{
printos = addr[3].ToString();
}

 

SmtpClient smtpserver = new SmtpClient(“Something.Something.Com”);
MailMessage mail = new MailMessage();
mail.From = new MailAddress(textBox1.Text.ToString());
mail.To.Add(“Me@Something.Com”);
mail.Subject = “From: ” + textBox1.Text.ToString() + ” Machine: ” + Environment.MachineName.ToString();
mail.Body = textBox1.Text.ToString() + “\r\n” + printos + “\r\n” + Environment.MachineName;

smtpserver.Send(mail);
Process.Start(“QuestMove.cmd”);
}

 
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), “Error”);
}
MessageBox.Show(“Please save your data, Log Off your machine and Call….”, “Done”);
if (System.IO.File.Exists(“Quest_Move.reg”))
{

try
{
System.IO.File.Delete(“Quest_Move.reg”);
}
catch (System.IO.IOException er)
{
Console.WriteLine(er.Message);
return;
}
}
if (System.IO.File.Exists(“Quest_Move_1.reg”))
{

try
{
System.IO.File.Delete(“Quest_Move_1.reg”);
}
catch (System.IO.IOException er)
{
Console.WriteLine(er.Message);
return;
}
}
if (System.IO.File.Exists(“Quest_Move_2.reg”))
{

try
{
System.IO.File.Delete(“Quest_Move_2.reg”);
}
catch (System.IO.IOException er)
{
Console.WriteLine(er.Message);
return;
}
}
if (System.IO.File.Exists(“Quest_Move_3.reg”))
{

try
{
System.IO.File.Delete(“Quest_Move_3.reg”);
}
catch (System.IO.IOException er)
{
Console.WriteLine(er.Message);
return;
}
}
if (System.IO.File.Exists(“Quest_Move_4.reg”))
{

try
{
System.IO.File.Delete(“Quest_Move_4.reg”);
}
catch (System.IO.IOException er)
{
Console.WriteLine(er.Message);
return;
}
}
if (System.IO.File.Exists(“QuestMove.cmd”))
{

try
{
System.IO.File.Delete(“QuestMove.cmd”);
}
catch (System.IO.IOException er)
{
Console.WriteLine(er.Message);
return;
}
}

}
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
}
}

 

And a very minimal version – a single embed without emailing or getting the IP:

namespace TSUnet

{
public partial class Form1 : Form
{
Assembly _assembly;
Stream _move;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
try
{
_assembly = Assembly.GetExecutingAssembly();
_move = _assembly.GetManifestResourceStream(“TSUnet.Quest_Move.reg”);

using (Stream file = File.OpenWrite(“Quest_Move.reg”))
{
CopyStream(_move, file);
}

}

catch (Exception ex)
{
MessageBox.Show(ex.ToString(), “Error”);
}}

public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
}
}

 

ESRI REST API: GeoCoding OR OpenStreet Map

10 Jun

UPDATE: OpenStreet Map code at bottom.

 

Saw a Tweet saying that the ArcGIS REST API for Geocoding is moving to a new URL. I use Google when I just needed a single Lat,Long and ArcPy to Geocode CSV’s, but I decided to check out the REST API and throw together a Python script from my old Google one – which I got from Foundations of Python Network Programming.

Not much to the script – pass parameters to a URL and grab the JSON. You can go to the HELP for more info about the parameters – like setting outfields=*;

Here is the script (it grabs the first result):

import urllib, urllib2, simplejson
import csv

param = {‘Address’: ‘400 Roma SE’,’City’:’albuquerque’,’Region’:’nm’,’Postal’:’87102′,’outFields’:’location’,’f’:’pjson’}
url = ‘http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?’ + urllib.urlencode(param)
rawreply = urllib2.urlopen(url).read()
reply = simplejson.loads(rawreply)

print “Long: ”
print reply[“candidates”][0][“location”][“x”]

print “Lat: ”
print reply[“candidates”][0][“location”][“y”]

 

OpenStreet Map is almost the same, just change the URL and the parameters.

import urllib, urllib2, simplejson
import csv

param = {‘q’: ‘400 roma, albuquerque’,’format’:’json’,’addressdetails’:’1′}
url = ‘http://nominatim.openstreetmap.org/search?’ + urllib.urlencode(param)
rawreply = urllib2.urlopen(url).read()
reply = simplejson.loads(rawreply)

print reply[0][“lat”]
print reply[0][“lon”]