1

I have to really ask this question as I donot know Python. Following are a few lines taken from this place. I would appreciate if someone guides me in translating the following to C#

#Step 1: Get a session key
servercontent = myhttp.request(baseurl + '/services/auth/login', 'POST',
                            headers={}, body=urllib.urlencode({'username':username, 'password':password}))[1]
sessionkey = minidom.parseString(servercontent).getElementsByTagName('sessionKey')[0].childNodes[0].nodeValue
print "====>sessionkey:  %s  <====" % sessionkey

2 Answers 2

5

I can't translate it to C#, but I can explain what this code does:

  1. Login to baseurl + '/services/auth/login' using the username and password provided.
  2. Read the contents of that URL.
  3. Parse the content for the first <sessionkey> tag, and read the value of its first child node.
Sign up to request clarification or add additional context in comments.

1 Comment

I would think that this would be completely sufficient for someone that does know C#, since they should be able to now write the equivalent. Don't see why it would even be necc to actually write out the C# anyways. +1
2

Here's a quick-n-dirty translation:

using System.Linq.Xml;
using System.Net;
using System.Collections.Generic;
using System.Web;

// ...
var client = new WebClient();
var parameters = new Dictionary<string, string> 
{ 
  { "username", username },
  { "password", password }
};

var result = client.UploadString(String.Format("{0}/services/auth/login", BaseUrl), UrlEncode(parameters));
var doc = XDocument.Load(result);  // load response into XML document (LINQ)
var key = doc.Elements("sessionKey").Single().Value // get the one-and-only <sessionKey> element.
Console.WriteLine("====>sessionkey:  {0}  <====", key);
// ...

// Utility function: 
private static string UrlEncode(IDictionary<string, string> parameters)
{
  var sb = new StringBuilder();
  foreach(var val in parameters) 
  {
    // add each parameter to the query string, url-encoding the value.
    sb.AppendFormat("{0}={1}&", val.Key, HttpUtility.UrlEncode(val.Value));
  }
  sb.Remove(sb.Length - 1, 1); // remove last '&'
  return sb.ToString();
}

This code does a check to see that the response only has one sessionKey element, otherwise it'll throw an exception if there's 0, or more than 1. Then it prints it out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.