// Load assemblies needed for this code to run private static List<Assembly> LoadDLRAssemblies(StreamResourceInfo xap) { var assemblies = new List<Assembly>(); foreach (string assm in _dlrAssemblies) { assemblies.Add(new AssemblyPart().Load(Application.GetResourceStream(xap, new Uri(string.Format("{0}.dll", assm), UriKind.Relative)).Stream)); } return assemblies; }
//public void Save(string imageUrl) //{ // ThreadPool.QueueUserWorkItem(GetImage, imageUrl); //} private void Download(string imageUrl, string imageName, Action<BitmapImage> callBack, string imageSaveName) { var imageUri = new Uri(string.Format(imageUrl, imageName)); var client = new WebClient(); client.OpenReadCompleted += (s, e) => { try { var streamResourseInfo = new StreamResourceInfo(e.Result, null); var streamReader = new StreamReader(streamResourseInfo.Stream); byte[] imageBytes; using (var binaryReader = new BinaryReader(streamReader.BaseStream)) { imageBytes = binaryReader.ReadBytes((int)streamReader.BaseStream.Length); } string name = imageSaveName ?? imageName; using (var stream = _isolatedStorageFile.CreateFile(name)) { stream.Write(imageBytes, 0, imageBytes.Length); var image = new BitmapImage(); image.SetSource(stream); callBack.Invoke(image); } } catch (Exception ex) { // Let it fail if not something catastrophic if (!(ex is WebException)) throw; } }; client.OpenReadAsync(imageUri, client); }
static void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { StreamResourceInfo zipInfo = new StreamResourceInfo(e.Result, null); // Read manifest from zip file StreamResourceInfo manifestInfo = Application.GetResourceStream(_zipInfo, new Uri("content.xml", UriKind.Relative)); StreamReader reader = new StreamReader(manifestInfo.Stream); XDocument document = XDocument.Load(reader); var mediaFiles = from m in document.Descendants("mediafile") select new MediaInfo { Type = (MediaType) Enum.Parse(typeof(MediaType), m.Attribute("type").Value, true), Name = m.Attribute("name").Value }; _mediaInfos = new List<MediaInfo>(); _mediaInfos.AddRange(mediaFiles); ProgressTextBlock.Visibility = Visibility.Collapsed; PrevButton.IsEnabled = true; NextButton.IsEnabled = true; DisplayMedia(_mediaInfos[0]); StreamResourceInfo manifestInfo = Application.GetResourceStream(zipInfo, new Uri("content.xml", UriKind.Relative)); StreamReader reader = new StreamReader(manifestInfo.Stream); XDocument xd = XDocument.Load(reader); reader.Close(); var files = from m in xd.Descendants("templatefile") select m.Attribute("name").Value; if (DataTemplates == null) DataTemplates = new Dictionary<string, string>(); foreach (var f in files) { string filename = f + ".xaml"; StreamResourceInfo streamInfo = Application.GetResourceStream(zipInfo, new Uri(filename, UriKind.Relative)); using (StreamReader r = new StreamReader(streamInfo.Stream)) { string s = r.ReadToEnd(); if (!DataTemplates.ContainsKey(f)) DataTemplates.Add(f, s); } } } }
public MainPage() { InitializeComponent(); xml = App.GetResourceStream(new Uri("dinesafe.xml", UriKind.Relative)); loadedData = XDocument.Load(xml.Stream); var data = from query in loadedData.Descendants("ROW") select new DineSafe { Name = (string)query.Attribute("N"), FoodType = (string)query.Attribute("T"), Address = (string)query.Attribute("A"), Status = (string)query.Attribute("S"), Details = (string)query.Attribute("D"), Date = (string)query.Attribute("I"), Severity = (string)query.Attribute("X") }; original = data.ToArray<DineSafe>(); Dictionary<string, short> seenEntries = new Dictionary<string, short>(); foreach (DineSafe dineSafe in data) { string key = dineSafe.GetKey(); if (!seenEntries.ContainsKey(key)) { uniques.Add(dineSafe); seenEntries.Add(key, 0); } } seenEntries.Clear(); array = uniques.ToArray(); }
private static void ProcessResults(Stream result) { var manifest = Application.GetResourceStream( new StreamResourceInfo(result,null), new Uri("AppManifest.xaml", UriKind.Relative)); var appManifest = new StreamReader(manifest.Stream).ReadToEnd(); var reader = XmlReader.Create(new StringReader(appManifest)); Assembly asm = null; while (reader.Read()) { if(!reader.IsStartElement("AssemblyPart")) continue; reader.MoveToAttribute("Source"); reader.ReadAttributeValue(); if(!reader.Value.EndsWith(".dll")|| !reader.Value.StartsWith("Sydney")) continue; var assemblyStream = new StreamResourceInfo(result, "application/binary"); var si = Application.GetResourceStream(assemblyStream, new Uri(reader.Value, UriKind.Relative)); var p = new AssemblyPart(); asm = p.Load(si.Stream); break; } if(asm==null) return; var type = (from t in asm.GetTypes() where t.FullName.StartsWith("Sydney") select t).FirstOrDefault(); Activator.CreateInstance(type); }
void WebClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { const string tempJpeg = "TempJPEG"; var streamResourceInfo = new StreamResourceInfo(e.Result, null); var userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication(); if (userStoreForApplication.FileExists(tempJpeg)) { userStoreForApplication.DeleteFile(tempJpeg); } var isolatedStorageFileStream = userStoreForApplication.CreateFile(tempJpeg); var bitmapImage = new BitmapImage { CreateOptions = BitmapCreateOptions.None }; bitmapImage.SetSource(streamResourceInfo.Stream); var writeableBitmap = new WriteableBitmap(bitmapImage); writeableBitmap.SaveJpeg(isolatedStorageFileStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 85); isolatedStorageFileStream.Close(); isolatedStorageFileStream = userStoreForApplication.OpenFile(tempJpeg, FileMode.Open, FileAccess.Read); // Save the image to the camera roll or saved pictures album. var mediaLibrary = new MediaLibrary(); // Save the image to the saved pictures album. mediaLibrary.SavePicture(string.Format("SavedPicture{0}.jpg", DateTime.Now), isolatedStorageFileStream); isolatedStorageFileStream.Close(); }
public static void Start(Dictionary<string, List<string>> tests, StreamResourceInfo xap) { var assemblies = LoadDLRAssemblies(xap); InitializeDLR(xap, assemblies); LoadEggs(); ConfigureAndRunEggs(tests); }
private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { var manifestStream = Application.GetResourceStream( new StreamResourceInfo(e.Result, null), new Uri("AppManifest.xaml", UriKind.Relative)); string appManifest = new StreamReader(manifestStream.Stream).ReadToEnd(); XmlReader reader = XmlReader.Create(new StringReader(appManifest)); while (reader.Read()) { if (reader.IsStartElement("AssemblyPart")) { reader.MoveToAttribute("Source"); reader.ReadAttributeValue(); if (reader.Value.StartsWith("NIS.Module.") && !reader.Value.Contains("Interfaces") && !reader.Value.Contains("Services"))//&& reader.Value != assemblyName && GetMainAssembly==null { var assemblyStream = new StreamResourceInfo(e.Result, "application/binary"); var si = Application.GetResourceStream(assemblyStream, new Uri(reader.Value, UriKind.Relative)); GetMainAssembly(new AssemblyPart().Load(si.Stream)); _countModulesToLoad++; if(_countModulesToLoad==_overalModuleCount) { LoadCompleted(null, null); } } } } }
void LoadXap(FileInfo File) { using (FileStream stream = File.OpenRead()) { System.Windows.Resources.StreamResourceInfo Info = new System.Windows.Resources.StreamResourceInfo(stream, "application/binary"); StreamResourceInfo resource = System.Windows.Application.GetResourceStream(Info, new Uri("AppManifest.xaml", UriKind.Relative)); string resourceManifest = new StreamReader(resource.Stream).ReadToEnd(); IEnumerable <XElement> assemblyParts = XDocument.Parse(resourceManifest).Root.Element("Deployment").Element("Deployment.Parts").Elements("AssemblyPart"); foreach (XElement element in assemblyParts) { // 取出 AssemblyPart 的 Source 指定的 dll string source = element.Attribute("Source").Value; string xName = source.Substring(0, source.Length - 4); AssemblyPart assemblyPart = new AssemblyPart(); StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(Info, new Uri(source, UriKind.Relative)); System.Reflection.Assembly assembly = null; try { assembly = assemblyPart.Load(streamInfo.Stream); } catch { } if (assembly != null) { LoadAssembly(assembly); } } } }
public void LoadNationalitiesFromDatabase(List <DatabaseEntry> databaseEntryList) { for (int index = 0; index < databaseEntryList.Count; ++index) { DatabaseEntry databaseEntry = databaseEntryList[index]; string stringValue1 = databaseEntry.GetStringValue("Sprite Reference"); if (!this.mNationalitiesDict.ContainsKey(stringValue1)) { this.mNationalitiesDict[stringValue1] = new Nationality(); this.mNationalitiesDict[stringValue1].continent = NationalityManager.GetContinent(databaseEntry.GetStringValue("Continent")); this.mNationalitiesDict[stringValue1].SetKey(stringValue1); this.mNationalities.Add(this.mNationalitiesDict[stringValue1]); } string stringValue2 = databaseEntry.GetStringValue("ID"); string stringValue3 = databaseEntry.GetStringValue("Type"); if (stringValue3.Equals("Country")) { this.mNationalitiesDict[stringValue1].SetCountry(stringValue2); } else if (stringValue3.Equals("Nationality")) { this.mNationalitiesDict[stringValue1].SetNationality(stringValue2); } try { var uri = new Uri(string.Format("pack://application:,,,/Assets/Flags/{0}.png", this.mNationalitiesDict[stringValue1].localisedCountry)); System.Windows.Resources.StreamResourceInfo resourceStream = Application.GetResourceStream(uri); } catch (Exception ex) { Console.WriteLine("Could not find flag " + this.mNationalitiesDict[stringValue1].localisedCountry + ".png"); } } }
public Stream GetFileStream(string filename) { Uri fileUri = new Uri(filename, UriKind.Relative); StreamResourceInfo info = new StreamResourceInfo(this.stream, null); StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri); if (stream != null) return stream.Stream; return null; }
public static void Start(Uri testsXapUri, StreamResourceInfo eggsXap) { var assemblies = LoadDLRAssemblies(eggsXap); InitializeDLR(eggsXap, assemblies); LoadEggs(); DownloadTestsXap(testsXapUri, delegate(StreamResourceInfo testsXap) { ConfigureAndRunEggs(testsXap); }); }
public Stream GetFileStream(string filename) { var fileUri = new Uri(filename, UriKind.Relative); _stream.Seek(0, SeekOrigin.Begin); var info = new StreamResourceInfo(_stream, null); var stream = System.Windows.Application.GetResourceStream(info, fileUri); if (stream != null) return stream.Stream; return null; }
public static void FetchCompleted(List<string> assemblyNames, object sender, OpenReadCompletedEventArgs e) { var sri = new StreamResourceInfo(e.Result, null); foreach (var assembly in assemblyNames) { var dll = Application.GetResourceStream(sri, new Uri(string.Format("{0}.dll", assembly), UriKind.Relative)); if (dll != null) { Package.LanguageAssemblies.Add(dll); } } }
public void Null () { Assert.Throws<ArgumentNullException> (delegate { new StreamResourceInfo (null, String.Empty); }, "Stream"); StreamResourceInfo sri = new StreamResourceInfo (Stream.Null, null); Assert.IsNull (sri.ContentType, "ContentType"); Assert.IsTrue (Object.ReferenceEquals (Stream.Null, sri.Stream), "Stream"); }
private static void ConfigureAndRunEggs(StreamResourceInfo testsXap) { DynamicApplication.XapFile = testsXap; ScriptScope scope = _engine.CreateScope(); scope.SetVariable("_engine", _engine); var code = "Eggs.run(_engine)"; var source = _engine.CreateScriptSourceFromString(code, SourceCodeKind.File); source.Compile(new ErrorFormatter.Sink()).Execute(scope); }
private void SetupResourceStream(string resourcePath) { if (Uri.IsWellFormedUriString(resourcePath, UriKind.Relative)) { ResourceStream = Application.GetResourceStream(new Uri(resourcePath, UriKind.Relative)); } else { throw new UriFormatException("URI is not well formed"); } }
private static void DownloadTestXap_Complete(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { var sri = new StreamResourceInfo(e.Result, null); if (_onDownloadComplete != null) { _onDownloadComplete.Invoke(sri); } } else { System.Windows.Browser.HtmlPage.Window.Alert("Tests failed to download"); } }
/// <summary> /// Gets the file stream for the specified file. Returns null if the file could not be found. /// </summary> /// <param name="filename">The filename.</param> /// <returns>Stream to file inside zip stream</returns> public Stream GetFileStream(string filename) { Uri fileUri = new Uri(filename, UriKind.Relative); StreamResourceInfo info = new StreamResourceInfo(this.stream, null); if (this.stream is System.IO.FileStream) //For whatever reason, you have to this with file streams, or you will get null back in the next call this.stream.Seek(0, SeekOrigin.Begin); StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri); if (stream != null) return stream.Stream; return null; }
public Song(ContentManager content, string assetName) { _path = assetName; resourceInfo = Application.GetResourceStream(new Uri(_path + ".mp3", UriKind.Relative)); if (resourceInfo == null) { resourceInfo = Application.GetResourceStream(new Uri(_path + ".wma", UriKind.Relative)); } _graphics = ((IGraphicsDeviceService)content.ServiceProvider.GetService(typeof(IGraphicsDeviceService))).GraphicsDevice; }
public static string GetFileContents(StreamResourceInfo xap, Uri relativeUri) { Stream stream = GetFile(xap, relativeUri); if (stream == null) { return null; } string result; using (StreamReader sr = new StreamReader(stream)) { result = sr.ReadToEnd(); } return result; }
/// <summary> /// Gets the file stream for the specified filename. /// </summary> /// <param name="filename">The filename.</param> /// <returns></returns> public Stream GetFileStream(string filename) { if (entries == null) entries = ParseCentralDirectory(); long position = this.stream.Position; this.stream.Seek(0, SeekOrigin.Begin); Uri fileUri = new Uri(filename, UriKind.Relative); StreamResourceInfo info = new StreamResourceInfo(this.stream, null); StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri); this.stream.Position = position; if (stream != null) return stream.Stream; return null; }
/// <summary> /// Gets the file stream for the specified file. Returns null if the file could not be found. /// </summary> /// <param name="filename">The filename.</param> /// <returns>Stream to file inside zip stream</returns> public Stream GetFileStream(string filename) { if (fileEntries == null) fileEntries = ParseCentralDirectory(); //We need to do this in case the zip is in a format Silverligth doesn't like long position = this.stream.Position; this.stream.Seek(0, SeekOrigin.Begin); Uri fileUri = new Uri(filename, UriKind.Relative); StreamResourceInfo info = new StreamResourceInfo(this.stream, null); StreamResourceInfo stream = System.Windows.Application.GetResourceStream(info, fileUri); this.stream.Position = position; if (stream != null) return stream.Stream; return null; }
private void wcXap_OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if ((e.Error == null) && (e.Cancelled == false)) { var xap = new StreamResourceInfo(e.Result, null); System.Reflection.Assembly asm = new AssemblyPart().Load( Application.GetResourceStream( xap, new Uri("Eggs.dll", UriKind.Relative) ).Stream ); asm.GetType("Eggs").GetMethod("Start").Invoke(null, new object[] { (object) new Uri("http://localhost:35863/TicTacToe.Tests.xap"), (object) xap }); } }
private static void InitializeDLR(StreamResourceInfo xap, List<Assembly> assemblies) { DynamicApplication.XapFile = xap; var setup = DynamicApplication.CreateRuntimeSetup(assemblies); setup.DebugMode = true; var runtime = new ScriptRuntime(setup); // Load default silverlight assemblies for the script to have access to DynamicApplication.LoadDefaultAssemblies(runtime); // Load the assemblies into the runtime, giving the script access to them assemblies.ForEach((a) => runtime.LoadAssembly(a)); _engine = IronRuby.Ruby.GetEngine(runtime); _scope = _engine.CreateScope(); }
public static IEnumerable<Assembly> LoadPackagedAssemblies(Stream packageStream) { List<Assembly> assemblies = new List<Assembly>(); StreamResourceInfo packageStreamInfo = new StreamResourceInfo(packageStream, null); IEnumerable<AssemblyPart> parts = GetDeploymentParts(packageStreamInfo); foreach (AssemblyPart ap in parts) { StreamResourceInfo sri = Application.GetResourceStream(packageStreamInfo, new Uri(ap.Source, UriKind.Relative)); assemblies.Add(ap.Load(sri.Stream)); } packageStream.Close(); return assemblies; }
public LineMap() { InitializeComponent(); PageHeader.ShowProgresBar = true; Vasttrafik.Data.VasttrafikAPI api = new Data.VasttrafikAPI(); if (NetworkInterface.GetIsNetworkAvailable()) { api.GetImage(image => Deployment.Current.Dispatcher.BeginInvoke(() => { BitmapImage img = new BitmapImage(); StreamResourceInfo Resource = new StreamResourceInfo(image, null); img.SetSource(Resource.Stream); mymap.Source = img; PageHeader.ShowProgresBar = false; })); } else { PageHeader.ShowProgresBar = false; } }
/// <summary> /// Only reads AssemblyParts and does not support external parts (aka Platform Extensions or TPEs). /// </summary> private static IEnumerable<AssemblyPart> GetDeploymentParts(StreamResourceInfo xapStreamInfo) { Uri manifestUri = new Uri("AppManifest.xaml", UriKind.Relative); StreamResourceInfo manifestStreamInfo = Application.GetResourceStream(xapStreamInfo, manifestUri); List<AssemblyPart> assemblyParts = new List<AssemblyPart>(); // The code assumes the following format in AppManifest.xaml //<Deployment ... > // <Deployment.Parts> // <AssemblyPart x:Name="A" Source="A.dll" /> // <AssemblyPart x:Name="B" Source="B.dll" /> // ... // <AssemblyPart x:Name="Z" Source="Z.dll" /> // </Deployment.Parts> //</Deployment> if (manifestStreamInfo != null) { Stream manifestStream = manifestStreamInfo.Stream; using (XmlReader reader = XmlReader.Create(manifestStream)) { if (reader.ReadToFollowing("AssemblyPart")) { do { string source = reader.GetAttribute("Source"); if (source != null) { assemblyParts.Add( new AssemblyPart { Source = source }); } } while (reader.ReadToNextSibling("AssemblyPart")); } } } return assemblyParts; }
public PersonalityTraitDataManager() { try { var uri = new Uri("pack://application:,,,/Assets/PersonalityTraits.txt"); System.Windows.Resources.StreamResourceInfo resourceStream = Application.GetResourceStream(uri); using (var reader = new StreamReader(resourceStream.Stream)) { string traitsText = reader.ReadToEnd(); List <DatabaseEntry> result = DatabaseReader.LoadFromText(traitsText); LoadPersonalityTraitsFromDatabase(result); } } catch (Exception e) { Console.WriteLine(e); //throw; } }
public CircuitManager() { Instance = this; try { var uri = new Uri("pack://application:,,,/Assets/Locations.txt"); System.Windows.Resources.StreamResourceInfo resourceStream = Application.GetResourceStream(uri); using (var reader = new StreamReader(resourceStream.Stream)) { string traitsText = reader.ReadToEnd(); List <DatabaseEntry> result = DatabaseReader.LoadFromText(traitsText); LoadCircuitsFromDatabase(result, ClimateManager.Instance); } } catch (Exception e) { Console.WriteLine(e); //throw; } }
private async Task<BitmapImage> Download(string imageUrl, string imageName, string imageSaveName) { Stream imageStream = null; var client = new WebClient(); try { var imageUri = new Uri(string.Format(imageUrl, imageName)); imageStream = await client.OpenReadTaskAsync(imageUri); } catch (Exception ex) { // Let it fail if not something catastrophic if (!(ex is WebException)) throw; } if (imageStream == null) return null; var streamResourceInfo = new StreamResourceInfo(imageStream, null); var streamReader = new StreamReader(streamResourceInfo.Stream); byte[] imageBytes; using (var binaryReader = new BinaryReader(streamReader.BaseStream)) imageBytes = binaryReader.ReadBytes((int) streamReader.BaseStream.Length); var image = new BitmapImage(); string name = imageSaveName ?? imageName; using (var stream = _isolatedStorageFile.CreateFile(name)) { stream.Write(imageBytes, 0, imageBytes.Length); image.SetSource(stream); } return image; }
/// <summary> ********************************************** /// Get file path info /// </summary> /// <param name="package"></param> /// <returns></returns> public String getPath(StreamResourceInfo package, String fileName, out bool everythingOK) { BinaryReader reader = new BinaryReader(package.Stream); package.Stream.Seek(0, SeekOrigin.Begin); string name = null; while (ParseFileHeader(reader, out name)) { // If file founded, also folder-name saved if file is under folder if (name.Contains(fileName)) { // Save the folder - name if there was sub - folder for HTML content if (name.Contains("/")) StaticDataForPageChange.htmlContentFolderName = name.Substring(0, name.IndexOf("/") + 1); else StaticDataForPageChange.htmlContentFolderName = ""; everythingOK = true; return name; } } everythingOK = false; return "File path info not found"; }
/// <summary> /// Open Resource Xap file Complete hander. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Event Args</param> private void OpenReadResourceXapCompleted(object sender, OpenReadCompletedEventArgs e) { try { if ((e.Error == null) && (!e.Cancelled)) { // Load the Localized resources. StreamResourceInfo streamInfo = new StreamResourceInfo(e.Result, null); if (streamInfo != null) { // Get resource Manifest file. Uri manifiestURl = new Uri(appResourceManifestFilename, UriKind.RelativeOrAbsolute); if (manifiestURl != null) { StreamResourceInfo resourceInfo = Application.GetResourceStream(streamInfo, manifiestURl); if (resourceInfo != null) { StreamReader resourceReader = new StreamReader(resourceInfo.Stream); if (resourceReader != null) { string appManifest = resourceReader.ReadToEnd(); if (!String.IsNullOrEmpty(appManifest)) { XElement resourcesElements = XDocument.Parse(appManifest).Root; if (resourcesElements != null) { // Get names of all resources in manifest file. List<XElement> ResourceParts = new List<XElement>(); foreach (XElement assemblyElement in resourcesElements.Elements().Elements()) ResourceParts.Add(assemblyElement); // Load the resources. Assembly resourceAssembly = null; foreach (XElement resourceElement in ResourceParts) { string assemblyName = resourceElement.Attribute("Source").Value; if ((!string.IsNullOrEmpty(assemblyName)) && (assemblyName.ToLower().EndsWith("resources.dll", StringComparison.OrdinalIgnoreCase))) { // only load resources assemblies AssemblyPart resourcePart = new AssemblyPart(); StreamResourceInfo resourceStreamInfo = Application.GetResourceStream(new StreamResourceInfo(e.Result, "application/binary"), new Uri(assemblyName, UriKind.RelativeOrAbsolute)); if (resourceStreamInfo != null)// Load resource assembles resourceAssembly = resourcePart.Load(resourceStreamInfo.Stream); } } } } } } } } } } catch { } finally { if (e.UserState != null) { if (e.UserState is EventHandler) { EventHandler callbackEvent = e.UserState as EventHandler; if (callbackEvent != null) callbackEvent(sender, new EventArgs()); } } } }
private void StartButton_Click(object sender, System.Windows.RoutedEventArgs e) { CheckBox[] Levels = new CheckBox[5]; Levels[0] = Level1; Levels[1] = Level2; Levels[2] = Level3; Levels[3] = Level4; Levels[4] = Level5; int[] selectedDicts = new int[5]; for (int i = 0; i < 5; i++) { if (Levels[i].IsChecked == true) selectedDicts[i] = i + 1; else selectedDicts[i] = 0; } for (int i = 0; i < 5; i++) { if (selectedDicts[i] != 0) { xml = App.GetResourceStream(new Uri(dicts[i], UriKind.Relative)); loadedData = XDocument.Load(xml.Stream); var dict = from query in loadedData.Descendants("Word") select new Word { Kanji = (string)query.Attribute("Kanji"), Kana = (string)query.Attribute("Kana"), English = (string)query.Attribute("English"), Romaji = (string)query.Attribute("Romaji"), Katakana = (string)query.Attribute("Katakana"), Hiragana = (string)query.Attribute("Hiragana") }; Words.AddRange(dict.ToList()); System.Diagnostics.Debug.WriteLine("Loaded" + dicts[i]); } } if (Mode.Text.Equals("Quiz")) NavigationService.Navigate(new Uri("/Flashcards.xaml", UriKind.Relative)); else if (Mode.Text.Equals("Teach")) NavigationService.Navigate(new Uri("/Teach.xaml", UriKind.Relative)); }
public static void LoadFromFile(string inPath, Dictionary <string, LocalisationEntry> inEntries, Dictionary <string, LocalisationGroup> inGroups) { var uri = new Uri(string.Format("pack://application:,,,/Assets/{0}.txt", inPath)); System.Windows.Resources.StreamResourceInfo resourceStream = Application.GetResourceStream(uri); using (var reader = new StreamReader(resourceStream.Stream)) { string fileContents = reader.ReadToEnd(); try { CsvReader csvReader = new CsvReader((TextReader) new StringReader(fileContents)); while (csvReader.Read()) { if (csvReader.CurrentRecord.Length > csvReader.FieldHeaders.Length) { Debug.WriteLine("Field with more entries than there are columns - some data will be ignored! Check your data! File: {0}, line: {1}, columns: {2}, values in row: {3}", (object)inPath, (object)csvReader.Row, (object)csvReader.FieldHeaders.Length, (object)csvReader.CurrentRecord.Length); } if (csvReader.CurrentRecord.Length < csvReader.FieldHeaders.Length) { Debug.WriteLine("Field with fewer entries than there are columns - data is missing and can't be read. This row is being skipped. Check your data! File: {0}, line: {1}, columns: {2}, values in row: {3}", (object)inPath, (object)csvReader.Row, (object)csvReader.FieldHeaders.Length, (object)csvReader.CurrentRecord.Length); } else { LocalisationEntry localisationEntry = new LocalisationEntry(); for (int index1 = 0; index1 < csvReader.FieldHeaders.Length; ++index1) { string field; if (!csvReader.TryGetField <string>(index1, out field)) { Debug.WriteLine("Missing field, line {0} in file \"{1}\"", new object[2] { (object)csvReader.Row, (object)inPath }); } else { string fieldHeader = csvReader.FieldHeaders[index1]; if (fieldHeader == "Message Group") { localisationEntry.group = field; if (!inGroups.ContainsKey(localisationEntry.group)) { inGroups[localisationEntry.group] = new LocalisationGroup(); } inGroups[localisationEntry.group].entries.Add(localisationEntry); } else if (fieldHeader == "User Data") { if (!Localisation.IsValueEmpty(field)) { string str1 = field; char[] chArray1 = new char[1] { ',' }; foreach (string str2 in str1.Split(chArray1)) { char[] chArray2 = new char[1] { '=' }; string[] strArray = str2.Split(chArray2); if (strArray.Length < 2) { Debug.WriteLine("Bad User Data (missing '=' sign): \"{0}\", line {1} in file \"{2}\"", (object)field, (object)csvReader.Row, (object)inPath); } else { localisationEntry.userData[strArray[0]] = strArray[1]; } } } } else if (fieldHeader == "ID") { localisationEntry.id = field; } else { if (fieldHeader == "English") { localisationEntry.text[fieldHeader] = field; } } } } if (!string.IsNullOrEmpty(localisationEntry.id)) { if (inEntries.ContainsKey(localisationEntry.id)) { Debug.WriteLine("LOCALISATION: Duplicate string ID (" + localisationEntry.id + ") found in " + inPath); } else { inEntries[localisationEntry.id] = localisationEntry; } } } } } catch (Exception e) { Console.WriteLine(e); throw; } } }