Skip to content

Commit

Permalink
Sample code committed as start of client code.
Browse files Browse the repository at this point in the history
  • Loading branch information
btimby committed Dec 28, 2011
1 parent 8287204 commit 2870c2e
Show file tree
Hide file tree
Showing 8 changed files with 256 additions and 0 deletions.
26 changes: 26 additions & 0 deletions AssemblyInfo.cs
@@ -0,0 +1,26 @@
using System.Reflection;
using System.Runtime.CompilerServices;

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("SmartFileAPI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

[assembly: AssemblyVersion("1.0.*")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
31 changes: 31 additions & 0 deletions Main.cs
@@ -0,0 +1,31 @@
using System;

namespace SmartFileAPI {
class MainClass {
// A short function to ask the user a question and
// return their response.
private static string Prompt(string prompt) {
Console.Write(prompt);
return Console.ReadLine();
}

// Start things off in Main()
public static void Main(string[] args) {
// Ask the user for the required parameters. These will be
// passed to the API via an HTTP POST request.
string fullname = Prompt("Please enter a full name: ");
string username = Prompt("Please enter a username: ");
string password = Prompt("Please enter a password: ");
string email = Prompt("Please enter an email address: ");
try {
// Try to create the new user...
SmartFileAPI.CreateUser(fullname, username, password, email);
Console.WriteLine("Successfully created user {0}.", username);
}
catch (SmartFileException e) {
// Print the server response on failure.
Console.WriteLine("Error creating user {0}: {1}", username, e.Message);
}
}
}
}
88 changes: 88 additions & 0 deletions SmartFileAPI.cs
@@ -0,0 +1,88 @@
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Xml;
using System.Text;
using System.Collections;

namespace SmartFileAPI {
class SmartFileAPI {
// These constants are needed to access the API.
private static string API_URL = "http://app.smartfile.com/api/1";
private static string API_KEY = "api-key";
private static string API_PWD = "api-password";

// This function does the bulk of the work by performing
// the HTTP request and raising an exception for any HTTP
// status code other than 201.
private static void httpRequest(string uri, Hashtable data, string method) {
// We use the XML format for C# because there is no native JSON decoder.
string url = String.Format("{0}{1}?format=xml", API_URL, uri);
string auth = String.Format("{0}:{1}", API_KEY, API_PWD);
auth = Convert.ToBase64String(new ASCIIEncoding().GetBytes(auth));
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Headers.Add("Authorization", String.Format("Basic {0}", auth));
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = ".NET SmartFile API Sample Client";
request.KeepAlive = false;
request.Method = method;
if (method == "POST") {
string pre = "";
StringBuilder post = new StringBuilder();
foreach (string key in data.Keys) {
string val = HttpUtility.UrlEncode(data[key].ToString());
post.Append(String.Format("{0}{1}={2}", pre, key, val));
pre = "&";
}
byte[] byteData = UTF8Encoding.UTF8.GetBytes(post.ToString());
request.ContentLength = byteData.Length;
using (Stream requestStream = request.GetRequestStream()) {
requestStream.Write(byteData, 0, byteData.Length);
}
}
try {
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
return;
}
}
catch (WebException e) {
// Any HTTP status other than 2XX will land us here.
using (HttpWebResponse response = (HttpWebResponse)e.Response) {
StreamReader responseStream = new StreamReader(response.GetResponseStream());
string message = responseStream.ReadToEnd();
try {
using (XmlTextReader reader = new XmlTextReader(new System.IO.StringReader(message)))
{
bool inMessage = false;
while (reader.Read())
if (reader.Name == "message" && reader.NodeType == XmlNodeType.Element)
inMessage = true;
else if (inMessage && reader.NodeType == XmlNodeType.Text)
{
message = reader.Value;
break;
}
}
}
catch (Exception)
{ }
throw new SmartFileException(response.StatusCode, message);
}
}
}

// This function makes the User add API call. It uses the httpRequest
// function to handle the transport. Additional API calls could be supported
// simply by writing additional wrappers that create the data Hashtable and
// use httpRequest to do the grunt work.
public static void CreateUser(string fullname, string username, string password, string email) {
Hashtable data = new Hashtable();
data["name"] = fullname;
data["username"] = username;
data["password"] = password;
data["email"] = email;
httpRequest("/users/add/", data, "POST");
}
}
}
44 changes: 44 additions & 0 deletions SmartFileAPI.csproj
@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{0B790D9A-11A9-48F8-9617-5EF5C41E44C4}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>SmartFileAPI</RootNamespace>
<AssemblyName>SmartFileAPI</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Web" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Main.cs" />
<Compile Include="AssemblyInfo.cs" />
<Compile Include="SmartFileException.cs" />
<Compile Include="SmartFileAPI.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>
Binary file added SmartFileAPI.pidb
Binary file not shown.
20 changes: 20 additions & 0 deletions SmartFileAPI.sln
@@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmartFileAPI", "SmartFileAPI.csproj", "{0B790D9A-11A9-48F8-9617-5EF5C41E44C4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0B790D9A-11A9-48F8-9617-5EF5C41E44C4}.Debug|x86.ActiveCfg = Debug|x86
{0B790D9A-11A9-48F8-9617-5EF5C41E44C4}.Debug|x86.Build.0 = Debug|x86
{0B790D9A-11A9-48F8-9617-5EF5C41E44C4}.Release|x86.ActiveCfg = Release|x86
{0B790D9A-11A9-48F8-9617-5EF5C41E44C4}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
StartupItem = SmartFileAPI.csproj
EndGlobalSection
EndGlobal
23 changes: 23 additions & 0 deletions SmartFileAPI.userprefs
@@ -0,0 +1,23 @@
<Properties>
<MonoDevelop.Ide.Workspace ActiveConfiguration="Debug|x86" ctype="Workspace" />
<MonoDevelop.Ide.Workbench ActiveDocument="SmartFileAPI.cs" ctype="Workbench">
<Files>
<File FileName="Main.cs" Line="31" Column="2" />
<File FileName="SmartFileException.cs" Line="1" Column="1" />
<File FileName="SmartFileAPI.cs" Line="12" Column="44" />
</Files>
<Pads>
<Pad Id="ProjectPad">
<State expanded="True">
<Node name="SmartFileAPI" expanded="True">
<Node name="References" expanded="True" />
<Node name="SmartFileAPI.cs" selected="True" />
</Node>
</State>
</Pad>
<Pad Id="ClassPad">
<State expanded="True" selected="True" />
</Pad>
</Pads>
</MonoDevelop.Ide.Workbench>
</Properties>
24 changes: 24 additions & 0 deletions SmartFileException.cs
@@ -0,0 +1,24 @@
using System;
using System.Net;

namespace SmartFileAPI {
// A simple Exception class that can handle the HTTP
// status.
class SmartFileException : Exception {
private HttpStatusCode status;

public SmartFileException(HttpStatusCode status, string error) : base(error) {
this.status = status;
}

public override string ToString() {
return this.Message;
}

public HttpStatusCode StatusCode {
get {
return this.status;
}
}
}
}

0 comments on commit 2870c2e

Please sign in to comment.