This is my first usage of RestSharp
I am trying to connect to HubSpot using their FormsAPI (https://legacydocs.hubspot.com/docs/methods/forms/submit_form)
Using .Net, C#, MVC.
When I run in Fiddler, it works.
Here is my C# code, when I run it, I get a StatusCode of "NotFound". I am sure it is something simple I am missing?
var client = new RestClient("https://api.hsforms.com");
var request = new RestRequest("submissions/v3/integration/submit/{PortalId}/{formGuid}", Method.POST);
request.AddUrlSegment("portalId", "[myportalid]");
request.AddUrlSegment("formGuid", "[myformid]");
request.AddQueryParameter("hapikey", "[myapikey]");
request.RequestFormat = DataFormat.Json;
request.AddParameter("firstname", "testfirstname");
request.AddParameter("lastname", "testlastname");
request.AddParameter("email", "testemail#emailaddress.com");
request.AddParameter("business_unit", "Test");
It is better to create model of c# class and serialize it to Json and send POST request.
Example of RestSharp request
public async Task SendHubSpotRequest()
{
var PortalId = 1;
var formGuid = 1;
var client = new RestClient("https://api.hsforms.com");
var request = new RestRequest($"submissions/v3/integration/submit/{PortalId}/{formGuid}", Method.POST);
var hubSpotRequest = new HubSpotRequest()
{
SubmittedAt = "1517927174000",
Fields = new Field[]
{
new Field() { Name = "email", Value = "testemail#emailaddress.com" },
new Field() { Name = "firstname", Value = "testfirstname" },
new Field() { Name = "lastname", Value = "testlastname" }
},
Context = new Context
{
Hutk = "hutk",
PageUri = "www.example.com/page",
PageName = "Example page"
},
LegalConsentOptions = new LegalConsentOptions
{
Consent = new Consent
{
// Fill other params
}
}
};
request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(hubSpotRequest), ParameterType.RequestBody);
var response = await client.ExecuteAsync(request);
var responseContent = response.Content;
}
C# classes of body json model
public class HubSpotRequest
{
[JsonProperty("submittedAt")]
public string SubmittedAt { get; set; }
[JsonProperty("fields")]
public Field[] Fields { get; set; }
[JsonProperty("context")]
public Context Context { get; set; }
[JsonProperty("legalConsentOptions")]
public LegalConsentOptions LegalConsentOptions { get; set; }
}
public class Context
{
[JsonProperty("hutk")]
public string Hutk { get; set; }
[JsonProperty("pageUri")]
public string PageUri { get; set; }
[JsonProperty("pageName")]
public string PageName { get; set; }
}
public class Field
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class LegalConsentOptions
{
[JsonProperty("consent")]
public Consent Consent { get; set; }
}
public class Consent
{
[JsonProperty("consentToProcess")]
public bool ConsentToProcess { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("communications")]
public Communication[] Communications { get; set; }
}
public class Communication
{
[JsonProperty("value")]
public bool Value { get; set; }
[JsonProperty("subscriptionTypeId")]
public long SubscriptionTypeId { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
Related
I tried with this code, but it doesn't seem to work.
public ActionResult Getcountries()
{
var webClient = new WebClient();
var json = webClient.DownloadString(#"C:\Users\kristijanm\source\repos\contactForm\contactForm\data\Countries.json");
var CountryL = JsonConvert.DeserializeObject<CountriesModel>(json);
return View(CountryL);
}
Here is my Model:
public class CountriesModel
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
}
I am using DropDownlist in order to get country of all the world. I have attached the file(country_list.txt) using srcFilePath. The error i am getting is "There is no ViewData item of type 'IEnumerable' that has the key 'SelectedCountryId'.What could be an issue, because my EditFormTrainingRegViewModel does have this field SelectedCountry as a primary key. Its been declared as public int? SelectedCountryId {get;set;}
// List for countries.
private IEnumerable<SelectListItem> GetCountryList()
{
SelectList listcn = null;
try
{
var list = this.LoadData().Select(p => new SelectListItem
{
Value = p.Country_Id.ToString(),
Text = p.Country_Name
});
listcn = new SelectList(list, "Value", "Text");
}catch(Exception ex)
{
throw ex;
}
return listcn;
}
public ActionResult DropDownSelect()
{
EditTrainingRegFormViewModel model = new EditTrainingRegFormViewModel();
model.SelectedCountryId = 0;
this.ViewBag.CountryList = this.GetCountryList();
return this. View(model);
}
// Loading data for country list.
private List<EditTrainingRegFormViewModel> LoadData()
{
List<EditTrainingRegFormViewModel> lst = new List<EditTrainingRegFormViewModel>();
try
{
string line = string.Empty;
string srcFilePath = "Content/files/country_list.txt";
var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var fullPath = Path.Combine(rootPath, srcFilePath);
string filePath = new Uri(fullPath).LocalPath;
StreamReader src = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
// while to read the file
while((line = src.ReadLine()) !=null) {
EditTrainingRegFormViewModel infoLst = new EditTrainingRegFormViewModel();
string[] info = line.Split(',');
//Setting
infoLst.Country_Id = Convert.ToInt32(info[0].ToString());
infoLst.Country_Name = info[1].ToString();
lst.Add(infoLst);
}
src.Dispose();
src.Close();
}catch(Exception ex)
{
Console.Write(ex);
}
return lst;
}
//View
#Html.DropDownListFor(m=>m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new {#class = "form-control"})
// Model class
public class EditTrainingRegFormViewModel
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Position { get; set; }
public string Company { get; set; }
public string Address { get; set; }
[Display(Name = "Choose country")]
public int ? SelectedCountryId { get; set; }
public string Code { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Cell_Number { get; set; }
public List<string> Dietary_requirement { get; set; }
public string Email { get; set; }
public int Country_Id { get; set; }
public string Country_Name { get; set; }
}
want to parse a JSON string in combobox to 'text'. The response is something like
How can I parse the JSON and extract its 'text' values?
var restClient = new RestClient("https://cbsservis.tkgm.gov.tr/megsiswebapi.v2/api/idariYapi/ilListe");
var restRequest = new RestRequest(Method.GET);
var restResponse = restClient.Execute(restRequest);
restRequest.AddHeader("Accept", "text/json");
var jArray = Newtonsoft.Json.Linq.JObject.Parse(restResponse.Content);
dynamic jsonResponse = JsonConvert.DeserializeObject(restResponse.Content);
dynamic jsonResponse2 = JsonConvert.DeserializeObject<RootObject>(string JObject);`
Your response can be represented by classes like this:
public class Rootobject
{
public Feature[] features { get; set; }
public string type { get; set; }
public Crs crs { get; set; }
}
public class Crs
{
public string type { get; set; }
public Properties properties { get; set; }
}
public class Properties
{
public string name { get; set; }
}
public class Feature
{
public string type { get; set; }
public Geometry geometry { get; set; }
public Properties1 properties { get; set; }
}
public class Geometry
{
public string type { get; set; }
public object[][][] coordinates { get; set; }
}
public class Properties1
{
public string text { get; set; }
public int id { get; set; }
}
Hence your code can be changed to:
var restClient = new RestClient("https://cbsservis.tkgm.gov.tr/megsiswebapi.v2/api/idariYapi/ilListe");
var restRequest = new RestRequest(Method.GET);
var restResponse = restClient.Execute(restRequest);
restRequest.AddHeader("Accept", "text/json");
var obj = JsonConvert.DeserializeObject<Rootobject>(restResponse.Content);
You will receive the object like this:
And then you can loop through properties to get desired text.
I have a ViewModel which is initialized dto. I want to send json object from postman with their values but c# object can not take values and is set null. How can i do that ?
public class RegisterUserVm
{
public UserDto User { get; set; }
public RegisterUserVm()
{
User = new UserDto();
}
}
public class UserDto
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Password { get; set; }
}
[HttpPost]
[Route("RegisterUser")]
public async Task<ActionResult<UserDto>> RegisterUser([FromBody] RegisterUserVm vm)
{
var registeredUser = await userBusiness.RegisterUser(new RegisterUserCommand
{
User = vm.User
});
return registeredUser.Result;
}
[HttpPost]
[Route("RegisterUser")]
public async Task<IActionResult> RegisterUser([FromBody] RegisterUserVm vm)
{
var registeredUser = await userBusiness.RegisterUser(new RegisterUserCommand
{
User = vm.User
});
var resultModel = registeredUser.Result.ToResultModel();
return Ok(resultModel);
}
hello people I have this Json data:
https://openexchangerates.org/api/latest.json?app_id=6cf59607a32d408eb3e04de1427a3169
and I want to deserialize in the following class
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Divisas2MVVM2.Classes
{
public class ExchangeRates
{
[JsonProperty(PropertyName = "disclaimer")]
public string Disclaimer { get; set; }
[JsonProperty(PropertyName = "license")]
public string License { get; set; }
[JsonProperty(PropertyName = "timestamp")]
public int TimeStamp { get; set; }
[JsonProperty(PropertyName = "base")]
public string Base { get; set; }
[JsonProperty(PropertyName = "rates")]
public Rates Rates { get; set; }
}
public class Rates
{
public double AED { get; set; }
public double AFN { get; set; }
public double ALL { get; set; }
public double AMD { get; set; }
// I cut the text so that it would not be to long
public double ZMW { get; set; }
public double ZWL { get; set; }
}
public class Rate
{
public double TaxRate { get; set; }
public string Code { get; set; }
}
this is my attribute
private ExchangeRates exchangeRates;
the constructor of my MainViewModel
new ObservableCollection data
Rates = new ObservableCollection<Rate>();
and in this method a get the json data
try
{
var client = new HttpClient();
client.BaseAddress = new Uri("https://openexchangerates.org");
var url = "/api/latest.json?app_id=6cf59607a32d408eb3e04de1427a3169";
var response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
Message = response.StatusCode.ToString();
IsRunning = false;
return;
}
var result = await response.Content.ReadAsStringAsync();
exchangeRates = JsonConvert.DeserializeObject<ExchangeRates>(result);
}
everything works fine, the variable result has correctly the json data in a string format, but when i call JsonConvert . DeserializeObject, the data "rates" it is not assigned correctly, all the other data: disclaimer", "license", "timestamp" etc. is correctly assigned. only rates fail.
the string is correct
other data is correct in the class
rates is incorrect
sorry for my English I hope you have understood me :)
use this as your model class
namespace Rate
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Rates
{
[JsonProperty("disclaimer")]
public string Disclaimer { get; set; }
[JsonProperty("license")]
public string License { get; set; }
[JsonProperty("timestamp")]
public long Timestamp { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("rates")]
public Dictionary<string, double> RatesRates { get; set; }
}
public partial class Rates
{
public static Rates FromJson(string json) => JsonConvert.DeserializeObject<Rates>(json, Rate.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Rates self) => JsonConvert.SerializeObject(self, Rate.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 }
},
};
}
}
Then do this in your class
var data = Rate.Rates.FromJson("jsonresult");
var rate = data.RatesRates;
foreach (var pair in rate)
{
string symbol = pair.Key; //"AED"
double value = pair.Value; //3.673175,
}
var time = data.Timestamp;
var disclaimer = data.Disclaimer;
var license = data.License;
Tested and working