public TwitterSearchException(RequestResult searchResult, string query) : base(string.Format( "Twitter search error. TwitterSearchResult: {0}; query: {1}", Enum.GetName(typeof(RequestResult), searchResult), query)) { }
internal RetryContext(int currentRetryCount, RequestResult lastRequestResult, StorageLocation nextLocation, LocationMode locationMode) { this.CurrentRetryCount = currentRetryCount; this.LastRequestResult = lastRequestResult; this.NextLocation = nextLocation; this.LocationMode = locationMode; }
private static void SetupContext() { _playback = new Playback(); _playback.AddEtlFiles(ConfigurationConstants.HttpServerTrace); _all = _playback.GetObservable<Parse>(); _result = new RequestResult<List<Parse>> { Data = new List<Parse>() }; }
/// <summary> /// Initializes a new instance of the ByteCountingStream class with an expandable capacity initialized to zero. /// </summary> public ByteCountingStream(Stream wrappedStream, RequestResult requestObject) : base() { CommonUtility.AssertNotNull("WrappedStream", wrappedStream); CommonUtility.AssertNotNull("RequestObject", requestObject); this.wrappedStream = wrappedStream; this.requestObject = requestObject; }
public static void AccessToken(HyvesServicesCallback<AccessToken> serviceCallback) { HyvesApplication hyvesApplication = HyvesApplication.GetInstance(); Dictionary<string, string> parameters = new Dictionary<string, string>(); HyvesRequest<AccessToken> hyvesRequest = HyvesRequestFactory.GetHyvesRequest<AccessToken>(); RequestResult<AccessToken> requestResult = new RequestResult<AccessToken>() { Callback = serviceCallback }; hyvesRequest.Request(HyvesMethod.AuthAccesstoken, parameters, hyvesApplication.RequestToken, hyvesApplication.RequestTokenSecret, new RequestCallbackDelegate<AccessToken>(AccessTokenResponseCallback), requestResult); }
private static void AccessTokenResponseCallback(RequestResult<AccessToken> requestResult) { ServiceResult<AccessToken> serviceResult = new ServiceResult<AccessToken>() { IsError = requestResult.IsError, Execption = requestResult.Execption, Message = requestResult.Message }; if (!requestResult.IsError) { AccessToken requestToken = JsonConvert.DeserializeObject<AccessToken>(requestResult.Response); serviceResult.Result = requestToken; } requestResult.Callback(serviceResult); }
private static void UsersGetByFriendsLastLoginReponseCallback(RequestResult<List<User>> requestResult) { ServiceResult<List<User>> serviceResult = new ServiceResult<List<User>>() { IsError = requestResult.IsError, Execption = requestResult.Execption, Message = requestResult.Message }; if (!requestResult.IsError) { UsersGetByFriendsLastLoginResponse usersGetByFriendsLastLoginResponse = JsonConvert.DeserializeObject<UsersGetByFriendsLastLoginResponse>(requestResult.Response); serviceResult.Result = usersGetByFriendsLastLoginResponse.user; } requestResult.Callback(serviceResult); }
public static void login(string username, string password, HyvesServicesCallback<RequestToken> serviceCallback) { Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters["username"] = username; parameters["userpassword"] = password; HyvesApplication hyvesApplication = HyvesApplication.GetInstance(); HyvesRequest<RequestToken> hyvesRequest = HyvesRequestFactory.GetHyvesRequestSecure<RequestToken>(); RequestResult<RequestToken> requestResult = new RequestResult<RequestToken>() { Callback = serviceCallback }; hyvesRequest.Request(HyvesMethod.AuthLogin, parameters,"", "", new RequestCallbackDelegate<RequestToken>(LoginReponseCallback), requestResult); }
public static void RequestToken(HyvesServicesCallback<RequestToken> serviceCallback) { HyvesApplication hyvesApplication = HyvesApplication.GetInstance(); Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters["methods"] = GetMethods(HyvesMethod.All); HyvesRequest<RequestToken> hyvesRequest = HyvesRequestFactory.GetHyvesRequest<RequestToken>(); RequestResult<RequestToken> requestResult = new RequestResult<RequestToken>() { Callback = serviceCallback }; hyvesRequest.Request(HyvesMethod.AuthRequesttoken, parameters, "", "", new RequestCallbackDelegate<RequestToken>(RequestTokenReponseCallback), requestResult); }
internal async static Task<StorageException> PopulateStorageExceptionFromHttpResponseMessage(HttpResponseMessage response, RequestResult currentResult, Func<Stream, HttpResponseMessage, string, StorageExtendedErrorInformation> parseError) { if (!response.IsSuccessStatusCode) { try { currentResult.HttpStatusMessage = response.ReasonPhrase; currentResult.HttpStatusCode = (int)response.StatusCode; currentResult.ServiceRequestID = HttpResponseMessageUtils.GetHeaderSingleValueOrDefault(response.Headers, Constants.HeaderConstants.RequestIdHeader); string tempDate = HttpResponseMessageUtils.GetHeaderSingleValueOrDefault(response.Headers, Constants.HeaderConstants.Date); currentResult.RequestDate = string.IsNullOrEmpty(tempDate) ? DateTime.Now.ToString("R", CultureInfo.InvariantCulture) : tempDate; if (response.Headers.ETag != null) { currentResult.Etag = response.Headers.ETag.ToString(); } if (response.Content != null && response.Content.Headers.ContentMD5 != null) { currentResult.ContentMd5 = Convert.ToBase64String(response.Content.Headers.ContentMD5); } } catch (Exception) { // no op } try { Stream errStream = await response.Content.ReadAsStreamAsync(); if (parseError != null) { currentResult.ExtendedErrorInformation = parseError(errStream, response, response.Content.Headers.ContentType.ToString()); } else { currentResult.ExtendedErrorInformation = StorageExtendedErrorInformation.ReadFromStream(errStream.AsInputStream()); } } catch (Exception) { // no op } return new StorageException(currentResult, response.ReasonPhrase, null); } else { return null; } }
internal static StorageException GenerateTimeoutException(RequestResult res, Exception inner) { if (res != null) { res.HttpStatusCode = 408; // RequestTimeout } TimeoutException timeoutEx = new TimeoutException(SR.TimeoutExceptionMessage, inner); return new StorageException(res, timeoutEx.Message, timeoutEx) { IsRetryable = false }; }
internal static string ExtractEntityIndexFromExtendedErrorInformation(RequestResult result) { if (result != null && result.ExtendedErrorInformation != null && !string.IsNullOrEmpty(result.ExtendedErrorInformation.ErrorMessage)) { int semiDex = result.ExtendedErrorInformation.ErrorMessage.IndexOf(":"); if (semiDex > 0 && semiDex < 3) { return result.ExtendedErrorInformation.ErrorMessage.Substring(0, semiDex); } } return null; }
public RequestResult WaitFor(Action request, int timeout) { var result = new RequestResult(); using (var listener = new HttpListener()) { var server = listener; Action test = () => { server.Prefixes.Add(_listenUri); server.Start(); request(); var context = server.GetContext(); result.ContentType = context.Request.ContentType; result.HttpMethod = context.Request.HttpMethod; try { using (var reader = new StreamReader(context.Request.InputStream)) { var body = reader.ReadToEnd(); var serializer = new JavaScriptSerializer(); result.Json = serializer.Deserialize<Dictionary<string, object>>(body); } context.Response.StatusCode = 200; } catch { context.Response.StatusCode = 500; } finally { context.Response.Close(); } }; result.TimedOut = Wait(test, timeout); listener.Stop(); listener.Close(); } return result; }
/// <summary> /// 向指定地址发送一个 GET 请求。 /// </summary> /// <param name="url">要请求的地址。</param> /// <returns>请求返回的结果。</returns> public static RequestResult<string> SendGetRequest(string url) { var requestResult = new RequestResult<string>(); try { var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Method = "GET"; var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var responseStream = httpWebResponse.GetResponseStream()) { using (var streamReader = new StreamReader(responseStream, Encoding.UTF8)) { requestResult.OperateResult = OperateResultEnum.Success; requestResult.Code = httpWebResponse.StatusCode; requestResult.Result = streamReader.ReadToEnd(); } } } catch (WebException e) { using (var errorResponseStream = e.Response.GetResponseStream()) { using (var errorStreamReader = new StreamReader(errorResponseStream, Encoding.UTF8)) { requestResult.OperateResult = OperateResultEnum.Fail; var httpWebResponse = e.Response as HttpWebResponse; if (httpWebResponse != null) requestResult.Code = httpWebResponse.StatusCode; requestResult.ErrorMsg = errorStreamReader.ReadToEnd(); } } } catch (Exception e1) { requestResult.OperateResult = OperateResultEnum.Fail; requestResult.ErrorMsg = e1.ToString(); } return requestResult; }
public static RequestResult GetTreeItem(List <Organization> organizations, Guid rootOrganizationId, Account account) { RequestResult requestResult = new RequestResult(); try { var treeItems = new List <TreeItem>(); var attributes = new Dictionary <Define.EnumTreeAttribute, string>() { { Define.EnumTreeAttribute.NodeType, string.Empty }, { Define.EnumTreeAttribute.ToolTip, string.Empty }, { Define.EnumTreeAttribute.OrganizationId, string.Empty }, { Define.EnumTreeAttribute.PersonId, string.Empty } }; using (CFContext context = new CFContext()) { if (account.QueryableOrganizationIds.Contains(rootOrganizationId)) { var people = context.People.Where(p => p.OrganizationId == rootOrganizationId).OrderBy(p => p.LoginId).ToList(); foreach (var p in people) { var treeItem = new TreeItem() { Title = p.Name }; attributes[Define.EnumTreeAttribute.NodeType] = Define.EnumTreeNodeType.Person.ToString(); attributes[Define.EnumTreeAttribute.ToolTip] = string.Format("{0}/{1}", p.LoginId, p.Name); attributes[Define.EnumTreeAttribute.OrganizationId] = rootOrganizationId.ToString(); attributes[Define.EnumTreeAttribute.LoginId] = p.LoginId; foreach (var a in attributes) { treeItem.Attributes[a.Key.ToString()] = a.Value; } treeItems.Add(treeItem); } } var newOrganizations = organizations.Where(o => o.ParentId == rootOrganizationId && account.VisibleOrganizationIds.Contains(o.OrganizationId)).OrderBy(o => o.OId).ToList(); foreach (var o in newOrganizations) { var treeItem = new TreeItem() { Title = o.Name }; attributes[Define.EnumTreeAttribute.NodeType] = Define.EnumTreeNodeType.Organization.ToString(); attributes[Define.EnumTreeAttribute.ToolTip] = string.Format("{0}/{1}", o.OId, o.Name); attributes[Define.EnumTreeAttribute.OrganizationId] = o.OrganizationId.ToString(); attributes[Define.EnumTreeAttribute.LoginId] = string.Empty; foreach (var a in attributes) { treeItem.Attributes[a.Key.ToString()] = a.Value; } bool haveDownStreamOrganization = organizations.Any(os => os.ParentId == o.OrganizationId && account.VisibleOrganizationIds.Contains(os.OrganizationId)); bool havePerson = account.QueryableOrganizationIds.Contains(o.OrganizationId) && context.People.Any(p => p.OrganizationId == o.OrganizationId); if (haveDownStreamOrganization || havePerson) { treeItem.State = "closed"; } treeItems.Add(treeItem); } } requestResult.ReturnData(treeItems); } catch (Exception e) { var error = new Error(MethodBase.GetCurrentMethod(), e); Logger.Log(error); requestResult.ReturnError(error); //throw; } return(requestResult); }
/// <summary> /// Default Constructor /// </summary> public GetRecipeResponse() { Result = new RequestResult(); }
public void ShouldGetUserProfile() { UserProfile userProfile = new UserProfile { HdId = hdid, AcceptedTermsOfService = true, }; DBResult <UserProfile> userProfileDBResult = new DBResult <UserProfile> { Payload = userProfile, Status = DBStatusCode.Read }; UserProfileModel expected = UserProfileModel.CreateFromDbModel(userProfile); LegalAgreement termsOfService = new LegalAgreement() { Id = Guid.NewGuid(), LegalText = "", EffectiveDate = DateTime.Now }; Mock <IEmailQueueService> emailer = new Mock <IEmailQueueService>(); Mock <IUserProfileDelegate> profileDelegateMock = new Mock <IUserProfileDelegate>(); profileDelegateMock.Setup(s => s.GetUserProfile(hdid)).Returns(userProfileDBResult); profileDelegateMock.Setup(s => s.Update(userProfile, true)).Returns(userProfileDBResult); UserPreference dbUserPreference = new UserPreference { HdId = hdid, Preference = "TutorialPopover", Value = true.ToString(), }; List <UserPreference> userPreferences = new List <UserPreference>(); userPreferences.Add(dbUserPreference); DBResult <IEnumerable <UserPreference> > readResult = new DBResult <IEnumerable <UserPreference> > { Payload = userPreferences, Status = DBStatusCode.Read }; Mock <IUserPreferenceDelegate> preferenceDelegateMock = new Mock <IUserPreferenceDelegate>(); preferenceDelegateMock.Setup(s => s.GetUserPreferences(hdid)).Returns(readResult); Mock <IEmailDelegate> emailDelegateMock = new Mock <IEmailDelegate>(); Mock <IMessagingVerificationDelegate> emailInviteDelegateMock = new Mock <IMessagingVerificationDelegate>(); emailInviteDelegateMock.Setup(s => s.GetByInviteKey(It.IsAny <Guid>())).Returns(new MessagingVerification()); Mock <IConfigurationService> configServiceMock = new Mock <IConfigurationService>(); configServiceMock.Setup(s => s.GetConfiguration()).Returns(new ExternalConfiguration()); Mock <ILegalAgreementDelegate> legalAgreementDelegateMock = new Mock <ILegalAgreementDelegate>(); legalAgreementDelegateMock .Setup(s => s.GetActiveByAgreementType(LegalAgreementType.TermsofService)) .Returns(new DBResult <LegalAgreement>() { Payload = termsOfService }); Mock <ICryptoDelegate> cryptoDelegateMock = new Mock <ICryptoDelegate>(); Mock <INotificationSettingsService> notificationServiceMock = new Mock <INotificationSettingsService>(); Mock <IMessagingVerificationDelegate> messageVerificationDelegateMock = new Mock <IMessagingVerificationDelegate>(); IUserProfileService service = new UserProfileService( new Mock <ILogger <UserProfileService> >().Object, profileDelegateMock.Object, preferenceDelegateMock.Object, emailDelegateMock.Object, emailInviteDelegateMock.Object, configServiceMock.Object, emailer.Object, legalAgreementDelegateMock.Object, cryptoDelegateMock.Object, notificationServiceMock.Object, messageVerificationDelegateMock.Object, new Mock <IPatientService>().Object); RequestResult <UserProfileModel> actualResult = service.GetUserProfile(hdid); Assert.Equal(ResultType.Success, actualResult.ResultStatus); Assert.True(actualResult.ResourcePayload.IsDeepEqual(expected)); }
/// <summary> /// Retrieve an item of type <typeparamref name="T" /> from the Blizzard Community /// or Game Data API. /// </summary> /// <typeparam name="T"> /// The return type. /// </typeparam> /// <param name="requestUri"> /// The URI the request is sent to. /// </param> /// <param name="arrayName"> /// The name of the array to deserialize to prevent the use of JSON root objects. /// </param> /// <returns> /// The JSON response, deserialized to an object of type <typeparamref name="T" />. /// </returns> protected async Task <RequestResult <T> > Get <T>(string requestUri, string?arrayName = null) where T : class { // Acquire a new OAuth token if we don't have one. Get a new one if it's expired. if (_token == null || DateTime.UtcNow >= _tokenExpiration) { _token = await GetOAuthToken().ConfigureAwait(false); _tokenExpiration = DateTime.UtcNow.AddSeconds(_token.ExpiresIn).AddSeconds(-30); } // Add an authentication header with the token. _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token.AccessToken); // Retrieve the response. var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; var request = new HttpRequestMessage(HttpMethod.Get, requestUri); using var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false); if (response.IsSuccessStatusCode && response.Content != null) { var stream = await response.Content.ReadAsStreamAsync(); var json = await StreamToStringAsync(stream); if (string.IsNullOrEmpty(json)) { var requestError = JsonConvert.DeserializeObject <RequestError>(json); return(requestError); } try { if (arrayName != null) { json = JObject.Parse(json).SelectToken(arrayName).ToString(); } RequestResult <T> requestResult = JsonConvert.DeserializeObject <T>(json, new JsonSerializerSettings { ContractResolver = new BaseClientContractResolver(), MissingMemberHandling = MissingMemberHandling.Error }); return(requestResult); } catch (JsonReaderException ex) { var requestError = new RequestError { Code = string.Empty, Detail = ex.Message, Type = typeof(JsonReaderException).ToString() }; return(new RequestResult <T>(requestError)); } } // If not then it is most likely a problem on our end due to an HTTP error. var message = $"Response code {(int) response.StatusCode} ({response.ReasonPhrase}) does not indicate success. Request: {requestUri}"; throw new HttpRequestException(message); }
public ApiResult PostEdit(Page page, string text, string reason, string section = null, bool minor = false, bool watch = false, bool SuppressSummary = false, bool Create = true) { ApiResult result = new ApiResult(null, null, null); string token = null; bool InvalidToken = false; while (!InvalidToken) { while (token == null) { if (section != null || Variables.EditToken == null) { result = ApiRequest("action=query&prop=info&intoken=edit&titles=" + System.Web.HttpUtility.UrlEncode(page.Name)); if (result.ResultInError) { return result; } token = GetParameter(result.Text, "edittoken"); } } } return result; }
protected virtual void ValidateDelete(long id, RequestResult result) { }
public static RequestResult GetRootTreeItem(List <Organization> organizationList, Guid rootOrganizationId, Account account) { RequestResult requestResult = new RequestResult(); try { var treeItems = new List <TreeItem>(); var attributes = new Dictionary <Define.EnumTreeAttribute, string>() { { Define.EnumTreeAttribute.NodeType, string.Empty }, { Define.EnumTreeAttribute.ToolTip, string.Empty }, { Define.EnumTreeAttribute.OrganizationId, string.Empty }, { Define.EnumTreeAttribute.MaterialType, string.Empty }, { Define.EnumTreeAttribute.MaterialSpecificationId, string.Empty } }; using (CFContext context = new CFContext()) { var organization = organizationList.First(x => x.OrganizationId == rootOrganizationId); var treeItem = new TreeItem() { Title = organization.Name }; attributes[Define.EnumTreeAttribute.NodeType] = Define.EnumTreeNodeType.Organization.ToString(); attributes[Define.EnumTreeAttribute.ToolTip] = string.Format("{0}/{1}", organization.OId, organization.Name); attributes[Define.EnumTreeAttribute.OrganizationId] = organization.OrganizationId.ToString(); attributes[Define.EnumTreeAttribute.MaterialType] = string.Empty; attributes[Define.EnumTreeAttribute.MaterialSpecificationId] = string.Empty; foreach (var attribute in attributes) { treeItem.Attributes[attribute.Key.ToString()] = attribute.Value; } var haveDownStreamOrganization = organizationList.Any(x => x.ParentId == organization.OrganizationId && account.VisibleOrganizationIds.Contains(x.OrganizationId)); var haveMaterialSpecification = account.QueryableOrganizationIds.Contains(organization.OrganizationId) && context.MSpecifications.Any(x => x.OrganizationId == organization.OrganizationId); if (haveDownStreamOrganization || haveMaterialSpecification) { treeItem.State = "closed"; } treeItems.Add(treeItem); } requestResult.ReturnData(treeItems); } catch (Exception e) { var error = new Error(MethodBase.GetCurrentMethod(), e); Logger.Log(error); requestResult.ReturnError(error); } return(requestResult); }
public static RequestResult GetEditFormModel(string materialSpecificationId) { RequestResult requestResult = new RequestResult(); try { using (CFContext context = new CFContext()) { var specification = context.MSpecifications.First(x => x.MSpecificationId == new Guid(materialSpecificationId)); var editFormModel = new EditFormModel() { MaterialSpecificationId = specification.MSpecificationId.ToString(), OrganizationId = specification.OrganizationId.ToString(), ParentOrganizationFullName = OrganizationDataAccessor.GetOrganizationFullName(specification.OrganizationId), MaterialTypeSelectItems = new List <SelectListItem>() { Define.DefaultSelectListItem(Resources.Resource.Select), new SelectListItem() { Text = string.Format("{0}...", Resources.Resource.Create), Value = Define.New } }, FormInput = new FormInput() { MaterialType = specification.MaterialType, Name = specification.Name }, MaterialSpecificationOptionModels = context.MSOptions.Where(x => x.MSpecificationId == specification.MSpecificationId).Select(x => new MaterialSpecificationOptionModel { MaterialSpecificationOptionId = x.MSOptionId.ToString(), Name = x.Name, Seq = x.Seq }).OrderBy(x => x.Seq).ToList() }; var upStreamOrganizationIds = OrganizationDataAccessor.GetUpStreamOrganizationIds(specification.OrganizationId, true); editFormModel.MaterialTypeSelectItems.AddRange(context.MSpecifications.Where(x => upStreamOrganizationIds.Contains(x.OrganizationId)).Select(x => x.MaterialType).Distinct().OrderBy(x => x).Select(x => new SelectListItem { Value = x, Text = x }).ToList()); if (!string.IsNullOrEmpty(specification.MaterialType) && editFormModel.MaterialTypeSelectItems.Any(x => x.Value == specification.MaterialType)) { editFormModel.MaterialTypeSelectItems.First(x => x.Value == specification.MaterialType).Selected = true; } requestResult.ReturnData(editFormModel); } } catch (Exception e) { var error = new Error(MethodBase.GetCurrentMethod(), e); Logger.Log(error); requestResult.ReturnError(error); } return(requestResult); }
public static object Edit(EditFormModel editFormModel) { RequestResult requestResult = new RequestResult(); try { if (editFormModel.FormInput.MaterialType == Define.New) { requestResult.ReturnFailedMessage(string.Format("{0} {1}", Resources.Resource.Unsupported, Resources.Resource.MaterialType)); } else { using (CFContext context = new CFContext()) { var specification = context.MSpecifications.First(x => x.MSpecificationId == new Guid(editFormModel.MaterialSpecificationId)); var exists = context.MSpecifications.FirstOrDefault(x => x.MSpecificationId != specification.MSpecificationId && x.OrganizationId == specification.OrganizationId && x.MaterialType == editFormModel.FormInput.MaterialType && x.Name == editFormModel.FormInput.Name); if (exists == null) { #if !DEBUG using (TransactionScope trans = new TransactionScope()) { #endif #region MaterialSpecification specification.Name = editFormModel.FormInput.Name; specification.MaterialType = editFormModel.FormInput.MaterialType; context.SaveChanges(); #endregion #region MaterialSpecificationOption #region Delete context.MaterialSpecificationOptions.RemoveRange(context.MaterialSpecificationOptions.Where(x => x.MSpecificationId == new Guid(editFormModel.MaterialSpecificationId)).ToList()); context.SaveChanges(); #endregion #region Insert context.MSOptions.AddRange(editFormModel.FormInput.MaterialSpecificationOptionModels.Select(x => new CF.Models.Maintenance.MSOption { MSOptionId = !string.IsNullOrEmpty(x.MaterialSpecificationOptionId) ? new Guid(x.MaterialSpecificationOptionId) : Guid.NewGuid(), MSpecificationId = specification.MSpecificationId, Name = x.Name, Seq = x.Seq }).ToList()); context.SaveChanges(); #endregion #endregion #region MaterialSpecificaitonOptionValue var optionList = editFormModel.FormInput.MaterialSpecificationOptionModels.Where(x => !string.IsNullOrEmpty(x.MaterialSpecificationOptionId)).Select(x => x.MaterialSpecificationOptionId).ToList(); var specValueList = context.MaterialSpecificationOptions.Where(x => x.MSpecificationId == specification.MSpecificationId && !optionList.Contains(x.MSOptionId.ToString())).ToList(); foreach (var specValue in specValueList) { specValue.MSOptionId = Guid.Empty; } context.SaveChanges(); #endregion #if !DEBUG trans.Complete(); } #endif requestResult.ReturnSuccessMessage(string.Format("{0} {1} {2}", Resources.Resource.Edit, Resources.Resource.MaterialSpecification, Resources.Resource.Success)); } else { requestResult.ReturnFailedMessage(string.Format("{0} {1}", Resources.Resource.MaterialSpecificationName, Resources.Resource.Exists)); } } } } catch (Exception e) { var error = new Error(MethodBase.GetCurrentMethod(), e); Logger.Log(error); requestResult.ReturnError(error); } return(requestResult); }
public async Task GetMedications() { // Setup string hdid = "EXTRIOYFPNX35TWEBUAJ3DNFDFXSYTBC6J4M76GYE3HC5ER2NKWQ"; RequestResult <List <MedicationStatementHistory> > expectedResult = new RequestResult <List <MedicationStatementHistory> >() { ResultStatus = HealthGateway.Common.Constants.ResultType.Success, ResourcePayload = new List <MedicationStatementHistory>() { new MedicationStatementHistory() { PrescriptionIdentifier = "identifier", PrescriptionStatus = 'M', DispensedDate = DateTime.Parse("09/28/2020"), DateEntered = DateTime.Parse("09/28/2020"), Directions = "Directions", DispensingPharmacy = new Pharmacy() { AddressLine1 = "Line 1", AddressLine2 = "Line 2", CountryCode = "CA", City = "City", PostalCode = "A1A 1A1", Province = "PR", FaxNumber = "1111111111", Name = "Name", PharmacyId = "ID", PhoneNumber = "2222222222", }, MedicationSummary = new MedicationSummary() { DIN = "02242163", BrandName = "KADIAN 10MG CAPSULE", DrugDiscontinuedDate = DateTime.Parse("09/28/2020"), Form = "Form", GenericName = "Generic Name", IsPin = false, Manufacturer = "Nomos", MaxDailyDosage = 100, Quantity = 1, Strength = "Strong", StrengthUnit = "ml", }, PharmacyId = "Id", PractitionerSurname = "Surname", }, }, }; Mock <IMedicationStatementService> svcMock = new Mock <IMedicationStatementService>(); svcMock .Setup(s => s.GetMedicationStatementsHistory(hdid, null)) .ReturnsAsync(expectedResult); MedicationStatementController controller = new MedicationStatementController(null, svcMock.Object); // Act IActionResult actual = await controller.GetMedicationStatements(hdid); // Verify Assert.IsType <JsonResult>(actual); JsonResult jsonResult = (JsonResult)actual; Assert.IsType <RequestResult <List <MedicationStatementHistory> > >(jsonResult.Value); RequestResult <List <MedicationStatementHistory> > requestResult = (RequestResult <List <MedicationStatementHistory> >)jsonResult.Value; Assert.True(requestResult.IsDeepEqual(expectedResult)); }
internal bool ProcessCallback(DdemlTransaction transaction) { // This is here to alias the transaction object with a shorter variable name. DdemlTransaction t = transaction; switch (t.uType) { case Ddeml.XTYP_ADVREQ: { StringBuilder psz; int length; // Get the topic name from the hsz1 string handle. psz = new StringBuilder(Ddeml.MAX_STRING_SIZE); length = Ddeml.DdeQueryString(_InstanceId, t.hsz1, psz, psz.Capacity, Ddeml.CP_WINANSI); string topic = psz.ToString(); // Get the item name from the hsz2 string handle. psz = new StringBuilder(Ddeml.MAX_STRING_SIZE); length = Ddeml.DdeQueryString(_InstanceId, t.hsz2, psz, psz.Capacity, Ddeml.CP_WINANSI); string item = psz.ToString(); // Create the advise request cache key. string key = topic + "!" + item + ":" + t.uFmt.ToString(); // Get the data being advised if the cache does not contain it already. if (!_AdviseRequestCache.ContainsKey(key)) { // Get the data from the subclass. byte[] data = OnAdvise(topic, item, t.uFmt); // Add the data to the cache because it will be needed later. _AdviseRequestCache.Add(key, data); } // Get the data from the advise request cache. byte[] cached = _AdviseRequestCache[key]; // Get the number of remaining transactions of this type for the same topic name, item name, and format tuple. int remaining = t.dwData1.ToInt32(); // If this is the last transaction then free the data handle. if (remaining == 0) { // TODO: Does the data handle really need to be freed here? // Remove the data from the cache because it is no longer needed. _AdviseRequestCache.Remove(key); } // Create and return the data handle representing the data being advised. if (cached != null && cached.Length > 0) { t.dwRet = Ddeml.DdeCreateDataHandle(_InstanceId, cached, cached.Length, 0, t.hsz2, t.uFmt, 0); return true; } // This transaction could not be processed here. return false; } case Ddeml.XTYP_ADVSTART: { // Get the item name from the hsz2 string handle. StringBuilder psz = new StringBuilder(Ddeml.MAX_STRING_SIZE); int length = Ddeml.DdeQueryString(_InstanceId, t.hsz2, psz, psz.Capacity, Ddeml.CP_WINANSI); string item = psz.ToString(); // Get the Conversation from the conversation table. DdemlConversation conversation = _ConversationTable[t.hConv]; // Get a value indicating whether an advise loop should be initiated from the subclass. t.dwRet = OnStartAdvise(conversation, item, t.uFmt) ? new IntPtr(1) : IntPtr.Zero; return true; } case Ddeml.XTYP_ADVSTOP: { // Get the item name from the hsz2 string handle. StringBuilder psz = new StringBuilder(Ddeml.MAX_STRING_SIZE); int length = Ddeml.DdeQueryString(_InstanceId, t.hsz2, psz, psz.Capacity, Ddeml.CP_WINANSI); string item = psz.ToString(); // Get the Conversation from the conversation table. DdemlConversation conversation = _ConversationTable[t.hConv]; // Inform the subclass that the advise loop has been terminated. OnStopAdvise(conversation, item); // Return zero to indicate that there are no problems. t.dwRet = IntPtr.Zero; return true; } case Ddeml.XTYP_CONNECT: { // Get the topic name from the hsz1 string handle. StringBuilder psz = new StringBuilder(Ddeml.MAX_STRING_SIZE); int length = Ddeml.DdeQueryString(_InstanceId, t.hsz1, psz, psz.Capacity, Ddeml.CP_WINANSI); string topic = psz.ToString(); // Get a value from the subclass indicating whether the connection should be allowed. t.dwRet = OnBeforeConnect(topic) ? new IntPtr(1) : IntPtr.Zero; return true; } case Ddeml.XTYP_CONNECT_CONFIRM: { // Get the topic name from the hsz1 string handle. StringBuilder psz = new StringBuilder(Ddeml.MAX_STRING_SIZE); int length = Ddeml.DdeQueryString(_InstanceId, t.hsz1, psz, psz.Capacity, Ddeml.CP_WINANSI); string topic = psz.ToString(); // Create a Conversation object and add it to the conversation table. _ConversationTable.Add(t.hConv, new DdemlConversation(t.hConv, _Service, topic)); // Inform the subclass that a conversation has been established. OnAfterConnect(_ConversationTable[t.hConv]); // Return zero to indicate that there are no problems. t.dwRet = IntPtr.Zero; return true; } case Ddeml.XTYP_DISCONNECT: { // Get the Conversation from the conversation table. DdemlConversation conversation = _ConversationTable[t.hConv]; // Remove the Conversation from the conversation table. _ConversationTable.Remove(t.hConv); // Inform the subclass that the conversation has been disconnected. OnDisconnect(conversation); // Return zero to indicate that there are no problems. t.dwRet = IntPtr.Zero; return true; } case Ddeml.XTYP_EXECUTE: { // Get the command from the data handle. int length = Ddeml.DdeGetData(t.hData, null, 0, 0); byte[] data = new byte[length]; length = Ddeml.DdeGetData(t.hData, data, data.Length, 0); string command = _Context.Encoding.GetString(data, 0, data.Length); if (command[command.Length - 1] == '\0') { command = command.Substring(0, command.Length - 1); } // Get the Conversation from the conversation table. DdemlConversation conversation = _ConversationTable[t.hConv]; // Send the command to the subclass and get the result. ExecuteResult result = OnExecute(conversation, command); // Return DDE_FACK if the subclass processed the command successfully. if (result == ExecuteResult.Processed) { t.dwRet = new IntPtr(Ddeml.DDE_FACK); return true; } // Return CBR_BLOCK if the subclass needs time to process the command. if (result == ExecuteResult.PauseConversation) { // Increment the conversation's waiting count. conversation.IncrementWaiting(); t.dwRet = new IntPtr(Ddeml.CBR_BLOCK); return true; } // Return DDE_FBUSY if the subclass is too busy. if (result == ExecuteResult.TooBusy) { t.dwRet = new IntPtr(Ddeml.DDE_FBUSY); return true; } // Return DDE_FNOTPROCESSED if the subclass did not process the command. t.dwRet = new IntPtr(Ddeml.DDE_FNOTPROCESSED); return true; } case Ddeml.XTYP_POKE: { // Get the item name from the hsz2 string handle. StringBuilder psz = new StringBuilder(Ddeml.MAX_STRING_SIZE); int length = Ddeml.DdeQueryString(_InstanceId, t.hsz2, psz, psz.Capacity, Ddeml.CP_WINANSI); string item = psz.ToString(); // Get the data from the data handle. length = Ddeml.DdeGetData(t.hData, null, 0, 0); byte[] data = new byte[length]; length = Ddeml.DdeGetData(t.hData, data, data.Length, 0); // Get the Conversation from the conversation table. DdemlConversation conversation = _ConversationTable[t.hConv]; // Send the data to the subclass and get the result. PokeResult result = OnPoke(conversation, item, data, t.uFmt); // Return DDE_FACK if the subclass processed the data successfully. if (result == PokeResult.Processed) { t.dwRet = new IntPtr(Ddeml.DDE_FACK); return true; } // Return CBR_BLOCK if the subclass needs time to process the data. if (result == PokeResult.PauseConversation) { // Increment the conversation's waiting count. conversation.IncrementWaiting(); t.dwRet = new IntPtr(Ddeml.CBR_BLOCK); return true; } // Return DDE_FBUSY if the subclass is too busy. if (result == PokeResult.TooBusy) { t.dwRet = new IntPtr(Ddeml.DDE_FBUSY); return true; } // Return DDE_FNOTPROCESSED if the subclass did not process the data. t.dwRet = new IntPtr(Ddeml.DDE_FNOTPROCESSED); return true; } case Ddeml.XTYP_REQUEST: { // Get the item name from the hsz2 string handle. StringBuilder psz = new StringBuilder(Ddeml.MAX_STRING_SIZE); int length = Ddeml.DdeQueryString(_InstanceId, t.hsz2, psz, psz.Capacity, Ddeml.CP_WINANSI); string item = psz.ToString(); // Get the Conversation from the conversation table. DdemlConversation conversation = _ConversationTable[t.hConv]; // Send the request to the subclass and get the result. RequestResult result = OnRequest(conversation, item, t.uFmt); // Return a data handle if the subclass processed the request successfully. if (result == RequestResult.Processed) { // Create and return the data handle for the data being requested. if (result.Data != null) { t.dwRet = Ddeml.DdeCreateDataHandle(_InstanceId, result.Data, result.Data.Length, 0, t.hsz2, t.uFmt, 0); } return true; } // Return CBR_BLOCK if the subclass needs time to process the request. if (result == RequestResult.PauseConversation) { conversation.IncrementWaiting(); t.dwRet = new IntPtr(Ddeml.CBR_BLOCK); return true; } // Return DDE_FNOTPROCESSED if the subclass did not process the command. t.dwRet = new IntPtr(Ddeml.DDE_FNOTPROCESSED); return true; } } // This transaction could not be processed here. return false; }
public void OnError(RequestResult info) { appstore.logger.DebugLog(string.Format("onReceiptValidation() called with: {0}", info.data.DebugAsString())); }
public async Task CloudBlobClientMaximumExecutionTimeoutAsync() { CloudBlobClient blobClient = GenerateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(Guid.NewGuid().ToString("N")); byte[] buffer = BlobTestBase.GetRandomBuffer(20 * 1024 * 1024); try { await container.CreateAsync(); CloudBlockBlob blockBlob = container.GetBlockBlobReference("blob1"); CloudPageBlob pageBlob = container.GetPageBlobReference("blob2"); blobClient.MaximumExecutionTime = TimeSpan.FromSeconds(5); using (MemoryStream ms = new MemoryStream(buffer)) { try { await blockBlob.UploadFromStreamAsync(ms.AsInputStream()); } catch (Exception ex) { Assert.AreEqual("The client could not finish the operation within specified timeout.", RequestResult.TranslateFromExceptionMessage(ex.Message).ExceptionInfo.Message); } } using (MemoryStream ms = new MemoryStream(buffer)) { try { await pageBlob.UploadFromStreamAsync(ms.AsInputStream()); } catch (AggregateException ex) { Assert.AreEqual("The client could not finish the operation within specified timeout.", RequestResult.TranslateFromExceptionMessage(ex.InnerException.InnerException.Message).ExceptionInfo.Message); } } } finally { blobClient.MaximumExecutionTime = null; container.DeleteIfExistsAsync().AsTask().Wait(); } }
public static RequestResult Create(CreateFormModel model) { RequestResult requestResult = new RequestResult(); try { using (CFContext context = new CFContext()) { var exists = context.People.FirstOrDefault(p => p.LoginId == model.FormInput.Id); if (exists == null) { bool exceedsLimit = false; var upStreamOrganizationIds = OrganizationDataAccessor.GetUpStreamOrganizationIds(new Guid(model.OrganizationId), true); PopulationLimit populationLimit = null; foreach (var item in Config.PopulationLimits) { if (upStreamOrganizationIds.Contains(item.OrganizationId)) { populationLimit = item; break; } } if (populationLimit != null) { var organization = OrganizationDataAccessor.GetOrganization(populationLimit.OrganizationId); var downStreamOrganizations = OrganizationDataAccessor.GetDownStreamOrganizations(populationLimit.OrganizationId, true); var people = context.People.Where(p => downStreamOrganizations.Contains(p.OrganizationId)).ToList(); if (people.Count + 1 > populationLimit.NumberOfPeople) { exceedsLimit = true; requestResult.ReturnFailedMessage(string.Format(Resources.Resource.ExceedsPopulationLimit, organization.Name, populationLimit.NumberOfPeople)); } else { if (model.FormInput.IsMobilePerson && people.Count(x => x.IsMobilePerson) + 1 > populationLimit.NumberOfMobilePeople) { exceedsLimit = true; requestResult.ReturnFailedMessage(string.Format(Resources.Resource.ExceedsMobilePopulationLimit, organization.Name, populationLimit.NumberOfMobilePeople)); } } } if (!exceedsLimit) { var roles = context.Roles.Where(r => model.FormInput.RoleIdsString.Contains(r.RoleId)).ToList(); context.People.Add(new CF.Models.Person() { OrganizationId = new Guid(model.OrganizationId), LoginId = model.FormInput.Id, Name = model.FormInput.Name, Password = model.FormInput.Id, Title = model.FormInput.Title, Email = model.FormInput.EMail, IsMobilePerson = model.FormInput.IsMobilePerson, LastModifyTime = DateTime.Now, Roles = roles }); context.SaveChanges(); requestResult.ReturnData(model.FormInput.Id, string.Format("{0} {1} {2}", Resources.Resource.Create, Resources.Resource.Person, Resources.Resource.Success)); } } else { requestResult.ReturnFailedMessage(string.Format("{0} {1}", Resources.Resource.PId, Resources.Resource.Exists)); } } } catch (Exception e) { var error = new Error(MethodBase.GetCurrentMethod(), e); Logger.Log(error); requestResult.ReturnError(error); //throw; } return(requestResult); }
public static RequestResult Move(string organizationId, List <string> selectedList) { RequestResult requestResult = new RequestResult(); try { #if !DEBUG using (TransactionScope trans = new TransactionScope()) { #endif using (CFContext context = new CFContext()) { foreach (var pId in selectedList) { context.People.First(x => x.LoginId == pId).OrganizationId = new Guid(organizationId); } context.SaveChanges(); } #if EquipmentPatrol || EquipmentMaintenance using (CFContext context = new CFContext()) { //foreach (var userID in selectedList) //{ // db.JobUser.RemoveRange(db.JobUser.Where(x => x.UserID == userID).ToList()); //} //db.SaveChanges(); } #endif #if EquipmentMaintenance using (CFContext context = new CFContext()) { //foreach (var userID in SelectedList) //{ // db.MJobUser.RemoveRange(db.MJobUser.Where(x => x.UserID == userID).ToList()); //} //db.SaveChanges(); } #endif #if !DEBUG trans.Complete(); } #endif requestResult.ReturnSuccessMessage(string.Format("{0} {1} {2}", Resources.Resource.Move, Resources.Resource.Person, Resources.Resource.Success)); } catch (Exception e) { var error = new Error(MethodBase.GetCurrentMethod(), e); Logger.Log(error); requestResult.ReturnError(error); //throw; } return(requestResult); }
public static RequestResult GetTreeItems(List <Models.Shared.Organization> organizationList, Guid organizationId, string materialType, Account account) { RequestResult requestResult = new RequestResult(); try { var treeItems = new List <TreeItem>(); var attributes = new Dictionary <Define.EnumTreeAttribute, string>() { { Define.EnumTreeAttribute.NodeType, string.Empty }, { Define.EnumTreeAttribute.ToolTip, string.Empty }, { Define.EnumTreeAttribute.OrganizationId, string.Empty }, { Define.EnumTreeAttribute.MaterialType, string.Empty }, { Define.EnumTreeAttribute.MaterialSpecificationId, string.Empty } }; using (CFContext context = new CFContext()) { if (string.IsNullOrEmpty(materialType)) { if (account.QueryableOrganizationIds.Contains(organizationId)) { var materialTypes = context.MSpecifications.Where(x => x.OrganizationId == organizationId).Select(x => x.MaterialType).Distinct().OrderBy(x => x).ToList(); foreach (var type in materialTypes) { var treeItem = new TreeItem() { Title = type }; attributes[Define.EnumTreeAttribute.NodeType] = Define.EnumTreeNodeType.MaterialType.ToString(); attributes[Define.EnumTreeAttribute.ToolTip] = type; attributes[Define.EnumTreeAttribute.OrganizationId] = organizationId.ToString(); attributes[Define.EnumTreeAttribute.MaterialType] = type; attributes[Define.EnumTreeAttribute.MaterialSpecificationId] = string.Empty; foreach (var attribute in attributes) { treeItem.Attributes[attribute.Key.ToString()] = attribute.Value; } treeItem.State = "closed"; treeItems.Add(treeItem); } } var organizations = organizationList.Where(x => x.ParentId == organizationId && account.VisibleOrganizationIds.Contains(x.OrganizationId)).OrderBy(x => x.OId).ToList(); foreach (var organization in organizations) { var treeItem = new TreeItem() { Title = organization.Name }; attributes[Define.EnumTreeAttribute.NodeType] = Define.EnumTreeNodeType.Organization.ToString(); attributes[Define.EnumTreeAttribute.ToolTip] = string.Format("{0}/{1}", organization.OId, organization.Name); attributes[Define.EnumTreeAttribute.OrganizationId] = organization.OrganizationId.ToString(); attributes[Define.EnumTreeAttribute.MaterialType] = string.Empty; attributes[Define.EnumTreeAttribute.MaterialSpecificationId] = string.Empty; foreach (var attribute in attributes) { treeItem.Attributes[attribute.Key.ToString()] = attribute.Value; } var haveDownStreamOrganization = organizationList.Any(x => x.ParentId == organization.OrganizationId && account.VisibleOrganizationIds.Contains(x.OrganizationId)); var haveMaterialSpecification = account.QueryableOrganizationIds.Contains(organization.OrganizationId) && context.MSpecifications.Any(x => x.OrganizationId == organization.OrganizationId); if (haveDownStreamOrganization || haveMaterialSpecification) { treeItem.State = "closed"; } treeItems.Add(treeItem); } } else { var specifications = context.MSpecifications.Where(x => x.OrganizationId == organizationId && x.MaterialType == materialType).OrderBy(x => x.Name).ToList(); foreach (var specification in specifications) { var treeItem = new TreeItem() { Title = specification.Name }; attributes[Define.EnumTreeAttribute.NodeType] = Define.EnumTreeNodeType.MaterialSpecification.ToString(); attributes[Define.EnumTreeAttribute.ToolTip] = specification.Name; attributes[Define.EnumTreeAttribute.OrganizationId] = specification.OrganizationId.ToString(); attributes[Define.EnumTreeAttribute.MaterialType] = specification.MaterialType; attributes[Define.EnumTreeAttribute.MaterialSpecificationId] = specification.MSpecificationId.ToString(); foreach (var attribute in attributes) { treeItem.Attributes[attribute.Key.ToString()] = attribute.Value; } treeItems.Add(treeItem); } } } requestResult.ReturnData(treeItems); } catch (Exception e) { var error = new Error(MethodBase.GetCurrentMethod(), e); Logger.Log(error); requestResult.ReturnError(error); } return(requestResult); }
/// <summary> /// 审核状态 /// </summary> /// <param name="aid"></param> /// <param name="auditStatus"></param> /// <returns></returns> public InvokeResult <bool> AuditArticle(string aid, int auditStatus, string auditMessage) { var entity = GetForm(aid); entity.BookStatus = auditStatus; entity.AuditMessage = auditMessage; using (var trans = _Respository.BeginTransaction()) { try { var updateFileds = new List <string>() { "BookStatus", "AuditMessage" }; if (!entity.ResourceType.IsEmpty() && auditStatus == (int)BookStatus.审核通过) { if (entity.ResourceType == "pdf" || entity.ResourceType == "doc" || entity.ResourceType == "docx" || entity.ResourceType == "ppt" || entity.ResourceType == "pptx" || entity.ResourceType == "xls" || entity.ResourceType == "xlsx") { entity.HasImages = false; } else { entity.HasImages = true; } //updateFileds.Add("HasImages"); if (entity.CoverUrl.IsEmpty() && !entity.Attachment.IsEmpty()) { var attFile = entity.Attachment.Split(',')[0]; entity.CoverUrl = $"{attFile.Replace(FileHelper.GetExtension(FileHelper.MapFilePath(attFile)), "")}/{FileHelper.GetFileNameNoExtension(attFile)}1.jpg"; updateFileds.Add("CoverUrl"); } } var b = _Respository.UpdateFields(entity, updateFileds.ToArray()); if (!b) { trans.Rollback(); return(RequestResult.Failed <bool>("审核处理积分失败")); } if (auditStatus == (int)BookStatus.审核通过) { //关联专题 数量处理 if (!entity.SpecialTopicId.IsEmpty()) { var articleTopicRespository = CoreContextProvider.GetService <IArticleTopicRespository>(); var topic = articleTopicRespository.Get(entity.SpecialTopicId); if (topic != null) { topic.ResourceCount++; if (!articleTopicRespository.UpdateFields(topic, "ResourceCount")) { trans.Rollback(); _logger.LogError($"审核时更新{topic.Id}:topic.ResourceCount+1失败!"); return(RequestResult.Failed <bool>("审核处理失败,请重试")); } } } //积分 var memberScoreService = CoreContextProvider.GetService <IMemberScoreService>(); var scoreResult = memberScoreService.AddScore(entity.MemberId, ScoreType.addbook, aid); if (!scoreResult.Success) { trans.Rollback(); _logger.LogError(scoreResult.Message); return(RequestResult.Failed <bool>("审核处理积分失败")); } } trans.Commit(); //资源文件生成图片操作 if (!entity.ResourceType.IsEmpty() && auditStatus == (int)BookStatus.审核通过) { //if (entity.ResourceType == "pdf" || entity.ResourceType == "doc" || entity.ResourceType == "docx" // || entity.ResourceType == "ppt" || entity.ResourceType == "pptx" || entity.ResourceType == "xls" // || entity.ResourceType == "xlsx") CoreContextProvider.ConvertFileToImage(entity.Attachment.Split(',').ToList(), entity.PageCount, _logger); } return(RequestResult.Success(true)); } catch (Exception ex) { trans.Rollback(); _logger.LogError($"[method.AuditArticle({aid},{auditStatus})]:" + ex.Message); return(RequestResult.Failed <bool>("审核失败,数据异常")); } } }
protected virtual void RequestCompleted(RequestResult result) { if (this.OnRequestCompleted != null) { this.OnRequestCompleted(this, result); } }
public static RequestResult Query(QueryParameters queryParameters, Account account) { RequestResult requestResult = new RequestResult(); try { using (CFContext context = new CFContext()) { var downStreamOrganizations = OrganizationDataAccessor.GetDownStreamOrganizationIds(new Guid(queryParameters.OrganizationId), true); var query = (from p in context.People join o in context.Organizations on p.OrganizationId equals o.OrganizationId where downStreamOrganizations.Contains(p.OrganizationId) && account.QueryableOrganizationIds.Contains(p.OrganizationId) select new { Person = p, OrganizationName = o.Name }).AsQueryable(); if (!string.IsNullOrEmpty(queryParameters.Keyword)) { query = query.Where(x => x.Person.Title.Contains(queryParameters.Keyword) || x.Person.LoginId.Contains(queryParameters.Keyword) || x.Person.Name.Contains(queryParameters.Keyword)); } var organization = OrganizationDataAccessor.GetOrganization(new Guid(queryParameters.OrganizationId)); var items = query.ToList(); var model = new GridViewModel() { Permission = account.OrganizationPermission(new Guid(queryParameters.OrganizationId)), OrganizationId = queryParameters.OrganizationId, OrganizationName = organization.Name, FullOrganizationName = organization.FullName, Items = items.Select(x => new GridItem() { Permission = account.OrganizationPermission(x.Person.OrganizationId), OrganizationName = x.OrganizationName, Title = x.Person.Title, Id = x.Person.LoginId, Name = x.Person.Name, Email = x.Person.Email, IsMobilePerson = x.Person.IsMobilePerson, RoleNameList = x.Person.Roles.Select(r => r.Name).ToList() }).OrderBy(x => x.OrganizationName).ThenBy(x => x.Title).ThenBy(x => x.Id).ToList() }; var ancestorOrganizationId = OrganizationDataAccessor.GetAncestorOrganizationId(new Guid(queryParameters.OrganizationId)); var downStreams = OrganizationDataAccessor.GetDownStreamOrganizations(ancestorOrganizationId, true); foreach (var downStream in downStreams) { if (account.EditableOrganizationIds.Any(x => x == downStream)) { model.MoveToTargets.Add(new MoveToTarget() { Id = downStream, Name = OrganizationDataAccessor.GetOrganizationFullName(downStream), Direction = Define.EnumMoveDirection.Down }); } } model.MoveToTargets = model.MoveToTargets.OrderBy(x => x.Name).ToList(); requestResult.ReturnData(model); } } catch (Exception e) { var error = new Error(MethodBase.GetCurrentMethod(), e); Logger.Log(error); requestResult.ReturnError(error); //throw; } return(requestResult); }
private void GetRequestStreamCallback(IAsyncResult asynchronousResult) { try { string filePath = this.filePath; byte[] bytes = getFileBytes(filePath); HttpWebRequest httpWebRequest = this.HttpWebRequest; // End the operation Stream postStream = httpWebRequest.EndGetRequestStream(asynchronousResult); // Write to the request stream. postStream.Write(bytes, 0, bytes.Length); postStream.Close(); // Start the asynchronous operation to get the response httpWebRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), asynchronousResult.AsyncState); } catch (WebException e) { RequestCallbackDelegate<string> callback = (RequestCallbackDelegate<string>)asynchronousResult.AsyncState; RequestResult<string> requestResult = new RequestResult<string>(); requestResult.IsError = true; requestResult.Execption = e; requestResult.Message = e.Message; callback(requestResult); } }
public void GetBill_returns_correct_results() { // arrange var mockWebRequestHelper = new Mock<IWebRequestHelper>(MockBehavior.Strict); string content; // using the sample bill downloaded from: // http://safe-plains-5453.herokuapp.com/bill.json using (var streamReader = File.OpenText("bill.json")) { content = streamReader.ReadToEnd(); } var requestResult = new RequestResult { HttpStatusCode = HttpStatusCode.OK, Content = content }; mockWebRequestHelper .Setup(x => x.GetRequestResult(It.IsAny<string>(), It.IsAny<string>())) .Returns(requestResult); var billingApi = new BillingApi(mockWebRequestHelper.Object); var call1 = new Call { Called = "07716393769", Cost = 2.13m, Duration = new TimeSpan(0, 23, 3) }; var call2 = new Call { Called = "02074351359", Cost = 2.13m, Duration = new TimeSpan(0, 23, 3) }; var calls = Enumerable.Repeat(call1, 18).Concat(Enumerable.Repeat(call2, 10)).ToList(); var expectedBill = new Bill { Total = 136.03m, Statement = new Statement { Due = new DateTime(2015, 1, 25), Generated = new DateTime(2015, 1, 11), Period = new Period { From = new DateTime(2015, 1, 26), To = new DateTime(2015, 2, 25) } }, Package = new Package { Subscriptions = new List<Subscription> { new Subscription { Cost = 50.00m, Name = "Variety with Movies HD", Type = Subscription.SubscriptionType.Tv }, new Subscription { Cost = 5.00m, Name = "Sky Talk Anytime", Type = Subscription.SubscriptionType.Talk }, new Subscription { Cost = 16.40m, Name = "Fibre Unlimited", Type = Subscription.SubscriptionType.Broadband } }, Total = 71.40m }, CallCharges = new CallCharges { Calls = calls, Total = 59.64m }, SkyStore = new SkyStore { Rentals = new List<Programme> { new Programme { Title = "50 Shades of Grey", Cost = 4.99m } }, BuyAndKeep = new List<Programme> { new Programme { Title = "That's what she said", Cost = 9.99m }, new Programme { Title = "Broke back mountain", Cost = 9.99m } }, Total = 24.97m } }; // act var result = billingApi.GetBill(); // assert result.ShouldBeEquivalentTo(expectedBill); }
private void UploadFileRequestCallback(RequestResult<string> requestResult) { ServiceResult<MediaToken> serviceResult = new ServiceResult<MediaToken>() { IsError = requestResult.IsError, Execption = requestResult.Execption, Message = requestResult.Message }; serviceResult.Result = this.mediaToken; if (requestResult.IsError) { // Calling Service callback to let consumer know this.ServiceResult = serviceResult; this.serviceCallback(serviceResult); return; } UploadStatusRequest(this.mediaToken); }
/// <summary> /// 批量添加 /// </summary> /// <param name="articles"></param> /// <returns></returns> public InvokeResult <bool> AddBetchArticle(List <Article> articles) { _Respository.AddBetch(articles); return(RequestResult.Success(true)); }
public async void ShouldQueueNotificationUpdate() { UserProfile userProfile = new UserProfile { HdId = "1234567890123456789012345678901234567890123456789012", AcceptedTermsOfService = true, Email = string.Empty }; DBResult <UserProfile> insertResult = new DBResult <UserProfile> { Payload = userProfile, Status = DBStatusCode.Created }; UserProfileModel expected = UserProfileModel.CreateFromDbModel(userProfile); Mock <IEmailQueueService> emailer = new Mock <IEmailQueueService>(); Mock <IUserProfileDelegate> profileDelegateMock = new Mock <IUserProfileDelegate>(); profileDelegateMock.Setup(s => s.InsertUserProfile(userProfile)).Returns(insertResult); Mock <IUserPreferenceDelegate> preferenceDelegateMock = new Mock <IUserPreferenceDelegate>(); Mock <IEmailDelegate> emailDelegateMock = new Mock <IEmailDelegate>(); Mock <IMessagingVerificationDelegate> emailInviteDelegateMock = new Mock <IMessagingVerificationDelegate>(); emailInviteDelegateMock.Setup(s => s.GetByInviteKey(It.IsAny <Guid>())).Returns(new MessagingVerification()); Mock <IConfigurationService> configServiceMock = new Mock <IConfigurationService>(); configServiceMock.Setup(s => s.GetConfiguration()).Returns(new ExternalConfiguration() { WebClient = new WebClientConfiguration() { RegistrationStatus = RegistrationStatus.Open } }); Mock <ICryptoDelegate> cryptoDelegateMock = new Mock <ICryptoDelegate>(); cryptoDelegateMock.Setup(s => s.GenerateKey()).Returns("abc"); Mock <INotificationSettingsService> notificationServiceMock = new Mock <INotificationSettingsService>(); notificationServiceMock.Setup(s => s.QueueNotificationSettings(It.IsAny <NotificationSettingsRequest>())); Mock <IMessagingVerificationDelegate> messageVerificationDelegateMock = new Mock <IMessagingVerificationDelegate>(); IUserProfileService service = new UserProfileService( new Mock <ILogger <UserProfileService> >().Object, profileDelegateMock.Object, preferenceDelegateMock.Object, emailDelegateMock.Object, emailInviteDelegateMock.Object, configServiceMock.Object, emailer.Object, new Mock <ILegalAgreementDelegate>().Object, cryptoDelegateMock.Object, notificationServiceMock.Object, messageVerificationDelegateMock.Object, new Mock <IPatientService>().Object); RequestResult <UserProfileModel> actualResult = await service.CreateUserProfile(new CreateUserRequest() { Profile = userProfile }, new Uri("http://localhost/"), "bearer_token"); notificationServiceMock.Verify(s => s.QueueNotificationSettings(It.IsAny <NotificationSettingsRequest>()), Times.Once()); Assert.Equal(ResultType.Success, actualResult.ResultStatus); Assert.True(actualResult.ResourcePayload.IsDeepEqual(expected)); }
private static RequestResult _Request(HttpMethods method, string url, byte[] data, HttpRequestDataFormat dataFormat, Dictionary<string, string> headers, IEnumerable<Cookie> Cookies, ICredentials Credentials, Action<RequestResult> callback, ProgressReportDelegate progressReportCallback) { //enable protocols #if NETFX #if __MonoCS__ try{ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;}catch{} #warning WARNING the system is not secure when using only TLS1 !!!! you must use visual studio. #elif UNIVERSAL try{ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;} catch{} #endif #endif //add request cookies var cookieContainer = new CookieContainer(); if (Cookies != null) foreach (var entry in Cookies) #if NETFX cookieContainer.Add(entry); #elif UNIVERSAL cookieContainer.Add(new Uri(url), entry); #endif //creat request HttpWebRequest webRequest; try { webRequest = (HttpWebRequest)WebRequest.Create(url); } catch (Exception ex) { DebugEx.TraceError(ex, "Http request failed"); if (callback != null) callback(default(RequestResult)); return default(RequestResult); } //setup request webRequest.CookieContainer = cookieContainer; if (Credentials == null) webRequest.UseDefaultCredentials = true; else webRequest.Credentials = Credentials; #if NETFX webRequest.PreAuthenticate = true; webRequest.ServicePoint.Expect100Continue = false; //collect certificates /* if (!EnvironmentEx.IsRunningOnMono) webRequest.ClientCertificates = Tools.Certificates.CollectCertificates(); */ webRequest.AllowAutoRedirect = true; webRequest.MaximumAutomaticRedirections = 10; webRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.None; webRequest.UserAgent = UserAgent; #elif UNIVERSAL webRequest.Headers[HttpRequestHeader.UserAgent] = UserAgent; #endif webRequest.Accept = "*/*"; try { #if NETFX //build headers if (headers != null) foreach (var header in headers) webRequest.Headers.Add(header.Key, header.Value); #endif //setup method switch (method) { case HttpMethods.Get: webRequest.Method = "GET"; break; case HttpMethods.Post: webRequest.Method = "POST"; break; case HttpMethods.Put: webRequest.Method = "PUT"; break; default: DebugEx.Assert("Invalid Method"); throw new NotImplementedException("Invalid Method"); } //build request if (method == HttpMethods.Get) { #if NETFX webRequest.ContentLength = 0; webRequest.ContentType = webRequest.MediaType = "application/x-www-form-urlencoded"; #endif } else { string contentType = null; switch (dataFormat) { case HttpRequestDataFormat.Json: contentType = "application/json"; break; case HttpRequestDataFormat.Xml: contentType = "application/xhtml+xml"; break; case HttpRequestDataFormat.FormData: contentType = "application/x-www-form-urlencoded"; break; case HttpRequestDataFormat.Text: contentType = "mime/text"; break; case HttpRequestDataFormat.Soap: if (headers.ContainsKey("SoapContent-Type")) { contentType = headers["SoapContent-Type"]; webRequest.Headers.Remove("SoapContent-Type"); } break; case HttpRequestDataFormat.Binary: contentType = "application/octet-stream"; break; } webRequest.ContentType = contentType; #if NETFX webRequest.MediaType = contentType; #endif //write body data var body_data = data ?? new byte[0]; #if NETFX webRequest.ContentLength = body_data.Length; using (var stream = webRequest.GetRequestStream()) stream.Write(body_data, 0, body_data.Length); #elif UNIVERSAL using (var stream = webRequest.GetRequestStreamAsync().GetResults()) stream.Write(body_data, 0, body_data.Length); #endif } //get response HttpWebResponse response = null; Stream respstream = null; try { #if NETFX var _response = webRequest.GetResponse(); #elif UNIVERSAL var _response = webRequest.GetResponseAsync().GetResults(); #endif response = (HttpWebResponse)_response; respstream = response.GetResponseStream(); } catch (WebException ex) { response = ex.Response as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.RedirectMethod) DebugEx.TraceLog("Redirected from url " + url + " to url " + response.ResponseUri); else if (response != null && response.StatusCode == HttpStatusCode.NotFound) DebugEx.TraceLog("404 - Not Found. Url=" + url); else DebugEx.TraceError(ex, "Unhandled exception during webRequest.GetResponse() for url " + url); //try get response stream try { if (response != null) respstream = response.GetResponseStream(); } catch (WebException ex2) { DebugEx.TraceError(ex2, "Unhandled exception during redirect webRequest.GetResponseStream() for url " + url); } } //Read results and execute callback if (response != null) { //find encoding var encoding = response.Headers["content-encoding"]; var contentType = response.Headers["content-type"]; var contentTypeEntries = contentType?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (contentTypeEntries != null) for (int n = 0; n > contentTypeEntries.Length; n++) contentTypeEntries[n] = contentTypeEntries[n].Trim(); //find charset string charset = ""; if (contentTypeEntries != null && contentType != null && contentType.Contains("charset=")) try { var entry = contentTypeEntries.FirstOrDefault(e => e.ToLowerInvariant().StartsWith("charset=")); if (!string.IsNullOrWhiteSpace(entry)) charset = entry.Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries)[1].ToLowerInvariant(); } catch { charset = "utf-8"; } //consume stream byte[] bytes = null; if (respstream != null) try { using (var memStream = new MemoryStream()) { if (progressReportCallback == null) { //unzip or just copy to memstream if (encoding != null && encoding.ToLowerInvariant() == "gzip") using (var defStream = new GZipStream(respstream, CompressionMode.Decompress)) defStream.CopyTo(memStream); else respstream.CopyTo(memStream); } else { //unzip or just copy to memstream if (encoding != null && encoding.ToLowerInvariant() == "gzip") using (var defStream = new GZipStream(respstream, CompressionMode.Decompress)) StreamCopy(defStream, memStream, progressReportCallback, response.ContentLength); else StreamCopy(respstream, memStream, progressReportCallback, response.ContentLength); } //get bytes bytes = memStream.ToArray(); } } catch (Exception ex) { DebugEx.Assert(ex, "Unhandled exception while reading response stream"); } //build result var result = new RequestResult() { IsValid = true, ResponseUri = response.ResponseUri, ResponseBodyBinary = bytes, ContentTypeEntries = contentTypeEntries, Charset = charset, Cookies = cookieContainer.GetCookies(new Uri(url)).Cast<Cookie>().ToList(), StatusCode = response.StatusCode, IsSuccessStatusCode = ((int)response.StatusCode >= 200 && (int)response.StatusCode <= 299), }; if (callback != null) callback(result); //close and dispose response #if NETFX response.Close(); #endif response.Dispose(); //give result back return result; } else return default(RequestResult); } catch (Exception ex) { DebugEx.TraceError(ex, "Http request failed"); return default(RequestResult); } }
/// <summary> /// Translates the data service client exception. /// </summary> /// <param name="e">The exception.</param> /// <param name="reqResult">The request result.</param> /// <returns> /// The translated exception. /// </returns> internal static StorageException TranslateDataServiceClientException(Exception e, RequestResult reqResult) { DataServiceClientException dsce = FindInnerExceptionOfType <DataServiceClientException>(e); if (dsce == null) { InvalidOperationException ioe = TableUtilities.FindInnerExceptionOfType <InvalidOperationException>(e); if (ioe != null && !(ioe is WebException) && ioe.Source == "System.Data.Services.Client" && ioe.Message.Contains("type is not compatible with the expected")) { return(new StorageException(reqResult, e.Message, e) { IsRetryable = false }); } return(null); } else { reqResult.HttpStatusCode = dsce.StatusCode; using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(dsce.Message))) { reqResult.ExtendedErrorInformation = StorageExtendedErrorInformation.ReadFromStream(stream); } return(new StorageException( reqResult, reqResult.ExtendedErrorInformation != null ? reqResult.ExtendedErrorInformation.ErrorCode : dsce.Message, dsce)); } }
private void GetResponseCallback(IAsyncResult asynchronousResult) { RequestCallbackDelegate<string> callback = (RequestCallbackDelegate<string>)asynchronousResult.AsyncState; RequestResult<string> requestResult = new RequestResult<string>(); // End the operation HttpWebResponse response = null; try { response = (HttpWebResponse)this.httpWebRequest.EndGetResponse(asynchronousResult); } catch (WebException e) { WebResponse r = e.Response; if (r != null) { Stream s = r.GetResponseStream(); requestResult.Message = new StreamReader(s).ReadToEnd(); } else { requestResult.Message = e.Message; } requestResult.IsError = true; requestResult.Execption = e; //Error occurred, calling callback callback(requestResult); return; } Stream streamResponse = response.GetResponseStream(); StreamReader streamRead = new StreamReader(streamResponse); string responseString = streamRead.ReadToEnd(); // Close the stream object streamResponse.Close(); streamRead.Close(); // Release the HttpWebResponse response.Close(); //Calling callback requestResult.Response = responseString; requestResult.IsError = false; callback(requestResult); }
public static RequestResult Create(CreateFormModel createFormModel) { RequestResult result = new RequestResult(); try { using (CFContext context = new CFContext()) { var exists = context.Checkpoints.FirstOrDefault(x => x.OrganizationId == new Guid(createFormModel.OrganizationId) && x.CId == createFormModel.FormInput.CId); if (exists == null) { if (!string.IsNullOrEmpty(createFormModel.FormInput.TagId) && context.Checkpoints.Any(x => x.TagId == createFormModel.FormInput.TagId)) { var checkpoint = context.Checkpoints.First(x => x.TagId == createFormModel.FormInput.TagId); var organization = OrganizationDataAccessor.GetOrganization(checkpoint.OrganizationId); result.ReturnFailedMessage(string.Format("{0} {1} {2} {3} {4}", Resources.Resource.TagId, createFormModel.FormInput.TagId, Resources.Resource.Exists, organization.Name, checkpoint.Name)); } else { Guid checkpointId = Guid.NewGuid(); context.Checkpoints.Add(new CF.Models.Maintenance.Checkpoint() { CheckpointId = checkpointId, OrganizationId = new Guid(createFormModel.OrganizationId), CId = createFormModel.FormInput.CId, Name = createFormModel.FormInput.Name, IsFeelItemDefaultNormal = createFormModel.FormInput.IsFeelItemDefaultNormal, TagId = createFormModel.FormInput.TagId, Remark = createFormModel.FormInput.Remark, CheckItems = createFormModel.CheckItemModels.Select(x => new CF.Models.Maintenance.CheckItem() { CheckItemId = new Guid(x.CheckItemId), IsInherit = x.IsInherit, LowerLimit = x.LowerLimit, LowerAlertLimit = x.LowerAlertLimit, UpperAlertLimit = x.UpperAlertLimit, UpperLimit = x.UpperLimit, AccumulationBase = x.AccumulationBase, Unit = x.Unit, Remark = x.Remark }).ToList(), LastModifyTime = DateTime.Now }); context.SaveChanges(); result.ReturnData(checkpointId, string.Format("{0} {1} {2}", Resources.Resource.Create, Resources.Resource.Checkpoint, Resources.Resource.Success)); } } else { result.ReturnFailedMessage(string.Format("{0} {1}", Resources.Resource.CId, Resources.Resource.Exists)); } } } catch (Exception ex) { var err = new Error(MethodBase.GetCurrentMethod(), ex); Logger.Log(err); result.ReturnError(err); } return result; }
private void UploadFileStatusRequestCallback(RequestResult<string> requestResult) { // Using trick to get standard status, replacing token with "token_status" string JObject o = JObject.Parse(requestResult.Response); string status = o["data"][this.mediaToken.token][0].ToString(); MediaTokenStatus mediaTokenStatus = JsonConvert.DeserializeObject<MediaTokenStatus>(status); this.mediaToken.MediaTokenStatus = mediaTokenStatus; ServiceResult<MediaToken> serviceResult = new ServiceResult<MediaToken>() { IsError = requestResult.IsError, Execption = requestResult.Execption, Message = requestResult.Message }; serviceResult.Result = this.mediaToken; if(mediaTokenStatus.error.errornumber != null) { // Calling consumer this.ServiceResult = serviceResult; this.serviceCallback(serviceResult); return; } if (mediaTokenStatus.currentstate == "done") { // Calling consumer this.ServiceResult = serviceResult; DetectFace(); return; } // Wait for 1 sec System.Threading.Thread.Sleep(100); UploadStatusRequest(this.mediaToken); }
private void ProcessError(RequestResult requestResult, string errorMessage, string methodName) { /* var ex = CreateException(requestResult); log.Error(ex); return ex; LogError(requestResult, errorMessage, methodName, null); ThrowException(requestResult);*/ }
public ContentSaveResultPacket(RequestResult requestResult) { RequestResult = requestResult; }
protected virtual Task <bool> ShouldInactiveOnDelete(long id, RequestResult result) { return(Task.FromResult(false)); }
internal static StorageException GenerateCancellationException(RequestResult res, Exception inner) { if (res != null) { res.HttpStatusCode = 306; res.HttpStatusMessage = "Unused"; } OperationCanceledException cancelEx = new OperationCanceledException(SR.OperationCanceled, inner); return new StorageException(res, cancelEx.Message, inner) { IsRetryable = false }; }
public static RequestResult Edit(EditFormModel editFormModel) { RequestResult requestResult = new RequestResult(); try { using (CFContext context = new CFContext()) { var person = context.People.Include("Roles").First(x => x.LoginId == editFormModel.PId); bool exceedsLimit = false; if (editFormModel.FormInput.IsMobilePerson) { var upStreamOrganizationIds = OrganizationDataAccessor.GetUpStreamOrganizationIds(person.OrganizationId, true); PopulationLimit populationLimit = null; foreach (var item in Config.PopulationLimits) { if (upStreamOrganizationIds.Contains(item.OrganizationId)) { populationLimit = item; break; } } if (populationLimit != null) { var organization = OrganizationDataAccessor.GetOrganization(populationLimit.OrganizationId); var downStreamOrganizations = OrganizationDataAccessor.GetDownStreamOrganizations(populationLimit.OrganizationId, true); var mobilePeople = context.People.Where(x => x.LoginId != person.LoginId && x.IsMobilePerson && downStreamOrganizations.Contains(x.OrganizationId)).ToList(); if (mobilePeople.Count + 1 > populationLimit.NumberOfMobilePeople) { exceedsLimit = true; requestResult.ReturnFailedMessage(string.Format(Resources.Resource.ExceedsMobilePopulationLimit, organization.Name, populationLimit.NumberOfMobilePeople)); } } } if (!exceedsLimit) { #if !DEBUG using (TransactionScope trans = new TransactionScope()) { #endif #region Person person.Name = editFormModel.FormInput.Name; person.Title = editFormModel.FormInput.Title; person.Email = editFormModel.FormInput.EMail; //person.UID = editFormModel.FormInput.UID; person.IsMobilePerson = editFormModel.FormInput.IsMobilePerson; person.LastModifyTime = DateTime.Now; context.SaveChanges(); #endregion #region PersonRoles #region Delete if (person != null) { person.Roles = new List <CF.Models.Role>(); context.SaveChanges(); } #endregion #region Insert foreach (var roleId in editFormModel.FormInput.RoleIds) { var role = context.Roles.First(r => r.RoleId == roleId); person.Roles.Add(role); } context.SaveChanges(); #endregion #endregion #if !DEBUG trans.Complete(); } #endif requestResult.ReturnSuccessMessage(string.Format("{0} {1} {2}", Resources.Resource.Edit, Resources.Resource.Person, Resources.Resource.Success)); } } } catch (Exception e) { var error = new Error(MethodBase.GetCurrentMethod(), e); Logger.Log(error); requestResult.ReturnError(error); //throw; } return(requestResult); }
public static string GetResponseResultMessage(RequestResult result) { return result == RequestResult.RateLimited ? "You are now rate limited." : "Unknown error"; }
public RequestResultAssertions(RequestResult <T> instance) { Subject = instance; }
public static RequestResult AddCheckItem(List<CheckItemModel> checkItemModels, List<string> selectedList, string refOrganizationId) { RequestResult result = new RequestResult(); try { using (CFContext context = new CFContext()) { foreach (string selected in selectedList) { string[] temp = selected.Split(Define.Seperators, StringSplitOptions.None); var organizationId = temp[0]; var checkType = temp[1]; var checkItemId = temp[2]; if (!string.IsNullOrEmpty(checkItemId)) { if (!checkItemModels.Any(x => x.CheckItemId == checkItemId)) { var checkItem = context.CheckItems.First(x => x.CheckItemId == new Guid(checkItemId)); checkItemModels.Add(new CheckItemModel() { CheckItemId = checkItem.CheckItemId.ToString(), Type = checkItem.Type, CIId = checkItem.CIId, Name = checkItem.Name, IsFeelItem = checkItem.IsFeelItem, IsAccumulation = checkItem.IsAccumulation, IsInherit = true, OriLowerLimit = checkItem.LowerLimit, OriLowerAlertLimit = checkItem.LowerAlertLimit, OriUpperAlertLimit = checkItem.UpperAlertLimit, OriUpperLimit = checkItem.UpperLimit, OriAccumulationBase = checkItem.AccumulationBase, OriUnit = checkItem.Unit, OriRemark = checkItem.Remark }); } } else { if (!string.IsNullOrEmpty(checkType)) { var checkItems = context.CheckItems.Where(x => x.OrganizationId == new Guid(organizationId) && x.Type == checkType).ToList(); foreach (var checkItem in checkItems) { if (!checkItemModels.Any(x => x.CheckItemId == checkItem.CheckItemId.ToString())) { checkItemModels.Add(new CheckItemModel() { CheckItemId = checkItem.CheckItemId.ToString(), Type = checkItem.Type, CIId = checkItem.CIId, Name = checkItem.Name, IsFeelItem = checkItem.IsFeelItem, IsAccumulation = checkItem.IsAccumulation, IsInherit = true, OriLowerLimit = checkItem.LowerLimit, OriLowerAlertLimit = checkItem.LowerAlertLimit, OriUpperAlertLimit = checkItem.UpperAlertLimit, OriUpperLimit = checkItem.UpperLimit, OriAccumulationBase = checkItem.AccumulationBase, OriUnit = checkItem.Unit, OriRemark = checkItem.Remark }); } } } else { var availableOrganizationIds = OrganizationDataAccessor.GetUpStreamOrganizationIds(new Guid(refOrganizationId), true); var downStreamOrganizationIds = OrganizationDataAccessor.GetDownStreamOrganizationIds(new Guid(organizationId), true); foreach (var downStreamOrganizationId in downStreamOrganizationIds) { if (availableOrganizationIds.Any(x => x == downStreamOrganizationId)) { var checkItems = context.CheckItems.Where(x => x.OrganizationId == downStreamOrganizationId).ToList(); foreach (var checkItem in checkItems) { if (!checkItemModels.Any(x => x.CheckItemId == checkItem.CheckItemId.ToString())) { checkItemModels.Add(new CheckItemModel() { CheckItemId = checkItem.CheckItemId.ToString(), Type = checkItem.Type, CIId = checkItem.CIId, Name = checkItem.Name, IsFeelItem = checkItem.IsFeelItem, IsAccumulation = checkItem.IsAccumulation, IsInherit = true, OriLowerLimit = checkItem.LowerLimit, OriLowerAlertLimit = checkItem.LowerAlertLimit, OriUpperAlertLimit = checkItem.UpperAlertLimit, OriUpperLimit = checkItem.UpperLimit, OriAccumulationBase = checkItem.AccumulationBase, OriUnit = checkItem.Unit, OriRemark = checkItem.Remark }); } } } } } } } } checkItemModels = checkItemModels.OrderBy(x => x.Type).ThenBy(x => x.CIId).ToList(); result.ReturnData(checkItemModels); } catch (Exception ex) { var err = new Error(MethodBase.GetCurrentMethod(), ex); Logger.Log(err); result.ReturnError(err); } return result; }
/// <summary> /// Initializes a new instance of the <see cref="EnergyConsumptionResponse"/> class. /// </summary> public EnergyConsumptionResponse() { Result = new RequestResult(); }
private Exception CreateException(RequestResult requestResult, string errorMessage) { switch (requestResult) { case RequestResult.ConnectionFailure: return new ConnectionFailureException(errorMessage); case RequestResult.FileNotFound: return new ResourceNotFoundException(errorMessage); case RequestResult.RateLimited: return new RateLimitException(errorMessage); case RequestResult.Unauthorized: return new UnauthorizedException(errorMessage); default: return new TwitterException(errorMessage); } }
public static RequestResult Edit(EditFormModel editFormModel) { RequestResult result = new RequestResult(); try { using (CFContext context = new CFContext()) { var checkpoint = context.Checkpoints.Include("CheckItems").First(x => x.CheckpointId == new Guid(editFormModel.CheckpointId)); var exists = context.Checkpoints.FirstOrDefault(x => x.CheckpointId != checkpoint.CheckpointId && x.OrganizationId == checkpoint.OrganizationId && x.CId == editFormModel.FormInput.CId); if (exists == null) { if (!string.IsNullOrEmpty(editFormModel.FormInput.TagId) && context.Checkpoints.Any(x => x.CheckpointId != checkpoint.CheckpointId && x.TagId == editFormModel.FormInput.TagId)) { var query = context.Checkpoints.First(x => x.CheckpointId != checkpoint.CheckpointId && x.TagId == editFormModel.FormInput.TagId); var organization = OrganizationDataAccessor.GetOrganization(query.OrganizationId); result.ReturnFailedMessage(string.Format("{0} {1} {2} {3} {4}", Resources.Resource.TagId, editFormModel.FormInput.TagId, Resources.Resource.Exists, organization.Name, checkpoint.Name)); } else { #if !DEBUG using (TransactionScope trans = new TransactionScope()) { #endif #region ControlPoint checkpoint.CId = editFormModel.FormInput.CId; checkpoint.Name = editFormModel.FormInput.Name; checkpoint.TagId = editFormModel.FormInput.TagId; checkpoint.Remark = editFormModel.FormInput.Remark; checkpoint.IsFeelItemDefaultNormal = editFormModel.FormInput.IsFeelItemDefaultNormal; checkpoint.LastModifyTime = DateTime.Now; context.SaveChanges(); #endregion #region CheckItems #region Delete checkpoint.CheckItems = new HashSet<CheckItem>(); context.SaveChanges(); #endregion #region Insert checkpoint.CheckItems = editFormModel.CheckItemModels.Select(x => new CheckItem() { CheckItemId = new Guid(x.CheckItemId), CIId = x.CIId, Name = x.Name, Type = x.Type, IsInherit = x.IsInherit, IsFeelItem = x.IsFeelItem, IsAccumulation = x.IsAccumulation, LowerLimit = x.LowerLimit, LowerAlertLimit = x.LowerAlertLimit, UpperLimit = x.UpperLimit, UpperAlertLimit = x.UpperAlertLimit, Unit = x.Unit, Remark = x.Remark, AccumulationBase = x.AccumulationBase, LastModifyTime = DateTime.Now }).ToList(); context.SaveChanges(); #endregion #endregion #if !DEBUG trans.Complete(); } #endif result.ReturnSuccessMessage(string.Format("{0} {1} {2}", Resources.Resource.Edit, Resources.Resource.Checkpoint, Resources.Resource.Success)); } } else { result.ReturnFailedMessage(string.Format("{0} {1}", Resources.Resource.Checkpoint, Resources.Resource.Exists)); } } } catch (Exception ex) { var err = new Error(MethodBase.GetCurrentMethod(), ex); Logger.Log(err); result.ReturnError(err); } return result; }
/// <summary> /// Implements getting the stream without specifying a range. /// </summary> /// <param name="destStream">The destination stream.</param> /// <param name="offset">The offset.</param> /// <param name="length">The length.</param> /// <param name="accessCondition">An object that represents the access conditions for the file. If null, no condition is used.</param> /// <param name="options">A <see cref="FileRequestOptions"/> object that specifies additional options for the request.</param> /// <returns> /// A <see cref="RESTCommand{T}" /> that gets the stream. /// </returns> private RESTCommand<NullType> GetFileImpl(Stream destStream, long? offset, long? length, AccessCondition accessCondition, FileRequestOptions options) { string lockedETag = null; AccessCondition lockedAccessCondition = null; bool isRangeGet = offset.HasValue; bool arePropertiesPopulated = false; string storedMD5 = null; long startingOffset = offset.HasValue ? offset.Value : 0; long? startingLength = length; long? validateLength = null; RESTCommand<NullType> getCmd = new RESTCommand<NullType>(this.ServiceClient.Credentials, this.StorageUri); options.ApplyToStorageCommand(getCmd); getCmd.CommandLocationMode = CommandLocationMode.PrimaryOrSecondary; getCmd.RetrieveResponseStream = true; getCmd.DestinationStream = destStream; getCmd.CalculateMd5ForResponseStream = !options.DisableContentMD5Validation.Value; getCmd.BuildRequestDelegate = (uri, builder, serverTimeout, useVersionHeader, ctx) => FileHttpWebRequestFactory.Get(uri, serverTimeout, offset, length, options.UseTransactionalMD5.Value, accessCondition, useVersionHeader, ctx); getCmd.SignRequest = this.ServiceClient.AuthenticationHandler.SignRequest; getCmd.RecoveryAction = (cmd, ex, ctx) => { if ((lockedAccessCondition == null) && !string.IsNullOrEmpty(lockedETag)) { lockedAccessCondition = AccessCondition.GenerateIfMatchCondition(lockedETag); if (accessCondition != null) { lockedAccessCondition.LeaseId = accessCondition.LeaseId; } } if (cmd.StreamCopyState != null) { offset = startingOffset + cmd.StreamCopyState.Length; if (startingLength.HasValue) { length = startingLength.Value - cmd.StreamCopyState.Length; } } getCmd.BuildRequestDelegate = (uri, builder, serverTimeout, useVersionHeader, context) => FileHttpWebRequestFactory.Get(uri, serverTimeout, offset, length, options.UseTransactionalMD5.Value && !arePropertiesPopulated, accessCondition, useVersionHeader, context); }; getCmd.PreProcessResponse = (cmd, resp, ex, ctx) => { HttpResponseParsers.ProcessExpectedStatusCodeNoException(offset.HasValue ? HttpStatusCode.PartialContent : HttpStatusCode.OK, resp, NullType.Value, cmd, ex); if (!arePropertiesPopulated) { this.UpdateAfterFetchAttributes(resp, isRangeGet); storedMD5 = resp.Headers[HttpResponseHeader.ContentMd5]; if (!options.DisableContentMD5Validation.Value && options.UseTransactionalMD5.Value && string.IsNullOrEmpty(storedMD5)) { throw new StorageException( cmd.CurrentResult, SR.MD5NotPresentError, null) { IsRetryable = false }; } // If the download fails and Get File needs to resume the download, going to the // same storage location is important to prevent a possible ETag mismatch. getCmd.CommandLocationMode = cmd.CurrentResult.TargetLocation == StorageLocation.Primary ? CommandLocationMode.PrimaryOnly : CommandLocationMode.SecondaryOnly; lockedETag = attributes.Properties.ETag; if (resp.ContentLength >= 0) { validateLength = resp.ContentLength; } arePropertiesPopulated = true; } else { if (!HttpResponseParsers.GetETag(resp).Equals(lockedETag, StringComparison.Ordinal)) { RequestResult reqResult = new RequestResult(); reqResult.HttpStatusMessage = null; reqResult.HttpStatusCode = (int)HttpStatusCode.PreconditionFailed; reqResult.ExtendedErrorInformation = null; throw new StorageException(reqResult, SR.PreconditionFailed, null /* inner */); } } return NullType.Value; }; getCmd.PostProcessResponse = (cmd, resp, ctx) => { HttpResponseParsers.ValidateResponseStreamMd5AndLength(validateLength, storedMD5, cmd); return NullType.Value; }; return getCmd; }
public static RequestResult GetEditFormModel(string checkpointId) { RequestResult result = new RequestResult(); try { using (CFContext context = new CFContext()) { var checkpoint = context.Checkpoints.Include("CheckItems").First(x => x.CheckpointId == new Guid(checkpointId)); result.ReturnData(new EditFormModel() { CheckpointId = checkpoint.CheckpointId.ToString(), OrganizationId = checkpoint.OrganizationId.ToString(), ParentOrganizationFullName = OrganizationDataAccessor.GetOrganizationFullName(checkpoint.OrganizationId), CheckItemModels = checkpoint.CheckItems.Select(x=>new CheckItemModel() { CheckItemId = x.CheckItemId.ToString(), CIId = x.CIId, Name = x.Name, Type = x.Type, IsFeelItem = x.IsFeelItem, IsAccumulation = x.IsAccumulation, IsInherit = x.IsInherit, OriLowerLimit = x.LowerLimit, OriLowerAlertLimit = x.LowerAlertLimit, OriUpperAlertLimit = x.UpperAlertLimit, OriUpperLimit = x.UpperLimit, OriAccumulationBase = x.AccumulationBase, OriUnit = x.Unit, OriRemark = x.Remark, LowerLimit = x.LowerLimit, LowerAlertLimit = x.LowerAlertLimit, UpperAlertLimit = x.UpperAlertLimit, UpperLimit = x.UpperLimit, AccumulationBase = x.AccumulationBase, Unit = x.Unit, Remark = x.Remark }).OrderBy(x => x.Type).ThenBy(x => x.CIId).ToList(), FormInput = new FormInput() { CId = checkpoint.CId, Name = checkpoint.Name, IsFeelItemDefaultNormal = checkpoint.IsFeelItemDefaultNormal, TagId = checkpoint.TagId, Remark = checkpoint.Remark } }); } } catch (Exception ex) { var err = new Error(MethodBase.GetCurrentMethod(), ex); Logger.Log(err); result.ReturnError(err); } return result; }
private DataServiceResponse ParseDataServiceResponse(DataServiceResponse resp, RequestResult reqResult, TableCommand<DataServiceResponse, DataServiceResponse> cmd) { if (reqResult.Exception != null) { throw reqResult.Exception; } return resp; }
public static RequestResult GetTreeItems(List<Models.Shared.Organization> organizations, Guid organizationId, Account account) { RequestResult result = new RequestResult(); try { var treeItemList = new List<TreeItem>(); var attributes = new Dictionary<Define.EnumTreeAttribute, string>() { { Define.EnumTreeAttribute.NodeType, string.Empty }, { Define.EnumTreeAttribute.ToolTip, string.Empty }, { Define.EnumTreeAttribute.OrganizationId, string.Empty }, { Define.EnumTreeAttribute.CheckpointId, string.Empty } }; using (CFContext context = new CFContext()) { if (account.QueryableOrganizationIds.Contains(organizationId)) { var checkpoints = context.Checkpoints.Where(x => x.OrganizationId == organizationId).OrderBy(x => x.CId).ToList(); foreach (var checkpoint in checkpoints) { var treeItem = new TreeItem() { Title = checkpoint.Name }; attributes[Define.EnumTreeAttribute.NodeType] = Define.EnumTreeNodeType.Checkpoint.ToString(); attributes[Define.EnumTreeAttribute.ToolTip] = string.Format("{0}/{1}", checkpoint.CId, checkpoint.Name); attributes[Define.EnumTreeAttribute.OrganizationId] = organizationId.ToString(); attributes[Define.EnumTreeAttribute.CheckpointId] = checkpoint.CheckpointId.ToString(); foreach (var attribute in attributes) { treeItem.Attributes[attribute.Key.ToString()] = attribute.Value; } treeItemList.Add(treeItem); } } var newOrganizations = organizations.Where(x => x.ParentId == organizationId && account.VisibleOrganizationIds.Contains(x.OrganizationId)).OrderBy(x => x.OId).ToList(); foreach (var organization in newOrganizations) { var treeItem = new TreeItem() { Title = organization.Name }; attributes[Define.EnumTreeAttribute.NodeType] = Define.EnumTreeNodeType.Organization.ToString(); attributes[Define.EnumTreeAttribute.ToolTip] = string.Format("{0}/{1}", organization.OId, organization.Name); attributes[Define.EnumTreeAttribute.OrganizationId] = organization.OrganizationId.ToString(); attributes[Define.EnumTreeAttribute.CheckpointId] = string.Empty; foreach (var attribute in attributes) { treeItem.Attributes[attribute.Key.ToString()] = attribute.Value; } if (organizations.Any(x => x.ParentId == organization.OrganizationId && account.VisibleOrganizationIds.Contains(x.OrganizationId)) || (account.QueryableOrganizationIds.Contains(organization.OrganizationId) && context.Checkpoints.Any(x => x.OrganizationId == organization.OrganizationId))) { treeItem.State = "closed"; } treeItemList.Add(treeItem); } } result.ReturnData(treeItemList); } catch (Exception ex) { var err = new Error(MethodBase.GetCurrentMethod(), ex); Logger.Log(err); result.ReturnError(err); } return result; }
/// <summary> /// Dispatches a sync read operation that either reads from the cache or makes a call to /// the server. /// </summary> /// <param name="buffer">The buffer to read the data into.</param> /// <param name="offset">The byte offset in buffer at which to begin writing /// data read from the stream.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>Number of bytes read from the stream.</returns> private async Task<int> DispatchReadASync(byte[] buffer, int offset, int count) { try { this.internalBuffer.SetLength(0); await this.file.DownloadRangeToStreamAsync( this.internalBuffer, this.currentOffset, this.GetReadSize(), null /* accessCondition */, this.options, this.operationContext); if (!this.file.Properties.ETag.Equals(this.accessCondition.IfMatchETag, StringComparison.Ordinal)) { RequestResult reqResult = new RequestResult(); reqResult.HttpStatusMessage = null; reqResult.HttpStatusCode = (int)HttpStatusCode.PreconditionFailed; reqResult.ExtendedErrorInformation = null; throw new StorageException(reqResult, SR.PreconditionFailed, null /* inner */); } this.internalBuffer.Seek(0, SeekOrigin.Begin); return this.ConsumeBuffer(buffer, offset, count); } catch (Exception e) { this.lastException = e; throw; } }
public async Task CloudFileClientMaximumExecutionTimeoutAsync() { CloudFileClient fileClient = GenerateCloudFileClient(); CloudFileShare share = fileClient.GetShareReference(Guid.NewGuid().ToString("N")); CloudFileDirectory rootDirectory = share.GetRootDirectoryReference(); byte[] buffer = FileTestBase.GetRandomBuffer(80 * 1024 * 1024); try { await share.CreateAsync(); fileClient.DefaultRequestOptions.MaximumExecutionTime = TimeSpan.FromSeconds(5); CloudFile file = rootDirectory.GetFileReference("file"); file.StreamWriteSizeInBytes = 1 * 1024 * 1024; using (MemoryStream ms = new MemoryStream(buffer)) { try { await file.UploadFromStreamAsync(ms); Assert.Fail(); } catch (AggregateException ex) { #if !FACADE_NETCORE Assert.AreEqual("The client could not finish the operation within specified timeout.", RequestResult.TranslateFromExceptionMessage(ex.InnerException.Message).ExceptionInfo.Message); #else Assert.AreEqual("The client could not finish the operation within specified timeout.", RequestResult.TranslateFromExceptionMessage(ex.InnerException.Message).Exception.Message); #endif } catch (TaskCanceledException) { } } } finally { fileClient.DefaultRequestOptions.MaximumExecutionTime = null; share.DeleteIfExistsAsync().Wait(); } }