<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dirty Motherfucking Blog &#187; c#</title>
	<atom:link href="http://dirty-motherfucker.org/blog/category/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://dirty-motherfucker.org/blog</link>
	<description>All kinds of shit</description>
	<lastBuildDate>Wed, 04 Jan 2012 15:38:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4-alpha-19620</generator>
		<item>
		<title>KeePass QR-Code Plugin</title>
		<link>http://dirty-motherfucker.org/blog/2011/03/26/keepass-qr-code-plugin/</link>
		<comments>http://dirty-motherfucker.org/blog/2011/03/26/keepass-qr-code-plugin/#comments</comments>
		<pubDate>Fri, 25 Mar 2011 23:32:47 +0000</pubDate>
		<dc:creator>gencha</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[keepass]]></category>
		<category><![CDATA[qr]]></category>

		<guid isPermaLink="false">http://www.dirty-motherfucker.org/blog/?p=331</guid>
		<description><![CDATA[So, a few weeks ago I finally got an Android smartphone and was faced with quite the problem. I wanted to set up my numerous eMail accounts on the phone but was pretty much unable to enter my passwords. For a long time I&#8217;ve been using KeePass to store my passwords. Additionally, I also generate [...]]]></description>
			<content:encoded><![CDATA[<p>So, a few weeks ago I finally got an Android smartphone and was faced with quite the problem. I wanted to set up my numerous eMail accounts on the phone but was pretty much unable to enter my passwords.</p>
<p>For a long time I&#8217;ve been using <a href="http://www.keepass.info">KeePass</a> to store my passwords. Additionally, I also generate random passwords (usually to the maximum complexity allowed). So first I thought I should just get an application to read my password store on my phone. But my master password for my password store requires both a key file and an incredibly complex password.</p>
<p>So I started copying my passwords into a QR code generator and setting up my accounts that way. And that worked out quite well.</p>
<p>Given how well it worked for me, I assumed there must be a KeePass plugin to streamline the process. Sadly, I couldn&#8217;t find one. So I wrote it. I quickly found a nice <a href="http://www.codeproject.com/KB/cs/qrcode.aspx">C# QR code library</a> that I could use for this project. Given that library, I only needed a couple lines of code to finish this project.</p>
<p>Long story short, this is the <a href="http://keepass.info/plugins.html#qrcodegen">KeePass QR code plugin</a>. Hopefully, in the future, I can make another small adjustment so that the size of the resulting code is optimized for the length of the password. But for now, I&#8217;m quite happy.</p>
]]></content:encoded>
			<wfw:commentRss>http://dirty-motherfucker.org/blog/2011/03/26/keepass-qr-code-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Passing SOAP faults from NuSoap to C#</title>
		<link>http://dirty-motherfucker.org/blog/2010/04/27/passing-soap-faults-from-nusoap-to-c/</link>
		<comments>http://dirty-motherfucker.org/blog/2010/04/27/passing-soap-faults-from-nusoap-to-c/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 19:59:06 +0000</pubDate>
		<dc:creator>gencha</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[nusoap]]></category>
		<category><![CDATA[soap]]></category>

		<guid isPermaLink="false">http://www.dirty-motherfucker.org/blog/?p=308</guid>
		<description><![CDATA[I am currently implementing a SOAP interface for a PHP application I am working on. The built-in SOAP support in PHP didn&#8217;t really provide everything I needed (namely WSDL generation), so I went with NuSoap. After a lot of pain trying to get a WSDL out of it, that Visual Studio would consume, and correctly [...]]]></description>
			<content:encoded><![CDATA[<p>I am currently implementing a SOAP interface for a PHP application I am working on. The built-in SOAP support in PHP didn&#8217;t really provide everything I needed (namely WSDL generation), so I went with NuSoap.<br />
After a lot of pain trying to get a WSDL out of it, that Visual Studio would consume, and correctly parse the SOAP messages I return, I came along the next big issue today.<br />
Whenever I tried to pass a fault from the server to my C# application, I would receive a nasty exception:</p>
<blockquote><p>Server returned an invalid SOAP Fault.  Please see InnerException for more details.</p></blockquote>
<p>Ok, so let&#8217;s look at that InnerException:</p>
<blockquote><p>Element &#8216;faultstring&#8217; with namespace name &#8221; was not found. Line 6, position 126.</p></blockquote>
<p>What? No &#8220;faultstring&#8221; element? Impossible!<br />
After double-checking my code for obvious errors and confirming with SoapUI that the &#8220;faultstring&#8221; element was indeed present, I started looking for the source of the issue. First I checked the nusoap_fault source, if there was anything weird in there that might confuse the CLR. But it seemed fine.</p>
<p>So I was sure the problem must be in the .Net libraries. I went on to decompile the binaries that are in use when making SOAP requests (namely System.ServiceModel). The actual issue was in System.ServiceModel.Channels.ReceivedFault.CreateFault11(). That function expects the elements of a SOAP fault&#8217;s body to be in a precise order! If the order is anything else than what it expects, it will throw the exception mentioned above.</p>
<p>I did not take the time to check whether this behavior is actually defined by the SOAP definition (although I highly doubt it). I just went on to extend the NuSoap classes to fix the issue. And here they are:</p>
<p>NuSoapServer.php:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
  require_once( &quot;nusoap/nusoap.php&quot; );

  require_once( dirname( __FILE__ ) . &quot;/NuSoapFault.php&quot; );

  /**
  * Wraps a NuSoap server.
  * This class overrides the fault method of nusoap_server to use a customized version of nusoap_fault.
  */
  class NuSoapServer extends nusoap_server {
    /**
     * Specify a fault to be returned to the client.
     * This also acts as a flag to the server that a fault has occured.
     *
     * @param        string $faultcode
     * @param        string $faultstring
     * @param        string $faultactor
     * @param        string $faultdetail
     * @access   public
     */
    function fault( $faultcode, $faultstring, $faultactor='', $faultdetail='' ) {
      if( $faultdetail == &quot;&quot; &amp;&amp; $this-&gt;debug_flag ) {
        $faultdetail = $this-&gt;getDebug();
      }
      $this-&gt;fault = new NuSoapFault( $faultcode, $faultactor, $faultstring, $faultdetail );
      $this-&gt;fault-&gt;soap_defencoding = $this-&gt;soap_defencoding;
    }

  }
?&gt;
</pre>
<p>NuSoapFault.php:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
  require_once( &quot;nusoap/nusoap.php&quot; );

  /**
  * Wraps a SOAP fault.
  * This class overrides nusoap_fault's serialize() method to fix the order in which it's members are serialized.
  * This is necessary to allow for communication with .Net clients.
  */
  class NuSoapFault extends nusoap_fault {
    /**
     * serialize a fault
     *
     * @return       string  The serialization of the fault instance.
     * @access   public
     */
    function serialize() {
      $ns_string = '';
      foreach( $this-&gt;namespaces as $k =&gt; $v ) {
        $ns_string .= &quot;\n  xmlns:$k=\&quot;$v\&quot;&quot;;
      }
      $return_msg =
        '&lt;?xml version=&quot;1.0&quot; encoding=&quot;' . $this-&gt;soap_defencoding . '&quot;?&gt;' .
        '&lt;SOAP-ENV:Envelope SOAP-ENV:encodingStyle=&quot;http://schemas.xmlsoap.org/soap/encoding/&quot;' . $ns_string . &quot;&gt;\n&quot; .
          '&lt;SOAP-ENV:Body&gt;' .
            '&lt;SOAP-ENV:Fault&gt;' .
              $this-&gt;serialize_val( $this-&gt;faultcode,   'faultcode'   ) .
              $this-&gt;serialize_val( $this-&gt;faultstring, 'faultstring' ) .
              $this-&gt;serialize_val( $this-&gt;faultactor,  'faultactor'  ) .
              $this-&gt;serialize_val( $this-&gt;faultdetail, 'detail'      ) .
            '&lt;/SOAP-ENV:Fault&gt;' .
          '&lt;/SOAP-ENV:Body&gt;' .
        '&lt;/SOAP-ENV:Envelope&gt;';
      return $return_msg;
    }

  }
?&gt;
</pre>
<p>So now in my actual code I don&#8217;t use nusoap_server anymore, but my own NuSoapServer. And now everything works fine.</p>
]]></content:encoded>
			<wfw:commentRss>http://dirty-motherfucker.org/blog/2010/04/27/passing-soap-faults-from-nusoap-to-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Adding build date/time/count to your C# project</title>
		<link>http://dirty-motherfucker.org/blog/2009/12/21/adding-build-datetimecount-to-your-c-project/</link>
		<comments>http://dirty-motherfucker.org/blog/2009/12/21/adding-build-datetimecount-to-your-c-project/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 12:57:42 +0000</pubDate>
		<dc:creator>gencha</dc:creator>
				<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.dirty-motherfucker.org/blog/?p=302</guid>
		<description><![CDATA[This is pretty much a straight-forward conversion of http://www.dirty-motherfucker.org/blog/2009/04/24/build-count-of-vc-project-for-version-string/ I was quite pissed that there is no easy option to get something as simple as the build date into your C# project. So here is my pre-build script I use in my C# projects: I went the easy route with this by simply dropping the [...]]]></description>
			<content:encoded><![CDATA[<p>This is pretty much a straight-forward conversion of http://www.dirty-motherfucker.org/blog/2009/04/24/build-count-of-vc-project-for-version-string/<br />
I was quite pissed that there is no easy option to get something as simple as the build date into your C# project.<br />
So here is my pre-build script I use in my C# projects:</p>
<pre class="brush: plain; title: ; notranslate">
@echo off
SETLOCAL
set TARGET_PATH=%~dp0
set IN_FILENAME=&quot;%TARGET_PATH%Version.txt&quot;
set OUT_FILENAME=&quot;%TARGET_PATH%Version.cs&quot;
set /p BUILD= &lt; %IN_FILENAME%
set BUILD=%BUILD:~22%
if /I &quot;%BUILD%&quot; == &quot;&quot; set BUILD=0
set /a BUILD=%BUILD%+1
echo #define VERSION_BUILD %BUILD% &gt; %IN_FILENAME%
echo using System; &gt; %OUT_FILENAME%
echo namespace Angler { &gt;&gt; %OUT_FILENAME%
echo 	class Version { &gt;&gt; %OUT_FILENAME%
echo 		public const int BuildCount 	= %BUILD%; &gt;&gt; %OUT_FILENAME%
echo 		public const string BuildDate 	= &quot;%DATE%&quot;; &gt;&gt; %OUT_FILENAME%
echo 		public const string BuildTime 	= &quot;%TIME%&quot;; &gt;&gt; %OUT_FILENAME%
echo 	} &gt;&gt; %OUT_FILENAME%
echo } &gt;&gt; %OUT_FILENAME%
ENDLOCAL
</pre>
<p>I went the easy route with this by simply dropping the build count into an additional file.<br />
I wanted to avoid parsing the value out of the .cs file. But you&#8217;re welcome to improve on this :P</p>
<p>When you first run it, it will create the VersionInfo.txt file which will contain the initial build count (for you to adjust).<br />
I place the script in my project directory as &#8220;Increase build count.cmd&#8221; and add this as a pre-build event: &#8220;$(ProjectDir)Increase build count.cmd&#8221; (INCLUDING the quotes!)<br />
Now you simply add Version.cs to your project and use its members in your program.</p>
]]></content:encoded>
			<wfw:commentRss>http://dirty-motherfucker.org/blog/2009/12/21/adding-build-datetimecount-to-your-c-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simulating TCP data from another device</title>
		<link>http://dirty-motherfucker.org/blog/2009/12/03/simulating-tcp-data-from-another-device/</link>
		<comments>http://dirty-motherfucker.org/blog/2009/12/03/simulating-tcp-data-from-another-device/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 22:11:22 +0000</pubDate>
		<dc:creator>gencha</dc:creator>
				<category><![CDATA[administration]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.dirty-motherfucker.org/blog/?p=293</guid>
		<description><![CDATA[This almost feels too simple to even mention it. But I guess it doesn&#8217;t hurt putting it our there. Someone might hit it in a desperate Google hunt. So this is the deal. You have a device on your network that controls another device by means of sending out simple TCP payloads. Now you want [...]]]></description>
			<content:encoded><![CDATA[<p>This almost feels too simple to even mention it. But I guess it doesn&#8217;t hurt putting it our there. Someone might hit it in a desperate Google hunt.<br />
So this is the deal. You have a device on your network that controls another device by means of sending out simple TCP payloads.<br />
Now you want to perform the same tasks with your program to get rid of the device. This is how you do it.</p>
<p>First, you wanna fire up your old friend <a href="http://www.wireshark.org/">Wireshark</a>. Now set up the device you want to emulate to send the data to the IP of your machine. Now you can start a Live Capture in Wireshark (Ctrl+E). Now you command your device to send the message by whatever means needed (like pressing the correct button on the device). Now stop the Live Capture in Wireshark (Ctrl+E) and add a filter to get the packet you need.</p>
<p>Let&#8217;s assume the devices IP address is 10.0.0.1 and your IP address is 10.0.0.2. Now the correct filter would be</p>
<pre class="brush: plain; title: ; notranslate">
ip.src == 10.0.0.1 &amp;&amp; ip.dst == 10.0.0.2
</pre>
<p>Now, hopefully you&#8217;ll see a single packet. In the center panel of Wireshark there should be a Data segment. This is what we want. Right-click it and select Copy -> Bytes (Hex Stream). You&#8217;ll get something like:</p>
<pre class="brush: plain; title: ; notranslate">
4e656574732c4b2c0100
</pre>
<p>(In case you&#8217;re interested, this is the payload when you press the first button on a <a href="http://neets.dk/products/control_system/307-0001/index.php">Neets Control EU Standard</a> device.)</p>
<p>Now let&#8217;s put this into code. The below example already has 2 payloads that would signal the target device to be turned on or off. For this 2 packets have been captured and can now be selected via the command line. The implementation is straight-forward.</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace Neets_Control {
  class Program {

    private static byte[] WORKLOAD_ON   = new byte[] { 0x4e, 0x65, 0x65, 0x74, 0x73, 0x2c, 0x4b, 0x2c, 0x01, 0x00 };
    private static byte[] WORKLOAD_OFF  = new byte[] { 0x4e, 0x65, 0x65, 0x74, 0x73, 0x2c, 0x4b, 0x2c, 0x02, 0x00 };

    private static string TARGET_HOST   = &quot;10.11.110.11&quot;;
    private static int    TARGET_PORT   = 5009;

    static void Main( string[] args ) {

      TcpClient sender = new TcpClient( TARGET_HOST, TARGET_PORT );
      NetworkStream stream = sender.GetStream();
      if( args[ 0 ] == &quot;on&quot; ) {
        Console.WriteLine( &quot;Switching on&quot; );
        stream.Write( WORKLOAD_ON, 0, WORKLOAD_ON.Length );

      } else if( args[ 0 ] == &quot;off&quot; ) {
        Console.WriteLine( &quot;Switching off&quot; );
        stream.Write( WORKLOAD_OFF, 0, WORKLOAD_OFF.Length );

      } else {
        Console.WriteLine( &quot;Missing parameter (on/off).&quot; );
      }

      stream.Close();
      sender.Close();

    }
  }
}
</pre>
<p>So, yeah, I can now just refer back to my introduction. Possibly this wasn&#8217;t event worth mentioning ;)</p>
]]></content:encoded>
			<wfw:commentRss>http://dirty-motherfucker.org/blog/2009/12/03/simulating-tcp-data-from-another-device/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Run .bat file with a set of parameters</title>
		<link>http://dirty-motherfucker.org/blog/2009/11/28/run-bat-file-with-a-set-of-parameters/</link>
		<comments>http://dirty-motherfucker.org/blog/2009/11/28/run-bat-file-with-a-set-of-parameters/#comments</comments>
		<pubDate>Sat, 28 Nov 2009 00:39:18 +0000</pubDate>
		<dc:creator>gencha</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[.bat]]></category>
		<category><![CDATA[batch]]></category>
		<category><![CDATA[console]]></category>

		<guid isPermaLink="false">http://www.dirty-motherfucker.org/blog/?p=287</guid>
		<description><![CDATA[I am currently working on a project of larger scale than what I am usually working on. During this project I wrote several small tools which I personally feel are somewhat interesting. I&#8217;ll try to write up a few posts about some solutions I came up with to kinda special problems. This is the first [...]]]></description>
			<content:encoded><![CDATA[<p>I am currently working on a project of larger scale than what I am usually working on. During this project I wrote several small tools which I personally feel are somewhat interesting.<br />
I&#8217;ll try to write up a few posts about some solutions I came up with to kinda special problems.<br />
This is the first one and I already feel the topic is not capturing the essence of what this tool does.</p>
<p>In this project we have a Windows domain of about 100 machines which are running our software are mainly used to display &#8220;stuff&#8221; (let&#8217;s not go into details).<br />
When I arrived on site where we deployed our product I found that some technicians where using .bat files to deploy files to machines in the domain. After deploying their files they would restart the machine remotely through Windows remote desktop feature. They would repeat that process for every machine in the domain manually until the desired group was up-to-date.<br />
Needless to say, for a programmer, this seemed unnecessarily cumbersome. This was when I wrote the first helpful tool.</p>
<p>The tool will read a .xml file which contains target IP addresses (or machine names if DNS is available) and will use them as a parameter to a supplied batch file. Alternatively it would use a list of targets supplied via the command line. Thus enabling you to run a .bat file for a large set of targets.<br />
Let&#8217;s have a look at the source:</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Xml;
using System.Diagnostics;

namespace BatchProcessor {
  class Program {

    private const   String      APPLICATION_NAME    = &quot;Batch Processor&quot;;
    private const   String      APPLICATION_VERSION = &quot;0.1&quot;;

    private static ConsoleColor defaultColor        = ConsoleColor.Gray;

    static void Main( string[] args ) {

      Console.WindowWidth = 160;
      Console.Title = String.Format( &quot;{0} {1}&quot;, APPLICATION_NAME, APPLICATION_VERSION );

      Console.ForegroundColor = ConsoleColor.Cyan;
      Console.WriteLine( String.Format( &quot;{0} {1}&quot;, APPLICATION_NAME, APPLICATION_VERSION ) );
      Console.ForegroundColor = ConsoleColor.DarkCyan;
      Console.WriteLine( &quot;CPP Studios Event GmbH 2009&quot; );
      Console.ForegroundColor = defaultColor;

      string        batchFile   = String.Empty;
      string        targetsFile = String.Empty;
      List&lt;string&gt;  targets     = new List&lt;string&gt;();

      if( args.Length &lt; 2 ) {
        errorExit( &quot;Incorrect number of arguments&quot; );
        return;
      }

      batchFile   = args[ 0 ];
      targetsFile = args[ 1 ];

      // Check if targetsFile is actually a file
      FileInfo targetsFileInfo = new FileInfo( targetsFile );
      if( !targetsFileInfo.Exists ) {
        for( int targetIndex = 1; targetIndex &lt; args.Length; ++targetIndex ) {
          targets.Add( args[ targetIndex ] );
        }

      } else {
        XmlDocument targetFile = new XmlDocument();
        try {
          Console.WriteLine( String.Format( &quot;Reading targets from {0}...&quot;, targetsFile ) );
          targetFile.Load( targetsFile );

          XmlNodeList targetNodes = targetFile.SelectNodes( &quot;/targets/target&quot; );
          foreach( XmlNode targetNode in targetNodes ) {
            targets.Add( targetNode.Attributes[ &quot;ip&quot; ].InnerText );
          }

        } catch( Exception ex ) {
          Console.ForegroundColor = ConsoleColor.Red;
          Console.WriteLine( &quot;Error while reading targets: &quot; + ex.Message );
          Console.ForegroundColor = defaultColor;
        }
      }
      Console.WriteLine( String.Format( &quot;Got {0} targets&quot;, targets.Count ) );

      foreach( String target in targets ) {
        string commandLine = String.Format( &quot;{0} {1}&quot;, batchFile, target );
        Console.ForegroundColor = ConsoleColor.DarkGreen;
        Console.WriteLine( String.Format( &quot;Executing '{0}'...&quot;, commandLine ) );
        Console.ForegroundColor = defaultColor;

        ProcessStartInfo  p     = new ProcessStartInfo( batchFile );
        Process           proc  = new Process();

        p.Arguments               = target;
        p.RedirectStandardOutput  = true;
        p.UseShellExecute         = false;
        proc.StartInfo            = p;

        proc.Start();
        StreamReader outputReader = proc.StandardOutput;

        proc.WaitForExit();
        Console.Write( outputReader.ReadToEnd() );

        Console.ForegroundColor = ConsoleColor.DarkGreen;
        Console.WriteLine( String.Format( &quot;Finished processing '{0}'.&quot;, commandLine ) );
        Console.ForegroundColor = defaultColor;
      }

      Console.ForegroundColor = ConsoleColor.Magenta;
      Console.WriteLine( &quot;Operation completed.&quot; );
      Console.ForegroundColor = defaultColor;

    }

    private static void errorExit( String errorMessage ) {
      Console.ForegroundColor = ConsoleColor.Red;
      Console.WriteLine( errorMessage );
      Console.ForegroundColor = defaultColor;
      Thread.Sleep( 5000 );
    }

  }
}
</pre>
<p>Pretty much a straight forward implementation of what I explained above.<br />
What amazed me most about the tool was the simplicity and how much can be achieved by the approach. Everyone who is capable of writing a .bat file could plug it right into the system and apply the command set to our pre-defined groups. I like to think that it turned out to be a very simple, yet versatile tool.</p>
<p>Another thing to notice is the console redirection used here. It&#8217;s pretty much what you will find if you google for &#8220;c# redirect console output&#8221; in a few seconds. Soon I noticed that it&#8217;s a very shitty way to redirect console output and leaves a lot to wish for. I will cover that topic in more detail in an upcoming post.</p>
]]></content:encoded>
			<wfw:commentRss>http://dirty-motherfucker.org/blog/2009/11/28/run-bat-file-with-a-set-of-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

