Showing post in category: Random hacks

26 Feb 2007

Gtk.TreeView right click part 2

Posted by Jacob Emcken Comments (0)

While on my winter vacation I played around with the Gtk.TreeView and the right click challanges. I found a way to extract the row which is clicked on and the data within. The following example shows how (it builds upon my last Gtk.TreeView right click example:

public class TreeViewExample {
    public static void Main ()
    {
        Gtk.Application.Init ();
        new TreeViewExample ();
        Gtk.Application.Run ();
    }

    public TreeViewExample ()
    {
        Gtk.Window window = new Gtk.Window ("TreeView Example");
        window.SetSizeRequest (500,200);

        MusicTreeView tree = new MusicTreeView ();
        window.Add (tree);
        window.ShowAll ();
    }
}

// Creating a new class MusicTreeView which is derived from the TreeView class
public class MusicTreeView : Gtk.TreeView {

        private Gtk.ListStore musicListStore;

        public MusicTreeView ()
        {
                musicListStore = new Gtk.ListStore (typeof (string), typeof (string));

                this.AppendColumn ("Artist", new Gtk.CellRendererText (), "text", 0);
                this.AppendColumn ("Title", new Gtk.CellRendererText (), "text", 1);

                musicListStore.AppendValues ("Garbage", "Dog New Tricks");
                musicListStore.AppendValues ("The Chemical Brothers", "Galvanize");
                this.Model = musicListStore;
        }

        // The TreeView has a build in function which is called upon a OnButtonPressEvent
        // We override the function to capture right clicks with the mouse
        protected override bool OnButtonPressEvent (Gdk.EventButton evnt)
        {
                if(evnt.Button == 3) {
                        Gtk.TreePath path = new Gtk.TreePath();
                        // Get TreePath from the xy-coordinates of the mouse from the event
                        // GetPathAtPos is a function from the TreeView class
                        GetPathAtPos (System.Convert.ToInt16 (evnt.X), System.Convert.ToInt16 (evnt.Y), out path);
                        Gtk.TreeIter iter;
                        // Get iter from the path
                        if (this.musicListStore.GetIter (out iter, path)) {
                                // Get artist and title from the iter
                                string artist = (string) this.musicListStore.GetValue (iter, 0);
                                string title = (string) this.musicListStore.GetValue (iter, 1);
                                System.Console.WriteLine ("Artist: " + artist + ", Title: " + title);
                        }
                        return true;
                }
                // Now if we would ever get this far
                // we run the TreeViews OnButtonPressEvent function
                // to make sure everything else works as normal
                return base.OnButtonPressEvent(evnt);
        }
}

Notes I found in Monodoc:

  • TreePath represents a particular node of a TreeView
  • The TreeIter is the primary structure for accessing a tree row.

Whatever that means :)

15 Feb 2007

XSLT: Search replace attribute values

Posted by Jacob Emcken Comments (3)

Yesterday I needed an xsl transformation which could replace a specific attribute value in a xml file and keep the rest intact. The following code is put together by pieces I found around the net (copy-paste FTW :) ):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:param name="attribute"/>
    <xsl:param name="oldvalue"/>
    <xsl:param name="newvalue"/>

    <xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
    </xsl:template>

    <!-- This is a generic search replace of attribute values --> 
    <xsl:template match="@*" priority="10">
        <xsl:attribute name="{name()}">
            <xsl:choose>
                <xsl:when test="(name()=$attribute) and (. = $oldvalue)"><xsl:value-of select="$newvalue"/></xsl:when>
                <xsl:otherwise><xsl:value-of select="."/></xsl:otherwise>
            </xsl:choose>
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

Lets say that the above code is saved in a file called attribute_replace.xslt. Now with xsltproc you would be able to replace the vaule 5011 with 5015 in all attributes called port:

xsltproc --stringparam attribute port --stringparam oldvalue 5011 --stringparam newvalue 5015 attribute_replace.xslt server_config.xml > new_server_config.xml

I used this to manupulate with some JBoss configuration files.

08 Feb 2007

Heartbeat starting my resources twice… why?

Posted by Jacob Emcken Comments (0)

While working on implementing failover for a JBoss application in heartbeat I had it sometimes fail miserably. After examining the logs files for a while I noticed that it tried to start my service twice.. why?

This was due to multiple errors from my side:

  1. I hadn’t implemented the status call for my heartbeat resource script
  2. My script didn’t return true when asked to start and it was already started.

According to LSB standard your start / stop scripts should return true even though your service is already started.

Note to self: Learn to read the documentation and not just assume you know how it works (especially not with failover clusters… they are meant to have uptime you know.

Good readings about heartbeat and the resouces scripts.

25 Jan 2007

Mono coding: Capturing right clicks in a Gtk.TreeView

Posted by Jacob Emcken Comments (0)

I had a hard time figuring out how to capture a right click on a TreeView, which I needed to be able to make a context menu or popup menu or what ever you wanna call it. The way I expected it would work didn’t… I think it have something to do with a change in Mono some time ago (Why don’t I get ButtonPressEvents from my Button/Treeview?).

This example is based on the “Shortcuts – Writing Less Code” example from the www.mono-project.com website. The main difference is that the TreeView is no longer setup in the main class but is now a separate class with the function OnButtonPressEvent overwritten.

public class TreeViewExample {
    public static void Main ()
    {
        Gtk.Application.Init ();
        new TreeViewExample ();
        Gtk.Application.Run ();
    }

    public TreeViewExample ()
    {
        Gtk.Window window = new Gtk.Window ("TreeView Example");
        window.SetSizeRequest (500,200);

        MusicTreeView tree = new MusicTreeView ();
        window.Add (tree);
        window.ShowAll ();
    }
}

// Creating a new class MusicTreeView which is derived from the TreeView class
public class MusicTreeView : Gtk.TreeView {

        public MusicTreeView ()
        {
                Gtk.ListStore musicListStore = new Gtk.ListStore (typeof (string), typeof (string));

                this.AppendColumn ("Artist", new Gtk.CellRendererText (), "text", 0);
                this.AppendColumn ("Title", new Gtk.CellRendererText (), "text", 1);

                musicListStore.AppendValues ("Garbage", "Dog New Tricks");
                this.Model = musicListStore;
        }

        // The TreeView has a build in function which is called upon a OnButtonPressEvent
        // We override the function to capture right clicks with the mouse
        protected override bool OnButtonPressEvent (Gdk.EventButton evnt)
        {
                if(evnt.Button == 3) {
                        System.Console.WriteLine ("Right click");
                        return true;
                }
                // Now if we would ever get this far
                // we run the TreeViews OnButtonPressEvent function
                // to make sure everything else works as normal
                return base.OnButtonPressEvent(evnt);
        }
}

Update: I wrote a new “right click in Gtk.TreeView” example.

24 Jan 2007

Searching packages on RHEL CD’s

Posted by Jacob Emcken Comments (0)

Sometimes you have to get primitive … duh.

Today I got really annoyed about the “Package Management” tool on Red Hat EL 4 update 4. When I tried to install the “Development tools” I just got an error that krb5-libs could not be found which was a dependencie of krb5-workstation (1.3.4, 33). Both krb5-libs and krb5-workstation was installed…?!? I’m not Red Hat expert… and that is probably my biggest problem here :)

Back to the commandline… it always works. I had to search the CD’es (afterwards I found that all the packages I needed was on CD3). I made a little search script… dont think anyone can use it… just thought it was fun:

for i in 1 2 3 4 5
do
    mount -o loop /root/RHEL4-U4-i386-ES-disc$i.iso  /mnt/
    echo "Results on cd $i"
    find /mnt/RedHat/RPMS/ -iname $1\*
    umount /mnt/
done

02 Nov 2006

Solution to vmnet1 down after suspend

Posted by Jacob Emcken Comments (2)

I rarely shut down my laptop, but I use suspend all the time. Right now I have like 14 days of “uptime” which would have been a lot more if it wasn’t because I just installed Edgy :) I have VMware Server installed on it which I use for my work. I have all the machines on a host only network which works just great. But every time I suspend my laptop the virtually device vmnet1 seems to “go down” and I have to make a:

sudo ip link set vmnet1 up

to be able to connect from my laptop to the VMware machines again.

Now I created a file at the following location:

/etc/acpi/resume.d/89-enable-vmware-host-only-net.sh

With the following content:

#!/bin/sh

ip link set vmnet1 up

Now I don’t have do it manually any more, horay :-D

02 Nov 2006

Using PHP to connect to an Active Directory

Posted by Jacob Emcken Comments (4)

I am looking into authenticating users on Solaris 9 via Active Directory (AD) as an LDAP server. To chop the problem into smaller problems I started to try and connect to the LDAP interface of the AD from a platform which I know. I’m no Solaris expert :)

So I installed Ubuntu edgy (server install from alternative CD) and a evaluation Windows 2003 R2 server in the free VMware Server product. Then I install an Active Directory (and a DNS server) on the Windows Server. The I tried to connect to the AD with PHP scripts to test how it worked. I found a good article on www.developer.com about PHP LDAP connections to AD. I also found an article about various handy LDAP search filters for Active Directory.

First create a normal Windows user in the AD which you use to connect to the AD with. You don’t need to add this user to any special groups to allow it to connect to the AD. Just a plain normal user. You might wanna disable password expiration if you are gonna use it in a production environment :)

The I made a php script on my Ubuntu server somewhat like the following:

#!/usr/bin/php

Trouble shooting

49: Invalid credentials

Remember when you tell PHP script which user you want to connect with, also supply the realm in which the user resides. In my test setup I used my own user je (Jacob Emcken), and my realm testdomain.com which means I’m connecting with to LDAP with the following user:

je@testdomain.com

1: Operations error

This error can come from to things:

  1. You have used DN instead of DC in you distinct name:

    DN=testdomain,DN=com (didn't work for me)
    

    This worked for me:

    DC=testdomain,DC=com
    
  2. You get this if you are trying to search the root of the tree and you haven’t set the following:

    ldap_set_option($ldap_connect_resource, LDAP_OPT_REFERRALS, 0);
    

18 Aug 2004

Substitute “Mac” newlines with unix ones

Posted by Jacob Emcken Comments (2)

At work we have been struggling with bad newlines in php-pages created with dreamweaver on a Mac. The newlines screwed up grep results and was mainly just one big pain in the ***. This is a little note to my self about how to solve it.

This solution (parsed around by one of the guys at work, thanks Frank) should be carved in stone to be remember for eternity. The second best would be writing it on the Internet and I don’t have any stones not already written on at the moment:

tr '\r\n' '\n'  OUTPUTFILE

03 Jul 2004

Ever biched over IE not being able to use transparent PNG’s?

Posted by Jacob Emcken Comments (0)

Well I have!!

Some days ago I found a link to a hack on Jakub ‘jimmac’ Steiner’s homepage.

I have now made a function in PHP which automaticaly uses this workaround in IE. Take a look at the code below.

$localDocumentRoot = str_replace($_SERVER['PHP_SELF'],
"", $_SERVER['SCRIPT_FILENAME']);

//$image is an array
/* This is a hack to use PNG transparentsy in IE */
function transparentImage($image, $ie) {
  global $localDocumentRoot;
  //The str_replace makes sure that images with spaces is also recognized
  $imageFile = getimagesize( str_replace(' ','%20',
  $localDocumentRoot.$image['src'] ) );
  if($ie) {
?>
<div
<?=((isset($image['id'])) ? ' id="'.$image[id].'"' : '')?>
<?=((isset($image['class'])) ? ' class="'.$image['class'].'"' : '')?>
style="<?=' height:'.$imageFile[1].'px;'?> filter:progid:DXImageTransform.Microsoft.\AlphaImageLoader(src='',
sizingMethod='scale');" > </div>
<?php
  }
  else {
?>
<img src="<?=$image['src']?>"
<?=((isset($image['id'])) ? ' id="'.$image['id'].'"' : '')?>
<?=((isset($image['class'])) ? ' class="'.$image['class'].'"' : '')?>
<?=((isset($image['alt'])) ? ' alt="'.$image['alt'].'"' : '')?>
 width="<?=$imageFile[0]?>"
 height="<?=$imageFile[1]?>"
<?=((isset($image['title'])) ? ' title="'.$image['title'].'"' : '')?>
/>
<?php
  }
}
?>

//Now run the function
$image['src'] = "/gallery/image.png";
$image['id'] = "unique_image";
$image['class'] = "image";
$image['alt'] = "Image example with transparent PNG images";
$image['title'] = "Tooltip for image";

transparentImage($image, true);

Tomorrow I will take a look at this post to make sure that I havet posted shitty code ;) Perhapes I can find a way so that Serendipity doesn’t fuck with the layout?!

30 May 2004

chmod (distinguish between files and directories)

Posted by Jacob Emcken Comments (1)

I hate having execute bit set on files not supposed to be executable. But I have always found it a lot easier to set it to keep directories browseable when chmod’ing a directory recursive. Now I thrown a little bash line together to easily only chmod files or directories.

This only chmod’s files:

debian:~# find -type f  | xargs -i chmod 640 {}

This only chmod’s directories:

debian:~#find -name '*' -type d  | xargs -i chmod 750 {}

The -name ‘*’ makes sure that it is only sub directories is processed (and not the current directory).