I'm using a REST Service library with C# called RestSharp. I've been trying for too long to send information to a emailforge(newsletter service) server but i couldn't make it so far. I can post, put and get basic information, but i can't do the same with fields or lists within the Json sent.
RestClient client = new RestClient();
client.BaseUrl = "https://s3s.fr/api/rest/1/";
client.Authenticator = new HttpBasicAuthenticator(splioUser, splioPass);
var request = new RestRequest("{item}", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddUrlSegment("item", "contact");
request.AddParameter("email", "test#test.com.br");
request.AddParameter("firstname", "Jhonny");
request.AddParameter("lastname", "Test");
request.AddParameter("lang", "EN");
And that's the result:
{"email":"test#test.com.br","date":"2013-12-20 18:43:42","firstname":"Jhonny","lastname":"Test","lang":"EN","fields":[{"id":"0","name":"sexo","value":""},{"id":"1","name":"nascimento","value":""},{"id":"2","name":"cidade","value":""},{"id":"3","name":"estado","value":""},{"id":"4","name":"data altera\u00e7\u00e3o do cadastro","value":""},{"id":"5","name":"data \u00faltima compra","value":""},{"id":"6","name":"data primeira compra","value":""},{"id":"7","name":"data de criacao do cadastro","value":""},{"id":"8","name":"data de ultimo login no site","value":""}],"lists":[]}
It seems that i can't include any values between "lists" and "fields" values.
There's a manual orienting how to do it using PHP:
$universe = 'testapi';
$pass = 'MySecretAPIKEY';
$resource = ‘contact‘ ;
$email = ‘old#s3s.fr’ $service_url = "https://$universe:$pass#s3s.fr/api/rest/1/$resource/$email";
$curl = curl_init($service_url);
$query = array ( 'email' => ‘newmail#s3s.fr', 'lang' => 'de', 'fields' => array ( array ( 'id' => '0', 'value' => 'bl10'), array ( 'name' => 'field2', 'value' => 'myothercustomfield_value'), ), 'lists' => array ( array ( 'name' => 'Test Api' ), array ( 'id' => '5', 'action' => 'unsubscribe' ), ), ) ;
$qstring = json_encode($query);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_POSTFIELDS,$qstring);
curl_setopt($curl,CURLOPT_HTTPHEADER,array("Expect:"));
$curl_response = curl_exec($curl);
curl_close($curl);
var_dump($curl_response);
var_dump(json_decode($curl_response, true));
Thanks in advance!
Using RestSharp, you should use the built in json serialization. See this previous answer for an example
ADDED
Also, I find that using Fiddler or a similar tool is very useful for debugging. Fiddler requires some configuration to monitor traffic for some use cases,
Related
My project tracking system needs a bit of work. Currently, every user can assign themselves a bunch of projects and track their hours on said projects.
I'm trying to add a where condition to my list of options where people can add their hours. Currently, people can select all projects. That can be a bit tiresome with lots of projects, so I want a Where statement to limit their options to their own projects.
Here's the problematic piece of code:
.Field(new Field("ProjectEntry.IdProject")
.Options(new Options()
.Table("View_User_Project")
.Value("IdProject")
.Label("Name")
.Where("View_User_Project", "View_User_Project.IdUser", "=", idUser) // TODO Find out what's going on
)
.Validator(Validation.NotEmpty())
)
This "Where" method only takes one argument, an Action<Query> kind of argument. I've never seen an example for a Where statement with that kind of syntax.
Could someone provide me with an example?
Full DB code:
var context = HttpContext.Current;
var idUser = Utility.GetIdUser(context);
var request = context.Request;
using (var db = Utility.GetDb())
{
var editor = new Editor(db, "ProjectEntry", "IdProjectEntry")
.Model<ProjectEntryModel>("ProjectEntry")
.Model<ProjectModel>("Project")
.Field(new Field("ProjectEntry.IdProject")
.Options(new Options()
.Table("View_User_Project")
.Value("IdProject")
.Label("Name")
.Where("View_User_Project", "View_User_Project.IdUser", "=", idUser) // TODO Find out what's going on
)
.Validator(Validation.NotEmpty())
)
.Field(new Field("ProjectEntry.IdUser"))
.Field(new Field("ProjectEntry.TimeWorked")
.Validator(Validation.NotEmpty())
.Validator(Validation.Numeric())
)
.Field(new Field("ProjectEntry.TimestampWeek")
.Validator(Validation.NotEmpty())
)
.LeftJoin("Project", "Project.IdProject", "=", "ProjectEntry.IdProject")
.Where("ProjectEntry.IdUser", idUser, "=");
editor.PreCreate += (sender, e) => editor.Field("ProjectEntry.IdUser").SetValue(idUser);
var response = editor.Process(request).Data();
return Json(response);
}
A forum post that gave me a little bit of insight
Well, that was short. Turns out you need an anonymous function to edit the query object.
Example:
.Field(new Field("UserProject.IdProject")
.Options(new Options()
.Table("View_User_Project")
.Value("IdProject")
.Label("Name")
.Where((q) =>
{
q.Where("View_User_Project.IdUser", idUser);
}
)
)
.Validator(Validation.NotEmpty())
)
I am writing a C# client for a 3rd party API (I'm using the RestSharp nuget package). Their documentation contains PHP examples which I must translate to C#. Most of their samples are simple enough and I have been able to convert them to C# but I am struggling with one of them because it accepts an array of arrays. Here's the sample from their documentation:
$params = array (
'user_key' => 'X',
'client_id'=> 'X,
'label' => array(
array(
'language' => 'en_US',
'name' => 'English label',
),
array(
'language' => 'fr_CA',
'name' => 'French label',
),
),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.3rdparty.com/xxx/yyy');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apikey: YOURAPIKEY'));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
Here's what I have so far:
var labels = new Dictionary<string, string>()
{
{ "en_US", "English Label" },
{ "fr_CA", "French Label" }
};
var request = new RestRequest("/xxx/yyy", Method.POST) { RequestFormat = DataFormat.Json };
request.AddHeader("apikey", myApiKey);
request.AddParameter("user_key", myUserKey);
request.AddParameter("client_id", myClientId);
request.AddParameter("label", ???);
var client = new RestSharp.RestClient("https://api.3rdparty.com")
{
Timeout = timeout,
UserAgent = "My .NET REST Client"
};
var response = client.Execute(request);
Does anybody know how to convert the "labels" dictionary into a format that would be equivalent to PHP's http_build_query?
http_build_query($params) produces output that looks like this:
user_key=X&client_id=X&label%5B0%5D%5Blanguage%5D=en_US&label%5B0%5D%5Bname%5D=English+label&label%5B1%5D%5Blanguage%5D=fr_CA&label%5B1%5D%5Bname%5D=French+label
Which, decoded, looks like:
user_key=X&client_id=X&label[0][language]=en_US&label[0][name]=English label&label[1][language]=fr_CA&label[1][name]=French label
So, you should be able to do:
var request = new RestRequest("/xxx/yyy", Method.POST);
request.AddHeader("apikey", myApiKey);
request.AddParameter("user_key", myUserKey);
request.AddParameter("client_id", myClientId);
foreach (var item in labels.Select((pair, i) => new { index = i, language = pair.Key, name = pair.Value }))
{
request.AddParameter(string.Format("label[{0}][language]", item.index), item.language);
request.AddParameter(string.Format("label[{0}][name]", item.index), item.name);
}
Note that, from experimentation, I have noticed that RestSharp is encoding a space as %20 rather than as +. Hopefully not a problem.
You may use HttpBuildQuery that is the specular implementation of that PHP function.
I need to check the syntax OID's for LDAP attributes but I can't find any good starting point. I'm using C# and currently System.DirectoryServices.Protocols (must stay generic / non-Active Directory specific).
For example, using Apache Directory Studio against we can see that in Active Directory the "distinguishedName" attribute has syntax OID "1.3.6.1.4.1.1466.115.121.1.12".
Can anyone please kick me in the right direction?
Okay, I figured it out. I used a combination of this and this SO posts to work it out. Here it is stitched together, if any other soulds out there need it. Note that this works on Active Directory and OpenLDAP (using System.DirectoryServices.Protocols).
var ldapConnection = new LdapConnection( "hostname.tld" );
ldapConnection.AuthType = AuthType.Yours;
ldapConnection.Credential = new NetworkCredential( "username", "password", "domain" );
ldapConnection.SessionOptions.ProtocolVersion = 3;
// Find the subschema first...
var searchRequest = new SearchRequest( null, "(objectClass=*)", SearchScope.Base, "subschemasubentry" );
var searchResponse = (SearchResponse) ldapConnection.SendRequest( searchRequest );
var subSchemaArray = searchResponse.Entries[0].Attributes["subschemasubentry"].GetValues( typeof( String ) );
var subSchema = (String) subSchemaArray[0];
// Now query the LDAP server and get the attribute types
searchRequest = new SearchRequest( subSchema, "(objectClass=*)", SearchScope.Base, "attributetypes" );
searchResponse = (SearchResponse) ldapConnection.SendRequest( searchRequest );
foreach ( string attributeType in searchResponse.Entries[0].Attributes["attributeTypes"].GetValues( typeof( String ) ) )
{
// This is a chunky string, but the name and syntax OID is listed here
Console.WriteLine(attributeType);
}
I am trying to read json into my C# application from a url. When I run the application I keep getting a error:
"Additional Text encountered after finished reading JSON content: {. Path ",line 2, position 667".
This is from this URL
I checked the page and the view source and can't seem to find the problem. How do I fix this?
The JSON is derived from a php array that is json encoded and echoed:
$args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'Alcopops' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo json_encode($product);
endwhile;
wp_reset_query();
That page doesn't contain valid json. Take a look at this:
"product_type":"simple"}{"id":246,"post":
there's no comma between } and {
Edit:
The problem is with your php, rather than the c#.
Try this:
$args = array( 'post_type' => 'product', 'posts_per_page' => 200, 'product_cat' => 'Alcopops' );
$loop = new WP_Query( $args );
echo json_encode($loop->get_posts());
wp_reset_query();
use WebClient :
var json = new WebClient().DownloadString("http://cbbnideas.com/brydens-website/products/?category=Alcopops");
I am having a problem reading the following JSON output in C#. I am not too familiar with JSON syntax, but it doesn't seem to be properly formatted, or I am unclear how to properly deserialize the data:
Array (
[label] => Column_Name
[column] => column0 )
15 0
Array (
[0] => 0
[1] => Array
(
)
[2] => 0 ) {"total":0,"entities":[],"page":0}
The code used in C# is simply:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Encoding enc = Encoding.GetEncoding(1252);
StreamReader configStream = new StreamReader(response.GetResponseStream(), enc);
var configuration = configStream.ReadToEnd();
JavaScriptSerializer jSerialize = new JavaScriptSerializer();
List[] operations = jSerialize.Deserialize<List[]>(configuration);
The error I am receiving is that 'Array' is not a valid JSON primitive. Assuming the syntax is correct from the JSON output, how do I derialize the data?
Your code should work for correct JSON input. The only part of your input that's correct json is: {"total":0,"entities":[],"page":0}
In one of my Silverlight project I've do this:
using Newtonsoft.Json; //add this library to refferences
ObservableCollection<MyClass> list = JsonConvert.DeserializeObject<ObservableCollection<MyClass>>(json)
Hope this help.