Ejemplo n.º 1
0
        public CommandContext(IDictionary<string, IEnumerable<string>> propertyErrors, IEnumerable<string> operationErrors)
        {
            PropertyErrors = propertyErrors;
            OperationErrors = operationErrors;

            IsValid = !(operationErrors.Any() || propertyErrors.Any(t => t.Value.Any()));
        }
Ejemplo n.º 2
0
 public override Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state) {
     if (state.Any()) {
         Value = state[nameof(Value)]?.ToString();
         state.Clear();
     }
     return Task.CompletedTask;
 }
Ejemplo n.º 3
0
        protected string Generate(IDictionary<int, string> divisibleByLabels, int start, int end)
        {
            if (end <= start)
                throw new ArgumentException("Invalid start and end values.  Start must less than end");

            if (null != divisibleByLabels && divisibleByLabels.Any(x => x.Key == 0))
                throw new ArgumentException("Cannot have a zero divisible by", "divisibleByLabels");

            var returnValue = new StringBuilder();
            for (int i = start; i <= end; i++)
            {
                var line = string.Empty;
                if (null != divisibleByLabels)
                {
                    foreach (var label in divisibleByLabels)
                    {
                        if (i%label.Key == 0)
                            line += label.Value;
                    }
                }

                if (string.IsNullOrEmpty(line))
                    line = i.ToString(CultureInfo.InvariantCulture);
                returnValue.AppendLine(line);
            }

            return returnValue.ToString();
        }
 public async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
 {
     if (state.Any())
     {
         Sub = JsonConvert.DeserializeObject<SubredditItem>((string)state["sub"]);
         Images = IncrementalSubredditGallery.fromJson((string)state["images"]);
         state.Clear();
     }
     else
     {
         if (mode == NavigationMode.Back)
         {
             if (galleryMetaInfo == null)
             {
                 galleryMetaInfo = BootStrapper.Current.SessionState["GalleryInfo"] as GalleryMetaInfo;
                 Images = galleryMetaInfo?.Gallery as IncrementalSubredditGallery;
                 var sub = (await Reddits.SearchSubreddits(Images.Subreddit)).First(s => s.Data.DisplayName == Images.Subreddit);
                 Sub = new SubredditItem(sub);
             }
             ImageSelectedIndex = galleryMetaInfo?.SelectedIndex ?? 0;
         }
         else
         {
             Activate(parameter);
         }
     }
     await Task.CompletedTask;
 }
        public async Task<HttpResponseMessage> Send(HttpMethod method, Uri uri, IDictionary<string, string> requestHeaders, object content)
        {
            requestHeaders = requestHeaders ?? new Dictionary<string, string>() { };

            var httpRequestMessage = new HttpRequestMessage(method, uri)
            {
                Content = GetContent(content, requestHeaders),
            };

            foreach (var header in DefaultRequestHeaders)
            {
                if (requestHeaders.Any(x => x.Key == header.Key))
                    requestHeaders.Remove(header.Key);

                requestHeaders.Add(header.Key, header.Value);
            }

            foreach (var header in requestHeaders)
            {
                if (httpRequestMessage.Headers.Contains(header.Key))
                    httpRequestMessage.Headers.Remove(header.Key);

                httpRequestMessage.Headers.Add(header.Key, header.Value);
            }

            return await _httpClient.SendAsync(httpRequestMessage);
        }
Ejemplo n.º 6
0
 private static string GetBdmtTitles(IDictionary<Language, string> bdmtTitles)
 {
     return !bdmtTitles.Any()
                ? null
                : string.Join(Environment.NewLine,
                              bdmtTitles.Select(pair => string.Format("{0}: {1}", pair.Key.ISO_639_2, pair.Value)));
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="parameter">FortData containing the Pokestop that we're visiting</param>
 /// <param name="mode"></param>
 /// <param name="suspensionState"></param>
 /// <returns></returns>
 public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode,
     IDictionary<string, object> suspensionState)
 {
     if (suspensionState.Any())
     {
         // Recovering the state
         CurrentPokestop = (FortDataWrapper) suspensionState[nameof(CurrentPokestop)];
         CurrentPokestopInfo = (FortDetailsResponse) suspensionState[nameof(CurrentPokestopInfo)];
         CurrentSearchResponse = (FortSearchResponse) suspensionState[nameof(CurrentSearchResponse)];
     }
     else if (parameter is bool)
     {
         // Navigating from game page, so we need to actually load the Pokestop                  
         Busy.SetBusy(true, "Loading Pokestop");
         CurrentPokestop = (FortDataWrapper)NavigationHelper.NavigationState[nameof(CurrentPokestop)];                
         NavigationHelper.NavigationState.Remove(nameof(CurrentPokestop));
         Logger.Write($"Searching {CurrentPokestop.Id}");                
         CurrentPokestopInfo = await GameClient.GetFort(CurrentPokestop.Id, CurrentPokestop.Latitude, CurrentPokestop.Longitude);
         Busy.SetBusy(false);
         // If timeout is expired we can go to to pokestop page          
         if (CurrentPokestop.CooldownCompleteTimestampMs >= DateTime.UtcNow.ToUnixTime())
         {
             // Timeout is not expired yet, player can't get items from the fort
             SearchInCooldown?.Invoke(null, null);
         }
     }
     await Task.CompletedTask;
 }
        /// <summary>
        /// Clears all columns from the parts list, except the ones that appear in a specified collection.
        /// </summary>
        /// <param name="partsList">The <see cref="PartsList"/> instance that this extension method affects.</param>
        /// <param name="columnIdsToKeep">A dictionary of IDs of <see cref="PropertyTypeEnum.kFileProperty"/> columns
        /// that shouldn't be removed.</param>
        /// <param name="propertyTypesToKeep"></param>
        /// <exception cref="ArgumentNullException"><paramref name="partsList"/> is <c>null</c>.</exception>
        public static void ClearColumnsExcept(
            this PartsList partsList,
            IDictionary<string, int> columnIdsToKeep,
            params PropertyTypeEnum[] propertyTypesToKeep
        )
        {
            if (partsList == null)
                throw new ArgumentNullException(nameof(partsList));

            foreach (PartsListColumn column in partsList.PartsListColumns)
            {
                if (column.PropertyType == PropertyTypeEnum.kFileProperty)
                {
                    var filePropertyId = column.GetFilePropertyId();

                    if (columnIdsToKeep != null &&
                        columnIdsToKeep.Any(x => x.Key == filePropertyId.Key && x.Value == filePropertyId.Value))
                        continue;
                }
                else if (propertyTypesToKeep != null && propertyTypesToKeep.Contains(column.PropertyType))
                    continue;

                column.Remove();
            }
        }
        private Tuple<string, Encoding> ParseContentHeaders(IDictionary<string, string> headers)
        {
            string contentType = null;
            Encoding encoding = null;

            if (headers != null && headers.Any())
            {
                foreach (var header in headers)
                {
                    if (header.Key.Equals("Content-Type", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var contentTypeHeaderSplit = header.Value.Split(';');
                        contentType = contentTypeHeaderSplit.First().Trim().ToLower();

                        var encodingString = contentTypeHeaderSplit.FirstOrDefault(x => x.Contains("charset="));
                        if (!String.IsNullOrEmpty(encodingString))
                        {
                            encodingString = encodingString.Trim().Replace("charset=", "").ToLower();
                            encoding = _encodingMapper.Convert(encodingString);
                        }
                        break;
                    }
                }
            }

            return new Tuple<string, Encoding>(contentType, encoding);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="parameter">MapPokemonWrapper containing the Pokemon that we're trying to capture</param>
 /// <param name="mode"></param>
 /// <param name="suspensionState"></param>
 /// <returns></returns>
 public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode,
     IDictionary<string, object> suspensionState)
 {
     if (suspensionState.Any())
     {
         // Recovering the state
         CurrentPokemon = (MapPokemonWrapper) suspensionState[nameof(CurrentPokemon)];                
         CurrentEncounter = (EncounterResponse) suspensionState[nameof(CurrentEncounter)];
         CurrentCaptureAward = (CaptureAward) suspensionState[nameof(CurrentCaptureAward)];
         SelectedCaptureItem =  (ItemData) suspensionState[nameof(SelectedCaptureItem)];
     } else if (parameter is bool)
     {                
         // Navigating from game page, so we need to actually load the encounter                
         CurrentPokemon = (MapPokemonWrapper) NavigationHelper.NavigationState[nameof(CurrentPokemon)];
         Busy.SetBusy(true, Utils.Resources.Translation.GetString("LoadingEncounter") + Utils.Resources.Pokemon.GetString(CurrentPokemon.PokemonId.ToString()));
         NavigationHelper.NavigationState.Remove(nameof(CurrentPokemon));
         Logger.Write($"Catching {CurrentPokemon.PokemonId}");                
         CurrentEncounter = await GameClient.EncounterPokemon(CurrentPokemon.EncounterId, CurrentPokemon.SpawnpointId);
         SelectedCaptureItem = ItemsInventory.First(item => item.ItemId == ItemId.ItemPokeBall);
         Busy.SetBusy(false);
         if (CurrentEncounter.Status != EncounterResponse.Types.Status.EncounterSuccess)
         {
             // Encounter failed, probably the Pokemon ran away
             await new MessageDialog(Utils.Resources.Translation.GetString("PokemonRanAway")).ShowAsyncQueue();
             ReturnToGameScreen.Execute();
         }
     }
     await Task.CompletedTask;
 }
        public virtual bool Filter(IDictionary<string, dynamic> data)
        {
            if (!data.Any(prop => prop.Key == Key && prop.Value.ToString() == Value.Trim('\'')))
                return false;

            return true;
        }
 private string GetParameters(IDictionary<string, object> param)
 {
     var result = param.Any()
                      ? "Params: [" + string.Join(";", param.Keys.Select(key => key + ": " + param[key])) + "]"
                      : "No params";
     return result;
 }
Ejemplo n.º 13
0
        protected virtual void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)
        {
            if (!values.Any())
            {
                var cookied = new HttpCookie(TempDataCookieKey)
                {
                    Expires = DateTime.Now.AddDays(-30),
                    Path = controllerContext.HttpContext.Request.ApplicationPath,
                    Secure = controllerContext.HttpContext.Request.IsSecureConnection
                };
                _httpContext.Response.Cookies.Add(cookied);
                return;
            }
                
            var cookieValue = SerializeToBase64EncodedString(values);

            var cookie = new HttpCookie(TempDataCookieKey)
            {
                HttpOnly = true,
                Value = cookieValue,
                Path = controllerContext.HttpContext.Request.ApplicationPath,
                Secure = controllerContext.HttpContext.Request.IsSecureConnection
            };

            _httpContext.Response.Cookies.Add(cookie);
        }
Ejemplo n.º 14
0
 public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
 {
     if (suspensionState.Any())
     {
         Value = suspensionState[nameof(Value)]?.ToString();
     }
     await Task.CompletedTask;
 }
 /// <summary>
 /// Creates a new <see cref="StempelPolishStemFilterFactory"/>
 /// </summary>
 public StempelPolishStemFilterFactory(IDictionary<string, string> args)
     : base(args)
 {
     if (args.Any())
     {
         throw new ArgumentException("Unknown parameters: " + args);
     }
 }
Ejemplo n.º 16
0
 public override void OnNavigatedTo(object parameter, NavigationMode mode, IDictionary<string, object> state)
 {
     if (state.Any())
     {
         Value = state[nameof(Value)]?.ToString();
         state.Clear();
     }
 }
 private void VerifyCrosscheck(IDictionary<HgNodeID, IList<uint>> manifestLinkrevs, IDictionary<string, IList<uint>> fileLinkrevs, IDictionary<string, IDictionary<HgNodeID, uint>> fileNodeIDs)
 {
     if(manifestLinkrevs.Any())
     {
         throw new Exception("changeset refers to unknown manifest " + manifestLinkrevs.Keys.First().Short);
     }
     //throw new NotImplementedException();
 }
        public override bool Filter(IDictionary<string, dynamic> data)
        {

            if (!data.Any(prop => prop.Key == Key && Regex.IsMatch(prop.Value.ToString(), Pattern)))
                    return false;

            return true;
        }
Ejemplo n.º 19
0
 public override void OnNavigatedTo(string parameter, NavigationMode mode, IDictionary<string, object> state)
 {
     if (state.Any())
     {
         // restore
     }
     base.OnNavigatedTo(parameter, mode, state);
 }
Ejemplo n.º 20
0
Archivo: Edge.cs Proyecto: Vadi/sones
        public Edge(IVertex mySourceVertex, IEnumerable<IVertex> myTargetVertices, IDictionary<String, Object> myAttributes = null)
        {
            _SourceVertex    = mySourceVertex;
            _TargetVertices = myTargetVertices;

            if (myAttributes != null && myAttributes.Any())
                AddAttribute(myAttributes);
        }
Ejemplo n.º 21
0
Archivo: Edge.cs Proyecto: Vadi/sones
        public Edge(IVertex mySourceVertex, IVertex myTargetVertex, IDictionary<String, Object> myAttributes = null)
        {
            _SourceVertex = mySourceVertex;
            _TargetVertices = new List<IVertex> { myTargetVertex };

            if (myAttributes != null && myAttributes.Any())
                AddAttribute(myAttributes);
        }
 /// <summary>
 /// Converts the dictionary to attributes.
 /// </summary>
 /// <param name="dictionary">The dictionary.</param>
 /// <returns></returns>
 public static string ConvertDictionaryToAttributes(IDictionary<string, object> dictionary)
 {
     if (dictionary != null && dictionary.Any())
     {
         return dictionary.Aggregate(" ", (c, att) => c + String.Format("{0}=\"{1}\"", att.Key, att.Value));
     }
     return String.Empty;
 }
Ejemplo n.º 23
0
 protected void UpdateValidation() {
     var result = Validator.Validate(this);
     _errors = result.Errors.ToDictionary(x => x.PropertyName, x => x.ErrorMessage);
     _error = string.Join(Environment.NewLine, result.Errors.Select(x => x.ErrorMessage));
     // we could decide not to use this at all, thus always leave the OK/Save button enabled?
     IsValid = !_errors.Any();
     this.RaisePropertyChanged("Error"); // Needed / used?
 }
Ejemplo n.º 24
0
        public static Uri ApplyParameters(this Uri uri, IDictionary<string, string> parameters)
        {
            Ensure.ArgumentNotNull(uri, "uri");

            if (parameters == null || !parameters.Any()) return uri;

            // to prevent values being persisted across requests
            // use a temporary dictionary which combines new and existing parameters
            IDictionary<string, string> p = new Dictionary<string, string>(parameters);

            string queryString;
            if (uri.IsAbsoluteUri)
            {
                queryString = uri.Query;
            }
            else
            {
                var hasQueryString = uri.OriginalString.IndexOf("?", StringComparison.Ordinal);
                queryString = hasQueryString == -1
                    ? ""
                    : uri.OriginalString.Substring(hasQueryString);
            }

            var values = queryString.Replace("?", "")
                .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);

            var existingParameters = values.ToDictionary(
                key => key.Substring(0, key.IndexOf('=')),
                value => value.Substring(value.IndexOf('=') + 1));

            foreach (var existing in existingParameters)
            {
                if (!p.ContainsKey(existing.Key))
                {
                    p.Add(existing);
                }
            }

            Func<string, string, string> mapValueFunc = (key, value) =>
            {
                if (key == "q") return value;
                return Uri.EscapeDataString(value);
            };

            string query = String.Join("&", p.Select(kvp => kvp.Key + "=" + mapValueFunc(kvp.Key, kvp.Value)));
            if (uri.IsAbsoluteUri)
            {
                var uriBuilder = new UriBuilder(uri)
                {
                    Query = query
                };
                return uriBuilder.Uri;
            }

            return new Uri(uri + "?" + query, UriKind.Relative);
        }
Ejemplo n.º 25
0
 public static string WrapWithTag(this string content, string tag, IDictionary<string, string> attributes = null)
 {
     var headingTag = tag;
     if (attributes != null && attributes.Any())
     {
         headingTag += " " + string.Join(" ",
             attributes.Select(a => $"{a.Key}=" + a.Value.WrapWithQuotes()));
     }
     return $"<{headingTag}>{content}</{tag}>";
 }
 public static void AddAttributes(this HtmlTextWriter writer, IDictionary<string, object> attributes)
 {
   if (attributes!=null && attributes.Any())
   {
     foreach (KeyValuePair<string, object> attribute in attributes)
     {
       writer.AddAttribute(attribute.Key, attribute.Value.ToString(), true);
     }
   }
 }
        public EntityObjectDataLoaderFactory(IDictionary<string, string> bindings)
        {
            if (bindings == null)
                throw new ArgumentNullException("bindings");

            if (!bindings.Any())
                throw new ArgumentException("Parameter bindings cannot be empty", "bindings");

            _bindings = bindings;
        }
Ejemplo n.º 28
0
 public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode,
     IDictionary<string, object> suspensionState)
 {
     if (suspensionState.Any())
     {
         // Restoring from suspend means that we need to initialize the game again
         await InitGame(true);
     }
     await Task.CompletedTask;
 }
Ejemplo n.º 29
0
 public override void OnNavigatedTo(object parameter, NavigationMode mode, IDictionary<string, object> state)
 {
     if (state.Any())
     {
         // use cache value(s)
         if (state.ContainsKey(nameof(Value))) Value = state[nameof(Value)]?.ToString();
         // clear any cache
         state.Clear();
     }
 }
 public static void AddAttributes(this HtmlTextWriter writer, IDictionary<string, object> attributes)
 {
     if (attributes.Any<KeyValuePair<string, object>>())
     {
         foreach (var pair in attributes)
         {
             if (pair.Value != null)
                 writer.AddAttribute(pair.Key, pair.Value.ToString(), true);
         }
     }
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Merge a dictionary of values with an existing <see cref="Uri"/>
        /// </summary>
        /// <param name="uri">Original request Uri</param>
        /// <param name="parameters">Collection of key-value pairs</param>
        /// <returns>Updated request Uri</returns>
        public static Uri ApplyParameters(this Uri uri, IDictionary <string, string> parameters)
        {
            Ensure.ArgumentNotNull(uri, nameof(uri));

            if (parameters == null || !parameters.Any())
            {
                return(uri);
            }

            // to prevent values being persisted across requests
            // use a temporary dictionary which combines new and existing parameters
            IDictionary <string, string> p = new Dictionary <string, string>(parameters);

            var hasQueryString = uri.OriginalString.IndexOf("?", StringComparison.Ordinal);

            string uriWithoutQuery = hasQueryString == -1
                    ? uri.ToString()
                    : uri.OriginalString.Substring(0, hasQueryString);

            string queryString;

            if (uri.IsAbsoluteUri)
            {
                queryString = uri.Query;
            }
            else
            {
                queryString = hasQueryString == -1
                    ? string.Empty
                    : uri.OriginalString.Substring(hasQueryString);
            }

            var values = queryString.Replace("?", string.Empty)
                         .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);

            var existingParameters = values.ToDictionary(
                key => key.Substring(0, key.IndexOf('=')),
                value => value.Substring(value.IndexOf('=') + 1));

            foreach (var existing in existingParameters)
            {
                if (!p.ContainsKey(existing.Key))
                {
                    p.Add(new KeyValuePair <string, string>(existing.Key, Uri.UnescapeDataString(existing.Value)));
                }
            }

            Func <string, string, string> mapValueFunc = (key, value) => key == "q" ? value : Uri.EscapeDataString(value);

            string query = string.Join("&", p.Select(kvp => kvp.Key + "=" + mapValueFunc(kvp.Key, kvp.Value)));

            if (uri.IsAbsoluteUri)
            {
                var uriBuilder = new UriBuilder(uri)
                {
                    Query = query
                };
                return(uriBuilder.Uri);
            }

            return(new Uri(uriWithoutQuery + "?" + query, UriKind.Relative));
        }
Ejemplo n.º 32
0
        public virtual int SaveThemeVariables(string themeName, int storeId, IDictionary <string, object> variables)
        {
            Guard.ArgumentNotEmpty(themeName, "themeName");
            Guard.Against <ArgumentException>(!_themeRegistry.ThemeManifestExists(themeName), "The theme '{0}' does not exist in the registry.".FormatInvariant(themeName));
            Guard.ArgumentNotNull(variables, "variables");

            if (!variables.Any())
            {
                return(0);
            }

            var count = 0;
            var infos = _themeRegistry.GetThemeManifest(themeName).Variables;

            using (var scope = new DbContextScope(ctx: _rsVariables.Context, autoCommit: false))
            {
                var  unsavedVars    = new List <string>();
                var  savedThemeVars = _rsVariables.Table.Where(v => v.StoreId == storeId && v.Theme.Equals(themeName, StringComparison.OrdinalIgnoreCase)).ToList();
                bool touched        = false;

                foreach (var v in variables)
                {
                    ThemeVariableInfo info;
                    if (!infos.TryGetValue(v.Key, out info))
                    {
                        // var not specified in metadata so don't save
                        // TODO: (MC) delete from db also if it exists
                        continue;
                    }

                    var value = v.Value == null ? string.Empty : v.Value.ToString();

                    var savedThemeVar = savedThemeVars.FirstOrDefault(x => x.Name == v.Key);
                    if (savedThemeVar != null)
                    {
                        if (value.IsEmpty() || String.Equals(info.DefaultValue, value, StringComparison.CurrentCultureIgnoreCase))
                        {
                            // it's either null or the default value, so delete
                            _rsVariables.Delete(savedThemeVar);
                            _eventPublisher.EntityDeleted(savedThemeVar);
                            touched = true;
                            count++;
                        }
                        else
                        {
                            // update entity
                            if (!savedThemeVar.Value.Equals(value, StringComparison.OrdinalIgnoreCase))
                            {
                                savedThemeVar.Value = value;
                                _eventPublisher.EntityUpdated(savedThemeVar);
                                touched = true;
                                count++;
                            }
                        }
                    }
                    else
                    {
                        if (value.HasValue() && !String.Equals(info.DefaultValue, value, StringComparison.CurrentCultureIgnoreCase))
                        {
                            // insert entity (only when not default value)
                            unsavedVars.Add(v.Key);
                            savedThemeVar = new ThemeVariable
                            {
                                Theme   = themeName,
                                Name    = v.Key,
                                Value   = value,
                                StoreId = storeId
                            };
                            _rsVariables.Insert(savedThemeVar);
                            _eventPublisher.EntityInserted(savedThemeVar);
                            touched = true;
                            count++;
                        }
                    }
                }

                if (touched)
                {
                    _rsVariables.Context.SaveChanges();
                }
            }

            return(count);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="mode"></param>
        /// <param name="suspensionState"></param>
        /// <returns></returns>
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode,
                                                      IDictionary <string, object> suspensionState)
        {
            GameClient.OnAppliedItemExpired += GameClient_OnAppliedItemExpired;
            GameClient.OnAppliedItemStarted += GameClient_OnAppliedItemStarted;

            // Prevent from going back to other pages
            NavigationService.ClearHistory();
            if (parameter == null || mode == NavigationMode.Back)
            {
                return;
            }
            var gameMapNavigationMode = (GameMapNavigationModes)parameter;

            AudioUtils.PlaySound(AudioUtils.GAMEPLAY);

            // We just resumed from suspension so we restart update service and we get data from suspension state
            if (suspensionState.Any())
            {
                // Recovering the state
                PlayerProfile = new PlayerData();
                PlayerStats   = new PlayerStats();
                PlayerProfile.MergeFrom(ByteString.FromBase64((string)suspensionState[nameof(PlayerProfile)]).CreateCodedInput());
                PlayerStats.MergeFrom(ByteString.FromBase64((string)suspensionState[nameof(PlayerStats)]).CreateCodedInput());
                RaisePropertyChanged(() => PlayerProfile);
                RaisePropertyChanged(() => PlayerStats);
                // Restarting update service
                await GameClient.InitializeClient();
                await StartGpsDataService();

                GameClient.ToggleUpdateTimer();
                return;
            }

            // Let's do the proper action
            switch (gameMapNavigationMode)
            {
            case GameMapNavigationModes.AppStart:
                // App just started, so we get GPS access and eventually initialize the client
                await StartGpsDataService();
                await UpdatePlayerData(true);

                GameClient.ToggleUpdateTimer();
                break;

            case GameMapNavigationModes.SettingsUpdate:
                // We navigated back from Settings page after changing the Map provider, but this is managed in the page itself
                break;

            case GameMapNavigationModes.PokestopUpdate:
                // We came here after the catching page so we need to restart map update timer and update player data. We also check for level up.
                GameClient.ToggleUpdateTimer();
                await UpdatePlayerData(true);

                break;

            case GameMapNavigationModes.PokemonUpdate:
                // As above
                GameClient.ToggleUpdateTimer();
                await UpdatePlayerData(true);

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
 public bool HasMatch(string textKey)
 {
     return(_regexDictionary.Any(r => r.Key.IsMatch(textKey)));
 }
Ejemplo n.º 35
0
        public CommandResponse ParseCommand()
        {
            var message = new StringBuilder();

            if (string.IsNullOrWhiteSpace(_resource))
            {
                return CommandResponse.Set(false, $"The Resource OPTION is missing. All requests require a Resource type to be specified.");
            }

            message.AppendLine("Resource: " + _resource);
            message.AppendLine("Format: " + _format);

            if (_headers == null || !_headers.Any())
            {
                return CommandResponse.Set(false, $"All requests requires the setheaders option.");
            }

            if (!ValidMethods.Contains(_method))
            {
                return CommandResponse.Set(false, $"The Method {_method} is invalid.");
            }

            if (_method == "get" || _method == "delete" || _method == "put")
            {
                if (_parameters == null || !_parameters.Any())
                {
                    return CommandResponse.Set(false, $"The Parameters OPTION is missing or invalid. The GET, PUT and DELETE method requires parameters.");
                }

                message.AppendLine("Parameters: " + _parameters);
            }

            if ((_method == "put" || _method == "post"))
            {
                if (!string.IsNullOrWhiteSpace(_body))
                {
                    try
                    {
                        _pointerBody = JsonConvert.DeserializeObject<NrlsPointerBody>(_body);
                    }
                    catch(Exception ex)
                    {
                        return CommandResponse.Set(false, $"The Body OPTION is invalid. Exception Message: {ex.Message}");
                    }

                }
                else if (!string.IsNullOrWhiteSpace(_input))
                {
                    var inputLocation = GetInputLocation();

                    if (inputLocation == null)
                    {
                        return CommandResponse.Set(false, $"The Input OPTION is invalid. See --help for more details.");
                    }
                    else
                    {
                        if (!inputLocation.Success)
                        {
                            return inputLocation;
                        }

                        try
                        {
                            var jsonParser = new FhirJsonParser();
                            var pointer = File.ReadAllText(inputLocation.Result);
                            _pointer = jsonParser.Parse<DocumentReference>(pointer);
                        }
                        catch(Exception ex)
                        {
                            return CommandResponse.Set(false, $"Error trying to parse input. Exception Message: {ex.Message}");
                        }
                        
                       
                    }
                }
                else
                {
                    return CommandResponse.Set(false, $"Both the Body OPTION and the Input OPTION are missing. PUT and POST methods require at least one.");
                }
            }

            ////not for beta
            //if (_method == "put")
            //{
            //    //its now a parameter
            //    if (string.IsNullOrWhiteSpace(_uniqueId))
            //    {
            //        return CommandResponse.Set(false, $"The id OPTION is missing. PUT methods require a id.");
            //    }

            //    message.AppendLine("id: " + _uniqueId);
            //}

            return CommandResponse.Set(true, message.ToString());
        }
Ejemplo n.º 36
0
 public static Boolean HasSpellById(int spellId)
 {
     return(Spells.Any(spell => spell.Value.SpellId.Equals(spellId)));
 }
        public async Task <IActionResult> PostSignaturesAsync([FromQuery] string uniqueId, [FromQuery] long roundId, [FromBody] IDictionary <int, string> signatures)
        {
            if (roundId <= 0 ||
                signatures == null ||
                !signatures.Any() ||
                signatures.Any(x => x.Key < 0 || string.IsNullOrWhiteSpace(x.Value)) ||
                !ModelState.IsValid)
            {
                return(BadRequest());
            }

            (CcjRound round, Alice alice) = GetRunningRoundAndAliceOrFailureResponse(roundId, uniqueId, out IActionResult returnFailureResponse);
            if (returnFailureResponse != null)
            {
                return(returnFailureResponse);
            }

            // Check if Alice provided signature to all her inputs.
            if (signatures.Count != alice.Inputs.Count())
            {
                return(BadRequest("Alice did not provide enough witnesses."));
            }

            CcjRoundPhase phase = round.Phase;

            switch (phase)
            {
            case CcjRoundPhase.Signing:
            {
                using (await SigningLock.LockAsync())
                {
                    foreach (var signaturePair in signatures)
                    {
                        int       index   = signaturePair.Key;
                        WitScript witness = null;
                        try
                        {
                            witness = new WitScript(signaturePair.Value);
                        }
                        catch (Exception ex)
                        {
                            return(BadRequest($"Malformed witness is provided. Details: {ex.Message}"));
                        }
                        int maxIndex = round.UnsignedCoinJoin.Inputs.Count - 1;
                        if (maxIndex < index)
                        {
                            return(BadRequest($"Index out of range. Maximum value: {maxIndex}. Provided value: {index}"));
                        }

                        // Check duplicates.
                        if (round.SignedCoinJoin.Inputs[index].HasWitness())
                        {
                            return(BadRequest($"Input is already signed."));
                        }

                        // Verify witness.
                        var cjCopy = Transaction.Parse(round.UnsignedCoinJoin.ToHex(), Network);
                        cjCopy.Inputs[index].WitScript = witness;
                        TxOut output = alice.Inputs.Single(x => x.OutPoint == cjCopy.Inputs[index].PrevOut).Output;
                        if (!Script.VerifyScript(output.ScriptPubKey, cjCopy, index, output.Value, ScriptVerify.Standard, SigHash.All))
                        {
                            return(BadRequest($"Invalid witness is provided."));
                        }

                        // Finally add it to our CJ.
                        round.SignedCoinJoin.Inputs[index].WitScript = witness;
                    }

                    alice.State = AliceState.SignedCoinJoin;

                    await round.BroadcastCoinJoinIfFullySignedAsync();
                }

                return(NoContent());
            }

            default:
            {
                return(Conflict($"CoinJoin can only be requested from Signing phase. Current phase: {phase}."));
            }
            }
        }
Ejemplo n.º 38
0
        static void Main(string[] args)
        {
            Console.WriteLine(@" ——————————————————————————————————————————————————————————————");
            Console.WriteLine(@" Availables structures");
            Console.WriteLine(@" ——————————————————————————————————————————————————————————————");
            DmiStructureCollection structures = DMI.Instance.Structures;

            foreach (DmiStructure structure in structures)
            {
                Console.WriteLine($@" {(int)structure.Class:D3}-{structure.FriendlyClassName}");
            }

            foreach (DmiStructure structure in structures)
            {
                Console.WriteLine();
                Console.WriteLine(@" ——————————————————————————————————————————————————————————————");
                Console.WriteLine($@" {(int)structure.Class:D3}-{structure.FriendlyClassName} structure detail");
                Console.WriteLine(@" ——————————————————————————————————————————————————————————————");
                DmiClassCollection elements = structure.Elements;
                foreach (DmiClass element in elements)
                {
                    DmiClassPropertiesTable elementProperties = element.Properties;
                    foreach (KeyValuePair <IPropertyKey, object> property in elementProperties)
                    {
                        object value = property.Value;

                        IPropertyKey key          = property.Key;
                        string       friendlyName = GetFriendlyName(key);
                        PropertyUnit valueUnit    = key.PropertyUnit;
                        string       unit         =
                            valueUnit == PropertyUnit.None
                                ? string.Empty
                                : valueUnit.ToString();

                        if (value == null)
                        {
                            Console.WriteLine($@" > {friendlyName} > NULL");
                            continue;
                        }

                        if (value is string)
                        {
                            Console.WriteLine($@" > {friendlyName} > {value} {unit}");
                        }
                        else if (value is byte)
                        {
                            Console.WriteLine($@" > {friendlyName} > {value} {unit} [{value:X2}h]");
                        }
                        else if (value is short)
                        {
                            Console.WriteLine($@" > {friendlyName} > {value} {unit} [{value:X4}h]");
                        }
                        else if (value is ushort)
                        {
                            Console.WriteLine($@" > {friendlyName} > {value} {unit} [{value:X4}h]");
                        }
                        else if (value is int)
                        {
                            Console.WriteLine($@" > {friendlyName} > {value} {unit} [{value:X4}h]");
                        }
                        else if (value is uint)
                        {
                            Console.WriteLine($@" > {friendlyName} > {value} {unit} [{value:X4}h]");
                        }
                        else if (value is long)
                        {
                            Console.WriteLine($@" > {friendlyName} > {value} {unit} [{value:X8}h]");
                        }
                        else if (value is ulong)
                        {
                            Console.WriteLine($@" > {friendlyName} > {value} {unit} [{value:X8}h]");
                        }
                        else if (value.GetType() == typeof(ReadOnlyCollection <byte>))
                        {
                            Console.WriteLine($@" > {friendlyName} > {string.Join(", ", (ReadOnlyCollection<byte>)value)}");
                        }
                        else if (value.GetType() == typeof(DmiGroupAssociationElementCollection))
                        {
                            // prints elements
                        }
                        else if (value.GetType() == typeof(ReadOnlyCollection <string>))
                        {
                            Console.WriteLine($@" > {friendlyName}");
                            var collection = (ReadOnlyCollection <string>)value;
                            foreach (var entry in collection)
                            {
                                Console.WriteLine($@"   > {entry} {unit}");
                            }
                        }
                        else
                        {
                            Console.WriteLine($@" > {friendlyName} > {value} {unit}");
                        }
                    }
                }
            }

            Console.WriteLine();
            Console.WriteLine(@" ——————————————————————————————————————————————————————————————");
            Console.WriteLine(@" Gets a single property directly");
            Console.WriteLine(@" ——————————————————————————————————————————————————————————————");

            object biosVersion = structures.GetProperty(DmiProperty.Bios.BiosVersion);

            if (biosVersion != null)
            {
                Console.WriteLine($@" > BIOS Version > {biosVersion}");
            }

            string biosVendor = structures.GetProperty <string>(DmiProperty.Bios.Vendor);

            Console.WriteLine($@" > BIOS Vendor > {biosVendor}");

            int currentSpeed = structures.GetProperty <int>(DmiProperty.Processor.CurrentSpeed);

            Console.WriteLine($@" > Current Speed > {currentSpeed:N0} {DmiProperty.Processor.CurrentSpeed.PropertyUnit}");

            string processorManufacturer = structures.GetProperty <string>(DmiProperty.Processor.ProcessorManufacturer);

            Console.WriteLine($@" > Processor Manufacturer > {processorManufacturer}");

            Console.WriteLine();
            Console.WriteLine(@" ——————————————————————————————————————————————————————————————");
            Console.WriteLine(@" Gets a multiple properties directly");
            Console.WriteLine(@" ——————————————————————————————————————————————————————————————");
            IDictionary <int, object> systemSlots = structures.GetProperties(DmiProperty.SystemSlots.SlotId);
            bool hasSystemSlots = systemSlots.Any();

            if (!hasSystemSlots)
            {
                Console.WriteLine($@" > There is no system slots information structure in this computer");
            }
            else
            {
                foreach (KeyValuePair <int, object> systemSlot in systemSlots)
                {
                    int element  = systemSlot.Key;
                    var property = ((IEnumerable <KeyValuePair <IPropertyKey, object> >)systemSlot.Value).FirstOrDefault();
                    Console.WriteLine($@" > System Slot ({element}) > {property.Value}");
                }
            }

            Console.ReadLine();
        }
Ejemplo n.º 39
0
        private async Task WriteResultsToSql(
            DateTime utcNow,
            string connectionString,
            string tableName,
            string session,
            string description,
            string aspnetCoreVersion,
            string runtimeVersion,
            string scenario,
            Hardware hardware,
            string hardwareVersion,
            Benchmarks.ServerJob.OperatingSystem operatingSystem,
            Scheme scheme,
            Source source,
            string connectionFilter,
            WebHost webHost,
            int?kestrelThreadCount,
            int clientThreads,
            int connections,
            int duration,
            int?pipelineDepth,
            string path,
            string method,
            IDictionary <string, string> headers,
            string dimension,
            double value,
            bool runtimeStore)
        {
            string insertCmd =
                @"
                INSERT INTO [dbo].[" + tableName + @"]
                           ([DateTime]
                           ,[Session]
                           ,[Description]
                           ,[AspNetCoreVersion]
                           ,[RuntimeVersion]
                           ,[Scenario]
                           ,[Hardware]
                           ,[HardwareVersion]
                           ,[OperatingSystem]
                           ,[Framework]
                           ,[RuntimeStore]
                           ,[Scheme]
                           ,[ConnectionFilter]
                           ,[WebHost]
                           ,[KestrelThreadCount]
                           ,[ClientThreads]
                           ,[Connections]
                           ,[Duration]
                           ,[PipelineDepth]
                           ,[Path]
                           ,[Method]
                           ,[Headers]
                           ,[Dimension]
                           ,[Value])
                     VALUES
                           (@DateTime
                           ,@Session
                           ,@Description
                           ,@AspNetCoreVersion
                           ,@RuntimeVersion
                           ,@Scenario
                           ,@Hardware
                           ,@HardwareVersion
                           ,@OperatingSystem
                           ,@Framework
                           ,@RuntimeStore
                           ,@Scheme
                           ,@ConnectionFilter
                           ,@WebHost
                           ,@KestrelThreadCount
                           ,@ClientThreads
                           ,@Connections
                           ,@Duration
                           ,@PipelineDepth
                           ,@Path
                           ,@Method
                           ,@Headers
                           ,@Dimension
                           ,@Value)
                ";

            using (var connection = new SqlConnection(connectionString))
            {
                await connection.OpenAsync();

                var transaction = connection.BeginTransaction();

                try
                {
                    var command = new SqlCommand(insertCmd, connection, transaction);
                    var p       = command.Parameters;
                    p.AddWithValue("@DateTime", utcNow);
                    p.AddWithValue("@Session", session);
                    p.AddWithValue("@Description", description);
                    p.AddWithValue("@AspNetCoreVersion", aspnetCoreVersion);
                    p.AddWithValue("@RuntimeVersion", runtimeVersion);
                    p.AddWithValue("@Scenario", scenario.ToString());
                    p.AddWithValue("@Hardware", hardware.ToString());
                    p.AddWithValue("@HardwareVersion", hardwareVersion);
                    p.AddWithValue("@OperatingSystem", operatingSystem.ToString());
                    p.AddWithValue("@Framework", "Core");
                    p.AddWithValue("@RuntimeStore", runtimeStore);
                    p.AddWithValue("@Scheme", scheme.ToString().ToLowerInvariant());
                    p.AddWithValue("@ConnectionFilter",
                                   string.IsNullOrEmpty(connectionFilter) ? (object)DBNull.Value : connectionFilter);
                    p.AddWithValue("@WebHost", webHost.ToString());
                    p.AddWithValue("@KestrelThreadCount", (object)kestrelThreadCount ?? DBNull.Value);
                    p.AddWithValue("@ClientThreads", clientThreads);
                    p.AddWithValue("@Connections", connections);
                    p.AddWithValue("@Duration", duration);
                    p.AddWithValue("@PipelineDepth", (object)pipelineDepth ?? DBNull.Value);
                    p.AddWithValue("@Path", string.IsNullOrEmpty(path) ? (object)DBNull.Value : path);
                    p.AddWithValue("@Method", method.ToString().ToUpperInvariant());
                    p.AddWithValue("@Headers", headers.Any() ? JsonConvert.SerializeObject(headers) : (object)DBNull.Value);
                    p.AddWithValue("@Dimension", dimension);
                    p.AddWithValue("@Value", value);

                    await command.ExecuteNonQueryAsync();

                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
                finally
                {
                    transaction.Dispose();
                }
            }
        }
Ejemplo n.º 40
0
 bool IsSensitive(IDictionary <string, string> displaySettings)
 {
     return(displaySettings.Any(x => x.Key == ControlType.ControlTypeKey && x.Value == ControlType.Sensitive));
 }
Ejemplo n.º 41
0
        /// <summary>
        ///     Creates javascript string from column to be included in grid javascript
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            var script = new StringBuilder();

            // Start column
            script.Append("{").AppendLine();

            // Align
            if (_align.HasValue)
            {
                script.AppendFormat("align:'{0}',", _align.ToString().ToLower()).AppendLine();
            }

            // Classes
            if (_classes.Count > 0)
            {
                script.AppendFormat("classes:'{0}',", string.Join(" ", (from c in _classes select c).ToArray())).
                AppendLine();
            }

            // Columnname
            script.AppendFormat("name:'{0}',", _columnName).AppendLine();

            // FirstSortOrder
            if (_firstSortOrder.HasValue)
            {
                script.AppendFormat("firstsortorder:'{0}',", _firstSortOrder.ToString().ToLower()).AppendLine();
            }

            // FixedWidth
            if (_fixedWidth.HasValue)
            {
                script.AppendFormat("fixed:{0},", _fixedWidth.Value.ToString().ToLower()).AppendLine();
            }

            // Formatters
            if (_formatter.HasValue && _formatter.Value.Value.IsNullOrWhiteSpace())
            {
                script.AppendFormat("formatter:'{0}',", _formatter.Value.Key.ToString().ToLower()).AppendLine();
            }

            if (_formatter.HasValue && !_formatter.Value.Value.IsNullOrWhiteSpace())
            {
                script.AppendLine("formatter:'" + _formatter.Value.Key.ToString().ToLower() + "', formatoptions: {" + _formatter.Value.Value + "},");
            }

            // Custom formatter
            if (!_customFormatter.IsNullOrWhiteSpace())
            {
                script.AppendFormat("formatter:{0},", _customFormatter).AppendLine();
            }

            // Hidden
            if (_hidden.HasValue)
            {
                script.AppendFormat("hidden:{0},", _hidden.Value.ToString().ToLower()).AppendLine();
            }

            // Key
            if (_key.HasValue)
            {
                script.AppendFormat("key:{0},", _key.Value.ToString().ToLower()).AppendLine();
            }

            // Label
            if (!_label.IsNullOrWhiteSpace())
            {
                script.AppendFormat("label:'{0}',", _label).AppendLine();
            }

            // Resizable
            if (_resizeable.HasValue)
            {
                script.AppendFormat("resizable:{0},", _resizeable.Value.ToString().ToLower()).AppendLine();
            }

            // Search
            if (_search.HasValue)
            {
                script.AppendFormat("search:{0},", _search.Value.ToString().ToLower()).AppendLine();
            }


            // Sortable
            if (_sortable.HasValue)
            {
                script.AppendFormat("sortable:{0},", _sortable.Value.ToString().ToLower()).AppendLine();
            }

            // Title
            if (_title.HasValue)
            {
                script.AppendFormat("title:{0},", _title.Value.ToString().ToLower()).AppendLine();
            }

            // Width
            if (_width.HasValue)
            {
                script.AppendFormat("width:{0},", _width.Value).AppendLine();
            }

            // Editable
            if (_editable.HasValue)
            {
                script.AppendFormat("editable:{0},", _editable.Value.ToString().ToLower()).AppendLine();
            }

            // Setup search options
            var searchOptions = new Dictionary <string, string>();

            // SearchType
            if (_searchType.HasValue)
            {
                if (_searchType.Value == Searchtype.Text)
                {
                    script.AppendLine("stype:'text',");
                }

                if (_searchType.Value == Searchtype.Select)
                {
                    script.AppendLine("stype:'select',");
                }

                if (_searchOptions.Any())
                {
                    searchOptions.Add("sopt", string.Format("['{0}']", _searchOptions.Aggregate((current, next) => current + "',  '" + next)));
                }
                else
                {
                    searchOptions.Add("sopt", "['bw']");
                }
            }

            // Searchoptions
            if (_searchType == Searchtype.Select || _searchType == Searchtype.Datepicker)
            {
                // SearchType select
                if (_searchType == Searchtype.Select)
                {
                    if (_searchTerms != null)
                    {
                        var emtpyOption = (_searchTerms.Any()) ? ":;" : ":";
                        searchOptions.Add("value", "\"" + string.Format("{0}{1}", emtpyOption, string.Join(";", _searchTerms.Select(s => s.Key + ":" + s.Value).ToArray())) + "\"");
                    }
                    else
                    {
                        searchOptions.Add("value", "':'");
                    }
                }

                // SearchType datepicker
                if (_searchType == Searchtype.Datepicker)
                {
                    if (_searchDateFormat.IsNullOrWhiteSpace())
                    {
                        searchOptions.Add("dataInit", "function(el){$(el).datepicker({changeYear:true, onSelect: function() {var sgrid = $('###gridid##')[0]; sgrid.triggerToolbar();},dateFormat:'dd-mm-yy'});}");
                    }
                    else
                    {
                        searchOptions.Add("dataInit", "function(el){$(el).datepicker({changeYear:true, onSelect: function() {var sgrid = $('###gridid##')[0]; sgrid.triggerToolbar();},dateFormat:'" + _searchDateFormat + "'});}");
                    }
                }
            }

            // SearchType
            if (_searchType.HasValue && !_defaultSearchValue.IsNullOrWhiteSpace())
            {
                searchOptions.Add("defaultValue", "'" + _defaultSearchValue + "'");
            }

            // Default value when no search type is set
            if ((!_searchType.HasValue && !_defaultSearchValue.IsNullOrWhiteSpace()))
            {
                searchOptions.Add("defaultValue", "'" + _defaultSearchValue + "'");
            }

            // Clear search
            if (_clearSearch.HasValue)
            {
                searchOptions.Add("clearSearch", _clearSearch.Value.ToString().ToLower());
            }

            // Search Option: sopt
            if (_searchOptions.Any() && !_searchType.HasValue) // When searchtype is set, searchoptions is already added
            {
                searchOptions.Add("sopt", "['" + _searchOptions.Aggregate((current, next) => current + "', '" + next) + "']");
            }

            if (searchOptions.Any())
            {
                script.AppendLine("searchoptions: { " + string.Join(", ", searchOptions.Select(x => x.Key + ":" + x.Value)) + " },");
            }

            //edit type
            if (_editType.HasValue)
            {
                script.AppendFormat("edittype:'{0}',", _editType.Value.ToString().ToLower()).AppendLine();
            }

            //edit options
            if (_editOptions != null)
            {
                script.AppendFormat("editoptions:{0},", _editOptions.ToString()).AppendLine();
            }

            //edit rules
            if (_editRules != null)
            {
                script.AppendFormat("editrules:{0},", _editRules.ToString()).AppendLine();
            }

            //edit form options
            if (_editFormOptions != null)
            {
                script.AppendFormat("formoptions:{0},", _editFormOptions.ToString()).AppendLine();
            }

            if (_sortType.HasValue)
            {
                script.AppendFormat("sorttype:'{0}',", _sortType.ToString().ToLower()).AppendLine();
            }

            // Index
            script.AppendFormat("index:'{0}'", _index).AppendLine();

            // End column
            script.Append("}");

            return(script.ToString());
        }
Ejemplo n.º 42
0
 /// <summary>
 /// Indicates whether the current entity is dirty.
 /// </summary>
 /// <returns>True if entity is dirty, otherwise False</returns>
 public bool IsDirty()
 {
     return(_propertyChangedInfo.Any());
 }
        public async Task <bool> ContainsAsync(Expression <Func <T, bool> > filterExpression)
        {
            Func <T, bool> predicate = filterExpression.Compile();

            return(_items.Any(kvp => predicate(kvp.Value)));
        }
 private XElement?CreatePropertyGroup(IDictionary <string, string?> values)
 {
     return(values.Any()
                ? new XElement(Constants.PropertyGroup, values.Select(z => new XElement(z.Key, z.Value)))
                : null);
 }
Ejemplo n.º 45
0
        //
        // クラスメソッド
        //

        /// <summary>
        /// インスタンスを生成する
        /// </summary>
        /// <param name="fileName">ファイル名(パスなし)</param>
        /// <param name="scenarioSetAsYaml">シナリオセットのYAML表現</param>
        /// <returns>生成インスタンス</returns>
        internal static UseCaseScenarioSet CreateInstance(string fileName, IDictionary <object, object> scenarioSetAsYaml)
        {
            Contract.Requires(scenarioSetAsYaml != null && scenarioSetAsYaml.Any());
            Contract.Ensures(Contract.Result <UseCaseScenarioSet>() != null);

            var title     = string.Empty;
            var summary   = string.Empty;
            var mainActor = string.Empty;
            var subActors = new List <string>();
            IEnumerable <UseCaseScenario> scenarios = null;
            var updateHistory = new List <UseCaseUpdateInfo>();
            var metadata      = new Dictionary <string, object>();

            foreach (var pair in scenarioSetAsYaml)
            {
                var key = pair.Key as string;
                switch (key)
                {
                case "シナリオセット":
                    title = pair.Value as string;
                    break;

                case "説明":
                    summary = pair.Value as string;
                    break;

                case "主アクター":
                    mainActor = pair.Value as string;
                    break;

                case "副アクター":
                    if (pair.Value is string)
                    {
                        subActors.Add(pair.Value as string);
                    }
                    else
                    {
                        subActors.AddRange((pair.Value as IEnumerable <object>).Select(value => value.ToString()));
                    }
                    break;

                case "シナリオ":
                    scenarios = (pair.Value as IEnumerable <object>).Select(scenarioAsYaml => UseCaseScenario.CreateInstance((scenarioAsYaml as ValueOverwriteDisallowDictionary <object, object>).AsDictionary));
                    break;

                case "更新履歴":
                    updateHistory.AddRange(((pair.Value as ValueOverwriteDisallowDictionary <object, object>).AsDictionary).Select(history => UseCaseUpdateInfo.CreateInstance(history)));
                    break;

                default:
                    metadata.Add(key, pair.Value);
                    break;
                }
            }

            return(new UseCaseScenarioSet {
                FileName = fileName,
                Title = title,
                Summary = summary,
                MainActor = mainActor,
                SubActors = subActors,
                Scenarios = scenarios.ToList().AsReadOnly(),
                UpdateHistory = updateHistory.ToList().AsReadOnly(),
                metadata = new ReadOnlyDictionary <string, object>(metadata),
            });
        }
Ejemplo n.º 46
0
 public bool OpcodeExists(uint opcode) => opcodes.Any(x => x.Value == opcode);
        public static string ProcessTemplateSubstitions(IToolLogger logger, string templateBody, IDictionary <string, string> substitutions, string workingDirectory)
        {
            if (DetermineTemplateFormat(templateBody) != TemplateFormat.Json || substitutions == null || !substitutions.Any())
            {
                return(templateBody);
            }

            logger?.WriteLine($"Processing {substitutions.Count} substitutions.");
            var root = JsonConvert.DeserializeObject(templateBody) as JObject;

            foreach (var kvp in substitutions)
            {
                logger?.WriteLine($"Processing substitution: {kvp.Key}");
                var token = root.SelectToken(kvp.Key);
                if (token == null)
                {
                    throw new LambdaToolsException($"Failed to locate JSONPath {kvp.Key} for template substitution.", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError);
                }

                logger?.WriteLine($"\tFound element of type {token.Type}");

                string replacementValue;
                if (workingDirectory != null && File.Exists(Path.Combine(workingDirectory, kvp.Value)))
                {
                    var path = Path.Combine(workingDirectory, kvp.Value);
                    logger?.WriteLine($"\tReading: {path}");
                    replacementValue = File.ReadAllText(path);
                }
                else
                {
                    replacementValue = kvp.Value;
                }

                try
                {
                    switch (token.Type)
                    {
                    case JTokenType.String:
                        ((JValue)token).Value = replacementValue;
                        break;

                    case JTokenType.Boolean:
                        bool b;
                        if (bool.TryParse(replacementValue, out b))
                        {
                            ((JValue)token).Value = b;
                        }
                        else
                        {
                            throw new LambdaToolsException($"Failed to convert {replacementValue} to a bool", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError);
                        }

                        break;

                    case JTokenType.Integer:
                        int i;
                        if (int.TryParse(replacementValue, out i))
                        {
                            ((JValue)token).Value = i;
                        }
                        else
                        {
                            throw new LambdaToolsException($"Failed to convert {replacementValue} to an int", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError);
                        }
                        break;

                    case JTokenType.Float:
                        double d;
                        if (double.TryParse(replacementValue, out d))
                        {
                            ((JValue)token).Value = d;
                        }
                        else
                        {
                            throw new LambdaToolsException($"Failed to convert {replacementValue} to a double", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError);
                        }
                        break;

                    case JTokenType.Array:
                    case JTokenType.Object:
                        var    jcon  = token as JContainer;
                        var    jprop = jcon.Parent as JProperty;
                        JToken subData;
                        try
                        {
                            subData = JsonConvert.DeserializeObject(replacementValue) as JToken;
                        }
                        catch (Exception e)
                        {
                            throw new LambdaToolsException($"Failed to parse substitue JSON data: {e.Message}", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError);
                        }
                        jprop.Value = subData;
                        break;

                    default:
                        throw new LambdaToolsException($"Unable to determine how to convert substitute value into the template. " +
                                                       "Make sure to have a default value in the template which is used to determine the type. " +
                                                       "For example \"\" for string fields or {} for JSON objects.",
                                                       LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError);
                    }
                }
                catch (Exception e)
                {
                    throw new LambdaToolsException($"Error setting property {kvp.Key} with value {kvp.Value}: {e.Message}", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError);
                }
            }

            var json = JsonConvert.SerializeObject(root);

            return(json);
        }
Ejemplo n.º 48
0
        // This draws the individual point features
        private void DrawFeatures(MapArgs e, IEnumerable <IFeature> features, bool selected)
        {
            IDictionary <IFeature, IDrawnState> states = DrawingFilter.DrawnStates;

            if (states == null)
            {
                return;
            }
            if (selected && !states.Any(_ => _.Value.IsSelected))
            {
                return;
            }

            Graphics g             = e.Device ?? Graphics.FromImage(BackBuffer);
            Matrix   origTransform = g.Transform;

            foreach (IFeature feature in features)
            {
                if (!states.ContainsKey(feature))
                {
                    continue;
                }
                IDrawnState ds = states[feature];
                if (ds == null || !ds.IsVisible || ds.SchemeCategory == null)
                {
                    continue;
                }

                if (selected && !ds.IsSelected)
                {
                    continue;
                }

                IPointCategory pc = ds.SchemeCategory as IPointCategory;
                if (pc == null)
                {
                    continue;
                }

                IPointSymbolizer ps = selected ? pc.SelectionSymbolizer : pc.Symbolizer;
                if (ps == null)
                {
                    continue;
                }
                var clockwiseAngle = -GetAngleFromExpression(feature.Fid, ps);
                foreach (Coordinate c in feature.Geometry.Coordinates)
                {
                    DrawPoint(c.X, c.Y, e, ps, g, origTransform, clockwiseAngle);
                }
            }


            if (e.Device == null)
            {
                g.Dispose();
            }
            else
            {
                g.Transform = origTransform;
            }
        }
Ejemplo n.º 49
0
        public async Task <IActionResult> PostSignaturesAsync([FromQuery, Required] string uniqueId, [FromQuery, Required] long roundId, [FromBody, Required] IDictionary <int, string> signatures)
        {
            if (roundId < 0 ||
                !signatures.Any() ||
                signatures.Any(x => x.Key < 0 || string.IsNullOrWhiteSpace(x.Value)) ||
                !ModelState.IsValid)
            {
                return(BadRequest());
            }

            (CcjRound round, Alice alice) = GetRunningRoundAndAliceOrFailureResponse(roundId, uniqueId, CcjRoundPhase.Signing, out IActionResult returnFailureResponse);
            if (returnFailureResponse != null)
            {
                return(returnFailureResponse);
            }

            // Check if Alice provided signature to all her inputs.
            if (signatures.Count != alice.Inputs.Count())
            {
                return(BadRequest("Alice did not provide enough witnesses."));
            }

            CcjRoundPhase phase = round.Phase;

            switch (phase)
            {
            case CcjRoundPhase.Signing:
            {
                using (await SigningLock.LockAsync())
                {
                    foreach (var signaturePair in signatures)
                    {
                        int       index   = signaturePair.Key;
                        WitScript witness = null;
                        try
                        {
                            witness = new WitScript(signaturePair.Value);
                        }
                        catch (Exception ex)
                        {
                            return(BadRequest($"Malformed witness is provided. Details: {ex.Message}"));
                        }
                        int maxIndex = round.UnsignedCoinJoin.Inputs.Count - 1;
                        if (maxIndex < index)
                        {
                            return(BadRequest($"Index out of range. Maximum value: {maxIndex}. Provided value: {index}"));
                        }

                        // Check duplicates.
                        if (round.SignedCoinJoin.Inputs[index].HasWitScript())
                        {
                            return(BadRequest($"Input is already signed."));
                        }

                        // Verify witness.
                        // 1. Copy UnsignedCoinJoin.
                        Transaction cjCopy = Transaction.Parse(round.UnsignedCoinJoin.ToHex(), Network);
                        // 2. Sign the copy.
                        cjCopy.Inputs[index].WitScript = witness;
                        // 3. Convert the current input to IndexedTxIn.
                        IndexedTxIn currentIndexedInput = cjCopy.Inputs.AsIndexedInputs().Skip(index).First();
                        // 4. Find the corresponding registered input.
                        Coin registeredCoin = alice.Inputs.Single(x => x.Outpoint == cjCopy.Inputs[index].PrevOut);
                        // 5. Verify if currentIndexedInput is correctly signed, if not, return the specific error.
                        if (!currentIndexedInput.VerifyScript(registeredCoin, out ScriptError error))
                        {
                            return(BadRequest($"Invalid witness is provided. ScriptError: {error}."));
                        }

                        // Finally add it to our CJ.
                        round.SignedCoinJoin.Inputs[index].WitScript = witness;
                    }

                    alice.State = AliceState.SignedCoinJoin;

                    await round.BroadcastCoinJoinIfFullySignedAsync();
                }

                return(NoContent());
            }

            default:
            {
                TryLogLateRequest(roundId, CcjRoundPhase.Signing);
                return(Conflict($"CoinJoin can only be requested from Signing phase. Current phase: {phase}."));
            }
            }
        }
Ejemplo n.º 50
0
 private string GetResourceType(IDictionary <string, IDictionary <string, string> > type)
 {
     return(type != null && type.Any() ? type.First().Key : string.Empty);
 }
Ejemplo n.º 51
0
        public void TestWithDeletions()
        {
            Directory         dir = NewDirectory();
            IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));

            iwc.SetMergePolicy(NewLogMergePolicy());
            RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, iwc);
            KeyValuePair <List <string>, IDictionary <string, Document> > res = GenerateIndexDocuments(AtLeast(1000), false, false);
            IDictionary <string, Document> docs = res.Value;
            List <String> invalidDocTerms       = res.Key;
            Random        rand       = Random();
            List <string> termsToDel = new List <string>();

            foreach (Document doc in docs.Values)
            {
                IIndexableField f2 = doc.GetField(FIELD_NAME);
                if (rand.nextBoolean() && f2 != null && !invalidDocTerms.Contains(f2.GetStringValue()))
                {
                    termsToDel.Add(doc.Get(FIELD_NAME));
                }
                writer.AddDocument(doc);
            }
            writer.Commit();

            Term[] delTerms = new Term[termsToDel.size()];
            for (int i = 0; i < termsToDel.size(); i++)
            {
                delTerms[i] = new Term(FIELD_NAME, termsToDel[i]);
            }

            foreach (Term delTerm in delTerms)
            {
                writer.DeleteDocuments(delTerm);
            }
            writer.Commit();
            writer.Dispose();

            foreach (string termToDel in termsToDel)
            {
                var toDel = docs[termToDel];
                assertTrue(toDel != null);
                docs.Remove(termToDel);
            }

            IndexReader ir = DirectoryReader.Open(dir);

            assertEquals(ir.NumDocs, docs.size());
            IDictionary    dictionary    = new DocumentDictionary(ir, FIELD_NAME, WEIGHT_FIELD_NAME);
            IInputIterator inputIterator = dictionary.GetEntryIterator();
            BytesRef       f;

            while ((f = inputIterator.Next()) != null)
            {
                var      field = f.Utf8ToString();
                Document doc   = docs.ContainsKey(field) ? docs[field] : null;
                docs.Remove(field);
                assertTrue(f.equals(new BytesRef(doc.Get(FIELD_NAME))));
                IIndexableField weightField = doc.GetField(WEIGHT_FIELD_NAME);
                assertEquals(inputIterator.Weight, (weightField != null) ? weightField.GetInt64ValueOrDefault() : 0);
                assertEquals(inputIterator.Payload, null);
            }

            foreach (string invalidTerm in invalidDocTerms)
            {
                var invalid = docs[invalidTerm];
                docs.Remove(invalidTerm);
                assertNotNull(invalid);
            }
            assertTrue(!docs.Any());

            ir.Dispose();
            dir.Dispose();
        }
Ejemplo n.º 52
0
        public static ICollection <DossierTableValuedModel> GetAuthorized(this IRepository <Dossier> repository, string userName, string domain, int skip, int top, short?year, int?number, string subject, short?idContainer,
                                                                          DateTimeOffset?startDateFrom, DateTimeOffset?startDateTo, DateTimeOffset?endDateFrom, DateTimeOffset?endDateTo, string note, Guid?idMetadataRepository, string genericMetadataValue,
                                                                          IDictionary <string, string> metadataValues, short?idCategory, DossierType?dossierType, DossierStatus?status, bool optimization = true)
        {
            QueryParameter yearParameter                 = new QueryParameter(CommonDefinition.SQL_Param_Dossier_Year, DBNull.Value);
            QueryParameter numberParameter               = new QueryParameter(CommonDefinition.SQL_Param_Dossier_Number, DBNull.Value);
            QueryParameter subjectParameter              = new QueryParameter(CommonDefinition.SQL_Param_Dossier_Subject, DBNull.Value);
            QueryParameter containerParameter            = new QueryParameter(CommonDefinition.SQL_Param_Dossier_Container, DBNull.Value);
            QueryParameter startDateFromParameter        = new QueryParameter(CommonDefinition.SQL_Param_Dossier_StartDateFrom, DBNull.Value);
            QueryParameter startDateToParameter          = new QueryParameter(CommonDefinition.SQL_Param_Dossier_StartDateTo, DBNull.Value);
            QueryParameter endDateFromParameter          = new QueryParameter(CommonDefinition.SQL_Param_Dossier_EndDateFrom, DBNull.Value);
            QueryParameter endDateToParameter            = new QueryParameter(CommonDefinition.SQL_Param_Dossier_EndDateTo, DBNull.Value);
            QueryParameter noteParameter                 = new QueryParameter(CommonDefinition.SQL_Param_Dossier_Note, DBNull.Value);
            QueryParameter idMetadataRepositoryParameter = new QueryParameter(CommonDefinition.SQL_Param_Dossier_IdMetadataRepository, DBNull.Value);
            QueryParameter genericMetadataValueParameter = new QueryParameter(CommonDefinition.SQL_Param_Dossier_MetadataValue, DBNull.Value);
            QueryParameter metadataValuesParameter       = new QueryParameter(CommonDefinition.SQL_Param_Fascicle_MetadataValues, DBNull.Value)
            {
                ParameterTypeName = "keyvalue_tbltype"
            };
            QueryParameter idCategoryParameter  = new QueryParameter(CommonDefinition.SQL_Param_Category_IdCategory, DBNull.Value);
            QueryParameter dossierTypeParameter = new QueryParameter(CommonDefinition.SQL_Param_Dossier_DossierType, DBNull.Value);
            QueryParameter statusParameter      = new QueryParameter(CommonDefinition.SQL_Param_DossierFolder_Status, DBNull.Value);

            if (year.HasValue)
            {
                yearParameter.ParameterValue = year.Value;
            }
            if (number.HasValue)
            {
                numberParameter.ParameterValue = number.Value;
            }
            if (!string.IsNullOrEmpty(subject))
            {
                subjectParameter.ParameterValue = subject;
            }
            if (!string.IsNullOrEmpty(note))
            {
                noteParameter.ParameterValue = note;
            }
            if (idContainer.HasValue)
            {
                containerParameter.ParameterValue = idContainer.Value;
            }
            if (startDateFrom.HasValue)
            {
                startDateFromParameter.ParameterValue = startDateFrom;
            }
            if (startDateTo.HasValue)
            {
                startDateToParameter.ParameterValue = startDateTo;
            }
            if (endDateFrom.HasValue)
            {
                endDateFromParameter.ParameterValue = endDateFrom;
            }
            if (endDateTo.HasValue)
            {
                endDateToParameter.ParameterValue = endDateTo;
            }
            if (idMetadataRepository.HasValue)
            {
                idMetadataRepositoryParameter.ParameterValue = idMetadataRepository.Value;
            }
            if (!string.IsNullOrEmpty(genericMetadataValue))
            {
                genericMetadataValueParameter.ParameterValue = genericMetadataValue;
            }
            if (idCategory.HasValue)
            {
                idCategoryParameter.ParameterValue = idCategory;
            }
            if (dossierType.HasValue)
            {
                dossierTypeParameter.ParameterValue = dossierType;
            }
            if (status.HasValue)
            {
                statusParameter.ParameterValue = status;
            }
            DataTable table = new DataTable();

            table.Columns.Add("KeyName", typeof(string));
            table.Columns.Add("Value", typeof(string));
            if (metadataValues != null && metadataValues.Any())
            {
                foreach (KeyValuePair <string, string> metadataValue in metadataValues)
                {
                    table.Rows.Add(metadataValue.Key, metadataValue.Value);
                }
            }
            metadataValuesParameter.ParameterValue = table;

            ICollection <DossierTableValuedModel> results = repository.ExecuteModelFunction <DossierTableValuedModel>(CommonDefinition.SQL_FX_Dossier_AuthorizedDossiers,
                                                                                                                      new QueryParameter(CommonDefinition.SQL_Param_Dossier_UserName, userName), new QueryParameter(CommonDefinition.SQL_Param_Dossier_Domain, domain),
                                                                                                                      new QueryParameter(CommonDefinition.SQL_Param_Dossier_Skip, skip), new QueryParameter(CommonDefinition.SQL_Param_Dossier_Top, top),
                                                                                                                      yearParameter, numberParameter, subjectParameter, noteParameter, containerParameter, idMetadataRepositoryParameter, genericMetadataValueParameter, startDateFromParameter,
                                                                                                                      startDateToParameter, endDateFromParameter, endDateToParameter, metadataValuesParameter, idCategoryParameter, dossierTypeParameter, statusParameter);

            return(results.OrderBy(x => x.Year).OrderBy(x => x.Number).ToList());
        }
        public void Initialize(ITelemetry telemetry)
        {
            if (telemetry == null)
            {
                return;
            }

            telemetry.Context.Cloud.RoleInstance = _roleInstanceName;

            RequestTelemetry request = telemetry as RequestTelemetry;

            // Zero out all IP addresses other than Requests
            if (request == null)
            {
                telemetry.Context.Location.Ip = LoggingConstants.ZeroIpAddress;
            }
            else
            {
                if (request.Context.Location.Ip == null)
                {
                    request.Context.Location.Ip = LoggingConstants.ZeroIpAddress;
                }
            }

            IDictionary <string, string> telemetryProps = telemetry.Context.Properties;

            // Apply our special scope properties
            IDictionary <string, object> scopeProps =
                DictionaryLoggerScope.GetMergedStateDictionary() ?? new Dictionary <string, object>();

            string invocationId = scopeProps.GetValueOrDefault <string>(ScopeKeys.FunctionInvocationId);

            if (invocationId != null)
            {
                telemetryProps[LogConstants.InvocationIdKey] = invocationId;
            }

            // this could be telemetry tracked in scope of function call - then we should apply the logger scope
            // or RequestTelemetry tracked by the WebJobs SDK or AppInsight SDK - then we should apply Activity.Tags
            if (request == null && scopeProps.Any())
            {
                telemetry.Context.Operation.Name = scopeProps.GetValueOrDefault <string>(ScopeKeys.FunctionName);

                // Apply Category and LogLevel to all telemetry
                string category = scopeProps.GetValueOrDefault <string>(LogConstants.CategoryNameKey);
                if (category != null)
                {
                    telemetryProps[LogConstants.CategoryNameKey] = category;
                }

                LogLevel?logLevel = scopeProps.GetValueOrDefault <LogLevel?>(LogConstants.LogLevelKey);
                if (logLevel != null)
                {
                    telemetryProps[LogConstants.LogLevelKey] = logLevel.Value.ToString();
                }

                int?eventId = scopeProps.GetValueOrDefault <int?>(LogConstants.EventIdKey);
                if (eventId != null && eventId.HasValue && eventId.Value != 0)
                {
                    telemetryProps[LogConstants.EventIdKey] = eventId.Value.ToString();
                }
            }
            // we may track traces/dependencies after function scope ends - we don't want to update those
            else if (request != null)
            {
                Activity currentActivity = Activity.Current;
                if (currentActivity != null) // should never be null, but we don't want to throw anyway
                {
                    // tags is a list, we'll enumerate it
                    foreach (var tag in currentActivity.Tags)
                    {
                        switch (tag.Key)
                        {
                        case LogConstants.NameKey:
                            request.Context.Operation.Name = tag.Value;
                            request.Name = tag.Value;
                            break;

                        default:
                            request.Properties[tag.Key] = tag.Value;
                            break;
                        }
                    }
                }
                else // workaround for https://github.com/Microsoft/ApplicationInsights-dotnet-server/issues/1038
                {
                    if (request.Properties.TryGetValue(LogConstants.NameKey, out var functionName))
                    {
                        request.Context.Operation.Name = functionName;
                        request.Name = functionName;
                    }
                }
            }
        }
Ejemplo n.º 54
0
        public void AddQueueTask(string queueName, Action <object, BasicDeliverEventArgs> action, int taskNumber = 1)
        {
            if (_subTasks.Any(p => p.Key == queueName))
            {
                throw new Exception("一个队列只能有一个线程解析!");
            }

            if (taskNumber <= 0)
            {
                taskNumber = 1;
            }

            var threads = new List <Thread>();

            for (int i = 0; i < taskNumber; i++)
            {
                Thread thread = new Thread(() =>
                {
                    var channel = _connection.CreateModel();

                    channel.BasicQos(0, 1, false);//告诉broker同一时间只处理一个消息

                    var consurmer       = new EventingBasicConsumer(channel);
                    consurmer.Received += (sender, e) =>
                    {
                        //Task.Run(() =>
                        //{
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();


                        var consumer = sender as EventingBasicConsumer;
                        try
                        {
                            action(sender, e);
                        }
                        catch (Exception ex)
                        {
                            EngineContext.Current.Resolve <ILogger>().InsertQueueLog("HandlerError", Encoding.UTF8.GetString(e.Body) + Environment.NewLine + ex.Message);
                        }
                        finally
                        {
                            //处理完成,告诉Broker可以服务端可以删除消息,分配新的消息过来
                            channel.BasicAck(e.DeliveryTag, false);
                            stopwatch.Stop();
                            EngineContext.Current.Resolve <ILogger>().InsertQueueLog("Receive", $"处理耗时:{stopwatch.Elapsed.TotalMilliseconds}," + Encoding.UTF8.GetString(e.Body));
                        }
                        //});
                    };

                    //noAck设置false,告诉broker,发送消息之后,消息暂时不要删除,等消费者处理完成再说
                    channel.BasicConsume(queueName, false, consurmer);
                });

                threads.Add(thread);
            }

            _subTasks.Add(queueName, threads);

            foreach (var thread in threads)
            {
                thread.Start();
            }
        }
Ejemplo n.º 55
0
        private void HandleMessage(NetIncomingMessage msg)
        {
            switch (msg.MessageType)
            {
            case NetIncomingMessageType.ConnectionApproval:
                string  verStr = msg.ReadString();
                Version ver    = new Version(verStr);

                if (ver == MulTUNG.MulTUNG.Version)
                {
                    msg.SenderConnection.Approve();

                    string username = msg.ReadString().Trim();

                    if (!Players.Any(o => o.Value.Username.Equals(username)))
                    {
                        IGConsole.Log($"{username.Length} {MaxUsernameLength}");
                        if (username.Length < MaxUsernameLength)
                        {
                            msg.SenderConnection.Approve();
                        }
                        else
                        {
                            msg.SenderConnection.Deny($"your username must be shorter than {MaxUsernameLength} characters.");
                        }
                    }
                    else
                    {
                        msg.SenderConnection.Deny("someone is already using that username.");
                    }
                }
                else
                {
                    msg.SenderConnection.Deny($"wrong MulTUNG version, server has v{MulTUNG.MulTUNG.Version}.");
                }

                break;

            case NetIncomingMessageType.Data:
                var packet = PacketDeserializer.DeserializePacket(new MessagePacketReader(msg));

                if (packet.SenderID == Network.ServerPlayerID)
                {
                    break;
                }

                PacketLog.LogReceive(packet);

                if (packet.ShouldBroadcast)
                {
                    Broadcast(packet, packet.ReliableBroadcast ? NetDeliveryMethod.ReliableOrdered : NetDeliveryMethod.UnreliableSequenced);
                }
                else
                {
                    Network.ProcessPacket(packet, Network.ServerPlayerID);
                }

                break;

            case NetIncomingMessageType.StatusChanged:
                var status = (NetConnectionStatus)msg.ReadByte();

                if (status == NetConnectionStatus.Connected)
                {
                    int id = PlayerIdCounter++;

                    msg.SenderConnection.SendMessage(new PlayerWelcomePacket
                    {
                        YourID         = id,
                        ServerUsername = Network.Username,
                        Players        = Players.Select(o => new Tuple <int, string>(o.Key, o.Value.Username)).ToList()
                    }.GetMessage(Server), NetDeliveryMethod.ReliableOrdered, 0);

                    var player = new Player(id, msg.SenderConnection);

                    Log.WriteLine("Connected player " + player.ID);

                    Players.Add(id, player);
                }
                else if (status == NetConnectionStatus.Disconnected)
                {
                    var player = Players.SingleOrDefault(o => o.Value.Connection == msg.SenderConnection);

                    Players.Remove(player.Key);
                    PlayerManager.WaveGoodbye(player.Key);
                }

                break;
            }
        }
        internal static async Task CheckNonOptionalSettings(IDictionary <string, string> secrets, string scriptPath)
        {
            try
            {
                // FirstOrDefault returns a KeyValuePair<string, string> which is a struct so it can't be null.
                var azureWebJobsStorage = secrets.FirstOrDefault(pair => pair.Key.Equals("AzureWebJobsStorage", StringComparison.OrdinalIgnoreCase)).Value;
                var functionJsonFiles   = await FileSystemHelpers
                                          .GetDirectories(scriptPath)
                                          .Select(d => Path.Combine(d, "function.json"))
                                          .Where(FileSystemHelpers.FileExists)
                                          .Select(async f => (filePath: f, content: await FileSystemHelpers.ReadAllTextFromFileAsync(f)))
                                          .WhenAll();

                var functionsJsons = functionJsonFiles
                                     .Select(t => (filePath: t.filePath, jObject: JsonConvert.DeserializeObject <JObject>(t.content)))
                                     .Where(b => b.jObject["bindings"] != null);

                var allHttpTrigger = functionsJsons
                                     .Select(b => b.jObject["bindings"])
                                     .SelectMany(i => i)
                                     .Where(b => b?["type"] != null)
                                     .Select(b => b["type"].ToString())
                                     .Where(b => b.IndexOf("Trigger") != -1)
                                     .All(t => t == "httpTrigger");

                if (string.IsNullOrWhiteSpace(azureWebJobsStorage) && !allHttpTrigger)
                {
                    throw new CliException($"Missing value for AzureWebJobsStorage in {SecretsManager.AppSettingsFileName}. This is required for all triggers other than HTTP. "
                                           + $"You can run 'func azure functionapp fetch-app-settings <functionAppName>' or specify a connection string in {SecretsManager.AppSettingsFileName}.");
                }

                foreach ((var filePath, var functionJson) in functionsJsons)
                {
                    foreach (JObject binding in functionJson["bindings"])
                    {
                        foreach (var token in binding)
                        {
                            if (token.Key == "connection" || token.Key == "apiKey" || token.Key == "accountSid" || token.Key == "authToken")
                            {
                                var appSettingName = token.Value.ToString();
                                if (string.IsNullOrWhiteSpace(appSettingName))
                                {
                                    ColoredConsole.WriteLine(WarningColor($"Warning: '{token.Key}' property in '{filePath}' is empty."));
                                }
                                else if (!secrets.Any(v => v.Key.Equals(appSettingName, StringComparison.OrdinalIgnoreCase)))
                                {
                                    ColoredConsole
                                    .WriteLine(WarningColor($"Warning: Cannot find value named '{appSettingName}' in {SecretsManager.AppSettingsFileName} that matches '{token.Key}' property set on '{binding["type"]?.ToString()}' in '{filePath}'. " +
                                                            $"You can run 'func azure functionapp fetch-app-settings <functionAppName>' or specify a connection string in {SecretsManager.AppSettingsFileName}."));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e) when(!(e is CliException))
            {
                ColoredConsole.WriteLine(WarningColor($"Warning: unable to verify all settings from {SecretsManager.AppSettingsFileName} and function.json files."));
                if (StaticSettings.IsDebug)
                {
                    ColoredConsole.WriteLine(e);
                }
            }
        }
Ejemplo n.º 57
0
        private static async Task WatchTeamsAsync(int limit)
        {
            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();
            //await GetTeams();
            //await DbOperations.AddTeamsToTable(allTeams);

            var teams = DbOperations.GetTeams(limit);//.Skip(limit*2);//allTeams.OrderBy(o => o.CreatedDateTime).Take(limit);

            foreach (var team in teams)
            {
                teamSitesDeltaLinks.Add(team.TeamId, null);
            }

            watch.Stop();
            Console.WriteLine($"Checking Teams completed on {watch.ElapsedMilliseconds / 1000} seconds");

            while (!noChanges || iterationCounter != MaxIteration)
            {
                try
                {
                    await WatchTeamsSitesAsync();

                    processTime     = (int)DateTime.UtcNow.Subtract(lastProcessTime).TotalSeconds;
                    lastProcessTime = DateTime.UtcNow;
                    var wait = interval - processTime;
                    if (wait < 0)
                    {
                        wait = 0;
                    }
                    await Task.Delay(wait * 1000);

                    await DbOperations.UpdateResourcesAsync(resources);

                    resources.Clear();
                    firstCall = false;

                    if (teamSitesDeltaLinks.Any(w => w.Value == null))
                    {
                        noChanges        = false;
                        iterationCounter = 0;
                    }
                    else if (teamSitesDeltaLinks.All(w => w.Value.NoChanges))
                    {
                        noChanges = true;
                        ++iterationCounter;
                    }
                    else
                    {
                        noChanges        = false;
                        iterationCounter = 0;
                    }
                    perf.ActivitiesCalls     = activitiesCalls;
                    perf.DeltaCalls          = libraryDeltaCalls;
                    perf.AverageSyncDuration = DbOperations.GetAverageSync();
                    await DbOperations.UpdatePerformanceAsync(perf);
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                }
            }
        }
Ejemplo n.º 58
0
        //
        // クラスメソッド
        //

        /// <summary>
        /// インスタンスを生成する
        /// </summary>
        /// <param name="scenarioAsYaml">シナリオセットのYAML表現</param>
        /// <returns>生成インスタンス</returns>
        internal static UseCaseScenario CreateInstance(IDictionary <object, object> scenarioAsYaml)
        {
            Contract.Requires(scenarioAsYaml != null && scenarioAsYaml.Any());
            Contract.Ensures(Contract.Result <UseCaseScenario>() != null);

            var title        = string.Empty;
            var summary      = string.Empty;
            var baseScenario = string.Empty;
            var actions      = new List <UseCaseScenarioAction>();
            var metadata     = new Dictionary <string, object>();
            IEnumerable <string> preconditions = null;

            foreach (var pair in scenarioAsYaml)
            {
                var key = pair.Key as string;
                switch (key)
                {
                case "タイトル":
                    title = pair.Value as string;
                    break;

                case "サマリー":
                    summary = System.Text.RegularExpressions.Regex.Replace(pair.Value as string, "\\s*\\\\n\\s*", "\n");
                    break;

                case "ベースシナリオ":
                    baseScenario = pair.Value as string;
                    break;

                case "事前条件":
                    preconditions = pair.Value is string
                                    ?new List <string> {
                        pair.Value as string
                    }
                    : (pair.Value as IEnumerable <object>).Select(precondition => precondition as string);
                    break;

                case "アクション":
                    var index = 1;
                    foreach (var actionsAsYaml in pair.Value as IEnumerable <object> )
                    {
                        var actionsAsDictionary = actionsAsYaml as IDictionary <object, object>;
                        if (actionsAsDictionary.ContainsKey("操作") == false)
                        {
                            throw new ApplicationException(string.Format(Resources.Resources.Exception_Format_NoOperation, title, index));
                        }
                        if (actionsAsDictionary.ContainsKey("結果") == false)
                        {
                            throw new ApplicationException(string.Format(Resources.Resources.Exception_Format_NoExpectedResult, title, index));
                        }
                        var actionAsDictionary = actionsAsDictionary["操作"];
                        var action             = actionAsDictionary is string
                                                 ?actionAsDictionary as string
                                                 : string.Join(" / ", (actionAsDictionary as IEnumerable <object>).Select(result => result as string));
                        var resultsAsDictionary = actionsAsDictionary["結果"];
                        var actionResults       = resultsAsDictionary is string
                                                  ?new List <string> {
                            resultsAsDictionary as string
                        }
                        : (resultsAsDictionary as IEnumerable <object>).Select(result => result as string);
                        actions.Add(UseCaseScenarioAction.CreateInstance(action, actionResults));
                        ++index;
                    }
                    break;

                default:
                    metadata.Add(key, pair.Value);
                    break;
                }
            }
            if (preconditions == null)
            {
                throw new ApplicationException(string.Format(Resources.Resources.Exception_Format_NotFoundPreconditionKey, title));
            }

            return(new UseCaseScenario {
                Title = title,
                Summary = summary,
                BaseScenario = baseScenario,
                Preconditions = preconditions.ToList().AsReadOnly(),
                Actions = actions.ToList().AsReadOnly(),
                metadata = new ReadOnlyDictionary <string, object>(metadata),
            });
        }
Ejemplo n.º 59
0
        public static void Update(this CefSettings cefSettings, IDictionary <string, string> customSettings)
        {
            if (cefSettings == null || customSettings == null || !customSettings.Any())
            {
                return;
            }

            foreach (var setting in customSettings)
            {
                bool boolResult;
                int  intResult;

                if (string.IsNullOrWhiteSpace(setting.Value))
                {
                    continue;
                }

                switch (setting.Key.ToUpper())
                {
                case CefSettingKeys.NOSANDBOX:
                    if (setting.Value.TryParseBoolean(out boolResult))
                    {
                        cefSettings.NoSandbox = boolResult;
                    }

                    break;

                case CefSettingKeys.BROWSERSUBPROCESSPATH:
                    cefSettings.BrowserSubprocessPath = setting.Value;
                    break;

                case CefSettingKeys.MULTITHREADEDMESSAGELOOP:
                    if (setting.Value.TryParseBoolean(out boolResult))
                    {
                        cefSettings.MultiThreadedMessageLoop = boolResult;
                    }

                    break;

                case CefSettingKeys.EXTERNALMESSAGEPUMP:
                    if (setting.Value.TryParseBoolean(out boolResult))
                    {
                        cefSettings.ExternalMessagePump = boolResult;
                    }

                    break;

                case CefSettingKeys.WINDOWLESSRENDERINGENABLED:
                    if (setting.Value.TryParseBoolean(out boolResult))
                    {
                        cefSettings.WindowlessRenderingEnabled = boolResult;
                    }

                    break;

                case CefSettingKeys.COMMANDLINEARGSDISABLED:
                    if (setting.Value.TryParseBoolean(out boolResult))
                    {
                        cefSettings.CommandLineArgsDisabled = boolResult;
                    }

                    break;

                case CefSettingKeys.CACHEPATH:
                    cefSettings.CachePath = setting.Value;
                    break;

                case CefSettingKeys.USERDATAPATH:
                    cefSettings.UserDataPath = setting.Value;
                    break;

                case CefSettingKeys.PERSISTSESSIONCOOKIES:
                    if (setting.Value.TryParseBoolean(out boolResult))
                    {
                        cefSettings.PersistSessionCookies = boolResult;
                    }

                    break;

                case CefSettingKeys.PERSISTUSERPREFERENCES:
                    if (setting.Value.TryParseBoolean(out boolResult))
                    {
                        cefSettings.PersistUserPreferences = boolResult;
                    }

                    break;

                case CefSettingKeys.USERAGENT:
                    cefSettings.UserAgent = setting.Value;
                    break;

                case CefSettingKeys.LOCALE:
                    cefSettings.Locale = setting.Value;
                    break;

                case CefSettingKeys.CEFLOGFILE:
                case CefSettingKeys.LOGFILE:
                    cefSettings.LogFile = setting.Value;
                    break;

                case CefSettingKeys.LOGSEVERITY:
                    switch (setting.Value.ToUpper())
                    {
                    case LogSeverityOption.DEFAULT:
                        cefSettings.LogSeverity = CefLogSeverity.Default;
                        break;

                    case LogSeverityOption.VERBOSE:
                        cefSettings.LogSeverity = CefLogSeverity.Verbose;
                        break;

                    case LogSeverityOption.INFO:
                        cefSettings.LogSeverity = CefLogSeverity.Info;
                        break;

                    case LogSeverityOption.ERROR:
                        cefSettings.LogSeverity = CefLogSeverity.Warning;
                        break;

                    case LogSeverityOption.EXTERNAL:
                        cefSettings.LogSeverity = CefLogSeverity.Error;
                        break;

                    case LogSeverityOption.FATAL:
                        cefSettings.LogSeverity = CefLogSeverity.Fatal;
                        break;

                    case LogSeverityOption.DISABLE:
                        cefSettings.LogSeverity = CefLogSeverity.Disable;
                        break;
                    }

                    break;

                case CefSettingKeys.JAVASCRIPTFLAGS:
                    cefSettings.JavaScriptFlags = setting.Value;
                    break;

                case CefSettingKeys.RESOURCESDIRPATH:
                    cefSettings.ResourcesDirPath = setting.Value;
                    break;

                case CefSettingKeys.LOCALESDIRPATH:
                    cefSettings.LocalesDirPath = setting.Value;
                    break;

                case CefSettingKeys.PACKLOADINGDISABLED:
                    if (setting.Value.TryParseBoolean(out boolResult))
                    {
                        cefSettings.PackLoadingDisabled = boolResult;
                    }

                    break;

                case CefSettingKeys.REMOTEDEBUGGINGPORT:
                    if (setting.Value.TryParseInteger(out intResult))
                    {
                        cefSettings.RemoteDebuggingPort = intResult;
                    }

                    break;

                case CefSettingKeys.UNCAUGHTEXCEPTIONSTACKSIZE:
                    if (setting.Value.TryParseInteger(out intResult))
                    {
                        cefSettings.UncaughtExceptionStackSize = intResult;
                    }

                    break;

                case CefSettingKeys.ACCEPTLANGUAGELIST:
                    cefSettings.AcceptLanguageList = setting.Value;
                    break;

                // Not supported by CefGlue
                case CefSettingKeys.FOCUSEDNODECHANGEDENABLED:
                    break;

                // MacOS Only
                case CefSettingKeys.FRAMEWORKDIRPATH:
                    cefSettings.FrameworkDirPath = setting.Value;
                    break;

                // MacOS Only
                case CefSettingKeys.MAINBUNDLEPATH:
                    cefSettings.MainBundlePath = setting.Value;
                    break;

                default:
                    break;
                }
            }
        }
Ejemplo n.º 60
0
        public void ClearOnChange <T>(IDictionary <string, object> cacheForType, IEnumerable <string> updatedKeys, Func <IEnumerable <string>, object> updateFn)
            where T : DataModel
        {
            var type = typeof(T);

            _logger.LogInformation("SignalR {0} Update for keys {1}", type.Name, string.Join(", ", updatedKeys));
            bool isPostUpdate = type.Name == "Post";

            if (!isPostUpdate)
            {
                lock (cacheForType)
                {
                    if (type.Name == "Minister")
                    {
                        foreach (string key in updatedKeys)
                        {
                            cacheForType.Remove(key);
                        }
                    }
                    else
                    {
                        cacheForType.Clear();
                    }
                }
            }
            // call the API server (maybe be a different one)
            var update = updateFn(updatedKeys);

            if (isPostUpdate)
            {
                lock (cacheForType)
                {
                    var  oldestPost       = cacheForType.Any() ? (Post)cacheForType.TakeLast(1).SingleOrDefault().Value : null;
                    var  updatedPosts     = update as IList <Post>;
                    bool need2ReSortPosts = false;
                    foreach (string key in updatedKeys)
                    {
                        Post updatedPost = updatedPosts.FirstOrDefault(p => p.Key == key);
                        if (updatedPost == null)
                        {
                            cacheForType.Remove(key); // post unpublished
                            need2ReSortPosts = true;
                            continue;
                        }
                        if (oldestPost == null || oldestPost.PublishDate > updatedPost.PublishDate)
                        {
                            continue;                                                                         // Can't insert as it would probably out of order
                        }
                        object cachedPost;
                        cacheForType.TryGetValue(key, out cachedPost);
                        need2ReSortPosts |= cachedPost == null || ((Post)cachedPost).PublishDate != updatedPost.PublishDate;
                        cacheForType[key] = updatedPost;
                    }
                    PurgeCache <T>(cacheForType, NUM_CACHED_POSTS * 2);
                    if (need2ReSortPosts)
                    {
                        var newPostList = cacheForType.OrderByDescending(m => ((Post)m.Value).PublishDate).ToList();
                        cacheForType.Clear();
                        foreach (KeyValuePair <string, object> p in newPostList)
                        {
                            cacheForType.Add(p);
                        }
                    }
                }
            }
        }