Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

May fortune be my IM status.

// Tired of having others have cooler status on their IM clients,
// I decided that I shall put an end to that.
// Yet, I am no factory of coolness, but I figured my favorite buddy,
// "fortune" will help me out a little.

// By the way, this tool can definitely be done much better with regard
// to the way it updates the MSN, but hey, I just wanted to play with
// C#. My first time :P

// BTW, the MSN thing works only if you have your MSN not minimized PLUS
// the toolbar showing. (LAME! I know.)

// If you really want to do it right, use http://www.xihsolutions.net/dotmsn/
// and send me the code ;) bhtek@yahoo.com

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Automation;
using System.Runtime.InteropServices;


namespace ZenStatusUpdater
{
    class Program 
    {
        [DllImport("USER32.DLL", EntryPoint = "FindWindowA", CallingConvention = CallingConvention.StdCall)]
        private static extern IntPtr FindWindow(string sClassName, string sWindowName);

        [DllImport("USER32.DLL", EntryPoint = "PostMessageA", CallingConvention = CallingConvention.StdCall)]
        private static extern bool PostMessage(IntPtr hWnd, uint iMsg, long wParam, long lParam); 

        static void exploreElement(AutomationElement sub)
        {
            foreach (AutomationProperty prop in sub.GetSupportedProperties())
            {
                Console.WriteLine("\tProp[" + prop.ProgrammaticName + "]: " + sub.GetCurrentPropertyValue(prop));
            }

            foreach (AutomationPattern pat in sub.GetSupportedPatterns())
            {
                Console.WriteLine("\tPat[" + pat.ProgrammaticName + "]");
            }
        }

        static void explore(AutomationElement el)
        {
            Console.WriteLine("Self...");
            exploreElement(el);


            foreach (AutomationElement sub in el.FindAll(TreeScope.Descendants, Condition.TrueCondition))
            {
                Console.WriteLine("Sub...");
                exploreElement(sub);
            }
        }

        static void Main(string[] args)
        {
            String fortune = null;
            int tries = 0;

            do
            {
                fortune = GetFortune();
                tries++;
            } while (fortune.Length > 130);

            Console.WriteLine("Try #" + tries + ": " + fortune);

            updateMsnStatus(fortune);
            updateYahooStatus(fortune);

            System.Threading.Thread.Sleep(5000);
        }

        protected static void updateYahooStatus(String fortune)
        {
            // Get the current signed in user
            //
            string sUserName = "bhtek";
            Console.WriteLine("The currently logged in user is " + sUserName);

            // Now open the current user's profile and set the current status message, pass true to
            // OpenSubKey to request write access

            RegistryKey keyYahooCustomMessages = Registry.CurrentUser.OpenSubKey("Software\\Yahoo\\Pager\\profiles\\"
            + sUserName + "\\Custom Msgs", true);

            // Set the 5th message, seems like yahoo messenger has the functionality to move the newly set
            // message up as the first one.
            String status = fortune;
            keyYahooCustomMessages.SetValue("5", status);
            byte[] statusBin = (new ASCIIEncoding()).GetBytes(status);
            keyYahooCustomMessages.SetValue("5_bin", (byte[])statusBin); 
            keyYahooCustomMessages.Close();
                
            // We are done setting the value in the registry. We now need to notify y! of this change
            //

            // Find the yahoo messenger window and sent it the notification
            // 0x111: WM_COMMAND
            // 0x188: Code 392

            IntPtr hWndY = FindWindow("YahooBuddyMain", null);
            System.Diagnostics.Debug.WriteLine("Find window got: " + hWndY.ToString());
            PostMessage(hWndY, 0x111, 0x188, 0);
        }

        protected static void updateMsnStatus(String fortune)
        {
            AutomationElementCollection msnWindows = AutomationElement.RootElement.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "MSBLWindowClass"));
            if (msnWindows.Count > 1)
            {
                foreach (AutomationElement potentialMsn in msnWindows)
                {
                    exploreElement(potentialMsn);
                }

                return;
            }

            AutomationElement msn = msnWindows[0];
            msn.SetFocus();

            AutomationElement tools = msn.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AccessKeyProperty, "Alt+T"));
            ExpandCollapsePattern toolsPat = (ExpandCollapsePattern)tools.GetCurrentPattern(ExpandCollapsePattern.Pattern);
            toolsPat.Expand();

            AutomationElement options = tools.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Options..."));
            InvokePattern optionsPat = (InvokePattern)options.GetCurrentPattern(InvokePattern.Pattern);
            optionsPat.Invoke();

            AutomationElement optionsWindow = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Options"));

            AutomationElement personalMessage = optionsWindow.FindFirst(TreeScope.Descendants,
                new AndCondition(
                    new PropertyCondition(AutomationElement.ClassNameProperty, "RichEdit20W"),
                    new PropertyCondition(AutomationElement.NameProperty, "Type a personal message for your contacts to see:")
                    )
            );
            ValuePattern personalMessagePat = (ValuePattern)personalMessage.GetCurrentPattern(ValuePattern.Pattern);
            personalMessagePat.SetValue(fortune);

            AutomationElement ok = optionsWindow.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "OK"));
            InvokePattern okPat = (InvokePattern)ok.GetCurrentPattern(InvokePattern.Pattern);
            okPat.Invoke();
        }

        private static String GetFortune()
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "c:\\cygwin\\bin\\fortune.exe";
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;
            process.Start();
            String fortune = process.StandardOutput.ReadToEnd();

            fortune = System.Text.RegularExpressions.Regex.Replace(fortune, "\\s+", " ");
            return fortune;
        }

       
    }
}

Quick and dirty email server checker, python

// description of your code here
This sends an email from a gmail account with a GUID for the subject to another email account, and then writes this GUID to file. On the other end, the other half of the program checks the GUID in the recieved message and matches it to the GUID in the file to verify that the message has been recieved. I schedule the sender to run every ten minutes, and the reciever/checker to run every minute. The reciever has a threshold value of 20 so if it has checked 20 times and not recieved the email it sends an IM to my gmail account. Whew is that contrived or what.
// First part, email sender, schedule to run every 10 minutes or so
// this uses GUID from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163604

from smtplib import SMTP
from socket import sslerror         #if desired
import Guid
import os

guidSubj = Guid.generate()
guidBod1 = Guid.generate()
guidBod2 = Guid.generate()

if not os.path.exists("sent.txt"):   #check whether the file exists, if not create it
    fileHandle = open('sent.txt','w')
    fileHandle.write (guidSubj)
    fileHandle.close()
    server = SMTP('smtp.gmail.com',587)
    server.set_debuglevel(1) # or 1 for verbosity
    server.ehlo('user@gmail.com')
    server.starttls()
    server.ehlo('user@gmail.com')  # say hello again
    server.login('user@gmail.com', 'password')
    # i have a suspicion that smptlib does not add the required newline dot newline so i do it myself
    server.sendmail('user@gmail.com', 'user@place.com', "Subject:Ping," + guidSubj + '\n\n' + guidBod1 + '\n\n' + guidBod2 + '\n.\n')
    # next line generates the ignorable socket.sslerror
    server.quit()

// Second email checker/reciever, check every minute or so
# This script is a helper to clean POP3 mailboxes
# containing malformed mails that hangs MUA's, that 
# are too large, or whatever...
#
# It iterates over the non-retrieved mails, prints
# selected elements from the headers and prompt the 
# user to delete bogus messages.
#
# Written by Xavier Defrang <xavier.defrang@brutele.be>
# 

# 
import getpass, poplib, re, os, fileinput, sys, xmpp

def sendIM(toAddress=None):
    
    # Google Talk constants
    FROM_GMAIL_ID = "user@gmail.com"
    GMAIL_PASS = "pass"
    GTALK_SERVER = "talk.google.com"
    TO_GMAIL_ID = "user@gmail.com"
    jid=xmpp.protocol.JID(FROM_GMAIL_ID)
    cl=xmpp.Client(jid.getDomain(),debug=[])
    if not cl.connect((GTALK_SERVER,5222)):
        raise IOError('Can not connect to server.')
    if not cl.auth(jid.getNode(),GMAIL_PASS):
        raise IOError('Can not auth with server.')

    cl.send( xmpp.Message( TO_GMAIL_ID ,"Fix your email!" ) )
    cl.disconnect()

# Change this to your needs
POPHOST = "131.0.0.1"
POPUSER = "user"
POPPASS = "pass"

# How many lines of message body to retrieve
MAXLINES = 10

# Headers we're actually interrested in
rx_headers  = re.compile(r"^(Subject)")

try:

    # Connect to the POPer and identify user
    pop = poplib.POP3(POPHOST)
    pop.user(POPUSER)

    if not POPPASS:
        # If no password was supplied, ask for it
        POPPASS = getpass.getpass("Password for %s@%s:" % (POPUSER, POPHOST))

    # Authenticate user
    pop.pass_(POPPASS)

    # Get some general informations (msg_count, box_size)
    stat = pop.stat()

    bye = 0
    count_del = 0
    
    #for n in range(stat[0]):

    msgnum = stat[0]

    # Retrieve headers
    response, lines, bytes = pop.top(msgnum, MAXLINES)

    # Print message info and headers we're interrested in
    test = "".join(filter(rx_headers.match, lines))
    num = test.split(',')
    out = num[1]
    

    #Read the sent.txt file to get the GUID
    fileHandle = open ( 'sent.txt' )
    sentGuid = fileHandle.readline()
    print sentGuid
    fileHandle.close()
    
    if out == sentGuid:
        print "They match!! yay"
        pop.dele(msgnum)
        print "Message %d marked for deletion" % msgnum
        count_del += 1
        #delete the retry.txt and sent.txt file
        os.remove("retry.txt")
        os.remove("sent.txt")
    else:

        #There are no messages yet, so we will increment the retry value
        if not os.path.exists("retry.txt"):
            fileHandle = open ( 'retry.txt','a')
            fileHandle.write('1')
            fileHandle.close()
        else:
        
        fileHandle = open("retry.txt")
        retryValue = fileHandle.readline()
        fileHandle.close()
        #delete the file then recreate with new value
        os.remove('retry.txt')

        if retryValue != '':
            retryValue = int(retryValue) + 1
            out = str(retryValue)
            fileHandle = open ( 'retry.txt','a')
            fileHandle.write(out)
            fileHandle.close()
            if retryValue > 20 and retryValue <25:
                sendIM()

   # Summary
    print "Deleting %d message(s) in mailbox %s@%s" % (count_del, POPUSER, POPHOST)

    # Commit operations and disconnect from server
    print "Closing POP3 session"
    pop.quit()

except poplib.error_proto, detail:

    # Fancy error handling
    print "POP3 Protocol Error:", detail

    #There are no messages yet, so we will increment the retry value
    if not os.path.exists("retry.txt"):
        fileHandle = open ( 'retry.txt','a')
        fileHandle.write('1')
        fileHandle.close()
    else:
        
        fileHandle = open("retry.txt")
        retryValue = fileHandle.readline()
        fileHandle.close()
        #delete the file then recreate with new value
        os.remove('retry.txt')

        if retryValue != '':
            retryValue = int(retryValue) + 1
            out = str(retryValue)
            fileHandle = open ( 'retry.txt','a')
            fileHandle.write(out)
            fileHandle.close()
            if retryValue > 20 and retryValue <25:
                sendIM()

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS