/// <summary> /// Returns a <see cref="IUIElementAdapter"/> for the specified uielement. /// </summary> /// <param name="uiElement">UltraToolbar or PopupMenuTool for which to return a <see cref="IUIElementAdapter"/></param> /// <returns>A <see cref="IUIElementAdapter"/> that represents the specified <see cref="UltraToolbar"/> or <see cref="PopupMenuTool"/></returns> public IUIElementAdapter GetAdapter(object uiElement) { Guard.ArgumentNotNull(uiElement, "uiElement"); if (uiElement is TreeNodesCollection) { return(new TreeNodesCollectionUIAdapter((TreeNodesCollection)uiElement)); } if (uiElement is UltraTree) { return(new TreeNodesCollectionUIAdapter(((UltraTree)uiElement).Nodes)); } else if (uiElement is UltraTreeNode) { return(new TreeNodeOwnerUIAdapter((UltraTreeNode)uiElement)); } throw ExceptionFactory.CreateInvalidAdapterElementType(uiElement.GetType(), this.GetType()); }
/// <summary> /// Returns a <see cref="IUIElementAdapter"/> for the specified uielement. /// </summary> /// <param name="uiElement">uiElement for which to return a <see cref="IUIElementAdapter"/></param> /// <returns>A <see cref="IUIElementAdapter"/> that represents the specified element</returns> public IUIElementAdapter GetAdapter(object uiElement) { Guard.ArgumentNotNull(uiElement, "uiElement"); if (uiElement is RibbonControl) { return(new RibbonPageCollectionUIAdapter(((RibbonControl)uiElement).Pages)); } if (uiElement is RibbonPage) { return(new RibbonPageGroupCollectionUIAdapter(((RibbonPage)uiElement).Groups)); } if (uiElement is RibbonPageGroup) { return(new BarLinksCollectionUIAdapter(((RibbonPageGroup)uiElement).ItemLinks, ((RibbonPageGroup)uiElement).Ribbon.Items)); } if (uiElement is RibbonPageCollection) { return(new RibbonPageCollectionUIAdapter(((RibbonPageCollection)uiElement))); } if (uiElement is BarItemWrapper) { return(new BarLinksOwnerCollectionUIAdapter(((BarItemWrapper)uiElement).Item, ((BarItemWrapper)uiElement).ItemLinks)); } if (uiElement is RibbonQuickAccessToolbar) { return(new RibbonQuickAccessToolbarUIAdapter((RibbonQuickAccessToolbar)uiElement)); } if (uiElement is RibbonStatusBar) { return(new RibbonStatusBarUIAdapter((RibbonStatusBar)uiElement)); } throw ExceptionFactory.CreateInvalidAdapterElementType(uiElement.GetType(), GetType()); }
public async Task HandleAsync(UpdateCacheCommand command) { if (command == null) { throw ExceptionFactory.CommandIsNull(); } List <RecipModel> listOfRecipModel = new List <RecipModel>(); RootobjectModel rootobject = GetRootobject(GetFoodrepoProducts($"https://www.foodrepo.org/api/v3/products?page%5Bnumber%5D=1&page%5Bsize%5D={ command.PageSize }").Result, command.PageNumer); listOfRecipModel.AddRange(rootobject.Data); for (int i = 0; i < 3; i++) { rootobject = GetRootobject(GetFoodrepoProducts(rootobject.Links.Next).Result, command.PageNumer); listOfRecipModel.AddRange(rootobject.Data); } var tmpListOfRecips = (from RecipModel model in listOfRecipModel select _recipMapper.Map(model)).ToList(); var listOfRecip = _unitOfWork.Foodrepos.GetAllAsyncRecip().Result; foreach (Recip recip in listOfRecip) { if (tmpListOfRecips.Select(x => x.RepoId).ToList().Contains(recip.RepoId)) { tmpListOfRecips.Remove(tmpListOfRecips.Where(x => x.RepoId == recip.RepoId).First()); } } if (tmpListOfRecips.Count > 0 || listOfRecip.Count == 0) { try { _unitOfWork.Foodrepos.AddRangeRecip(tmpListOfRecips); _eventStore.AddEvents(_foodrepoEventFactory.GetFoodrepoUpdatedEvent(tmpListOfRecips)); await _unitOfWork.SaveAsync(); } catch (Exception ex) { _logger.LogError(ex.Message); } } }
/// <summary> /// Copy array string object to a remore file /// </summary> /// <param name="_string_list"></param> /// <param name="_remote_file_path"></param> /// <param name="_contactable_ip"></param> public async Task CopyStringArrayToRemoteFileAsync(string[] _string_list, string _remote_file_path, string _contactable_ip = null) { using (new Impersonator(_local_computeresource_context.GetCredentialUsername(), _local_computeresource_context.GetCredentialDomain(), _local_computeresource_context.GetCredentialPassword())) { string _remote_file_location = Path.Combine(@"\\", await _local_computeresource_context.GetContactibleIPAsync(true), _remote_file_path.Replace(':', '$')); if (!Directory.Exists(Path.GetDirectoryName(_remote_file_location))) { Directory.CreateDirectory(Path.GetDirectoryName(_remote_file_location)); } try { File.WriteAllLines(_remote_file_location, _string_list); } catch (Exception _ex) { throw ExceptionFactory.TerodoViewIoException(_ex, _remote_file_location); } } }
public async Task <Employee> AddEmployee(Employee newEmp, int userId) { if (newEmp.AvatarId != null) { var avatar = await _context.Avatar.FirstOrDefaultAsync(x => x.Id == newEmp.AvatarId); if (avatar == null) { throw ExceptionFactory.SoftException(ExceptionEnum.AvatarRecordDoesntExist, ""); } newEmp.Avatar = avatar; } if (newEmp.ResumeId != null) { var resume = await _context.Resume.FirstOrDefaultAsync(x => x.Id == newEmp.ResumeId); if (resume == null) { throw ExceptionFactory.SoftException(ExceptionEnum.ResumeRecordDoesntExist, ""); } newEmp.Resume = resume; } await _context.Employee.AddAsync(newEmp); await _context.SaveChangesAsync(); UserEmployee ue = new UserEmployee() { UserId = userId, EmployeeId = newEmp.Id, }; await _context.UserEmployee.AddAsync(ue); await _context.SaveChangesAsync(); return(newEmp); }
public async Task <string> ParseStructure(string markdownText) { var nodes = new Jsonize(markdownText).ParseHtmlToTypedJson();//.Children.FirstOrDefault();//HtmlToJsonService.HtmlToJson(markdownText).Replace("\r\n", ""); var flattenedNode = FlatNodes(nodes); foreach (var node in flattenedNode) { // ReSharper disable once StringLiteralTypo if (node.Tag == "linktocomponent") { var(_, idValue) = node.Attributes.FirstOrDefault(x => x.Key == "id"); if (idValue != null) { if (!int.TryParse((string)idValue, out var intId)) { throw ExceptionFactory.SoftException(ExceptionEnum.SomethingWentWrong, "Something went wrong"); } var linkToComment = await _publicContext.Comment.FirstOrDefaultAsync(x => x.Id == intId); if (linkToComment == null) //first i check is it link to comment because link to comment have bigger chance to appear { var linkToPost = await _publicContext.Post.FirstOrDefaultAsync(x => x.Id == intId); if (linkToPost != null) { node.Attributes.TryAdd("isPost", "true"); continue; } node.Attributes.TryAdd("isExist", "false"); continue; } node.Attributes.TryAdd("isComment", "true"); } } } return(JObject.FromObject(nodes, _jsonWriter).ToString()); //.Replace("\r\n", ""); }
public static ILayerScopeContextResolver Create(FindAs findAs) { switch (findAs) { case FindAs.Parent: return(ParentResolver); case FindAs.Sibling: return(SiblingResolver); case FindAs.Ancestor: return(AncestorResolver); case FindAs.ShadowHost: return(ShadowHostResolver); default: throw ExceptionFactory.CreateForUnsupportedEnumValue(findAs, nameof(findAs)); } }
public void NullInnerExceptionForMultipleEndpointsWithNoLastException() { try { using (var muxer = Create(keepAlive: 1, connectTimeout: 10000, allowAdmin: true)) { var conn = muxer.GetDatabase(); muxer.AllowConnect = false; SocketManager.ConnectCompletionType = CompletionType.Async; var ex = ExceptionFactory.NoConnectionAvailable(true, new RedisCommand(), null, null, muxer.GetServerSnapshot()); Assert.IsInstanceOf <RedisConnectionException>(ex); Assert.Null(ex.InnerException); } } finally { SocketManager.ConnectCompletionType = CompletionType.Any; ClearAmbientFailures(); } }
/// <summary> /// Publishes the specified message to all subscribers /// </summary> /// <typeparam name="T"></typeparam> /// <param name="message">The message.</param> public void Publish <T>(T message) where T : class, IMessage { ExceptionFactory.ThrowIf( message == null, () => new ArgumentNullException(nameof(message), "You can not publish a null message.")); if (!listeners.ContainsKey(typeof(T))) { return; } // Create a local reference of the collection to protect us against the collection // adding a new subscriber while we're enumerating var listenersToPublishTo = this.listeners[typeof(T)].ToArray(); foreach (INotification <T> handler in listenersToPublishTo) { handler.ProcessMessage(message); } }
private void Update(OrderFillEvent @event) { this.fillPrices[@event.OrderId] = @event.AveragePrice; this.precision = Math.Max(this.precision, @event.AveragePrice.Precision); switch (@event.OrderSide) { case OrderSide.Buy: this.HandleBuyOrderFill(@event); break; case OrderSide.Sell: this.HandleSellOrderFill(@event); break; default: throw ExceptionFactory.InvalidSwitchArgument(@event.OrderSide, nameof(@event.OrderSide)); } this.relativeQuantity = this.buyQuantity - this.sellQuantity; this.Quantity = Quantity.Create(Math.Abs(this.relativeQuantity)); if (this.Quantity > this.PeakQuantity) { this.PeakQuantity = this.Quantity; } if (this.relativeQuantity > 0) { this.MarketPosition = MarketPosition.Long; } else if (this.relativeQuantity < 0) { this.MarketPosition = MarketPosition.Short; } else { this.MarketPosition = MarketPosition.Flat; this.ClosedTime = @event.ExecutionTime; this.OpenDuration = this.ClosedTime - this.OpenedTime; } }
/// <summary> /// Returns the FXCM order status from the given string. /// </summary> /// <param name="orderStatus">The order status.</param> /// <returns>A <see cref="string"/>.</returns> public static string GetFxcmOrderStatus(string orderStatus) { switch (orderStatus) { case "W": return("Waiting"); case "P": return("In_Process"); case "I": return("Dealer_Intervention"); case "Q": return("Requoted"); case "E": return("Executing"); case "C": return("Cancelled"); case "R": return("Rejected"); case "T": return("Expired"); case "F": return("Executed"); case "U": return("Pending_Calculated"); case "S": return("Pending_Cancel"); default: throw ExceptionFactory.InvalidSwitchArgument(orderStatus, nameof(orderStatus)); } }
/// <summary> /// Writes the specified message as error message and then throws the specified exception. /// <para /> /// The specified exception must have a constructor that accepts a single string as message. /// </summary> /// <typeparam name="TException">The type of the exception.</typeparam> /// <param name="log">The log.</param> /// <param name="innerException">The inner exception.</param> /// <param name="messageFormat">The message format.</param> /// <param name="args">The args.</param> /// <returns>Exception.</returns> /// <exception cref="System.NotSupportedException"></exception> /// <exception cref="ArgumentNullException">The <paramref name="log" /> is <c>null</c>.</exception> /// <exception cref="NotSupportedException">The <typeparamref name="TException" /> does not have a constructor accepting a string.</exception> /// <example> /// <code> /// This example logs an error and immediately throws the exception:<para /><![CDATA[ /// throw Log.ErrorAndCreateException<NotSupportedException>("This action is not supported"); /// ]]></code> /// </example> public static Exception ErrorAndCreateException <TException>(this ILog log, Exception innerException, string messageFormat, params object[] args) where TException : Exception { return(ErrorAndCreateException <TException>(log, innerException, msg => { var exception = ExceptionFactory.CreateException <TException>(msg, innerException); if (exception == null) { var error = string.Format("Exception type '{0}' does not have a constructor accepting a string", typeof(TException).Name); if (log != null) { log.Error(error); } throw new NotSupportedException(error); } return exception; }, messageFormat, args)); }
public async Task <ReactionComment> AddReactionComment(ReactionComment reactionComment, Guid authorUser) { if (await _context.ReactionComment.AnyAsync(x => x.CommentId == reactionComment.CommentId && x.UserId == authorUser)) { throw ExceptionFactory.SoftException(ExceptionEnum.ReactionAlreadyExist, $"another reaction already exist"); } if (!await _context.ReactionTypeComment.AnyAsync(x => x.ReactionId == reactionComment.ReactionId)) { throw ExceptionFactory.SoftException(ExceptionEnum.ReactionDoesNotExist, $"reactionId does not exist"); } reactionComment.UserId = authorUser; var insertedReactionComment = await _context.ReactionComment.AddAsync(reactionComment); await _context.SaveChangesAsync(); return(insertedReactionComment.Entity); }
public void ExceptionFactoryTest() { var exception = ExceptionFactory.CreateException("code", "msg", "id", "host"); var exception1 = ExceptionFactory.CreateException("code1", "msg1", "id1", "host1", exception); Assert.AreEqual(exception1.InnerException, exception); try { ExceptionFactory.CreateInvalidResponseException(exception); Assert.IsTrue(false); } catch (InvalidOperationException e) { Assert.AreEqual(e.InnerException, exception); } catch (Exception e) { Assert.Fail(e.Message); } }
public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.ModelState.IsValid == false) { var errorList = string.Join(",", (from item in actionContext.ModelState where item.Value.Errors.Any() select item.Value.Errors[0].ErrorMessage).ToList()); actionContext.Request.Headers.TryGetValues("X-Correlation-Id", out _correlationGuid); logger.Error("Messasge: {0}, Guid:{1}, Uri:{2} ", errorList, _correlationGuid.First(), actionContext.Request.RequestUri); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(ExceptionFactory.GetExceptionText(errorList), Encoding.UTF8, "application/json"), RequestMessage = actionContext.Request }; actionContext.Response = response; } }
/// <summary> /// Writes the bytes data to the UART slave device. /// </summary> /// <param name="buffer">The byte array that contains the data to write to the device.</param> /// <param name="offset">The offset in buffer at which to begin copying bytes.</param> /// <param name="count">The number of bytes to write</param> public int Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count > buffer.Length - offset) { throw new Exception("Can not write more bytes than the buffer holds."); } byte[] tmpBuffer = new byte[count]; Array.Copy(buffer, offset, tmpBuffer, 0, count); var length = Convert.ToUInt32(count); var ret = NativeUart.Write(_handle, tmpBuffer, length); if (ret < Internals.Errors.ErrorCode.None) { throw ExceptionFactory.CreateException(ret); } return((int)ret); }
// * // Set the font for the text. // \param fontName Filenpath of a font or name of font (only on windows desktops) // \param fontSize Size of font [px] (default 12) // \exception Ogre::InvalidParametersException Empty font name // \exception Ogre::InvalidParametersException Font size is below 4 // \todo Add search for font names on non windows systems. // public TextShape setFont(string fontName, byte fontSize) { if (fontName.empty()) { //C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the C++ __LINE__ macro: //C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the C++ __FILE__ macro: throw ExceptionFactory.create(Mogre.ExceptionCodeType <Mogre.Exception.ExceptionCodes.ERR_INVALIDPARAMS>(), "There must be more than 0 characters in font name", "Procedural::TextShape::setFont(Ogre::String fontName, Ogre::byte fontSize)", __FILE__, __LINE__); } ; if (fontSize < 4) { //C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the C++ __LINE__ macro: //C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the C++ __FILE__ macro: throw ExceptionFactory.create(Mogre.ExceptionCodeType <Mogre.Exception.ExceptionCodes.ERR_INVALIDPARAMS>(), "Minimum font size is 4", "Procedural::TextShape::setFont(Ogre::String fontName, Ogre::byte fontSize)", __FILE__, __LINE__); } ; mFontName = fontName; mFontSize = fontSize; return(this); }
// ReSharper disable InconsistentNaming public void ExceptionFactoryCreateCriticalExceptionViewModel_LogFilesExists_EnsureThatTheLogFilesAreAlsoInitialized() { //Initialization var e = GetException(); const string studioLog = "Studio.log"; ExceptionFactory.GetStudioLogTempPath = () => studioLog; const string uniqueTxt = "Unique.txt"; ExceptionFactory.GetUniqueOutputPath = ext => uniqueTxt; const string severTxt = "Sever.txt"; ExceptionFactory.GetServerLogTempPath = evn => severTxt; //Execute var vm = ExceptionFactory.CreateViewModel(e, _contextModel.Object, ErrorSeverity.Critical); //Assert Assert.AreEqual(vm.StudioLogTempPath, studioLog); Assert.AreEqual(vm.ServerLogTempPath, severTxt); Assert.AreEqual(vm.OutputPath, uniqueTxt); }
async public Task AddSource(int groupId, int sourceId, int userId) { Group g = await _context.Group.Include(x => x.Category).FirstOrDefaultAsync(x => x.Category.AdminId == userId && x.Id == groupId); Source s = await _context.Source.FirstOrDefaultAsync(x => x.Id == sourceId); if (g != null && s != null) { await _context.GroupSource.AddAsync(new GroupSource() { GroupId = groupId, SourceId = sourceId, }); await _context.SaveChangesAsync(); } else { throw ExceptionFactory.SoftException(ExceptionEnum.GroupNotFound, $"Group with id {groupId} or source with {sourceId} not found"); } }
public void Timestamp_added_to_exception_data() { // Arrange NullReferenceException exception = null; // Act try { ExceptionFactory.ThrowIf( true, () => new NullReferenceException()); } catch (NullReferenceException ex) { exception = ex; } // Assert Assert.IsTrue(exception.Data.Contains("Date")); Assert.IsInstanceOfType(Convert.ToDateTime(exception.Data["Date"]), typeof(DateTime)); }
public ValidationException ThrowAll() { var exceptions = this.Where(predicate => !predicate.Validate()) .Select(error => ExceptionFactory .ArgumentException( m_rule.Target.Name, error.ErrorMessage, m_rule.Target .ExceptionData)); if (exceptions.IsEmpty()) { return(null); } return(ExceptionFactory.ValidationException(m_rule.Target.Name, "Validation of {0} Failed.".Inject(m_rule.Target.Name), exceptions, m_rule.Target.ExceptionData)); }
public ShowIngredientsPageViewModel( IIngredientsRepository ingredientsRepository, INavigationService navigationService, IUserInteraction userInteraction) : base(navigationService, ingredientsRepository) { this.WhenAnyObservable(vm => vm.Ingredients.ItemChanged) .ObserveOn(RxApp.MainThreadScheduler) .Where(arg => arg.PropertyName == nameof(DrinkIngredientViewModel.TickSelected)) .Select(arg => (DrinkIngredientViewModel)arg.Sender) .Do(ingredient => SelectedDrinkIngredient = ingredient) .Subscribe(async ingredientViewModel => { var selections = new List <string>() { "Edit", "Delete" }; var result = await userInteraction.DisplayActionSheetAsync( $"{ingredientViewModel.Name} selected!", "Cancel", null, selections.ToArray()); if (result == "Edit") { var navigationParameter = new TypedParameter(typeof(DrinkIngredientViewModel), ingredientViewModel); await navigationService.PushAsync <EditIngredientPageViewModel>(navigationParameter); } else if (result == "Delete") { await ingredientsRepository.DeleteAsync(ingredientViewModel.Ingredient); await ActivateAsync(); } else { ExceptionFactory.Get <NotImplementedException>("That selection is not jet implemented!"); } }); }
public override void Initialize(string name, NameValueCollection config) { foreach (var cfgKey in config.AllKeys) { config[cfgKey] = ConfigManager.ResolveValueSetting(config[cfgKey]); } ConnectionStringName = config["connectionStringName"]; System.Configuration.ConnectionStringSettings cnString = System.Configuration.ConfigurationManager.ConnectionStrings[ConnectionStringName]; if (cnString == null) { ExceptionFactory.Throw <System.Configuration.ConfigurationErrorsException>("Unable to find connection key '{0}' in <connectionStrings> section{1}{2}", ConnectionStringName, Environment.NewLine, getConfigMessage(config)); } else { ConnectionString = cnString.ConnectionString; } base.Initialize(name, config); //this erases all values in 'config' }
public virtual IEdge AddEdge(object id, IVertex outVertex, IVertex inVertex, string label) { GraphContract.ValidateAddEdge(id, outVertex, inVertex, label); string idString = null; IEdge edge; if (null != id) { idString = id.ToString(); edge = Edges.Get(idString); if (null != edge) { throw ExceptionFactory.EdgeWithIdAlreadyExist(id); } } else { var done = false; while (!done) { idString = GetNextId(); edge = Edges.Get(idString); if (null == edge) { done = true; } } } edge = new TinkerEdge(idString, outVertex, inVertex, label, this); Edges.Put(edge.Id.ToString(), edge); var out_ = (TinkerVertex)outVertex; var in_ = (TinkerVertex)inVertex; out_.AddOutEdge(label, edge); in_.AddInEdge(label, edge); return(edge); }
public async Task <UserAnswer> UserAnswer(InUserAnswer inUserAnswer, int userId) { var gameQuestion = await context.GameQuestions .FirstOrDefaultAsync(x => x.QuestionId == inUserAnswer.QuestionId && x.GameId == inUserAnswer.GameId); if (gameQuestion.IsCurrent == true) { var newUa = new UserAnswer { AnswerId = inUserAnswer.AnswerId, GameId = inUserAnswer.GameId, QuestionId = inUserAnswer.QuestionId, UserId = userId, }; await context.UserAnswers.AddAsync(newUa); await context.SaveChangesAsync(); return(await context.UserAnswers.Include(x => x.Answer).Include(x => x.User).FirstOrDefaultAsync(x => x.Id == newUa.Id)); } throw ExceptionFactory.SoftException(ExceptionEnum.QuestionNotCurrent, "QuestionNotCurrent"); }
/// <summary> /// Assign a key/value property to the vertex. /// If a value already exists for this key, then the previous key/value is overwritten. /// </summary> /// <param name="key">the string key of the property</param> /// <param name="value">the object value of the property</param> public override void SetProperty(string key, object value) { if (key == null || key.Length == 0) { throw new ArgumentException("Property key may not be null or be an empty string"); } if (value == null) { throw new ArgumentException("Property value may not be null"); } if (key.Equals(StringFactory.Id)) { throw ExceptionFactory.PropertyKeyIdIsReserved(); } PropertyType pt = m_vertexType.FindProperty(key); if (pt == null) { pt = m_vertexType.MyGraph.NewVertexProperty(m_vertexType, key, DataType.Object, PropertyKind.Indexed); } m_vertexType.SetPropertyValue(VertexId, pt, (IComparable)value); }
public void ServerTakesPrecendenceOverSnapshot() { try { using (var muxer = Create(keepAlive: 1, connectTimeout: 10000, allowAdmin: true)) { var conn = muxer.GetDatabase(); muxer.AllowConnect = false; muxer.GetServer(muxer.GetEndPoints()[0]).SimulateConnectionFailure(); var ex = ExceptionFactory.NoConnectionAvailable(true, true, new RedisCommand(), null, muxer.GetServerSnapshot()[0], muxer.GetServerSnapshot()); Assert.IsType <RedisConnectionException>(ex); Assert.IsType <RedisConnectionException>(ex.InnerException); Assert.Equal(ex.InnerException, muxer.GetServerSnapshot()[0].LastException); } } finally { ClearAmbientFailures(); } }
/// <summary> Make a DELETE request to the API. </summary> /// <param name="url"> URL of the request. </param> /// <returns> A Task. </returns> /// <seealso cref="M:TonyBaloney.St2.Client.ISt2Client.DeleteApiRequestAsync(string)"/> public async Task DeleteApiRequestAsync(string url) { using (var client = new HttpClient()) { client.BaseAddress = _apiUrl; client.AddXAuthToken(_token); try { var response = await client.DeleteAsync(url); if (!response.IsSuccessStatusCode) { throw ExceptionFactory.FailedDeleteRequest(response); } } catch (HttpRequestException hre) { throw new FailedRequestException(hre.Message); } } }
public void ServerTakesPrecendenceOverSnapshot() { try { using (var muxer = Create(keepAlive: 1, connectTimeout: 10000, allowAdmin: true, shared: false, backlogPolicy: BacklogPolicy.FailFast)) { muxer.GetDatabase(); muxer.AllowConnect = false; muxer.GetServer(muxer.GetEndPoints()[0]).SimulateConnectionFailure(SimulatedFailureType.All); var ex = ExceptionFactory.NoConnectionAvailable(muxer as ConnectionMultiplexer, null, muxer.GetServerSnapshot()[0]); Assert.IsType <RedisConnectionException>(ex); Assert.IsType <RedisConnectionException>(ex.InnerException); Assert.Equal(ex.InnerException, muxer.GetServerSnapshot()[0].LastException); } } finally { ClearAmbientFailures(); } }
public async Task <AuthorizationResponse> Register([FromBody] RegisterInModel registerInModel) { var isProviderTokenExist = Request.Headers.TryGetValue("ProviderToken", out var providerToken); if (isProviderTokenExist) { var providerTokenComponents = providerToken.ToString().Split(" "); if (providerTokenComponents.Length == 2) { var regService = RegisterServiceFactory.GetRegisterServiceCenter(providerTokenComponents[0], providerTokenComponents[1], serviceProvider); if (regService != null) { var user = await regService.RegisterUser(registerInModel); var token = jwtTokenService.GenerateToken(regService.GetAuthCenterName(), jwtTokenService.GetIdentity(user.Id, user.UserSecurities.First().AuthorizationCenterId, await regService.GetProviderId())); return(new AuthorizationResponse { Name = user.Name, UserId = user.Id, Token = token, }); } else { throw ExceptionFactory.SoftException(ExceptionEnum.AuthCenterNotFound, "AuthCenterNotFound"); } } else { throw ExceptionFactory.SoftException(ExceptionEnum.InvalidProviderTokenFormat, "InvalidProviderTokenFormat"); } } else { throw ExceptionFactory.SoftException(ExceptionEnum.ProviderTokenAbsent, "ProviderToken"); } }
/// <summary> /// Construct an exception from the given factory, using the message constructed from the given /// formatting arguments. /// </summary> /// <param name="factory"></param> /// <param name="fmt"></param> /// <param name="args"></param> internal static void ThrowException(ExceptionFactory factory, string fmt, params object[] args) { throw factory(String.Format(CultureInfo.CurrentCulture, fmt, args)); }
internal static void ThrowException( ExceptionFactory factory, string fmt, params object[] args ) { throw factory( String.Format( fmt, args ) ); }