public JsonResult <ApiBaseResponse> ChangeEmail([FromUri] Guid userId, string email, string code) { var result = new ApiBaseResponse(); try { var user = UserManager.FindById(userId); var validCode = UserManager.VerifyUserToken(userId, IdentityUserTokenHelper.GenerateTokenPurpose(IdentityUserTokenHelper.TokenPurpose.Editing, email), code); if (!validCode || user == null) { result.Status = Core.Enums.ApiStatusCode.WrongArgumentsOrData; return(Json(result)); } user.Email = email; if (!UserManager.Update(user).Succeeded) { result.Status = Core.Enums.ApiStatusCode.WrongArgumentsOrData; } } catch (Exception ex) { result.Status = Core.Enums.ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
public JsonResult <ApiBaseResponse> LoginByEmail([FromUri] string email) { var result = new ApiBaseResponse(); try { var user = Mapper.Map <OntextUser, ApiUser>(UserManager.FindByEmail(email)); if (user == null) { result.Status = Core.Enums.ApiStatusCode.WrongArgumentsOrData; } else { var purpose = IdentityUserTokenHelper.GenerateTokenPurpose(IdentityUserTokenHelper.TokenPurpose.Loging, email); var token = UserManager.GenerateUserToken(purpose, user.Id); UserManager.SendEmail(email, "Security Code", token); } } catch (Exception ex) { result.Status = Core.Enums.ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
public async Task <JsonResult <ApiBaseResponse> > Post() { var result = new ApiBaseResponse(); try { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var root = HttpContext.Current.Server.MapPath(OntextSettings.UploadImageDirectoryPath); var provider = new CustomMultipartFormDataStreamProvider(root); // Read the form data. await Request.Content.ReadAsMultipartAsync(provider); } catch (Exception ex) { result.Status = ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
/// <summary> /// Convert the HTTP response message into a simple structure suitable for apps to process /// </summary> /// <param name="response">The response to convert</param> /// <returns>A simple response</returns> private static async Task <ApiBaseResponse> TranslateSectionGroupsResponse(HttpResponseMessage response) { ApiBaseResponse apiBaseResponse; string body = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK /* GET Pages calls always return 200-OK upon success */) { apiBaseResponse = JsonConvert.DeserializeObject <GenericEntityResponse>(body); } else { apiBaseResponse = new ApiBaseResponse(); } // Extract the correlation id. Apps should log this if they want to collect the data to diagnose failures with Microsoft support IEnumerable <string> correlationValues; if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues)) { apiBaseResponse.CorrelationId = correlationValues.FirstOrDefault(); } apiBaseResponse.StatusCode = response.StatusCode; apiBaseResponse.Body = body; return(apiBaseResponse); }
private void SetResponseLinks(ApiBaseResponse apiBaseResponse) { if (apiBaseResponse != null && apiBaseResponse.Links != null) { ClientLinkLaunchButton.DataContext = apiBaseResponse.Links.OneNoteClientUrl.Href; } }
public async Task <ApiBaseResponse> RegisterAsync(RegisterRequestModel requestModel) { ApiBaseResponse apiBaseResponse = new ApiBaseResponse(); var isExistedEmail = await _userService.ExistedByEmailAsync(requestModel.Email); if (isExistedEmail) { throw new BlogSolutionException("The email address has already exist.", ApplicationStatusCode.AnErrorHasOccured); } var isExistedUsername = await _userService.ExistedByUsernameAsync(requestModel.Username); if (isExistedUsername) { throw new BlogSolutionException("The username has already exist.", ApplicationStatusCode.AnErrorHasOccured); } var password = new PasswordHasher(requestModel.Password); await _userService.AddUserAsync(new User { Username = requestModel.Username, Name = requestModel.Name, Email = requestModel.Email, PhoneNumber = requestModel.PhoneNumber, PasswordHash = password.Hash, PasswordSalt = password.Salt }); return(apiBaseResponse); }
public async Task <ApiBaseResponse> LoginAsync(LoginRequestModel requestModel) { ApiBaseResponse apiBaseResponse = new ApiBaseResponse(); var user = await _userService.FindByEmailAsync(requestModel.Email); if (user == null) { return(new ApiBaseResponse(System.Net.HttpStatusCode.BadRequest, ApplicationStatusCode.AnErrorHasOccured, null, "The email or password is wrong")); } if (!user.IsActive || user.IsDeleted) { return(new ApiBaseResponse(System.Net.HttpStatusCode.BadRequest, ApplicationStatusCode.AnErrorHasOccured, null, "The email or password is wrong")); } bool isVerified = PasswordHasher.Verify(user.PasswordSalt, user.PasswordHash, requestModel.Password); if (!isVerified) { return(new ApiBaseResponse(System.Net.HttpStatusCode.BadRequest, ApplicationStatusCode.AnErrorHasOccured, null, "The email or password is wrong")); } var token = _jwtHandler.CreateToken(user.Id.ToString()); apiBaseResponse.Result = token; return(apiBaseResponse); }
/// <summary> /// This method provides the API Base Response. /// </summary> /// <param name="result"></param> /// <returns></returns> protected ObjectResult CreateResponse(ApiBaseResponse result) { return(new ObjectResult(result) { StatusCode = (int)(result.StatusCode) }); }
public JsonResult <ApiBaseResponse> SendMessage([FromBody] ApiMessage message) { var result = new ApiBaseResponse(); try { var messageId = ServicesHost.GetService <IMessagesProvider>().Save(message); message = ServicesHost.GetService <IMessagesProvider>().GetById(messageId); var contact = ServicesHost.GetService <IContactsProvider>().GetById(message.ContactId); var receiverUser = UserManager.FindByPhoneNumber(contact.PhoneNumber); if (receiverUser == null) { var smsMessageText = message.GetSmsMessageText(message); ServicesHost.GetService <ISmsService>().SendSmsMessage(contact.PhoneNumber, smsMessageText); } else { var userDeviceTokens = ServicesHost.GetService <IDevicesProvider>().GetUserDevices(receiverUser.Id).Select(d => d.Token); var messagesCount = ServicesHost.GetService <IMessagesProvider>().UnreadUserMessagesCount(receiverUser.Id); var messageText = message.GetPushNotificationText(); Task.Run(() => ServicesHost.GetService <IApplePushNotificationService>().SendPushNotifications(userDeviceTokens, messageText, messagesCount, messageId.ToString())); } } catch (Exception ex) { result.Status = ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
public JsonResult <ApiBaseResponse> SendCodeBySms(Guid userId, string phoneNumber) { var result = new ApiBaseResponse(); try { var user = Mapper.Map <OntextUser, ApiUser>(UserManager.FindById(userId)); if (user == null) { result.Status = Core.Enums.ApiStatusCode.WrongArgumentsOrData; } else { var purpose = IdentityUserTokenHelper.GenerateTokenPurpose(IdentityUserTokenHelper.TokenPurpose.Editing, phoneNumber); var token = UserManager.GenerateUserToken(purpose, user.Id); ServicesHost.GetService <ISmsService>().SendSmsMessage(phoneNumber, token); } } catch (Exception ex) { result.Status = Core.Enums.ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
/// <summary> /// Get the content for a specific page /// Previously example showed us how to get page meta data. This example shows how to get the content of the page. /// </summary> /// <param name="debug">Run the code under the debugger</param> /// <param name="pageId">Id of the page for which the content is returned</param> /// <param name="provider"></param> /// <param name="apiRoute"></param> /// <remarks> The pageId can be fetched from an earlier GET/POST response of pages endpoint (e.g. GET https://www.onenote.com/api/v1.0/pages ). /// </remarks> /// <returns>The converted HTTP response message</returns> public static async Task <ApiBaseResponse> GetASpecificPageContent(bool debug, string pageId, AuthProvider provider, string apiRoute) { if (debug) { Debugger.Launch(); Debugger.Break(); } var client = new HttpClient(); // Note: Page content is returned in a same HTML fashion supported by POST Pages client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html")); // Not adding the Authentication header would produce an unauthorized call and the API will return a 401 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await Auth.GetAuthToken(provider)); // Prepare an HTTP GET request to the Pages endpoint var getMessage = new HttpRequestMessage(HttpMethod.Get, apiRoute + "pages/" + pageId + "/content"); // ?includeIDs=true"); HttpResponseMessage response = await client.SendAsync(getMessage); ApiBaseResponse apiResponse = await TranslatePageContentResponse(response); // check if response has a vcard if yes then process vcard. bool isvCardPreset = apiResponse.Body.Contains(".vcf"); if (isvCardPreset) { // load it into xml dom or somehow extract the <object> tag holding the .vcf entry. var getvCard = new HttpRequestMessage(HttpMethod.Get, "https://www.onenote.com/api/v1.0/me/notes/resources/1-20864c3a4d904265b609203706ab868c!1-6198c848-9990-4de3-a235-ff07a2901b67/$value"); HttpResponseMessage vCardResponse = await client.SendAsync(getvCard); string vCardBody = await vCardResponse.Content.ReadAsStringAsync(); Debug.WriteLine("vCardBody:" + vCardBody); var bizCards = Deserializer.GetVCards(vCardBody); foreach (var card in bizCards) { var topBizCard = card; Debug.WriteLine("Formatted Name: " + topBizCard.FormattedName); Debug.WriteLine("First Name: " + topBizCard.FirstName); Debug.WriteLine("Last Name: " + topBizCard.LastName); Debug.WriteLine("Org Name: " + topBizCard.Organization); Debug.WriteLine("Url: " + topBizCard.Url.ToString()); foreach (var email in topBizCard.Emails) { Debug.WriteLine("EMail Type (" + email.Type + ") - Tel Number : " + email.EmailAddress); } foreach (var telNo in topBizCard.Telephones) { Debug.WriteLine("Tel Type (" + telNo.Type + ") - Tel Number : " + telNo.Number); } } } return(apiResponse); }
public void OnActionExecuted(ActionExecutedContext context) { if (context.Result is OkObjectResult okObjectResult) { var newResponse = new ApiBaseResponse <object> { Data = okObjectResult.Value }; context.Result = new OkObjectResult(newResponse); } }
public JsonResult <ApiBaseResponse> LoginByPhone([FromUri] string phoneNumber) { var result = new ApiBaseResponse(); try { var user = Mapper.Map <OntextUser, ApiUser>(UserManager.FindByPhoneNumber(phoneNumber)); if (user == null) { var userEntity = new OntextUser(); var phone = ServicesHost.GetService <IPhonesProvider>().GetByPhoneNumber(phoneNumber) ?? new ApiPhone { Number = phoneNumber }; userEntity.UserName = Guid.NewGuid().ToString(); userEntity.TwoFactorEnabled = true; var userPassword = OntextSettings.UserDefaultPassword; var r = UserManager.Create(userEntity, userPassword); if (!r.Succeeded) { result.Status = Core.Enums.ApiStatusCode.WrongArgumentsOrData; return(Json(result)); } phone.UserId = userEntity.Id; ServicesHost.GetService <IPhonesProvider>().Save(phone); user = Mapper.Map <OntextUser, ApiUser>(UserManager.FindByPhoneNumber(phoneNumber)); } var purpose = IdentityUserTokenHelper.GenerateTokenPurpose(IdentityUserTokenHelper.TokenPurpose.Loging, phoneNumber); var token = UserManager.GenerateUserToken(purpose, user.Id); #if DEBUG UserManager.SendEmail(ConfigurationManager.AppSettings["Email"], "Security Code", token); #else UserManager.SendSms(phoneNumber, token); #endif } catch (Exception ex) { result.Status = Core.Enums.ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
/// <summary> /// Update a message /// </summary> /// <param name="value">Message to update</param> /// <returns></returns> public JsonResult <ApiBaseResponse> Put([FromBody] ApiMessage value) { var result = new ApiBaseResponse(); try { ServicesHost.GetService <IMessagesProvider>().Save(value); } catch (Exception ex) { result.Status = ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
/// <summary> /// Delete a contact /// </summary> /// <param name="id">Contact ID</param> /// <returns></returns> public JsonResult <ApiBaseResponse> Delete(Guid id) { var result = new ApiBaseResponse(); try { ServicesHost.GetService <IContactsProvider>().Delete(id); } catch (Exception ex) { result.Status = Core.Enums.ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
public JsonResult <ApiBaseResponse> SaveUserSettings([FromBody] ApiSettings settings) { var result = new ApiBaseResponse(); try { ServicesHost.GetService <ISettingsProvider>().Save(settings); } catch (Exception ex) { result.Status = Core.Enums.ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
public JsonResult <ApiBaseResponse> DeleteAll(Guid userId) { var result = new ApiBaseResponse(); try { ServicesHost.GetService <IMessagesProvider>().DeleteAll(userId); } catch (Exception ex) { result.Status = ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
public JsonResult <ApiBaseResponse> Delete(Guid id) { var result = new ApiBaseResponse(); try { var filePath = HostingEnvironment.MapPath(string.Format("{0}{1}{2}", OntextSettings.UploadImageDirectoryPath, id, OntextSettings.UploadImageExtension)); File.Delete(filePath); } catch (Exception ex) { result.Status = ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
/// <summary> /// Convert the HTTP response message into a simple structure suitable for apps to process /// </summary> /// <param name="response">The response to convert</param> /// <returns>A simple response</returns> private static async Task <ApiBaseResponse> TranslatePageContentResponse(HttpResponseMessage response) { string body = await response.Content.ReadAsStringAsync(); var apiBaseResponse = new ApiBaseResponse(); // Extract the correlation id. Apps should log this if they want to collect the data to diagnose failures with Microsoft support IEnumerable <string> correlationValues; if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues)) { apiBaseResponse.CorrelationId = correlationValues.FirstOrDefault(); } apiBaseResponse.StatusCode = response.StatusCode; apiBaseResponse.Body = body; return(apiBaseResponse); }
public JsonResult <ApiBaseResponse> ChangePhoneNumber([FromUri] Guid userId, string oldPhoneNumber, string newPhoneNumber, string code) { var result = new ApiBaseResponse(); try { var user = UserManager.FindById(userId); var oldPhone = ServicesHost.GetService <IPhonesProvider>().GetByPhoneNumber(oldPhoneNumber); var newPhone = ServicesHost.GetService <IPhonesProvider>().GetByPhoneNumber(newPhoneNumber); var validCode = UserManager.VerifyUserToken(userId, IdentityUserTokenHelper.GenerateTokenPurpose(IdentityUserTokenHelper.TokenPurpose.Editing, newPhoneNumber), code); if (!validCode || user == null || (oldPhone == null || oldPhone.UserId != userId) || (newPhone != null && newPhone.UserId.HasValue && newPhone.UserId != Guid.Empty)) { result.Status = Core.Enums.ApiStatusCode.WrongArgumentsOrData; return(Json(result)); } if (newPhone == null) { newPhone = new ApiPhone { Number = newPhoneNumber, UserId = user.Id }; ServicesHost.GetService <IPhonesProvider>().Save(newPhone); } else { newPhone.UserId = user.Id; ServicesHost.GetService <IPhonesProvider>().Save(newPhone); } oldPhone.UserId = null; ServicesHost.GetService <IPhonesProvider>().Save(oldPhone); } catch (Exception ex) { result.Status = Core.Enums.ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
public JsonResult <ApiBaseResponse> SaveUserDeviceToken([FromUri] Guid userId, string token) { var result = new ApiBaseResponse(); try { var userEntity = UserManager.FindById(userId); if (userEntity == null) { result.Status = Core.Enums.ApiStatusCode.WrongArgumentsOrData; } else { var device = ServicesHost.GetService <IDevicesProvider>().GetByToken(token); if (device == null) { device = new ApiDevice { Token = token, UserId = userEntity.Id }; ServicesHost.GetService <IDevicesProvider>().Save(device); } else if (device.UserId != userEntity.Id) { device.UserId = userEntity.Id; ServicesHost.GetService <IDevicesProvider>().Save(device); } } } catch (Exception ex) { result.Status = Core.Enums.ApiStatusCode.SystemError; result.Error = ex.Message; } return(Json(result)); }
/// <summary> /// This method does the following operations : ///Takes the patient records, converts it to XML and calls the repository for saving the information. /// /// </summary> /// <param name="patientDetailViewModel"></param> /// <returns></returns> public async Task <ApiBaseResponse> AddPatientAsync(PatientDetailViewModel patientDetailViewModel) { var response = new ApiBaseResponse(); try { var patientDetail = new PatientDetail { Record = patientDetailViewModel.SerializeObject() }; await _patientRepository.AddPatientAsync(patientDetail); response.StatusCode = HttpStatusCode.OK; } catch (Exception ex) { response.StatusCode = HttpStatusCode.BadRequest; response.Error = "Error Occured while saving patient information"; _logger.LogError("Error Occured while saving patient information", ex); } return(response); }
/// <summary> /// Convert the HTTP response message into a simple structure suitable for apps to process /// </summary> /// <param name="response">The response to convert</param> /// <returns>A simple response</returns> private static async Task <ApiBaseResponse> TranslatePatchResponse(HttpResponseMessage response) { var apiBaseResponse = new ApiBaseResponse();; string body = await response.Content.ReadAsStringAsync(); // PATCH returns 204 NoContent upon success apiBaseResponse.StatusCode = response.StatusCode; //If the request was successful, the response body will be empty. //Otherwise, it will contain errors or warnings relevant to your request apiBaseResponse.Body = body; // Extract the correlation id. Apps should log this if they want to collect the data to diagnose failures with Microsoft support IEnumerable <string> correlationValues; if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues)) { apiBaseResponse.CorrelationId = correlationValues.FirstOrDefault(); } return(apiBaseResponse); }
private static Task HandleErrorAsync(HttpContext context, Exception exception) { var errorCode = "error"; var statusCode = HttpStatusCode.BadRequest; var applicationCode = ApplicationStatusCode.AnErrorHasOccured; var message = "There was an error."; switch (exception) { case BlogSolutionException e: errorCode = e.Code; message = e.Message; applicationCode = e.ApplicationStatusCode; break; } var response = new ApiBaseResponse(statusCode, applicationCode, null, message); var payload = JsonConvert.SerializeObject(response); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)statusCode; return(context.Response.WriteAsync(payload)); }
/// <summary> /// Convert the HTTP response message into a simple structure suitable for apps to process /// </summary> /// <param name="response">The response to convert</param> /// <returns>A simple response</returns> private static async Task<ApiBaseResponse> TranslateNotebookResponse(HttpResponseMessage response) { ApiBaseResponse apiBaseResponse; string body = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK /* GET Pages calls always return 200-OK upon success */) { apiBaseResponse = JsonConvert.DeserializeObject<GenericEntityResponse>(body); } else { apiBaseResponse = new ApiBaseResponse(); } // Extract the correlation id. Apps should log this if they want to collect the data to diagnose failures with Microsoft support IEnumerable<string> correlationValues; if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues)) { apiBaseResponse.CorrelationId = correlationValues.FirstOrDefault(); } apiBaseResponse.StatusCode = response.StatusCode; apiBaseResponse.Body = body; return apiBaseResponse; }
/// <summary> /// Convert the HTTP response message into a simple structure suitable for apps to process /// </summary> /// <param name="response">The response to convert</param> /// <returns>A simple response</returns> private static async Task<ApiBaseResponse> TranslatePatchResponse(HttpResponseMessage response) { var apiBaseResponse = new ApiBaseResponse();; string body = await response.Content.ReadAsStringAsync(); // PATCH returns 204 NoContent upon success apiBaseResponse.StatusCode = response.StatusCode; //If the request was successful, the response body will be empty. //Otherwise, it will contain errors or warnings relevant to your request apiBaseResponse.Body = body; // Extract the correlation id. Apps should log this if they want to collect the data to diagnose failures with Microsoft support IEnumerable<string> correlationValues; if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues)) { apiBaseResponse.CorrelationId = correlationValues.FirstOrDefault(); } return apiBaseResponse; }
private async void SendButton_Click(object sender, RoutedEventArgs e) { ApiBaseResponse response = await CreateSimplePage(HeadingBox.Text, BodyBox.Text); StatusTextBox.Text = "The Note can be accessed via\n " + response.Links.OneNoteWebUrl.Href.ToString() + "\n" + response.Body.ToString(); }
/// <summary> /// Convert the HTTP response message into a simple structure suitable for apps to process /// </summary> /// <param name="response">The response to convert</param> /// <returns>A simple response</returns> private static async Task<ApiBaseResponse> TranslatePageContentResponse(HttpResponseMessage response) { string body = await response.Content.ReadAsStringAsync(); var apiBaseResponse = new ApiBaseResponse(); // Extract the correlation id. Apps should log this if they want to collect the data to diagnose failures with Microsoft support IEnumerable<string> correlationValues; if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues)) { apiBaseResponse.CorrelationId = correlationValues.FirstOrDefault(); } apiBaseResponse.StatusCode = response.StatusCode; apiBaseResponse.Body = body; return apiBaseResponse; }
public static ApiBaseResponse <T> WrapResponse <T>(this T data, string path, HttpStatusCode statusCode = HttpStatusCode.OK) => ApiBaseResponse <T> .Wrap(data, path, statusCode);