private void AddMovieClick(object data = null) { ObservableCollection <CinemaHall> cinemaHalls; try { cinemaHalls = JsonFileHelper.JsonDeserialization <CinemaHall>("Database of Cinemas/cinemas"); } catch (Exception) { cinemaHalls = new ObservableCollection <CinemaHall>(); } if (cinemaHalls.FirstOrDefault(ch => ch.Movie.ImdbID == Movie.ImdbID) != null) { System.Windows.MessageBox.Show("This movie already exists.", "Mosaviena"); return; } cinemaHalls.Add(new CinemaHall { Movie = this.Movie }); JsonFileHelper.JsonSerialization(cinemaHalls, "Database of Cinemas/cinemas"); System.Windows.MessageBox.Show($"Movie \"{Movie.Title}\" added to cinema successfully.", "Mosaviena"); }
public static string LanguageList(string applicationId) { var filePath = Path.Combine(LanguageFilesPath, applicationId, "languages.json"); var languages = JsonFileHelper.GetFileContents(filePath) ?? string.Empty; return(languages); }
public async Task <ActionResult <bool> > UpdateIllustrationImagesConfig(List <BaseConfigDTO> data) { var filepath = Path.Combine(Directory.GetCurrentDirectory(), "config/illustration.json"); bool flag = await JsonFileHelper.SetConfig(filepath, data); return(Ok(flag)); }
public static TResponse GetTransactionLookupStatusResponse <TResponse>(string referenceNumber, Func <TrainingModeResponses, string> getFileName) { var instance = GetConfiguration(); var scenario = instance.Scenarios.SingleOrDefault(x => x.ReferenceNumber == referenceNumber && getFileName(x.Responses) != null); if (scenario?.Responses == null) { throw new TrainingModeException("STRKEY_TRAINING_ERROR_EDIT_TRAN_REF_NUMBER"); } var responseFilePath = Path.Combine(JsonFileHelper.ExecutingDir(), TrainingModeFolderName, scenario.SessionType.ToString(), referenceNumber ?? string.Empty, getFileName(scenario.Responses)); if (!File.Exists(responseFilePath)) { throw new FileNotFoundException($"Could not find Training Mode Transaction Lookup Status response file for referenceNumber:{referenceNumber}."); } try { return(JsonProcessor.DeserializeObject <TResponse>(JsonFileHelper.GetFileContents(responseFilePath), true)); } catch (Exception exception) { throw new InvalidDataException($"Could not deserialize Training Mode Transaction Lookup Status response for sessionType:{scenario.SessionType}, referenceNumber:{referenceNumber}.", exception); } }
private static IConfigurationRoot BuildConfiguration() { const string appConfigJsonName = "appsettings.json"; var appConfigJsonPath = Path.Combine(BasePath, appConfigJsonName); if (!File.Exists(appConfigJsonPath)) { JsonFileHelper.AddOrUpdateSection(appConfigJsonPath, nameof(ReplacementOptions), new ReplacementOptions()); } else { WriteLine($"{Environment.NewLine}是否重新生成 appsettings.json 文件? Y/任意键"); if (ReadLine().Trim().ToLower() == "y") { JsonFileHelper.AddOrUpdateSection(appConfigJsonPath, nameof(ReplacementOptions), new ReplacementOptions()); } } ForegroundColor = ConsoleColor.Yellow; WriteLine($"请先配置程序目录下的 appsettings.json 文件。"); ResetColor(); WriteLine($"{Environment.NewLine}配置完成?任意键继续..."); ReadKey(); var builder = new ConfigurationBuilder() .SetBasePath(BasePath) .AddJsonFile(appConfigJsonName, false, true); return(builder.Build()); }
private static IConfigurationRoot BuildConfiguration() { const string appConfigJsonName = "appsettings.json"; var appConfigJsonPath = Path.Combine(BasePath, appConfigJsonName); if (!File.Exists(appConfigJsonPath)) { JsonFileHelper.AddOrUpdateSection(appConfigJsonPath, nameof(AppSettings), new AppSettings()); } var builder = new ConfigurationBuilder() .SetBasePath(BasePath) .AddJsonFile(appConfigJsonName) .AddJsonFile("Resources/appsettings.custom.json", true) .AddEnvironmentVariables(); if (!string.IsNullOrEmpty(EnvironmentName)) { builder.AddJsonFile($"appsettings.{EnvironmentName}.json", true); } if (IsDevelopment()) { builder.AddUserSecrets <Program>(); } return(builder.Build()); }
public static string GetLanguage(string applicationId, string langId) { var filePath = Path.Combine(LanguageFilesPath, applicationId, langId + ".json"); var language = JsonFileHelper.GetFileContents(filePath) ?? string.Empty; return(language); }
private void PutMovieToCinemaButtonClick(object data) { if (data is Movie movie) { System.Windows.MessageBoxResult result = System.Windows.MessageBox.Show($"Do you want to add \"{movie.Title}\" to cinema ?", "Mosaviena", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question); if (result == System.Windows.MessageBoxResult.Yes) { try { CinemaHalls = JsonFileHelper.JsonDeserialization <CinemaHall>("Database of Cinemas/cinemas"); } catch (Exception) { CinemaHalls = new ObservableCollection <CinemaHall>(); } if (CinemaHalls.FirstOrDefault(cm => cm.Movie.ImdbID == movie.ImdbID) != null) { System.Windows.MessageBox.Show($"You already add this movie to cinema.", "Mosaviena"); return; } CinemaHalls.Add(new CinemaHall { Movie = movie }); JsonFileHelper.JsonSerialization <CinemaHall>(CinemaHalls, "Database of Cinemas/cinemas"); } System.Windows.MessageBox.Show($"Operation {result} done successfully.", "Mosaviena"); } }
/// <summary> /// GetAvailableEquipment - /// Requesting both to cancel the current booking date /// and provide New availability of EquipmentID for the new request date /// </summary> /// <param name="requestDate"></param> /// <param name="newRequestDate"></param> /// <returns></returns> public int GetAvailableEquipment(DateTime requestDate, DateTime newRequestDate) { if (_equipmentSetting.Environment == "Production") { using (var _client = new HttpClient()) { //calling external equipment availability api and getting availability status _client.BaseAddress = new Uri(_equipmentSetting.Uri); _client.DefaultRequestHeaders.Accept.Clear(); //TODO: Making a request to return availability status?? } } else { // cancelling of existing appointment // providing new availability for the new request date var equipment = JsonFileHelper.GetEquipmentAvailability(_equipmentSetting.DataFile); var equipmentId = equipment .Where(e => e.isAvailable == true && e.Date >= newRequestDate) .Select(x => x.EquipmentID) .FirstOrDefault(); return(equipmentId); } return(0); }
public MoAndLocationRepository() { var jsonData = JsonFileHelper.GetFileContents(_configurationFilePath); MoAndLocations = !string.IsNullOrEmpty(jsonData) ? JsonProcessor.DeserializeObject <MoAndLocationsData>(jsonData): new MoAndLocationsData(); }
public async Task <ActionResult <bool> > UpdateIndexVideoOrImageConfig(IndexVideoConfigDTO data) { var filepath = Path.Combine(Directory.GetCurrentDirectory(), "config/indexVideo.json"); bool flag = await JsonFileHelper.SetConfig(filepath, data); return(Ok(flag)); }
private async void ImportData_Click(object sender, RoutedEventArgs e) { FileOpenPicker picker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.MusicLibrary }; picker.FileTypeFilter.Add(".json"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { MainPage.Instance.Loader.ShowIndeterminant("ProcessRequest"); try { string json = await FileIO.ReadTextAsync(file); Settings settings = JsonFileHelper.Convert <Settings>(json); bool successful = await UpdateMusicLibrary(); MainPage.Instance.Loader.Hide(); MainPage.Instance.ShowLocalizedNotification(successful ? "DataImported" : "ImportDataCancelled"); } catch (Exception ex) { MainPage.Instance.Loader.Hide(); MainPage.Instance.ShowLocalizedNotification("ImportDataFailed" + ex.Message); } } }
static AppSettings() { _solutionSettingsFile = Path.Combine(Path.GetTempPath(), "SolutionTemplate.json"); if (_solutionSettingsFile.FileExists()) { try { SolutionTemplateSettings = JsonFileHelper.ReadJsonFile <ProjectTemplate>(_solutionSettingsFile); } catch (Exception e) { Trace.WriteLine(e); } } if (SolutionTemplateSettings == null) { SolutionTemplateSettings = new ProjectTemplate { TemplateName = "My Multi-Template Solution", LanguageTag = "C#", PlatformTags = "Windows", ProjectTypeTags = "Web" }; } }
public MainViewPresenter(IMainView view) { _view = view; SetAllEvents(); _petrols = JsonFileHelper.JSONDeSerialization <Petrol>("Petrols"); _view.PetrolComboBox.DisplayMember = "Name"; _view.PetrolComboBox.DataSource = _petrols; _view.PriceTextBox.Text = _petrols[0].InitialPrice.ToString(); _view.PictureToolTip.SetToolTip(_view.CarPictureBox, "Man refuelling his car."); _petrolOperationContext = new PetrolOperationContext(); SetListBoxDataSource(); try { if (!_petrolOperationContext.PetrolPaymentOperations.Any()) { _view.InfoLabel.Visible = true; } } catch (Exception) { } }
/// <summary> /// Insert a CustomerEntity to Json File /// </summary> /// <param name="customerEntity"></param> /// <returns>True, if the entity is successfully inserted; /// False, if the entity has the identical user name with other customer /// </returns> public bool Insert(CustomerEntity customerEntity) { if (_logger.IsDebugEnabled) { _logger.Debug("[CustomersRepository::Insert] Starting insert costomerEntity. CustomerEntity: {}", customerEntity); } try { if (customerEntity == null) { throw new ArgumentNullException( nameof(customerEntity), "[CustomersRepository::Insert] CustomerEntity can not be null."); } var jObjectFromFile = JsonFileHelper.ReadJsonFile(_customersFilePath, _customersFileName); var customerEntityJObject = jObjectFromFile["Customers"] .FirstOrDefault(c => customerEntity.UserName.Equals((string)c["UserName"])); // Can't insert when there is a same userName if (customerEntityJObject != null) { _logger.Warn( "[CustomersRepository::Insert] Can't insert when there is a same userName. CustomerEntity: {}", customerEntity); return(false); } var jObjectFromEntity = CustomerEntityToJToken(customerEntity); jObjectFromFile.Merge(jObjectFromEntity, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union }); JsonFileHelper.WriteJsonFile(_customersFilePath, _customersFileName, jObjectFromFile); if (_logger.IsDebugEnabled) { _logger.Debug( "[CustomersRepository::Insert] Insert customerEntity Successfully. InsertedEntity: {}", customerEntity); } return(true); } catch (FileNotFoundException e) { CreateCustomersFile(); _logger.Error(e, "[CustomersRepository::Insert] Insert customerEntity failed. Can note find file. Entity: {}", customerEntity); throw new DataAccessException("[CustomersRepository::Insert] Insert customerEntity failed.", e); } catch (Exception e) { _logger.Error(e, "[CustomersRepository::Insert] Insert customerEntity failed. Can note find file. Entity: {}", customerEntity); throw new DataAccessException("[CustomersRepository::Insert] Insert customerEntity failed.", e); } }
protected override void Load(ContainerBuilder builder) { // var assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray(); //builder.RegisterAssemblyTypes(assemblies).Where(b => b.GetInterfaces(). // Any(c => c == baseType && b != baseType)).AsImplementedInterfaces().InstancePerLifetimeScope(); ////自动注册控制器 //builder.RegisterControllers(assemblies); string path = Assembly.GetExecutingAssembly().Location; string[] dllFiles = new string[] { "ApiDoc.DAL.dll", "ApiDoc.BLL.dll" }; var basePath = path.Replace("ApiDoc.dll", ""); List <Assembly> assList = new List <Assembly>(); foreach (string file in dllFiles) { var businessDALFile = Path.Combine(basePath, file); var assemblysBusiness = Assembly.LoadFrom(businessDALFile); assList.Add(assemblysBusiness); } builder.RegisterAssemblyTypes(assList.ToArray()) .AsImplementedInterfaces() //对每一个依赖或每一次调用创建一个新的唯一的实例。这也是默认的创建实例的方式。 .InstancePerDependency(); //注册路由集合 builder.RegisterType <DBRouteValueDictionary>().SingleInstance(); //builder.RegisterType<MyConfig>().SingleInstance(); //配置文件,验证码,数据库的连接方式 string jsonName = basePath + "MyConfig"; MyConfig myConfig = new JsonFileHelper(jsonName).Read <MyConfig>(); builder.RegisterInstance(myConfig).SingleInstance(); //注册数据库 builder.RegisterType <OracleConnection>().Named <IDbConnection>("Oracle"); builder.RegisterType <OracleDataAdapter>().Named <IDbDataAdapter>("Oracle"); builder.RegisterType <OracleParameter>().Named <DbParameter>("Oracle"); builder.RegisterType <SqlConnection>().Named <IDbConnection>("SqlServer"); builder.RegisterType <SqlDataAdapter>().Named <IDbDataAdapter>("SqlServer"); builder.RegisterType <SqlParameter>().Named <DbParameter>("SqlServer"); //MySql.Data.MySqlClient builder.RegisterType <MySqlConnection>().Named <IDbConnection>("MySql"); builder.RegisterType <MySqlDataAdapter>().Named <IDbDataAdapter>("MySql"); builder.RegisterType <MySqlParameter>().Named <DbParameter>("MySql"); #region RS256 builder.RegisterType <JWTHSService>(). As <IJWTService>(). InstancePerLifetimeScope(); //对等验证 //builder.RegisterType<JWTRSService>(). // As<IJWTService>(). // InstancePerLifetimeScope(); //非对等验证 #endregion }
public static void Save() { if (AlbumInfoList?.Count == 0) { return; } JsonFileHelper.SaveAsync(JsonFilename, AlbumInfoList); JsonFileHelper.SaveAsync(Helper.TempFolder, JsonFilename + Helper.TimeStamp, AlbumInfoList); }
public void Update(Action <T> updateAction, bool reload = true, JsonSerializerOptions serializerOptions = null) { JsonFileHelper.AddOrUpdateSection(_jsonFilePath, _sectionName, updateAction, serializerOptions ?? _defaultSerializerOptions); if (reload) { _configuration?.Reload(); } }
void SavePlayerSession() { //Debug.Log("Saving player session to: " + playerSessionFilePath); JsonFileHelper.SaveToFile(playerSessionFilePath, playerInfoSession); #if UNITY_EDITOR UnityEditor.AssetDatabase.Refresh(); #endif }
public MyConfigController(IHostEnvironment hostingEnvironment, MyConfig myConfig, ILogger <MyConfigController> logger) { string path = hostingEnvironment.ContentRootPath + "\\MyConfig"; jsonFileHelper = new JsonFileHelper(path); this.myConfig = myConfig; this.logger = logger; }
public void Update(Action <T> updateAction, bool reload = true) { JsonFileHelper.AddOrUpdateSection(_jsonFilePath, _sectionName, updateAction); if (reload) { _configuration?.Reload(); } }
public LocationViewModel() { string APIKey = ConfigurationManager.AppSettings["BingMapAPIKEY"]; BingMapServices.Provider = new ApplicationIdCredentialsProvider(APIKey); TotalBudget = BinaryFileHelper.BinaryDeserialization("Total Budget"); Locations = JsonFileHelper.JsonDeserialization <Models.Location>("Cinema Locations/locations"); BackCommand = new RelayCommand(BackClick); }
/// <summary> /// Update a CustomerEntity to Json File /// </summary> /// <param name="customerEntity"></param> /// <returns>True, if the entity is successfully updated; /// False, if there is no customer has the identical user name /// </returns> public bool Update(CustomerEntity customerEntity) { if (_logger.IsDebugEnabled) { _logger.Debug("[CustomersRepository::Update] Starting update customerEntity. CustomerEntity: {}", customerEntity); } try { if (customerEntity == null) { throw new ArgumentNullException( nameof(customerEntity), "[CustomersRepository::Update] CustomerEntity can not be null."); } var jObjectFromFile = JsonFileHelper.ReadJsonFile(_customersFilePath, _customersFileName); var customerEntityJObject = jObjectFromFile["Customers"].FirstOrDefault( c => string.Equals(customerEntity.UserName, (string)c["UserName"]) && customerEntity.Id == (int)c["Id"]); // Can't update if id and userName are not matched if (customerEntityJObject == null) { _logger.Warn( "[CustomersRepository::Update] Can't update if id and userName are not matched. CustomerEntity: {}", customerEntity); return(false); } UpdateJTokenByEntity(customerEntityJObject, customerEntity); JsonFileHelper.WriteJsonFile(_customersFilePath, _customersFileName, jObjectFromFile); if (_logger.IsDebugEnabled) { _logger.Debug( "[CustomersRepository::Update] Update customerEntity Successfully. UpdatedEntity: {0}", customerEntity); } return(true); } catch (FileNotFoundException e) { CreateCustomersFile(); _logger.Error(e, "[CustomersRepository::Update] Update customerEntity failed. Can note find file. Entity: {0}", customerEntity); throw new DataAccessException("[CustomersRepository::Update] Update customerEntity failed. Can note find file.", e); } catch (Exception e) { _logger.Error(e, "[CustomersRepository::Update] Update customerEntity failed. Entity: {0}", customerEntity); throw new DataAccessException("[CustomersRepository::Update] Update customerEntity failed. ", e); } }
public EnvironmentAgentRepository() { var jsonData = JsonFileHelper.GetFileContents(_configurationFilePath); Identities = !string.IsNullOrEmpty(jsonData) ? JsonProcessor.DeserializeObject <Dictionary <string, List <EnvironmentAgent> > >(jsonData) : null; Identities = Identities ?? new Dictionary <string, List <EnvironmentAgent> >(); }
///<summary> ///Returns all products from the store with the passed store id. ///</summary> public List <Product> GetStoreProducts(int storeId) { ProductCatalog = JsonFileHelper <Dictionary <int, List <Product> > > .ReadJsonSingle(jsonFilePath); if (ProductCatalog.ContainsKey(storeId)) { return(ProductCatalog[storeId]); } return(new List <Product>()); }
public SupportAuthPrincipalCreator() { var jsonFile = Path.Combine(JsonFileHelper.ExecutingDir(), ConfigurationManager.AppSettings["SupportAuthFileName"]); if (File.Exists(jsonFile)) { var jsonData = File.ReadAllText(jsonFile); this.supportAuthAgents = JsonProcessor.DeserializeObject <Dictionary <string, AuthClaimsVm> >(jsonData); } }
public async Task <ActionResult <List <BaseConfigDTO> > > GetDetailsImagesConfig() { var filepath = Path.Combine(Directory.GetCurrentDirectory(), "config/detailsPic.json"); JObject jObject = await JsonFileHelper.GetConfig <JObject>(filepath); string data = jObject.GetValue("data").ToString(); List <BaseConfigDTO> baseConfigs = JsonConvert.DeserializeObject <List <BaseConfigDTO> >(data); return(Ok(baseConfigs)); }
public async Task <ActionResult <IndexVideoConfigDTO> > GetIndexVideoOrImageConfig() { var filepath = Path.Combine(Directory.GetCurrentDirectory(), "config/indexVideo.json"); JObject jObject = await JsonFileHelper.GetConfig <JObject>(filepath); string data = jObject.GetValue("data").ToString(); IndexVideoConfigDTO baseConfigs = JsonConvert.DeserializeObject <IndexVideoConfigDTO>(data); return(Ok(baseConfigs)); }
private static UserSettings ReadSettingsFromFile() { var userSettingsFileContents = JsonFileHelper.GetFileContents(UserConfigFilePath); UserSettings settings = null; if (userSettingsFileContents != null) { settings = JsonConvert.DeserializeObject <UserSettings>(userSettingsFileContents); } return(settings); }
private void SaveConfiguration() { var serviceOptionInfos = new ServiceOptionInfoList { ServiceOptionInfos = ServiceOptions.Values.ToList() }; var fileContents = JsonProcessor.SerializeObject(serviceOptionInfos, indented: true); JsonFileHelper.SaveFileContents(_configurationFilePath, fileContents); }