Beispiel #1
0
        public ActionBar(Character character)
        {
            this.provider = GameManager.Instance;
            this.character = character;

            buttons = new Rectangle[NUM_BUTTONS];
            cds = new Rectangle[NUM_BUTTONS];

            ContentManager content = provider.Game.Content;

            font = content.Load<SpriteFont>("Fonts/GUIFont");
            textColor = Color.White;

            buttonTexture = content.Load<Texture2D>("UITextures/popbg");
            coolDownTexture = new Texture2D(provider.Game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            coolDownTexture.SetData<Color>(new[] { new Color(0.1f, 0.1f, 0.1f, 0.5f) });

            int xOffset = HPAD;
            int yOffset = provider.Game.GraphicsDevice.Viewport.Height - VPAD - (int)BUTTON_SIZE.Y;

            for (int i = 0; i < NUM_BUTTONS; i++)
            {
                buttons[i] = new Rectangle(xOffset, yOffset, (int)BUTTON_SIZE.X, (int)BUTTON_SIZE.Y);
                cds[i] = new Rectangle(xOffset, yOffset, (int)BUTTON_SIZE.X, (int)BUTTON_SIZE.Y);
                xOffset += (int)BUTTON_SIZE.X + SPACING;
            }
        }
Beispiel #2
0
        public NamePlate(Character character)
        {
            this.provider = GameManager.Instance;
            this.character = character;

            ContentManager content = provider.Game.Content;

            teamColor = GameSettings.TeamColour(character.Team);
            name = character.Name;
            font = content.Load<SpriteFont>("Fonts/namePlateFont");

            maxHealth = new Rectangle(0, 0, (int)BAR_SIZE.X, (int)BAR_SIZE.Y);
            effectiveHealth = new Rectangle(0, 0, (int)BAR_SIZE.X, (int)BAR_SIZE.Y);
            currentHealth = new Rectangle(0, 0, (int)BAR_SIZE.X, (int)BAR_SIZE.Y);
            namePosition = new Vector2();

            maxHealthTexture = new Texture2D(provider.Game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            maxHealthTexture.SetData<Color>(new[] { new Color(0.1f, 0.1f, 0.1f, 0.7f) });

            currentHealthTexture = new Texture2D(provider.Game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            currentHealthTexture.SetData<Color>(new[] { Color.White });

            effectiveHealthTexture = new Texture2D(provider.Game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            effectiveHealthTexture.SetData<Color>(new[] { new Color(0.1f, 0.1f, 0.1f, 0.5f) });
        }
Beispiel #3
0
        /// <summary>
        /// Creates a fresh gamestate with all game objects initialized and set to inactive.
        /// </summary>
        public GameState( ResourceProvider provider )
        {
            towers = new Tower[2];
            towers[0] = new Tower(Team.BLUE, provider);
            towers[1] = new Tower(Team.RED, provider);

            characters = new Character[GameSettings.MAX_LOBBY_CAPACITY];
            for ( int i = 0; i < GameSettings.MAX_LOBBY_CAPACITY; ++i )
            {
                characters[i] = new Character( provider );
            }

            spells = new Spell[GameSettings.MAX_SPELLS];
            for ( int i = 0; i < GameSettings.MAX_SPELLS; ++i )
            {
                spells[i] = new Spell( provider );
            }

            pickups = new PickUp[GameSettings.MAX_PICKUPS];
            for ( int i = 0; i < GameSettings.MAX_PICKUPS; ++i )
            {
                pickups[i] = new PickUp( provider );
            }

            roundClock = TimeSpan.Zero;

            scores = new int[2];
            for ( int i = 0; i < scores.Length; ++i )
            {
                scores[i] = 0;
            }
        }
        public ZeroMqResourceProviderFacade(ResourceProvider provider, string serverUri)
            : this(serverUri)
        {
            if (provider == null) throw new ArgumentNullException("provider");

            _work = (request, reply) => { reply(provider.Get(request)); };
            _sendPendingResults = () => { };
        }
Beispiel #5
0
 public ForwardKernelRoute(Guid routeGroupId, string nriregex, long energy, bool auth, ResourceProvider provider)
 {
     IsAuthoritative = auth;
     _regex = new Regex(nriregex);
     _provider = provider;
     GroupId = routeGroupId;
     DeliveryTime = energy;
 }
Beispiel #6
0
 /// <summary>
 /// Constructor lets the caller specify whether to include the standard
 /// "A=ok, B=cancel" usage text prompt.
 /// </summary>
 public UpgradeMenu(ResourceProvider p)
 {
     IsPopup = true;
     provider = p;
     TransitionOnTime = TimeSpan.FromSeconds(0.2);
     TransitionOffTime = TimeSpan.FromSeconds(0.2);
     crystalTexture = p.Game.Content.Load<Texture2D>("Images/diamond");
 }
Beispiel #7
0
        public PlayerFrame(Character character)
        {
            this.provider = GameManager.Instance;
            this.character = character;

            ContentManager content = provider.Game.Content;

            name = character.Name;
            font = content.Load<SpriteFont>("Fonts/GUIFont");
            font2 = content.Load<SpriteFont>("Fonts/playerFrameFont");

            maxHealthTexture = new Texture2D(provider.Game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            maxHealthTexture.SetData<Color>(new[] { new Color(0.1f, 0.1f, 0.1f, 0.3f) });

            currentHealthTexture = new Texture2D(provider.Game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            currentHealthTexture.SetData<Color>(new[] { new Color(0.1f, 0.7f, 0.1f, 1f) });

            effectiveHealthTexture = new Texture2D(provider.Game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            effectiveHealthTexture.SetData<Color>(new[] { new Color(0.1f, 0.1f, 0.1f, 0.1f) });

            maxFocusTexture = new Texture2D(provider.Game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            maxFocusTexture.SetData<Color>(new[] { new Color(0.1f, 0.1f, 0.1f, 0.3f) });

            currentFocusTexture = new Texture2D(provider.Game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            currentFocusTexture.SetData<Color>(new[] { new Color(255, 215, 0f, 1f) });

            crystalTexture = content.Load<Texture2D>("Images/diamond");

                roleIconTextures[0] = content.Load<Texture2D>("Images/wizardicon");

                roleIconTextures[1] = content.Load<Texture2D>("Images/priesticon");

                roleIconTextures[2] = content.Load<Texture2D>("Images/wlicon");

                roleIconTextures[3] = content.Load<Texture2D>("Images/bmicon");

            roleBgTexture = new Texture2D(provider.Game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            roleBgTexture.SetData<Color>(new[] { new Color(0.5f, 0.5f, 0.5f, 0.5f) });

            frameTexture = content.Load<Texture2D>("UITextures/CharFrame");

            healthStringPos= new Vector2(maxHealth.X + maxHealth.Width/2, maxHealth.Y + maxHealth.Height/2+2);
            healthStringOrigin = font.MeasureString("HEALTH") * 0.5f;

            focusStringPos = new Vector2(maxFocus.X + maxFocus.Width/2, maxFocus.Y + maxFocus.Height/2+2);
            focusStringOrigin = font.MeasureString("FOCUS") * 0.5f;

            crystalCountPos = new Vector2((int)(466*SCALE), (int)(91*SCALE));
            crystalCountOrigin = font.MeasureString("55") * 0.5f;
        }
Beispiel #8
0
        public void RegisterResourceProvider(ResourceProvider provider, int energy, bool isAuthoritative)
        {
            var providerid = Guid.NewGuid();

            RegisterResourceHandler(providerid, RoutesRequest.Get(providerid).NetResourceLocator,energy, isAuthoritative,  _=>provider.Get(RoutesRequest.GetGlobal()).Guard().Resource);

            _provider.Add(providerid, provider);
            var routeresource = _kernel.Get(RoutesRequest.Get(providerid)).Guard();

            var routelist = MediaFormatter<RoutesInformation>.Parse(routeresource.Resource, RoutesInformation.Mediatype);

            foreach (var routeEntry in routelist.Routes)
            {
                if (!String.IsNullOrEmpty(routeEntry.Identifier)) RegisterResourceForwarder(providerid, IdentifierToRegex(routeEntry.Identifier), provider, routeEntry.DeliveryTime + routeresource.Resource.Energy);
                else RegisterResourceForwarder(providerid, routeEntry.Regex, provider, routeEntry.DeliveryTime + routeresource.Resource.Energy);
            }
        }
Beispiel #9
0
        private static ResourceSet EvaluateSet(ControllerContext controllerContext, ResourceProvider provider, CultureInfo culture)
        {
            var route = controllerContext.RouteData;

            try
            {
                var set = route != null
                    ? string.Format("{0}/{1}", route.GetRequiredString("controller"), route.GetRequiredString("action"))
                    : string.Empty;

                return provider.GetResourceSet(culture, set);
            }
            catch (InvalidOperationException) // no route data
            {
                return provider.GetResourceSet(culture, string.Empty);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Add a command that opens the settings for a plugin or shows some options as a result using a <see cref="SubItemsSource"/>.
        /// In order for options to be added to the search results, <typeparamref name="TSettings"/> needs to have at least one public property with a getter
        /// and a setter with either a <see cref="GenericOptionAttribute"/>, <see cref="SelectionOptionAttribute"/> or <see cref="NumberOptionAttribute"/>
        /// attached to it.
        /// </summary>
        /// <typeparam name="TSettings">Type of the settings object which has some properties
        /// with a <see cref="GenericOptionAttribute"/>/<see cref="SelectionOptionAttribute"/>/<see cref="NumberOptionAttribute"/>
        /// atteched to it.
        /// </typeparam>
        /// <param name="pluginName">Name of the plugin.</param>
        /// <param name="settings">The settings object used by the plugin or a proxy object for it.</param>
        /// <param name="openSettingsViewAction">
        /// Every <see cref="Playnite.SDK.Plugins.Plugin"/> has the
        /// <see cref="Playnite.SDK.Plugins.Plugin.OpenSettingsView"/> method
        /// that should be used here.
        /// </param>
        /// <returns>The item that was added. Can be used to remove it.</returns>
        public static CommandItem AddPluginSettings <TSettings>(string pluginName, TSettings settings, OpenSettingsViewDelegate openSettingsViewAction)
        {
            var    assembly     = Assembly.GetCallingAssembly();
            string assemblyName = assembly?.GetName()?.Name ?? "Null";

            assemblyName = assemblyName.Replace("_", " ");;
            var key = $"{assemblyName}_{pluginName}_SETTINGS";

            if (!registeredAssemblies.Contains(assemblyName))
            {
                registeredAssemblies.Add(assemblyName);
            }

            var settingsCommand = new CommandItem(pluginName + " " + Application.Current.FindResource("LOCSettingsLabel"), () => { openSettingsViewAction?.Invoke(); }, string.Format(ResourceProvider.GetString("LOC_QS_OpenSettings"), pluginName), ResourceProvider.GetString("LOC_QS_OpenAction"))
            {
                IconChar = IconChars.Settings
            };

            if (settings?.GetType().GetProperties().Any(prop => prop.GetCustomAttribute <GenericOptionAttribute>(true) != null) ?? false)
            {
                var subItemsSource = new SettingsItemSource <TSettings>()
                {
                    Prefix = pluginName + " " + Application.Current.FindResource("LOCSettingsLabel") as string, Settings = settings
                };
                var subItemsAction = new SubItemsAction()
                {
                    Action = () => { }, Name = ResourceProvider.GetString("LOC_QS_ShowAction"), SubItemSource = subItemsSource, CloseAfterExecute = false
                };
                subItemsAction.SubItemSource = subItemsSource;
                settingsCommand.Actions.Add(subItemsAction);
            }
            foreach (CommandItemKey k in settingsCommand.Keys.ToArray())
            {
                settingsCommand.Keys.Add(new CommandItemKey()
                {
                    Key = "> " + k.Key, Weight = 1
                });
            }
            var source = GetOrCreateSource(assemblyName);

            if (!source.entries.ContainsKey(key))
            {
                source.entries.Add(key, settingsCommand);
            }
            return(source.entries[key] as CommandItem);
        }
        public List <GamePassGame> UpdateGamePassCatalog(bool resetCache)
        {
            var gamePassGamesList = new List <GamePassGame>();

            PlayniteApi.Dialogs.ActivateGlobalProgress((a) =>
            {
                var service = new GamePassCatalogBrowserService(PlayniteApi, GetPluginUserDataPath(), settings.Settings.NotifyCatalogUpdates, settings.Settings.AddExpiredTagToGames, settings.Settings.AddNewGames, settings.Settings.RemoveExpiredGames, settings.Settings.RegionCode);
                if (resetCache == true)
                {
                    service.DeleteCache();
                }
                gamePassGamesList = service.GetGamePassGamesList();
                service.Dispose();
            }, new GlobalProgressOptions(ResourceProvider.GetString("LOCGamePass_Catalog_Browser_UpdatingCatalogProgressMessage")));

            return(gamePassGamesList);
        }
        private void OpenVideoManager()
        {
            var window = PlayniteApi.Dialogs.CreateWindow(new WindowCreationOptions
            {
                ShowMinimizeButton = false
            });

            window.Height                = 600;
            window.Width                 = 800;
            window.Title                 = $"Splash Screen - {ResourceProvider.GetString("LOCSplashScreen_VideoManagerTitle")}";
            window.Content               = new VideoManager();
            window.DataContext           = new VideoManagerViewModel(PlayniteApi);
            window.Owner                 = PlayniteApi.Dialogs.GetCurrentAppWindow();
            window.WindowStartupLocation = WindowStartupLocation.CenterOwner;

            window.ShowDialog();
        }
Beispiel #13
0
        public static IEnumerable <object[]> ResourceExplorerRegistrationTestData()
        {
            var testProviders            = new ResourceProvider[] { new TestResourceProvider() };
            var testDeclarativeTypes     = new DeclarativeType[] { new DeclarativeType <ResourceExplorerOptionsTests>("test") };
            var testConverterFactories   = new JsonConverterFactory[] { new JsonConverterFactory <TestDeclarativeConverter>() };
            var testLegacyComponentTypes = new IComponentDeclarativeTypes[] { new TestDeclarativeComponentRegistration() };

            // params: ResourceExplorerOptions options

            // Initial declarative types only
            yield return(new object[] { new ResourceExplorerOptions(null, testDeclarativeTypes, testConverterFactories)
                                        {
                                            DeclarativeTypes = null
                                        }, null });

            // Initial IComponentDeclarativeTypes only
            yield return(new object[] { new ResourceExplorerOptions(null, null, null)
                                        {
                                            DeclarativeTypes = testLegacyComponentTypes
                                        }, null });

            // Initial declarative types and IComponentDeclarativeTypes
            yield return(new object[] { new ResourceExplorerOptions(null, testDeclarativeTypes, testConverterFactories)
                                        {
                                            DeclarativeTypes = testLegacyComponentTypes
                                        }, null });

            // Legacy registration only
            yield return(new object[] { new ResourceExplorerOptions(null, null, null)
                                        {
                                            DeclarativeTypes = null
                                        }, new TestDeclarativeComponentRegistration() });

            // Legacy bridged registration only
            yield return(new object[] { new ResourceExplorerOptions(null, null, null)
                                        {
                                            DeclarativeTypes = null
                                        }, new LegacyTestComponentRegistration() });

            // All at once, should to union of all registrations
            yield return(new object[] { new ResourceExplorerOptions(null, testDeclarativeTypes, testConverterFactories)
                                        {
                                            DeclarativeTypes = testLegacyComponentTypes
                                        }, new LegacyTestComponentRegistration() });
        }
Beispiel #14
0
        protected internal override void claimFiles(CleanupInfo info, ResourceProvider resourceProvider, Slide slide)
        {
            String rml         = null;
            String rmlFullPath = getRmlFilePath(slide);

            if (resourceProvider.fileExists(rmlFullPath))
            {
                using (StreamReader stringReader = new StreamReader(resourceProvider.openFile(rmlFullPath)))
                {
                    rml = stringReader.ReadToEnd();
                }
            }

            if (String.IsNullOrEmpty(rml))
            {
                Logging.Log.Warning("Could not claim files for slide '{0}', cannot find rml file '{1}' for panel '{2}'", slide.UniqueName, rmlFullPath, ElementName);
                return; //Break if we cannot load the rml
            }

            info.claimFile(rmlFullPath);

            XDocument rmlDoc = XDocument.Parse(rml);
            var       images = from query in rmlDoc.Descendants("img")
                               where query.Attribute("src") != null
                               select query.Attribute("src").Value;

            foreach (String image in images)
            {
                info.claimFile(Path.Combine(slide.UniqueName, image));
            }

            var triggers = from e in rmlDoc.Root.Descendants()
                           where e.Attribute("onclick") != null
                           select e;

            if (info.hasObjectClass(Slide.SlideActionClass))
            {
                foreach (var element in triggers)
                {
                    info.claimObject(Slide.SlideActionClass, element.Attribute("onclick").Value);
                }
            }

            base.claimFiles(info, resourceProvider, slide);
        }
Beispiel #15
0
        private void CreateYoutubeWindow(bool searchShortVideos = true, bool showDownloadButton = true, string defaultSearchTerm = null)
        {
            var window = PlayniteApi.Dialogs.CreateWindow(new WindowCreationOptions
            {
                ShowMinimizeButton = false
            });

            window.Height = 600;
            window.Width  = 840;
            window.Title  = ResourceProvider.GetString("LOCExtra_Metadata_Loader_YoutubeWindowDownloadTitle");

            window.Content               = new YoutubeSearchView();
            window.DataContext           = new YoutubeSearchViewModel(PlayniteApi, PlayniteApi.MainView.SelectedGames.Last(), videosDownloader, searchShortVideos, showDownloadButton, defaultSearchTerm);
            window.Owner                 = PlayniteApi.Dialogs.GetCurrentAppWindow();
            window.WindowStartupLocation = WindowStartupLocation.CenterOwner;

            window.ShowDialog();
        }
        public static MvcHtmlString FormLabelFor <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression)
        {
            TagBuilder label = new TagBuilder("label");

            if (expression.IsRequired())
            {
                TagBuilder requiredSpan = new TagBuilder("span");
                requiredSpan.AddCssClass("required");
                requiredSpan.InnerHtml = " *";

                label.InnerHtml = requiredSpan.ToString();
            }

            label.MergeAttribute("for", TagBuilder.CreateSanitizedId(ExpressionHelper.GetExpressionText(expression)));
            label.InnerHtml = ResourceProvider.GetPropertyTitle(expression) + label.InnerHtml;

            return(new MvcHtmlString(label.ToString()));
        }
Beispiel #17
0
        public void GetClientValidationRules_SetsOtherPropertyDisplayName()
        {
            IServiceProvider       services  = Substitute.For <IServiceProvider>();
            IModelMetadataProvider provider  = new EmptyModelMetadataProvider();
            ModelMetadata          metadata  = provider.GetMetadataForProperty(typeof(AdaptersModel), "EqualTo");
            EqualToAttribute       attribute = new EqualToAttribute("EqualTo");

            attribute.OtherPropertyDisplayName = null;

            ClientModelValidationContext context = new ClientModelValidationContext(metadata, provider, services);

            new EqualToAdapter(attribute).GetClientValidationRules(context);

            String expected = ResourceProvider.GetPropertyTitle(typeof(AdaptersModel), "EqualTo");
            String actual   = attribute.OtherPropertyDisplayName;

            Assert.Equal(expected, actual);
        }
Beispiel #18
0
 /// <summary>
 /// Create Cosmos DB Stored Procedure
 /// </summary>
 /// <param name="collectionUri"></param>
 /// <param name="spId"></param>
 /// <returns></returns>
 private async Task <StoredProcedure> CreateSPAsync(Uri collectionUri, string spId)
 {
     try
     {
         var spBody       = ResourceProvider.GetResourceString(ResourceNamespaces.CosmosDBSp, CosmosDBSPKeys.spGetGridContent);
         var spDefinition = new StoredProcedure
         {
             Id   = spId,
             Body = spBody
         };
         var result = ExecuteWithFollowOnAction(() => Client.CreateStoredProcedureAsync(collectionUri, spDefinition));
         return(await Task.FromResult(result));
     }
     catch (Exception ex)
     {
     }
     return(null);
 }
Beispiel #19
0
        public void ToString_003()
        {
            var html = HtmlBuilder
                       .Element("body", body => body
                                .Element("p", p => p
                                         .Append("foo ")
                                         .Element("span", span => span
                                                  .Attribute("class", "quux")
                                                  .Append("bar"))
                                         .Append(" baz"))
                                .Element("p", p => p
                                         .Append("foo ")
                                         .Element("span", "qux")
                                         .Append(" baz")))
                       .ToHtml(Formatting);

            Assert.AreEqual(ResourceProvider.ReadTextFile(nameof(ToString_003) + ".html"), html);
        }
Beispiel #20
0
        public void GetMenus_SetsHasActiveSubmenuIfAnyOfItsSubmenusAreActiveOrHasActiveSubmenus()
        {
            routeValues["area"]       = "administration";
            routeValues["controller"] = "roles";
            routeValues["action"]     = "index";

            MvcSiteMapNode expected = parser.GetMenuNodes(siteMap).Single(menu => menu.Area == "Administration" && menu.Action == null);
            IEnumerable <MvcSiteMapMenuNode> actualMenus = TreeToEnumerable(provider.GetMenus()).Where(menu => menu.HasActiveSubMenu);
            MvcSiteMapMenuNode actual = actualMenus.Single();

            Assert.AreEqual(ResourceProvider.GetSiteMapTitle(expected.Area, expected.Controller, expected.Action), actual.Title);
            Assert.AreEqual(expected.IconClass, actual.IconClass);
            Assert.AreEqual(expected.Controller, actual.Controller);
            Assert.AreEqual(expected.Action, actual.Action);
            Assert.AreEqual(expected.Area, actual.Area);
            Assert.IsTrue(actual.HasActiveSubMenu);
            Assert.IsFalse(actual.IsActive);
        }
Beispiel #21
0
        private void SaveSettingsButton_Click(object sender, RoutedEventArgs e)
        {
            ResourceProvider resource = ResourceProvider.Instance;

            try
            {
                _xmlhelper.UpdateSettingValue("user_login", textBoxLogin.Text);
                _xmlhelper.UpdateSettingValue("user_password", EncDec.Shifrovka(passwordBox.Password, "private_string"));
                _xmlhelper.UpdateSettingValue("realm1_client_location", location1.Text);

                if (copyApp.IsChecked == true)
                {
                    _xmlhelper.UpdateSettingValue("run_copy_app", "false");
                }
                else
                {
                    _xmlhelper.UpdateSettingValue("run_copy_app", "true");
                }

                FancyBalloon balloon = new FancyBalloon();
                balloon.BalloonMessage = resource.Get(TextResource.SETTINGOK);
                tb.ShowCustomBalloon(balloon, PopupAnimation.Slide, 5000);
                Logger.Current.AppendText("Пользовательские данные успешно сохранены");
                SetResultText("");

                var popupReset = new PopupDialogReset();
                popupReset.Owner = this;
                ApplyEffect(this);
                bool?dialogResult = popupReset.ShowDialog();
                ClearEffect(this);

                if (dialogResult == true)
                {
                    Close();
                }
            }
            catch
            {
                FancyBalloon balloon = new FancyBalloon();
                balloon.BalloonMessage = resource.Get(TextResource.SETTINGERR);
                tb.ShowCustomBalloon(balloon, PopupAnimation.Slide, 5000);
                Logger.Current.AppendText("Ошибка сохранения пользовательских данных");
            }
        }
Beispiel #22
0
        private String FormTitleButtons(params LinkAction[] actions)
        {
            String buttons = String.Empty;

            foreach (LinkAction action in actions)
            {
                TagBuilder icon = new TagBuilder("i");
                switch (action)
                {
                case LinkAction.Create:
                    icon.AddCssClass("fa fa-file-o");
                    break;

                case LinkAction.Details:
                    icon.AddCssClass("fa fa-info");
                    break;

                case LinkAction.Edit:
                    icon.AddCssClass("fa fa-pencil");
                    break;

                case LinkAction.Delete:
                    icon.AddCssClass("fa fa-times");
                    break;
                }

                TagBuilder span = new TagBuilder("span");
                span.InnerHtml = ResourceProvider.GetActionTitle(action.ToString());

                String button = String.Format(
                    html.ActionLink(
                        "{0}{1}",
                        action.ToString(),
                        new { id = html.ViewContext.RouteData.Values["id"] },
                        new { @class = "btn" })
                    .ToString(),
                    icon,
                    span);

                buttons += button;
            }

            return(buttons);
        }
Beispiel #23
0
        /// <summary>
        ///     Executes the experiment.
        /// </summary>
        ///<exception cref="InvalidOperationException">Thrown when the resource path is invalid, the matcher is not assigned or the resource provider is not assigned.</exception>
        public void Execute()
        {
            VerifyPreconditions();

            // Loading features
            List <string> imgCaptions;
            var           features = GetFeatures(out imgCaptions);

            // Perform all comparissons
            List <double> genuine;
            List <double> impostor;
            List <string> falseNotMatches;
            List <string> falseMatches;
            double        speed = DoComparisons(features, imgCaptions, out genuine, out impostor, out falseNotMatches, out falseMatches);

            // Saving data
            Directory.CreateDirectory(string.Format(@"{0}\Results\", ResourcePath));
            string fileName = string.Format(@"{0}\Results\{1}.falseNotMatches.csv", ResourcePath, Matcher.GetType().Name);

            SaveBadMatches(fileName, falseNotMatches);
            fileName = string.Format(@"{0}\Results\{1}.falseMatches.csv", ResourcePath, Matcher.GetType().Name);
            SaveBadMatches(fileName, falseMatches);

            fileName = string.Format(@"{0}\Results\{1}.Summary.csv", ResourcePath, Matcher.GetType().Name);
            StreamWriter fs = new StreamWriter(fileName, false);

            fs.WriteLine(String.Format("Features:; {0}", ResourceProvider.GetSignature()));
            fs.WriteLine("Average match time(ms):; {0:f5}", speed);
            double          eer, fmr100, fmr1000, zeroFmr;
            List <ROCPoint> roc;

            ComputeAccuracy(genuine, impostor, out eer, out fmr100, out fmr1000, out zeroFmr, out roc);
            fs.WriteLine("EER(%):; {0:f3}", eer);
            fs.WriteLine("FMR100(%):; {0:f3}", fmr100);
            fs.WriteLine("FMR1000(%):; {0:f3}", fmr1000);
            fs.WriteLine("ZeroFmr(%):; {0:f3}", zeroFmr);
            ROCSerializer.Serialize(roc, "FMR", "FNMR", Matcher.GetType().Name, fs);
            fs.Close();

            //fileName = string.Format(@"{0}\Results\{1}.Genuine.bin", resultsDir, Matcher.GetType().Name);
            //BinarySerializer.Serialize(genuine, fileName);
            //fileName = string.Format(@"{0}\Results\{1}.Impostor.bin", resultsDir, Matcher.GetType().Name);
            //BinarySerializer.Serialize(impostor, fileName);
        }
        private void SetHotkey(KeyEventArgs e, TextBox tbHotkey, Button setHotkeyButton, Hotkey hotkeyGesture)
        {
            // Get modifiers and key data
            var modifiers = Keyboard.Modifiers;
            var key       = e.Key;

            // When Alt is pressed, SystemKey is used instead
            if (key == Key.System)
            {
                key = e.SystemKey;
            }

            // Pressing delete, backspace or escape without modifiers clears the current value
            if (modifiers == ModifierKeys.None ||
                (key == Key.Delete || key == Key.Back || key == Key.Escape))
            {
                // Hotkey = null;
                return;
            }

            // If no actual key was pressed - return
            if (key == Key.LeftCtrl ||
                key == Key.RightCtrl ||
                key == Key.LeftAlt ||
                key == Key.RightAlt ||
                key == Key.LeftShift ||
                key == Key.RightShift ||
                key == Key.LWin ||
                key == Key.RWin ||
                key == Key.Clear ||
                key == Key.OemClear ||
                key == Key.Apps)
            {
                return;
            }

            tbHotkey.Text = $"{modifiers} + {key}";

            hotkeyGesture.Key       = key;
            hotkeyGesture.Modifiers = modifiers;
            tbHotkey.Focusable      = false;
            setHotkeyButton.Focus();
            setHotkeyButton.Content = ResourceProvider.GetString("LOCPlayState_SettingChangeHotkeyButtonLabel");
        }
        private void SetHotkey(KeyEventArgs e, TextBox shortcutText, Button setHotkeyButton, SearchSettings.Hotkey searchHotkey)
        {
            // Get modifiers and key data
            var modifiers = Keyboard.Modifiers;
            var key = e.Key;

            // When Alt is pressed, SystemKey is used instead
            if (key == Key.System)
            {
                key = e.SystemKey;
            }

            // Pressing delete, backspace or escape without modifiers clears the current value
            if (modifiers == ModifierKeys.None &&
                (key == Key.Delete || key == Key.Back || key == Key.Escape))
            {
                // Hotkey = null;
                return;
            }

            // If no actual key was pressed - return
            if (key == Key.LeftCtrl ||
                key == Key.RightCtrl ||
                key == Key.LeftAlt ||
                key == Key.RightAlt ||
                key == Key.LeftShift ||
                key == Key.RightShift ||
                key == Key.LWin ||
                key == Key.RWin ||
                key == Key.Clear ||
                key == Key.OemClear ||
                key == Key.Apps)
            {
                return;
            }

            shortcutText.Text = $"{modifiers} + {key}";

            searchHotkey.Key = key;
            searchHotkey.Modifiers = modifiers;
            shortcutText.Focusable = false;
            setHotkeyButton.Focus();
            setHotkeyButton.Content = ResourceProvider.GetString("LOC_QS_SetHotkeyButton");
        }
        public override bool ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var uri = new Uri(request.Url);

            this.Stream = ResourceProvider.GetStream(uri.AbsolutePath);
            if (this.Stream == null)
            {
                throw new NullReferenceException($"Resource for path was not found: {uri.AbsolutePath}");
            }
            this.Stream.Position = 0;

            this.StatusCode     = (int)HttpStatusCode.OK;
            this.ResponseLength = Stream.Length;
            this.MimeType       = GetMimeType(Path.GetExtension(uri.AbsolutePath));

            callback.Continue();

            return(true);
        }
Beispiel #27
0
        public async Task DocumentWithImage()
        {
            var httpResourceProvider = Mocks.HttpResourceProvider()
                                       .Resource("http://localhost/", "<html><body><img src='image.bmp'/></body></html>")
                                       .Resource("http://localhost/image.bmp", new byte[] { 1, 2, 3, 2, 1 }, "image/bmp");

            var resourceProvider = new ResourceProvider(httpResourceProvider, null);
            var engine           = new Engine(resourceProvider);
            var page             = await engine.OpenUrl("http://localhost");

            var img = (HtmlImageElement)page.Document.GetElementsByTagName("img").First();

            var loadSignal = new ManualResetEvent(false);

            img.OnLoad += evt => { loadSignal.Set(); };
            img.Src     = "image.bmp";
            Assert.IsTrue(loadSignal.WaitOne(1000));
            Assert.IsTrue(img.Complete);
        }
        private void Translate()
        {
            ResourceProvider resource     = ResourceProvider.Instance;
            string           hotNewsConst = resource.Get(TextResource.HOTNEWS);
            string           playConst    = resource.Get(TextResource.PLAY);

            gamesBtn.Content       = resource.Get(TextResource.GAMESBTN);
            newsBtn.Content        = resource.Get(TextResource.NEWSBTN);
            minimizeButton.ToolTip = resource.Get(TextResource.TOOLMINI);
            closeButton.ToolTip    = resource.Get(TextResource.TOOLCLOSE);
            settingsBtn.Content    = resource.Get(TextResource.SETTINGSBTN);
            shopBtn.Content        = resource.Get(TextResource.SHOPBTN);
            forumBtn.Content       = resource.Get(TextResource.FORUMBTN);

            playButton.Content   = playConst;
            hotNewsLabel.Content = hotNewsConst;

            Logger.Current.AppendText("Завершен метод перевода главного окна");
        }
Beispiel #29
0
 public override IEnumerable <TopPanelItem> GetTopPanelItems()
 {
     yield return(new TopPanelItem()
     {
         Icon = new TextBlock
         {
             Text = char.ConvertFromUtf32(0xebdf),
             FontSize = 20,
             FontFamily = ResourceProvider.GetResource("FontIcoFont") as FontFamily
         },
         Title = "Calculator",
         Activated = () => Process.Start("calc")
     });
     //new TopPanelItem()
     //{
     //    Title = "Steam fields",
     //    Activated = () => Process.Start(@"steam://open/friends")
     //}
 }
        public void GetHashCode_AllPossibleResourceProviderCombinations_HashCodesAreUnique()
        {
            var hashCodes = new List <Int32>();

            foreach (var type in Enum.GetValues(typeof(ResourceTypes)))
            {
                foreach (var production in new UInt32[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 })
                {
                    var hashCode = new ResourceProvider((ResourceTypes)type, production).GetHashCode();

                    if (hashCodes.Contains(hashCode))
                    {
                        throw new Exception(String.Format("Duplicate hash code found for {0} and {1}.", type, production));
                    }

                    hashCodes.Add(hashCode);
                }
            }
        }
        public static string GetString(Dock value)
        {
            switch (value)
            {
            case Dock.Left:
                return(ResourceProvider.GetString("LOCDockLeft"));

            case Dock.Right:
                return(ResourceProvider.GetString("LOCDockRight"));

            case Dock.Top:
                return(ResourceProvider.GetString("LOCDockTop"));

            case Dock.Bottom:
                return(ResourceProvider.GetString("LOCDockBottom"));
            }

            return("<UknownDockMode>");
        }
Beispiel #32
0
        // e.g.

        /*
         * arn:partition:service:region:account-id:resource
         * arn:partition:service:region:account-id:resourcetype/resource
         * arn:partition:service:region:account-id:resourcetype:resource
         */

        // aws:host/i-453-352-18
        // aws:us-east-1:bucket/carbon

        public static ManagedResource Parse(string text)
        {
            var segments = text.Split(Seperators.ForwardSlash); // '/'

            if (segments.Length != 2)
            {
                throw new Exception("missing id seperator '/')");
            }

            var parts = segments[0].Split(Seperators.Colon); // ':'

            var provider = ResourceProvider.Parse(parts[0]);

            string locationName = null;
            string typeName     = null;

            if (parts.Length == 1)
            {
                typeName = "unknown";
            }
            if (parts.Length == 2)
            {
                typeName = parts[1];
            }
            else if (parts.Length == 3)
            {
                locationName = parts[1];
                typeName     = parts[2];
            }

            var id = segments[1];

            var resourceType = new ResourceType(typeName); // normalize?

            if (locationName != null)
            {
                var location = Locations.Get(provider, locationName);

                return(FromLocation(location, resourceType, id));
            }

            return(new ManagedResource(provider, resourceType, id));
        }
Beispiel #33
0
        public void GetMenus_DoesnNotAuthorizeMenusWithoutAction()
        {
            Authorization.Provider = Substitute.For <IAuthorizationProvider>();
            Authorization.Provider.IsAuthorizedFor(Arg.Any <String>(), "Administration", "Roles", "Index").Returns(true);

            IEnumerator <MvcSiteMapNode>     expected = TreeToEnumerable(parser.GetMenuNodes(siteMap)).Skip(1).Take(2).GetEnumerator();
            IEnumerator <MvcSiteMapMenuNode> actual   = TreeToEnumerable(provider.GetMenus()).GetEnumerator();

            while (expected.MoveNext() | actual.MoveNext())
            {
                Assert.AreEqual(ResourceProvider.GetSiteMapTitle(expected.Current.Area, expected.Current.Controller, expected.Current.Action), actual.Current.Title);
                Assert.AreEqual(expected.Current.IconClass, actual.Current.IconClass);
                Assert.AreEqual(expected.Current.Controller, actual.Current.Controller);
                Assert.AreEqual(expected.Current.Action, actual.Current.Action);
                Assert.AreEqual(expected.Current.Area, actual.Current.Area);
                Assert.IsFalse(actual.Current.HasActiveSubMenu);
                Assert.IsFalse(actual.Current.IsActive);
            }
        }
Beispiel #34
0
        public void GetMenus_RemovesMenusWithoutActionAndSubmenus()
        {
            Authorization.Provider = Substitute.For <IAuthorizationProvider>();
            Authorization.Provider.IsAuthorizedFor(HttpContext.Current.User.Identity.Name, null, "Home", "Index").Returns(true);

            IEnumerator <MvcSiteMapNode>     expected = TreeToEnumerable(parser.GetMenuNodes(siteMap).Where(menu => menu.Controller == "Home" && menu.Action == "Index")).GetEnumerator();
            IEnumerator <MvcSiteMapMenuNode> actual   = TreeToEnumerable(provider.GetMenus()).GetEnumerator();

            while (expected.MoveNext() | actual.MoveNext())
            {
                Assert.AreEqual(ResourceProvider.GetSiteMapTitle(expected.Current.Area, expected.Current.Controller, expected.Current.Action), actual.Current.Title);
                Assert.AreEqual(expected.Current.IconClass, actual.Current.IconClass);
                Assert.AreEqual(expected.Current.Controller, actual.Current.Controller);
                Assert.AreEqual(expected.Current.Action, actual.Current.Action);
                Assert.AreEqual(expected.Current.Area, actual.Current.Area);
                Assert.IsFalse(actual.Current.HasActiveSubMenu);
                Assert.IsFalse(actual.Current.IsActive);
            }
        }
Beispiel #35
0
        private static void Tree_SetNodeAttributes(RadTreeNode node)
        {
            if (node == null)
            {
                return;
            }

            ActionType type       = (ActionType)Enum.Parse(typeof(ActionType), node.Category);
            string     imageUrl   = null;
            Type       typeOfThis = typeof(ActionsControl);

            if (node.ParentNode == null)
            {
                imageUrl      = ResourceProvider.GetImageUrl(typeOfThis, "Folder.gif");
                node.Expanded = true;
            }

            switch (type)
            {
            case ActionType.GlobalNavigationLink:
                if (node.ParentNode != null)
                {
                    if (imageUrl == null)
                    {
                        imageUrl = ResourceProvider.GetImageUrl(typeOfThis, "HyperLink.gif");
                    }
                }
                break;

            case ActionType.Page:
                if (imageUrl == null)
                {
                    imageUrl = ResourceProvider.GetImageUrl(typeOfThis, "Page.gif");
                }
                break;

            case ActionType.Control:
                imageUrl = ResourceProvider.GetImageUrl(typeOfThis, "Control.gif");
                break;
            }

            node.ImageUrl = CustomUrlProvider.CreateApplicationAbsoluteUrl(imageUrl);
        }
Beispiel #36
0
        private void SetLabelTag(string binding, string text, IValueConverter converter = null, string bindingName = null)
        {
            if (PanelItemsHost == null)
            {
                return;
            }

            var elem = new Label();

            elem.SetResourceReference(Label.StyleProperty, "FilterPanelLabel");
            BindingTools.SetBinding(elem,
                                    FrameworkElement.TagProperty,
                                    mainModel.AppSettings.FilterSettings,
                                    bindingName ?? $"{binding}.{nameof(FilterItemProperites.IsSet)}",
                                    fallBackValue: false,
                                    converter: converter);
            elem.Content = ResourceProvider.GetString(text);
            PanelItemsHost.Children.Add(elem);
        }
Beispiel #37
0
        public async Task DocumentWithEmbeddedImage()
        {
            var httpResourceProvider = Mocks.HttpResourceProvider()
                                       .Resource("http://localhost/",
                                                 "<html><body><img " +
                                                 "onload='document.body.appendChild(document.createElement(\"span\"))' " +
                                                 $"src='data:image/bmp;base64,{Img64}'/></body></html>"
                                                 );

            var resourceProvider = new ResourceProvider(httpResourceProvider, null);

            var engine = TestingEngine.BuildJint(resourceProvider);
            var page   = await engine.OpenUrl("http://localhost");

            Assert.IsNotNull(page.Document.WaitSelector("span", 1000), "Onload fired");

            ((HtmlImageElement)page.Document.GetElementsByTagName(TagsNames.Img).First())
            .Assert(img => img.NaturalWidth == 8 && img.NaturalHeight == 4);
        }
Beispiel #38
0
        protected Boolean IsSpecified <TView>(TView view, Expression <Func <TView, Object> > property) where TView : BaseView
        {
            Boolean isSpecified = property.Compile().Invoke(view) != null;

            if (!isSpecified)
            {
                UnaryExpression unary = property.Body as UnaryExpression;
                if (unary == null)
                {
                    ModelState.AddModelError(property, Validations.Required, ResourceProvider.GetPropertyTitle(property));
                }
                else
                {
                    ModelState.AddModelError(property, Validations.Required, ResourceProvider.GetPropertyTitle(unary.Operand));
                }
            }

            return(isSpecified);
        }
Beispiel #39
0
        private MvcSiteMapBreadcrumb CreateBreadcrumb(params MvcSiteMapNode[] nodes)
        {
            MvcSiteMapBreadcrumb breadcrumb = new MvcSiteMapBreadcrumb();

            foreach (MvcSiteMapNode node in nodes)
            {
                breadcrumb.Add(new MvcSiteMapBreadcrumbNode()
                {
                    Title     = ResourceProvider.GetSiteMapTitle(node.Area, node.Controller, node.Action),
                    IconClass = node.IconClass,

                    Controller = node.Controller,
                    Action     = node.Action,
                    Area       = node.Area
                });
            }

            return(breadcrumb);
        }
        public void TestAccessingNullTokenResource()
        {
            ResourceContext context = new ResourceContext();
            context.Headers = new NameValueCollection();
            context.Headers["Authorization"] = "bearer my-token";

            Mock<ContextProcessor<IResourceContext>> mckProvider = new Mock<ContextProcessor<IResourceContext>>(new Mock<IServiceFactory>().Object);
            mckProvider.Setup(x => x.IsSatisfiedBy(context)).Returns(true);
            mckProvider.Setup(x => x.Process(context));

            SimpleServiceLocator container = new SimpleServiceLocator();
            container.RegisterAll<ContextProcessor<IResourceContext>>(mckProvider.Object);

            ServiceLocator.SetLocatorProvider(() => container);

            ResourceProvider provider = new ResourceProvider();

            CommonErrorAssert(context, provider, Parameters.ErrorParameters.ErrorValues.InvalidToken);

            mckProvider.Verify();
        }
        public void TestAccessingResourceUnhandledByProcessor()
        {
            ResourceContext context = new ResourceContext();
            context.Headers = new NameValueCollection();
            context.Headers["Authorization"] = "bearer my-token";

            Mock<ContextProcessor<IResourceContext>> mckProvider = new Mock<ContextProcessor<IResourceContext>>(new Mock<IServiceFactory>().Object);
            mckProvider.Setup(x => x.IsSatisfiedBy(context)).Returns(false);

            SimpleServiceLocator container = new SimpleServiceLocator();
            container.RegisterAll<ContextProcessor<IResourceContext>>(mckProvider.Object);

            ServiceLocator.SetLocatorProvider(() => container);

            ResourceProvider provider = new ResourceProvider();

            provider.AccessProtectedResource(context);


            mckProvider.Verify();

        }
Beispiel #42
0
 //Necessary Constructor
 public Spell(ResourceProvider provider)
     : base(provider)
 {
 }
Beispiel #43
0
 public NPC(ResourceProvider provider)
     : base(provider)
 {
     Name = "NPC";
 }
Beispiel #44
0
 //Necessary Constructor
 public PickUp(ResourceProvider provider)
     : base(provider)
 {
 }
Beispiel #45
0
 public Router(ResourceProvider kernel)
 {
     if (kernel == null) throw new ArgumentNullException("kernel");
     _kernel = kernel;
 }
Beispiel #46
0
        protected override void Initialize()
        {
            Content.RootDirectory = "Content";

            // register this instance as a service
            ServiceRegistry.Register<UltimaGame>(this);

            // Create all the services we need.
            ServiceRegistry.Register<SpriteBatch3D>(new SpriteBatch3D(this));
            ServiceRegistry.Register<SpriteBatchUI>(new SpriteBatchUI(this));
            ServiceRegistry.Register<AudioService>(new AudioService());
            Network = ServiceRegistry.Register<INetworkClient>(new NetworkClient());
            Input = ServiceRegistry.Register<InputManager>(new InputManager(Window.Handle));
            UserInterface = ServiceRegistry.Register<UserInterfaceService>(new UserInterfaceService());
            Plugins = new PluginManager(AppDomain.CurrentDomain.BaseDirectory);

            // Make sure we have a UO installation before loading IO.
            if (FileManager.IsUODataPresent)
            {
                // Initialize and load data
                IResourceProvider provider = new ResourceProvider(this);
                provider.RegisterResource<EffectData>(new EffectDataResource());
                ServiceRegistry.Register<IResourceProvider>(provider);

                HueData.Initialize(GraphicsDevice);
                SkillsData.Initialize();
                GraphicsDevice.Textures[1] = HueData.HueTexture0;
                GraphicsDevice.Textures[2] = HueData.HueTexture1;

                IsRunning = true;
                WorldModel.IsInWorld = false;

                ActiveModel = new LoginModel();
            }
            else
            {
                Tracer.Critical("Did not find a compatible UO Installation. UltimaXNA is compatible with any version of UO through Mondian's Legacy.");
            }
        }
        public void TestInvalidMissingTokenScope()
        {
            ResourceContext context = new ResourceContext();

            ResourceProvider provider = new ResourceProvider();

            try
            {
                provider.ValidateScope(context, new string[] { "delete" });
                Assert.Fail("No exception was thrown");
            }
            catch (OAuthErrorResponseException<IResourceContext> x)
            {
                Assert.AreEqual(Parameters.ErrorParameters.ErrorValues.InvalidToken, x.Error);
                Assert.AreEqual(401, x.HttpStatusCode);
            }
            catch (Exception x)
            {
                Assert.Fail("Unexpected exception: " + x.Message);
            }
        }
Beispiel #48
0
 protected override void Initialize()
 {
     Content.RootDirectory = "Content";
     Service.Add(this);
     Service.Add(new SpriteBatch3D(this));
     Service.Add(new SpriteBatchUI(this));
     Service.Add<INetworkClient>(new NetworkClient());
     Service.Add<IInputService>(new InputService(Window.Handle));
     Service.Add(new AudioService());
     m_UserInterface = Service.Add(new UserInterfaceService());
     m_Plugins = new PluginManager(AppDomain.CurrentDomain.BaseDirectory);
     m_Models = new ModelManager();
     // Make sure we have a UO installation before loading IO.
     if (FileManager.IsUODataPresent)
     {
         // Initialize and load data
         IResourceProvider provider = new ResourceProvider(this);
         provider.RegisterResource(new EffectDataResource());
         Service.Add(provider);
         HueData.Initialize(GraphicsDevice);
         SkillsData.Initialize();
         GraphicsDevice.Textures[1] = HueData.HueTexture0;
         GraphicsDevice.Textures[2] = HueData.HueTexture1;
         m_IsRunning = true;
         WorldModel.IsInWorld = false;
         Models.Current = new LoginModel();
     }
     else
     {
         Tracer.Critical("Did not find a compatible UO Installation. UltimaXNA is compatible with any version of UO through Mondian's Legacy.");
     }
 }
Beispiel #49
0
 public AsyncRequestHandler(ResourceProvider provider, Request request, Action<Response> onresponse)
 {
     _onresponse = onresponse;
     _work = () => Response = provider.Get(request);
 }
 public MultithreadedResourceProviderFacade(ResourceProvider provider)
 {
     _provider = provider;
 }
Beispiel #51
0
 public Tower(Team team, ResourceProvider provider)
     : base(provider)
 {
     this.team = team;
 }
        public void TestValidScope()
        {
            ResourceContext context = new ResourceContext();
            context.Token = new AccessTokenBase { Scope = new[] { "create" } };

            ResourceProvider provider = new ResourceProvider();

            provider.ValidateScope(context, new string[] { "CREATE" });
        }
Beispiel #53
0
 //Necessary Constructor
 public Sprite( ResourceProvider provider )
 {
     this.provider = provider;
     this.active = false;
 }
        public void TestInvalidScope()
        {
            ResourceContext context = new ResourceContext();
            context.Token = new AccessTokenBase { Scope = new[] { "create" } };

            ResourceProvider provider = new ResourceProvider();

            try
            {
                provider.ValidateScope(context, new string[] { "delete" });
                Assert.Fail("No exception was thrown");
            }
            catch (OAuthErrorResponseException<IResourceContext> x)
            {
                Assert.AreEqual(Parameters.ErrorParameters.ErrorValues.InsufficientScope, x.Error);
                Assert.AreEqual(403, x.HttpStatusCode);
            }
            catch (Exception x)
            {
                Assert.Fail("Unexpected exception: " + x.Message);
            }
        }
Beispiel #55
0
 public AssemblyNode(TypeNodeProvider provider, TypeNodeListProvider listProvider,
   CustomAttributeProvider provideCustomAttributes, ResourceProvider provideResources, string directory)
     : base(provider, listProvider, provideCustomAttributes, provideResources)
 {
     this.Directory = directory;
     this.NodeType = NodeType.Assembly;
     this.ContainingAssembly = this;
 }
 private static void CommonErrorAssert(ResourceContext context, ResourceProvider provider, string error)
 {
     try
     {
         provider.AccessProtectedResource(context);
         Assert.Fail("No exception was thrown");
     }
     catch (OAuthErrorResponseException<IResourceContext> x)
     {
         Assert.AreEqual(error, x.Error);
     }
     catch (Exception x)
     {
         Assert.Fail("Unexpected exception was thrown:" + x.Message);
     }
 }
Beispiel #57
0
 public Module(TypeNodeProvider provider, TypeNodeListProvider listProvider, CustomAttributeProvider provideCustomAttributes, ResourceProvider provideResources)
     : base(NodeType.Module)
 {
     this.provideCustomAttributes = provideCustomAttributes;
     this.provideResources = provideResources;
     this.provideTypeNode = provider;
     this.provideTypeNodeList = listProvider;
     this.IsNormalized = true;
 }
 static ResourceProviders()
 {
     _current = EmptyResourceProvider.Instance;
     _editor = null;
 }
Beispiel #59
0
 public void RegisterResourceForwarder(Guid routeGroupId, string nriregex, ResourceProvider provider, long energy)
 {
     _routes.Add(new ForwardKernelRoute(routeGroupId, nriregex, energy,true,  provider));
 }
        public void TestAccessingExpiredTokenResource()
        {
            ResourceContext context = new ResourceContext();
            context.Headers = new NameValueCollection();
            context.Headers["Authorization"] = "bearer my-token";

			IAccessToken expiredToken = new AccessTokenBase
            {
                Token = "my-token",
                ExpiresIn = 2,
                IssuedOn = DateTime.Now.AddMinutes(-1).ToEpoch()
            };
            Mock<ContextProcessor<IResourceContext>> mckProvider = new Mock<ContextProcessor<IResourceContext>>(new Mock<IServiceFactory>().Object);
            mckProvider.Setup(x => x.IsSatisfiedBy(context)).Returns(true);
            mckProvider.Setup(x => x.Process(context)).Callback(() => context.Token = expiredToken);

            SimpleServiceLocator container = new SimpleServiceLocator();
            container.RegisterAll<ContextProcessor<IResourceContext>>(mckProvider.Object);

            ServiceLocator.SetLocatorProvider(() => container);

            ResourceProvider provider = new ResourceProvider();

            CommonErrorAssert(context, provider, Parameters.ErrorParameters.ErrorValues.InvalidToken);

            mckProvider.Verify();
        }