I've created an ASP.NET Core API solution that uses RestSharp to send data to a third party API and return results back to my API and database. On my API, I want to return the results of the RestSharp call as part of my controller class so that my DNN site can consume the RestSharp Responses. How do I return the responses obtained from the third party API in my controller class?
My RestSharp logic is as follows:
/// <summary>
/// Executes a particular http request to a resource.
/// </summary>
/// <typeparam name="T">The response type.</typeparam>
/// <param name="request">The REST request.</param>
/// <param name="baseUrl">The base URL.</param>
/// <returns>Returns a response of the type parameter.</returns>
private static T Execute<T>(IRestRequest request, string baseUrl) where T : class, new()
{
baseUrl = "https://xmltest.propay.com/api/propayapi/PropayMerchantService.svc/";
var client = new RestClient(baseUrl);
var response = client.Execute<T>(request);
if (response.ErrorException != null)
{
Console.WriteLine(
"Error: Exception: {0}, Headers: {1}, Content: {2}, Status Code: {3}",
response.ErrorException,
response.Headers,
response.Content,
response.StatusCode);
}
return response.Data;
}
public static ProPayResponse MerchantSignUpForProPay()
{
var baseUrl = "https://xmltest.propay.com/api/propayapi/PropayMerchantService.svc/";
var request = BuildMerchantTestData();
var restRequest = CreateRestRequest("/Signup", Method.PUT);
restRequest.AddJsonBody(request);
return Execute<ProPayResponse>(restRequest, baseUrl);
}
/// <summary>
/// Builds the merchant request data.
/// </summary>
/// <returns>The request data.</returns>
private static SignUpRequest BuildMerchantTestData()
{
var onboarding = new Onboarding();
var signUpRequest = new SignUpRequest();
var userid = "userId";
var email = userid + "#test.com";
using (SOBOContext context = new SOBOContext())
{
var signupRequest = new SignUpRequest
{
SignupAccountData = new SignupAccountData
{
ExternalId = "12345",
Tier = onboarding.AverageTicket.ToString(),
CurrencyCode = "USD",
PhonePIN = onboarding.PhonePin,
UserId = onboarding.UserName
},
Address =
new Address
{
Address1 = onboarding.Address1Line1,
Address2 = onboarding.Address1Line1,
ApartmentNumber = " ",
City = onboarding.Address1City,
State = onboarding.Address1State,
Country = onboarding.Address1Country,
Zip = onboarding.Address1ZipCode
},
BusinessAddress =
new Address
{
Address1 = onboarding.BusinessAddressLine1,
Address2 = onboarding.BusinessAddressLine2,
ApartmentNumber = " ",
City = onboarding.BusinessCity,
State = onboarding.BusinessState,
Country = onboarding.BusinessCountry,
Zip = onboarding.BusinessZipCode
},
MailAddress = new Address { Address1 = onboarding.OwnerAddress, City = onboarding.OwnerCity, State = onboarding.OwnerRegion, Country = onboarding.OwnerCountry, Zip = onboarding.OwnerZipCode },
BankAccount =
new BankAccount
{
AccountCountryCode = onboarding.BankAccount1CountryCode,
AccountType = onboarding.BankAccount1Type,
AccountOwnershipType = onboarding.BankAccount1OwnershipType,
BankAccountNumber = onboarding.BankAccount1Number,
BankName = onboarding.BankAccount1BankName,
RoutingNumber = onboarding.BankAccount1RoutingNumber
},
SecondaryBankAccount =
new BankAccount
{
AccountCountryCode = onboarding.BankAccount2CountryCode,
AccountType = onboarding.BankAccount2Type,
AccountOwnershipType = onboarding.BankAccount2OwnershipType,
BankAccountNumber = onboarding.BankAccount2Number,
BankName = onboarding.BankAccount2BankName,
RoutingNumber = onboarding.BankAccount2RoutingNumber
},
BusinessData =
new BusinessData
{
BusinessLegalName = onboarding.BusinessLegalName,
DoingBusinessAs = onboarding.DoingBusinessAs,
EIN = onboarding.Ein,
},
CreditCardData = new CreditCardData
{
CreditCardNumber = onboarding.CreditCardNumber, // test card number
ExpirationDate = onboarding.ExpirationDate
},
PersonalData =
new PersonalData
{
DateOfBirth = onboarding.DateOfBirth.ToString(),
SourceEmail = onboarding.Email,
SocialSecurityNumber = onboarding.Ssn,
FirstName = onboarding.FirstName,
LastName = onboarding.Lastname,
MiddleInitial = onboarding.MiddleInitial,
PhoneInformation =
new PhoneInformation { DayPhone = onboarding.DayPhone, EveningPhone = onboarding.EveningPhone }
}
};
context.SaveChangesAsync();
return signupRequest;
}
}
/// <summary>
/// Request factory to ensure API key is always first parameter added.
/// </summary>
/// <param name="resource">The resource name.</param>
/// <param name="method">The HTTP method.</param>
/// <returns>Returns a new <see cref="RestRequest"/>.</returns>
private static RestRequest CreateRestRequest(string resource, Method method)
{
var credentials = GetCredentials();
var restRequest = new RestRequest { Resource = resource, Method = method, RequestFormat = DataFormat.Json, };
restRequest.AddHeader("accept", "application/json");
restRequest.AddHeader("Authorization", credentials);
return restRequest;
}
My controller class thus far is as follows:
public async Task<IActionResult> GetMerchantSignUp()
{
await _context.ProPayResponse.ToListAsync();
return Ok();
}
Are there any other steps needed to retrieve the RestSharp responses and expose them in my controller class?
Related
I am using a PHP API to return the data of a user and i am trying to get the result into an object.When i try to put it in a user object it just throws an exception at runtime.This is a WPF program that i was trying to get user data , which consists of username and password and a boolean which states if he logged in or not.
namespace WpfApp3 {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow: Window {
public MainWindow() {
InitializeComponent();
}
private async void show_selection(object sender, RoutedEventArgs e) {
var userName = username.Text;
var passWord = password.Text;
var formContent = new FormUrlEncodedContent(new [] {
new KeyValuePair < string, string > ("username", userName),
new KeyValuePair < string, string > ("password", passWord)
});
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("http://localhost/pharmasuite/login1.php");
var response = await client.PostAsync(client.BaseAddress.ToString(), formContent);
var user = await response.Content.ReadAsAsync < user > ();
if (user.logged_in == true) {
MessageBox.Show("logged in");
}
}
class user {
public string username {
get;
set;
}
public string password {
get;
set;
}
public bool logged_in {
get;
set;
}
}
}
I receive this error when send post form-data to another api, with HttpClient :
I have this parameters on another api controller:
public class IntegracaoArquivosDigitaisDto
{
/// <summary>
/// IdInteral do arquivo digital
/// </summary>
/// <example>1</example>
public int IdInternalArquivoDigital { get; set; }
/// <summary>
/// Chave do Módulo
/// </summary>
/// <example>
/// RecursosHumanos
/// </example>
public string ChaveModulo { get; set; }
/// <summary>
/// Versão do Módulo
/// </summary>
/// <example>
/// 1.6
/// </example>
public int? Versao { get; set; }
/// <summary>
/// Versão dos Dados enviados para processamento
/// </summary>
/// <example>
/// c8283005-68f5-41bf-aea6-29496068656c
/// </example>
public Guid IdProcessamento { get; set; }
/// <summary>
/// Colunas chaves
/// </summary>
public List<PayloadDTO> ColunasChaves { get; set; }
/// <summary>
/// Tipo de operação - I,A,E
/// </summary>
/// <example>1</example>
public string TipoOperacao { get; set; }
/// <summary>
/// Id arquivo Digital
/// </summary>
/// <example>1</example>
public string IdArquivoDigital { get; set; }
/// <summary>
/// Nome Arquivo
/// </summary>
/// <example>teste.pdf</example>
public string NomeArquivoDigital { get; set; }
/// <summary>
/// Arquivo
/// </summary>
public IFormFile Arquivo { get; set; }
}
public class PayloadDTO
{
/// <summary>
/// Nome do campo
/// </summary>
/// <example>
/// Cidade
/// </example>
public string Campo { get; set; }
/// <summary>
/// Valor representativo do campo
/// </summary>
/// <example>José da Silva</example>
public string Valor { get; set; }
/// <summary>
/// Tipo do dado
/// </summary>
/// <example>int</example>
public string Tipo { get; set; }
}
And I this is controller :
[HttpPost]
public async Task<IActionResult> Teste([FromForm] IntegracaoArquivosDigitaisDto dto)
{
var json = JsonSerializer.Serialize(dto, new JsonSerializerOptions
{
WriteIndented = true,
});
return Ok(json);
}
I try using StringContent, Json , FormUrlEncodedContent And MultipartFormDataContent, but not working.
What is the correct way to make a post form-data using httpClient, with these parameters?
This is my implementation tests :
[HttpGet]
public async Task<IActionResult> Get()
{
string url = "http://localhost:5001/teste";
using (MultipartFormDataContent formDataContent = new MultipartFormDataContent())
{
var obj = new
{
IdInternalArquivoDigital = 3,
ChaveModulo = "RecursosHumanos",
Versao = 3,
IdProcessamento = Guid.NewGuid(),
ColunasChaves = new List<PayloadDTO>{
new PayloadDTO{
Campo="CdCategoria",
Tipo= "int",
Valor= "32",
},
new PayloadDTO{
Campo="Id",
Tipo= "int",
Valor= "3",
},
new PayloadDTO{
Campo="Nome",
Tipo= "strig",
Valor= "Samuel",
},
},
TipoOperacao = "I",
IdArquivoDigital = Guid.NewGuid().ToString(),
NomeArquivoDigital = "a7x.jg",
};
var json = JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true, });
//json content
// var jsonContent = new StringContent(json);
// jsonContent.Headers.ContentType = new MediaTypeHeaderValue("application/json")
// {
// CharSet = "utf-8"
// };
// Dictionary<string, string> dic = new Dictionary<string, string>();
// dic.Add(nameof(IntegracaoArquivosDigitaisDto.Versao), obj.Versao.ToString());
// dic.Add(nameof(IntegracaoArquivosDigitaisDto.IdArquivoDigital), obj.IdArquivoDigital.ToString());
// dic.Add(nameof(IntegracaoArquivosDigitaisDto.IdInternalArquivoDigital), obj.IdInternalArquivoDigital.ToString());
// dic.Add(nameof(IntegracaoArquivosDigitaisDto.IdProcessamento), obj.IdProcessamento.ToString());
// dic.Add(nameof(IntegracaoArquivosDigitaisDto.ChaveModulo), obj.ChaveModulo);
// dic.Add(nameof(IntegracaoArquivosDigitaisDto.NomeArquivoDigital), obj.NomeArquivoDigital);
// dic.Add(nameof(IntegracaoArquivosDigitaisDto.TipoOperacao), obj.TipoOperacao);
// formDataContent.Add(new FormUrlEncodedContent(dic), "dto");
// formDataContent.Add(new StringContent(obj.Versao.ToString()), nameof(IntegracaoArquivosDigitaisDto.Versao));
// formDataContent.Add(new StringContent(obj.IdArquivoDigital.ToString()), nameof(IntegracaoArquivosDigitaisDto.IdArquivoDigital));
// formDataContent.Add(new StringContent(obj.IdInternalArquivoDigital.ToString()), nameof(IntegracaoArquivosDigitaisDto.IdInternalArquivoDigital));
// formDataContent.Add(new StringContent(obj.IdProcessamento.ToString()), nameof(IntegracaoArquivosDigitaisDto.IdProcessamento));
// formDataContent.Add(new StringContent(obj.NomeArquivoDigital), nameof(IntegracaoArquivosDigitaisDto.NomeArquivoDigital));
// formDataContent.Add(new StringContent(obj.TipoOperacao), nameof(IntegracaoArquivosDigitaisDto.TipoOperacao));
// formDataContent.Add(new StringContent(obj.ColunasChaves.ToString()), nameof(IntegracaoArquivosDigitaisDto.ColunasChaves));
// formDataContent.Add(new StringContent(obj.ChaveModulo), nameof(IntegracaoArquivosDigitaisDto.ChaveModulo));
formDataContent.Add(new MultipartFormDataContent(obj.ChaveModulo), nameof(IntegracaoArquivosDigitaisDto.ChaveModulo));
string caminhoArquivo = #"C:\Users\samue\OneDrive\Imagens\a7x.jpg";
using (var fileStream = new FileStream(caminhoArquivo, FileMode.Open))
{
try
{
using (MemoryStream ms = new MemoryStream())
{
await fileStream.CopyToAsync(ms);
var bytes = ms.ToArray();
var fileContent = new ByteArrayContent(bytes);
//file content
// fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
// {
// FileName = "a7x.jpg"
// .Replace("(", string.Empty)
// .Replace(")", string.Empty)
// .Replace(" ", string.Empty),
// Name = "arquivo",
// };
formDataContent.Add(fileContent, nameof(IntegracaoArquivosDigitaisDto.Arquivo), "a7x.jpg");
_client.Timeout = TimeSpan.FromMinutes(2);
var res = await _client.PostAsync(url, formDataContent);
res.EnsureSuccessStatusCode();
}
}
catch (System.Exception ex) when (ex is HttpRequestException || ex is OperationCanceledException)
{
throw;
}
}
}
return Ok();
}
I have basic CRUD for a class ConfigSystem.
I have also two methods in the basic ConfigSystem Service.
public Type Get<Type>(string key, string userId)
{
//get config system
var configEntry = this.repository.GetSingleAsync(cs => cs.Key == key && cs.UserId == userId).Await();
if (configEntry == null)
{
configEntry = this.repository.GetSingleAsync(cs => cs.Key == key).Await();
}
if (typeof(Type).Name == configEntry.Type)
{
return JsonConvert.DeserializeObject<Type>(configEntry.Value);
//invalid config type exception
}
else
{
throw new InvalidCastException($"Cannot get the type of this particular key! ");
}
}
public async Task Set<T>(string key, string userId, T value)
{
CheckKey(key, userId);
// find key and then update its value
var configEntry = await this.repository.GetSingleAsync(cs => cs.Key == key && cs.UserId == userId);
//configEntry.Key = key;
if (configEntry == null)
{
configEntry = await this.repository.GetSingleAsync(cs => cs.Key == key);
}
configEntry.Type = value.GetType().Name;
configEntry.Value = JsonConvert.SerializeObject(value);
await this.repository.UpdateAsync(configEntry);
}
I have a static file Config:
public static Dictionary<string, object> ConfigurationList = new Dictionary<string, object>()
{
{"Currency", Enums.Currency.Lev },
{"Measure", Enums.Unit.LinearMetre },
{"DailyDraftLimit", 6},
{"DeleteDraftPeriod", 5},
{"NotificationStartTime", new TimeSpan(03, 00, 00) }, //give exact time 3AM.},
//TODO: Exclude weekends
{"NotificationPeriod", 24},//24 hours
{"PaymentNotificationPeriod", 24},
{"PaymentReceivers", null}, //what do I put here? if I dont have the ids/ -> we put null if we are not sure about the info or the info is not static!
{"VisitsNotificationPeriod", 24},
{"VisitsInternalReceivers", null},
{"VisitsExternalReceivers", null},
{"TermsNotificationPeriod", 24},
{"TermsReceivers", null }
}
and this is my ConfigSystem class:
public class ConfigSystem : AuditEntity<long>
{
/// <summary>
/// Gets or sets the key.
/// </summary>
public string Key { get; set; }
/// <summary>
/// Gets or sets the type.
/// </summary>
public string Type { get; set; }
/// <summary>
/// Gets or sets the value.
/// </summary>
public string Value { get; set; }
/// <summary>
/// Gets or sets the user identifier.
/// </summary>
public string UserId { get; set; }
}
This is my method in the Startup.
private void CreateDefaultConfig(ApplicationDbContext context, IServiceScope serviceScope)
{
var defaultConfig = DefaultTenantConfig.ConfigurationList;
if (context.ConfigSystems.Count() == 0)
{
var configSystemService = serviceScope.ServiceProvider.GetRequiredService<IConfigSystemService>();
//foreach (var entry in defaultConfig)
//{
// var entityToSaveInDb = configSystemService.CreateAsync()
//}
//create for each record a config system entry in the database
}
//check if in the context of the database there are no configs
}
I have no idea what to do with the object, but I had to keep it in object because I had different type of entries. I need to create them for each tenant and it is a default config if they are not created in the database.
I'm looking for a way to send model and image in one request. I tried to send my model from body, but I don't know how to send the file. Is there another way than sending image and model in a different files?
Here's the POST method from my API:
[HttpPost]
[Route("UploadNewEvent")]
public async Task<IActionResult> CreateNewEventAsync([FromBody] EventModel model)
{
var file = this.Request.Form.Files.LastOrDefault();
if (file != null)
{
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
using (var fileStream = new FileStream(Path.Combine(uploads, "test.jpg"), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
// do sth with model later
return Ok();
}
And here's the code from my App:
public async Task SendNewEvent(EventModel model, MediaFile photo)
{
var uri = $"{baseUri}api/User/Event/CreateNewEvent";
if (photo != null)
{
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StreamContent(photo.GetStream()), "\"file\"", $"\"{photo.Path}\"");
var httpClient = new HttpClient();
var jsonObject = JsonConvert.SerializeObject(model);
var stringContent = new StringContent(jsonObject, Encoding.UTF8, "application/json");
var httpResponseMessage = await httpClient.PostAsync(uri, stringContent);
}
}
For passing Model with File parameter, you need to post data as form-data.
Follow steps below:
Change FromBody to FromForm
[HttpPost]
[Route("UploadNewEvent")]
public async Task<IActionResult> CreateNewEventAsync([FromForm] EventModel model)
{
// do sth with model later
return Ok();
}
Change client code to send form-data instead of json string
var uri = $"https://localhost:44339/UploadNewEvent";
FileStream fileStream = new FileStream(#"filepath\T1.PNG", FileMode.Open);
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StreamContent(fileStream), "\"file\"", #"filepath\T1.PNG");
// EventModel other fields
multipartContent.Add(new StringContent("2"), "Id");
multipartContent.Add(new StringContent("Tom"), "Name");
var httpClient = new HttpClient();
var httpResponseMessage = httpClient.PostAsync(uri, multipartContent).Result;
EventModel
public class EventModel
{
public int Id { get; set; }
public string Name { get; set; }
public IFormFile File { get; set; }
}
I have resolved this type of issue by following code. Please let me know if you find any difficulty. In my example I have used File, Model Object and simple string will help in future.
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace TestingProject
{
class Program1
{
static void Main(string[] args)
{
UploadFile();
}
public static async Task UploadFile()
{
HttpClient httpClient = new HttpClient
{
BaseAddress = new Uri("https://google.com/")
};
var filepath = #"C:\Sample Documents.pdf";
var filename = "Sample Documents.pdf";
using (MultipartFormDataContent content = new MultipartFormDataContent())
{
ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filepath));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
Request request = new Request()
{
UserId = "1",
UserName = "test",
address = new AddressModel()
{
City = "test",
Country = "India"
},
FileDetails = fileContent
};
var addressSerialize = JsonConvert.SerializeObject(request.address);
FileStream fileStream = new FileStream(filepath, FileMode.Open);
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StreamContent(fileStream), "\"file\"", filepath);
multipartContent.Add(new StringContent(request.UserId), "UserId");
multipartContent.Add(new StringContent(request.UserName), "UserName");
multipartContent.Add(new StringContent(addressSerialize), "address");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("upload", multipartContent).ConfigureAwait(false);
var personResponse = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
public class Request
{
/// <summary>
/// userId
/// </summary>
[JsonProperty(PropertyName = "userId")]
public string UserId { get; set; }
/// <summary>
/// UserName
/// </summary>
[JsonProperty(PropertyName = "UserName")]
public string UserName { get; set; }
/// <summary>
/// docType
/// </summary>
[JsonProperty(PropertyName = "FileDetails")]
public ByteArrayContent FileDetails { get; set; }
/// <summary>
/// address
/// </summary>
[JsonProperty(PropertyName = "address")]
public AddressModel address { get; set; }
}
public class AddressModel
{
/// <summary>
/// City
/// </summary>
[JsonProperty(PropertyName = "City")]
public string City { get; set; }
/// <summary>
/// Country
/// </summary>
[JsonProperty(PropertyName = "Country")]
public string Country { get; set; }
}
}
}
I'm working with a oAuthTwitterTimeline example that Andy created but I'm kind of having a hard time making sure the default constructor is called(Parameterless Constructor) to pull the data from my web.config file instead of having me hardcode the app settings in.
I am calling the method "GetMyTimeline()" but AuthenticateSettings.
I get a bunch of null reference exceptions when I finally jump into AuthenticateMe method.
AuthResponse twitAuthResponse = authenticate.AuthenticateMe(AuthenticateSettings);
This is the parameterless constructor
public OAuthTwitterWrapper()
{
string oAuthConsumerKey = ConfigurationManager.AppSettings["oAuthConsumerKey"];
string oAuthConsumerSecret = ConfigurationManager.AppSettings["oAuthConsumerSecret"];
string oAuthUrl = ConfigurationManager.AppSettings["oAuthUrl"];
AuthenticateSettings = new AuthenticateSettings { OAuthConsumerKey = oAuthConsumerKey, OAuthConsumerSecret = oAuthConsumerSecret, OAuthUrl = oAuthUrl };
string screenname = ConfigurationManager.AppSettings["screenname"];
string include_rts = ConfigurationManager.AppSettings["include_rts"];
string exclude_replies = ConfigurationManager.AppSettings["exclude_replies"];
int count = Convert.ToInt16(ConfigurationManager.AppSettings["count"]);
string timelineFormat = ConfigurationManager.AppSettings["timelineFormat"];
TimeLineSettings = new TimeLineSettings
{
ScreenName = screenname,
IncludeRts = include_rts,
ExcludeReplies = exclude_replies,
Count = count,
TimelineFormat = timelineFormat
};
string searchFormat = ConfigurationManager.AppSettings["searchFormat"];
string searchQuery = ConfigurationManager.AppSettings["searchQuery"];
SearchSettings = new SearchSettings
{
SearchFormat = searchFormat,
SearchQuery = searchQuery
};
}
Nothing special in the controller
public class HomeController : Controller
{
private readonly OAuthTwitterWrapper.OAuthTwitterWrapper _oAuthTwitterWrapper;
public HomeController(OAuthTwitterWrapper.OAuthTwitterWrapper oAuthTwitterWrapper)
{
_oAuthTwitterWrapper = oAuthTwitterWrapper;
}
public ActionResult Index()
{
return View();
}
public JsonResult GetTwitterFeed()
{
return Json(_oAuthTwitterWrapper.GetMyTimeline(), JsonRequestBehavior.AllowGet);
}
//Some more stuff
}
The whole class "OAuthTwitterWrapper"
namespace OAuthTwitterWrapper
{
public class OAuthTwitterWrapper : IOAuthTwitterWrapper
{
public IAuthenticateSettings AuthenticateSettings { get; set; }
public ITimeLineSettings TimeLineSettings { get; set; }
public ISearchSettings SearchSettings { get; set; }
/// <summary>
/// The default constructor takes all the settings from the appsettings file
/// </summary>
public OAuthTwitterWrapper()
{
string oAuthConsumerKey = ConfigurationManager.AppSettings["oAuthConsumerKey"];
string oAuthConsumerSecret = ConfigurationManager.AppSettings["oAuthConsumerSecret"];
string oAuthUrl = ConfigurationManager.AppSettings["oAuthUrl"];
AuthenticateSettings = new AuthenticateSettings { OAuthConsumerKey = oAuthConsumerKey, OAuthConsumerSecret = oAuthConsumerSecret, OAuthUrl = oAuthUrl };
string screenname = ConfigurationManager.AppSettings["screenname"];
string include_rts = ConfigurationManager.AppSettings["include_rts"];
string exclude_replies = ConfigurationManager.AppSettings["exclude_replies"];
int count = Convert.ToInt16(ConfigurationManager.AppSettings["count"]);
string timelineFormat = ConfigurationManager.AppSettings["timelineFormat"];
TimeLineSettings = new TimeLineSettings
{
ScreenName = screenname,
IncludeRts = include_rts,
ExcludeReplies = exclude_replies,
Count = count,
TimelineFormat = timelineFormat
};
string searchFormat = ConfigurationManager.AppSettings["searchFormat"];
string searchQuery = ConfigurationManager.AppSettings["searchQuery"];
SearchSettings = new SearchSettings
{
SearchFormat = searchFormat,
SearchQuery = searchQuery
};
}
/// <summary>
/// This allows the authentications settings to be passed in
/// </summary>
/// <param name="authenticateSettings"></param>
public OAuthTwitterWrapper(IAuthenticateSettings authenticateSettings)
{
AuthenticateSettings = authenticateSettings;
}
/// <summary>
/// This allows the authentications and timeline settings to be passed in
/// </summary>
/// <param name="authenticateSettings"></param>
/// <param name="timeLineSettings"></param>
public OAuthTwitterWrapper(IAuthenticateSettings authenticateSettings, ITimeLineSettings timeLineSettings)
{
AuthenticateSettings = authenticateSettings;
TimeLineSettings = timeLineSettings;
}
/// <summary>
/// This allows the authentications, timeline and search settings to be passed in
/// </summary>
/// <param name="authenticateSettings"></param>
/// <param name="timeLineSettings"></param>
/// <param name="searchSettings"></param>
public OAuthTwitterWrapper(IAuthenticateSettings authenticateSettings, ITimeLineSettings timeLineSettings, ISearchSettings searchSettings)
{
AuthenticateSettings = authenticateSettings;
TimeLineSettings = timeLineSettings;
SearchSettings = searchSettings;
}
public string GetMyTimeline()
{
var timeLineJson = string.Empty;
IAuthenticate authenticate = new Authenticate();
AuthResponse twitAuthResponse = authenticate.AuthenticateMe(AuthenticateSettings);
// Do the timeline
var utility = new Utility();
timeLineJson = utility.RequstJson(TimeLineSettings.TimelineUrl, twitAuthResponse.TokenType, twitAuthResponse.AccessToken);
return timeLineJson;
}
public string GetSearch()
{
var searchJson = string.Empty;
IAuthenticate authenticate = new Authenticate();
AuthResponse twitAuthResponse = authenticate.AuthenticateMe(AuthenticateSettings);
// Do the timeline
var utility = new Utility();
searchJson = utility.RequstJson(SearchSettings.SearchUrl, twitAuthResponse.TokenType, twitAuthResponse.AccessToken);
return searchJson;
}
}
}
If anyone is having the same issue...
I labeled the default parameterless constructor with
namespace OAuthTwitterWrapper
{
public class OAuthTwitterWrapper : IOAuthTwitterWrapper
{
public IAuthenticateSettings AuthenticateSettings { get; set; }
public ITimeLineSettings TimeLineSettings { get; set; }
public ISearchSettings SearchSettings { get; set; }
[InjectConstructor]
public OAuthTwitterWrapper()
{
string oAuthConsumerKey = ConfigurationManager.AppSettings["oAuthConsumerKey"];
string oAuthConsumerSecret = ConfigurationManager.AppSettings["oAuthConsumerSecret"];
string oAuthUrl = ConfigurationManager.AppSettings["oAuthUrl"];
AuthenticateSettings = new AuthenticateSettings { OAuthConsumerKey = oAuthConsumerKey, OAuthConsumerSecret = oAuthConsumerSecret, OAuthUrl = oAuthUrl };
string screenname = ConfigurationManager.AppSettings["screenname"];
string include_rts = ConfigurationManager.AppSettings["include_rts"];
string exclude_replies = ConfigurationManager.AppSettings["exclude_replies"];
int count = Convert.ToInt16(ConfigurationManager.AppSettings["count"]);
string timelineFormat = ConfigurationManager.AppSettings["timelineFormat"];
TimeLineSettings = new TimeLineSettings
{
ScreenName = screenname,
IncludeRts = include_rts,
ExcludeReplies = exclude_replies,
Count = count,
TimelineFormat = timelineFormat
};
string searchFormat = ConfigurationManager.AppSettings["searchFormat"];
string searchQuery = ConfigurationManager.AppSettings["searchQuery"];
SearchSettings = new SearchSettings
{
SearchFormat = searchFormat,
SearchQuery = searchQuery
};
after making a reference to Unity(my IoC container).