<?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; Programming</title>
	<atom:link href="http://blog.simonstahl.com/category/programming/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>Parallel Image loading performance in Android</title>
		<link>http://blog.simonstahl.com/2011/03/22/parallel-image-loading-performance-in-android/</link>
		<comments>http://blog.simonstahl.com/2011/03/22/parallel-image-loading-performance-in-android/#comments</comments>
		<pubDate>Tue, 22 Mar 2011 09:25:35 +0000</pubDate>
		<dc:creator>Simon</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[AsyncTask]]></category>
		<category><![CDATA[image download]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://blog.simonstahl.com/?p=166</guid>
		<description><![CDATA[I just ran into the problem that I have to load a whole bunch of images in an Android application, so I wondered about the performance of parallel image loading and how many images can be loaded simultaneously. Therefore I wrote a small benchmark app that loads about 100 images (each between 4 and 7 KB) from [...]]]></description>
			<content:encoded><![CDATA[<p>I just ran into the problem that I have to load a whole bunch of images in an Android application, so I wondered about the performance of parallel image loading and how many images can be loaded simultaneously. Therefore I wrote a small benchmark app that loads about 100 images (each between 4 and 7 KB) from a webpage. I admit, the app could be written better, but for my purpose it should be fine.</p>
<p>I measured the time in seconds that it took to load all images <strong>without </strong>displaying them in a View. 0 Threads means that all images were loaded in a sequence. A Thread count above 0 means that I created a new AsyncTask for each image and ran n of them at the same time.</p>
<p><a href="http://blog.simonstahl.com/wp-content/uploads/2011/03/ImageLoading.png"><img class="aligncenter size-full wp-image-167" title="Parallel image loading performance" src="http://blog.simonstahl.com/wp-content/uploads/2011/03/ImageLoading.png" alt="" width="516" height="387" /><span id="more-166"></span></a></p>
<h3>Emulator Eclair 2.1</h3>
<p>Eclair did well in the emulator between around 3 and 40 simultaneous downloads. It became pretty critical above 50 though. When i tried 100 downloads at the same time, it just stopped to work. The app did not crash, but the downloads seemed to stop completely and no progress was visible anymore.</p>
<h3>Emulator Gingerbread 2.3</h3>
<p>Interestingly, the emulator with Gingerbread did way worse then Eclair, but it was OK until around 30 parallel downloads. Gingerbread even had problems to create the AsyncTasks. Even when I tried 100 parallel downloads, I could never create and run more than 75 AsyncTasks at the same time. At least the app ran until the end, but the used time for 100 parallel downloads is just beyond the acceptable.</p>
<h3>Nexus One Gingerbread 2.3.3 (T-Mobile)</h3>
<p>Well, the difference from the emulator to my Nexus One was impressive. I got the best result with 20 simultaneous downloads in 7 seconds, but the whole range from 3 to 50 parallel downloads was fine and never over 11 seconds. I think that is a pretty good time.</p>
<p>At the end I would suggest not to go over around 20 or 30 simultaneous downloads. In that way it&#8217;s still tolerable in the emulator as well as on phones with slower download rates.</p>
<p>It would be interesting though to see similar performance tests with other phones and carriers.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.simonstahl.com/2011/03/22/parallel-image-loading-performance-in-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Login to the Foursquare API v2 from Android with OAuth</title>
		<link>http://blog.simonstahl.com/2011/03/16/login-with-oauth-to-the-foursquare-api-v2-from-android/</link>
		<comments>http://blog.simonstahl.com/2011/03/16/login-with-oauth-to-the-foursquare-api-v2-from-android/#comments</comments>
		<pubDate>Wed, 16 Mar 2011 07:50:42 +0000</pubDate>
		<dc:creator>Simon</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Social]]></category>
		<category><![CDATA[Foursquare]]></category>
		<category><![CDATA[OAuth]]></category>

		<guid isPermaLink="false">http://blog.simonstahl.com/?p=147</guid>
		<description><![CDATA[Once you figured out how OAuth works, you might ask yourself how this principle works from within a native Android app. It&#8217;s actually easier then expected at first. There exist some libraries that can make our life somehow easier, but I decided not to use any of them and to do everything from scratch. This [...]]]></description>
			<content:encoded><![CDATA[<p>Once you figured out how OAuth works, you might ask yourself how this principle works from within a native Android app. It&#8217;s actually easier then expected at first. There exist some libraries that can make our life somehow easier, but I decided not to use any of them and to do everything from scratch.</p>
<p><strong>This is the OAuth workflow for Foursquare:</strong></p>
<ul>
<li>A call to the Foursquare server is made with the client id and a redirect URL (has to be in a browser)</li>
<li>The user accepts the access request of the application</li>
<li>Foursquare calls the redirect URL with special code as parameter</li>
<li>The Foursquare server has to be called again with the client id, client secret, the code and the redirect URL (not in the browser anymore)</li>
<li>Foursquare returns now the access token which has to be saved by the app</li>
<li>Further calls to the Foursquare API can be made with the token</li>
</ul>
<p><span id="more-147"></span>The only problem in this workflow is how we can make the first call in the browser and then return to our app.</p>
<p>OK, we&#8217;re going to register out app first as an OAuth Consumer at Foursquare. Define the Callback URL as &#8220;simontest-android-app://&#8221;. You can do so <a title="Foursquare OAuth Consumer registration" href="https://foursquare.com/oauth/">here</a>.</p>
<p>Now, we create a new Android project and <strong>give it the INTERNET permission</strong>.</p>
<p>Then open the Manifest file and add the following filter to the &lt;application&gt; tag:</p>
<pre class="brush:xml">&lt;application android:icon="@drawable/icon" android:label="@string/app_name"&gt;
	&lt;activity android:name=".LoginTest" android:label="@string/app_name"&gt;
		&lt;intent-filter&gt;
			&lt;action android:name="android.intent.action.MAIN" /&gt;
			&lt;category android:name="android.intent.category.LAUNCHER" /&gt;
		&lt;/intent-filter&gt;

		&lt;!-- Add this filter --&gt;
		&lt;intent-filter&gt;
 			&lt;action android:name="android.intent.action.VIEW" /&gt;
 			&lt;category android:name="android.intent.category.DEFAULT" /&gt;
 			&lt;category android:name="android.intent.category.BROWSABLE" /&gt;
 			&lt;data android:scheme="simontest-android-app" /&gt;
 		&lt;/intent-filter&gt;

 	&lt;/activity&gt;
&lt;/application&gt;</pre>
<p>This maps the schema &#8220;simontest-android-app&#8221; to this activity.</p>
<p>Now it&#8217;s time to start the coding. Add a button or something to your UI and add a click listener to it, which calls this method:</p>
<pre class="brush:java">private void loginToForsquare() {
	// Call the webbrowser with the Foursquare OAuth login URL
	Intent intent = new Intent(Intent.ACTION_VIEW);
	intent.setData(
	      Uri.parse(
	    		  "https://foursquare.com/oauth2/authenticate" +
	    		  "?client_id=" +CLIENT_ID +
	    		  "&amp;response_type=code" +
	    		  "&amp;redirect_uri=simontest-android-app://"));
	startActivity(intent);
}</pre>
<p>This will open the browser where the user can accept or deny our app to access his Foursquare data. After that the browser will automatically be redirected to the Callback URL &#8220;simontest-android-app://&#8221; which we have previously mapped to our activity. The activity will be called and we can check for the expected parameter in the onResume() method:</p>
<pre class="brush:java">public void onResume() {
	super.onResume();

    // extract the OAUTH access token if it exists
    Uri uri = this.getIntent().getData();
    if(uri != null) {
    	String code = null;

    	// Check if ther is a parameter called "code"
    	if((code = uri.getQueryParameter("code")) != null){

			try {
				// Call Foursquare again to get the access token
				JSONObject tokenJson = executeHttpGet(
						"https://foursquare.com/oauth2/access_token" +
						"?client_id=" + CLIENT_ID +
						"&amp;client_secret=" + CLIENT_SECRET +
						"&amp;grant_type=authorization_code" +
						"&amp;redirect_uri=simontest-android-app://" +
						"&amp;code=" + code);

				String token = tokenJson.getString("access_token");

				// TODO save token

				// Get userdata of myself
				JSONObject userJson = executeHttpGet(
						"https://api.foursquare.com/v2/" +
						"users/self" +
						"?oauth_token=" +token);

				// Get return code
				int returnCode = Integer.parseInt(userJson.getJSONObject("meta").getString("code"));

				// 200 = OK
				if(returnCode == 200){
					// output data
					Log.i("LoginTest", userJson.getJSONObject("response").getJSONObject("user").toString());
				}else{
					Toast.makeText(this, "Wrong return code: " +code, Toast.LENGTH_SHORT).show();
				}
			} catch (Exception exp) {
				Log.e("LoginTest", "Login to Foursquare failed", exp);
			}
    	}else if((code = uri.getQueryParameter("error")) != null){
    		Toast.makeText(this, code, Toast.LENGTH_SHORT).show();
    	}else{
    		Toast.makeText(this, "Unknown login error", Toast.LENGTH_SHORT).show();
    	}
    }
}

// Calls a URI and returns the answer as a JSON object
private JSONObject executeHttpGet(String uri) throws Exception{
	HttpGet req = new HttpGet(uri);

	HttpClient client = new DefaultHttpClient();
	HttpResponse resLogin = client.execute(req);
	BufferedReader r = new BufferedReader(
			new InputStreamReader(resLogin.getEntity()
					.getContent()));
	StringBuilder sb = new StringBuilder();
	String s = null;
	while ((s = r.readLine()) != null) {
		sb.append(s);
	}

	return new JSONObject(sb.toString());
}</pre>
<p>And that is already everything. You just might wanna save the token after you&#8217;ve got it so you don&#8217;t have to login to Foursquare the next time the user starts your app.</p>
<p>Happy Coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.simonstahl.com/2011/03/16/login-with-oauth-to-the-foursquare-api-v2-from-android/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<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[Note: This tutorial is for the Foursquare API V1. A version for v2 can be found here. 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 [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Note: This tutorial is for the Foursquare API V1. A version for v2 can be found <a title="Login with OAuth to the Foursquare API v2 from Android" href="http://blog.simonstahl.com/2011/03/16/login-with-oauth-to-the-foursquare-api-v2-from-android/">here</a>.</strong></p>
<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>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>
		<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 [...]]]></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>

