<?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>Simon&#039;s Wonder World &#187; c#</title>
	<atom:link href="http://blog.simonstahl.com/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.simonstahl.com</link>
	<description>Just another European geek in Silicon Valley</description>
	<lastBuildDate>Tue, 19 Apr 2011 22:01:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Define some items in a ListBox as unselectable</title>
		<link>http://blog.simonstahl.com/2010/01/11/define-some-items-in-a-listbox-as-unselectable/</link>
		<comments>http://blog.simonstahl.com/2010/01/11/define-some-items-in-a-listbox-as-unselectable/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 23:48:47 +0000</pubDate>
		<dc:creator>Simon</dc:creator>
				<category><![CDATA[XAML]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[disable]]></category>
		<category><![CDATA[item]]></category>
		<category><![CDATA[listbox]]></category>
		<category><![CDATA[listboxitem]]></category>
		<category><![CDATA[unselectable]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://blog.simonstahl.com/?p=51</guid>
		<description><![CDATA[It seems to be a quite common problem that one does not know how to set one or more items in a ListBox to unselectable or disabled. The same principle as described here can also be user for similar problems like setting a different background color for some items. First we&#8217;re going to create a [...]]]></description>
			<content:encoded><![CDATA[<p>It seems to be a quite common problem that one does not know how to set one or more items in a <strong>ListBox </strong>to <strong>unselectable</strong> or <strong>disabled</strong>.</p>
<p>The same principle as described here can also be user for similar problems like setting a different background color for some items.</p>
<p>First we&#8217;re going to create a simple domain class with a property that describes if the item should be selectable or not.</p>
<pre class="brush:c#">public class MyDataObject {
    public string Name { get; set; }
    public bool IsSelectable { get; set; }
}</pre>
<p><span id="more-51"></span>Next we create a <strong>XAML</strong> Window that contains a ListBox. In this ListBox we define a custom <strong>ItemContainerStyle </strong>with a Style that defines if the Item will be selected or not. And finally we bind this Style to the <strong>IsSelectable </strong>property from our data object.</p>
<pre class="brush:xml">

            <!--
                <Setter Property="Focusable" Value="{Binding IsSelectable}" />

--></pre>
<p>And now we just have to fill the <strong>ItemsSource</strong> from the ListBox and we can run the example.</p>
<pre class="brush:c#">public partial class MainWindow : Window {
    public MainWindow() {
        InitializeComponent();

        myListBox.ItemsSource =
            from i in Enumerable.Range(0, 10)
            select new MyDataObject() { Name = string.Format("Object {0}", i), IsSelectable = i % 3 != 0 };
    }
}</pre>
<p>That&#8217;s all. Easy, isn&#8217;t it?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.simonstahl.com/2010/01/11/define-some-items-in-a-listbox-as-unselectable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An easy way to revert changes in Object data</title>
		<link>http://blog.simonstahl.com/2009/12/14/an-easy-way-to-revert-changes-in-object-data/</link>
		<comments>http://blog.simonstahl.com/2009/12/14/an-easy-way-to-revert-changes-in-object-data/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 23:43:53 +0000</pubDate>
		<dc:creator>Simon</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Clone]]></category>
		<category><![CDATA[DataBinding]]></category>
		<category><![CDATA[DataContext]]></category>
		<category><![CDATA[INotifyPropertyChanged]]></category>
		<category><![CDATA[Model View Control]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[PropertyChangedEventHandler]]></category>
		<category><![CDATA[Serializable]]></category>
		<category><![CDATA[SerializationException]]></category>

		<guid isPermaLink="false">http://blog.simonstahl.com/?p=42</guid>
		<description><![CDATA[A quite common problem in an MVC GUI is the need to revert changes in the model made by the user. Let&#8217;s say you create a UI where the user can modify some fields that are bound to a model object. After the user already did some changes, he recognizes that he entered some wrong [...]]]></description>
			<content:encoded><![CDATA[<p>A quite common problem in an <strong>MVC </strong>GUI is the need to revert changes in the model made by the user. Let&#8217;s say you create a UI where the user can modify some fields that are bound to a model object. After the user already did some changes, he recognizes that he entered some wrong data and wants to cancel the editing. So what now? The data is already written into the model.</p>
<p>The easiest way to revert this changes is obviously to let the user work with a copy of the real data object. So let&#8217;s add a clone method to the model and mark it as Serializable.<span id="more-42"></span></p>
<h2>Model with Clone() method</h2>
<pre class="brush:c#">[Serializable]
public abstract class PersonModel {

    public string Name { get; set; }
    public string FirstName { get; set; }
    public int Age { get; set; }

    public PersonModel Clone() {
        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream) {
            formatter.Serialize(stream, this);
            stream.Seek(0, SeekOrigin.Begin);
            return (PersonModel)formatter.Deserialize(stream);
        }
    }
}</pre>
<p>We now just bind the copy of the object to the view:</p>
<pre class="brush:c#">myView.DataContext = person.Clone();</pre>
<p>This copy can easily be dropped in case the user cancels the editing. In case he saves the<br />
changes, you can just replace the original object with the copy.</p>
<p>One problem I ran in it was, that I normally implement the <strong>INotifyPropertyChanged </strong>interfaces to my models to inform the view about changes in the model. Unfortunately the <strong>PropertyChangedEventHandler </strong>contained in this interface causes a nasty SerializationException because the Class PropertyChangedEventManager is not marked as Serializable.</p>
<p><em><strong>System.Runtime.Serialization.SerializationException was caught</strong><br />
Message=&#8221;Type &#8216;System.ComponentModel.PropertyChangedEventManager&#8217; in Assembly &#8216;WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&#8242; is not marked as serializable.&#8221;</em></p>
<p>The easiest way to work around this problem is to just exclude the <strong>PropertyChangedEventHandler </strong>from the serialization.</p>
<h2>Clonable Model that implements INotifyPropertyChanged</h2>
<pre class="brush:c#">[Serializable]
public abstract class PersonModel : INotifyPropertyChanged {
    [field: NonSerialized]
    public event PropertyChangedEventHandler PropertyChanged;

    private string name;
    private string firstName;
    private int age;

    public string Name {
        get { return name; }
        set { name = value; OnPropertyChange(); }
    }
    public string FirstName {
        get { return firstName; }
        set { firstName = value; OnPropertyChange(); }
    }
    public int Age {
        get { return age; }
        set { age = value; OnPropertyChange(); }
    }

    public PersonModel Clone() {
        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream) {
            formatter.Serialize(stream, this);
            stream.Seek(0, SeekOrigin.Begin);
            return (PersonModel)formatter.Deserialize(stream);
        }
    }

    protected void OnPropertyChange() {
        string propName = new StackFrame(1).GetMethod().Name.Replace("set_", "");
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}</pre>
<p>In this way everything works fine and you have hopefully one problem less to care about&#8230;</p>
<p>Happy DataBinding <img src='http://blog.simonstahl.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.simonstahl.com/2009/12/14/an-easy-way-to-revert-changes-in-object-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Access a Zend Rest Service from C#</title>
		<link>http://blog.simonstahl.com/2009/11/14/access-a-zend-rest-service-from-c/</link>
		<comments>http://blog.simonstahl.com/2009/11/14/access-a-zend-rest-service-from-c/#comments</comments>
		<pubDate>Sat, 14 Nov 2009 19:30:22 +0000</pubDate>
		<dc:creator>Simon</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[zend]]></category>

		<guid isPermaLink="false">http://simonstahl.com/wordpress/?p=32</guid>
		<description><![CDATA[Accessing a Restful service is actually no big deal, but it took me quite a while to figure out some details. So here&#8217;s a short description of it. First of all, we build a small Zend Rest Service with two ping methods and save it as MyRestService.php. &#60;?php class MyRestService { /** * @param string [...]]]></description>
			<content:encoded><![CDATA[<p>Accessing a Restful service is actually no big deal, but it took me quite a while to figure out some details. So here&#8217;s a short description of it.<br />
<span id="more-32"></span><br />
First of all, we build a small Zend Rest Service with two ping methods and save it as MyRestService.php.</p>
<pre class="brush:php">&lt;?php

class MyRestService {
 /**
 * @param string $name
 * @return string
 */
 public function ping($name) {
 return 'Hello ' . $name;
 }
}

require 'Zend/Rest/Server.php';

$server = new Zend_Rest_Server ( );
$server-&gt;setClass ( 'MyRestService' );
$server-&gt;handle();

require 'Zend/Rest/Server.php';

$server = new Zend_Rest_Server ( );
$server-&gt;setClass ( 'MyRestService' );
$server-&gt;handle();</pre>
<p>We can now allready access our service with the browser by entering the URL <a href="http://localhost/MyRestService.php?method=ping&amp;name=Simon">http://localhost/MyRestService.php?method=ping&amp;name=Simon</a>. The service returns the answer as XML.</p>
<pre class="brush:xml">&lt;MyRestService generator="zend" version="1.0"&gt;
 &lt;ping&gt;
 &lt;response&gt;Hello Simon&lt;/response&gt;
 &lt;status&gt;success&lt;/status&gt;
 &lt;/ping&gt;
&lt;/MyRestService&gt;</pre>
<p>As you can see the call as well as the answer are really straightforward and easy to unserstand. We&#8217;re going now to access our service from C#.</p>
<pre class="brush:c#">public void CallRest() {
 string methodName = "ping";
 string name = "Simon";

 // Build the URL with the parameters
 StringBuilder sb = new StringBuilder();
 sb.Append("http://localhost/MyRestService.php");
 sb.Append(string.Format("?method={0}", HttpUtility.UrlEncode(methodName)));
 sb.Append(string.Format("&amp;name={0}", HttpUtility.UrlEncode(name)));

 // Download the service answer as string
 Uri address = new Uri(sb.ToString());
 WebClient serviceClient = new WebClient();
 serviceClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(serviceClient_DownloadStringCompleted);
 serviceClient.DownloadStringAsync(address);
}

private void serviceClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) {
 try {
 // Check for service error
 if (e.Error != null)
 throw e.Error;

 // Load the result as XML for easy Linq access
 XElement elem = XElement.Parse(e.Result);

 // Check the return status
 string status = (string)(from el in elem.Descendants("status") select el).First();

 if ("success".Equals(status)) {
 // Get the response
 string resp = (string)(from el in elem.Descendants("response") select el).First();
 MessageBox.Show(resp, "The Restservice says...", MessageBoxButton.OK);

 } else if ("failed".Equals(status)) {
 // Get the error message
 string errmsg = (string)(from el in elem.Descendants("message") select el).First();
 throw new Exception(errmsg);

 } else {
 throw new Exception(string.Format("Unknown Rest status: {0}", status));
 }
 } catch (Exception exp) {
 MessageBox.Show(exp.ToString(), "Error", MessageBoxButton.OK);
 }
}</pre>
<p>When we run the code a MessageBox with the service response should pop up.</p>
<p>So, this was the part I figured out quite fast. But what happens if you change the service function so somewhat like this:</p>
<pre class="brush:php">/**
* @param array $names
* @return string
*/
public function ping($names){
 return $names['p2'];
}</pre>
<p>It took me some time to figure out that the answer is quite easy. Let&#8217;s change the C# function to fit the array parameter.</p>
<pre class="brush:c#">public void CallRest() {
 string methodName = "ping";
 string[] names = { "Simon", "John", "Bill" };

 // Build the URL with the parameters
 StringBuilder sb = new StringBuilder();
 sb.Append("http://localhost/MyRestService.php");
 sb.Append(string.Format("?method={0}", HttpUtility.UrlEncode(methodName)));

 for (int i = 0; i &lt; names.Length; i++)
 sb.Append(string.Format("&amp;names[p{0}]={1}", i, HttpUtility.UrlEncode(names[i])));

 // Download the service answer as string
 Uri address = new Uri(sb.ToString());
 WebClient serviceClient = new WebClient();
 serviceClient.DownloadStringCompleted += new
 DownloadStringCompletedEventHandler(serviceClient_DownloadStringCompleted);
 serviceClient.DownloadStringAsync(address);
}</pre>
<p>As you can see I just add the parameter as everybody would access an array. And once again, you can also access the service direct with your browser unter the URL <a href="http://localhost/MyRestService.php?method=ping&amp;names[p0]=Simon&amp;names[p1]=John&amp;names[p2]=Bill">http://localhost/MyRestService.php?method=ping&amp;names[p0]=Simon&amp;names[p1]=John&amp;names[p2]=Bill</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.simonstahl.com/2009/11/14/access-a-zend-rest-service-from-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

