473,513 Members | 2,618 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

HttpUtility error in OAuth code

1 New Member
Ok, so I downloaded a class online (OAuthBase.cs). Every time I plug it into my project, I am getting "The name 'HttpUtility' does not exist in the current context" error.

I got this from the following site: http://oauth.googlecode.com/svn/code/csharp/OAuthBase.cs

Here is the code I am trying to use:

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Security.Cryptography;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Web;
  6.  
  7. namespace OAuth {
  8.     public class OAuthBase {
  9.  
  10.         /// <summary>
  11.         /// Provides a predefined set of algorithms that are supported officially by the protocol
  12.         /// </summary>
  13.         public enum SignatureTypes {
  14.             HMACSHA1,
  15.             PLAINTEXT,
  16.             RSASHA1
  17.         }
  18.  
  19.         /// <summary>
  20.         /// Provides an internal structure to sort the query parameter
  21.         /// </summary>
  22.         protected class QueryParameter {
  23.             private string name = null;
  24.             private string value = null;
  25.  
  26.             public QueryParameter(string name, string value) {
  27.                 this.name = name;
  28.                 this.value = value;
  29.             }
  30.  
  31.             public string Name {
  32.                 get { return name; }
  33.             }
  34.  
  35.             public string Value {
  36.                 get { return value; }
  37.             }            
  38.         }
  39.  
  40.         /// <summary>
  41.         /// Comparer class used to perform the sorting of the query parameters
  42.         /// </summary>
  43.         protected class QueryParameterComparer : IComparer<QueryParameter> {
  44.  
  45.             #region IComparer<QueryParameter> Members
  46.  
  47.             public int Compare(QueryParameter x, QueryParameter y) {
  48.                 if (x.Name == y.Name) {
  49.                     return string.Compare(x.Value, y.Value);
  50.                 } else {
  51.                     return string.Compare(x.Name, y.Name);
  52.                 }
  53.             }
  54.  
  55.             #endregion
  56.         }
  57.  
  58.         protected const string OAuthVersion = "1.0";
  59.         protected const string OAuthParameterPrefix = "oauth_";
  60.  
  61.         //
  62.         // List of know and used oauth parameters' names
  63.         //        
  64.         protected const string OAuthConsumerKeyKey = "oauth_consumer_key";
  65.         protected const string OAuthCallbackKey = "oauth_callback";
  66.         protected const string OAuthVersionKey = "oauth_version";
  67.         protected const string OAuthSignatureMethodKey = "oauth_signature_method";
  68.         protected const string OAuthSignatureKey = "oauth_signature";
  69.         protected const string OAuthTimestampKey = "oauth_timestamp";
  70.         protected const string OAuthNonceKey = "oauth_nonce";
  71.         protected const string OAuthTokenKey = "oauth_token";
  72.         protected const string OAuthTokenSecretKey = "oauth_token_secret";
  73.  
  74.         protected const string HMACSHA1SignatureType = "HMAC-SHA1";
  75.         protected const string PlainTextSignatureType = "PLAINTEXT";
  76.         protected const string RSASHA1SignatureType = "RSA-SHA1";
  77.  
  78.         protected Random random = new Random();
  79.  
  80.         protected string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
  81.  
  82.         /// <summary>
  83.         /// Helper function to compute a hash value
  84.         /// </summary>
  85.         /// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function</param>
  86.         /// <param name="data">The data to hash</param>
  87.         /// <returns>a Base64 string of the hash value</returns>
  88.         private string ComputeHash(HashAlgorithm hashAlgorithm, string data) {
  89.             if (hashAlgorithm == null) {
  90.                 throw new ArgumentNullException("hashAlgorithm");
  91.             }
  92.  
  93.             if (string.IsNullOrEmpty(data)) {
  94.                 throw new ArgumentNullException("data");
  95.             }
  96.  
  97.             byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(data);
  98.             byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);
  99.  
  100.             return Convert.ToBase64String(hashBytes);
  101.         }
  102.  
  103.         /// <summary>
  104.         /// Internal function to cut out all non oauth query string parameters (all parameters not begining with "oauth_")
  105.         /// </summary>
  106.         /// <param name="parameters">The query string part of the Url</param>
  107.         /// <returns>A list of QueryParameter each containing the parameter name and value</returns>
  108.         private List<QueryParameter> GetQueryParameters(string parameters) {
  109.             if (parameters.StartsWith("?")) {
  110.                 parameters = parameters.Remove(0, 1);
  111.             }
  112.  
  113.             List<QueryParameter> result = new List<QueryParameter>();
  114.  
  115.             if (!string.IsNullOrEmpty(parameters)) {
  116.                 string[] p = parameters.Split('&');
  117.                 foreach (string s in p) {
  118.                     if (!string.IsNullOrEmpty(s) && !s.StartsWith(OAuthParameterPrefix)) {
  119.                         if (s.IndexOf('=') > -1) {
  120.                             string[] temp = s.Split('=');
  121.                             result.Add(new QueryParameter(temp[0], temp[1]));
  122.                         } else {
  123.                             result.Add(new QueryParameter(s, string.Empty));
  124.                         }
  125.                     }
  126.                 }
  127.             }
  128.  
  129.             return result;
  130.         }
  131.  
  132.         /// <summary>
  133.         /// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
  134.         /// While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth
  135.         /// </summary>
  136.         /// <param name="value">The value to Url encode</param>
  137.         /// <returns>Returns a Url encoded string</returns>
  138.         protected string UrlEncode(string value) {
  139.             StringBuilder result = new StringBuilder();
  140.  
  141.             foreach (char symbol in value) {
  142.                 if (unreservedChars.IndexOf(symbol) != -1) {
  143.                     result.Append(symbol);
  144.                 } else {
  145.                     result.Append('%' + String.Format("{0:X2}", (int)symbol));
  146.                 }
  147.             }
  148.  
  149.             return result.ToString();
  150.         }
  151.  
  152.         /// <summary>
  153.         /// Normalizes the request parameters according to the spec
  154.         /// </summary>
  155.         /// <param name="parameters">The list of parameters already sorted</param>
  156.         /// <returns>a string representing the normalized parameters</returns>
  157.         protected string NormalizeRequestParameters(IList<QueryParameter> parameters) {            
  158.             StringBuilder sb = new StringBuilder();
  159.             QueryParameter p = null;
  160.             for (int i = 0; i < parameters.Count; i++) {
  161.                 p = parameters[i];
  162.                 sb.AppendFormat("{0}={1}", p.Name, p.Value);
  163.  
  164.                 if (i < parameters.Count - 1) {
  165.                     sb.Append("&");
  166.                 }
  167.             }
  168.  
  169.             return sb.ToString();
  170.         }
  171.  
  172.         /// <summary>
  173.         /// Generate the signature base that is used to produce the signature
  174.         /// </summary>
  175.         /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
  176.         /// <param name="consumerKey">The consumer key</param>        
  177.         /// <param name="token">The token, if available. If not available pass null or an empty string</param>
  178.         /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
  179.         /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
  180.         /// <param name="signatureType">The signature type. To use the default values use <see cref="OAuthBase.SignatureTypes">OAuthBase.SignatureTypes</see>.</param>
  181.         /// <returns>The signature base</returns>
  182.         public string GenerateSignatureBase(Uri url, string consumerKey, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string signatureType, out string normalizedUrl, out string normalizedRequestParameters) {
  183.             if (token == null) {
  184.                 token = string.Empty;
  185.             }
  186.  
  187.             if (tokenSecret == null) {
  188.                 tokenSecret = string.Empty;
  189.             }
  190.  
  191.             if (string.IsNullOrEmpty(consumerKey)) {
  192.                 throw new ArgumentNullException("consumerKey");
  193.             }
  194.  
  195.             if (string.IsNullOrEmpty(httpMethod)) {
  196.                 throw new ArgumentNullException("httpMethod");
  197.             }
  198.  
  199.             if (string.IsNullOrEmpty(signatureType)) {
  200.                 throw new ArgumentNullException("signatureType");
  201.             }
  202.  
  203.             normalizedUrl = null;
  204.             normalizedRequestParameters = null;
  205.  
  206.             List<QueryParameter> parameters = GetQueryParameters(url.Query);
  207.             parameters.Add(new QueryParameter(OAuthVersionKey, OAuthVersion));
  208.             parameters.Add(new QueryParameter(OAuthNonceKey, nonce));
  209.             parameters.Add(new QueryParameter(OAuthTimestampKey, timeStamp));
  210.             parameters.Add(new QueryParameter(OAuthSignatureMethodKey, signatureType));
  211.             parameters.Add(new QueryParameter(OAuthConsumerKeyKey, consumerKey));
  212.  
  213.             if (!string.IsNullOrEmpty(token)) {
  214.                 parameters.Add(new QueryParameter(OAuthTokenKey, token));
  215.             }
  216.  
  217.             parameters.Sort(new QueryParameterComparer());
  218.  
  219.             normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
  220.             if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
  221.             {
  222.                 normalizedUrl += ":" + url.Port;
  223.             }
  224.             normalizedUrl += url.AbsolutePath;
  225.             normalizedRequestParameters = NormalizeRequestParameters(parameters);
  226.  
  227.             StringBuilder signatureBase = new StringBuilder();            
  228.             signatureBase.AppendFormat("{0}&", httpMethod.ToUpper());
  229.             signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
  230.             signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));
  231.  
  232.             return signatureBase.ToString();
  233.         }
  234.  
  235.         /// <summary>
  236.         /// Generate the signature value based on the given signature base and hash algorithm
  237.         /// </summary>
  238.         /// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
  239.         /// <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param>
  240.         /// <returns>A base64 string of the hash value</returns>
  241.         public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm hash) {
  242.             return ComputeHash(hash, signatureBase);
  243.         }
  244.  
  245.         /// <summary>
  246.         /// Generates a signature using the HMAC-SHA1 algorithm
  247.         /// </summary>        
  248.         /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
  249.         /// <param name="consumerKey">The consumer key</param>
  250.         /// <param name="consumerSecret">The consumer seceret</param>
  251.         /// <param name="token">The token, if available. If not available pass null or an empty string</param>
  252.         /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
  253.         /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
  254.         /// <returns>A base64 string of the hash value</returns>
  255.         public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, out string normalizedUrl, out string normalizedRequestParameters) {            
  256.             return GenerateSignature(url, consumerKey, consumerSecret, token, tokenSecret, httpMethod, timeStamp, nonce, SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
  257.         }
  258.  
  259.         /// <summary>
  260.         /// Generates a signature using the specified signatureType 
  261.         /// </summary>        
  262.         /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
  263.         /// <param name="consumerKey">The consumer key</param>
  264.         /// <param name="consumerSecret">The consumer seceret</param>
  265.         /// <param name="token">The token, if available. If not available pass null or an empty string</param>
  266.         /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
  267.         /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
  268.         /// <param name="signatureType">The type of signature to use</param>
  269.         /// <returns>A base64 string of the hash value</returns>
  270.         public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, SignatureTypes signatureType, out string normalizedUrl, out string normalizedRequestParameters) {
  271.             normalizedUrl = null;
  272.             normalizedRequestParameters = null;
  273.  
  274.             switch (signatureType) {
  275.                 case SignatureTypes.PLAINTEXT:                    
  276.                     return HttpUtility.UrlEncode(string.Format("{0}&{1}", consumerSecret, tokenSecret));
  277.                 case SignatureTypes.HMACSHA1:                    
  278.                     string signatureBase = GenerateSignatureBase(url, consumerKey, token, tokenSecret, httpMethod, timeStamp, nonce, HMACSHA1SignatureType, out normalizedUrl, out normalizedRequestParameters);
  279.  
  280.                     HMACSHA1 hmacsha1 = new HMACSHA1();
  281.                     hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret)));
  282.  
  283.                     return GenerateSignatureUsingHash(signatureBase, hmacsha1);                                        
  284.                 case SignatureTypes.RSASHA1:
  285.                     throw new NotImplementedException();
  286.                 default:
  287.                     throw new ArgumentException("Unknown signature type", "signatureType");
  288.             }
  289.         }
  290.  
  291.         /// <summary>
  292.         /// Generate the timestamp for the signature        
  293.         /// </summary>
  294.         /// <returns></returns>
  295.         public virtual string GenerateTimeStamp() {
  296.             // Default implementation of UNIX time of the current UTC time
  297.             TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  298.             return Convert.ToInt64(ts.TotalSeconds).ToString();            
  299.         }
  300.  
  301.         /// <summary>
  302.         /// Generate a nonce
  303.         /// </summary>
  304.         /// <returns></returns>
  305.         public virtual string GenerateNonce() {
  306.             // Just a simple implementation of a random number between 123400 and 9999999
  307.             return random.Next(123400, 9999999).ToString();            
  308.         }
  309.  
  310.     }
  311. }
  312.  
Apr 7 '11 #1
1 2971
samueal
8 New Member
Go to Project properties->Application and
change the target framework to .Net Framework 4
May 19 '11 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

0
6776
by: sql-db2-dba | last post by:
CLI connection failed. SQL0902C. A system error (reason code="6029321") occurred. Subsequent SQL statements cannot be processed. SQLSTATE=58005. Has anyone encountered the above error? We are...
1
2220
by: Tom | last post by:
Suppose you have code structure like this: Option Explicit Dim MyVariable As Single Private Sub CallingProcedure() Call CalledProcedure() ....Do This ... End Sub Private Sub...
13
4434
by: Thelma Lubkin | last post by:
I use code extensively; I probably overuse it. But I've been using error trapping very sparingly, and now I've been trapped by that. A form that works for me on the system I'm using, apparently...
3
8681
by: JPARKER | last post by:
Our DB2 8.2 FixPak9 database running on Win2K crashed with after reporting this message SQL0902C A system error (reason code = 9") ocurred I have searched the DB2 documentation as well as the...
3
1543
by: Mark | last post by:
I'm just starting out in an introductory ASP.Net course, and am trying to run a simple program but keeping getting an error. "http://localhost/day1/listing0104.aspx" is placed in the address line...
1
5134
by: scottrm | last post by:
I want to get the file name, line number etc. in error handling code in an asp.net application. I know how to trap errors in the Global.asax and I read that you can use the stack frame from the...
3
2314
by: jonamukundu | last post by:
Hi everyone out there I have a rather funny problem. Error handling code routines do not seem to work on my laptop. I still get the default error messages when i test. One my desktop the code...
5
3411
by: GaryE | last post by:
Hello: I am having trouble linking a couple of files using the boost::filesystem. I am using MSVC 6.0. Here is an abbreviated version of my problem: foo.h: #ifndef __FOO_ #define...
2
10405
by: globomike | last post by:
Hi, can anybody tell me what the reason code 18 means in combination with a SQL0902 error? It would be helpful to know details about the reason code but I could not find any details about that...
1
1477
by: Forsi | last post by:
Hello I don't know a thing about writing VBA Codes but this forum I was able thas helped me to finally figure out how to link the pictures to a path etc on a form. Everything works fine on the...
0
7257
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7379
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7521
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5682
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5084
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4745
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3232
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1591
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.