Tag Archives: C#

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);
}
}
}
}

 

Python in C# Using IronPython

16 May
C# calling Python

C# calling Python

I am better at Python than C# and when I couldn’t do something in C#, I would use:

System.Diagnostics.Process.Start(“DoItInPython.py”);

I had seen some posts about IronPython but always ignored them – to my own detriment. IronPython is the solution! You can call Python from C# or C# from Python. That means I can use System.Windows.Forms in my Python code.

Reading a post from MSDN, I put together this example that onClick() of button1 it passes the string from the textbox to a python function that just adds “Hello: ” to it. The python function is in name.py:

def printName(name):
return “Hello: “+name

The C# using IronPython:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
var ipy = Python.CreateRuntime();
dynamic test = ipy.UseFile(@”C:\Documents and Settings\user\Desktop\name.py”);
MessageBox.Show(test.printName(textBox1.Text.ToString()));
}
}
}

You can go the other way too. Read the documentation for IronPython.net for more information than I will give here. Here is a Python script using a Windows Form.

Python calling System.Windows.Forms.MessageBox.Show()

Python calling System.Windows.Forms.MessageBox.Show()

You can see it took me a minute to get it working using my own DLL. Here is how to use a System DLL:

import clr

clr.AddReference(“System.Windows.Forms”)

import System.Windows.Forms as f

f.MessageBox.Show(“Hello From Python!”)

This will popup a MessageBox. Simple, right? I have a DLL on my desktop I wrote. As you can see in my screenshot above, I got it to come in almost the same way – just use AddReferenceToFileAndPath(“C:\desktop\yourname.dll”). Here is the full code to call the method MyName() – yourname is the namespace, Name is the class and myName is a method:

import clr

clr.AddReferenceToFileAndPath(“C:\desktop\yourname.dll”)

import yourname as n

a=n.Name()

a.myName(“Paul”)

Ouputs: ‘Hello:  Paul’

Now I can use Python in C# and Windows DLLs in Python. I’m positive this will come in handy.

Send MMS from ArcGIS Desktop Explorer – or Revit.

2 May
MMS from a button in Desktop Explorer.

MMS from a button in Desktop Explorer.

I had an earlier post on sending an MMS from C#. I have taken it one step further and dropped this code in to ArcGIS Desktop Explorer as a button. click the button and it takes a screenshot, pops up a form and attaches the screenshot. Can send as email or as an MMS. This should work for Revit too since the SDK is C# and all the code is from Microsoft not the GIS API.

 

When launching a form from the buttons in GIS, threading becomes an issue. Note the use of ShowDialog().  Also, in order to caputure the screen without the form in the way, grab it before launching the form. This is how you launch a form from the button in GIS:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Windows.Forms;
using System.Drawing.Imaging;

using ESRI.ArcGISExplorer;
using ESRI.ArcGISExplorer.Application;
using ESRI.ArcGISExplorer.Mapping;
using ESRI.ArcGISExplorer.Geometry;
using ESRI.ArcGISExplorer.Data;
using ESRI.ArcGISExplorer.Threading;

namespace geomms
{
public class Button : ESRI.ArcGISExplorer.Application.Button
{

public override void OnClick()
{
int screenWidth = Screen.GetBounds(new System.Drawing.Point(0, 0)).Width;
int screenHeight = Screen.GetBounds(new System.Drawing.Point(0, 0)).Height;
Bitmap bmpScreenShot = new Bitmap(screenWidth, screenHeight);
Graphics gfx = Graphics.FromImage((Image)bmpScreenShot);
gfx.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight));
bmpScreenShot.Save(“test.jpg”, ImageFormat.Jpeg);

Form1 a = new Form1();
a.ShowDialog();

}
}
}

 

 

Here is the code to send the MMS:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Drawing.Imaging;

namespace geomms
{
public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)
{
try
{
String strFileName = string.Empty;
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient(“embudo.cabq.gov”);
mail.From = new MailAddress(“pcrickard@cabq.gov”);
mail.To.Add(tobox.Text.ToString());
mail.Subject = subjbox.Text.ToString();
mail.Body = msgbox.Text.ToString();
strFileName = “test.jpg”;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(strFileName);
mail.Attachments.Add(attachment);

SmtpServer.Send(mail);
MessageBox.Show(“Sent Message”, “MMS by Paul”);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

 

RabbitMQ, Python and C#

17 Apr
C# consuming a message from python producer via RabbitMQ.

C# consuming a message from python producer via RabbitMQ.

I don’t know much about software patterns. My applications tend to be more of the script variety – though I throw some OOP in for fun. I recently came across RabbitMQ – a message broker. It sits between producers and consumers of messages – it is the queue. I tested out the python hello world example and then got the bright idea to use C# as one piece. The thing about RabbitMQ is that it uses a standard Advanced Messaging Queuing Protocol. This means any language or application that implements that protocol can communicate – think HTTP or FTP protocols.

Here is the python producer taken from the RabbitMQ Tutorial. You will need pika.

import pika
import logging
logging.basicConfig()
connection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’))
channel = connection.channel()

channel.queue_declare(queue=’hello’)

channel.basic_publish(exchange=”,routing_key=’hello’,body=’Hello World!’)
print ” [x] Sent ‘Hello World!'”
connection.close()

 

Simple enough. Now I wrote a C# form that consumes the messages onClick of a button and displays them in a text box – appending the new messages as they come in.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RabbitMQ.Client;

 

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

private void button1_Click(object sender, EventArgs e)
{
var connectionFactory = new ConnectionFactory();
IConnection connection = connectionFactory.CreateConnection();
IModel channel = connection.CreateModel();
channel.QueueDeclare(“hello”, false, false, false, null);
BasicGetResult result = channel.BasicGet(“hello”, true);
if (result != null)
{
string message = Encoding.UTF8.GetString(result.Body);

textBox1.Text += message+”\r\n”;
}

channel.Close();
connection.Close();
}
}
}

 

C# Front-End to Python

12 Apr

I am best at coding in Python, but when it comes adding GUIs, I find myself lacking. My very first C# program was a plugin that had one line of code

System.Diagnostics.Process.Start("http://www.webpage.com");

That led to my second, which just replaced the URL with “python MyApp.py.” It finally clicked. I could just use the drag and drop GUI form builder in C# Visual Studio Express. Connect each python script to a button, pass text box values to the python script using sys.argv and grab the output as a string. The best part is I found a function for this on CodeProject.

So now I can write python scripts for my functionality and use a windows form for the GUI control.

Leaflet.js Map in C#

9 Apr
Leaflet in C# on the Desktop

Leaflet in C# on the Desktop

I have been writing some plugins for ArcGIS Desktop Explorer and thought that for my purposes, Leaflet could do this so much faster and so much lighter.  I could write a webpage to load data from all my sources – Sharepoint, SQL Server, CSV – but I don’t know how to make all the connections and all my SharePoint data is acquired through C# already so why not stick with it? I just needed to figure out how to load Leaflet in a C# Form. I used the WebBrowser Tool.

To figure it out, I went to StackOverflow and Atanas Korchev had the answer. I default open to my base Leaflet map with one point. I added the BounceMarker  plugin because it’s cool.  Lastly, I added a print button.

Here is the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSHTML;
namespace LeafletCsharp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            HtmlElement head = webBrowser1.Document.GetElementsByTagName(“head”)[0];
            HtmlElement scriptEl = webBrowser1.Document.CreateElement(“script”);
            IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
            element.text = “var mymarker; function addPoints() { mymarker = new L.marker([36.104743, -106.629925]); map.addLayer(mymarker); mymarker.bindPopup(‘HELLO <br>Added By C#.’); }”;
            head.AppendChild(scriptEl);
            webBrowser1.Document.InvokeScript(“addPoints”);

           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            HtmlElement head = webBrowser1.Document.GetElementsByTagName(“head”)[0];
            HtmlElement scriptEl = webBrowser1.Document.CreateElement(“script”);
            IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
            element.text = “function removePoints() { map.removeLayer(mymarker); }”;
            head.AppendChild(scriptEl);
            webBrowser1.Document.InvokeScript(“removePoints”);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            webBrowser1.ShowPrintDialog();
        }
    }
}

 

Send MMS From C#

8 Apr
The Best GUI you have ever seen.

The Best GUI you have ever seen.

I have been working on ArcGIS Desktop Explorer writing a few plugins. One of them was to send a text message. Sending text messages just requires an email to be sent to the appropriate gateway. These gateways differ for SMS and MMS. For a list of gateways go to Wikipedia. Here is the code to send an MMS in C#.

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

namespace MMS
{
    public partial class Form1 : Form
    {
        private String strFileName = string.Empty;

        public Form1()
        {
            InitializeComponent();
        }

        private void sendbtn_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(“Your.SMTP.Server”);
                mail.From = new MailAddress(YourEMail@Domain.com);
                mail.To.Add(tobox.Text.ToString());
                mail.Subject = subjbox.Text.ToString();
                mail.Body = msgbox.Text.ToString();

                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment(strFileName);
                mail.Attachments.Add(attachment);

                SmtpServer.Send(mail);
                MessageBox.Show(“Sent Message”,”MMS by Paul”);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        private void attachbtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = “All files (*.*)|*.*”;
            openFileDialog1.InitialDirectory = “C:”; openFileDialog1.Title = “Select an Attachment”;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
                strFileName = openFileDialog1.FileName;
            if (strFileName == String.Empty)
                 return;//user didn’t select a file

         }

     }
}