public async void LoadCustomersFromFile() { try { StorageFolder storageFolder = ApplicationData.Current.LocalFolder; StorageFile storageFile = await storageFolder.GetFileAsync("CustomerSaveFile.sav"); string text; var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); text = dataReader.ReadString(numBytesLoaded); } } text = text.Replace("\n", string.Empty); string[] words = text.Split('%'); for (int i = 0; i < words.Length - 1; i += 3) { Customer tempCustomer = new Customer(words[i], words[i + 1], words[i + 2]); CustomerCollection.Add(tempCustomer); } } catch (System.IO.FileNotFoundException e) { errorMessage += $"{e.Message}\n"; } }
public async void LoadCustomerOrdersFromFile(string SaveFileName, ObservableCollection <CustomerOrder> customerOrders) { try { StorageFolder storageFolder = ApplicationData.Current.LocalFolder; StorageFile storageFile = await storageFolder.GetFileAsync(SaveFileName); string text; var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); text = dataReader.ReadString(numBytesLoaded); } } text = text.Replace("\n", string.Empty); string[] words = text.Split(new char[] { '%', '¤' }); for (int i = 0; i < words.Length - 1; i += 10) { CustomerOrder tempOrder = new CustomerOrder(new Customer(words[i + 1], words[i + 2], words[i + 3]), new Merchandise(words[i + 5], words[i + 6], Int32.Parse(words[i + 7])), Int32.Parse(words[i + 9])); tempOrder.OrderDateTime = DateTime.Parse(words[i]); customerOrders.Add(tempOrder); } } catch (System.IO.FileNotFoundException e) { errorMessage += $"{e.Message}\n"; } }
public static async Task <string> ReadFile(string filename, string folderPath = "DataCache", bool isInstallationFolder = false) { StorageFolder localFolder; if (isInstallationFolder) { localFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; } else { localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; } var folder = await localFolder.GetFolderAsync(folderPath); //var folder = await installFolder.GetFolderAsync("Assets/Constellation"); var file = await folder.GetFileAsync(filename); var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var inStream = fs.GetInputStreamAt(0); Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(inStream); await reader.LoadAsync((uint)fs.Size); string data = reader.ReadString((uint)fs.Size); reader.DetachStream(); return(data); }
private async void OpenFileButton_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker { ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail, SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary }; picker.FileTypeFilter.Add(".yo"); SourceFile = await picker.PickSingleFileAsync(); if (SourceFile == null) { return; } var stream = await SourceFile.OpenAsync(FileAccessMode.Read); ulong size = stream.Size; SourceList.Clear(); using (var dataReader = new Windows.Storage.Streams.DataReader(stream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); SourceText = dataReader.ReadString(numBytesLoaded); RealSource = SourceText.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); } this.SourceListView.SelectedIndex = 0; WorkCompletedForSource(); LoadInstructions(); }
//We use a protected override void to execute code as soon as the page is loaded into memory protected async override void OnNavigatedTo(NavigationEventArgs e) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile signInInfo = await storageFolder.CreateFileAsync("signin.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); var stream = await signInInfo.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string signinAddress = dataReader.ReadString(numBytesLoaded); //string currentUser = emailBox.Text; if (signinAddress.ToString() == "") { emailBox.Text = "@wh-at.net"; } else { emailBox.Text = signinAddress.ToString(); Frame.Navigate(typeof(helpdesk)); } } } stream.Dispose(); }
private async void C_BUTTON_LOAD_ENTITY_Click(object sender,RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as picker.FileTypeFilter.Add(".json"); // Default file name if the user does not type one in or select a file to replace var t_storagefile = await picker.PickSingleFileAsync(); if (t_storagefile == null) { return; } String json_str; using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(transaction.Stream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)transaction.Stream.Size); json_str = dataReader.ReadString(numBytesLoaded); await transaction.Stream.FlushAsync(); await transaction.CommitAsync(); } } Deserialize(json_str); }
// Read out and print the message received from the socket. private async void StartReader(Windows.Networking.Proximity.ProximityStreamSocket socket, Windows.Storage.Streams.DataReader reader) { uint initialLength = 4; try { await reader.LoadAsync(initialLength); uint msgLength = (uint)reader.ReadInt32(); try { await reader.LoadAsync(msgLength); string message = reader.ReadString(msgLength); WriteMessageText("Received message: " + message + "\n"); // After receiving a message, listen for the next message. StartReader(socket, reader); } catch (Exception e) { WriteMessageText("Error: " + e.Message + "\n"); socket.Dispose(); } } catch (Exception e) { WriteMessageText("Error: " + e.Message + "\n"); socket.Dispose(); } }
private async void Read_text_file_stream_Click(object sender, RoutedEventArgs e) { // Get the sample file Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("sample.txt"); // Open stream to sample file var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read); // Get size of the stream for user later ulong size = stream.Size; // Get the input stream using (var inputStream = stream.GetInputStreamAt(0)) { // Read the stream using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string text = dataReader.ReadString(numBytesLoaded); // Show contents of file this.Read_File_Contents_Stream.Text = text; } } }
/// <summary> /// This is the click handler for the 'Copy Strings' button. Here we will parse the /// strings contained in the ElementsToWrite text block, write them to a stream using /// DataWriter, retrieve them using DataReader, and output the results in the /// ElementsRead text block. /// </summary> /// <param name="sender">Contains information about the button that fired the event.</param> /// <param name="e">Contains state information and event data associated with a routed event.</param> private async void TransferData(object sender, RoutedEventArgs e) { // Initialize the in-memory stream where data will be stored. using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream()) { // Create the data writer object backed by the in-memory stream. using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream)) { dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Write each element separately. foreach (string inputElement in inputElements) { uint inputElementSize = dataWriter.MeasureString(inputElement); dataWriter.WriteUInt32(inputElementSize); dataWriter.WriteString(inputElement); } // Send the contents of the writer to the backing stream. await dataWriter.StoreAsync(); // For the in-memory stream implementation we are using, the flushAsync call is superfluous, // but other types of streams may require it. await dataWriter.FlushAsync(); // In order to prolong the lifetime of the stream, detach it from the DataWriter so that it // will not be closed when Dispose() is called on dataWriter. Were we to fail to detach the // stream, the call to dataWriter.Dispose() would close the underlying stream, preventing // its subsequent use by the DataReader below. dataWriter.DetachStream(); } // Create the input stream at position 0 so that the stream can be read from the beginning. stream.Seek(0); using (var dataReader = new Windows.Storage.Streams.DataReader(stream)) { // The encoding and byte order need to match the settings of the writer we previously used. dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataReader.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; // Once we have written the contents successfully we load the stream. await dataReader.LoadAsync((uint)stream.Size); var receivedStrings = ""; // Keep reading until we consume the complete stream. while (dataReader.UnconsumedBufferLength > 0) { // Note that the call to readString requires a length of "code units" to read. This // is the reason each string is preceded by its length when "on the wire". uint bytesToRead = dataReader.ReadUInt32(); receivedStrings += dataReader.ReadString(bytesToRead) + "\n"; } // Populate the ElementsRead text block with the items we read from the stream. ElementsRead.Text = receivedStrings; } } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { //Select problem button Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile problemInfo = await storageFolder.CreateFileAsync("problem.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); var problemStream = await problemInfo.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong problemSize = problemStream.Size; using (var inputStream = problemStream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)problemSize); string problemContent = dataReader.ReadString(numBytesLoaded); if (problemContent == "") { selectProblemButton.Content = "choose a problem"; } else { selectProblemButton.Content = problemContent.ToString(); } } } problemStream.Dispose(); //Select room button Windows.Storage.StorageFile roomInfo = await storageFolder.CreateFileAsync("room.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); var roomStream = await roomInfo.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong roomSize = roomStream.Size; using (var inputStream = roomStream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)roomSize); string roomContent = dataReader.ReadString(numBytesLoaded); if (roomContent == "") { selectRoomButton.Content = "choose a room"; } else { selectRoomButton.Content = roomContent.ToString(); } } } roomStream.Dispose(); }
public async Task <string> GetData(Windows.Storage.Streams.IBuffer data, uint scanDataType) { try { string result = null; if (data == null) { result = "No data"; } else { switch (Windows.Devices.PointOfService.BarcodeSymbologies.GetName(scanDataType)) { case "Ean13": case "Ean8": case "Code128": case "Qr": case "Code93": case "Code39": case "Gs1128": case "DataMatrix": case "Gs1128Coupon": case "Gs1DatabarType1": case "Gs1DatabarType2": case "Gs1DatabarType3": case "Upca": case "Upce": case "TfInd": case "TfInt": case "TfStd": case "UccEan128": case "Ean13Add2": case "Ean13Add5": Windows.Storage.Streams.DataReader reader = Windows.Storage.Streams.DataReader.FromBuffer(data); result = reader.ReadString(data.Length).ToString(); byte[] bytes = Encoding.ASCII.GetBytes(result); result = Encoding.UTF8.GetString(bytes); break; default: result = string.Format("Decoded data unavailable. Raw label data: {0}", GetData(data)); break; } } return(result); } catch (Exception ex) { //await DisplayAlert("Error", "GetData failed, Code:" + " Message:" + ex.Message, "OK"); } return(""); }
public async void LoadPresets() { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as picker.FileTypeFilter.Add(".json"); // Default file name if the user does not type one in or select a file to replace var t_storagefile = await picker.PickSingleFileAsync(); if (t_storagefile == null) { return; } String json_str; using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(transaction.Stream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)transaction.Stream.Size); json_str = dataReader.ReadString(numBytesLoaded); await transaction.Stream.FlushAsync(); await transaction.CommitAsync(); } } List <PresetItem> list = null; try { list = (List <PresetItem>)Serial.JsonHelper.FromJson(json_str, m_Presets.GetType()); }catch (Exception e) { return; } if (list == null) { return; } C_PRESETLIST.ItemsSource = null; foreach (PresetItem item in list) { m_Presets.Add(item); } C_PRESETLIST.ItemsSource = m_Presets; }
private async Task <string> IncludeLastScript(Stream input) { var inputStream = input.AsInputStream(); string result; using (var dataReader = new Windows.Storage.Streams.DataReader(input.AsInputStream())) { uint numBytesLoaded = await dataReader.LoadAsync((uint)input.Length); string text = dataReader.ReadString(numBytesLoaded); result = text.Replace(@"<!-- INCLUDE xml for last-script -->", mostRecentBlocks); } return(result); }
private async void LoadRolodexButton_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; picker.FileTypeFilter.Add(".txt"); picker.FileTypeFilter.Add(".csv"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string text = dataReader.ReadString(numBytesLoaded); var lines = text.Split('\n'); foreach (var line in lines) { var components = line.Split(','); if (components.Length == 6) { var newCoord = new Coordinates(components[0], components[1], components[2], float.Parse(components[3]), float.Parse(components[4]), float.Parse(components[5])); Collection.Add(newCoord); } } } } appendLineToConsole("Loaded File: " + file.Name); } else { appendLineToConsole("Operation Cancelled"); } }
public static async Task <string> ReadFile(string filename) { var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; var folder = localFolder; var file = await folder.GetFileAsync(filename); var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var inStream = fs.GetInputStreamAt(0); Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(inStream); await reader.LoadAsync((uint)fs.Size); string data = reader.ReadString((uint)fs.Size); reader.DetachStream(); return(data); }
private async Task <string> ReadFile(StorageFile file) { var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); string textBody; ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; uint numBytesLoaded = await dataReader.LoadAsync((uint)size); textBody = dataReader.ReadString(numBytesLoaded); } } return(textBody); }
public async static Task <StorageFile> CopyFile(StorageFile file) { StorageFile newFile = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(file.Name, CreationCollisionOption.ReplaceExisting); var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string text = dataReader.ReadString(numBytesLoaded); await FileIO.WriteTextAsync(newFile, text); } } return(newFile); }
/// <summary> /// 스트림으로 파일 읽기 /// </summary> /// <param name="storage"></param> /// <returns></returns> private async Task <string> FileRead_UsingStream(StorageFile storage) { string text = string.Empty; var stream = await storage.OpenAsync(FileAccessMode.Read, StorageOpenOptions.AllowOnlyReaders); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); text = dataReader.ReadString(numBytesLoaded); } } return(text); }
public async Task<string> readFile() { string text; Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile dataFile = await storageFolder.GetFileAsync("db.txt"); var stream = await dataFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); text = dataReader.ReadString(numBytesLoaded); dataReader.Dispose(); } } stream.Dispose(); return text; }
public async Task <string> GetContentFromFileAsync(StorageFile fileToLoadFrom) { string contentToReturn = ""; if (fileToLoadFrom != null) { var stream = await fileToLoadFrom.OpenAsync(Windows.Storage.FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); contentToReturn = dataReader.ReadString(numBytesLoaded); } } } return(contentToReturn); }
// Read out and print the message received from the socket. private async void StartReader(Windows.Networking.Sockets.StreamSocket socket, Windows.Storage.Streams.DataReader reader) { try { uint bytesRead = await reader.LoadAsync(sizeof(uint)); if (bytesRead > 0) { uint strLength = (uint)reader.ReadUInt32(); bytesRead = await reader.LoadAsync(strLength); if (bytesRead > 0) { String message = reader.ReadString(strLength); WriteMessageText("Received message: " + message + "\n"); StartReader(socket, reader); // Start another reader } else { WriteMessageText("The peer app closed the socket\n"); reader.Dispose(); CloseSocket(); } } else { WriteMessageText("The peer app closed the socket\n"); reader.Dispose(); CloseSocket(); } } catch { WriteMessageText("The peer app closed the socket\n"); reader.Dispose(); CloseSocket(); } }
private async Task <string> ReadFile() { string rawtext; Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile DataFile = await storageFolder.CreateFileAsync("Data.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); var stream = await DataFile.OpenAsync(Windows.Storage.FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); rawtext = dataReader.ReadString(numBytesLoaded); } } return(rawtext); }
public async Task <Settings> GetSettingsAsync() { var formatter = new DataContractSerializer(typeof(Settings)); var filePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, SettingsName); Settings settings = new Settings(); if (!File.Exists(filePath)) { var defaultSettings = Create(); return(await WriteSettingsAsync(defaultSettings)); } var file = await ApplicationData.Current.LocalFolder.GetFileAsync(SettingsName); var stream = await file.OpenAsync(FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); settings.FileSystemDirectory = dataReader.ReadString(numBytesLoaded); // BUG settings.IsFileSystemEnabled = dataReader.ReadBoolean(); } } //var lines = await FileIO.ReadTextAsync(file); //settings.FileSystemDirectory = lines; //var stream = new FileStream(settingsFileName, FileMode.Open, FileAccess.Read, FileShare.None); //settings = (Settings)formatter.ReadObject(stream); Debug.WriteLine("Read Settings"); return(settings); }
/// <summary> /// Load the strings from a file and give back a List<Move> /// </summary> /// <returns></returns> public async Task <List <Move> > LoadGame() { FileOpenPicker fileOpenPicker = new FileOpenPicker(); fileOpenPicker.FileTypeFilter.Add(".csv"); StorageFile sourceFile = await fileOpenPicker.PickSingleFileAsync(); string moveListAsString; List <Move> moveList = new List <Move>(); if (sourceFile != null) { var stream = await sourceFile.OpenAsync(Windows.Storage.FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); moveListAsString = dataReader.ReadString(numBytesLoaded); } } stream.Dispose(); string[] moveStringList = moveListAsString.Split(System.Environment.NewLine); // The first number determines how many moves in the file need to be read // I use this trick because I haven't found a way to empty a file int moveNumber = int.Parse(moveStringList[0]); for (int i = 1; i <= moveNumber; i++) { moveList.Add(Move.Parse(moveStringList[i])); } } return(moveList); }
public async Task <string> readFile() { string text; Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile dataFile = await storageFolder.GetFileAsync("db.txt"); var stream = await dataFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); text = dataReader.ReadString(numBytesLoaded); dataReader.Dispose(); } } stream.Dispose(); return(text); }
private async void ticketTextBlock_Tapped(object sender, TappedRoutedEventArgs e) { //READ //Open the text file Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile ticketsFile = await storageFolder.CreateFileAsync("tickets.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); var stream = await ticketsFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string savedTickets = dataReader.ReadString(numBytesLoaded); ticketTextBlock.Text = savedTickets; } } stream.Dispose(); }
private async void C_LOAD_BUTTON_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as picker.FileTypeFilter.Add(".json"); // Default file name if the user does not type one in or select a file to replace var t_storagefile = await picker.PickSingleFileAsync(); if (t_storagefile == null) { return; } String json_str; using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(transaction.Stream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)transaction.Stream.Size); json_str = dataReader.ReadString(numBytesLoaded); await transaction.Stream.FlushAsync(); await transaction.CommitAsync(); } } var serialize = (Model.TrickerStarNodeViewSerialize)Model.JsonHelper.FromJson(json_str, typeof(Model.TrickerStarNodeViewSerialize)); foreach (var node in serialize.Nodes) { C_MAIN_NODE_VIEW.TS_AddNode(node.NodeName); C_MAIN_NODE_VIEW.TS_SetNodePosition(node.NodeName, node.Pos); C_MAIN_NODE_VIEW.TS_SetNodeTitle(node.NodeName, node.NodeTitle); foreach (var inslot in node.InputSlot) { if (inslot.SlotType == Model.TrickerStarSlotType.PLACEHOLDER) { C_MAIN_NODE_VIEW.TS_AddSlot(node.NodeName, inslot.SlotType, inslot.SlotName, inslot.SlotSide); } else { C_MAIN_NODE_VIEW.TS_AddSlot(node.NodeName, inslot.SlotType, inslot.SlotName, inslot.SlotSide); } if (inslot.SlotType == Model.TrickerStarSlotType.INSTANCE_VALUE) { C_MAIN_NODE_VIEW.TS_SetSlotValue(node.NodeName, inslot.SlotIndex, inslot.SlotSide, inslot.SlotValue); } } foreach (var outslot in node.OutputSlot) { if (outslot.SlotType == Model.TrickerStarSlotType.PLACEHOLDER) { C_MAIN_NODE_VIEW.TS_AddSlot(node.NodeName, outslot.SlotType, outslot.SlotName, outslot.SlotSide); } else { C_MAIN_NODE_VIEW.TS_AddSlot(node.NodeName, outslot.SlotType, outslot.SlotName, outslot.SlotSide); } if (outslot.SlotType == Model.TrickerStarSlotType.INSTANCE_VALUE) { C_MAIN_NODE_VIEW.TS_SetSlotValue(node.NodeName, outslot.SlotIndex, outslot.SlotSide, outslot.SlotValue); } } } foreach (var line in serialize.Lines) { C_MAIN_NODE_VIEW.TS_AddLine(line.LineName, line.From.NodeName, line.From.SlotIndex, line.To.NodeName, line.To.SlotIndex); } foreach (var code in serialize.Codes) { m_NodeCode[code.NodeName] = code.Code; } foreach (var group in serialize.Groups) { m_GroupList.Add(group); } foreach (var group in serialize.NodeGroups) { m_NodeGroup[group.NodeName] = new Model.TrickerStarGroupModel() { GroupName = group.GroupName, GroupTitle = group.GroupTitle, }; } }
//************************************************* //************************************************* //********** EXECUTE COMMAND LINE STRING ********** //************************************************* //************************************************* private async Task <string> ExecuteCommandLineString(string CommandString) { const string CommandLineProcesserExe = "c:\\windows\\system32\\cmd.exe"; const uint CommandStringResponseBufferSize = 64 * 1024; string currentDirectory = "C:\\"; StringBuilder textOutput = new StringBuilder((int)CommandStringResponseBufferSize); uint bytesLoaded = 0; if (string.IsNullOrWhiteSpace(CommandString)) { return(""); } var commandLineText = CommandString.Trim(); var standardOutput = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var standardError = new Windows.Storage.Streams.InMemoryRandomAccessStream(); var options = new Windows.System.ProcessLauncherOptions { StandardOutput = standardOutput, StandardError = standardError }; try { var args = "/C \"cd \"" + currentDirectory + "\" & " + commandLineText + "\""; var result = await Windows.System.ProcessLauncher.RunToCompletionAsync(CommandLineProcesserExe, args, options); //First write std out using (var outStreamRedirect = standardOutput.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(outStreamRedirect)) { while ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0) { textOutput.Append(dataReader.ReadString(bytesLoaded)); } new System.Threading.ManualResetEvent(false).WaitOne(10); if ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0) { textOutput.Append(dataReader.ReadString(bytesLoaded)); } } } //Then write std err using (var errStreamRedirect = standardError.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(errStreamRedirect)) { while ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0) { textOutput.Append(dataReader.ReadString(bytesLoaded)); } new System.Threading.ManualResetEvent(false).WaitOne(10); if ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0) { textOutput.Append(dataReader.ReadString(bytesLoaded)); } } } return(textOutput.ToString()); } catch (UnauthorizedAccessException uex) { return("ERROR - " + uex.Message + "\n\nCmdNotEnabled"); } catch (Exception ex) { return("ERROR - " + ex.Message + "\n"); } }
/// <summary> /// Creates and adds a time track objects into the Items collection. /// </summary> public async void LoadData() { var fileList = await ApplicationData.Current.LocalFolder.GetFilesAsync(); var file = fileList.FirstOrDefault(f => f.Name == localFileName); if (file != null) { using (var stream = await file.OpenReadAsync()) { using (var dr = new Windows.Storage.Streams.DataReader(stream)) { try { await dr.LoadAsync(unchecked((uint)stream.Size)); var numberOfItems = dr.ReadInt32(); ObservableCollection<TrackItem> loadingItems = new ObservableCollection<TrackItem>(); for (int x = 0; x < numberOfItems; x++) { TrackItem item = new TrackItem(); item.Start = dr.ReadDateTime(); item.End = dr.ReadDateTime(); int topicLength = dr.ReadInt32(); item.Topic = dr.ReadString((uint)topicLength); loadingItems.Add(item); } bool currentItemExists = dr.ReadBoolean(); TrackItem loadingCurrentItem = null; if (currentItemExists) { loadingCurrentItem = new TrackItem(); loadingCurrentItem.Start = dr.ReadDateTime(); int topicLength = dr.ReadInt32(); loadingCurrentItem.Topic = dr.ReadString((uint)topicLength); } dr.DetachStream(); Items = loadingItems; OnPropertyChanged(nameof(Items)); CurrentItem = loadingCurrentItem; IsDataLoaded = true; } catch { try { await file.DeleteAsync(); } catch { } CurrentItem = null; IsDataLoaded = true; } } } } else { // Sample data; replace with real data Items.Add(new TrackItem() { Topic = "First Tracked Item", Start = new DateTimeOffset(new DateTime(2015, 11, 5, 9, 0, 0), new TimeSpan(-6, 0, 0)), End = new DateTimeOffset(new DateTime(2015, 11, 5, 11, 30, 0), new TimeSpan(-6, 0, 0)), }); Items.Add(new TrackItem() { Topic = "Second Tracked Item", Start = new DateTimeOffset(new DateTime(2015, 11, 5, 12, 30, 0), new TimeSpan(-6, 0, 0)), End = new DateTimeOffset(new DateTime(2015, 11, 5, 17, 0, 0), new TimeSpan(-6, 0, 0)), }); CurrentItem = null; this.IsDataLoaded = true; } }
private async void submitButton_Click(object sender, RoutedEventArgs e) { //MessageBox if (selectProblemButton.Content.ToString() == "choose a problem") { MessageDialog invalidProblem = new MessageDialog("You need to select a problem type before you can submit a ticket.", "Invalid problem type"); await invalidProblem.ShowAsync(); } else if (descriptionText.Text == "") { MessageDialog invalidDescription = new MessageDialog("You need to type a description before you can submit a ticket.", "You need to type a description"); await invalidDescription.ShowAsync(); } else if (expletiveslist.expletivesArray.Contains(descriptionText.Text)) { MessageDialog expletivesDetected = new MessageDialog("There are expletives in your description. Please remove these before sending the ticket.", "Expletives detected"); await expletivesDetected.ShowAsync(); } else { //Get variables var submitDate = DateTime.Now.ToString(); var problem = selectProblemButton.Content.ToString(); var location = selectRoomButton.Content.ToString(); var attachedFile = fileText.Text.ToString(); string videoAttached = null; if (attachedFile.Contains("mp4")) { videoAttached = "Attached video: " + attachedFile; } else { videoAttached = "Attached photo: " + attachedFile; } //WRITE //Create the text file to hold the data Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile ticketsFile = await storageFolder.CreateFileAsync("tickets.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); await FileIO.AppendTextAsync(ticketsFile, "\n" + "Submitted: " + submitDate + "\n" + "Problem: " + problem + "\n" + "Room: " + location + "\n" + "Description: " + descriptionText.Text + "\n" + "Priority: " + priority + "\n" + videoAttached + "\n"); //Use stream to write to the file var stream = await ticketsFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); using (var outputStream = stream.GetOutputStreamAt(0)) { using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream)) { await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well.*/ //READ //Open the text file stream = await ticketsFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); string savedTickets = dataReader.ReadString(numBytesLoaded); ticketTextBlock.Text = savedTickets; } } stream.Dispose(); //SEND EMAIL string messageBody = "\n" + "Ticket submitted: " + submitDate + "\n" + "Problem: " + problem.ToUpper() + "\n" + "Room: " + location + "\n" + "Description: " + descriptionText.Text + "\n" + "Priority: " + priority + "\n" + videoAttached + "\n" + "\n" + "----------------------------------------------------------" + "\n" + "Sent from wh-at Helpdesk (for Windows 10)" + "\n" + "\n" + "You may respond to this email, it will send an email to the sender."; string messageTitle = problem.ToUpper() + " | " + location; if (_file == null) { EmailMessage emailMessage = new EmailMessage(); emailMessage.To.Add(new EmailRecipient("*****@*****.**")); emailMessage.Body = messageBody; emailMessage.Subject = messageTitle; await EmailManager.ShowComposeNewEmailAsync(emailMessage); } else { EmailMessage emailMessage = new EmailMessage(); emailMessage.To.Add(new EmailRecipient("*****@*****.**")); emailMessage.Body = messageBody; emailMessage.Subject = messageTitle; var emailStream = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(_file); var attachment = new Windows.ApplicationModel.Email.EmailAttachment( _file.Name, emailStream); emailMessage.Attachments.Add(attachment); await EmailManager.ShowComposeNewEmailAsync(emailMessage); } } }