<?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 Tech Blog</title>
	<atom:link href="http://blog.simonstahl.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.simonstahl.com</link>
	<description>Simon Stahls Blog about programming and software development</description>
	<lastBuildDate>Sat, 15 May 2010 20:10:15 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Login to Foursquare with an Android App using OAuth</title>
		<link>http://blog.simonstahl.com/2010/05/15/login-to-foursquare-with-an-android-app-using-oauth/</link>
		<comments>http://blog.simonstahl.com/2010/05/15/login-to-foursquare-with-an-android-app-using-oauth/#comments</comments>
		<pubDate>Sat, 15 May 2010 20:10:15 +0000</pubDate>
		<dc:creator>Simon</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Foursquare]]></category>
		<category><![CDATA[OAuth]]></category>

		<guid isPermaLink="false">http://blog.simonstahl.com/?p=69</guid>
		<description><![CDATA[Although the Foursquare login process is pretty easy, it took me some time to figure out how this could be done from an Android application. The problem here is, that I don&#8217;t want a Popup window for the OAuth login. There&#8217;s a different requirement for the whole login process.
A standard OAuth login process consists of this [...]]]></description>
			<content:encoded><![CDATA[<p>Although the Foursquare login process is pretty easy, it took me some time to figure out how this could be done from an Android application. The problem here is, that I don&#8217;t want a Popup window for the OAuth login. There&#8217;s a different requirement for the whole login process.</p>
<p>A standard OAuth login process consists of this flow:</p>
<ul>
<li>Create consumer with application token and secret</li>
<li>Get login URL from service</li>
<li>Redirect the user to the login URL</li>
<li>User grant or deny access to service</li>
<li>Get the access token and secret</li>
</ul>
<p>But in a mobile application, without a URL redirection, what we actually want is something like this:</p>
<ul>
<li>Create consumer with application token and secret</li>
<li>Login to service</li>
<li>Get the access token and secret<span id="more-69"></span></li>
</ul>
<p>OK, first we need an OAuth library. In this example I&#8217;m going to user the Signpost lib. You can get it from here: <a href="http://code.google.com/p/oauth-signpost/">http://code.google.com/p/oauth-signpost/</a></p>
<p>There are 3 available libraries, but for this example we need only the <strong>core </strong>and the <strong>commonshttp4 </strong>part. Then, it&#8217;s actually pretty easy to login. We can to this in just one step with the user <strong>Email-address</strong> and his <strong>password</strong>.</p>
<pre class="brush:java">// Build URL and create GET request
String url = "http://api.foursquare.com/v1/authexchange" +
				"?fs_username=" +
				EMAIL +
				"&amp;fs_password=" +
				PW;
HttpGet reqLogin = new HttpGet(url);

// Instantiate consumer with application key and secret
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(
		CONSUMER_KEY,
		CONSUMER_SECRET);
consumer.sign(reqLogin);

// Login
HttpClient httpClient = new DefaultHttpClient();
HttpResponse resLogin = httpClient.execute(reqLogin);
if (resLogin.getEntity() == null) {
	throw new Exception("Could not login");
}

// Parse response
Document document =
	DocumentBuilderFactory
		.newInstance()
			.newDocumentBuilder()
				.parse(resLogin.getEntity().getContent());

// Get access token
Element eOAuthToken =
	(Element)document.getElementsByTagName("oauth_token").item(0);
Node e = eOAuthToken.getFirstChild();
String sOAuthToken =  e.getNodeValue();
System.out.println("token: " +sOAuthToken);

// Get access secret
Element eOAuthTokenSecret =
	(Element)document.getElementsByTagName("oauth_token_secret").item(0);
e = eOAuthTokenSecret.getFirstChild();
String sOAuthTokenSecret =  e.getNodeValue();
System.out.println("Secret: " +sOAuthTokenSecret);

// Set access token and secret for further requests
consumer.setTokenWithSecret(sOAuthToken, sOAuthTokenSecret);

// Get user information
HttpGet requestVenue = new HttpGet("http://api.foursquare.com/v1/user");
consumer.sign(requestVenue);
HttpResponse resVenue = httpClient.execute(requestVenue);
if (resVenue.getEntity() == null) {
	throw new Exception("Could not get user information");
}

InputStream is = resVenue.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null; 

while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
}

System.out.println(sb.toString());</pre>
<p>Of course, this login process has to be done just once. We just need to store the access token and the secret somewhere for further use.</p>
<p>That&#8217;s it. Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.simonstahl.com/2010/05/15/login-to-foursquare-with-an-android-app-using-oauth/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Does Social Networking changes our view of privacy?</title>
		<link>http://blog.simonstahl.com/2010/05/15/does-social-networking-changes-our-view-of-privacy/</link>
		<comments>http://blog.simonstahl.com/2010/05/15/does-social-networking-changes-our-view-of-privacy/#comments</comments>
		<pubDate>Sat, 15 May 2010 19:04:25 +0000</pubDate>
		<dc:creator>Simon</dc:creator>
				<category><![CDATA[Social]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[Privacy]]></category>
		<category><![CDATA[Social Networking]]></category>

		<guid isPermaLink="false">http://blog.simonstahl.com/?p=65</guid>
		<description><![CDATA[Social Networking:
How Social Networking changes our view of privacy
As Social Networking Sites (SNS) in the Internet are faced with an exponential growth, it gets more and more important what kind of personal data users are willing to disclose to get a fully satisfying user-experience in return. These days, many users expect a SNS to allow [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;">Social Networking:</p>
<p style="text-align: center;">How Social Networking changes our view of privacy</p>
<p>As Social Networking Sites (SNS) in the Internet are faced with an exponential growth, it gets more and more important what kind of personal data users are willing to disclose to get a fully satisfying user-experience in return. These days, many users expect a SNS to allow them to broadcast their thoughts and doings in realtime to all their friends. But that was not always the case; when Mark Zuckerberg, the founder of Facebook which has currently over 400 million active users (Facebook, 2010), in 2004 invented the status field that allowed the users to make their thoughts public, many people asked him &#8220;What is that good for?&#8221; and &#8220;Why would I like to post my thoughts to the Internet?&#8221;. Since then, posting status messages has become normal for Facebook users and most of them would certainly miss that feature. These status messages are in fact nothing else then highly personal data. It is possible to know a person quite well just by reading this persons Facebook wall. But what does it mean when millions of people feel the demand to disclose their personal data to their friends and often to the whole world? Does this mean that they are less concerned about their privacy than people were previously? My research actually shows exactly the opposite of that; Even if people are sharing quite a lot of their private data, it seems that they care rather more about their privacy then in the early days.<span id="more-65"></span></p>
<p>The Term SNS is widely used these days and it may be hard to distinguish where it really applies and where not, so first of all it is important to clarify what exactly a SNS is. Boyd and Ellison (2007) defined it as</p>
<p style="padding-left: 30px;">web-based services that allow individuals to (1) construct a public or semi-public profile within a bounded system, (2) articulate a list of other users with whom they share a connection, and (3) view and traverse their list of connections and those made by others within the system. The nature and nomenclature of these connections may vary from site to site.</p>
<p>Facebook is a perfect example of a SNS. It allows users to create a profile which they can share with their friends as an closed profile (closed to the public) or to the whole world as an open profile (open to the public). It contains a privacy settings page, which allows users to define exactly which information they want to be public and which private. Furthermore, Facebook allows users to connect their profile to a social graph consisting of their friends and family. And finally users can browse the social graph of their friends to see with whom they are friend. And of course everyone can post status messages which can, depending on the privacy settings, be seen by either just their friends or by everyone who looks at their profile.</p>
<p>An important point, however, is that all users have the guarantied right by law to decide themselves who can access their data. Schaefer and Birkland (2007) distinguished between four guaranteed privacy rights that are guaranteed by law: informational, physical, decision and propriety privacy. Regarding SNS the applicable one is that of informational privacy, which includes the control of personal data. With Facebook this means that all users can control who can see their personal data like name, address, Email address and also their status messages and the comments they made. Facebook does indeed provide the possibility of defining exactly who can access which information about a person. However, these are opt-out settings, which means the default is that every information is shared with everyone. If the users want their data to be private, they have to find the proper setting and change it accordingly.</p>
<p>Even if this privacy rights are guaranteed by law, there are exceptions that allows the FBI for example to see all information submitted through the Internet. The FBI has had the right to observe the digital data of suspects on the Internet for a long time. If they previously had a suspicion that a person did something illegal, they could request this persons data and look over it. But Batra (2008) pointed out that as reaction to the 9/11 attacks, the Patriot Act was released which now gave the FBI the right to store and even automatically analyze information gathered in the Internet. This means they do not even need a suspicion anymore to analyze someone’s data. Everybody‘s data is now automatically checked by a bunch of algorithms to see if it contains content that may be dangerous for the public. If someone, for example, writes an Email to a friend in which he complains about the government and where he writes that he would like to kill the president, the FBIs algorithms would recognize this message as potential dangerous and may alert an agent. This can lead to further observations of this person and in extreme cases even to a black listing so this person is not allowed anymore to enter the US or to fly over US territory.</p>
<p>Thought not just the FBI can see personal information from SNS; because of the opt-out mechanism that defines information as public by default, almost everyone with a computer can gather a lot of information about a person via a SNS. One statistic released by Lampe, Ellison and Steinfield (2008) demonstrated that about one third of the SNS users think that their profile has been watched by possible future employers and even total strangers. Of course, it brings some discomfort to know that people at the company where I just applied for a job can see the party pictures I made last weekend.</p>
<p>As a logical consequence of the assumption that strangers watch their profile and the fact that most SNS users know pretty well that the Internet is everything but anonymous and private, some users have started to obscure their real identity. Quan-Haase and Young (2009) showed that many users try to hide their real identity by providing some fake data or by excluding important information from their profile. The hope of this users is that by doing this, their profile won’t be that easy to find anymore or not relatable to them as person at all.</p>
<p>Although it’s just a minority that try to hide their identity in such a way, most of the SNS users provide their real data and do not even make use of the available privacy settings to hide their information from unknown people. Schrammel, Köffel and Tscheligi (2009) discovered that more then half of the SNS users disclose their real name as well as their picture to the public. A bit less, but still more then one third also share their date of birth and their friend connections with the world. Their profiles can therefore pretty easily be found and their data can be used or misused by anybody.</p>
<p>With the further evolution of SNS and the invention of Photo-services people have been faced with even more possibilities of data disclosure. Ahern, Eckles, Good, King, Naaman and Nair (2007) showed that 28% of photos that show people and were uploaded to a photo-service in the Internet were publicly accessible. Even a larger amount of non-person pictures were public; for example 64% of pictures showing activities were accessibly by everybody. They also found out that just a minority of the people are concerned about the location tagging of the pictures. With this technique, it is possible to see on a map where the users were at the moment when they took the picture. This information can, of course, easily be misused for example by a stalker to physically meet the person that took the picture.</p>
<p>The fact that SNS users disclose their data in such a liberal way does not mean, that they do not care about their privacy. In fact, most are very concerned about their privacy. Kasper (2005) found that 79% of adults think it is &#8220;extremity important&#8221; to be in control of their personal data. This shows the difference between the concerns of the users and what they actually do to protect their personal data. On one side, they are very concerned about their privacy but on the other side are they sharing their information quite freely.</p>
<p>This willingness to provide personal information despite the concern about privacy might have its roots in the unlimited confidence that especially the younger users have in the Internet. While evaluating the search behavior of people on the Internet, Conti and Sobiesk (2007) came across the interesting fact that younger people are much more likely to search for sensitive keywords, that they do not want their employer to know about, than older users. This indicates that older Internet users do not fully trust in the shallow web-anonymity while the younger ones are much more trustworthy. It also exhibits the different mentality of the users that grew up with the Internet and others that also know the time before it.</p>
<p>As younger users are willing to trust the Internet more and more, some of the elder people might argue that SNS and the Internet in general mislead younger generations to disclose too much private data about themselves. While the elder ones in fact just may not know how to handle these new technologis. It may be true, that younger users are willing to share more information on the internet than elders, but as showed before they are well aware that this information can be watched by other people and will therefore mostly not share any sensitive information.</p>
<p>This fear, that new technologies lead to a reduction in privacy, could already be seen several times in latest history. People were also very concerned about their privacy after the invention of photography, the telephone and especially in the late 1960s after the computer was invented (Kasper, 2005). As we know now, however, our privacy rights do still exist even after these inventions.</p>
<p>Even if the disclosing of private data in SNS can be a serious problem, we can not deny the benefits we get in response. Ferrell, Nowak and Phelps (2000) found that people actually expect personalized Marketing and that they would be upset if they lost it. This expectation can just be fulfilled if the users continue to provide some amount of private data.</p>
<p style="text-align: center;">References</p>
<p><em>Facebook Statistics </em>(2010). Retrieved April 13, 2010 from <a href="http://www.facebook.com/press/info.php?statistics">http://www.facebook.com/press/info.php?statistics</a></p>
<p>Boyd, D.M., &amp; Ellison, N.B. (2007, October). Social network sites: Definition, history, and scholarship. <em>Journal of Computer-Mediated Communication,</em> 13, Article 11. Retrieved April 13, 2010, from <a href="http://jcmc.indiana.edu/vol13/issue1/boyd.ellison.html">http://jcmc.indiana.edu/vol13/issue1/boyd.ellison.html</a></p>
<p>Birkland, T.A., &amp; Schaefer, T.M. (2007). <em>Encyclopedia of media and politics</em>. Washington, D.C.: CQ Press. Batra, N. D. (2008). <em>Digital freedom: how much can you handle? </em>Lanham, Rowman &amp; Littlefield.</p>
<p>Ellison, N. B., Lampe, C., &amp; Steinfield, C. (2008). Changes in use and perception of Facebook. <em>Computer Supported Cooperative Work</em> (pp. 721-730). San Diego, CA: ACM. Retrieved April 13, 2010, from <a href="http://portal.acm.org.libaccess.sjlibrary.org/citation.cfm?doid=1460563.1460675">http://portal.acm.org.libaccess.sjlibrary.org/citation.cfm?doid=1460563.1460675</a></p>
<p>Quan-Haase, A., Young, &amp; A.L. (2009). Information revelation and Internet privacy concerns on social network sites: a case study of facebook. <em>Communities and Technologies </em>(pp. 265-274). University Park, PA: ACM. Retrieved April 13, 2010, from <a href="http://portal.acm.org.libaccess.sjlibrary.org/citation.cfm?id=1556460.1556499">http://portal.acm.org.libaccess.sjlibrary.org/citation.cfm?id=1556460.1556499</a></p>
<p>Köffel, C., Schrammel, J., &amp; Tscheligi, M. (2009). Personality traits, usage patterns and information disclosure in online communities. <em>British Computer Society Conference on </em><em>Human-Computer Interaction</em> (pp. 169-174). Cambridge, UK: British Computer Society. Retrieved April 13, 2010, from <a href="http://portal.acm.org.libaccess.sjlibrary.org/citation.cfm?id=1671031">http://portal.acm.org.libaccess.sjlibrary.org/citation.cfm?id=1671031</a></p>
<p>Ahern, S., Eckles, D., Good, N.S., King, S., Naaman, M., &amp; Nair, R. (2007). Over-exposed?: privacy patterns and considerations in online and mobile photo sharing. <em>Conference on </em><em>Human Factors in Computing Systems</em> (pp. 357-366). San Jose, CA: ACM. Retrieved April 13, 2010, from <a href="http://portal.acm.org.libaccess.sjlibrary.org/citation.cfm?id=1240624.1240683">http://portal.acm.org.libaccess.sjlibrary.org/citation.cfm?id=1240624.1240683</a></p>
<p>Kasper, D.V.S. (2005) The Evolution (Or Devolution) of Privacy. Sociological Forum, 20, 69-92. Retrieved April 13, 2010, from <a href="http://www.jstor.org/pss/4540882">http://www.jstor.org/pss/4540882</a></p>
<p>Conti, G., &amp; Sobiesk, E. (2007). An honest man has nothing to fear: user perceptions on web-based information disclosure. <em>ACM International Conference Proceeding Series</em> (pp. 112-121). Pittsburgh, PA: ACM. Retrieved April 13, 2010, from <a href="http://portal.acm.org.libaccess.sjlibrary.org/citation.cfm?id=1280680.1280695">http://portal.acm.org.libaccess.sjlibrary.org/citation.cfm?id=1280680.1280695</a></p>
<p>Phelps, J., Nowak, G., Ferrell, E. (2000). Privacy Concerns and Consumer Willingness to Provide Personal Information. <em>Journal of Public Policy &amp; Marketing</em>, 19, 27-41. Retrieved April 13, 2010, from <a href="http://www.jstor.org/stable/30000485">http://www.jstor.org/stable/30000485</a></p>
<p><em> </em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.simonstahl.com/2010/05/15/does-social-networking-changes-our-view-of-privacy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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 simple domain [...]]]></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>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" html-script: true"><Window x:Class="ListBoxSelectableTestGUI.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <ListBox Name="myListBox">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}"/>
                    <TextBlock Text="Selectable=" Margin="20,0,0,0"/>
                    <TextBlock Text="{Binding IsSelectable}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>

        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Focusable" Value="{Binding IsSelectable}"/>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
</Window>
</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.</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 $name
 * @return [...]]]></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>1</slash:comments>
		</item>
		<item>
		<title>PHP Webservices with the Zend Framework</title>
		<link>http://blog.simonstahl.com/2009/11/14/php-webservices-wth-the-zend-framework/</link>
		<comments>http://blog.simonstahl.com/2009/11/14/php-webservices-wth-the-zend-framework/#comments</comments>
		<pubDate>Sat, 14 Nov 2009 19:10:45 +0000</pubDate>
		<dc:creator>Simon</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[soap]]></category>
		<category><![CDATA[xmlrpc]]></category>
		<category><![CDATA[zend]]></category>

		<guid isPermaLink="false">http://simonstahl.com/wordpress/?p=6</guid>
		<description><![CDATA[With the Zend framework you can choose between Rest-, XmlRpc- and Soap-Webservices. I am going to describe here all of them with a simple ping service.
For all of them you need first a function or a class which you like to expose as service.
MyTestService.php
&#60;?php

class MyTestService {

	/**
	 * A simple ping service
	 *
	 * @param string [...]]]></description>
			<content:encoded><![CDATA[<p>With the Zend framework you can choose between <strong>Rest</strong>-, <strong>XmlRpc</strong>- and <strong>Soap</strong>-Webservices. I am going to describe here all of them with a simple ping service.<span id="more-6"></span></p>
<p>For all of them you need first a function or a class which you like to expose as service.</p>
<p>MyTestService.php</p>
<pre class="brush:php">&lt;?php

class MyTestService {

	/**
	 * A simple ping service
	 *
	 * @param string $value
	 * @return string
	 */
	function ping($value) {
		return $value . ' back from server';
	}
}</pre>
<p>It is quite important to add the documentation with the exact datatype for all parameters as well as for the return value to the function. This information is used by the Zend framework to parse the values e.g. for the WSDL generation.</p>
<h2><strong>Rest Service</strong></h2>
<p>RestService.php</p>
<pre class="brush:php">&lt;?php

require 'Zend/Rest/Server.php';
require_once 'MyTestService.php';

$server = new Zend_Rest_Server();
$server-&gt;setClass('MyTestService');
$server-&gt;handle();</pre>
<h2>XmlRpc Service</h2>
<p>XmlRpcService.php</p>
<pre class="brush:php">&lt;?php

require 'Zend/XmlRpc/Server.php';
require_once 'MyTestService.php';

$server = new Zend_XmlRpc_Server();
$server-&gt;setClass('MyTestService');
echo $server-&gt;handle();</pre>
<p>Caution: the echo on the last line is here essential!</p>
<h2>Soap Service</h2>
<p>SoapWebService.php</p>
<pre class="brush:php">&lt;?php

require 'MyTestService.php';

if (isset ( $_GET ['wsdl'] )) {
	require 'Zend/Soap/AutoDiscover.php';

	$autodiscover = new Zend_Soap_AutoDiscover ( );
	$autodiscover-&gt;setClass ( 'MyTestService' );
	$autodiscover-&gt;handle ();
} else {
	require 'Zend/Soap/Server.php';

	$url = URL;
	$server = new Zend_Soap_Server ( "http://localhost/SoapWebService.php?wsdl" );
	$server-&gt;setClass ( 'MyTestService' );
	echo $server-&gt;handle ();
}</pre>
<p>What we can see here is the possibility to generate the WSDL file automaticaly. The class Zend_Soap_AutoDiscover is doing this for us. We have just to set the class that we use as service. The WSDL is now accessible under the URL <a href="http://localhost/SoapWebService.php?wsdl">http://localhost/SoapWebService.php?wsdl</a>.</p>
<h2>Client</h2>
<p>Accessing the services is as easy as creating them.</p>
<p>index.php</p>
<pre class="brush:php">&lt;?php

require 'Zend/Rest/Client.php';
require 'Zend/XmlRpc/Client.php';
require 'Zend/Soap/Client.php';

try {

	// Rest
	$client = new Zend_Rest_Client ( "http://localhost/RestService.php" );
	$result = $client-&gt;ping ( 'test' )-&gt;get ();
	echo 'Rest:&lt;br/&gt;';
	var_dump ( $result );

	// XmlRpc
	$client = new Zend_XmlRpc_Client ( "http://localhost/XmlRpcService.php" );
	$result= $client-&gt;call('ping', array('test'));
	echo '&lt;br/&gt;&lt;br/&gt;XmlRpc:&lt;br/&gt;';
	var_dump ( $result );

	// Soap
	$client = new Zend_Soap_Client ( "http://localhost/SoapService.php?wsdl" );
	$result = $client-&gt;ping ( 'test' );
	echo '&lt;br/&gt;&lt;br/&gt;Soap:&lt;br/&gt;';
	var_dump ( $result );
} catch ( Exception $e ) {
	echo '&lt;b style="color:#FF0000;"&gt;Error: ' . $e-&gt;getMessage () . '&lt;/b&gt;';
}</pre>
<p>As you can see, the Rest- and the Soap service are a bit more intuitive to use than the XmlRpc service. Which one is best depends on the requirements and the use of the service.</p>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">
<div class="content_full">
<div class="bText">
<p>With the Zend framework you can choose between <strong>Rest</strong>-, <strong>XmlRpc</strong>- and <strong>Soap</strong>-Webservices. I am going to describe here all of them with a simple ping service.</p>
<p>For all of them you need first a function or a class which you like to expose as service.</p>
<p>MyTestService.php</p>
<pre class="brush:php">&lt;?php

class MyTestService {

<span style="color: #008000;">/**

* A simple ping service

*

* @param string $value

* @return string

*/</span>

function ping($value){

return $value .' back from server';

}

}

It is quite important to add the documentation with the exact datatype for all parameters as well as for the return value to the function. This information is used by the Zend framework to parse the values e.g. for the WSDL generation.

<span style="font-size: large;"><strong>Rest Service</strong></span>

<code>RestService.php</code>

<code><span style="color: #000080;">&lt;?php</span></code>

require 'Zend/Rest/Server.php';

require_once 'MyTestService.php';

$server = new Zend_Rest_Server();

$server-&gt;setClass('MyTestService');

$server-&gt;handle();

<span style="font-size: large;"><strong>XmlRpc Service</strong></span>

<code>XmlRpcService.php</code>

<code><span style="color: #000080;">&lt;?php</span></code>

require 'Zend/XmlRpc/Server.php';

require_once 'MyTestService.php';

$server = new Zend_XmlRpc_Server();

$server-&gt;setClass('MyTestService');

echo $server-&gt;handle();

<strong>Caution</strong>: the echo on the last line is here essential!

<span style="font-size: large;"><strong>Soap Service</strong></span>

<code>SoapWebService.php</code>

<code><span style="color: #000080;">&lt;?php</span></code>

require 'MyTestService.php';

if(isset($_GET['wsdl'])) {

require 'Zend/Soap/AutoDiscover.php';

$autodiscover = new Zend_Soap_AutoDiscover();

$autodiscover-&gt;setClass('MyTestService');

$autodiscover-&gt;handle();

} else {

require 'Zend/Soap/Server.php';

$url = URL;

$server = new Zend_Soap_Server("http://localhost/SoapWebService.php?wsdl");

$server-&gt;setClass('MyTestService');

echo $server-&gt;handle();

}

What we can see here is the possibility to generate the WSDL file automaticaly. The class Zend_Soap_AutoDiscover is doing this for us. We have just to set the class that we use as service. The WSDL is now accessible under the URL <a href="http://localhost/SoapWebService.php?wsdl">http://localhost/SoapWebService.php?wsdl</a>.

<span style="font-size: large;"><strong>Client</strong></span>

Accessing the services is as easy as creating them.

<code>index.php</code>

<span style="color: #000080;"><code>&lt;?php</code></span>

require 'Zend/Rest/Client.php';

require 'Zend/XmlRpc/Client.php';

require 'Zend/Soap/Client.php';

try {

<span style="color: #008000;">// Rest</span>

$client = new Zend_Rest_Client ( "http://localhost/RestService.php" );

$result = $client-&gt;ping('test')-&gt;get();

echo 'Rest:&lt;br/&gt;';

var_dump(<code>$result</code><code>);</code>

<span style="color: #008000;">// XmlRpc</span>

$client = new Zend_XmlRpc_Client ( "<code><a href="http://localhost/">http://localhost</a></code><code>/XmlRpcService.php" );

</code><code>$result</code><code>= $client-&gt;call(''ping'', array('test'));

echo '&lt;br/&gt;&lt;br/&gt;XmlRpc:&lt;br/&gt;';

var_dump(</code><code>$result</code><code>);</code>

<span style="color: #008000;">// Soap</span>

$client = new Zend_Soap_Client("<code><a href="http://localhost/">http://localhost</a></code><code>/SoapService.php?wsdl");

</code><code>$result </code><code>= $client-&gt;ping('test');

echo '&lt;br/&gt;&lt;br/&gt;Soap:&lt;br/&gt;';

var_dump(</code><code>$result</code><code><span style="color: #000080;">);

} catch ( Exception $e ) {

echo '&lt;b style="color:#FF0000;"&gt;Error: ' . $e-&gt;getMessage () . '&lt;/b&gt;';

}</span>

</code>

As you can see, the Rest- and the Soap service are a bit more intuitive to use than the XmlRpc service. Which one is best depends on the requirements and the use of the service.</pre>
</div>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.simonstahl.com/2009/11/14/php-webservices-wth-the-zend-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
