protected override void Arrange()
        {
            base.Arrange();

            var resources = new ResourceHelper<ConfigFileLocator>();
            resources.DumpResourceFileToDisk("empty.config");

            var applicationViewModel = Container.Resolve<ApplicationViewModel>();
            ConfigurationSourceModel sourceModel = applicationViewModel.CurrentConfigurationSource;
            applicationViewModel.NewEnvironment();

            EhabModel = sourceModel.AddSection(ExceptionHandlingSettings.SectionName, Section);
            EnvironmentViewModel = applicationViewModel.Environments.First();
            EnvironmentSection = (EnvironmentalOverridesSection)EnvironmentViewModel.ConfigurationElement;

            ((EnvironmentSourceViewModel)EnvironmentViewModel).EnvironmentConfigurationFile = "empty.config";
            ((EnvironmentSourceViewModel)EnvironmentViewModel).EnvironmentDeltaFile = "empty.config";

            WrapHandler = EhabModel.DescendentElements().Where(x => x.ConfigurationType == typeof(WrapHandlerData)).First();

            MainExceptionMessage = WrapHandler.Property("ExceptionMessage");
            MainExceptionMessage.Value = "Main Value";

            OverridesProperty = WrapHandler.Properties.Where(x => x.PropertyName.StartsWith("Overrides")).First(); 
            OverriddenExceptionMessage = OverridesProperty.ChildProperties.Where(x => x.PropertyName == "ExceptionMessage").First();
        }
        /// <summary>
        /// 保存
        /// </summary>
        public static void Save()
        {
            ResourceHelper resourceHelper = new ResourceHelper(SystemConfigTagPath);

            resourceHelper.SetObject(SystemConfigTagKey, m_SystemConfigTag);

            resourceHelper.Save();
        }
        protected override void Arrange()
        {
            base.Arrange();

            var resources = new ResourceHelper<ConfigFileLocator>();
            mainConfigurationFile = resources.DumpResourceFileToDisk("ehab_lab_and_daab.config");
            mergedConfigurationFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                       "ehab_lab_and_daab_merged.config");
        }
 public TestDriverConfigGenerator()
 {
     var resourceHelper = new ResourceHelper(typeof(IJobSubmissionResult).Assembly);
     var fileName = resourceHelper.GetString(ResourceHelper.DriverJarFullName);
     if (!File.Exists(fileName))
     {
         File.WriteAllBytes(fileName, 
             resourceHelper.GetBytes(ResourceHelper.FileResources[ResourceHelper.DriverJarFullName]));
     }
 }
        /// <summary>
        /// 初始化
        /// </summary>
        public static void Init()
        {
            //初始化系统配置
            if (File.Exists(SystemConfigTagPath))
            {
                ResourceHelper resourceHelper = new ResourceHelper(SystemConfigTagPath);

                m_SystemConfigTag = resourceHelper.GetObject(SystemConfigTagKey) as SystemConfigTag;
            }
        }
        protected override void Act()
        {
            var resources = new ResourceHelper<ConfigFileLocator>();
            var deltaConfigurationFile = resources.DumpResourceFileToDisk("override_lab_protection_dpapi.dconfig");
            
            ConfigurationMerger configurationMerger = new ConfigurationMerger(mainConfigurationFile, deltaConfigurationFile);
            configurationMerger.MergeConfiguration(mergedConfigurationFile);

            mergedConfigurationFileSource = new FileConfigurationSource(mergedConfigurationFile);
        }
        protected override void Arrange()
        {
            base.Arrange();

            var resources = new ResourceHelper<ConfigFileLocator>();
            var localFilename = resources.DumpResourceFileToDisk("systemweb_and_el.config");
            
            applicationModel = Container.Resolve<IApplicationModel>();
            applicationModel.Load(localFilename);

            saveAsTargetFileName = localFilename.Replace(".config", ".saveas.config");
        }
        protected override void Arrange()
        {
            base.Arrange();

            var resourceHelper = new ResourceHelper<ConfigFiles.ConfigFileLocator>();
            mainFilePath = resourceHelper.DumpResourceFileToDisk("empty.config", "ds_inv_rel_path");
            mainConfigurationSource = new DesignConfigurationSource(mainFilePath);

            configurationSourceElement = new FileConfigurationSourceElement("relativefile", "doesnt-exist\\relative.config");

            var mainFileDirectory = Path.GetDirectoryName(mainFilePath);
            expectedFilePath = Path.Combine(mainFileDirectory, configurationSourceElement.FilePath);
        }
        protected override void Arrange()
        {
            base.Arrange();

            UIServiceMock.Setup(x => x.ShowWindow(It.IsAny<Window>()));
            UIServiceMock.Setup(
                x => x.ShowMessageWpf(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MessageBoxButton>())).Returns(
                MessageBoxResult.OK);

            var resources = new ResourceHelper<ConfigFileLocator>();
            resources.DumpResourceFileToDisk(sourceFileName);

            applicationModel = Container.Resolve<IApplicationModel>();
        }
        protected override void Arrange()
        {
            base.Arrange();

            var resources = new ResourceHelper<ConfigFileLocator>();
            resources.DumpResourceFileToDisk("configurationsource_main_with_missing.config");

            designSource = new DesignConfigurationSource("configurationsource_main_with_missing.config");
            configurationSourceModel = Container.Resolve<ConfigurationSourceModel>();

            UIServiceMock.Setup(x => x.ShowWindow(It.IsAny<Window>()));
            UIServiceMock.Setup(
                x => x.ShowMessageWpf(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<MessageBoxButton>()))
                .Returns(MessageBoxResult.OK).Verifiable("Message not invoked");
        }
        protected override void Arrange()
        {
            base.Arrange();

            var resourceHelper = new ResourceHelper<ConfigFiles.ConfigFileLocator>();
            mainFilePath = resourceHelper.DumpResourceFileToDisk("empty.config", "ds_abs_ro_path");
            mainConfigurationSource = new DesignConfigurationSource(mainFilePath);

            var mainFileDirectory = Path.GetDirectoryName(mainFilePath);
            expectedFilePath = Path.Combine(mainFileDirectory, "absolutefile.config");

            configurationSourceElement = new FileConfigurationSourceElement("absolutefile", expectedFilePath);
            File.WriteAllText(expectedFilePath, "<configuration/>");
            File.SetAttributes(expectedFilePath, FileAttributes.ReadOnly);
        }
        protected override void Arrange()
        {
            base.Arrange();

            var resourceHelper = new ResourceHelper<ConfigFiles.ConfigFileLocator>();
            string resourceFile = "configuration_with_all_blocks.config";
            resourceHelper.DumpResourceFileToDisk(resourceFile);
            configFilePath = Path.Combine(Environment.CurrentDirectory, resourceFile);

            appModel = base.Container.Resolve<ApplicationViewModel>();
            appModel.Load(configFilePath);

            elementsWeakReference = appModel.CurrentConfigurationSource.Sections.SelectMany(s => s.DescendentElements().Union(new[] {s}))
                .Select(x => new WeakReference(x)).ToArray();

        }
        protected override void Arrange()
        {
            base.Arrange();
            base.Arrange();

            var resourceHelper = new ResourceHelper<ConfigFiles.ConfigFileLocator>();
            mainFilePath = resourceHelper.DumpResourceFileToDisk("empty.config", "ds_mgmt_subdir_path");
            mainConfigurationSource = new DesignConfigurationSource(mainFilePath);

            configurationSourceElement = new ManageableConfigurationSourceElement("relativefile", "subdir\\relative.config", "app");

            var mainFileDirectory = Path.GetDirectoryName(mainFilePath);
            expectedFilePath = Path.Combine(mainFileDirectory, configurationSourceElement.FilePath);

            Directory.CreateDirectory(Path.GetDirectoryName(expectedFilePath));
        }
        public void then_require_permission_property_has_xpath_that_resolves()
        {
            Property requirePermissionProperty = LoggingSectionViewModel.Properties.Where(x => x.PropertyName == "Require Permission").Single();

            var resources = new ResourceHelper<ConfigFileLocator>();
            resources.DumpResourceFileToDisk("logging_require_permission.config");

            string configFileDir = AppDomain.CurrentDomain.BaseDirectory;
            string configFilePath = Path.Combine(configFileDir, "logging_require_permission.config");

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(File.ReadAllText(configFilePath));


            var element = xmlDocument.SelectSingleNode(((IEnvironmentalOverridesProperty)requirePermissionProperty).ContainingElementXPath);
            Assert.IsNotNull(element);
            Assert.IsNotNull(element.Attributes[((IEnvironmentalOverridesProperty)requirePermissionProperty).PropertyAttributeName]);
        }
Exemple #15
0
        void btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                int olderDays = 0;
                int.TryParse(txtOlderDays.Text, out olderDays);
                olderDays = Math.Abs(olderDays);

                DateTime cutoffDate = DateTime.Now.AddDays(-olderDays);
                if (ShoppingCartItem.DeleteOlderThan(SiteId, Convert.ToInt32(ddlCartType.SelectedValue), cutoffDate))
                {
                    LogActivity.Write("Delete cart older " + cutoffDate + " day(s)", "Cart");
                    message.SuccessMessage = ResourceHelper.GetResourceString("Resource", "DeleteSuccessMessage");

                    grid.Rebind();
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
Exemple #16
0
        public Notifier(IConfig config, IMessenger messenger, IDispatcher dispatcher, IViewServiceRepository viewServices)
        {
            Dispatcher        = dispatcher;
            MessengerInstance = messenger;
            Config            = config;
            ViewServices      = viewServices;

            if (config.Notifications.SoundEnabled)
            {
                Player = new MediaPlayer();
                string soundFileName = File.Exists(config.Notifications.SoundFileName)
                                        ? config.Notifications.SoundFileName
                                        : ResourceHelper.GetDefaultNotificationSound();

                Player.Open(new Uri(soundFileName));
            }

            if (config.Notifications.PopupEnabled)
            {
                PopupNotify = new NotifyIcon();
            }
        }
Exemple #17
0
        public MentorController()
        {
            ViewBag.UserId       = base._userId;
            ViewBag.Logs         = ContactLogHelper.GetContactLogsByMentorId(ref this._db, _userId).Take(3);
            ViewBag.Messages     = MessagingHelper.GetMessagesToUserId(ref this._db, _userId).Take(3);
            ViewBag.Events       = CalendarHelper.GetEventsByUserId(ref this._db, _userId).Take(3);
            ViewBag.Resources    = ResourceHelper.GetResources(ref this._db).Take(3);
            ViewBag.Mentees      = MentorHelper.GetMenteesDropdownList(ref this._db);
            ViewBag.Ministries   = MinistryHelper.GetMinistriesDropdownList(ref this._db);
            ViewBag.ContactTypes = this._db.ContactTypes;
            ViewBag.Ministries   = _db.MinistriesList;
            ViewBag.States       = _db.StateList;
            ViewBag.Cities       = _db.CityList;
            ViewBag.Prefixes     = _db.Prefixes;
            ViewBag.Suffixes     = _db.Suffixes;
            ViewBag.Genders      = _db.Genders;
            ViewBag.Races        = _db.Races;
            ViewBag.YesNoList    = _db.YesNoList;

            Mapper.CreateMap <ContactLog, ContactLogViewModel>();
            Mapper.CreateMap <ContactLogViewModel, ContactLog>();
        }
        protected override void OnWebResponseReceived(WebResponse response)
        {
            LiveOperationResult opResult = this.CreateOperationResultFrom(response);

            if (opResult.Error != null)
            {
                this.OnOperationCompleted(opResult);
                return;
            }

            string uploadLink = null;

            if (opResult.Result != null && opResult.Result.ContainsKey(UploadLocationKey))
            {
                uploadLink = opResult.Result[UploadLocationKey] as string;
            }

            if (string.IsNullOrEmpty(uploadLink))
            {
                var error = new LiveConnectException(ApiOperation.ApiClientErrorCode,
                                                     ResourceHelper.GetString("NoUploadLinkFound"));
                opResult = new LiveOperationResult(error, false);
            }
            else
            {
                try
                {
                    Uri resourceUploadUrl = this.ConstructUploadUri(uploadLink);

                    opResult = new LiveOperationResult(null, resourceUploadUrl.OriginalString);
                }
                catch (LiveConnectException exp)
                {
                    opResult = new LiveOperationResult(exp, false);
                }
            }

            this.OnOperationCompleted(opResult);
        }
    public void ShowStar(Vector3 translate)
    {
        FreeStar();


        DataMission   dataMission  = _dataCampaign.missions [_selectTileIndex];
        Model_Mission modelMission = InstancePlayer.instance.model_User.model_level.GetMission(dataMission.magicId);

        string animName = "no_star";

        if (modelMission.starCount == 1)
        {
            animName = "01";
        }
        if (modelMission.starCount == 2)
        {
            animName = "02";
        }
        if (modelMission.starCount == 3)
        {
            animName = "03";
        }


        Vector3 tileCenter = GetTileCenter(_selectTileIndex);

        tileCenter.y += 70;
        tileCenter.z  = -1;
        tileCenter   += translate;

        string spineName = AppConfig.FOLDER_PROFAB_CAMPAIGN + "Star";

        _skeletonStar = ResourceHelper.Load(spineName);
        _skeletonStar.transform.position = tileCenter;

        SkeletonAnimation anim = _skeletonStar.GetComponentInChildren <SkeletonAnimation> ();

        anim.state.SetAnimation(0, animName, false);
    }
        void PasswordRulesValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            CustomValidator validator = source as CustomValidator;

            validator.ErrorMessage = string.Empty;

            if (args.Value.Length < Membership.MinRequiredPasswordLength)
            {
                args.IsValid = false;
                validator.ErrorMessage
                    += ResourceHelper.GetResourceString("Resource", "RegisterPasswordMinLengthWarning")
                       + Membership.MinRequiredPasswordLength.ToString(CultureInfo.InvariantCulture) + "<br />";
            }

            if (!HasEnoughNonAlphaNumericCharacters(args.Value))
            {
                args.IsValid = false;
                validator.ErrorMessage
                    += ResourceHelper.GetResourceString("Resource", "RegisterPasswordMinNonAlphaCharsWarning")
                       + Membership.MinRequiredNonAlphanumericCharacters.ToString(CultureInfo.InvariantCulture) + "<br />";
            }
        }
        private void PopulateLabels()
        {
            PasswordRegex.ValidationExpression = Membership.Provider.PasswordStrengthRegularExpression;

            string passwordRegexWarning = MessageTemplate.GetMessage("PasswordStrengthErrorMessage");

            if (passwordRegexWarning.Length > 0)
            {
                PasswordRegex.ErrorMessage = passwordRegexWarning;
                PasswordRegex.ToolTip      = passwordRegexWarning;
            }
            else
            {
                PasswordRegex.ErrorMessage = ResourceHelper.GetResourceString("Resource", "RegisterPasswordRegexWarning");
                PasswordRegex.ToolTip      = ResourceHelper.GetResourceString("Resource", "RegisterPasswordRegexWarning");
            }

            if (Membership.Provider.PasswordStrengthRegularExpression.Length == 0)
            {
                PasswordRegex.Visible = false;
            }
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void btnSave_Click(object sender, EventArgs e)


        {
            try
            {
                if (DateTime.Parse(dtPostedDate.Text) < DateTime.Parse(GlobalVariable.SystemDate))
                {
                    XtraMessageBox.Show(ResourceHelper.GetResourceValueByName("ResPostedDateLessSysemDate"), ResourceHelper.GetResourceValueByName("ResDetailContent"),
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    var message = _dbOptionsPresenter.Save();
                    if (message != null)
                    {
                        XtraMessageBox.Show(message, ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    GlobalVariable.PostedDate  = dtPostedDate.Text;
                    GlobalVariable.StartedDate = dtPostedDate.Text;//LINHMC gan lai de luu lai gia tri thay doi ngay hach toan
                    //_dbOptionsPresenter.Display();
                    Close();
                }
                //else
                //{
                //    var message = _dbOptionsPresenter.Save();
                //    if (message != null)
                //        XtraMessageBox.Show(message, ResourceHelper.GetResourceValueByName("ResDetailContent"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                //    _globalVariable.PostedDate = dtPostedDate.EditValue.ToString();
                //    GlobalVariable.StartedDate = dtPostedDate.EditValue.ToString();//LINHMC gan lai de luu lai gia tri thay doi ngay hach toan
                //    _dbOptionsPresenter.Display();
                //    Close();
                //}
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, ResourceHelper.GetResourceValueByName("ResExceptionCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void CCACreatedWithAuthenticationType_ClientCertificateWithNoClaims_DoesNotThrow()
        {
            // Arrange
            var cert = new X509Certificate2(
                ResourceHelper.GetTestResourceRelativePath("testCert.crtfile"), "passw0rd!");
            var claims = new Dictionary <string, string>();
            ApplicationConfiguration config = new ApplicationConfiguration
            {
                ClientCredentialCertificate = cert,
                ClaimsToSign = claims,
                ConfidentialClientCredentialCount = 1
            };

            // Act
            ClientCredentialWrapper clientCredentialWrapper = new ClientCredentialWrapper(config);

            // Assert
            // no exception is thrown
            Assert.AreEqual(
                ConfidentialClientAuthenticationType.ClientCertificate,
                clientCredentialWrapper.AuthenticationType);
        }
        public void CopyProfile(string name)
        {
            string pathToProfile = Path.Combine(Sys.PathToProfiles, $"{name}.xml");

            if (!File.Exists(pathToProfile))
            {
                Logger.Warn($"{ResourceHelper.Get(StringKey.ProfileDoesNotExist)}: {pathToProfile}");
                ReloadProfiles();
                return;
            }

            string newProfileName = null;

            try
            {
                newProfileName = InputNewProfileName(ResourceHelper.Get(StringKey.EnterProfileNameForTheCopy), ResourceHelper.Get(StringKey.CopyProfile));

                if (newProfileName == null)
                {
                    return; // user canceled inputting a profile name
                }

                File.Copy(pathToProfile, Path.Combine(Sys.PathToProfiles, $"{newProfileName}.xml"));

                string successMsg = string.Format(ResourceHelper.Get(StringKey.SuccessfullyCopiedProfile), name, newProfileName);
                Sys.Message(new WMessage(successMsg, true));

                ReloadProfiles();
                SelectedProfile = newProfileName;
            }
            catch (Exception e)
            {
                string errorMsg = string.Format(ResourceHelper.Get(StringKey.FailedToCopyProfile), name, newProfileName);
                Sys.Message(new WMessage(errorMsg, true)
                {
                    LoggedException = e
                });
            }
        }
Exemple #25
0
 static void Main()
 {
     DevExpress.Skins.SkinManager.EnableFormSkins();
     DevExpress.UserSkins.BonusSkins.Register();
     System.Windows.Forms.Application.EnableVisualStyles();
     System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
     ResourceHelper.ResourceLanguage = "vi-VN";
     System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(ResourceHelper.ResourceLanguage);
     ResourceHelper.InitResource();
     RegistryHelper.RemoveConnectionString();
     try
     {
         if (!RegistryHelper.GetValueByRegistryKey("DatabaseName").Equals("master") && !string.IsNullOrEmpty(RegistryHelper.GetValueByRegistryKey("DatabasePath")))
         {
             RegistryHelper.SaveConfigFile();
         }
     }
     catch (Exception ex)
     {
     }
     System.Windows.Forms.Application.Run(new MainRibbonForm());
 }
Exemple #26
0
        public void TestReadClientWhiteListKeyword(bool isSingle)
        {
            string value = isSingle ? nameKeyword : string.Format("{0},{1}", nameKeyword, memoKeyword);
            Dictionary <string, object> parameters = new Dictionary <string, object>()
            {
                { Parttion, AuthenticationInfoProvider.Current.DefaultPartition },
                { "keywords", value }
            };
            ReadResponseData <Client> result = PublicApiAdapter.CreateAdapterForDefaultConnection().ReadSuccess <Client>(parameters);

            Assert.AreEqual(Enums.PublicAPIResultCode.Success, result.Code,
                            string.Format(Enums.Message.READ_RESOURCE_FAILED, "Client"));

            //Verify existing of XML element
            ResourceHelper.VerifyListContainElement(result.Items, fields.Keys.ToList());

            //Verify the Count/Start/Total
            Assert.AreEqual(result.Start, 0, Enums.Message.START_ERROR);
            Assert.LessOrEqual(result.Count, 10, Enums.Message.COUNT_ERROR); //Default: 10
            Assert.Greater(result.Total, isSingle? 0 : 1, Enums.Message.TOTAL_ERROR);

            //Verify the type of fields in fieldList
            ResourceHelper.VerifyTypeOfField(result.Items, fields);

            //Verify the keyword
            foreach (Client client in result.Items)
            {
                if (isSingle)
                {
                    StringAssert.Contains(nameKeyword, client.Name,
                                          string.Format(Enums.Message.KEYWORD_NOT_MATCH, isSingle, "Client's Name", value));
                }
                else
                {
                    Assert.IsTrue(client.Name.Contains(nameKeyword) || client.Memo.Contains(memoKeyword),
                                  string.Format(Enums.Message.KEYWORD_NOT_MATCH, isSingle, "Client's Memo & Name", value));
                }
            }
        }
Exemple #27
0
        private void GetCartInfo()
        {
            if ((!includeItemCount) && (!includeCartTotal))
            {
                return;
            }



            siteSettings = CacheHelper.GetCurrentSiteSettings();

            currencyCulture = ResourceHelper.GetCurrencyCulture(siteSettings.GetCurrency().Code);

            cart = StoreHelper.GetCartIfExists(moduleGuid, Page.Request.IsAuthenticated);
            if (cart == null)
            {
                return;
            }

            itemCount = cart.CartOffers.Count();
            cartTotal = cart.SubTotal;
        }
    override public void ExtendedUpdate()
    {
        if (need_update)
        {
            Dress();

            Message msg = new Message();
            msg.Type = MainScene.MainMenuMessageType.INIT_BOUGHT_ITEM;
            var param = new MainScene.BuyItemParametr();
            foreach (string name in wear_entity.content.bought_textures)
            {
                param.item_texture = ResourceHelper.LoadTexture(name);
                msg.parametrs      = param;
                MessageBus.Instance.SendMessage(msg);
            }

            need_update = false;

            MessageBus.Instance.SendMessage(MainScene.MainMenuMessageType.CLOSE_SHOP);
            MessageBus.Instance.SendMessage(MainScene.MainMenuMessageType.CLOSE_CAT_SHOW);
        }
    }
Exemple #29
0
 /// <summary>
 /// Loads the data.
 /// </summary>
 public void LoadData()
 {
     try
     {
         treeList.BeginUpdate();
         InitializeTreeMain();
         LoadDataIntoTree();
         LoadGridLayout();
         SetGridNumericFormat();
         SetTreeListNumericFormat();
     }
     catch (Exception ex)
     {
         XtraMessageBox.Show(ex.Message, ResourceHelper.GetResourceValueByName("ResExceptionCaption"));
         treeList.EndUpdate();
     }
     finally
     {
         treeList.EndUpdate();
         ActionMode = ActionModeEnum.None;
     }
 }
Exemple #30
0
        public async Task UnknownNodesTestAsync()
        {
            string jsonFilePath = ResourceHelper.GetTestResourceRelativePath("CacheFromTheFuture.json");
            string jsonContent  = File.ReadAllText(jsonFilePath);

            byte[] cache = Encoding.UTF8.GetBytes(jsonContent);

            var tokenCache = new TokenCache();

            tokenCache.SetBeforeAccess(notificationArgs =>
            {
                notificationArgs.TokenCache.DeserializeMsalV3(cache);
            });
            tokenCache.SetAfterAccess(notificationArgs =>
            {
                cache = notificationArgs.TokenCache.SerializeMsalV3();
            });

            var notification = new TokenCacheNotificationArgs(tokenCache, null, null, false);
            await tokenCache.OnBeforeAccessAsync(notification).ConfigureAwait(false);

            await tokenCache.OnAfterAccessAsync(notification).ConfigureAwait(false);

            (tokenCache as ITokenCacheInternal).Accessor.AssertItemCount(5, 4, 3, 3, 3);

            await tokenCache.OnBeforeAccessAsync(notification).ConfigureAwait(false);

            (tokenCache as ITokenCacheInternal).Accessor.AssertItemCount(5, 4, 3, 3, 3);

            await tokenCache.OnAfterAccessAsync(notification).ConfigureAwait(false);

            (tokenCache as ITokenCacheInternal).Accessor.AssertItemCount(5, 4, 3, 3, 3);

            var finalJson = JObject.Parse(Encoding.UTF8.GetString(cache));

            var originalJson = JObject.Parse(jsonContent);

            Assert.IsTrue(JToken.DeepEquals(originalJson, finalJson));
        }
        private IEnumerable <Manufacturer> GetManufacturersFromFile(ILogger <BeverageContextSeed> logger)
        {
            string csvFileManufacturers = ResourceHelper.GetManifestResourceAsString($"{BeverageDataNameSpace}.Manufacturers.csv");

            string[] csvheaders = null;
            try
            {
                string[] requiredHeaders = { "name", "description", "country" };
                csvheaders = this.GetHeaders(csvFileManufacturers, requiredHeaders);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
            }

            return(csvFileManufacturers.SplitCsvRows()
                   .Skip(1)                      // skip header row
                   .Select(row => Regex.Split(row, ColumnRegexPattern))
                   .SelectTry(column => this.CreateManufacturer(column, csvheaders))
                   .OnCaughtException(ex => { logger.LogError(ex.Message); return null; })
                   .Where(x => x != null));
        }
Exemple #32
0
        public FilterTask(Models.BusinessTripManagement businessTripManagement)
        {
            string listItemDesc = string.Empty;

            if (businessTripManagement.Domestic == true)
            {
                listItemDesc = ResourceHelper.GetLocalizedString("BusinessTripManagement_BusinessTripTypeInternalTitle", StringConstant.ResourcesFileLists, CultureInfo.CurrentUICulture.LCID);
            }
            else
            {
                listItemDesc = ResourceHelper.GetLocalizedString("BusinessTripManagement_BusinessTripTypeExternalTitle", StringConstant.ResourcesFileLists, CultureInfo.CurrentUICulture.LCID);
            }

            this.Description     = string.Format("{0} - {1}", listItemDesc, businessTripManagement.BusinessTripPurpose);
            this.Requester       = businessTripManagement.Requester;
            this.Department      = businessTripManagement.CommonDepartment;
            this.CreatedDate     = businessTripManagement.Created;
            this.DueDate         = businessTripManagement.RequestDueDate; // TODO
            this.ItemId          = businessTripManagement.ID;
            this.ItemApprovalUrl = $"{DelegationManager.BuildListItemApprovalUrl2(BusinessTripManagementList.Url, businessTripManagement.ID)}&Source=/SitePages/Overview.aspx";
            this.InitModule(BusinessTripManagementList.Url);
        }
        public async Task TestSuccess(Type serializerType)
        {
            using var response = ResourceHelper.ReadResourceAsStream(@"Documents\Query\query-200-success.json");

            var buffer = new byte[response.Length];

            response.Read(buffer, 0, buffer.Length);

            var handlerMock = new Mock <HttpMessageHandler>();

            handlerMock.Protected().Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()).ReturnsAsync(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new ByteArrayContent(buffer)
            });

            var httpClient = new HttpClient(handlerMock.Object)
            {
                BaseAddress = new Uri("http://localhost:8091")
            };
            var httpClientFactory = new MockHttpClientFactory(httpClient);

            var mockServiceUriProvider = new Mock <IServiceUriProvider>();

            mockServiceUriProvider
            .Setup(m => m.GetRandomQueryUri())
            .Returns(new Uri("http://localhost:8093"));

            var serializer = (ITypeSerializer)Activator.CreateInstance(serializerType);
            var client     = new QueryClient(httpClientFactory, mockServiceUriProvider.Object, serializer,
                                             new Mock <ILogger <QueryClient> >().Object, NoopRequestTracer.Instance);

            var result = await client.QueryAsync <dynamic>("SELECT * FROM `default`", new QueryOptions()).ConfigureAwait(false);

            Assert.Equal(10, await result.CountAsync().ConfigureAwait(false));
        }
Exemple #34
0
        private void btn_LinguaLinksXmlBrowse_Click(object sender, System.EventArgs e)
        {
            string currentFile = m_LinguaLinksXmlFileName.Text;

            openFileDialog.Filter          = ResourceHelper.BuildFileFilter(FileFilterType.XML, FileFilterType.AllFiles);
            openFileDialog.FilterIndex     = 1;
            openFileDialog.CheckFileExists = true;
            openFileDialog.Multiselect     = false;

            if (currentFile != null)
            {
                openFileDialog.InitialDirectory = currentFile;
                openFileDialog.FileName         = currentFile;
            }

            openFileDialog.Title = ITextStrings.ksSelectLLXMLFile;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                m_LinguaLinksXmlFileName.Text = openFileDialog.FileName;
                UpdateLanguageCodes();
            }
        }
Exemple #35
0
        private void ProcessGetImageById(string propID, HttpContext context)
        {
            MaterialContentCollection mcs = MaterialContentAdapter.Instance.Load(builder => builder.AppendItem("CONTENT_ID", propID));

            if (mcs.Count > 0)
            {
                MaterialContent matirial = mcs[0];
                string          fileName = matirial.FileName;
                byte[]          content  = matirial.ContentData;

                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite(content);
            }
            else
            {
                byte[] content = ResourceHelper.GetResourceBytes(typeof(ImageUploadHandler).Assembly,
                                                                 "MCS.Web.Responsive.WebControls.ImageUploader.cannotShow.png");
                context.Response.ContentType = "image/jpeg";
                context.Response.Cache.SetNoStore();
                context.Response.BinaryWrite(content);
            }
        }
Exemple #36
0
        /// <summary>
        /// Gets the country owner of the registration (Example: An airplane registred as "PR-GGF" is from Brazil because it starts with "PR-"
        /// </summary>
        /// <param name="registration"></param>
        /// <returns></returns>
        private static string GetCountryRegistration(string registration)
        {
            if (ListOfCountries == null)
            {
                string jsonstring = ResourceHelper.LoadExternalResource(resourceFileName);
                ListOfCountries = JsonConvert.DeserializeObject <IDictionary <string, string> >(jsonstring);

                LoggingHelper.LogBehavior($">>> Done converting {resourceFileName} file ''.");
            }

            string country    = String.Empty;
            var    countryReg = ListOfCountries.Keys.Where(s => registration.StartsWith(s)).FirstOrDefault();

            countryReg = (String.IsNullOrEmpty(countryReg)) ? "" : countryReg;

            if (ListOfCountries.ContainsKey(countryReg))
            {
                country = ListOfCountries[countryReg];
            }

            return(country);
        }
Exemple #37
0
        private void SetAvailableControllerTypes(ComboBox comboBox, InteropEmu.ControllerType[] controllerTypes)
        {
            comboBox.Items.Clear();
            foreach (InteropEmu.ControllerType type in controllerTypes)
            {
                comboBox.Items.Add(ResourceHelper.GetEnumText(type));
            }

            InputInfo inputInfo        = (InputInfo)Entity;
            string    currentSelection = null;

            if (comboBox == cboPlayer1)
            {
                currentSelection = ResourceHelper.GetEnumText(inputInfo.Controllers[0].ControllerType);
            }
            else if (comboBox == cboPlayer2)
            {
                currentSelection = ResourceHelper.GetEnumText(inputInfo.Controllers[1].ControllerType);
            }
            else if (comboBox == cboPlayer3)
            {
                currentSelection = ResourceHelper.GetEnumText(inputInfo.Controllers[2].ControllerType);
            }
            else if (comboBox == cboPlayer4)
            {
                currentSelection = ResourceHelper.GetEnumText(inputInfo.Controllers[3].ControllerType);
            }

            SortDropdown(comboBox, ResourceHelper.GetEnumText(InteropEmu.ControllerType.None));

            if (currentSelection != null && comboBox.Items.Contains(currentSelection))
            {
                comboBox.SelectedItem = currentSelection;
            }
            else
            {
                comboBox.SelectedIndex = 0;
            }
        }
Exemple #38
0
        public frmInputConfig()
        {
            InitializeComponent();

            tlpControllers.Enabled = !InteropEmu.MoviePlaying() && !InteropEmu.MovieRecording();

            InteropEmu.UpdateInputDevices();

            Entity = ConfigManager.Config.InputInfo;

            for (int i = 0; i < 4; i++)
            {
                ConfigManager.Config.InputInfo.Controllers[i].ControllerType = InteropEmu.GetControllerType(i);
            }
            ConfigManager.Config.InputInfo.ExpansionPortDevice = InteropEmu.GetExpansionDevice();
            ConfigManager.Config.InputInfo.ConsoleType         = InteropEmu.GetConsoleType();
            ConfigManager.Config.InputInfo.UseFourScore        = InteropEmu.HasFourScore();

            AddBinding("ExpansionPortDevice", cboExpansionPort);
            AddBinding("ConsoleType", cboConsoleType);
            AddBinding("UseFourScore", chkFourScore);
            AddBinding("AutoConfigureInput", chkAutoConfigureInput);

            AddBinding("DisplayInputPort1", chkDisplayPort1);
            AddBinding("DisplayInputPort2", chkDisplayPort2);
            AddBinding("DisplayInputPort3", chkDisplayPort3);
            AddBinding("DisplayInputPort4", chkDisplayPort4);
            AddBinding("DisplayInputPosition", cboDisplayInputPosition);
            AddBinding("DisplayInputHorizontally", chkDisplayInputHorizontally);
            AddBinding("ControllerDeadzoneSize", trkControllerDeadzoneSize);
            AddBinding("HideMousePointerForZapper", chkHideMousePointerForZapper);

            //Sort expansion port dropdown alphabetically, but keep the "None" option at the top
            SortDropdown(cboExpansionPort, ResourceHelper.GetEnumText(InteropEmu.ExpansionPortDevice.None));

            UpdateCartridgeInputUi();
            UpdateConflictWarning();
        }
Exemple #39
0
        public static HexEditorOptions TryCreate(HexViewOptionsGroup group, IHexEditorOptionsDefinitionMetadata md)
        {
            if (group == null)
            {
                throw new ArgumentNullException(nameof(group));
            }
            if (md == null)
            {
                throw new ArgumentNullException(nameof(md));
            }

            if (md.SubGroup == null)
            {
                return(null);
            }
            var subGroup = md.SubGroup;

            if (subGroup == null)
            {
                return(null);
            }

            if (md.Guid == null)
            {
                return(null);
            }
            if (!Guid.TryParse(md.Guid, out var guid))
            {
                return(null);
            }

            if (md.Name == null)
            {
                return(null);
            }

            return(new HexEditorOptions(group, subGroup, guid, ResourceHelper.GetString(md.Type.Assembly, md.Name)));
        }
        public async Task GetAuthorizationRequestUrlB2CTestAsync()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                var app = ConfidentialClientApplicationBuilder.Create(MsalTestConstants.ClientId)
                          .WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), true)
                          .WithRedirectUri(MsalTestConstants.RedirectUri)
                          .WithClientSecret(MsalTestConstants.ClientSecret)
                          .WithHttpManager(httpManager)
                          .BuildConcrete();

                // add mock response for tenant endpoint discovery
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Get,
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        File.ReadAllText(
                            ResourceHelper.GetTestResourceRelativePath(@"OpenidConfiguration-QueryParams-B2C.json")))
                });

                var uri = await app
                          .GetAuthorizationRequestUrl(MsalTestConstants.Scope)
                          .WithLoginHint(MsalTestConstants.DisplayableId)
                          .ExecuteAsync(CancellationToken.None)
                          .ConfigureAwait(false);

                Assert.IsNotNull(uri);
                Dictionary <string, string> qp = CoreHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', true, null);
                Assert.IsNotNull(qp);

                Assert.AreEqual("my-policy", qp["p"]);
                ValidateCommonQueryParams(qp);
                Assert.AreEqual("offline_access openid profile r1/scope1 r1/scope2", qp["scope"]);
            }
        }
        public static void InitializeStateMenu(ToolStripMenuItem menu, bool forSave, ShortcutHandler shortcutHandler)
        {
            Action <uint> addSaveStateInfo = (i) => {
                ToolStripMenuItem item = new ToolStripMenuItem();
                menu.DropDownItems.Add(item);

                if (forSave)
                {
                    shortcutHandler.BindShortcut(item, (EmulatorShortcut)((int)EmulatorShortcut.SaveStateSlot1 + i - 1));
                }
                else
                {
                    shortcutHandler.BindShortcut(item, (EmulatorShortcut)((int)EmulatorShortcut.LoadStateSlot1 + i - 1));
                }
            };

            for (uint i = 1; i <= NumberOfSaveSlots; i++)
            {
                addSaveStateInfo(i);
            }

            if (!forSave)
            {
                menu.DropDownItems.Add("-");
                addSaveStateInfo(NumberOfSaveSlots + 1);
                menu.DropDownItems.Add("-");
                ToolStripMenuItem loadFromFile = new ToolStripMenuItem(ResourceHelper.GetMessage("LoadFromFile"), Resources.Folder);
                menu.DropDownItems.Add(loadFromFile);
                shortcutHandler.BindShortcut(loadFromFile, EmulatorShortcut.LoadStateFromFile);
            }
            else
            {
                menu.DropDownItems.Add("-");
                ToolStripMenuItem saveToFile = new ToolStripMenuItem(ResourceHelper.GetMessage("SaveToFile"), Resources.SaveFloppy);
                menu.DropDownItems.Add(saveToFile);
                shortcutHandler.BindShortcut(saveToFile, EmulatorShortcut.SaveStateToFile);
            }
        }
Exemple #42
0
        /// <summary>
        /// Grids the specified HTML.
        /// </summary>
        /// <typeparam name="TValue">The type of the value.</typeparam>
        /// <param name="html">The HTML helper.</param>
        /// <param name="searchExpression">The search expression.</param>
        /// <returns>Html-markup for jq grid.</returns>
        public static MvcHtmlString JqGrid <TValue>(this HtmlHelper <GridViewModel> html, Expression <Func <GridViewModel, TValue> > searchExpression)
        {
            var builder       = new StringBuilder();
            var filterWrapper = new TagBuilder("div");

            filterWrapper.AddCssClass("e_table_top clrfix");

            var searchWrapper = new TagBuilder("div");

            searchWrapper.AddCssClass("filter_l clrfix");

            searchWrapper.InnerHtml += GenerateSearch(html, searchExpression);
            searchWrapper.InnerHtml += GenerateAutoSearch(html);
            searchWrapper.InnerHtml += GenerateSearchButtons(html);

            filterWrapper.InnerHtml += searchWrapper.ToString(TagRenderMode.Normal);

            var noItem = new TagBuilder("div");

            noItem.InnerHtml = html.Translate("NoItemToDisplay", ResourceHelper.GetModelScope(typeof(GridViewModel)));
            noItem.MergeAttribute("id", "notItem");
            noItem.MergeAttribute("style", "display:none;");
            noItem.AddCssClass("noItemToDisplay");

            builder.Append(filterWrapper.ToString(TagRenderMode.Normal));

            builder.Append(GenerateGrid());

            builder.Append(noItem);

            builder.Append(GeneratePager());

            builder.Append(GenerateScript(html));

            MvcHtmlString result = MvcHtmlString.Create(builder.ToString());

            return(result);
        }
Exemple #43
0
        public void When_IOErrorThreshold_IsNot_Met_By_IOErrorInterval_NodeUnavailableException_Is_Thrown()
        {
            var json         = ResourceHelper.ReadResource(@"Data\Configuration\nodesext-cb-beta-4.json");
            var bucketConfig = JsonConvert.DeserializeObject <BucketConfig>(json);
            var node         = bucketConfig.GetNodes().First();

            var endPoint     = UriExtensions.GetEndPoint(_address);
            var clientConfig = new ClientConfiguration
            {
                IOErrorThreshold     = 10,
                IOErrorCheckInterval = 100
            };
            var connectionPool = new FakeConnectionPool();
            var ioService      = new FakeIOService(endPoint, connectionPool, false);
            var server         = new Server(ioService,
                                            node,
                                            new FakeTranscoder(),
                                            ContextFactory.GetCouchbaseContext(clientConfig, bucketConfig));

            Assert.IsFalse(server.IsDown);

            var stopWatch = new Stopwatch();

            stopWatch.Start();
            for (int i = 0; i < 11; i++)
            {
                server.CheckOnline(true);
                Console.WriteLine("{0}=>{1}", server.IsDown, server.IOErrorCount);
                Thread.Sleep(10);
            }
            // ReSharper disable once ThrowingSystemException
            Assert.Throws <NodeUnavailableException>(() =>
            {
                var operation = new FakeOperation(new DefaultTranscoder());
                server.Send(operation);
                throw operation.Exception;
            });
        }
Exemple #44
0
        public void TestReadRecruiterMultipleParameters(string fieldName, int count, int start)
        {
            List <string> fieldList = Util.StringToList(fieldName);

            Dictionary <string, object> parameters = new Dictionary <string, object>()
            {
                { Parttion, AuthenticationInfoProvider.Current.DefaultPartition },
                { "count", count },
                { "start", start },
                { "field", fieldName }
            };
            ReadResponseData <Recruiter> result = PublicApiAdapter.CreateAdapterForDefaultConnection().ReadSuccess <Recruiter>(parameters);

            Assert.AreEqual(Enums.PublicAPIResultCode.Success, result.Code,
                            string.Format(Enums.Message.READ_RESOURCE_FAILED, "Recruiter"));

            //Verify existing of XML element
            ResourceHelper.VerifyListContainElement(result.Items, fieldList);

            //Verify none existing elements that accepts in fieldList
            Dictionary <string, Dictionary <string, object> > fieldsTemp = Util.RemoveElements(fieldList, fields);

            ResourceHelper.VerifyListNotContainElement(result.Items, fieldsTemp.Keys.ToList());


            //Verify the Count/Start/Total
            Assert.AreEqual(result.Start, start, Enums.Message.START_ERROR);
            Assert.LessOrEqual(result.Count, count, Enums.Message.COUNT_ERROR);
            Assert.GreaterOrEqual(result.Total, 0, Enums.Message.TOTAL_ERROR);

            //Verify item is effected to Count
            Assert.AreEqual(result.Items.Count, count, Enums.Message.COUNT_NOT_EFFECTED);

            //Verify the type of fields in fieldList
            Dictionary <string, Dictionary <string, object> > fieldsTemp2 = Util.GetElements(fieldList, fields);

            ResourceHelper.VerifyTypeOfField(result.Items, fieldsTemp2);
        }
        [System.Security.SecuritySafeCritical]  // auto-generated
        private static void InitResourceHelper() {
            // Only the default AppDomain should have a ResourceHelper.  All calls to 
            // GetResourceString from any AppDomain delegate to GetResourceStringLocal 
            // in the default AppDomain via the fcall GetResourceFromDefault.

            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {

                Monitor.Enter(Environment.InternalSyncObject, ref tookLock);

                if (m_resHelper == null) {
#if FEATURE_SPLIT_RESOURCES
                    // See code:#splitResourceFeature
                    ResourceHelper rh = new ResourceHelper("mscorlib.debug", true);
#else
                    ResourceHelper rh = new ResourceHelper("mscorlib");
#endif // FEATURE_SPLIT_RESOURCES

                    System.Threading.Thread.MemoryBarrier();
                    m_resHelper =rh;
                }
            }
            finally {
                if (tookLock)
                    Monitor.Exit(Environment.InternalSyncObject);
            }
        }
 public GetResourceStringUserData(ResourceHelper resourceHelper, String key, CultureInfo culture)
 {
     m_resourceHelper = resourceHelper;
     m_key = key;
     m_culture = culture;
 }
        private static void InitResourceHelper() {

            // Only the default AppDomain should have a ResourceHelper.  All calls to 
            // GetResourceString from any AppDomain delegate to GetResourceStringLocal 
            // in the default AppDomain via the fcall GetResourceFromDefault.

            // Use Thread.BeginCriticalRegion to tell the CLR all managed
            // allocations within this block are appdomain-critical.
            // Use a CER to ensure we always exit this region.
            bool enteredRegion = false;
            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {
                RuntimeHelpers.PrepareConstrainedRegions();
                try {
                }
                finally {
                    Thread.BeginCriticalRegion();
                    enteredRegion = true;
                    Monitor.Enter(Environment.InternalSyncObject);
                    tookLock = true;
                }

                if (m_resHelper == null) {
                    ResourceHelper rh = new ResourceHelper();
                    System.Threading.Thread.MemoryBarrier();
                    m_resHelper =rh;
                }
            }
            finally {
                if (tookLock)
                    Monitor.Exit(Environment.InternalSyncObject);
                if (enteredRegion)
                    Thread.EndCriticalRegion();
            }
        }
        /// <summary>
        /// Creates the driver folder structure in this given folder as the root
        /// </summary>
        /// <param name="jobSubmission">Job submission information</param>
        /// <param name="driverFolderPath">Driver folder path</param>
        internal void CreateDefaultFolderStructure(IJobSubmission jobSubmission, string driverFolderPath)
        {
            Directory.CreateDirectory(Path.Combine(driverFolderPath, _fileNames.GetReefFolderName()));
            Directory.CreateDirectory(Path.Combine(driverFolderPath, _fileNames.GetLocalFolderPath()));
            Directory.CreateDirectory(Path.Combine(driverFolderPath, _fileNames.GetGlobalFolderPath()));

            var resourceHelper = new ResourceHelper(typeof(DriverFolderPreparationHelper).Assembly);
            foreach (var fileResources in clientFileResources)
            {
                var fileName = resourceHelper.GetString(fileResources.Item1);
                if (ClrDriverFullName == fileResources.Item1)
                {
                    fileName = Path.Combine(driverFolderPath, _fileNames.GetBridgeExePath());
                }
                File.WriteAllBytes(fileName, resourceHelper.GetBytes(fileResources.Item2));
            }
            
            var config = DefaultDriverConfigurationFileContents;
            if (!string.IsNullOrEmpty(jobSubmission.DriverConfigurationFileContents))
            {
                config = jobSubmission.DriverConfigurationFileContents;
            }
            File.WriteAllText(Path.Combine(driverFolderPath, _fileNames.GetBridgeExeConfigPath()), config);
        }
        protected override void Arrange()
        {
            base.Arrange();

            var resourceHelper = new ResourceHelper<ConfigFileLocator>();
            resourceHelper.DumpResourceFileToDisk(MainConfigurationFile);
            resourceHelper.DumpResourceFileToDisk(SatelliteConfigurationFile);

            var configurationSourceSection = ConfigurationSource.Sections.Where(s => s.ConfigurationType == typeof(ConfigurationSourceSection)).Single();
            configurationSourceSection.Property("SelectedSource").Value = SatelliteSourceName;

            var builder = new ConfigurationSourceBuilder();
            builder.ConfigureLogging()
                .LogToCategoryNamed("General")
                .SendTo.EventLog("EventLogListener")
                .ToLog("Application")
                .FormatWith(new FormatterBuilder().TextFormatterNamed("TextFormatter"));
            var section = builder.Get(LoggingSettings.SectionName);
            ConfigurationSource.AddSection(LoggingSettings.SectionName, section);
        }
 protected override void Arrange()
 {
     var resourceHelper = new ResourceHelper<CustomConfigurationElementCollectionFixture>();
     configurationFilePath = resourceHelper.DumpResourceFileToDisk("ConfigSourceWithInvalidType.config");
 }
        /// <summary>
        /// Creates the driver folder structure in this given folder as the root
        /// </summary>
        /// <param name="appParameters">Job submission information</param>
        /// <param name="driverFolderPath">Driver folder path</param>
        internal void CreateDefaultFolderStructure(AppParameters appParameters, string driverFolderPath)
        {
            Directory.CreateDirectory(Path.Combine(driverFolderPath, _fileNames.GetReefFolderName()));
            Directory.CreateDirectory(Path.Combine(driverFolderPath, _fileNames.GetLocalFolderPath()));
            Directory.CreateDirectory(Path.Combine(driverFolderPath, _fileNames.GetGlobalFolderPath()));

            var resourceHelper = new ResourceHelper(typeof(DriverFolderPreparationHelper).Assembly);
            foreach (var fileResources in ResourceHelper.FileResources)
            {
                var fileName = resourceHelper.GetString(fileResources.Key);
                if (ResourceHelper.ClrDriverFullName == fileResources.Key)
                {
                    fileName = Path.Combine(driverFolderPath, _fileNames.GetBridgeExePath());
                }
                if (!File.Exists(fileName))
                {
                    File.WriteAllBytes(fileName, resourceHelper.GetBytes(fileResources.Value));
                }
            }
            
            // generate .config file for bridge executable
            var config = DefaultDriverConfigurationFileContents;
            if (!string.IsNullOrEmpty(appParameters.DriverConfigurationFileContents))
            {
                config = appParameters.DriverConfigurationFileContents;
            }
            File.WriteAllText(Path.Combine(driverFolderPath, _fileNames.GetBridgeExeConfigPath()), config);

            // generate .config file for Evaluator executable
            File.WriteAllText(Path.Combine(driverFolderPath, _fileNames.GetGlobalFolderPath(), EvaluatorExecutable), 
                DefaultDriverConfigurationFileContents);
        }
 private static void InitResourceHelper()
 {
     bool lockTaken = false;
     RuntimeHelpers.PrepareConstrainedRegions();
     try
     {
         Monitor.Enter(InternalSyncObject, ref lockTaken);
         if (m_resHelper == null)
         {
             ResourceHelper helper = new ResourceHelper("mscorlib");
             Thread.MemoryBarrier();
             m_resHelper = helper;
         }
     }
     finally
     {
         if (lockTaken)
         {
             Monitor.Exit(InternalSyncObject);
         }
     }
 }
        protected override void Arrange()
        {
            base.Arrange();

            var resources = new ResourceHelper<ConfigFileLocator>();
            resources.DumpResourceFileToDisk("configurationsource_with_invalid_satellite.config");
            resources.DumpResourceFileToDisk("configurationsource_invalid_satellite.config");

            designSource = new DesignConfigurationSource("configurationsource_with_invalid_satellite.config");
            configurationSourceModel = Container.Resolve<ConfigurationSourceModel>();

            UIServiceMock.Setup(x => x.ShowWindow(It.IsAny<Window>()));
            UIServiceMock.Setup(
                x => x.ShowError(It.IsAny<Exception>(), It.IsAny<string>())).Verifiable();
        }
        [System.Security.SecurityCritical] // auto-generated
        #endif
        private static void InitRuntimeResourceHelper() {
            // Only the default AppDomain should have a ResourceHelper.  All calls to 
            // GetResourceString from any AppDomain delegate to GetResourceStringLocal 
            // in the default AppDomain via the fcall GetResourceFromDefault.

            bool tookLock = false;
            RuntimeHelpers.PrepareConstrainedRegions();
            try {

                Monitor.Enter(Environment.InternalSyncObject, ref tookLock);

                if (m_runtimeResHelper == null) {
                    ResourceHelper rh = new ResourceHelper("mscorlib", false);
                    System.Threading.Thread.MemoryBarrier();
                    m_runtimeResHelper = rh;
                }
            }
            finally {
                if (tookLock)
                    Monitor.Exit(Environment.InternalSyncObject);
            }
        }       
 public void Setup()
 {
     var fileCreator = new ResourceHelper<ConfigFileLocator>();
     fileCreator.DumpResourceFileToDisk("main.config");
     fileCreator.DumpResourceFileToDisk("subordinate.config");
 }
Exemple #56
0
        static byte[] PackDnaLibrary(byte[] dnaContent, string dnaDirectory, ResourceHelper.ResourceUpdater ru)
        {
            DnaLibrary dna = DnaLibrary.LoadFrom(dnaContent, dnaDirectory);
            if (dna == null)
            {
                // TODO: Better error handling here.
                Console.WriteLine(".dna file could not be loaded. Possibly malformed xml content? Aborting.");
                Environment.Exit(1);
            }
            if (dna.ExternalLibraries != null)
            {
                foreach (ExternalLibrary ext in dna.ExternalLibraries)
                {
                    if (ext.Pack)
                    {
                        string path = dna.ResolvePath(ext.Path);
                        Console.WriteLine("  ~~> ExternalLibrary path {0} resolved to {1}.", ext.Path, path);
                        if (Path.GetExtension(path).Equals(".DNA", StringComparison.OrdinalIgnoreCase))
                        {
                            string name = Path.GetFileNameWithoutExtension(path).ToUpperInvariant() + "_" + lastPackIndex++ + ".DNA";
                            byte[] dnaContentForPacking = PackDnaLibrary(File.ReadAllBytes(path), Path.GetDirectoryName(path), ru);
                            ru.AddDnaFile(dnaContentForPacking, name);
                            ext.Path = "packed:" + name;
                        }
                        else
                        {
                            string packedName = ru.AddAssembly(path);
                            if (packedName != null)
                            {
                                ext.Path = "packed:" + packedName;
                            }
                        }
                        if (ext.ComServer == true)
                        {
                            // Check for a TypeLib to pack
                            //string tlbPath = dna.ResolvePath(ext.TypeLibPath);
                            string resolvedTypeLibPath = null;
                            if (!string.IsNullOrEmpty(ext.TypeLibPath))
                            {
                                resolvedTypeLibPath = dna.ResolvePath(ext.TypeLibPath); // null is unresolved
                                if (resolvedTypeLibPath == null)
                                {
                                    // Try relative to .dll
                                    resolvedTypeLibPath = DnaLibrary.ResolvePath(ext.TypeLibPath, System.IO.Path.GetDirectoryName(path) ); // null is unresolved
                                    if (resolvedTypeLibPath == null)
                                    {
                                        Console.WriteLine("!!! ExternalLibrary TypeLib path {0} could not be resolved.", ext.TypeLibPath);
                                    }
                                }
                            }
                            else
                            {
                                // Check for .tlb
                                string tlbCheck = System.IO.Path.ChangeExtension(path, "tlb");
                                if (System.IO.File.Exists(tlbCheck))
                                {
                                    resolvedTypeLibPath = tlbCheck;
                                }
                            }
                            if (resolvedTypeLibPath != null)
                            {
                                Console.WriteLine("  ~~> ExternalLibrary typelib path {0} resolved to {1}.", ext.TypeLibPath, resolvedTypeLibPath);
                                int packedIndex = ru.AddTypeLib(File.ReadAllBytes(resolvedTypeLibPath));
                                ext.TypeLibPath = "packed:" + packedIndex.ToString();
                            }
                        }
                    }

                }
            }
            // Collect the list of all the references.
            List<Reference> refs = new List<Reference>();
            foreach (Project proj in dna.GetProjects())
            {
                if (proj.References != null)
                {
                    refs.AddRange(proj.References);
                }
            }
            // Fix-up if Reference is not part of a project, but just used to add an assembly for packing.
            foreach (Reference rf in dna.References)
            {
                if (!refs.Contains(rf))
                    refs.Add(rf);
            }
            // Now pack the references
            foreach (Reference rf in refs)
            {
                if (rf.Pack)
                {
                    string path = null;
                    if (rf.Path != null)
                    {
                        if (rf.Path.StartsWith("packed:"))
                        {
                            break;
                        }

                        path = dna.ResolvePath(rf.Path);
                        Console.WriteLine("  ~~> Assembly path {0} resolved to {1}.", rf.Path, path);
                    }
                    if (path == null && rf.Name != null)
                    {
                        // Try Load as as last resort (and opportunity to load by FullName)
                        try
                        {
                            #pragma warning disable 0618
                            Assembly ass = Assembly.LoadWithPartialName(rf.Name);
                            #pragma warning restore 0618
                            if (ass != null)
                            {
                                path = ass.Location;
                                Console.WriteLine("  ~~> Assembly {0} 'Load'ed from location {1}.", rf.Name, path);
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("  ~~> Assembly {0} not 'Load'ed. Exception: {1}", rf.Name, e);
                        }
                    }
                    if (path == null)
                    {
                        Console.WriteLine("  ~~> Reference with Path: {0} and Name: {1} not found.", rf.Path, rf.Name);
                        break;
                    }

                    // It worked!
                    string packedName = ru.AddAssembly(path);
                    if (packedName != null)
                    {
                        rf.Path = "packed:" + packedName;
                    }
                }
            }
            foreach (Image image in dna.Images)
            {
                if (image.Pack)
                {
                    string path = dna.ResolvePath(image.Path);
                    if (path == null)
                    {
                        Console.WriteLine("  ~~> Image path {0} not resolved.", image.Path);
                        break;
                    }
                    string name = Path.GetFileNameWithoutExtension(path).ToUpperInvariant() + "_" + lastPackIndex++ + Path.GetExtension(path).ToUpperInvariant();
                    byte[] imageBytes = File.ReadAllBytes(path);
                    ru.AddImage(imageBytes, name);
                    image.Path = "packed:" + name;
                }
            }
            foreach (Project project in dna.Projects)
            {
                foreach (SourceItem source in project.SourceItems)
                {
                    if (source.Pack && !string.IsNullOrEmpty(source.Path))
                    {
                        string path = dna.ResolvePath(source.Path);
                        if (path == null)
                        {
                            Console.WriteLine("  ~~> Source path {0} not resolved.", source.Path);
                            break;
                        }
                        string name = Path.GetFileNameWithoutExtension(path).ToUpperInvariant() + "_" + lastPackIndex++ + Path.GetExtension(path).ToUpperInvariant();
                        byte[] sourceBytes = File.ReadAllBytes(path);
                        ru.AddSource(sourceBytes, name);
                        source.Path = "packed:" + name;
                    }
                }
            }
            return DnaLibrary.Save(dna);
        }
        protected override void Arrange()
        {
            base.Arrange();

            var resources = new ResourceHelper<ConfigFileLocator>();
            resources.DumpResourceFileToDisk("configurationsource_main.config");
            resources.DumpResourceFileToDisk("configurationsource_satellite.config");

            var mainConfigFilePath = Path.Combine(Environment.CurrentDirectory, "configurationsource_main.config");
            designSource = new DesignConfigurationSource(mainConfigFilePath);

            configurationSourceModel = Container.Resolve<ConfigurationSourceModel>();

        }
Exemple #58
0
 public GetResourceStringUserData(ResourceHelper resourceHelper, String key)
 {
     m_resourceHelper = resourceHelper;
     m_key = key;
 }
        protected override void Arrange()
        {
            base.Arrange();
            
            UIServiceMock.Setup(x => x.ShowWindow(It.IsAny<Window>()));
            UIServiceMock.Setup(
                           x => x.ShowError(It.IsAny<Exception>(), It.IsAny<string>()));

            var resources = new ResourceHelper<ConfigFileLocator>();
            resources.DumpResourceFileToDisk(sourceFileName);
            resources.DumpResourceFileToDisk("configurationsource_invalid_satellite.config");

            applicationModel = Container.Resolve<IApplicationModel>();
        }
        protected override void Arrange()
        {
            targetFile = "empty.dconfig";
            environmentConfigFile = "empty.config";

            ResourceHelper<ConfigFileLocator> helper = new ResourceHelper<ConfigFileLocator>();
            helper.DumpResourceFileToDisk(targetFile);
            helper.DumpResourceFileToDisk(environmentConfigFile);

            mainFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "any.config");
            base.Arrange();

            applicationModel = (ApplicationViewModel)Container.Resolve<IApplicationModel>();
            applicationModel.ConfigurationFilePath = mainFile;

            ConfigurationSourceModel sourceModel = Container.Resolve<ConfigurationSourceModel>();
            applicationModel.NewEnvironment();

            applicationModel.Environments.First().EnvironmentDeltaFile = targetFile;
            applicationModel.Environments.First().EnvironmentConfigurationFile = environmentConfigFile;

            UIServiceMock.Setup(x => x.ShowFileDialog(It.IsAny<SaveFileDialog>()))
                         .Callback(() => Assert.Fail());

            UIServiceMock.Setup(x => x.ShowMessageWpf(It.IsRegex("overwrite", RegexOptions.None), It.IsAny<string>(), System.Windows.MessageBoxButton.OKCancel))
                .Returns(MessageBoxResult.Yes)
                .Verifiable();
        }