Feb
12

C#: Capitalize Words

With LINQ Aggregation:
public static string Capitalize(this String s)
{
  return s.ToCharArray().Aggregate(String.Empty,
    (working, next) =>
      working.Length == 0 && next != ' ' ? next.ToString().ToUpper() : (
        working.EndsWith(" ") ? working + next.ToString().ToUpper() :
          working + next.ToString()
    )
  );
}
Nov
11

JS: Disable TR onclick after dragging or reverting a drag with script.aculo.us’ Draggables

Today i made some clickable table elements (tr’s) draggable into a bunch of containers. I early regognized that the onclick event is fired after dragging, so i had the problem that my onclick ajax requests are processed after every drag – even if the drag gets reverted.
I managed it the following way.

1. Populated a global variable called dragging. Which is false by default
var dragging = false;

2. Checking if that variable is false before calling the onclick ajax request
<tr onclick="if(!dragging){process_click(xy)}else{return false;}">..</tr>

3. Setting the variable to true while dragging and back to false after dragging. Note that the Draggable onEnd event is processed before the onclick event, so we need to delay it a bit. In this case i decided to set the timeout to 1200ms. You can tweak it to your needs, of course.

new Draggable('row_xy',
{
revert: true,
ghosting: true,
onDrag:function(){ dragging=true; },
onEnd:function(){ window.setTimeout('dragging=false', 1200); },
}
);

Nov
04

PHP-LDAP: Convert Binary SID in Active Directory Results

function little_endian($hex) {
    $l_result = "";
    for ($i=strlen($hex)-2; $i >= 0; $i=$i-2)
      $l_result .= substr($hex,$i,2);
    return $l_result;
}
function sid_to_text($p_sid_bin) {
    $hex_sid = bin2hex($p_sid_bin);
    $rev = hexdec(substr($hex_sid,0,2));        // Revision
    $subcount = hexdec(substr($hex_sid,2,2));   // Sub-Count
    $auth = hexdec(substr($hex_sid,4,12));      // SECURITY_NT_AUTHORITY
    $result = $rev."-".$auth;
    for ($x=0;$x < $subcount; $x++) {
        // get all SECURITY_NT_AUTHORITY
        $subauth[$x] = hexdec(little_endian(substr($hex_sid,16+($x*8),8)));
        $result .= "-".$subauth[$x];
    }
    return $result;
}

Use it like:
$l_sid = sid_to_text($l_ldap_userdata[0]["objectsid"][0]);

I will publish my PHP LDAP Library including these methods later.
Nov
04

Exit iPhone Recovery Mode without recovering firmware

This basically works with a console tool called iRecovery which can be Downloaded Here. But remember: use it at your own risk..

1) For Windows you need to install libusb from the downloaded pack, Mac users can skip this step. Windows Vista/7 Users should run the installation in Windows XP compatibility Mode.

2) Connect your iPhone via USB and switch it on to see the Recovery Mode image (Itunes and Usb Cable)

3) Start iRecovery in Terminal / Console with irecovery -s

4) After some initialization you should see a console. Execute the following commands inside it:

	setenv auto-boot true
	saveenv
	/exit

5) Reboot your iPhone (keep holding home + sleep for 10 seconds or just switch it off and on again).

Jul
28

C#: Simple Text Writing

TextWriter tw = new StreamWriter(“log.txt”);
tw.WriteLine(DateTime.Now);
tw.Close();

Jul
01

C#: Object Comparison

To compare objects, the CaseInsensitiveComparer respectively the CaseSensitiveComparer is used. Here are the return values of it’s Compare(a,b) Method:

Value              Condition
lower than 0       a is lower than b (a<b)
0                  a == b
greater than 0     a is greater than b (a>b)
Jul
01

C#: Dynamic ContextMenu

{
    MenuItem l_MenuItem;
    IPHostEntry l_HostEntry = Dns.GetHostEntry(Dns.GetHostName());
    foreach (IPAddress ip in l_HostEntry.AddressList)
    {
        Log("Found IP address: " + ip.ToString());

        l_MenuItem = new MenuItem(ip.ToString());
        l_MenuItem.Click += delegate(object snd, EventArgs ea)
                                { this.IPMenuItemFrom_Click(snd, ea, ip); };

        btnCurrentToFrom.ContextMenu.MenuItems.Add(l_MenuItem.CloneMenu());
    }

}

private void IPMenuItemTo_Click(object sender, EventArgs e, IPAddress p_IP)
{ /* meep */ }
Jul
01

C#: Calling an EventHandler with additional parameters using delegate

private void WhatEver() {
  MenuItem l_MenuItem;
  foreach (IPAddress ip in l_HostEntry.AddressList)
  {
    l_MenuItem = new MenuItem(ip.ToString());
    l_MenuItem.Click += delegate(object snd, EventArgs ea)
                                { this.IPMenuItemTo_Click(snd, ea, ip); };
  }
}

private void IPMenuItemTo_Click(object sender, EventArgs e, IPAddress p_IP) {
  //p_IP available here
}
Jul
01

C#: Threading and Invoking the GUI

Today, it’s time to mention how GUI Threading is done and where the basic problems are.

In this post I describe how to start a Parameterized Thread, implement delegates, Invoke these Delegate Methods with parameters and Invoke delegate Methods without parameters. So, let’s start with the examples..

1. Start some Threads

private int m_threadcount = 10;

public void ThreadStarter()
{
  Thread[] t = new Thread[m_threadcount+1];

  for (i = 0; i < m_threadcount; i++)
  {
    t[i] = new Thread(new ParameterizedThreadStart(ThreadMethod));
    t[i].Start("ThreadParameter");
  }
}

public void ThreadMethod(String p_ThreadParameter) {
  // This method runs about 10 Minutes..
  while (true) {
    if (ListRecursive("C:\\")) {
      break;
    }
  }
}

2. Do some work

Create a Method called ListRecursive, which will do some work. The Thread should lastly be profitable, shouldn’t it?

public void ListRecursive(String p_Directory) {
  // do the hard work
  while (1) {..}
}

3. Show what is done in your GUI

So what about some GUI interactions inside the Thread, a progressBar or Log Window updater, for example?
For doing this, you need a delegate for your Method, which is actually changing the GUI. If this is given, an Invoke must call the delegate for you.

Note:
It is generally possible to do GUI changes inside ThreadMethod or ListRecursive by Invoking it via delegates.
But if you do so, the GUI will instantly freeze, because of the infinite while loop (depending on how long the Method call takes) !
Therefore it is much better to implement only cheap functions with a runtime of max 1/10s to do the GUI Stuff, so that no freeze should happen.
The following examples show how the implementation should be done correctly.

The lazy developer would do everything in his/her ListRecursive Method, which is actually possible, but its the
Bad way:

/* Method which is called by the Thread with a long runtime,
 * has got an own delegate prototype and is invoked by the Form Window */
protected delegate void MethodListRecursive(String p_Directory);
public void ListRecursive(String p_Directory) {
  // Invoke for GUI stuff
  if (this.InvokeRequired)
  {
    this.Invoke(new MethodListRecursive(ListRecursive),
       new Object[] { p_Directory });
    return;
  }
  // do the hard work
  // ..
  while (1) {
    // Show the directory entries:
    txtLog.Text = txtLog.Text + file + Environment.NewLine;
    progressBar.Value++;
    // ..
  }
}

The Thread safe developer, has got his own delegate and MethodInvoker for every GUI change!

Good and well working way:

/* Method, which only adds the Log Message (extremly fast call) */
protected delegate void MethodLog(String p_Message);
public void Log(String p_Message) {
  if (this.InvokeRequired)
  {
    this.Invoke(new MethodLog(Log),
       new Object[] { p_Message });
    return;
  }
  txtLog.Text = txtLog.Text + p_Message + Environment.NewLine;
}

/* Method, which only increments the ProgressBar */
public void ProgressPlus() {
  if (this.InvokeRequired)
  {
    this.Invoke(new MethodInvoker(ProgressPlus));
    return;
  }
  if (progressBar.Value + 1 <= progressBar.Maximum) progressBar.Value++;
}

/* Method which is called by the Thread - has got a long runtime */
public void ListRecursive(String p_Directory) {
  // do the hard work
  // ..
  // Show the directory entries:
  // Now we are using an own delegate method, which runs about 1 nano second ;-)
  Log(file);
  ProgressPlus();
  // ..
}
Jul
01

ASCII Table

ascii_table