Esempio n. 1
0
        public static async Task <ImmutableArray <Color> > GetColorsAsync()
        {
            var settingsStore = await OptionsHelper.GetReadonlySettingsStoreAsync();

            if (!settingsStore.CollectionExists(CollectionName))
            {
                return(ImmutableArray <Color> .Empty);
            }

            var index  = 0;
            var colors = new Color[NumberOfSavedColors];

            foreach (var name in GetColorNames())
            {
                var colorInt = 0;
                try
                {
                    // In case we ever change the values we're storing we might
                    // fail to retrieve a color. That's okay, just leave it to the default color
                    // value
                    colorInt = settingsStore.GetInt32(CollectionName, name);
                }
                catch { }

                var color = ColorHelpers.ToColor((uint)colorInt);
                colors[index++] = color;
            }

            return(colors.ToImmutableArray());
        }
Esempio n. 2
0
 private void OkButton_Click(object sender, EventArgs e)
 {
     _options.Connection = ConnectionStringTextBox.Text;
     _options.DbType     = (DbEnum)Enum.Parse(typeof(DbEnum), DbTypeComboBox.Text);
     OptionsHelper.SaveOptions(_dte, _options);
     Close();
 }
        public MainWindowControlViewModel()
        {
            ThrowIfNotOnUIThread();

            var ss = ThreadHelper.JoinableTaskFactory.Run(() => OptionsHelper.GetWritableSettingsStoreAsync());

            if (ss.TryGetBoolean(
                    OptionsHelper.GeneralSettingsCollectionName,
                    nameof(UseExtraContrastSuggestions),
                    out var useExtraContrastSuggestions))
            {
                UseExtraContrastSuggestions = useExtraContrastSuggestions;
            }

            PropertyChanged += OnPropertyChanged;

            EditForegroundCommand     = new RelayCommand <IList>(OnEditForeground);
            EditBackgroundCommand     = new RelayCommand <IList>(OnEditBackground);
            ToggleIsBoldCommand       = new RelayCommand <IList>(OnToggleIsBold);
            ResetToDefaultsCommand    = new RelayCommand <IList>(OnResetToDefaults);
            ResetAllToDefaultsCommand = new RelayCommand(OnResetAllToDefaults);

            foreach (var item in ClassificationProvider.GridItems)
            {
                ClassificationGridItems.Add(item);
            }

            ClassificationGridView        = CollectionViewSource.GetDefaultView(ClassificationGridItems);
            ClassificationGridView.Filter = o => FilterClassification((GridItem)o);
            ClassificationGridView.SortDescriptions.Clear();
            ClassificationGridView.SortDescriptions.Add(new SortDescription(nameof(GridItem.DefinitionLocalizedName), ListSortDirection.Ascending));

            (FontFamily, FontSize) = FontsAndColorsHelper.GetEditorFontInfo();
        }
        public async void SendActivitiesAsyncShouldSucceedAndNoActivityReturnedWithActivityTypeNotMessage()
        {
            // Arrange
            var activity = new Mock <Activity>().SetupAllProperties();

            activity.Object.Type        = ActivityTypes.Trace;
            activity.Object.Attachments = new List <Attachment> {
                new Attachment(contentUrl: "http://example.com")
            };
            activity.Object.Conversation = new ConversationAccount(id: "MockId");
            activity.Object.Text         = "Trace content";

            const string resourceIdentifier = "ringCentralContentId";
            var          mockOptions        = new RingCentralOptions()
            {
                RingCentralEngageApiAccessToken = "1111",
                RingCentralEngageApiUrl         = "http://someurl.com",
                BotId = "testbot"
            };

            var rcw            = new Mock <RingCentralClientWrapper>(OptionsHelper.GetOptionsMonitor(mockOptions));
            var mockBotAdapter = new Mock <IBotFrameworkHttpAdapter>().Object;

            rcw.Setup(x => x.SendContentToRingCentralAsync(activity.Object, "9f4bba850e69dc636a707fd6")).Returns(Task.FromResult(resourceIdentifier));
            var adapter = new RingCentralAdapter(rcw.Object, mockBotAdapter, new StaticHandoffRequestRecognizer());

            // Act
            var resourceResponses = await adapter.SendActivitiesAsync(null, new Activity[] { activity.Object }, default).ConfigureAwait(false);

            // Assert
            Assert.True(resourceResponses.Length == 0);
        }
        public async Task GetActivityFromRingCentralRequestAsync_UnspecificSourceRequest_ReturnsContentImportedAndUnspecificChannelId(string jsonFile)
        {
            // Arrange
            var request  = new Mock <HttpRequest>();
            var response = new DefaultHttpContext().Response;

            response.Body = new MemoryStream();
            var ringCentralRequest = GetEmbeddedTestData($"{GetType().Namespace}.TestData.{jsonFile}");

            using var ms = new MemoryStream();
            using var sw = new StreamWriter(ms);
            sw.Write(ringCentralRequest);
            sw.Flush();
            ms.Position = 0;
            request.Setup(x => x.Body).Returns(ms);
            request.Setup(x => x.Path).Returns(PathString.FromUriComponent("/contentimport"));

            var mockOptions = new RingCentralOptions()
            {
                RingCentralEngageApiAccessToken = "abc", RingCentralEngageApiUrl = "http://localhost", BotId = "testbot", RingCentralEngageBotControlledThreadCategoryId = "botcontrolled"
            };
            var mockRingCentralClient = new Mock <DimeloClient>();

            var sut            = new RingCentralClientWrapper(OptionsHelper.GetOptionsMonitor(mockOptions), new StaticHandoffRequestRecognizer());
            var mockBotAdapter = new Mock <IBotFrameworkHttpAdapter>().Object;
            var adapter        = new RingCentralAdapter(sut, mockBotAdapter, new StaticHandoffRequestRecognizer());

            // Act
            var(ringCentralWebhook, activity) = await sut.GetActivityFromRingCentralRequestAsync(adapter, mockBotAdapter, request.Object, response);

            // Assert
            Assert.Equal(RingCentralHandledEvent.ContentImported, ringCentralWebhook);
            Assert.Equal(RingCentralChannels.Unspecific, activity.ChannelId);
        }
        public async Task GetActivityFromRingCentralRequestAsync_WhatsAppContentImportedMissingBodyText_ReturnsUnknownEventAndNullActivity(string jsonFile)
        {
            // Arrange
            var request            = new Mock <HttpRequest>();
            var response           = new Mock <HttpResponse>();
            var ringCentralRequest = GetEmbeddedTestData($"{GetType().Namespace}.TestData.{jsonFile}");

            using var ms = new MemoryStream();
            using var sw = new StreamWriter(ms);
            sw.Write(ringCentralRequest);
            sw.Flush();
            ms.Position = 0;
            request.Setup(x => x.Body).Returns(ms);
            request.Setup(x => x.Path).Returns(PathString.FromUriComponent("/contentimport"));
            response.Setup(x => x.Body).Returns(new MemoryStream());

            var mockOptions = new RingCentralOptions()
            {
                RingCentralEngageApiAccessToken = "abc", RingCentralEngageApiUrl = "http://localhost", BotId = "testbot", RingCentralEngageBotControlledThreadCategoryId = "botcontrolled"
            };
            var mockRingCentralClient = new Mock <DimeloClient>();

            var sut            = new RingCentralClientWrapper(OptionsHelper.GetOptionsMonitor(mockOptions), new StaticHandoffRequestRecognizer());
            var mockBotAdapter = new Mock <IBotFrameworkHttpAdapter>().Object;
            var adapter        = new RingCentralAdapter(sut, mockBotAdapter, new StaticHandoffRequestRecognizer());

            // Act
            var(ringCentralWebhook, activity) = await sut.GetActivityFromRingCentralRequestAsync(adapter, mockBotAdapter, request.Object, response.Object);

            // Assert
            Assert.Equal(RingCentralHandledEvent.Unknown, ringCentralWebhook);
            Assert.Null(activity);
            response.VerifySet(x => x.StatusCode = StatusCodes.Status204NoContent);
        }
        public async void DeleteActivityAsyncShouldThrowNotSupportedException()
        {
            // Arrange
            var mockBotAdapter = new Mock <IBotFrameworkHttpAdapter>().Object;
            var mockOptions    = new RingCentralOptions()
            {
                RingCentralEngageApiAccessToken = "1111",
                RingCentralEngageApiUrl         = "http://someurl.com",
                BotId = "testbot"
            };
            var rcw      = new RingCentralClientWrapper(OptionsHelper.GetOptionsMonitor(mockOptions), new StaticHandoffRequestRecognizer());
            var adapter  = new RingCentralAdapter(rcw, mockBotAdapter, new StaticHandoffRequestRecognizer());
            var activity = new Activity();
            var conversationReference = new ConversationReference();

            // Act
            using (var turnContext = new TurnContext(adapter, activity))
            {
                // Assert
                await Assert.ThrowsAsync <NotImplementedException>(async() =>
                {
                    await adapter.DeleteActivityAsync(turnContext, conversationReference, default);
                });
            }
        }
        public void ToQueryParameters_WhenAllPropertyNotDefault_Return_AllProperties()
        {
            // Arrange
            var options = new ChangesFeedOptions
            {
                Conflicts          = true,
                Descending         = true,
                Filter             = Guid.NewGuid().ToString(),
                Heartbeat          = 1,
                IncludeDocs        = true,
                Attachments        = true,
                AttachEncodingInfo = true,
                Limit       = 1,
                Since       = Guid.NewGuid().ToString(),
                Style       = ChangesFeedStyle.AllDocs,
                Timeout     = 1,
                View        = Guid.NewGuid().ToString(),
                SeqInterval = 1
            };

            // Act
            var parameters = OptionsHelper.ToQueryParameters(options);

            // Assert
            Assert.Equal(13, parameters.Count());
        }
Esempio n. 9
0
        private ImmutableDictionary <string, bool> BuildRuleMapFromOptions()
        {
            var result = new Dictionary <string, bool>();

            var propertyBag = OptionsHelper.BuildDefaultPropertyBag();

            if (!string.IsNullOrEmpty(OptionsFilePath))
            {
                propertyBag.LoadFrom(OptionsFilePath);
            }

            propertyBag = (PropertyBag)propertyBag["CodeFormatterRules.Options"];
            foreach (string key in propertyBag.Keys)
            {
                string[] tokens = key.Split('.');
                Debug.Assert(tokens.Length == 2);
                Debug.Assert(tokens[1].Equals("Enabled"));

                string rule = tokens[0];
                result[rule] = (bool)propertyBag[key];
            }

            _ruleMap = result.ToImmutableDictionary();
            return(_ruleMap);
        }
Esempio n. 10
0
 public void Init()
 {
     if (m_Helper == null)
     {
         m_Helper = OptionsHelper.Get(serializedObject.targetObject.GetType());
     }
 }
        public async Task VerifyWebhookAsync_MissingHubChallenge_ReturnsBadRequest()
        {
            // Arrange
            var request  = new Mock <HttpRequest>();
            var response = new Mock <HttpResponse>();

            string webhookChallengeCode = "5af96abed0b2fc27a017bf5a7e961dd9";
            string webhookToken         = "abc123";

            request.Setup(x => x.QueryString).Returns(QueryString.FromUriComponent($"?hub.mode=subscribe&hub.verify_token={webhookToken}"));
            response.Setup(x => x.Body).Returns(new MemoryStream());

            var mockOptions = new RingCentralOptions()
            {
                RingCentralEngageApiAccessToken = "abc", RingCentralEngageApiUrl = "http://localhost", BotId = "testbot", RingCentralEngageWebhookValidationToken = "incorrect_token"
            };
            var sut = new RingCentralClientWrapper(OptionsHelper.GetOptionsMonitor(mockOptions), new StaticHandoffRequestRecognizer());

            // Act
            await sut.VerifyWebhookAsync(request.Object, response.Object, It.IsAny <CancellationToken>());

            response.Object.Body.Position = 0;
            using var sr = new StreamReader(response.Object.Body);
            var responseBody = sr.ReadToEnd();

            // Assert
            Assert.NotEqual(webhookChallengeCode, responseBody);
            response.VerifySet(x => x.StatusCode = StatusCodes.Status400BadRequest);
        }
Esempio n. 12
0
        public Dialog_Options(OptionsHelper options)
        {
            this._options = options;

            this.doCloseButton = true;
            this.doCloseX      = true;
        }
Esempio n. 13
0
        private static IServiceCollection AddSecurityForUI(this IServiceCollection services, BaseStartup startup)
        {
            var config = OptionsHelper.GetConfiguration <SecurityUIOptions>(startup.Configuration);

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = "Cookies";

                options.Authority            = config.Authority;
                options.RequireHttpsMetadata = false;

                options.ClientId     = config.ClientId;
                options.ClientSecret = config.ClientSecret;
                options.ResponseType = "code id_token";

                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;

                foreach (var item in config.Scopes)
                {
                    options.Scope.Add(item);
                }
            });

            return(services);
        }
        public async Task GetActivityFromRingCentralRequestAsync_ImplementationInfoRequest_ReturnsActionAndNullActivity(string jsonFile)
        {
            // Arrange
            var request  = new Mock <HttpRequest>();
            var response = new DefaultHttpContext().Response;

            response.Body = new MemoryStream();
            var ringCentralRequest = GetEmbeddedTestData($"{GetType().Namespace}.TestData.{jsonFile}");

            using var ms = new MemoryStream();
            using var sw = new StreamWriter(ms);
            sw.Write(ringCentralRequest);
            sw.Flush();
            ms.Position = 0;
            request.Setup(x => x.Body).Returns(ms);
            request.Setup(x => x.Path).Returns(PathString.FromUriComponent("/action"));

            var mockOptions = new RingCentralOptions()
            {
                RingCentralEngageApiAccessToken = "abc", RingCentralEngageApiUrl = "http://localhost", BotId = "testbot"
            };
            var sut            = new RingCentralClientWrapper(OptionsHelper.GetOptionsMonitor(mockOptions), new StaticHandoffRequestRecognizer());
            var mockBotAdapter = new Mock <IBotFrameworkHttpAdapter>().Object;
            var adapter        = new RingCentralAdapter(sut, mockBotAdapter, new StaticHandoffRequestRecognizer());

            // Act
            var(ringCentralWebhook, activity) = await sut.GetActivityFromRingCentralRequestAsync(adapter, mockBotAdapter, request.Object, response);

            // Assert
            Assert.Equal(RingCentralHandledEvent.Action, ringCentralWebhook);
            Assert.Null(activity);
            Assert.Equal(StatusCodes.Status200OK, response.StatusCode);
        }
Esempio n. 15
0
        public ActionResult GetEventsInfo(Int32 page)
        {
            HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            var result = PTCore.Instance.GetEventsInfo(OptionsHelper.GetServerFromCookies(this),
                                                       OptionsHelper.GetListFromCookies(this), page);

            return(Json(result ?? new object(), JsonRequestBehavior.AllowGet));
        }
Esempio n. 16
0
        public void GetSection_Success()
        {
            var teste = OptionsHelper.GetSection <TestOptions>(Configuration);

            Assert.AreEqual("string", teste["OptionString"]);
            Assert.AreEqual("999", teste["OptionInteger"]);
            Assert.AreEqual("True", teste["OptionBoolean"]);
            Assert.AreEqual("99.1", teste["OptionDouble"]);
        }
Esempio n. 17
0
 public ExplicitThisAnalyzerTests()
 {
     OptionsHelper.GetPropertiesImplementation = (analyzerOptions) =>
     {
         PropertyBag properties = CreatePolicyThatDisablesAllAnalysis();
         properties.SetProperty(OptionsHelper.BuildDefaultEnabledProperty(ExplicitThisAnalyzer.AnalyzerName), true);
         return(properties);
     };
 }
Esempio n. 18
0
        public MongoDbFixture()
        {
            var options = OptionsHelper.GetOptions <MongoDbOptions>("mongo");

            _client       = new MongoClient(options.ConnectionString);
            _databaseName = options.Database;
            _database     = _client.GetDatabase(_databaseName);
            //InitializeMongo();
        }
Esempio n. 19
0
        public void GetConfiguration_Success()
        {
            var teste = OptionsHelper.GetConfiguration <TestOptions>(Configuration);

            Assert.AreEqual("string", teste.OptionString);
            Assert.AreEqual(999, teste.OptionInteger);
            Assert.AreEqual(true, teste.OptionBoolean);
            Assert.AreEqual(99.1, teste.OptionDouble);
        }
Esempio n. 20
0
        protected void Init(SerializedProperty property)
        {
            if (m_Helper == null)
            {
                m_Helper = OptionsHelper.Get(fieldInfo.FieldType);
            }

            m_Property = property;
        }
Esempio n. 21
0
 public PlaceImportsOutsideNamespaceTests()
 {
     OptionsHelper.GetPropertiesImplementation = (analyzerOptions) =>
     {
         PropertyBag properties = CreatePolicyThatDisablesAllAnalysis();
         properties.SetProperty(OptionsHelper.BuildDefaultEnabledProperty(PlaceImportsOutsideNamespaceAnalyzer.AnalyzerName), true);
         return(properties);
     };
 }
Esempio n. 22
0
        protected PropertyBag CreatePolicyThatDisablesAllAnalysis()
        {
            PropertyBag propertyBag = OptionsHelper.BuildDefaultPropertyBag();

            foreach (string analyzerName in OptionsHelper.AllAnalyzerNames)
            {
                propertyBag.SetProperty(OptionsHelper.BuildDefaultEnabledProperty(analyzerName), false);
            }
            return(propertyBag);
        }
Esempio n. 23
0
        virtual public void Run()
        {
            Console.Clear();

            text          = sceneArt + "\n" + HelperFunctions.ArtReadHelper.write(addText) + "\n\n";
            opt_helper    = new OptionsHelper(text, options);
            optionsChoice = opt_helper.MenuChoice();
            // Runs the actual scene logic
            // Override in child classes
        }
Esempio n. 24
0
        public void ThrowsExceptionGivenNullValue()
        {
            var optionsWithValorNull = OptionsHelper.CreateOptionSnapshotMock(new TaxaJurosOptions {
                Valor = null
            });

            Func <TaxaJurosService> sut = () => new TaxaJurosService(optionsWithValorNull);

            sut.Should().Throw <Exception>();
        }
Esempio n. 25
0
 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     try
     {
         dispatcher.Ecu.Stop();
         OptionsHelper.SaveSettings();
         dispatcher.DatFile.Dispose();
     }
     catch
     { }
 }
Esempio n. 26
0
        public MongoDbFixture(string collectionName)
        {
            var options = OptionsHelper.GetOptions <MongoDbOptions>("mongo");

            _client         = new MongoClient(options.ConnectionString);
            _databaseName   = options.Database;
            _collectionName = collectionName;
            _database       = _client.GetDatabase(_databaseName);
            //InitializeMongo();
            _collection = _database.GetCollection <TEntity>(_collectionName);
        }
Esempio n. 27
0
        public static async Task SaveColorAsync(Color color, int index)
        {
            var settingsStore = await OptionsHelper.GetWritableSettingsStoreAsync();

            if (!settingsStore.CollectionExists(CollectionName))
            {
                settingsStore.CreateCollection(CollectionName);
            }

            settingsStore.SetInt32(CollectionName, $"Color{index}", ColorHelpers.ToInt(color));
        }
Esempio n. 28
0
        public async Task ReturnsCorrectValue(decimal valor)
        {
            var options = OptionsHelper.CreateOptionSnapshotMock(new TaxaJurosOptions {
                Valor = valor
            });
            var sut = new TaxaJurosService(options);

            decimal result = await sut.GetTaxaAtual();

            result.Should().Be(valor);
        }
        public void ToQueryParameters_WhenDefault_Return_NoProperties()
        {
            // Arrange
            var options = new ChangesFeedOptions();

            // Act
            var parameters = OptionsHelper.ToQueryParameters(options);

            // Assert
            Assert.Empty(parameters);
        }
Esempio n. 30
0
        public OptionsDialog(DTE dte)
        {
            InitializeComponent();

            _dte     = dte;
            _options = OptionsHelper.GetOptions(dte);
            ConnectionStringTextBox.Text = _options.Connection;

            DbTypeComboBox.Items.AddRange(Enum.GetNames(typeof(DbEnum)));
            DbTypeComboBox.Text = _options.DbType.ToString();
        }