- Posts: 3
- Thank you received: 0
Welcome to the LimeSurvey Community Forum
Ask the community, share ideas, and connect with other LimeSurvey users!
API - get_session_key - C#
- CSSDGS
- Topic Author
- Offline
- New Member
Less
More
1 year 7 months ago #232043
by CSSDGS
API - get_session_key - C# was created by CSSDGS
Hello,
This is my main class
string Baseurl = " xxxx.limesurvey.net/index.php/admin/remotecontrol ";
JsonRPCclient client = new JsonRPCclient(Baseurl);
client.Method = "get_session_key";
client.Parameters.Add("username", "username");
client.Parameters.Add("password", "PW");
client.Post();
string SessionKey = client.Response.result.ToString();
I'm using RPCclient.cs
using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace limesurvey
{
public class JsonRPCclient
{
private int id = 0;
/// <summary>
/// Set JSON-RPC webservice URL
/// </summary>
public string URL { set; get; }
/// <summary>
/// Set JSON-RPC method
/// </summary>
public string Method { set; get; }
/// <summary>
/// Add JSON-RPC params
/// </summary>
public JObject Parameters { set; get; }
/// <summary>
/// Results of the request
/// </summary>
public JsonRPCresponse Response { set; get; }
/// <summary>
/// Create a new object of RPCclient
/// </summary>
public JsonRPCclient()
{
Parameters = new JObject();
Response = null;
}
/// <summary>
/// Create a new object of RPCclient
/// </summary>
/// <param name="URL"></param>
public JsonRPCclient(string URL)
{
this.URL = URL;
Parameters = new JObject();
Response = null;
}
/// <summary>
/// POST the request and returns server response
/// </summary>
/// <returns></returns>
public string Post()
{
try
{
JObject jobject = new JObject();
jobject.Add(new JProperty("jsonrpc", "2.0"));
jobject.Add(new JProperty("id", ++id));
jobject.Add(new JProperty("method", Method));
jobject.Add(new JProperty("params", Parameters));
string PostData = JsonConvert.SerializeObject(jobject);
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(PostData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
request.KeepAlive = true;
request.ContentLength = bytes.Length;
Stream writeStream = request.GetRequestStream();
writeStream.Write(bytes, 0, bytes.Length);
writeStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
JsonRPCresponse Response = new JsonRPCresponse();
Response = JsonConvert.DeserializeObject<JsonRPCresponse>(readStream.ReadToEnd());
Response.StatusCode = response.StatusCode;
return Response.ToString();
}
catch (Exception e)
{
return e.ToString();
}
}
public void ClearParameters()
{
this.Parameters = new JObject();
}
}
public class JsonRPCresponse
{
public int id { set; get; }
public object result { set; get; }
public string error { set; get; }
public HttpStatusCode StatusCode { set; get; }
public JsonRPCresponse() { }
public override string ToString()
{
return "{\"id\":" + id.ToString() + ",\"result\""" + result.ToString() + "\",\"error\":" + error + ((String.IsNullOrEmpty(error)) ? "null" : "\"" + error + "\"") + "}";
}
}
}
Please tell me why i get always null error in
RPCclient.cs at line
Response = JsonConvert.DeserializeObject<JsonRPCresponse>(readStream.ReadToEnd()); ????!!!
Thanks vey much!
This is my main class
string Baseurl = " xxxx.limesurvey.net/index.php/admin/remotecontrol ";
JsonRPCclient client = new JsonRPCclient(Baseurl);
client.Method = "get_session_key";
client.Parameters.Add("username", "username");
client.Parameters.Add("password", "PW");
client.Post();
string SessionKey = client.Response.result.ToString();
I'm using RPCclient.cs
using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace limesurvey
{
public class JsonRPCclient
{
private int id = 0;
/// <summary>
/// Set JSON-RPC webservice URL
/// </summary>
public string URL { set; get; }
/// <summary>
/// Set JSON-RPC method
/// </summary>
public string Method { set; get; }
/// <summary>
/// Add JSON-RPC params
/// </summary>
public JObject Parameters { set; get; }
/// <summary>
/// Results of the request
/// </summary>
public JsonRPCresponse Response { set; get; }
/// <summary>
/// Create a new object of RPCclient
/// </summary>
public JsonRPCclient()
{
Parameters = new JObject();
Response = null;
}
/// <summary>
/// Create a new object of RPCclient
/// </summary>
/// <param name="URL"></param>
public JsonRPCclient(string URL)
{
this.URL = URL;
Parameters = new JObject();
Response = null;
}
/// <summary>
/// POST the request and returns server response
/// </summary>
/// <returns></returns>
public string Post()
{
try
{
JObject jobject = new JObject();
jobject.Add(new JProperty("jsonrpc", "2.0"));
jobject.Add(new JProperty("id", ++id));
jobject.Add(new JProperty("method", Method));
jobject.Add(new JProperty("params", Parameters));
string PostData = JsonConvert.SerializeObject(jobject);
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(PostData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
request.KeepAlive = true;
request.ContentLength = bytes.Length;
Stream writeStream = request.GetRequestStream();
writeStream.Write(bytes, 0, bytes.Length);
writeStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
JsonRPCresponse Response = new JsonRPCresponse();
Response = JsonConvert.DeserializeObject<JsonRPCresponse>(readStream.ReadToEnd());
Response.StatusCode = response.StatusCode;
return Response.ToString();
}
catch (Exception e)
{
return e.ToString();
}
}
public void ClearParameters()
{
this.Parameters = new JObject();
}
}
public class JsonRPCresponse
{
public int id { set; get; }
public object result { set; get; }
public string error { set; get; }
public HttpStatusCode StatusCode { set; get; }
public JsonRPCresponse() { }
public override string ToString()
{
return "{\"id\":" + id.ToString() + ",\"result\""" + result.ToString() + "\",\"error\":" + error + ((String.IsNullOrEmpty(error)) ? "null" : "\"" + error + "\"") + "}";
}
}
}
Please tell me why i get always null error in
RPCclient.cs at line
Response = JsonConvert.DeserializeObject<JsonRPCresponse>(readStream.ReadToEnd()); ????!!!
Thanks vey much!
Please Log in to join the conversation.
- CSSDGS
- Topic Author
- Offline
- New Member
Less
More
- Posts: 3
- Thank you received: 0
1 year 7 months ago - 1 year 7 months ago #232057
by CSSDGS
Replied by CSSDGS on topic API - get_session_key - C#
Hello again!
I did my solution: i would like to share
First: using POSTMAN to get this
Creation a console projet like below: everything works! (have to refactor my code but i get my session key and survey list)
my Program.cs
using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using RestSharp;
namespace limesurvey
{
class Program
{
private static readonly HttpClient client = new HttpClient();
static void Main(string args)
{
var client = new RestClient(" xxxx.limequery.net/admin/remotecontrol ");
var request = new RestRequest("", Method.Post);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Cookie", "PHPSESSID=e07219dc77786bfb3775003dd7e44e9c");
var body = @"{
" + "\n" +
@" ""method"": ""get_session_key"",
" + "\n" +
@" ""params"": [
" + "\n" +
@" ""username"",
" + "\n" +
@" ""PW""
" + "\n" +
@" ],
" + "\n" +
@" ""id"": 1
" + "\n" +
@"}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
Console.WriteLine(response.Content);
if (response!=null && response.Content!=null && response.Content.Length> 0)
{
var sessionKey = SessionResult.FromJson(response.Content);
// i get this: { "id":1,"result":"XiAwYJH6NyC5nFfts9l89hrZH4QouDkf","error":null}
request = new RestRequest("", Method.Post);
body = @"{
" + "\n" +
@" ""method"": ""list_surveys"",
" + "\n" +
@" ""params"": [
" + "\n" +
@" ""sessionKey"",
" + "\n" +
sessionKey.Result
+ "\n" +
@" ],
" + "\n" +
@" ""id"": 1
" + "\n" +
@"}";
var getSurveyJson = JsonConvert.SerializeObject(new { method = "list_surveys", @params = new { sessionKey.Result }, id = 1 });
request.AddParameter("application/json", getSurveyJson, ParameterType.RequestBody);
response = client.Execute(request);
}
var survey_list = response.ToString();
// I get survey list here
}
}
}
OutputSession.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Globalization;
namespace limesurvey
{
public partial class SessionResult
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("result")]
public string Result { get; set; }
[JsonProperty("error")]
public object Error { get; set; }
}
public partial class SessionResult
{
public static SessionResult FromJson(string json) => JsonConvert.DeserializeObject<SessionResult>;(json, limesurvey.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this SessionResult self) => JsonConvert.SerializeObject(self, limesurvey.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
Cheer!
Nicolas P.
I did my solution: i would like to share
First: using POSTMAN to get this
Creation a console projet like below: everything works! (have to refactor my code but i get my session key and survey list)
my Program.cs
using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using RestSharp;
namespace limesurvey
{
class Program
{
private static readonly HttpClient client = new HttpClient();
static void Main(string args)
{
var client = new RestClient(" xxxx.limequery.net/admin/remotecontrol ");
var request = new RestRequest("", Method.Post);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Cookie", "PHPSESSID=e07219dc77786bfb3775003dd7e44e9c");
var body = @"{
" + "\n" +
@" ""method"": ""get_session_key"",
" + "\n" +
@" ""params"": [
" + "\n" +
@" ""username"",
" + "\n" +
@" ""PW""
" + "\n" +
@" ],
" + "\n" +
@" ""id"": 1
" + "\n" +
@"}";
request.AddParameter("application/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
Console.WriteLine(response.Content);
if (response!=null && response.Content!=null && response.Content.Length> 0)
{
var sessionKey = SessionResult.FromJson(response.Content);
// i get this: { "id":1,"result":"XiAwYJH6NyC5nFfts9l89hrZH4QouDkf","error":null}
request = new RestRequest("", Method.Post);
body = @"{
" + "\n" +
@" ""method"": ""list_surveys"",
" + "\n" +
@" ""params"": [
" + "\n" +
@" ""sessionKey"",
" + "\n" +
sessionKey.Result
+ "\n" +
@" ],
" + "\n" +
@" ""id"": 1
" + "\n" +
@"}";
var getSurveyJson = JsonConvert.SerializeObject(new { method = "list_surveys", @params = new { sessionKey.Result }, id = 1 });
request.AddParameter("application/json", getSurveyJson, ParameterType.RequestBody);
response = client.Execute(request);
}
var survey_list = response.ToString();
// I get survey list here
}
}
}
OutputSession.cs
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Globalization;
namespace limesurvey
{
public partial class SessionResult
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("result")]
public string Result { get; set; }
[JsonProperty("error")]
public object Error { get; set; }
}
public partial class SessionResult
{
public static SessionResult FromJson(string json) => JsonConvert.DeserializeObject<SessionResult>;(json, limesurvey.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this SessionResult self) => JsonConvert.SerializeObject(self, limesurvey.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
Cheer!
Nicolas P.
Last edit: 1 year 7 months ago by holch. Reason: Pasted image deleted to get rid of "code salad"
Please Log in to join the conversation.
- CSSDGS
- Topic Author
- Offline
- New Member
Less
More
- Posts: 3
- Thank you received: 0
1 year 7 months ago #232058
by CSSDGS
Replied by CSSDGS on topic API - get_session_key - C#
Sorry about POSTMAN image.
I attached it!
Cheer!
I attached it!
Cheer!
Attachments:
Please Log in to join the conversation.