//10. Import Parts public static string ImportParts(CarDealerContext context, string inputXml) { const string root = "Parts"; var partsDto = XmlConverter.Deserialize <ImportPartsDTO>(inputXml, root); var supplierIds = context.Suppliers .Select(x => x.Id) .ToList(); var parts = partsDto .Where(s => supplierIds.Contains(s.SupplierId)) .Select(x => new Part { Name = x.Name, Price = x.Price, Quantity = x.Quantity, SupplierId = x.SupplierId }) .ToList(); context.Parts.AddRange(parts); context.SaveChanges(); return($"Successfully imported {parts.Count()}"); }
//13. Import Sales public static string ImportSales(CarDealerContext context, string inputXml) { const string root = "Sales"; var salesDto = XmlConverter.Deserialize <ImportSaleDTO>(inputXml, root); var carIds = context.Cars .Select(x => x.Id) .ToList(); var sales = salesDto .Where(s => carIds.Contains(s.CarId)) .Select(x => new Sale { CarId = x.CarId, CustomerId = x.CustomerId, Discount = x.Discount }) .ToList(); context.Sales.AddRange(sales); context.SaveChanges(); return($"Successfully imported {sales.Count()}"); }
private static ProcessConfig BuildConfig(XDocument xmlDocument) { string xmlString = xmlDocument.ToString(); var result = XmlConverter.Deserialize <ProcessConfig>(xmlString); return(result); }
public async Task HappyPath_ManyUniquePrnsGeneratedAndSeedUpdatedToExpectedValue() { // arrange var validXmlLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), @"ExampleXML\v3-valid-many-insertions.xml"); var validXmlString = File.ReadAllText(new Uri(validXmlLocation).LocalPath); var validXmlBytes = File.ReadAllBytes(new Uri(validXmlLocation).LocalPath); using (var database = new DatabaseWrapper()) { var modelHelper = new ModelHelper(database.Model); var org = modelHelper.CreateOrganisation(); var scheme = modelHelper.CreateScheme(org); var memberUpload = modelHelper.CreateMemberUpload(scheme); var message = new ProcessXmlFile(org.Id, validXmlBytes, "File name"); var initialSeed = database.WeeeContext.SystemData.Select(sd => sd.LatestPrnSeed).First(); var expectedSeed = ExpectedSeedAfterThisXml(validXmlString, initialSeed); var whiteSpaceCollapser = A.Fake <IWhiteSpaceCollapser>(); var xmlConverter = new XmlConverter(whiteSpaceCollapser, new Deserializer()); var schemeType = xmlConverter.Deserialize <schemeType>(xmlConverter.Convert(message.Data)); var producerCharges = new Dictionary <string, ProducerCharge>(); var anyAmount = 30; var anyChargeBandAmount = A.Dummy <ChargeBandAmount>(); foreach (var producerData in schemeType.producerList) { var producerName = producerData.GetProducerName(); if (!producerCharges.ContainsKey(producerName)) { producerCharges.Add(producerName, new ProducerCharge { Amount = anyAmount, ChargeBandAmount = anyChargeBandAmount }); } } database.Model.SaveChanges(); var contextMemberUpload = database.WeeeContext.MemberUploads .Single(mu => mu.Id == memberUpload.Id); // act var producers = await new GenerateFromXml( xmlConverter, new GenerateFromXmlDataAccess(database.WeeeContext)).GenerateProducers(message, contextMemberUpload, producerCharges); // assert long newSeed = database.WeeeContext.SystemData.Select(sd => sd.LatestPrnSeed).First(); Assert.Equal(expectedSeed, newSeed); var prns = producers.Select(p => p.RegisteredProducer.ProducerRegistrationNumber); Assert.Equal(prns.Distinct(), prns); // all prns should be unique } }
public T Get <T>(Enum key) { var serialized = ReadFromDisc(key.ToString()); var deserialized = XmlConverter.Deserialize <T>(serialized); return(deserialized); }
public async Task HappyPath_ManyUniquePrnsGeneratedAndSeedUpdatedToExpectedValue() { // arrange var validXmlLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), @"ExampleXML\v3-valid-many-insertions.xml"); var validXmlString = File.ReadAllText(new Uri(validXmlLocation).LocalPath); var validXmlBytes = File.ReadAllBytes(new Uri(validXmlLocation).LocalPath); using (var database = new DatabaseWrapper()) { var modelHelper = new ModelHelper(database.Model); var org = modelHelper.CreateOrganisation(); var scheme = modelHelper.CreateScheme(org); var memberUpload = modelHelper.CreateMemberUpload(scheme); var message = new ProcessXmlFile(org.Id, validXmlBytes, "File name"); var initialSeed = database.WeeeContext.SystemData.Select(sd => sd.LatestPrnSeed).First(); var expectedSeed = ExpectedSeedAfterThisXml(validXmlString, initialSeed); var whiteSpaceCollapser = A.Fake<IWhiteSpaceCollapser>(); var xmlConverter = new XmlConverter(whiteSpaceCollapser, new Deserializer()); var schemeType = xmlConverter.Deserialize<schemeType>(xmlConverter.Convert(message.Data)); var producerCharges = new Dictionary<string, ProducerCharge>(); var anyAmount = 30; var anyChargeBandAmount = A.Dummy<ChargeBandAmount>(); foreach (var producerData in schemeType.producerList) { var producerName = producerData.GetProducerName(); if (!producerCharges.ContainsKey(producerName)) { producerCharges.Add(producerName, new ProducerCharge { Amount = anyAmount, ChargeBandAmount = anyChargeBandAmount }); } } database.Model.SaveChanges(); var contextMemberUpload = database.WeeeContext.MemberUploads .Single(mu => mu.Id == memberUpload.Id); // act var producers = await new GenerateFromXml( xmlConverter, new GenerateFromXmlDataAccess(database.WeeeContext)).GenerateProducers(message, contextMemberUpload, producerCharges); // assert long newSeed = database.WeeeContext.SystemData.Select(sd => sd.LatestPrnSeed).First(); Assert.Equal(expectedSeed, newSeed); var prns = producers.Select(p => p.RegisteredProducer.ProducerRegistrationNumber); Assert.Equal(prns.Distinct(), prns); // all prns should be unique } }
private static void GetLoop(ValueSet valueSet) { int playlistIndex = int.Parse(valueSet["Loop"].ToString()); Library.Current[playlistIndex].Loop = XmlConverter.Deserialize <LoopKind>(valueSet["Kind"].ToString()); BackgroundAudioTask.Current.SetLoopToBackgroundPlayer(); Library.Current.SaveAsync(); }
private static void GetShuffle(ValueSet valueSet) { int playlistIndex = int.Parse(valueSet["Shuffle"].ToString()); Library.Current[playlistIndex].Shuffle = XmlConverter.Deserialize <ShuffleKind>(valueSet["Kind"].ToString()); Library.Current[playlistIndex].ShuffleList = XmlConverter.Deserialize <List <int> >(valueSet["List"].ToString()); Library.Current.SaveAsync(); }
public void Load(string xmlText) { SaveLibray sc = XmlConverter.Deserialize <SaveLibray>(xmlText); playlists = sc.Playlists; currentPlaylistIndex = sc.CurrentPlaylistIndex; SetLoaded(); }
/// <summary> /// 初始化 /// </summary> public virtual void Initial() { YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); SysSetting sysSetting = XmlConverter.Deserialize <SysSetting>("xmlconfig/sys.config"); if (sysSetting != null) { yuebonCacheHelper.Add("SysSetting", sysSetting); } }
public async Task <IActionResult> GetSysInfo() { CommonResult result = new CommonResult(); try { SysSetting sysSetting = XmlConverter.Deserialize <SysSetting>("xmlconfig/sys.config"); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); yuebonCacheHelper.Add("SysSetting", sysSetting); DashboardOutModel dashboardOutModel = new DashboardOutModel(); dashboardOutModel.CertificatedCompany = sysSetting.CompanyName; dashboardOutModel.WebUrl = sysSetting.WebUrl; dashboardOutModel.Title = sysSetting.SoftName; dashboardOutModel.MachineName = Environment.MachineName; dashboardOutModel.ProcessorCount = Environment.ProcessorCount; dashboardOutModel.SystemPageSize = Environment.SystemPageSize; dashboardOutModel.WorkingSet = Environment.WorkingSet; dashboardOutModel.TickCount = Environment.TickCount; dashboardOutModel.RunTimeLength = (Environment.TickCount / 1000).ToBrowseTime(); dashboardOutModel.FrameworkDescription = RuntimeInformation.FrameworkDescription; dashboardOutModel.OSName = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "Linux" : RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "OSX" : "Windows"; dashboardOutModel.OSDescription = RuntimeInformation.OSDescription + " " + RuntimeInformation.OSArchitecture; dashboardOutModel.OSArchitecture = RuntimeInformation.OSArchitecture.ToString(); dashboardOutModel.ProcessArchitecture = RuntimeInformation.ProcessArchitecture.ToString(); dashboardOutModel.Directory = AppContext.BaseDirectory; Version version = Environment.Version; dashboardOutModel.SystemVersion = version.Major + "." + version.Minor + "." + version.Build; dashboardOutModel.Version = AppVersionHelper.Version; dashboardOutModel.Manufacturer = AppVersionHelper.Manufacturer; dashboardOutModel.WebSite = AppVersionHelper.WebSite; dashboardOutModel.UpdateUrl = AppVersionHelper.UpdateUrl; dashboardOutModel.IPAdress = Request.HttpContext.Connection.LocalIpAddress.ToString(); dashboardOutModel.Port = Request.HttpContext.Connection.LocalPort.ToString(); dashboardOutModel.TotalUser = await userService.GetCountByWhereAsync("1=1"); dashboardOutModel.TotalModule = await menuService.GetCountByWhereAsync("1=1"); dashboardOutModel.TotalRole = await roleService.GetCountByWhereAsync("1=1"); dashboardOutModel.TotalTask = await taskManagerService.GetCountByWhereAsync("1=1"); result.ResData = dashboardOutModel; result.ErrCode = ErrCode.successCode; } catch (Exception ex) { Log4NetHelper.Error("获取系统信息异常", ex); result.ErrMsg = ErrCode.err60001; result.ErrCode = "60001"; } return(ToJsonContent(result)); }
public void AppendReportInfo(XmlDocument xml, string caption, int count, IFormattable dat, Dictionary <string, Image> imagelist) { try { reportInfo ri = xc.Deserialize(typeof(reportInfo), xml.DocumentElement.OuterXml) as reportInfo; AppendReportInfo(ri, caption, count, dat, imagelist); } catch (Exception ex) { errors += string.Format("Ошибка в шаблоне {0}, [{2}]\n ", caption, ex.Message); } }
private void ReceiveSongsPropertyChanged(ValueSet valueSet, string value) { string playlistPath = valueSet[playlistPathKey].ToString(); IPlaylist changedPlaylist; if (!HavePlaylist(playlistPath, out changedPlaylist)) { return; } changedPlaylist.Songs = XmlConverter.Deserialize(new SongCollection(), value); }
//12. Import Customers public static string ImportCustomers(CarDealerContext context, string inputXml) { const string root = "Customers"; InitializeAutoMapper(); var customersDto = XmlConverter.Deserialize <ImportCustomerDTO>(inputXml, root); var customers = mapper.Map <Customer[]>(customersDto); context.Customers.AddRange(customers); context.SaveChanges(); return($"Successfully imported {customers.Count()}"); }
public IActionResult Save(SysSetting info) { CommonResult result = new CommonResult(); info.LocalPath = _hostingEnvironment.WebRootPath; SysSetting sysSetting = XmlConverter.Deserialize <SysSetting>("xmlconfig/sys.config"); sysSetting = info; //对关键信息加密 if (!string.IsNullOrEmpty(info.Email)) { sysSetting.Email = DEncrypt.Encrypt(info.Email); } if (!string.IsNullOrEmpty(info.Emailsmtp)) { sysSetting.Emailsmtp = DEncrypt.Encrypt(info.Emailsmtp); } if (!string.IsNullOrEmpty(info.Emailpassword)) { sysSetting.Emailpassword = DEncrypt.Encrypt(info.Emailpassword); } if (!string.IsNullOrEmpty(info.Smspassword)) { sysSetting.Smspassword = DEncrypt.Encrypt(info.Smspassword); } if (!string.IsNullOrEmpty(info.Smsusername)) { sysSetting.Smsusername = DEncrypt.Encrypt(info.Smsusername); } string uploadPath = _hostingEnvironment.WebRootPath + "/" + sysSetting.Filepath; if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); if (yuebonCacheHelper.Exists("SysSetting")) { yuebonCacheHelper.Replace("SysSetting", sysSetting); } else { //写入缓存 yuebonCacheHelper.Add("SysSetting", sysSetting); } XmlConverter.Serialize <SysSetting>(sysSetting, "xmlconfig/sys.config"); result.ErrCode = ErrCode.successCode; return(ToJsonContent(result)); }
public IActionResult GetAllInfo() { CommonResult result = new CommonResult(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); SysSetting sysSetting = yuebonCacheHelper.Get("SysSetting").ToJson().ToObject <SysSetting>(); SysSettingOutputDto sysSettingOutputDto = new SysSettingOutputDto(); if (sysSetting == null) { sysSetting = XmlConverter.Deserialize <SysSetting>("xmlconfig/sys.config"); } //对关键信息解密 if (!string.IsNullOrEmpty(sysSetting.Email)) { sysSetting.Email = DEncrypt.Decrypt(sysSetting.Email); } if (!string.IsNullOrEmpty(sysSetting.Emailsmtp)) { sysSetting.Emailsmtp = DEncrypt.Decrypt(sysSetting.Emailsmtp); } if (!string.IsNullOrEmpty(sysSetting.Emailpassword)) { sysSetting.Emailpassword = DEncrypt.Decrypt(sysSetting.Emailpassword); } if (!string.IsNullOrEmpty(sysSetting.Smspassword)) { sysSetting.Smspassword = DEncrypt.Decrypt(sysSetting.Smspassword); } if (!string.IsNullOrEmpty(sysSetting.Smsusername)) { sysSetting.Smsusername = DEncrypt.Decrypt(sysSetting.Smsusername); } sysSettingOutputDto = sysSetting.MapTo <SysSettingOutputDto>(); if (sysSettingOutputDto != null) { sysSettingOutputDto.CopyRight = UIConstants.CopyRight; result.ResData = sysSettingOutputDto; result.Success = true; result.ErrCode = ErrCode.successCode; } else { result.ErrMsg = ErrCode.err60001; result.ErrCode = "60001"; } return(ToJsonContent(result)); }
public void ReadXml(XmlReader reader) { string currentPlaylistPath = reader.GetAttribute("CurrentPlaylistPath"); try { Playlists = XmlConverter.Deserialize(new PlaylistCollection(), reader.ReadInnerXml()); } catch (Exception e) { MobileDebug.Service.WriteEvent("LibraryXmlLoadFail", e, reader.Name, reader.NodeType); throw; } CurrentPlaylist = Playlists.FirstOrDefault(p => p.AbsolutePath == currentPlaylistPath) ?? Playlists.FirstOrDefault(); Loaded?.Invoke(this, System.EventArgs.Empty); }
private static void GetPlaylistXML(ValueSet valueSet) { string currentSongPath = CurrentSong.Path; int playlistIndex = int.Parse(valueSet["PlaylistXML"].ToString()); Playlist playlist = XmlConverter.Deserialize <Playlist>(valueSet["XML"].ToString()); if (Library.Current[playlistIndex].AbsolutePath != playlist.AbsolutePath && !Library.Current.HavePlaylistIndex(playlist.AbsolutePath, out playlistIndex)) { return; } Library.Current[playlistIndex] = playlist; PlaySongIfOther(currentSongPath); Library.Current.SaveAsync(); }
private static void GetSongXML(ValueSet valueSet) { string currentSongPath = CurrentSong.Path; string[] parts = valueSet["SongXML"].ToString().Split(';'); int playlistIndex = int.Parse(parts[0]); int songsIndex = int.Parse(parts[1]); Song song = XmlConverter.Deserialize <Song>(valueSet["XML"].ToString()); if (Library.Current[playlistIndex][songsIndex].Path != song.Path && !Library.Current.HavePlaylistIndexAndSongsIndex(song.Path, out playlistIndex, out songsIndex)) { return; } Library.Current[playlistIndex][songsIndex] = song; PlaySongIfOther(currentSongPath); Library.Current.SaveAsync(); }
private void ReceiveSongsChanged(ValueSet valueSet, string value) { MobileDebug.Service.WriteEvent("ReceiveSongs1"); string playlistPath = valueSet[playlistPathKey].ToString(); string removeXml = valueSet[removeKey].ToString(); string addXml = valueSet[addKey].ToString(); IPlaylist changedPlaylist; if (!HavePlaylist(playlistPath, out changedPlaylist)) { return; } Song[] removes = XmlConverter.Deserialize <Song[]>(removeXml); Song[] adds = XmlConverter.Deserialize <Song[]>(addXml); MobileDebug.Service.WriteEvent("ReceiveSongs2", adds.Length, removes.Length); for (int i = 0; i < removes.Length; i++) { Song song = removes[i]; song = changedPlaylist.Songs.FirstOrDefault(s => s.Path == song.Path); if (song != null) { removes[i] = song; } } for (int i = 0; i < adds.Length; i++) { Song song = adds[i]; song = changedPlaylist.Songs.Shuffle.FirstOrDefault(s => s.Path == song.Path); if (song != null) { adds[i] = song; } } MobileDebug.Service.WriteEvent("ReceiveSongs3"); changedPlaylist.Songs.Change(removes, adds); }
private void ReceiveShuffleCollectionChanged(ValueSet valueSet, string value) { string playlistPath = valueSet[playlistPathKey].ToString(); string removeXml = valueSet[removeKey].ToString(); string addXml = valueSet[addKey].ToString(); IPlaylist changedPlaylist; if (!HavePlaylist(playlistPath, out changedPlaylist)) { return; } Song[] removes = XmlConverter.Deserialize <Song[]>(removeXml); ChangeCollectionItem <Song>[] adds = XmlConverter.Deserialize <ChangeCollectionItem <Song>[]>(addXml); for (int i = 0; i < removes.Length; i++) { Song song = removes[i]; song = changedPlaylist.Songs.Shuffle.FirstOrDefault(s => s.Path == song.Path); if (song != null) { removes[i] = song; } } for (int i = 0; i < adds.Length; i++) { Song song = adds[i].Item; song = changedPlaylist.Songs.FirstOrDefault(s => s.Path == song.Path); if (song != null) { adds[i].Item = song; } } changedPlaylist.Songs.Shuffle.Change(removes, adds); }
private void ReceivePlaylistsCollectionChanged(ValueSet valueSet, string value) { string removeXml = valueSet[removeKey].ToString(); string addXml = valueSet[addKey].ToString(); string[] removePaths = XmlConverter.Deserialize <string[]>(removeXml); Playlist[] adds = XmlConverter.DeserializeList <Playlist>(addXml).ToArray(); List <IPlaylist> removes = new List <IPlaylist>(); foreach (string path in removePaths) { IPlaylist playlist; if (HavePlaylist(path, out playlist)) { removes.Add(playlist); } } library.Playlists.Change(removes, adds); }
private static void GetPlaylistsAndSongsIndexAndShuffle(ValueSet valueSet) { string currentSongPath = CurrentSong.Path; string path = valueSet["Path"].ToString(); string[] parts = valueSet["PlaylistsAndSongsIndexAndShuffle"].ToString().Split(';'); int playlistIndex = int.Parse(parts[0]); int songsIndex = int.Parse(parts[1]); if (Library.Current[playlistIndex][songsIndex].Path != path && !Library.Current.HavePlaylistIndexAndSongsIndex(path, out playlistIndex, out songsIndex)) { return; } Library.Current.CurrentPlaylistIndex = playlistIndex; Library.Current.CurrentPlaylist.SongsIndex = songsIndex; Library.Current.CurrentPlaylist.Shuffle = XmlConverter.Deserialize <ShuffleKind>(valueSet["ShuffleKind"].ToString()); Library.Current.CurrentPlaylist.ShuffleList = XmlConverter.Deserialize <List <int> >(valueSet["ShuffleList"].ToString()); PlaySongIfOther(currentSongPath); }
public void ReadXml(XmlReader reader) { double currentSongPosition = double.Parse(reader.GetAttribute("CurrentSongPosition") ?? "0"); AbsolutePath = reader.GetAttribute("AbsolutePath") ?? emptyOrLoadingPath; Name = reader.GetAttribute("Name") ?? emptyName; Loop = (LoopType)Enum.Parse(typeof(LoopType), reader.GetAttribute("Loop") ?? LoopType.Off.ToString()); string currentSongPath = reader.GetAttribute("CurrentSongPath") ?? string.Empty;; ShuffleType shuffle = (ShuffleType)Enum.Parse(typeof(ShuffleType), reader.GetAttribute("Shuffle") ?? ShuffleType.Off.ToString()); reader.ReadStartElement(); ISongCollection songs = reader.Name == typeof(SongCollection).Name ? (ISongCollection) new SongCollection() : new SimpleSongCollection(); songs.Parent = this; Songs = XmlConverter.Deserialize(songs, reader.ReadOuterXml()); CurrentSong = songs.FirstOrDefault(s => s.Path == currentSongPath) ?? songs.FirstOrDefault(); CurrentSongPosition = currentSongPosition; }
public IActionResult GetInfo() { CommonResult result = new CommonResult(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); SysSetting sysSetting = yuebonCacheHelper.Get("SysSetting").ToJson().ToObject <SysSetting>(); SysSettingOutputDto sysSettingOutputDto = new SysSettingOutputDto(); if (sysSetting == null) { sysSetting = XmlConverter.Deserialize <SysSetting>("xmlconfig/sys.config"); } sysSetting.Email = ""; sysSetting.Emailsmtp = ""; sysSetting.Emailpassword = ""; sysSetting.Smspassword = ""; sysSetting.SmsSignName = ""; sysSetting.Smsusername = ""; sysSettingOutputDto = sysSetting.MapTo <SysSettingOutputDto>(); if (sysSettingOutputDto != null) { sysSettingOutputDto.CopyRight = UIConstants.CopyRight; result.ResData = sysSettingOutputDto; result.Success = true; result.ErrCode = ErrCode.successCode; } else { result.ErrMsg = ErrCode.err60001; result.ErrCode = "60001"; } IEnumerable <APP> appList = aPPService.GetAllByIsNotDeleteAndEnabledMark(); yuebonCacheHelper.Add("AllowAppId", appList); return(ToJsonContent(result)); }
public async static Task <T> LoadObject <T>(string filenameWithExtention) { return(XmlConverter.Deserialize <T>(await LoadText(filenameWithExtention))); }