Skip to content

Instantly share code, notes, and snippets.

@jeremi
Created December 14, 2010 13:03
Show Gist options
  • Save jeremi/740377 to your computer and use it in GitHub Desktop.
Save jeremi/740377 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//The service we want to call
Uri uri = new Uri("http://seesmic.demo.exoplatform.org/rest/private/api/v1/social/portal/people/john/activities/?format=json");
string username = "john";
string password = "gtn";
WebClientHelper helper = new WebClientHelper(null);
//We want to create an activity, so we do a POST
helper.Method = "POST";
//We do the Basic authorization
helper.Authorization = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
//We add our callback for when the response arrive
//Our call is asynchronous
helper.RequestCompleted += delegate(object sender, RequestCompletedEventArgs e)
{
string dataFromStream = string.Empty;
if (e.Error == null)
{
Console.Out.WriteLine("Activity created.");
}
else
{
Console.Error.WriteLine("An error has occured while accessing the server.");
}
};
JObject data = new JObject();
JObject message = new JObject();
JObject entity = new JObject();
entity["type"] = "note";
entity["content"] = "my new activity";
message["data"] = data;
data["entity"] = entity;
//We send our request with the new activity as payload
helper.SendRequest(uri, message.ToString());
//Just to block the program
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//The service we want to call
Uri uri = new Uri("http://seesmic.demo.exoplatform.org/rest/private/api/v1/social/portal/people/john/activities/@consumption?format=json");
string username = "john";
string password = "gtn";
WebClientHelper helper = new WebClientHelper(null);
//We want to get the list of activities
helper.Method = "GET";
//We do the Basic authorization
helper.Authorization = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
//We add our callback for when the response arrive
//Our call is asynchronous
helper.RequestCompleted += delegate(object sender, RequestCompletedEventArgs e)
{
string dataFromStream = string.Empty;
if (e.Error == null)
{
dataFromStream = GetDataFromStream(e.Response);
//We parse the response in json
JObject feed = JObject.Parse(dataFromStream);
//The response is always in the data
//we are interested by the list of activities, so we go directly to the items
foreach (JObject entry in ((JArray)feed["data"]["items"]))
{
Console.Out.WriteLine((string)entry["authors"][0]["name"] + ":");
Console.Out.WriteLine((string)entry["title"]);
Console.Out.WriteLine();
}
}
else
{
Console.Error.WriteLine("An error has occured while accessing the server.");
}
};
//We send our request
helper.SendRequest(uri, null);
//Just to block the program
Console.ReadLine();
}
static private string GetDataFromStream(Stream str)
{
byte[] buffer = new byte[str.Length];
str.Position = 0L;
str.Read(buffer, 0, (int)str.Length);
str.Position = 0L;
return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
}
}
}
using System;
using System.IO;
using System.Net;
using System.ComponentModel;
namespace ConsoleApplication1
{
//from http://facebooktoolkit.codeplex.com/
internal class WebClientHelper
{
public event EventHandler<RequestCompletedEventArgs> RequestCompleted;
HttpWebRequest _webRequest;
readonly Object _userState;
public string Method
{
get;
set;
}
public string Authorization
{
get;
set;
}
public string ContentType
{
get;
set;
}
public Uri RequestUri
{
get
{
if (_webRequest != null)
{
return _webRequest.RequestUri;
}
return null;
}
}
public WebClientHelper(Object userState)
{
_userState = userState;
Method = "GET";
}
public void SendRequest(Uri uri, string data)
{
byte[] postData = null;
if (data != null)
{
postData = System.Text.Encoding.UTF8.GetBytes(data);
}
SendRequest(uri, postData, "application/x-www-form-urlencoded");
}
/// <summary>
///
/// </summary>
/// <param name="uri"></param>
/// <param name="postData"></param>
/// <param name="contentType"></param>
public void SendRequest(Uri uri, byte[] postData, string contentType)
{
_webRequest = (HttpWebRequest)WebRequest.Create(uri);
#if !SILVERLIGHT
_webRequest.KeepAlive = true;
#endif
_webRequest.Method = Method;
if (Authorization != null)
{
_webRequest.Headers["Authorization"] = Authorization;
}
if (postData != null)
{
_webRequest.ContentType = contentType;
_webRequest.BeginGetRequestStream(BeginRequest, postData);
}
else
{
_webRequest.BeginGetResponse(BeginResponse, null);
}
}
/// <summary>
/// Writes post data to stream and begin to retrieve response from server
/// </summary>
/// <param name="ar"></param>
void BeginRequest(IAsyncResult ar)
{
using (Stream stm = _webRequest.EndGetRequestStream(ar))
{
var postData = (byte[])ar.AsyncState;
stm.Write(postData, 0, (int)postData.Length);
stm.Close();
}
_webRequest.BeginGetResponse(BeginResponse, null);
}
/// <summary>
/// Parses response from server and signals the async operation
/// </summary>
/// <param name="ar"></param>
void BeginResponse(IAsyncResult ar)
{
Stream response = null;
Exception exception = null;
try
{
using (var webResponse = this._webRequest.EndGetResponse(ar))
{
Stream stm = webResponse.GetResponseStream();
ContentType = webResponse.ContentType;
using (BinaryReader reader = new BinaryReader(stm))
{
var buffer = new byte[2048];
response = new MemoryStream();
int bytesRead;
do
{
bytesRead = reader.Read(buffer, 0, buffer.Length);
response.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
response.Position = 0;
}
stm.Close();
webResponse.Close();
}
}
catch (System.Net.WebException e)
{
exception = new Exception("An unknown exception occured. Look at innerexception for details", e);
}
catch (System.Security.SecurityException e)
{
exception = new Exception("An exception occured while downloading data. Look at innerexception for details", e);
}
if (RequestCompleted != null)
{
RequestCompleted(this, new RequestCompletedEventArgs(response, exception, _userState));
}
}
}
class RequestCompletedEventArgs : AsyncCompletedEventArgs
{
public Stream Response
{
get;
private set;
}
public RequestCompletedEventArgs(Stream response, Exception ex, Object userState)
: base(ex, false, userState)
{
Response = response;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment