Archive

Posts Tagged ‘C#’

Making a simple ListBox with GTK and Glade3.

March 2nd, 2010 Jimmy No comments

Adding a simple ListBox widget in your GTK application is easier than you think. This tutorial will show you how to create ListBox-like functionality in GTK using Glade3. GTK uses the TreeView control as their do-all list control. You can create simple lists, tree-like lists and all sorts of various list views. What is really cool about the TreeView widget is that your columns can be almost any other widget type. You can put a Button in one column, and an entry widget in another, or even a progress bar! This example is only going to cover a basic 1 column listbox using the TreeView widget.

Requirements & Notes:
1. This tutorial expects that you have a little experience creating basic GUI’s in glade3. If not, please read a Glade3 tutorial.

2. I use Anjuta as my IDE.

3. The code in here is for reference. It is not necessarily a copy/paste working example, however, it does come from a working test project of mine….

4. This code only shows you how to populate a listbox (TreeView). The next one I write will be how to get a selected value and how to use signals (events).

Lets get started.
1. Open up your Glade3 User Interface. You should already have an interface with a TreeView object called “treeview1″.

2. Right click on your TreeView object from the left window pane and click “Edit Separately” and goto the “Hierarchy” tab.

3. Create a new Tree View column. Call it whatever you want.

4. Create a new Cell Renderer and call it anything.

Note the numbers on the picture below. :-)

This is pretty much it for the gui stuff. Save your gui and open up your GTK code. (callback.h, main.cpp etc etc) Here is my callback.h file. The GtkTreeModel is what stores your actual data. The other stuff is just some other junk I was playing with.

#include <gtk/gtk.h>
GtkEntry *myEntry;
GtkTextView *myTextView;
GtkTextIter iter;
GtkTreeModel *myStore;

void destroy (GtkWidget *widget, gpointer data);

Now for my main.cpp file. Here is some example source code of how I populate my TreeView control. This code is a little messy but it should give you a good idea of how it works.

GtkWidget* create_window (void)
{
	GtkWidget *window;
	GtkBuilder *builder;
	GError* error = NULL;
    GtkTreeIter iter;
	GtkTreeView *view;
   enum
  {
   COL_NAME = 0
  };	

	builder = gtk_builder_new ();
	if (!gtk_builder_add_from_file (builder, UI_FILE, &error))
	{
		g_warning ("Couldn't load builder file: %s", error->message);
		g_error_free (error);
	}

	/* This is important */
	gtk_builder_connect_signals (builder, NULL);
	window = GTK_WIDGET (gtk_builder_get_object (builder, "window"));
            myEntry = GTK_ENTRY (gtk_builder_get_object (builder, "entry1"));
	myTextView = GTK_TEXT_VIEW (gtk_builder_get_object (builder, "textview1"));

Here I define myStore so that I can use it. I am defining 1 column which will hold data of a G_TYPE_STRING type. I then get a reference to my treeview1 (called view in this case) which is eventually used with the gtk_tree_view_set_model function. The gtk_list_store_append function is what creates the new row and gtk_list_store_set is what actually sets my value. In this case I just use two static char variables (*t1 and *t2) and pass those in. The we use gtk_tree_view_set_model to set the model (store) in our TreeView object (view).

	myStore = gtk_list_store_new (1, G_TYPE_STRING);
             view = GTK_TREE_VIEW(gtk_builder_get_object(builder,"treeview1"));
	gchar *t1 = "text1";
	gchar *t2 = "text2";
             gtk_list_store_append (myStore, &iter);
	gtk_list_store_set(myStore,&iter,0,t1,-1);

	gtk_list_store_append (myStore, &iter);
	gtk_list_store_set(myStore,&iter,0,t2,-1);

   gtk_tree_view_set_model (GTK_TREE_VIEW (view), myStore);

  //gtk_list_store_set (store, &iter,    COL_NAME, "Heinz El-Mann", COL_AGE, 51, -1);
	gtk_entry_set_text (myEntry, t2);

	g_object_unref (builder);

	return window;
}

int main (int argc, char *argv[])
{
 	GtkWidget *window;

	gtk_set_locale ();
	gtk_init (&argc, &argv);

	window = create_window ();

	gtk_widget_show (window);

	gtk_main ();
	return 0;
}

You should eventually be able to get a Listbox like widget showing “text1″ and “text2″ in 2 different columns.

Categories: Programming Tags: , ,

Add background color to PNG files in C#.

January 15th, 2010 Jimmy No comments

This code snippet will let you force a background color into a PNG file with C#. When working with PNG files in Visual Studio sometimes you’ll run into situations where the background of a PNG shows up as grey or even blue. This is because of the PNG files transparency and Windows can sometimes get confused as what to do for background color, especially when pasting a PNG file into a Wordpad document.

To use the code all you have to do is pass an Image object that you have created either from a file or a pictureBox control. Pass the height, width and the Color you want for the background color and the function will fill on the fly. This function has no return type because it’s modifying the image with the Graphics class which modify’s the image in memory as is. If you pass the Image from a pictureBox control you won’t have to pass the Image object back to the pictureBox control to have it update, it will be updated using the referenced Image object.

    private void addBgToPng(Image img,int xWidth, int xHeight,Color color)
        {
            Image imgOrig = (Image)img.Clone();
            Graphics g = Graphics.FromImage(img);
            Rectangle bgImg = new Rectangle(0, 0, xWidth, xHeight);
            SolidBrush bgBrush = new SolidBrush(color);
            g.FillRectangle(bgBrush, bgImg);
            g.DrawImage(imgOrig, new Point(0, 0));
            bgBrush.Dispose();
         }

C#: A multi-threaded UDP server with BackgroundWorker.

January 12th, 2010 Jimmy No comments

The following code shows you how to build a UDP server in C# using the UUdpClient class for the networking and BackgroundWorker class for reporting data back to the application. This particular UDP server class is designed to be used with a Windows Forms or GUI. When using the UDP server you pass a BackgroundWorker class to the constructor. You should also make sure reporting is enable on that BackgroundWorker class so that they UDP server can report data and error back to your ReportProgress even.

/*
 * Created by Jimmy Burnett (jimmyburnett.com)
 * User: Jim
 * Date: 1/1/2010
 * Time: 9:19 AM
 */
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace JimmyBurnett
{
	public class udpListener
	{
		private System.ComponentModel.BackgroundWorker workerUDP;
		private int port=5121;
		public udpListener(System.ComponentModel.BackgroundWorker workerUDP,int port)
		{
			this.workerUDP = workerUDP;
		}

		/// <summary>
		/// Start the listener.
		/// </summary>
		public void udpListenerStart()
		{
		  try{
			this.workerUDP.ReportProgress(30,"UDP Server Starting...");
			byte[] data = new byte[1024];
			//IPAddress addy = IPAddress.Parse("192.168.1.1");
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, this.port);
            UdpClient newsock = new UdpClient(ipep);
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            data = newsock.Receive(ref sender);
				//send a status back to our background worker class.
	        this.workerUDP.ReportProgress(30,"UDP Server Listening...");

			while(true)
            {
             this.workerUDP.ReportProgress(30,"Received Data..");
             this.workerUDP.ReportProgress(50,data.Length);
              data = newsock.Receive(ref sender);
         	}       

         	}catch(Exception ee){
				this.workerUDP.ReportProgress(666,ee.Message);
				Console.WriteLine(ee.Message) ;
     	 	}
	  }
    }
}

Check for a Windows service in C#.

January 10th, 2010 Jimmy No comments


This code will check through a list of installed Windows Services for a specific service name in C# (returns boolean). The function allows you to pass a service name as a string and the function will check the Windows Service list for that name. It will also look for partial service names in case you don’t know the exact name of the service.

     public bool IsBonjourInstalled(string sname)
        {
            ServiceController[] services_array = ServiceController.GetServices();
            foreach (ServiceController service in services_array)
            {
                if (service.ServiceName.Contains(sname))
                    return true;
            }
            return false;
        }

Convert C# code to Visual Basic,Python and Back.

December 11th, 2009 Jimmy No comments

Some of you .NET programmers may some day find some sample code written in Visual Basic, or C#, but need it in another .NET language. SharpDevelop, a free .NET IDE, has a tool built in that will convert C# into Visual Basic and Python, or Visual Basic into C#, Python and any variation. This video shows you how to do the conversion and it also shows you what it looks like.  When you convert code new source files are created and old source files are retained. This lets you import your newly created source files right into your application.

RSS.NET – Read RSS feeds in .NET.

December 11th, 2009 Jimmy No comments

“RSS is a format for syndicating news and the content of news-like sites, including major news sites like Wired, news-oriented community sites like Slashdot, and personal weblogs. But it’s not just for news. Pretty much anything that can be broken down into discrete items can be syndicated via RSS: the “recent changes” page of a wiki, a changelog of CVS checkins, even the revision history of a book. Once information about each item is in RSS format, an RSS-aware program can check the feed for changes and react to the changes in an appropriate way.” – Mark Pilgrim

RSS.NET is an open-source .NET class library for RSS feeds. It provides a reusable object model for parsing and writing RSS feeds. It is fully compatible with RSS versions 0.90, 0.91, 0.92, and 2.0.1, implementing all constructs.

RSS is free to use in both commercial and non-commercial use. This is a library and is not a tool for end users to use. This has been tested under Visual Studio 2008 and SharpDevelop 3.0.

Categories: General Tags: ,

Rapid Application Development Library 2.9.0

December 10th, 2009 Jimmy No comments

Radlib is a C language library developed to abstract details of interprocess communications and common Linux/Unix system facilities so that application developers can concentrate on application solutions. It encourages developers to use a proven paradigm of event-driven, asynchronous design. By abstracting interprocess messaging, events, timers, and any I/O device that can be represented as a file descriptor, radlib simplifies the implementation of multi-purpose processes, as well as multi-process applications. In short, radlib is a sincere attempt to provide real-time OS capability on a non-real-time OS.

 

2.9.0 Changes: Build files were updated to support Debian package creation.

Homepage

API Reference

Categories: General Tags: ,

Simple Sockets

December 10th, 2009 Jimmy No comments

Simple Sockets is a cross platform socket library. It is different from other socket libraries which mix the application protocol and transport protocol layer (i.e. TCP sockets, UDP sockets, HTTP sockets, etc). This library focuses specifically on the transport protocols. Its features include blocking/non-blocking sockets, polling, thread safety, and signal safety.

This example creates a socket to a time server and receives the time.

#include <string.h>

#include "ActiveSocket.h"       // Include header for active socket object definition

 

int main(int argc, char **argv)

{

    CActiveSocket socket;       // Instantiate active socket object (defaults to TCP).

    char          time[50];

 

    memset(&time, 0, 50);

 

    //--------------------------------------------------------------------------

    // Initialize our socket object 

    //--------------------------------------------------------------------------

    socket.Initialize();

 

    //--------------------------------------------------------------------------

    // Create a connection to the time server so that data can be sent

    // and received.

    //--------------------------------------------------------------------------

    if (socket.Open((const uint8 *)"time-C.timefreq.bldrdoc.gov", 13))

    {

        //----------------------------------------------------------------------

        // Send a requtest the server requesting the current time.

        //----------------------------------------------------------------------

        if (socket.Send((const uint8 *)"\n", 1))

        {

            //------------------------------------------------------------------

            // Receive response from the server.

            //------------------------------------------------------------------

            socket.Receive(49);

            memcpy(&time, socket.GetData(), 49);

            printf("%s\n", time);

 

            //------------------------------------------------------------------

            // Close the connection.

            //------------------------------------------------------------------

            socket.Close();

        }

    }

 

 

    return 1;

}

 

Remember the endians!

December 7th, 2009 Jimmy No comments

For those of you that deal with bytes on a protocol level, I’ve discovered an easy solution for dealing with those endian issues. Some of you may know that when dumping data directly from memory as byte[] arrays will give you different results depending on the source’s computer architecture. As an example, a Motorola ColdFire board (LittleEndian) will dump the data differently than say an i386 (BigEndian) based processor. In a nutshell, this means that the byte[] arrays from the ColdFire board will be in reverse order than that of an i386 based microcontroller byte[] array. Obviously when processing this data you’ll run into huge problems if you don’t convert your byte[] arrays!

The simplest way to do this is to use the BitConverter class library in .NET as shown below (Correct me if I’m wrong!). The BitConverter class allows you to check for LittleEndians to allow you to reverse the byte[]array which will then be a BigEndian. This example is returning a 32bit integer from a byte[] array at a given index in the byte[] array. Remember, parsing data such as UDP network packets is normally done using byte[] arrays.

     private static Int32 ToInt32(byte[] value, int startIndex)
        {
            byte[] data = new byte[4];
            Array.Copy(value, startIndex, data, 0, 4);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(data);
            return BitConverter.ToInt32(data, 0);
        }

Categories: Programming Tags: , ,

Implement an RSS reader into your .NET program.

December 6th, 2009 Jimmy No comments

If you’re looking for RSS support in your .NET application head over to RSSdotnet.com and download the latest RSS.NET library. They provide all the source code and API documents you need to add RSS into your program. I haven’t thoroughly reviewed the code but it does work pretty code and seems stable. I’m currently using it in a blog tool I am about to release but more on that later lets see some RSS.NET code!

Below is a very simple implementation on how you can use RSS.NET. Don’t forget to add the project to your solution and add a reference to that project! This should parse out my RSS feed and pause for each item.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rss;
namespace ConsoleRssTest
{
    class Program
    {
        static void Main(string[] args)
        {
            RssFeed feed = RssFeed.Read("http://feeds.feedburner.com/uniprogrammer");
            RssChannel channel = (RssChannel)feed.Channels[0];
            foreach (RssItem Ri in channel.Items)
            {
                Console.WriteLine(Ri.Title);
                Console.WriteLine(Ri.Link.AbsoluteUri);
                Console.WriteLine(Ri.Description);

                //This will let you read each feed as they come in....
                Console.WriteLine("Press any key too continue...");
                Console.ReadLine();

            }

        }
    }
}

Categories: Programming Tags: , , ,