I am using the nexmo api for .NET to send verification code to given phone which gives me the following error
The underlying connection was closed
My code is as follows
public bool PhoneVerfication(string PhoneNumber, long userId)
{
try
{
long? _cellPhone = Convert.ToInt64(PhoneNumber);
var _util = new utilMessageSender();
_util.SendVerificationCode(PhoneNumber);
return true;
}
catch (Exception ex)
{
return false;
}
}
public utilMessageSender()
{
client = new Client(creds: new Credentials
{
ApiKey = "********",
ApiSecret = "**************",
ApplicationId = "*********-****-****-****-***********",
ApplicationKey = "**************"
});
}
public void SendVerificationCode(string phoneNumber)
{
try
{
var result = client.NumberVerify.Verify(new NumberVerify.VerifyRequest
{
number = phoneNumber,
brand = "Offey-app"
});
RequestId = result.request_id;
}
catch (Exception ex)
{
throw ex;
}
}
I am using this API for the first time it worked very fine and sent verification code to different phone numbers but I don't know what happened as now it's not working.
Related
I have code to authenticate with EWS using oAuth working fine if I call it from winform button click, but not working if I place my code inside custom class and call it inside constructor I don't know what is the problem ?
Authenticate Code function :
public async Task<AuthenticationResult> oAuthLoginRequest()
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cca = ConfidentialClientApplicationBuilder
.Create(Settings.Default.appId)
.WithClientSecret(Settings.Default.clientSecret)
.WithTenantId(Settings.Default.tenantId)
.Build();
var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
try
{
_authenticationResult = await cca.AcquireTokenForClient(ewsScopes)
.ExecuteAsync();
return _authenticationResult;
}
catch (Exception ex)
{
string.Format("oAuthLoginRequest: Exception= {0}", ex.Message).LogIt(TLogType.ltError);
return _authenticationResult;
}
}
Working well and I got access token :
private async void button1_Click(object sender, EventArgs e)
{
oAuthLoginRequest();
//Access Token Available here
var accessToken = _authenticationResult.AccessToken ; //Working fine
}
NOT WORKING :
public class TServiceController
{
private bool _started = false;
public bool Started { get { return _started; } }
TEWSService mailService = null;
public ExchangeService _service = null;
public AuthenticationResult _authenticationResult = null;
public DateTimeOffset TokenExpiresOn { get; set; }
public async Task<AuthenticationResult> oAuthLoginRequest()
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cca = ConfidentialClientApplicationBuilder
.Create(Settings.Default.appId)
.WithClientSecret(Settings.Default.clientSecret)
.WithTenantId(Settings.Default.tenantId)
.Build();
// "https://outlook.office365.com/.default" ,"https://outlook.office365.com/EWS.AccessAsUser.All" , "https://graph.microsoft.com/Mail.Send"
// "https://ps.outlook.com/full_access_as_app"
var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
try
{
_authenticationResult = await cca.AcquireTokenForClient(ewsScopes).ExecuteAsync();
TokenExpiresOn = _authenticationResult.ExpiresOn;
("AccessToken:" + _authenticationResult.AccessToken).LogIt(TLogType.ltDebug);
}
catch (Exception ex)
{
string.Format("oAuthLoginRequest: Exception= {0}", ex.Message).LogIt(TLogType.ltError);
}
return _authenticationResult;
}
public TServiceController()
{
var auth = oAuthLoginRequest().Result; //STUCK HERE
"Service controller started.".LogIt();
} //end constructore
} //END CLASS
Any explanation ?
I tried two methods one of them work just fine in winform click button and other solution not working within my class constructor .
I am trying to create different types of errors in an ASP.NET controller (which communicates with a service). Right now I am focusing on a ServiceNotFound error, but DbContextMock() always returns true. What is the correct way to do this?
(In OrdersController.cs)
public OrdersController(IOrdersService ordersService)
{
_ordersService = ordersService ?? throw new ArgumentNullException(nameof(ordersService));
}
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.NoContent)]
[ProducesResponseType((int)HttpStatusCode.InternalServerError)]
public async Task<IActionResult> PutOrdersAsync()
{
try
{
await _ordersService.PutOrdersAsync();
return new StatusCodeResult(StatusCodes.Status204NoContent);
}
catch (ServiceException ex)
{
return StatusCode(
(int)ex.StatusCode,
Responses.ErrorResponse with { Message = ex.Message, Content = JsonConvert.SerializeObject(ex), RequestId = Request.HttpContext.Connection.Id }
);
}
catch (Exception ex)
{
return StatusCode(
StatusCodes.Status500InternalServerError,
Responses.ErrorResponse with { Message = ex.Message, Content = JsonConvert.SerializeObject(ex), RequestId = Request.HttpContext.Connection.Id }
);
}
}
(In Tests.cs)
...
var context = new DbContextMock();
...
var service = GetOrdersService(context.Object, _pdcClientFactory.Object);
...
await service.PutOrdersAsync();
I'm working on my own ChatBot for YouTube in Winforms and C#. It already works on Twitch and I'm trying to replicate the functionality for Youtube using the C# API. I can download the Chat Messages no problem, but creating a chat message is causing me a headache as I'm getting a 403, Insufficient Permission error. The full error message is
Google.Apis.Requests.RequestError
Insufficient Permission [403]
Errors [
Message[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]
]
After some searching I've tried most things that I can find and have still come up empty as to what exactly is causing this. I get it's a permission issue and I obviously need to set something but I can't figure out what. My code is below and definitely works for reading data... but i don't know why it won't work for writing.
public class YouTubeDataWrapper
{
private YouTubeService youTubeService;
private string liveChatId;
private bool updatingChat;
private int prevResultCount;
public List<YouTubeMessage> Messages { get; private set; }
public bool Connected { get; private set; }
public bool ChatUpdated { get; set; }
//public Authorisation Authorisation { get; set; }
//public AccessToken AccessToken { get; set; }
public YouTubeDataWrapper()
{
this.Messages = new List<YouTubeMessage>();
}
public async void Connect()
{
Stream stream = new FileStream("client_secrets.json", FileMode.Open);
UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, new[] { YouTubeService.Scope.YoutubeForceSsl }, "user", CancellationToken.None, new FileDataStore(this.GetType().ToString()));
stream.Close();
stream.Dispose();
this.youTubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var res = this.youTubeService.LiveBroadcasts.List("id,snippet,contentDetails,status");
res.BroadcastType = LiveBroadcastsResource.ListRequest.BroadcastTypeEnum.Persistent;
res.Mine = true;
//res.BroadcastStatus = LiveBroadcastsResource.ListRequest.BroadcastStatusEnum.Active;
var resListResponse = await res.ExecuteAsync();
IEnumerator<LiveBroadcast> ie = resListResponse.Items.GetEnumerator();
while (ie.MoveNext() && string.IsNullOrEmpty(this.liveChatId))
{
LiveBroadcast livebroadcast = ie.Current;
string id = livebroadcast.Snippet.LiveChatId;
if (!string.IsNullOrEmpty(id))
{
this.liveChatId = id;
this.Connected = true;
}
bool? def = livebroadcast.Snippet.IsDefaultBroadcast;
string title = livebroadcast.Snippet.Title;
LiveBroadcastStatus status = livebroadcast.Status;
}
}
public async void UpdateChat()
{
if (!this.updatingChat)
{
if (!string.IsNullOrEmpty(this.liveChatId) && this.Connected)
{
this.updatingChat = true;
var livechat = this.youTubeService.LiveChatMessages.List(this.liveChatId, "id,snippet,authorDetails");
var livechatResponse = await livechat.ExecuteAsync();
PageInfo pageInfo = livechatResponse.PageInfo;
this.ChatUpdated = false;
if (pageInfo.TotalResults.HasValue)
{
if (!this.prevResultCount.Equals(pageInfo.TotalResults.Value))
{
this.prevResultCount = pageInfo.TotalResults.Value;
this.ChatUpdated = true;
}
}
if (this.ChatUpdated)
{
this.Messages = new List<YouTubeMessage>();
foreach (var livemessage in livechatResponse.Items)
{
string id = livemessage.Id;
string displayName = livemessage.AuthorDetails.DisplayName;
string message = livemessage.Snippet.DisplayMessage;
YouTubeMessage msg = new YouTubeMessage(id, displayName, message);
string line = string.Format("{0}: {1}", displayName, message);
if (!this.Messages.Contains(msg))
{
this.Messages.Add(msg);
}
}
}
this.updatingChat = false;
}
}
}
public async void SendMessage(string message)
{
LiveChatMessage liveMessage = new LiveChatMessage();
liveMessage.Snippet = new LiveChatMessageSnippet() { LiveChatId = this.liveChatId, Type = "textMessageEvent", TextMessageDetails = new LiveChatTextMessageDetails() { MessageText = message } };
var insert = this.youTubeService.LiveChatMessages.Insert(liveMessage, "snippet");
var response = await insert.ExecuteAsync();
if (response != null)
{
}
}
}
The main code in question is the Send Message method. I've tried changing the Scope of the UserCredentials to everything I can try to no avail. Any ideas?
From the YouTube Data API - Error, your error 403 or insufficientPermissions is error in the OAuth 2.0 token provided for the request specifies scopes that are insufficient for accessing the requested data.
So make sure you use proper Scope in your application. Here is the example of scope that is needed in your application.
https://www.googleapis.com/auth/youtube.force-ssl
https://www.googleapis.com/auth/youtube
For more information about this error 403, you can check this related SO question.
Turns out that revoking the access and then re-doing it fixed the issue. The error message was not very helpful.
I’m new with HttpClient and Web API so I’m sure I’m missing something obvious to others. I’m trying to call a 3rd party Web API with a list of new Employees. The API is supposed to return JSON with information about the employees that were uploaded. This is going to be a console app that will be run once a night. There is no requirement for this to run Async.
I’m trying to follow along with these articles.
http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
and
http://typecastexception.com/post/2013/07/03/Building-Out-a-Clean-REST-ful-WebApi-Service-with-a-Minimal-WebApi-Project.aspx
What’s not working is the following code to try to get the API results into an array or list. When I run it in Debug it gives me an exception “One or more errors occurred.” which doesn’t give me a lot to go on.
if (response.IsSuccessStatusCode)
{
AddEmployeeResult employeeResults = response.Content.ReadAsAsync<AddEmployeeResult>().Result;
}
The vendor gave me this as an example of what should be returned.
[{"EmployeeNumber":"22449","SuccessfullyAdded":true,"Existing":false,"Comments":"App UserId: 6037"},{"EmployeeNumber":"379844","SuccessfullyAdded":true,"Existing":false,"Comments":" App UserId: 6038"},{"EmployeeNumber":"23718","SuccessfullyAdded":true,"Existing":false,"Comments":" App UserId ps: 6039"}]
I created a class in my console app to match what is supposed to be returned from the API.
class AddEmployeeResult
{
public string EmployeeNumber { get; set; }
public bool SuccessfullyAdded { get; set; }
public bool Existing { get; set; }
public string Comments { get; set; }
}
Here is the code I’m trying.
static void Main(string[] args)
{
UploadNewEmployee();
}
public static void UploadNewEmployee()
{
string serviceURI = "https://services.website.com/api/employees/upload";
var credentials = new NetworkCredential("username", "password");
var clientHandler = new HttpClientHandler();
clientHandler.Credentials = credentials;
clientHandler.PreAuthenticate = true;
//*** Get the Employee Data ***
List<Employee> lstEmployee = new List<Employee>();
try
{
lstEmployee = DataManager.GetEmployees();
}
catch (Exception ex)
{
logger.Error("Error while getting data. | {0} | Trace: {1}", ex.Message, ex.StackTrace);
}
//*** Process users if there is data. ***
if (lstEmployee != null && lstEmployee.Count > 0)
{
logger.Info("Employee count: " + lstEmployee.Count);
logger.Debug("Web API Uri: " + serviceURI);
try
{
using (var client = new HttpClient(clientHandler))
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync(serviceURI, lstEmployee).Result;
if (response.IsSuccessStatusCode)
{
AddEmployeeResult employeeResults = response.Content.ReadAsAsync<AddEmployeeResult>().Result;
}
}
}
catch (Exception ex)
{
logger.Error("Error posting to Web API. | {0} | Trace: {1}", ex.Message, ex.StackTrace);
}
}
else
{
logger.Info("No records found.");
}
}
After reviewing and trying many of the suggestions surrounding the error message:
"An asynchronous module or handler completed while an asynchronous
operation was still pending."
I found myself in the situation where even though the call to the MVC accountController actually EXECUTED the desired code (an email was sent to the right place with the right content) and a Try/Catch in the controller method would not 'catch' the error, the AngularJS factory that was initiating the call would receive a server error "page".
Factory:(AngularJS)
InitiateResetRequest: function (email) {
var deferredObject = $q.defer();
$http.post(
'/Account/InitiateResetPassword', { email: email }
)
.success(function (data) {
deferredObject.resolve(data);
})
.error(function (data) {
//This is a stop-gap solution that needs to be fixed..!
if (data.indexOf("An asynchronous module or handler completed while an asynchronous operation was still pending.") > 0) {
deferredObject.resolve(true);
} else {
deferredObject.resolve(false);
}
});
return deferredObject.promise;
}
MVC Controller (C#):
[HttpPost]
[AllowAnonymous]
public async Task<int> InitiateResetPassword(string email)
{
try
{
_identityRepository = new IdentityRepository(UserManager);
string callbackUrl = Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, "/account/reset?id=");
await _identityRepository.InitiatePasswordReset(email, callbackUrl);
return 0;
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
return 1;
}
}
Identity Repository/InitiatePasswordReset:
public async Task InitiatePasswordReset(string email, string callbackUrl)
{
try
{
var u = await _applicationUserManager.FindByEmailAsync(email);
string passwordResetToken = await GetResetToken(u);
callbackUrl = callbackUrl + HttpUtility.UrlEncode(passwordResetToken);
await _applicationUserManager.SendEmailAsync(u.Id, RESET_SUBJECT, string.Format(RESET_BODY, u.FirstName, u.LastName, callbackUrl));
}
catch(Exception ex)
{ //another vain attempt to catch the exception...
Console.WriteLine(ex.ToString());
throw ex;
}
}
The EmailService injected into the ASP.NET Identity "ApplicationUserManager"
public class EmailService : IIdentityMessageService
{
XYZMailer xyzMailer;
public EmailService()
{
xyzMailer = XYZMailer.getCMRMailer();
}
public async Task SendAsync(IdentityMessage message)
{
//original code as posted:
//await Task.FromResult(xyzMailer.SendMailAsync(message));
//solution from #sirrocco-
await xyzMailer.SendMailAsync(message);
}
}
and finally...the XYZMailer class
class XYZMailer
{
#region"Constants"
private const string SMTP_SERVER = "XYZEXCHANGE.XYZ.local";
private const string NO_REPLY = "noReply#XYZCorp.com";
private const string USER_NAME = "noreply";
private const string PASSWORD = "theMagicP#55word"; //NO, that is not really the password :)
private const int SMTP_PORT = 587;
private const SmtpDeliveryMethod SMTP_DELIVERY_METHOD = SmtpDeliveryMethod.Network;
#endregion//Constants
internal XYZMailer()
{
//default c'tor
}
private static XYZMailer _XYZMailer = null;
public static XYZMailer getXYZMailer()
{
if (_XYZMailer == null)
{
_XYZMailer = new XYZMailer();
}
return _XYZMailer;
}
public async Task<int> SendMailAsync(IdentityMessage message)
{
#if DEBUG
message.Body += "<br/><br/>DEBUG Send To: " + message.Destination;
message.Destination = "me#XYZCorp.com";
#endif
// Create the message:
var mail =
new MailMessage(NO_REPLY, message.Destination)
{
Subject = message.Subject,
Body = message.Body,
IsBodyHtml = true
};
// Configure the client:
using (SmtpClient client = new SmtpClient(SMTP_SERVER, SMTP_PORT)
{
DeliveryMethod = SMTP_DELIVERY_METHOD,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(USER_NAME, PASSWORD),
EnableSsl = true
})
{
// Send:
await client.SendMailAsync(mail);
}
return 0;
}
}
(note: originally the controller method was simply "public async Task InitiateResetPassword, I added the return type as an attempt to trap the error on the server. At runtime, return 0; does hit (breakpoint) the catch does not get hit and at the client")
At the moment I am simply filtering for the expected error message and telling javascript to treat it as a success. This solution has the benefit of 'actually working'... but it is not 'ideal'.
How do I prevent the error on the server?
or alternately,
How do I catch the error on the server?
You need to remove await Task.FromResult from EmailService because that makes it so the code executes synchronously instead of async.
As to why the the exception was still raised and bubbled up outside the try/catch - I suspect the Task.FromResult was the culprit here too - if you now raise an exception in SendAsync (just to test it) you should catch in the controller.