I want to create Webinar in GoToWebinar using Citrix API. I am having following code:
public class CreateWebinarTime
{
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
}
public class NewWebinar
{
public string subject { get; set; }
public string description { get; set; }
public List<CreateWebinarTime> Times { get; set; }
public string timeZone { get; set; }
}
string uri = #"https://api.citrixonline.com/G2W/rest/organizers/[ORGKEY]/webinars";
CreateWebinarTime t = new CreateWebinarTime();
t.StartTime = DateTime.Now.AddDays(2);
t.EndTime = t.StartTime.AddHours(2);
List<CreateWebinarTime> tempList = new List<CreateWebinarTime>();
tempList.Add(t);
var newWebinar = new NewWebinar
{
subject="Webinar Test",
description="This is a test webinar.. Will be deleted soon",
Times = tempList,
timeZone = "Asia/Calcutta"
};
JavaScriptSerializer ser = new JavaScriptSerializer();
string json = ser.Serialize(newWebinar);
WebClient client = new WebClient();
client.Headers = new WebHeaderCollection();
client.Headers.Add("Accept", "application/json");
client.Headers.Add("Content-type", "application/json");
client.Headers.Add("Authorization", string.Format("OAuth oauth_token={0}", OauthToken));
string resp = client.UploadString(uri, "POST", json);
It is showing me error "The webinar subject, start or end time are missing" even though I am passing value. I am sure there is no problem with subject, so there is problem with time.
The json created is: {"subject":"Webinar Test","description":"This is a test webinar.. Will be deleted soon","Times":[{"StartTime":"/Date(1424233883641)/","EndTime":"/Date(1424241083641)/"}],"timeZone":"Asia/Calcutta"}
Please help me to fix this.
I solved it myself.
Json is case sensititve and I made mistake over there.
Used 'Times' instead of 'times', 'StartTime' instead of 'startTime' and 'EndTime' instead of 'endTime'
Related
I've ran into a problem with RestSharp. I need to make a POST call but with the quotation marks it doesn't work.
The JSON needs to look like this:
{
"api_key": "<api key>",
"controller": "invoice",
"action": "add",
"DebtorCode": "DB10000",
"Term": 14,
"InvoiceLines": [{"ProductCode":"P0001","Number":15},{"ProductCode":"P0002","Number":15},{"ProductCode":"P0003","Number":15}]
}
But when I send my request it is received as this: causing it to fail.
{
"api_key": "<api key>",
"controller": "invoice",
"action": "add",
"DebtorCode": "DB10000",
"Term": "14",
"InvoiceLines": "[{\"ProductCode\":\"P0001\",\"Number\":15},{\"ProductCode\":\"P0002\",\"Number\":15},{\"ProductCode\":\"P0003\",\"Number\":15}]"
}
My code for this call is the following:
var newInvoice = new InvoiceToSend();
newInvoice.DebtorCode = invoiceItem.DebtorCode;
newInvoice.Term = Convert.ToInt32(invoiceItem.Term);
newInvoice.InvoiceLines = new List<InvoiceLines>();
for (int i = 0; i < invoiceItem.InvoiceLines.Count; i++)
{
var newLine = new InvoiceLines();
newLine.Number = Convert.ToInt32(invoiceItem.InvoiceLines[i].Number);
newLine.ProductCode = invoiceItem.InvoiceLines[i].ProductCode;
newInvoice.InvoiceLines.Add(newLine);
}
object invoiceLines = JsonConvert.SerializeObject(newInvoice.InvoiceLines);
var request = new RestRequest(Method.POST)
{
AlwaysMultipartFormData = true
};
request.AddParameter("api_key", _options.ApiKey, ParameterType.GetOrPost);
request.AddParameter("controller", "invoice", ParameterType.GetOrPost);
request.AddParameter("action", "add", ParameterType.GetOrPost);
request.AddParameter("DebtorCode", newInvoice.DebtorCode);
request.AddParameter("Term", newInvoice.Term);
request.AddParameter("InvoiceLines", invoiceLines);
var response = Client.Execute(request);
Now i've seen a number of posts all over the internet saying you need to use AddBody or AddJsonBody instead of the AddParameter, but the receiver of my POST call doesn't accept "application/json" as a name, so that isn't working.
Is it possible with RestSharp to achieve what I want or do I have to find an alternative? If so, can you point me in the right direction?
Cheers and thanks in advance!
I've figured it out. Here's the answer if anyone ever stumbles acros the same issue:
I stopped trying to fix it with RestSharp. Instead I used HttpClient(). I added the api_key, controller and action to the InvoiceToSend model;
public class InvoiceToSend
{
public string api_key { get; set; }
public string controller { get; set; }
public string action { get; set; }
public string DebtorCode { get; set; }
public int Term { get; set; }
public List<InvoiceLines> InvoiceLines { get; set; }
}
public class InvoiceLines
{
public string ProductCode { get; set; }
public int Number { get; set; }
}
Then filled it with the data i needed;
var newInvoice = new InvoiceToSend();
newInvoice.api_key = _options.ApiKey;
newInvoice.controller = "invoice";
newInvoice.action = "add";
newInvoice.DebtorCode = invoiceItem.DebtorCode;
newInvoice.Term = Convert.ToInt32(invoiceItem.Term);
newInvoice.InvoiceLines = new List<InvoiceLines>();
for (int i = 0; i < invoiceItem.InvoiceLines.Count; i++)
{
var newLine = new InvoiceLines();
newLine.Number = Convert.ToInt32(invoiceItem.InvoiceLines[i].Number);
newLine.ProductCode = invoiceItem.InvoiceLines[i].ProductCode;
newInvoice.InvoiceLines.Add(newLine);
}
Then made the POST call using HttpClient():
var client = new HttpClient();
var json = JsonConvert.SerializeObject(newInvoice);
var data = new StringContent(json);
var response = await client.PostAsync(_options.BaseUrl, data);
Hope I can help someone with this in the future ;)
I am trying to post a contect to my server.
This is how I have been doing it for the past and it was working until I had to use objects besides strings.
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(authType, tokens);
var postParams = new Dictionary<string, object>();
postParams.Add("string", string);
postParams.Add("int", string);
postParams.Add("datetime", DateTime);
postParams.Add("datetime", DateTime);
postParams.Add("Match", Match);
postParams.Add("TicketId", token);
using (var postContent = new FormUrlEncodedContent(postParams.ToDictionary()))
{
var myContent = JsonConvert.SerializeObject(postParams);
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
using (HttpResponseMessage response = await client.PostAsync(#"http://url/api", byteContent))
{
response.EnsureSuccessStatusCode(); // Throw if httpcode is an error
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
var Json = JsonConvert.DeserializeObject<bool>(result);
return Json;
}
}
}
}
And this is how my request is supposed to be.
methode: POST
object: {
"title":"test-ticket-2",
"detail": "Description test create ticket in prod",
"dateStart": "2019-10-06",
"dateEnd": "2019-10-12",
"ratio": "2.15",
"matchResult": "2",
"matchs": [
{
"Teams": "Test-match-1",
"Proposal": "3x",
"DateStart": "2019-10-06 18:00",
"DateEnd": "2019-10-06 20:00",
"Payout": "0.6"
}
]
I have no idea IF and HOW I can add Objects other than string and make the request.
Any ideas?
Edit: Match looks like this
public class Match
{
public int Id { get; set; }
public string Teams { get; set; }
public string MatchResults { get; set; }
public string Proposal { get; set; }
public string Payout { get; set; }
public DateTime? DateStart { get; set; }
public DateTime? DateEnd { get; set; }
public Uri Ball { get; set; }
public int TicketId { get; set; }
}
HOW I can add Objects other than string and make the request. Any
ideas?
using (HttpClient httpclient = new HttpClient())
{
Models.ApplicationUser applicationUser = new ApplicationUser();
string serialized = Newtonsoft.Json.JsonConvert.SerializeObject(applicationUser);
StringContent stringContent = new StringContent(serialized);
httpclient.PostAsync("url", stringContent);
}
Hope you want to do something like this
I am calling the API for creating a meeting on a fixed date & time. I am using Microsoft Graph API for this. Here is the URL
var url = "https://graph.microsoft.com/v1.0/me/events";
I have taken care of the Authentication part and my code does the following thing to send the JSON response to the API
private async void sendInvites_Click(object sender, RoutedEventArgs e)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
var url = "https://graph.microsoft.com/v1.0/me/events";
CIBC.Models.SendMeetingInvites.RootObject obj = new CIBC.Models.SendMeetingInvites.RootObject();
CIBC.Models.SendMeetingInvites.Location loc = new CIBC.Models.SendMeetingInvites.Location();
loc.displayName = GlobalVariables.MeetingRoomName;
//loc.RoomEmailAddress = GlobalVariables.meetingRoomEmailID.ToString();
obj.subject = "Maths";
CIBC.Models.SendMeetingInvites.Body body = new CIBC.Models.SendMeetingInvites.Body();
body.content = "Its a booking for follow up meeting";
body.contentType = "HTML";
obj.body = body;
List<CIBC.Models.SendMeetingInvites.Attendee> attens = new List<Models.SendMeetingInvites.Attendee>();
for(int i=0;i<GlobalVariables.NumberOfParticipant.Count;i++)
{
CIBC.Models.SendMeetingInvites.EmailAddress email = new CIBC.Models.SendMeetingInvites.EmailAddress();
CIBC.Models.SendMeetingInvites.Attendee atten = new CIBC.Models.SendMeetingInvites.Attendee();
email.address = GlobalVariables.NumberOfParticipant[i].ParticipantADdress;
atten.emailAddress = email;
atten.type = "Required";
attens.Add(atten);
}
CIBC.Models.SendMeetingInvites.Start start = new CIBC.Models.SendMeetingInvites.Start();
start.dateTime = GlobalVariables.sendMeetingInviteStartDate;
start.timeZone = "UTC";
obj.start = start;
CIBC.Models.SendMeetingInvites.End end = new CIBC.Models.SendMeetingInvites.End();
end.dateTime = GlobalVariables.sendMeetingInviteEndTime;
end.timeZone = "UTC";
obj.end = end;
obj.attendees = attens;
obj.location = loc;
string postBody = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
// var postBody1 = "{'Subject':'Testing Organizer - 12','Location':{'DisplayName':'Some place'}," +
//"'Start': {'DateTime': '2016-07-15T15:00:00.0000000', 'TimeZone':'UTC'}," +
//"'End': {'DateTime': '2016-07-15T15:30:00.0000000', 'TimeZone':'UTC'}," +
//"'Body':{'Content': 'This is a test of Grap API.', 'ContentType':'Text'}," +
//"'IsOrganizer':'False','Organizer':{'EmailAddress': " + "{'Address':'organizer#some.com'} }}";
// var requestString = #"{"subject":"My event","start":{"dateTime":"2017-09-25T07:44:27.448Z","timeZone":"UTC"},"end":{"dateTime":"2017-10-02T07:44:27.448Z","timeZone":"UTC"}}"";
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer",GlobalVariables.Token);
request.Content = new StringContent(postBody, UTF8Encoding.UTF8, "application/json");
response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{ }
// return await response.Content.ReadAsStringAsync();
else
{
}
//return "";
}
Here is the class file that I am using to pass to the HTTPResponse Message
namespace CIBC.Models.SendMeetingInvites
{
public class Body
{
public string contentType { get; set; }
public string content { get; set; }
}
public class Start
{
public DateTime dateTime { get; set; }
public string timeZone { get; set; }
}
public class End
{
public DateTime dateTime { get; set; }
public string timeZone { get; set; }
}
public class Location
{
public string displayName { get; set; }
//public string RoomEmailAddress { get; set; }
}
public class EmailAddress
{
public string address { get; set; }
public string name { get; set; }
}
public class Attendee
{
public EmailAddress emailAddress { get; set; }
public string type { get; set; }
}
public class RootObject
{
public string subject { get; set; }
public Body body { get; set; }
public Start start { get; set; }
public End end { get; set; }
public Location location { get; set; }
public List<Attendee> attendees { get; set; }
}
}
My requirement is to send a meeting invite to all the users and also mentioning the Room Details like Name& Email ID of the room.
I tried adding a RoomEmail address in the Request as under The Location class
public string RoomEmailAddress { get; set; }
When I tested this using Microsoft Graph Explorer website , i got the error message
{
"error": {
"code": "RequestBodyRead",
"message": "The property 'RoomEmailAddress' does not exist on type 'Microsoft.OutlookServices.Location'. Make sure to only use
property names that are defined by the type or mark the type as open
type.",
"innerError": {
"request-id": "1883d87d-a5d6-4357-a699-7c112da0e56b",
"date": "2017-09-26T12:03:50"
}
} }
How do I make sure that whenever I create a meeting request , I can assign a room to it?
Currently I am just able to pass DisplayName while sending the Request to the URL.
Once I remove the Email Address property (I added myself ), the code returns Success.
Any workarounds so that I can send the room email address also so that the room also receives a copy of the meeting invite ?
Add the room as an attendee with "type": "Resource". Then add the room's display name in the location property.
I am just beginning developing using RestSharp and have hit an early roadblock. I think once I understand this simple, but key, concept, I should be off and running. I need to return an Access Token before making my standard calls later. I have set up the following classes, generated from json2csharp.com:
public class AccessToken
{
public string Instance_Url { get; set; }
public string Token { get; set; }
public string Expiration_date { get; set; }
public string Refresh_Token { get; set; }
}
public class RootObject
{
public AccessToken Access_Token { get; set; }
}
I have coded the following on a button click:
var tokenclient = new RestClient();
tokenclient.BaseUrl = "https://url";
tokenclient.Authenticator = new HttpBasicAuthenticator("username", "password");
var tokenrequest = new RestRequest(Method.GET);
tokenrequest.RequestFormat = DataFormat.Json;
IRestResponse tokenresponse = tokenclient.Execute(tokenrequest);
var content = tokenresponse.Content;
RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer();
var des = deserial.Deserialize<AccessToken>(tokenresponse);
I am able to return the following JSON as a string:
{
"Access_Token": {
"Instance_Url": "https://url",
"Token": "StringToken",
"Expiration_date": "9/30/2015 6:15:27 PM",
"Refresh_Token": "StringToken"
}
}
However, when I pull des.Token, it returns a blank value. Can somebody kindly point out my error?
using Newtonsoft.Json;
var response = client.DownloadString(url + queryString);
ResponseModel<string> dataResponse = new ResponseModel<string>();
if (!string.IsNullOrEmpty(response))
{
dataResponse = JsonConvert.DeserializeObject<ResponseModel<string>>(response);
}
var responseFromServer =
// lines split for readability
"{\"flag\":true,\"message\":\"\",\"result\":{\"ServicePermission\":true,"
+ "\"UserGroupPermission\":true}}";
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var responseValue = serializer.DeserializeObject(responseFromServer);
responseFromServer value is get a webservice, and then how to get the JSON string value, such as "flag","Servicepermission"??
affix: i'm sorry, using c# to do this.
Note: The JavaScriptSerializer is actually the slowest JSON Serializer I've ever benchmarked. So much so I've had to remove it from my benchmarks because it was taking too long (>100x slower).
Anyway this easily solved using ServiceStack.Text's JSON Serializer:
var response = JsonSerializer.DeserializeFromString<Dictionary<string,string>>(responseFromServer);
var permissions = JsonSerializer.DeserializeFromString<Dictionary<string,string>>(response["result"]);
Console.WriteLine(response["flag"] + ":" + permissions["ServicePermission"]);
For completeness this would also work with ServiceStack.Text.JsonSerializer:
public class Response
{
public bool flag { get; set; }
public string message { get; set; }
public Permisions result { get; set; }
}
public class Permisions
{
public bool ServicePermission { get; set; }
public bool UserGroupPermission { get; set; }
}
var response = JsonSerializer.DeserializeFromString<Response>(responseFromServer);
Console.WriteLine(response.flag + ":" + response.result.ServicePermission);
if u are using jQuery u can do this
var json=jQuery.parseJSON(responseFromServer);
//acess
alert(json.ServicePermission);
if you are asing microsoft ajax do this
var json=Sys.Serialization.JavaScriptSerializer.deserialize(responseFromServer,true);
//acess
alert(json.ServicePermission);
in c# like php i have'nt seen any method that converts json to object on the fly. To do conversions in c# you must first create a class for this.
For your case you can do like this
//define classes
public class Response
{
public bool flag { get; set; }
public string message { get; set; }
public Permisions result { get; set; }
}
public class Permisions
{
public bool ServicePermission { get; set; }
public bool UserGroupPermission { get; set; }
}
var responseFromServer =
// lines split for readability
"{\"flag\":true,\"message\":\"\",\"result\":{\"ServicePermission\":true,"
+ "\"UserGroupPermission\":true}}";
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var responseValue = serializer.Deserialize<Response>(responseFromServer);
//access
responseValue.result.ServicePermission