Skip to content

Instantly share code, notes, and snippets.

@timerickson
Created April 17, 2011 07:28
Show Gist options
  • Select an option

  • Save timerickson/923823 to your computer and use it in GitHub Desktop.

Select an option

Save timerickson/923823 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//TestGistPost();
TestGistLogin();
Console.ReadKey();
}
private static void TestGistLogin()
{
var user = "[email protected]";
var password = "secretPassword";
try
{
var gistSession = GistSession.Create(user, password);
Console.WriteLine("SUCCESS!: " + gistSession);
}
catch (GistSessionException ex)
{
Console.WriteLine("FAILED: " + ex);
}
}
private static void TestGistPost()
{
var description = "abc";
var content = "One";
var ext = ".txt";
var name = "Update Test";
Gist gist = null;
try
{
gist = Gist.Create(name, description, GistTypeExts.PlainText, content);
}
catch (Exception e)
{
Console.WriteLine(e);
}
var response = Gist.LastResponse;
File.WriteAllText(@"c:\users\pengt\desktop\GistResponse.html", response);
if (gist != null)
{
Console.WriteLine(string.Format("Id: {0} Version: {1} Name: {2}", gist.Id, gist.Version, gist.Name));
}
}
}
public class Gist
{
public string Id { get; private set; }
public string Version { get; private set; }
private const string GistUriString = "https://gist.github.com/gists";
public static string LastResponse;
public string Name { get; set; }
public string Description { get; set; }
public string Content { get; set; }
public GistTypeExts TypeExt { get; private set; }
private Gist()
{
}
public static Gist Create(string name, string description, GistTypeExts type, string content)
{
LastResponse = null;
var gist = new Gist
{
Name = name,
Description = description,
TypeExt = type,
Content = content
};
var request = WebRequest.Create(GistUriString);
var ext = GistTypeExt.GetValue(gist.TypeExt);
var body =
"authenticity_key=" + Uri.EscapeDataString("fcca8a96f57b3f7ba763403626d031f7074dc15d") +
"&description=" + Uri.EscapeDataString(description) +
"&file_contents[gistfile1]=" + Uri.EscapeDataString(content) +
"&file_ext[gistfile1]=" + ext +
"&file_name[gistfile1]=" + Uri.EscapeDataString(name);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = body.Length;
var requestBytes = Encoding.UTF8.GetBytes(body);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
var responseText = string.Empty;
using (var tr = new StreamReader(responseStream))
responseText = tr.ReadToEnd();
LastResponse = responseText;
gist.ParseMetadata(responseText);
if (string.IsNullOrWhiteSpace(gist.Id))
throw new GistCreationException(string.Format("Couldn't parse Id from {0}", responseText));
return gist;
}
private void ParseMetadata(string responseText)
{
var regex = new Regex(@"<a href=""/raw/(?<Id>[0-9]+)/(?<Version>[0-9a-f]+)/(?<Name>[^""]*)"">raw</a>");
var match = regex.Match(responseText);
this.Id = match.Groups["Id"].Value;
this.Version = match.Groups["Version"].Value;
this.Name = Uri.UnescapeDataString(match.Groups["Name"].Value);
}
}
public class GistCreationException : Exception
{
public GistCreationException(string message) : base(message)
{
}
public GistCreationException(string message, Exception innerException) : base(message, innerException)
{
}
}
public enum GistTypeExts
{
ASP,
ActionScript,
Ada,
AppleScript,
Arc,
Assembly,
Batchfile,
Befunge,
BlitzMax,
Boo,
Brainfuck,
C,
CObjDump,
CSS,
CSharp,
ChucK,
Clojure,
CoffeeScript,
ColdFusion,
CommonLisp,
Cpp,
CppObjDump,
Cucumber,
Cython,
D,
DObjDump,
DarcsPatch,
Delphi,
Diff,
Duby,
Dylan,
Eiffel,
EmacsLisp,
Empty,
Erlang,
FORTRAN,
FSharp,
Factor,
GAS,
Genshi,
GentooEbuild,
GentooEclass,
GettextCatalog,
Go,
Groff,
Groovy,
HTML,
HTML_Django,
HTML_ERB,
HTML_PHP,
HaXe,
Haml,
Haskell,
INI,
IRClog,
Io,
JSON,
Java,
JavaScript,
JavaServerPages,
LLVM,
LiterateHaskell,
Lua,
Makefile,
Mako,
Markdown,
Matlab,
Max_MSP,
Mirah,
Moocode,
Myghty,
Nu,
NumPy,
OCaml,
ObjDump,
ObjectiveC,
ObjectiveJ,
PHP,
ParrotInternalRepresentation,
Perl,
PlainText,
PureData,
Python,
Pythontraceback,
R,
RHTML,
Racket,
Rawtokendata,
Rebol,
Redcode,
Ruby,
SQL,
Sass,
Scala,
Scheme,
Self,
Shell,
Smalltalk,
Smarty,
SuperCollider,
Tcl,
Tcsh,
TeX,
Text,
Textile,
VHDL,
Vala,
Verilog,
VimL,
VisualBasic,
XML,
XQuery,
XS,
YAML,
mupad,
ooc,
reStructuredText
}
public static class GistTypeExt
{
public static string GetValue(GistTypeExts ext)
{
switch (ext)
{
case GistTypeExts.ASP: return ".ascx";
case GistTypeExts.ActionScript: return ".as";
case GistTypeExts.Ada: return ".adb";
case GistTypeExts.AppleScript: return ".scpt";
case GistTypeExts.Arc: return ".arc";
case GistTypeExts.Assembly: return ".asm";
case GistTypeExts.Batchfile: return ".bat";
case GistTypeExts.Befunge: return ".befunge";
case GistTypeExts.BlitzMax: return ".bmx";
case GistTypeExts.Boo: return ".boo";
case GistTypeExts.Brainfuck: return ".b";
case GistTypeExts.C: return ".c";
case GistTypeExts.CObjDump: return ".c-objdump";
case GistTypeExts.CSS: return ".css";
case GistTypeExts.CSharp: return ".cs";
case GistTypeExts.ChucK: return ".ck";
case GistTypeExts.Clojure: return ".clj";
case GistTypeExts.CoffeeScript: return ".coffee";
case GistTypeExts.ColdFusion: return ".cfm";
case GistTypeExts.CommonLisp: return ".cl";
case GistTypeExts.Cpp: return ".cpp";
case GistTypeExts.CppObjDump: return ".cppobjdump";
case GistTypeExts.Cucumber: return ".feature";
case GistTypeExts.Cython: return ".pyx";
case GistTypeExts.D: return ".d";
case GistTypeExts.DObjDump: return ".d -objdump";
case GistTypeExts.DarcsPatch: return ".darcspatch";
case GistTypeExts.Delphi: return ".pas";
case GistTypeExts.Diff: return ".diff";
case GistTypeExts.Duby: return ".duby";
case GistTypeExts.Dylan: return ".dylan";
case GistTypeExts.Eiffel: return ".e";
case GistTypeExts.EmacsLisp: return ".el";
case GistTypeExts.Empty: return " ";
case GistTypeExts.Erlang: return ".hrl";
case GistTypeExts.FORTRAN: return ".f";
case GistTypeExts.FSharp: return ".fs";
case GistTypeExts.Factor: return ".factor";
case GistTypeExts.GAS: return ".s";
case GistTypeExts.Genshi: return ".kid";
case GistTypeExts.GentooEbuild: return ".ebuild";
case GistTypeExts.GentooEclass: return ".eclass";
case GistTypeExts.GettextCatalog: return ".po";
case GistTypeExts.Go: return ".go";
case GistTypeExts.Groff: return ".man";
case GistTypeExts.Groovy: return ".groovy";
case GistTypeExts.HTML: return ".html";
case GistTypeExts.HTML_Django: return ".mustache";
case GistTypeExts.HTML_ERB: return ".erb";
case GistTypeExts.HTML_PHP: return ".phtml";
case GistTypeExts.HaXe: return ".hx";
case GistTypeExts.Haml: return ".haml";
case GistTypeExts.Haskell: return ".hs";
case GistTypeExts.INI: return ".ini";
case GistTypeExts.IRClog: return ".weechatlog";
case GistTypeExts.Io: return ".io";
case GistTypeExts.JSON: return ".json";
case GistTypeExts.Java: return ".java";
case GistTypeExts.JavaScript: return ".js";
case GistTypeExts.JavaServerPages: return ".jsp";
case GistTypeExts.LLVM: return ".ll";
case GistTypeExts.LiterateHaskell: return ".lhs";
case GistTypeExts.Lua: return ".lua";
case GistTypeExts.Makefile: return ".mak";
case GistTypeExts.Mako: return ".mao";
case GistTypeExts.Markdown: return ".md";
case GistTypeExts.Matlab: return ".matlab";
case GistTypeExts.Max_MSP: return ".mxt";
case GistTypeExts.Mirah: return ".mir";
case GistTypeExts.Moocode: return ".moo";
case GistTypeExts.Myghty: return ".myt";
case GistTypeExts.Nu: return ".nu";
case GistTypeExts.NumPy: return ".numpy";
case GistTypeExts.OCaml: return ".ml";
case GistTypeExts.ObjDump: return ".objdump";
case GistTypeExts.ObjectiveC: return ".m";
case GistTypeExts.ObjectiveJ: return ".j";
case GistTypeExts.PHP: return ".php";
case GistTypeExts.ParrotInternalRepresentation: return ".pir";
case GistTypeExts.Perl: return ".pl";
case GistTypeExts.PlainText: return ".txt";
case GistTypeExts.PureData: return ".pd";
case GistTypeExts.Python: return ".py";
case GistTypeExts.Pythontraceback: return ".pytb";
case GistTypeExts.R: return ".r";
case GistTypeExts.RHTML: return ".rhtml";
case GistTypeExts.Racket: return ".rkt";
case GistTypeExts.Rawtokendata: return ".raw";
case GistTypeExts.Rebol: return ".rebol";
case GistTypeExts.Redcode: return ".cw";
case GistTypeExts.Ruby: return ".rb";
case GistTypeExts.SQL: return ".sql";
case GistTypeExts.Sass: return ".sass";
case GistTypeExts.Scala: return ".scala";
case GistTypeExts.Scheme: return ".sls";
case GistTypeExts.Self: return ".self";
case GistTypeExts.Shell: return ".sh";
case GistTypeExts.Smalltalk: return ".st";
case GistTypeExts.Smarty: return ".tpl";
case GistTypeExts.SuperCollider: return ".sc";
case GistTypeExts.Tcl: return ".tcl";
case GistTypeExts.Tcsh: return ".tcsh";
case GistTypeExts.TeX: return ".tex";
case GistTypeExts.Text: return ".txt";
case GistTypeExts.Textile: return ".textile";
case GistTypeExts.VHDL: return ".vhdl";
case GistTypeExts.Vala: return ".vala";
case GistTypeExts.Verilog: return ".v";
case GistTypeExts.VimL: return ".vim";
case GistTypeExts.VisualBasic: return ".bas";
case GistTypeExts.XML: return ".xml";
case GistTypeExts.XQuery: return ".xqy";
case GistTypeExts.XS: return ".xs";
case GistTypeExts.YAML: return ".yml";
case GistTypeExts.mupad: return ".mu";
case GistTypeExts.ooc: return ".ooc";
case GistTypeExts.reStructuredText: return ".rst";
default:
throw new ArgumentOutOfRangeException(ext.ToString());
}
}
}
}
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
public class GistSession
{
public string Location { get; set; }
public GistCookie Cookie { get; set; }
public string AuthenticityToken { get; set; }
private GistSession()
{
}
public static GistSession Create(string user, string password)
{
var session = new GistSession();
var response = session.GET("https://gist.github.com/login?return_to=gist");
session.AuthenticityToken = GetAuthToken(response);
if (string.IsNullOrEmpty(session.AuthenticityToken))
throw new GistSessionException("No Auth Token from Login page");
var data = new Dictionary<string, string>
{
{"authenticity_token", session.AuthenticityToken},
{"commit", "Log in"},
{"login", user},
{"password", password},
{"return_to", "gist"}
};
response = session.POST("https://gist.github.com/session", data);
session.AuthenticityToken = GetAuthToken(response);
if (string.IsNullOrEmpty(session.AuthenticityToken))
throw new GistSessionException("No Auth Token from Gist form");
return session;
}
private string GET(string uri)
{
var request = CreateRequest(uri);
return GetResponse(request);
}
private string POST(string uri, Dictionary<string, string> data)
{
var request = CreateRequest(uri);
var body = GetPostBody(data);
var requestBytes = Encoding.UTF8.GetBytes(body);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestBytes.Length;
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
return GetResponse(request);
}
private static string GetPostBody(Dictionary<string, string> values)
{
var sb = new StringBuilder();
foreach (var key in values.Keys)
{
if (sb.Length > 0)
sb.Append("&");
sb.Append(string.Format("{0}={1}", key, Uri.EscapeDataString(values[key])));
}
return sb.ToString();
}
private static string GetAuthToken(string responseText)
{
var regex = new Regex(@"<input name=""authenticity_token"" type=""hidden"" value=""(?<AuthToken>[0-9a-f]+)"" />");
var match = regex.Match(responseText);
return match.Groups["AuthToken"].Value;
}
private HttpWebRequest CreateRequest(string uri)
{
var request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Referer = Location;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Headers["Accept-Language"] = "en-us,en;q=0.5";
//request.Headers["Accept-Encoding"] = "gzip, deflate";
request.Headers["Accept-Charset"] = "ISO-8859-1,utf-8;q=0.7,*;q=0.7";
request.Headers["Keep-Alive"] = "115";
request.KeepAlive = true;
if (Cookie != null)
request.Headers[HttpRequestHeader.Cookie] = Cookie.ToString();
request.AllowAutoRedirect = false;
return request;
}
private string GetResponse(HttpWebRequest request)
{
var response = request.GetResponse();
Location = request.RequestUri.ToString();
var setCookie = response.Headers[HttpResponseHeader.SetCookie];
if (setCookie != null)
Cookie = new GistCookie(setCookie);
var redirect = response.Headers[HttpResponseHeader.Location];
if (!string.IsNullOrWhiteSpace(redirect))
{
var redirectRequest = CreateRequest(redirect);
return GetResponse(redirectRequest);
}
var responseStream = response.GetResponseStream();
var responseText = string.Empty;
using (var tr = new StreamReader(responseStream))
responseText = tr.ReadToEnd();
return responseText;
}
}
public class GistCookie
{
public string csrf_id { get; set; }
public string _gh_sess { get; set; }
public string path { get; set; }
public string Expires { get; set; }
public string secure { get; set; }
public string HttpOnly { get; set; }
public NameValueCollection Values { get; set; }
public GistCookie(string setCookie)
{
Values = new NameValueCollection();
var pairs = setCookie.Split(new char[]{',', ';'}).Select(x => x.Trim());
foreach (var pair in pairs)
{
var parts = pair.Split('=');
var name = parts[0].Trim();
string value = string.Empty;
if (parts.Length == 2)
value = parts[1].Trim();
if (name == "csrf_id")
csrf_id = value;
else if (name == "_gh_sess")
_gh_sess = value;
else if (name == "path")
path = value;
else if (name == "Expires")
Expires = value;
else if (name == "secure")
secure = value;
else if (name == "HttpOnly")
HttpOnly = value;
}
}
public override string ToString()
{
var sb = new StringBuilder();
AppendValue(sb, "csrf_id", csrf_id);
AppendValue(sb, "_gh_sess", _gh_sess);
AppendValue(sb, "path", path);
AppendValue(sb, "Expires", Expires);
AppendValue(sb, "secure", secure);
AppendValue(sb, "HttpOnly", HttpOnly);
return sb.ToString();
}
private static void AppendValue(StringBuilder sb, string name, string value)
{
if (sb.Length > 0)
sb.Append(";");
sb.Append(name);
if (value != null)
sb.Append("=" + value);
}
}
public class GistSessionException : Exception
{
public GistSessionException()
{
}
public GistSessionException(string message) : base(message)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment