Sample Code – Authentication in C#
The following sample code illustrates how to implement query string authentication in C#.
using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Net; using System.IO; namespace ConsoleApplication1 { class Program { private static string GetMd5Hash(string input) { MD5 md5Hasher = new MD5CryptoServiceProvider(); byte[] computedHashBytes = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < computedHashBytes.Length; i++) { sBuilder.Append(computedHashBytes[i].ToString("x2")); } return sBuilder.ToString(); } private static string GetTimeStamp() { DateTime beginUTC = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); DateTime nowUTC = DateTime.UtcNow; TimeSpan elapsedSpanUTC = nowUTC.Subtract(beginUTC); return ((long)elapsedSpanUTC.TotalMilliseconds).ToString(); } private static string GetSig(string HTTPmethod, string requestURI, string timeStamp) { string myAppId = "YOUR_APPID_HERE"; string mySecret = "YOUR_SECRET_HERE"; StringBuilder buff = new StringBuilder(); buff.Append(myAppId).Append("\n"); buff.Append(HTTPmethod).Append("\n"); buff.Append(mySecret).Append("\n"); buff.Append(timeStamp).Append("\n"); buff.Append(requestURI).Append("\n"); String src = buff.ToString().ToLower(); return GetMd5Hash(src); } private static void GetData() { HttpWebResponse httpWebResponse = null; StreamReader streamReader = null; StreamWriter streamWriter = null; try { string timeStamp = GetTimeStamp(); string webQuery = string.Format("http://apiv1.cruvee.com/search/wines/all?appId=YOUR_APPID_HERE&sig={0}×tamp={1}&fmt=html&page=1&rpp=10,", GetSig("GET", "/search/wines/all", timeStamp), timeStamp); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(webQuery); httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // Get the stream associated with the response. Stream responseStream = httpWebResponse.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. streamReader = new StreamReader(responseStream, Encoding.UTF8); streamWriter = new StreamWriter(@"c:\temp\cruvee_wines_page1.html"); streamWriter.Write(streamReader.ReadToEnd()); Console.WriteLine("File c:\\temp\\cruvee_wines_page1.html created."); } catch (Exception exception) { Console.WriteLine(exception.ToString()); } finally { if (streamWriter != null) streamWriter.Close(); if (httpWebResponse != null) httpWebResponse.Close(); if (streamReader != null) streamReader.Close(); } Console.WriteLine("Press a key to exit..."); Console.ReadKey(); } static void Main(string[] args) { GetData(); } } }
