Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello

Below is the code that I am using. I want to retrieve the userid and name from collection. Can anyone tell me what is correct method of retrieve id and name from the NameValueCollection.

C#
private void HandleAuthorizeTokenResponse()
    {
        string consumerKey = ConfigurationManager.AppSettings["googleConsumerKey"];
        string consumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"];
        string token = Request.QueryString["oauth_token"];
        string verifier = Request.QueryString["oauth_verifier"];
        string accessTokenEndpoint = "https://www.google.com/accounts/OAuthGetAccessToken";

        // Exchange the Request Token for an Access Token
        var oAuthConsumer = new OAuthConsumerNew();

        var accessToken = oAuthConsumer.GetOAuthAccessToken(accessTokenEndpoint, realm, consumerKey, consumerSecret, token, verifier, GetRequesttoken().TokenSecret);

        // Google Only - This method will get the email of the authenticated user
        var responseText = oAuthConsumer.GetUserInfo("https://www.googleapis.com/oauth2/v1/userinfo?alt=json", realm, consumerKey, consumerSecret, accessToken.Token, accessToken.TokenSecret);
        string queryString = responseText;
   
        NameValueCollection nvc = StringToValue(queryString.Replace("\"", ""));
        string userid = string.Empty;
        string name = string.Empty;
        
        if (nvc["id"] != "")
        {
            userid = nvc["id"].ToString();
            // NullValueException handled by user code
            name = nvc["name"].ToString();
              // NullValueException handled by user code
            Response.Write("Userid" + userid + "<br />");
            Response.Write("FName=" + name + "<br />");
        }
    }


NameValueCollection StringToValue(string queryString)
    {
        NameValueCollection queryParameters = new NameValueCollection();
        string[] querySegments = queryString.Split(',');
        foreach (string segment in querySegments)
        {
            string[] parts = segment.Split(':');
            if (parts.Length > 0)
            {
                string key = parts[0].Trim(new char[] { '?', ' ' });
                string val = parts[1].Trim();
                Response.Write(key + ":" + val);
                queryParameters.Add(key, val);
            }
        }
        return queryParameters;
    }



Thanks,
Deepak
Posted
Updated 12-Oct-11 0:31am
v3
Comments
Reiss 12-Oct-11 6:07am    
string queryString = {"id": "1234", "name": "ABC XYZ", "given_name": "ABC", "family_name": "XYZ", "link": "http://profiles.google.com/123456", "gender": "male", "locale": "en-GB"};
Slacker007 12-Oct-11 6:19am    
I removed your "non-sense" remark to the OP. You might want to make this an answer instead of a comment and help the person out. Just a thought.
Reiss 12-Oct-11 6:24am    
I am trying to ascertain whether the querystring entity should be a single string or not as the syntax supplied is incorrect
aryan2010 12-Oct-11 6:15am    
This is not a nonsense this value is returened by google
through

var responseText = oAuthConsumer.GetUserInfo("https://www.googleapis.com/oauth2/v1/userinfo?alt=json", realm, consumerKey, consumerSecret, accessToken.Token, accessToken.TokenSecret);
string queryString = responseText;
Response.Write(queryString);

then output will be like below
here their is only one difference original value is replaced by dummy text.

Now what is nonsense


{ "id": "1234", "name": "ABC XYZ", "given_name": "ABC", "family_name": "XYZ", "link": "http://profiles.google.com/1234", "gender": "male", "locale": "en-GB" }
Reiss 12-Oct-11 6:22am    
Your supplied code won't compile as is because the value you have tried to assign to querystring is not valid c# syntax

1 solution

OK: that isn't going to work - it isn't even going to compile.

C#
string queryString = {"id": "1234", "name": "ABC XYZ", "given_name": "ABC", "family_name": "XYZ", "link": "http://profiles.google.com/123456", "gender": "male", "locale": "en-GB"};
will give you a huge pile of errors - the first being that you can only use an array initializer on an array. If you want to initialize this as a single string (and I assume you are for testing) then you need:
C#
string queryString = "\"id\": \"1234\",...";
Where "..." is the rest of your string similarly handled. That will probably fix your main problem.
Then, your next problem is that your string contains both ':' as a delimiter, and ':' as a part of your string - look at the "http..." part.
If your string will always be of the form
C#
"key":"value"
separated by commas, I would be tempted to use a Regex instead of manual processing:
C#
public static Regex regex = new Regex("(?:\")(?<Key>.*?)(?:\")\\s*:\\s*(?:\")(?<Value>.*?)(?:\")",
    RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);

The MatchCollection for this should give you the groups you want.



"can you me the complete code . Try to give me perfect solution by mixing your code in my code. I got confused where should I use your code to get the desired result"


What did your last slave die of? :laugh:

C#
        public static Regex regex = new Regex("(?:\")(?<Key>.*?)(?:\")\\s*:\\s*(?:\")(?<Value>.*?)(?:\")",
                                              RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
...
            string queryString = "\"id\": \"1234\", \"name\": \"ABC XYZ\", \"given_name\": \"ABC\", \"family_name\": \"XYZ\", \"link\": \"http://profiles.google.com/123456\", \"gender\": \"male\", \"locale\": \"en-GB\"";
            MatchCollection matches = regex.Matches(queryString);
            NameValueCollection queryParameters = new NameValueCollection();
            foreach (Match match in matches)
                {
                queryParameters.Add(match.Groups["Key"].Value, match.Groups["Value"].Value);
                }
 
Share this answer
 
v2
Comments
aryan2010 12-Oct-11 7:46am    
can you me the complete code . Try to give me perfect solution by mixing your code in my code. I got confused where should I use your code to get the desired result
OriginalGriff 12-Oct-11 8:51am    
Answer updated.
But don't do that again - try it yourself and see if you can do it. You learn better that way!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900