/// <summary> /// /// </summary> /// <param name="builder"></param> /// <param name="serialization"></param> private void BuildHeaderLine(StringBuilder builder, IDictionary<string, object> serialization) { var obj = serialization.FirstOrDefault(); var lines = obj.Value as IList<object>; if (lines == null) lines = new List<object>(new[] { serialization }); IDictionary line = lines.FirstOrDefault() as IDictionary; if (line != null) { IList<string> values = new List<string>(); foreach (DictionaryEntry entry in line) { if ((string)entry.Key == Serializer.ModelNameKey) continue; if (!(entry.Key is string)) throw new ArgumentException("Key of serialization dictionary must be a string.", "serialization"); var key = (entry.Key ?? "").ToString().Replace(FieldDefinition, FieldDefinitionEscape); values.Add(FieldDefinition + key + FieldDefinition); } builder.Append(String.Join(SeperatorCharacter.ToString(), values.ToArray())); builder.Append(LineTermination); } }
public bool OpenProject([Required] string projectName) { bool result = false; try { if (_uri != null) { var project = _availableProjects? .FirstOrDefault(x => string.CompareOrdinal(projectName, x.Key) == 0); if (project.HasValue) { Project = project.Value.Key; _projectId = project.Value.Value; ProjectOpened?.Invoke(this, projectName); result = true; } } } catch { Project = null; _projectId = Guid.Empty; } return(result); }
public KeyValuePair<string, string> GetKey(string typeName, IDictionary<string, object> values) { var fields = GetFields(typeName); var keyField = fields.First(o => o.IsKey); var kvp = values.FirstOrDefault(o => o.Key == keyField.FieldName); return new KeyValuePair<string, string>(kvp.Key, (kvp.Value ?? "").ToString()); }
public TemplateResult(bool success, IDictionary<string,string> dic) { var key = dic.FirstOrDefault(); Name = key.Key; Value = key.Value; Success = success; }
/// <summary> /// Internal constructor - the initialization of this exception may only be done internally from the ModelWithValidation class /// </summary> /// <param name="validationErrors"></param> internal ValidationException(IDictionary<string, IList<string>> validationErrors) : base((validationErrors == null || validationErrors.Count == 0) ? "" : ( validationErrors.Count == 1 && validationErrors.FirstOrDefault().Value.Count == 1 ? String.Format("Validation of property \"{0}\" failed with reason: \"{1}\".", validationErrors.FirstOrDefault().Key, validationErrors.FirstOrDefault().Value[0]) : "Multiple validation errors occurred")) { if (validationErrors == null || validationErrors.Count == 0 || validationErrors.FirstOrDefault().Value.Count == 0) { throw new ArgumentNullException("validationErrors", "Should be not null or empty"); } foreach (var _validationError in validationErrors) { Data.Add(_validationError.Key, _validationError.Value); } }
public object Handle(IDictionary<string, object> sourceList, MapperConfig config) { string sourceName = config.SourceName.FirstOrDefault(); if (sourceName == null) throw new ArgumentException("Incorrect field name for mapped to {0}", config.DestinationName); string[] values = sourceList.FirstOrDefault(x => x.Key.Equals(sourceName)).Value as string[]; return string.Join(",", values); }
//public List<IWebSocket> this[string metadata] //{ // get // { // if (clientsByMetadata.ContainsKey(metadata)) // { // return clientsByMetadata[metadata]; // } // return new List<IWebSocket>(); // } //} private void OnHandShaken(IWebSocket webSocket, ClientHandshake clientHandshake) { var handler = handlerFactory.Create(clientHandshake.ResourceName); if (handler != null) { webSocket.Received = handler.Received; webSocket.Disconnected = sender => { var found = clientsByMetadata.FirstOrDefault(kv => kv.Value.Exists(ws => ws == sender)); if (found.Value != null) { found.Value.Remove((WebSocket)sender); if (!found.Value.Any()) { clientsByMetadata.Remove(found.Key); } // A web socket with the metaData has been disconnected from the server handler.Disconnected(found.Key); } }; webSocket.Error = handler.Error; var metadata = GetMetadata(clientHandshake, webSocket); // A web socket with the metaData has been connected to the server handler.Connected(metadata); if (!clientsByMetadata.ContainsKey(metadata)) { clientsByMetadata.Add(metadata, new List <IWebSocket> { webSocket }); } else { //clientsByMetaData[metaData].Dispose(); clientsByMetadata[metadata].Add(webSocket); } // Begin receiving data from the client webSocket.ReceiveAsync(); } else { if (Log.IsDebugEnabled) { Log.Debug("There was no handler found for the resource name"); } // If nothing is handling client connections // the client connection should be closed webSocket.Dispose(); } }
public void Convert(UrdfRobot robot, string baseDirectory) { _linkToParentJoint = FindLinkParents(robot); var rootLink = _linkToParentJoint.FirstOrDefault(link => link.Value == null).Key; if (rootLink != null) { LoadLink(rootLink, Matrix.Identity, baseDirectory); } }
public string GetSecretForAppKey(string appKey) { KeyValuePair<string,string> result = _appKeySecretDict.FirstOrDefault((dict) => dict.Key == appKey); if (!string.IsNullOrWhiteSpace(result.Value)) { return result.Value; //var hash= _hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(result.Value)); //return Convert.ToBase64String(hash); } return string.Empty; }
public IGraphType this[Type type] { get { lock (_lock) { var result = _types.FirstOrDefault(x => x.Value.GetType() == type); return(result.Value); } } }
private CallbackDelegate OnVolumeChange(IDictionary <string, object> args, CallbackDelegate callback) { var volume = args.FirstOrDefault(arg => arg.Key == "volume").Value?.ToString(); if (!string.IsNullOrEmpty(volume)) { TriggerServerEvent(ServerEvents.OnSetVolume, volume); } return(callback); }
private CallbackDelegate OnSeek(IDictionary <string, object> args, CallbackDelegate callback) { var screenName = args.FirstOrDefault(arg => arg.Key == "screenName").Value?.ToString(); if (string.IsNullOrEmpty(screenName)) { return(callback); } if (!float.TryParse( args.FirstOrDefault(arg => arg.Key == "time").Value?.ToString(), out var time)) { return(callback); } this.playerPool.Seek(screenName, time); return(callback); }
Expression ParseAtom() { if (Accept(TokenType.Int, out IToken token)) { return(new IntLiteralExpression(token)); } else if (Accept(TokenType.Float, out token)) { return(new FloatLiteralExpression(token)); } else if (Accept(TokenType.Bool, out token)) { return(new BoolLiteralExpression(token)); } else if (Accept(TokenType.Ident, out token)) { Variable variable; if ((variable = Variables.FirstOrDefault(x => x.Key == token.Text).Value) != null) { if (variable is FloatVariable) { return(new FloatLiteralExpression((variable as FloatVariable).Value, token.LineNumber, token.ColumnNumber, token.LineNumber, token.ColumnNumber)); } else if (variable is BoolVariable) { return(new BoolLiteralExpression((variable as BoolVariable).Value, token.LineNumber, token.ColumnNumber, token.LineNumber, token.ColumnNumber)); } else { throw new Exception($"Invalid variable type {variable.GetType()}"); } } else { throw new Exception($"Invalid identifier {token.Text}"); } } else if (Accept(TokenType.OpenBracket)) { Expression innerExpression = ParseExpression(); if (Expect(TokenType.CloseBracket)) { return(innerExpression); } else { throw new Exception($"Missing matching close bracket for open at {innerExpression.EndLine}:{innerExpression.EndColumn}"); } } else { throw new Exception($"Invalid token at PUT LINE NUMBER HERE SOMEHOW"); } }
/// <summary>取值 /// </summary> /// <typeparam name="TKey">Key的泛型类型</typeparam> /// <typeparam name="TValue">值的泛型类型</typeparam> /// <param name="dictionary">字典</param> /// <param name="key">Key</param> /// <param name="ignoreCase">忽略大小写</param> /// <returns></returns> public static TValue GetOrDefault <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, TKey key, bool ignoreCase = false) { if (ignoreCase && key.GetType() == typeof(string)) { var kv = dictionary.FirstOrDefault(x => x.Key.ToString().ToUpper() == key.ToString()); if (!kv.Key.ToString().IsNullOrEmpty()) { key = kv.Key; } } return(dictionary.TryGetValue(key, out TValue o) ? o : default);
private CallbackDelegate OnStopVideo(IDictionary <string, object> args, CallbackDelegate callback) { var screenName = args.FirstOrDefault(arg => arg.Key == "screenName").Value?.ToString(); if (string.IsNullOrEmpty(screenName)) { return(callback); } TriggerServerEvent(ServerEvents.OnStopVideo, screenName); return(callback); }
public override object ConvertToInternal(List <CassandraObject> value, Type destinationType) { if (!(value is List <CassandraObject>)) { return(null); } if (destinationType == typeof(string)) { return(String.Join(":", (IEnumerable <CassandraObject>)value)); } if (destinationType == typeof(byte[])) { var components = value; using (var bytes = new MemoryStream()) { foreach (var c in components) { var b = (byte[])c; var length = (ushort)b.Length; // comparator part bytes.WriteByte((byte)1); bytes.WriteByte((byte)_aliases.FirstOrDefault(x => x.Value.FluentType == c.GetType()).Key); // value length bytes.Write(BitConverter.GetBytes(length), 0, 2); // value bytes.Write(b, 0, length); // end of component bytes.WriteByte((byte)0); } return(bytes.ToArray()); } } if (destinationType == typeof(CassandraObject[])) { return(value.ToArray()); } if (destinationType == typeof(List <CassandraObject>)) { return(value); } return(null); }
public JSONDictionarySourceProvider(string name, IDictionaryReader reader, DictionaryConfiguration configuration = null) { _reader = reader; if (configuration == null) { configuration = DictionaryConfiguration.Default; } _dictionaryConfiguration = configuration; _dictionaries = _reader.Initialize(); // var _default = _dictionaries.FirstOrDefault(x => x.Value.Language.IsDefault == true); _defaultDictionarySource = _dictionaries.FirstOrDefault(x => x.Value.Language.IsDefault == true).Value; //_default != null ? _default.Value : null; }
private static int SelectSamplingWindow(DateTime fromDate, DateTime toDate) { var window = (toDate - fromDate).TotalMinutes; var matchingWindow = SamplingWindows.FirstOrDefault(sw => window <= sw.Key.TotalMinutes); if (matchingWindow.Equals(default(KeyValuePair <TimeSpan, TimeSpan>))) { return(DefaultWindowMinutes); } return((int)matchingWindow.Value.TotalMinutes); }
private string GetDataBaseColumnName(string memberName) { if (_modelMapperDictionary == null || !_modelMapperDictionary.Any()) { return(memberName); } var mapping = _modelMapperDictionary.FirstOrDefault(mm => mm.Key.ToLower() == memberName.ToLower()); return(default(KeyValuePair <string, string>).Equals(mapping) ? memberName : mapping.Value.Replace("[", string.Empty).Replace("]", string.Empty)); }
private static bool TryGetNativePacketTypeIdentifier(int num, out string?type) { type = null; if (s_PacketTypes.All(c => c.Value != num)) { return(false); } type = s_PacketTypes.FirstOrDefault(c => c.Value == num).Key; return(true); }
private async void TTSCallback(IUserEvent userEvent) { IDictionary <string, object> payloadData = JsonConvert.DeserializeObject <Dictionary <string, object> >(userEvent.Data["Payload"].ToString()); string text = Convert.ToString(payloadData.FirstOrDefault(x => x.Key == "Text").Value); if (!string.IsNullOrWhiteSpace(text)) { await _misty.SpeakAsync(text, true, null); await _misty.DisplayTextAsync(text, null); } }
public string this[Type type] { get { string alias; if ((alias = _mappings.FirstOrDefault(m => m.Value == type).Key) != null) { return(alias); } throw new InvalidOperationException(type?.FullName); } }
private void HandleRejectRequestFromTargetTerminal(IPort port, ICallingEventArgs e) { IPort sourcePort = _onConnection.FirstOrDefault(x => x.Value == port).Key; IPort targetPort = port; Console.WriteLine( "Station: port[{0}] transfer reject from terminal {2} to terminal {1}.\n", targetPort.PortId, e.SourceNumber, e.TargetNumber); _onConnection.Remove(sourcePort); sourcePort.PortReciveReject(sourcePort, e); }
private void FillDataFromFields(VideoGameDto videoGame, bool isNew) { var platform = _itemsPlatform.FirstOrDefault(x => x.Value.Equals(PlatformDropDown.SelectedValue)).Key; videoGame.Title = isNew ? TitleText.Text.RemoveMultipleSpace().ToUpperAllFirstLetter() : TitleText.Text; videoGame.Price = Convert.ToDecimal(PriceNumeric.Value); videoGame.QuantityDisc = Convert.ToInt32(QuantityNumeric.Value); videoGame.Platform = platform; var state = _changeItemsStateProduct.FirstOrDefault(valuePair => valuePair.Value.Equals(ChangeProductStateComboBox.SelectedValue)).Key; videoGame.State = state; }
public static OpenApiSchema?GetSchema(this IDictionary <string, OpenApiMediaType> content, string contentType = MediaTypeNames.Application.Json) { if (content == null) { throw new ArgumentNullException(nameof(content)); } var(key, value) = content.FirstOrDefault(x => string.Equals(x.Key, contentType, StringComparison.Ordinal)); return(key == null ? null : value.Schema); }
public async Task <IActionResult> AuditPropertiesList(int auditId, IDictionary <string, string> paramList, ActionListOption <LogAuditListOfChangesDTO> options) { options.pg_PartialViewName = "_AuditProperties"; var pagingList = await PartialList(paramList, options, async (x, y) => await _auditService.DataService.GetDtoAsync <LogAuditListOfChangesDTO>(aud => aud.AuditEntryId == auditId)); _auditService.SetDisplayNameEntityProp(pagingList, true); // Remove unnecessary fields for the user. pagingList.RemoveAll(p => (p.PropertyName.EndsWith("Id") && p.PropertyName != "Id") || (string.IsNullOrEmpty(p.PropertyDisplayName) && p.PropertyName != "Id")); var audHistory = _auditService.GeEntityHistoryById(auditId); #region Filter date var paramDate = paramList.FirstOrDefault(p => p.Key == "filterDate"); if (!string.IsNullOrEmpty(paramDate.Value)) { var filterDate = paramDate.Value.Split("||"); if (filterDate.Length >= 1) { if (DateTime.TryParse(filterDate[0], out var dateFrom)) { if (dateFrom != DateTime.MinValue) { audHistory = audHistory.Where(p => p.CreatedDate.Date >= dateFrom.Date); } } } if (filterDate.Length == 2) { if (DateTime.TryParse(filterDate[1], out var dateTo)) { if (dateTo != DateTime.MinValue) { audHistory = audHistory.Where(p => p.CreatedDate.Date <= dateTo.Date); } } } } #endregion var audEntityHistory = audHistory.Select(p => new { Id = p.AuditEntryId, Name = p.CreatedDate.ToString("dd-MM-yyyy HH:mm") + " - " + p.CreatedBy }); ViewBag.listOfDate = new SelectList(audEntityHistory, "Id", "Name", auditId); return(PartialView(options.pg_PartialViewName, pagingList)); }
/// <summary> /// Initializes a new <see cref="AnalyzeContext"/> instance. /// </summary> /// <param name="projects">A dictionary of projects and their compilation for easy access.</param> /// <param name="options">The <see cref="AnalyzeOptions"/> that were passed to the command line.</param> public AnalyzeContext(IDictionary <Project, Lazy <Compilation> > projects, AnalyzeOptions options) { this.Projects = projects; this.Collector = new InvocationTreeCollector(this); this.Options = options; this.SpecifcationsProject = projects.FirstOrDefault(p => p.Key.Name == options.SpecificationsProject).Key; if (this.SpecifcationsProject == null) { throw new ArgumentException($"Project {options.SpecificationsProject} not found in solution."); } }
private ITemplate TryLoadExistingTemplate(string filePath) { // ReSharper disable once InconsistentlySynchronizedField var existingItem = Cache.FirstOrDefault(x => x.Key.Key == filePath && x.Key.Value == _languageManager.Language); if (!existingItem.Equals(default(KeyValuePair <KeyValuePair <string, string>, string>))) { return(new Template(existingItem.Value, _languageManager.Language, false)); } return(null); }
private void AddParamForms() { /* Update the UI Grid to fit everything */ for (int i = 0; i < parameterDict.Count * 2; i++) { RowDefinition rowDef = new RowDefinition(); rowDef.Height = System.Windows.GridLength.Auto; ParametersGrid.RowDefinitions.Add(rowDef); } Grid.SetRow(ButtonsPanel, ParametersGrid.RowDefinitions.Count - 1); /* Fill the UI with parameter data */ int count = 0; foreach (string paramName in parameterDict.Keys) { /* Parameter Name and Type */ Label parameterNameLabel = new Label(); parameterNameLabel.Content = paramName; Label parameterTypeLabel = new Label(); parameterTypeLabel.Content = "(" + parameterDict[paramName].Type + "): "; Grid.SetRow(parameterNameLabel, count * 2); Grid.SetRow(parameterTypeLabel, count * 2); Grid.SetColumn(parameterNameLabel, 0); Grid.SetColumn(parameterTypeLabel, 1); /* Input field */ TextBox parameterValueBox = new TextBox(); parameterValueBox.Name = paramName; // Set previous value for this parameter if available if (existingParamsDict != null) { var paramValue = existingParamsDict.FirstOrDefault(x => x.Key == paramName).Value; if (paramValue != null) { parameterValueBox.Text = paramValue; } } parameterValueBox.MinWidth = 200; parameterValueBox.Margin = new System.Windows.Thickness(0, 5, 5, 5); Grid.SetColumn(parameterValueBox, 0); Grid.SetRow(parameterValueBox, count * 2 + 1); Grid.SetColumnSpan(parameterValueBox, 2); /* Add to Grid */ ParametersGrid.Children.Add(parameterNameLabel); ParametersGrid.Children.Add(parameterTypeLabel); ParametersGrid.Children.Add(parameterValueBox); count++; } // Set focus to first parameter textbox if (count > 0) { ParametersGrid.Children[3].Focus(); } }
public bool removeToken(string gUIDtokenKey) { if (tokens.FirstOrDefault().Key == gUIDtokenKey) { tokens.Remove(gUIDtokenKey); return(true); } else { return(false); } }
private SubscriptionPlan GetPlan(int catalogItemId, SubscriptionPlan?existingSubscriptionPlan) { if (existingSubscriptionPlan != null) { if (_subscriptionCatalogMapping.TryGetValue(existingSubscriptionPlan.Value, out var purchasedProduct)) { purchasedProduct = purchasedProduct.Append(catalogItemId).OrderBy(x => x).ToArray(); var newPlanMapping = _subscriptionCatalogMapping.FirstOrDefault(x => x.Value.SequenceEqual(purchasedProduct)); return(newPlanMapping.Key); } } else { var newPlanMapping = _subscriptionCatalogMapping.FirstOrDefault(x => x.Value.SequenceEqual(new[] { catalogItemId })); return(newPlanMapping.Key); } throw new InvalidOperationException("Subscription plan not found"); }
public static OpenApiSchema?GetSchema(this IDictionary <string, OpenApiMediaType> content, string contentType = "application/json") { if (content == null) { throw new ArgumentNullException(nameof(content)); } var(key, value) = content.FirstOrDefault(x => x.Key == contentType); return(key == null ? null : value.Schema); }
private CallbackDelegate GetStateResponse(IDictionary <string, object> args, CallbackDelegate callback) { bool.TryParse(args.FirstOrDefault(arg => arg.Key == "paused").Value?.ToString(), out var paused); float.TryParse(args.FirstOrDefault(arg => arg.Key == "currentTime").Value?.ToString(), out var currentTime); float.TryParse(args.FirstOrDefault(arg => arg.Key == "duration").Value?.ToString(), out var duration); bool.TryParse(args.FirstOrDefault(arg => arg.Key == "ended").Value?.ToString(), out var ended); var currentSource = args.FirstOrDefault(arg => arg.Key == "currentSource").Value?.ToString(); var screenName = args.FirstOrDefault(arg => arg.Key == "screenName").Value?.ToString(); if (string.IsNullOrEmpty(screenName)) { Debug.WriteLine("error: received state response without valid screenName."); return(callback); } var state = new DuiState { CurrentTime = currentTime, ScreenName = screenName, Ended = ended, IsPaused = paused, Duration = duration, CurrentSource = currentSource }; StateQueue.Enqueue(state); return(callback); }
private void ProcessParameters(IDictionary <string, object> parameters) { try { object debugMode = parameters.FirstOrDefault(x => x.Key.ToLower().Trim() == "debugMode").Value; if (debugMode != null) { _debugMode = Convert.ToBoolean(debugMode); } if (_debugMode) { _misty.SkillLogger.LogLevel = SkillLogLevel.Verbose; } object driveMode = parameters.FirstOrDefault(x => x.Key.ToLower().Trim() == "drivemode").Value; if (driveMode != null && Enum.TryParse(typeof(DriveMode), Convert.ToString(driveMode).Trim(), true, out object driveModeEnum)) { _driveMode = (DriveMode)driveModeEnum; } switch (_driveMode) { case DriveMode.Wander: _driveManager = new WanderDrive(_misty, _currentObstacleState, _debugMode); _driveHeartbeat = new DriveHeartbeat(150); break; case DriveMode.Careful: _driveManager = new CarefulDrive(_misty, _currentObstacleState, _debugMode); _driveHeartbeat = new DriveHeartbeat(3000); break; } } catch (Exception ex) { _misty.SkillLogger.Log("Failed handling startup parameters", ex); } }
/// <summary> /// depending on the user input (pressed key) in calculator, /// return the type of operation which must be done /// </summary> /// <param name="keyInfo"></param> /// <param name="operation"></param> /// <returns></returns> public virtual KeyType GetKeyType(ConsoleKeyInfo keyInfo, ref KeyValuePair <MathOperation, char> operation) { try { int number = 0; //if numeric / point / comma key has been pressed if (int.TryParse(keyInfo.KeyChar.ToString(), out number) || keyInfo.KeyChar == ',' || keyInfo.KeyChar == '.') { return(KeyType.Numeric); } //if backspace '<-' button has been pressed else if (keyInfo.KeyChar == '\b') { return(KeyType.DeleteLast); } //if 'c' button has been pressed else if (keyInfo.KeyChar.ToString().ToLower() == "c") { return(KeyType.ClearBufferAndShowInitScreen); } //if 'Enter' button has been pressed else if (keyInfo.KeyChar.ToString().ToLower() == "\r") { return(KeyType.ClearBufferAndShowResult); } //if 'q' or 'Q' button has been pressed else if (keyInfo.KeyChar.ToString().ToLower() == "q") { return(KeyType.Exit); } else { //if any calc operation key (+, -, *, /, e ...) has been pressed operation = _calcOperationType.FirstOrDefault(x => x.Value == keyInfo.KeyChar); if (Enum.IsDefined(typeof(MathOperation), operation.Key)) { return(KeyType.CalcOperation); } else { return(KeyType.Na); } } } catch (Exception ex) //if error has been occured than show the error description and stack trace { ConsoleIO.Console_ShowErrorDescription(ex); Environment.Exit(0); } return(KeyType.Na); }
/// <summary> /// Given an IDictionary of mappings between old and new URLs, converts the URL /// in every Preview in the JdfTree to the appropriate new URL. /// </summary> /// <param name="ticket">The Ticket to process</param> /// <param name="urlMapping">A IDictionary keyed by existing URLs mapping to new System.Uri</param> /// <param name="mustMapCIDs">If <i>true</i> throws an exception if an existing URL starts with CID and /// no mapping has been provided for that CID.</param> /// <exception cref="JdfException">Thrown if mustMapCIDs is true and no mapping was supplied for a CID-based URL.</exception> public static void MapPreviewUrls(Ticket ticket, IDictionary<string, string> urlMapping, bool mustMapCIDs) { var previews = ticket.Root.SelectJDFDescendants(Element.Preview); foreach (var preview in previews) { var urlValue = preview.GetAttributeValueOrNull("URL"); if (urlValue != null) { string newUrl = urlMapping.FirstOrDefault(item => item.Key.Equals(urlValue, StringComparison.OrdinalIgnoreCase)).Value; if (newUrl != null) { preview.AddOrReplaceAttribute(new XAttribute("URL", (new Uri(newUrl)).AbsoluteUri)); } else { if (urlValue.StartsWith("cid:", StringComparison.OrdinalIgnoreCase) && mustMapCIDs) { throw new JdfException(string.Format(FluentJdf.Resources.Messages.MustMapCIDsIsTrueAndNoMappingSuppliedForURL, urlValue)); } } } } }
/// <summary> /// Serializes to json. /// </summary> /// <param name="serialization">The serialization.</param> /// <returns></returns> private void BuildLine(StringBuilder builder, IDictionary<string, object> serialization) { var obj = serialization.FirstOrDefault(); var lines = obj.Value as IList<object>; if (lines == null) lines = new List<object>(new[] { serialization }); foreach (var line in lines.Cast<IDictionary>()) { if (line != null) { IList<string> values = new List<string>(); foreach (DictionaryEntry entry in line) { if (!(entry.Key is string)) throw new ArgumentException("Key of serialization dictionary must be a string.", "serialization"); values.Add((entry.Value ?? "").ToString()); } builder.Append(String.Join(SeperatorCharacter.ToString(), values.ToArray())); builder.Append(LineTermination); } } }
private bool GetRootParent(int categoryId, IDictionary<string, object> source) { var item = source.FirstOrDefault(t => t.Key.Equals(categoryId.ToString())); { var valueCate = item.Value as Dictionary<string, object>; var parents = (valueCate["parents"] as object[]); if (parents.Count() > 0) { int pId = int.Parse(parents[0].ToString()); if (pId == rootId) return true; else return GetRootParent(pId, source); } } return false; }
static Task RunWorkers(IDictionary<Task, StateExpander> workers) { var setMinScores = new Action<int, StateExpander[]>((newMin, workObjects) => { _globalMin = Math.Min(_globalMin, newMin); foreach (var stateExpander in workObjects) { stateExpander.SetMinScore(newMin); } }); var continueAction = new Action<Task>(task => { lock(workers) { var resultData = workers[task]; Console.WriteLine("\n\nThread complete: {0}", task.Id); Console.WriteLine("Min score: {0}", resultData.MinScore); var nextWorker = workers.FirstOrDefault(m => m.Key.Id == _nextThreadId); if (nextWorker.Key != null) { Console.WriteLine("Starting thread: {0}", nextWorker.Key.Id); nextWorker.Key.Start(); _nextThreadId += 1; } } }); var result = new Task(() => { var workTasks = workers.Select(m => m.Key).ToArray(); var workObjects = workers.Select(m => m.Value).ToArray(); foreach (var stateExpander in workObjects) { stateExpander.NewMinFound += newMin => setMinScores(newMin, workObjects); } lock (workers) { foreach (var stateExpander in workTasks) { stateExpander.ContinueWith(continueAction); if (_nextThreadId <= MaxConcurrentWorkers) { Console.WriteLine("Starting thread: {0}", stateExpander.Id); stateExpander.Start(); _nextThreadId += 1; } } } Task.WaitAll(workTasks); }); result.Start(); return result; }
internal void MapMessageUrls(Message message, IDictionary<string, string> urlMapping) { // Access the URL in the QueueSubmissionParams or ResubmissionParams of each Command element in the JMF. foreach (var command in message.Root.SelectJDFDescendants(Element.Command)) { bool toProcess = false; var commandType = command.GetAttributeValueOrNull("Type"); IEnumerable<XElement> submissionParams = null; if (commandType == Command.SubmitQueueEntry) { submissionParams = command.SelectJDFDescendants(Element.QueueSubmissionParams); if (submissionParams.Count() == 0) { throw new JdfException(FluentJdf.Resources.Messages.QueueSubmissionParamsAreRequiredInSubmitQueueEntry); } else { toProcess = true; } } if (commandType == Command.ResubmitQueueEntry) { submissionParams = command.SelectJDFDescendants(Element.ResubmissionParams); if (submissionParams.Count() == 0) { throw new JdfException(FluentJdf.Resources.Messages.ReSubmissionParamsAreRequiredInResubmitQueueEntry); } else { toProcess = true; } } if (toProcess) { string jdfUrl = submissionParams.First().GetAttributeValueOrNull("URL").ToString().ToLower(); string newUrl = urlMapping.FirstOrDefault(item => item.Key.Equals(jdfUrl, StringComparison.OrdinalIgnoreCase)).Value; if (newUrl != null) { submissionParams.First().AddOrReplaceAttribute(new XAttribute("URL", (new Uri(newUrl)).AbsoluteUri)); } } } }
private static void SetParameters(Procedure procedure, IDbCommand cmd, IDictionary<string, object> suppliedParameters) { var returnParameter = procedure.Parameters.FirstOrDefault(p => p.Direction == ParameterDirection.ReturnValue); if (returnParameter!=null) { var cmdParameter = cmd.CreateParameter(); cmdParameter.ParameterName = SimpleReturnParameterName; cmdParameter.Size = returnParameter.Size; cmdParameter.Direction = ParameterDirection.ReturnValue; cmdParameter.DbType = returnParameter.Dbtype; cmd.Parameters.Add(cmdParameter); } int i = 0; foreach (var parameter in procedure.Parameters.Where(p => p.Direction != ParameterDirection.ReturnValue)) { //Tim Cartwright: Allows for case insensive parameters var value = suppliedParameters.FirstOrDefault(sp => sp.Key.Equals(parameter.Name.Replace("@", ""), StringComparison.InvariantCultureIgnoreCase) || sp.Key.Equals("_" + i) ); var cmdParameter = cmd.CreateParameter(); //Tim Cartwright: method AddParameter does not allow for the "default" keyword to ever be passed into // parameters in stored procedures with defualt values. Null is always sent in. This will allow for default // values to work properly. Not sure why this is so, in both cases the value gets set. Just is. //var cmdParameter = cmd.AddParameter(parameter.Name, value); cmdParameter.ParameterName = parameter.Name; cmdParameter.Value = value.Value; cmdParameter.Direction = parameter.Direction; //Tim Cartwright: I added size and dbtype so inout/out params would function properly. //not setting the proper dbtype and size with out put parameters causes the exception: "Size property has an invalid size of 0" // Mark: Just adding a quick check here so that if the Provider-specific type has been set by setting the value, this will not // override that. if (cmdParameter.DbType != parameter.Dbtype) { cmdParameter.DbType = parameter.Dbtype; } cmdParameter.Size = parameter.Size; cmd.Parameters.Add(cmdParameter); i++; } }
/// <summary> /// </summary> /// <param name="namedTypeSymbol"> /// </param> /// <param name="map"> /// </param> /// <param name="resolvedTypes"> /// </param> /// <returns> /// </returns> private static bool SelectGenericsFromArgumentsForOneLevel( NamedTypeSymbol namedTypeSymbol, IDictionary<IType, IType> map, List<TypeSymbol> resolvedTypes) { foreach (var typeSymbol in namedTypeSymbol.TypeArguments) { if (typeSymbol.Kind == SymbolKind.TypeParameter) { var foundType = map.FirstOrDefault(pair => pair.Key.Name == typeSymbol.Name); if (foundType.Key == null) { return false; } resolvedTypes.Add((foundType.Value as MetadataTypeAdapter).TypeDef); continue; } var subTypeNamedTypeSymbol = typeSymbol as NamedTypeSymbol; if (subTypeNamedTypeSymbol != null && subTypeNamedTypeSymbol.Arity > 0) { resolvedTypes.Add(ConstructGenericTypeSymbol(subTypeNamedTypeSymbol, map)); continue; } resolvedTypes.Add(subTypeNamedTypeSymbol); } return true; }
private static void ClearTypesIn(IDictionary<string, string> dictionary, string typeName = null) { if (String.IsNullOrWhiteSpace(typeName)) { dictionary.Clear(); } else { KeyValuePair<string, string>? pair = dictionary.FirstOrDefault(x => x.Value.Equals(typeName)); if (pair != null && pair.Value.Key != null) dictionary.Remove(pair.Value.Key); } }
private static ApiObject FindObject(IHasName apiObject, IDictionary<string, ApiObject> objects, string key) { var foundKey = objects.Keys.FirstOrDefault(k => string.Equals(k, key)); var obj = foundKey != null ? objects[foundKey] : objects.FirstOrDefault(o => o.Value.Name == apiObject.Name).Value; return obj; }
private string GetValueFromParameters(string key, IDictionary<string, object> paras, object defaultValue) { if (key.StartsWith("{") && key.EndsWith("}")) { string paraName = key.Substring(1, key.Length - 2).ToLower(); var para = paras.FirstOrDefault(o => o.Key.ToLower() == paraName); object paraVal = default(KeyValuePair<string,object>).Equals(para) ? defaultValue : para.Value; return paraVal == null ? defaultValue.ToString() : paraVal.ToString(); } return defaultValue.ToString(); }
private Action FirstOrDefaultQuickFix(IDictionary<string, Action> fixes) { return fixes.FirstOrDefault().Value; }
public override string ProcessOrder([NotNull] Order order, IDictionary<string, object> parameters) { Assert.ArgumentNotNull(order, "order"); Assert.ArgumentNotNull(parameters, "parameters"); Assert.IsNotNull(parameters.FirstOrDefault(p => p.Key == "orderlineid").Value, "Order line ID should be passed as parameter."); Assert.IsNotNull(parameters.FirstOrDefault(p => p.Key == "productcode").Value, "Product code should be passed as parameter."); Assert.IsNotNull(parameters.FirstOrDefault(p => p.Key == "quantity").Value, "Quantity should be passed as parameter."); string productCode = parameters["productcode"].ToString(); Assert.IsTrue(productCode != string.Empty, "Product code must not be empty"); long quantity = long.Parse(parameters["quantity"].ToString()); long orderLineId = long.Parse(parameters["orderlineid"].ToString()); // Resolving of the OrderLine. OrderLine orderLine = order.OrderLines.Single(ol => ol.Alias == orderLineId); Assert.IsNotNull(orderLine, "Cannot resolve order line"); this.SetOrderStates(order); // Resolving of the Stock. ProductStockInfo currentProductStockInfo = new ProductStockInfo { ProductCode = orderLine.LineItem.Item.Code }; long currentProductStock = this.productStockManager.GetStock(currentProductStockInfo).Stock; ProductStockInfo newProductStockInfo = new ProductStockInfo { ProductCode = productCode }; long newProductStock = this.productStockManager.GetStock(newProductStockInfo).Stock; if (newProductStock < quantity) { return CustomResults.OutOfStock.ToString(); } // Updating of the stock this.productStockManager.Update(currentProductStockInfo, currentProductStock + (long)orderLine.LineItem.Quantity); this.productStockManager.Update(newProductStockInfo, newProductStock - quantity); this.FormattedMessageForOldOrderLine = this.CreateFormattedMessage(orderLine); // Updating of the LineItem Assert.IsNotNull(this.orderLineFactory, "OrderLineFactory cannot be null."); LineItem newLineItem = this.orderLineFactory.CreateLineItemFromOrder(order, productCode, quantity); orderLine.LineItem.CopyLineItemFrom(newLineItem); this.FormattedMessageForNewOrderLine = this.CreateFormattedMessage(orderLine); // Recalculate taxable amount. order = this.UpdateTaxesForOrder(order, orderLine); // Saving of the Order) this.merchantOrderManager.Save(order); return SuccessfulResult; }