Archive

Posts Tagged ‘c-sharp’

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

Strip email addresses from HTML or Text with C#.

January 3rd, 2010 Jimmy 3 comments

This code shows you how to extract email addresses out of text and HTML documents. Some day you may need to strip email address from text, for what reason you would want to do this I leave to you, but hopefully not for spam. You can also find phone numbers, web addresses and other patterned parts of text using this code with some simple modifications. Spammers use methods like this for data mining and stripping email addresses off websites. This just goes to show that you should crypt your email address on any websites you use. Using methods such as myName-at-isp.com can help deter data miners.

using System;
using System.Net;
using System.Text.RegularExpressions;

namespace StripEmailAddresses
{
   ///
   /// Description of StripEmail.
   ///
   public class StripEmail
   {
      public StripEmail()
      {
      }

      public string stripEmails(string url)
      {
         //WebClient wc1 = new WebClient();
         //string htmlData = wc1.DownloadString(url);
         string emails="";
         Regex re = new Regex("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b");
         MatchCollection mc = re.Matches("jim@whatever.com\r\nxxx@1234.com\r\n\r\n");
         foreach( Match m in mc)
         {
            emails += m.Value.ToString();
         }

         return emails;

      }
   }
}
Categories: Programming Tags:

Linux GUI Programming with GTK#, Hello World.

December 24th, 2009 Jimmy No comments

Today I was sitting next to a nice warm stove up in Vermont looking at some Linux Application code I’ve developed in the past. I thought, what a good time to make a quick and dirty “Hello World” GTK# tutorial. GTK# is the equivalent in Linux as Visual Studio is to Windows and both use C#(c-sharp) as their programming language. The drag and drop component interface works much like Visual Studio, but there are a few differences which are easy to get used to. GTK# works with containers a lot more than Visual Studio traditionally does, almost forcing to he user into dynamic GUI development. Visual Studio has more of the static method where Forms do not scale depending on the windows size of the application. GTk# does have a “fixed” static container that lets you drag and drop a component anywhere on your form much like Visual Studio. In this mini-tutorial I drag the “fixed” container to my form to let me build my GUI in a free-form-like fashion.

Now that we have dragged a “Fixed” container to our form we can draw a button and entry (textBox) component to our Form. Drag and Drop the component to your Form, then resize the component once it’s dropped on the Form. Read more…

Categories: Programming Tags: , ,

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.

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: , , ,

How to send email attachments in C#.

December 5th, 2009 Jimmy No comments

attachment-icon-128

.NET provides an easy to use programming framework for developing applications. There are built in classes to do just about anything including email. Emailing with attachments isn’t as hard as you might think. You can email from the local host or an SMTP server with the <strong>SmtpClient</strong> class with just a few lines of code.<!–more–>

To send email attachments in C# you’re going to add some extra namespaces to your project, and then implement the code.

First you will need to add the proper namespaces to your code. You’re going to need the <strong>System.Net</strong>,<strong>System.Net.Mail</strong>, and <strong>System.Net.Mime</strong> namespaces to send attachments using C#. Check out the rest of the code below for a simple example. Keep in mind that this is "short" code and will not compile as is, however this was taken from an application tool I developed.

SmtpClient client = new SmtpClient("mail.smtp.com"); 

MailAddress from = new MailAddress((string) emailAddress); 

MailAddress to = new MailAddress((string) emailAddress);

MailMessage message = new MailMessage(from, to); 

message.Subject = (string) Subject; message.SubjectEncoding = System.Text.Encoding.UTF8; 

Attachment data= new Attachment((string) fileName, MediaTypeNames.Application.Octet); message.Attachments.Add(data); 

message.Body = (string) emailBody; message.BodyEncoding =  System.Text.Encoding.UTF8; 

Using proxy servers in your C# applications.

December 5th, 2009 Jimmy No comments

This code snippet will show you how to use a proxy server in conjunction with the WebClient class. I’m pretty sure the WebClient class automatically uses your IE configuration (correct me if I’m wrong). This is helpful for those that are developing C# in Linux, but are behind an annoying corporate proxy server.

private string downloadURL( string url )
		{
			WebProxy p = null;
			ICredentials cred;
			cred = new NetworkCredential(&quot;myUserName&quot;, &quot;myPasword&quot;);
			p = new WebProxy(&quot;inet1.someproxy.com:80&quot;, true, null, cred);
			WebRequest.DefaultWebProxy = p;

			WebClient wc = new WebClient();
			wc.Proxy = p;
			string data = wc.DownloadString(url);

			return data;
		}

The underlying connection was closed.

August 22nd, 2009 Jimmy No comments

There seems to be a big problem with the underlying code behind the sockets classes that Microsoft uses in their .NET framework. Many people are getting a “The underlying connection was closed.” error message, but there doesn’t seem to be an consistency to it.
Read more…

Categories: Programming Tags: