Beispiel #1
0
        async private Task Save(XDocument xdoc, string path)
        {
            StringWriter swriter = new StringWriter();

            xdoc.Save(swriter, SaveOptions.None);
            string  xmlString          = swriter.GetStringBuilder().ToString();
            IBuffer xmlEncryptedBuffer = EncryptionProvider.Encrypt(xmlString);

            StorageFolder sf = await ApplicationData.Current.LocalFolder.GetFolderAsync(@"data\");

            var file = await sf.GetFileAsync(Path.GetFileName(path));

            using (IRandomAccessStream ras = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outs = ras.GetOutputStreamAt(0))
                {
                    await outs.WriteAsync(xmlEncryptedBuffer);

                    bool suc = await outs.FlushAsync();

                    outs.Dispose();
                }
                ras.Dispose();
            }
        }
Beispiel #2
0
        /// <summary>
        /// Saves all data that this repository has
        /// </summary>
        /// <param name="rootFolder">Folder in which to save the data</param>
        public async Task Save(StorageFolder rootFolder)
        {
            StorageFolder modelFolder = await GetFolder(rootFolder);

            // If all data was deleted then delete all the files
            if (modelProperty().Count == 0)
            {
                // Create a new folder for this model, deleting the old one while it does
                modelFolder = await rootFolder.CreateFolderAsync(ModelName + "s", CreationCollisionOption.ReplaceExisting);
            }

            // Loop each instance in the list
            foreach (T model in modelProperty())
            {
                // Create an XmlSerializer for serializing the data
                XmlSerializer xmlSerializer = new XmlSerializer(model.GetType());
                // Create a file for the model
                // We replace existing files so that it overwrites old data
                StorageFile file = await modelFolder.CreateFileAsync(model.ID.ToString(), CreationCollisionOption.ReplaceExisting);

                // A random access stream is used to push data to the file
                IRandomAccessStream fileRandomAccessStream = await file.OpenAsync(FileAccessMode.ReadWrite);

                // Used to disposing and flushing data which helps for memory conservation
                IOutputStream fileOutputStream = fileRandomAccessStream.GetOutputStreamAt(0);
                // Serialize the data to the file
                xmlSerializer.Serialize(fileRandomAccessStream.AsStreamForWrite(), model);
                // Dispose of and flush the file streams (Do flush asynchronously so it doesn't jam the thread)
                fileRandomAccessStream.Dispose();
                await fileOutputStream.FlushAsync();

                fileOutputStream.Dispose();
            }
        }
Beispiel #3
0
        public async Task <bool> SaveEpisodeList()
        {
            var filename = "Episodes.json";

            try
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite);

                using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
                {
                    // Serialize the Session State.
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List <Episode>));

                    serializer.WriteObject(outStream.AsStreamForWrite(), EpisodesList);

                    await outStream.FlushAsync();

                    outStream.Dispose();
                    raStream.Dispose();

                    Debug.WriteLine("Episodelist saved");
                    return(true);
                }
            }
            catch (Exception) { Debug.WriteLine("episodelist failed to save"); return(false); }
        }
Beispiel #4
0
 //-------------------------------------------------------------------------zamykanie polaczenia
 private void disconnect()
 {
     if (reader != null)
     {
         reader.Dispose();
         reader = null;
     }
     if (writer != null)
     {
         writer.Dispose();
         writer = null;
     }
     if (socket != null)
     {
         socket.Dispose();
         socket = null;
     }
     if (service != null)
     {
         service = null;
     }
     if (stream != null)
     {
         stream.Dispose();
         stream = null;
     }
     if (buffer != null)
     {
         buffer = null;
     }
 }
Beispiel #5
0
        public async Task StopRecording()
        {
            await datawriter.StoreAsync();

            await outputstream.FlushAsync();

            outputstream.Dispose();
            datawriter.Dispose();

            using (outputstream = stream.GetOutputStreamAt(4))
                using (datawriter = new DataWriter(outputstream)
                {
                    ByteOrder = ByteOrder.LittleEndian
                })
                {
                    datawriter.WriteUInt32((uint)size + 44);
                    await datawriter.StoreAsync();

                    await outputstream.FlushAsync();
                }

            using (outputstream = stream.GetOutputStreamAt(40))
                using (datawriter = new DataWriter(outputstream)
                {
                    ByteOrder = ByteOrder.LittleEndian
                })
                {
                    datawriter.WriteUInt32((uint)size);
                    await datawriter.StoreAsync();

                    await outputstream.FlushAsync();
                }
        }
Beispiel #6
0
        public static async Task <bool> writeObjektAsync <T>(string file, T objekt)
        {
            try
            {
                StorageFile userdetailsfile = await
                                              ApplicationData.Current.LocalFolder.CreateFileAsync(file, CreationCollisionOption.ReplaceExisting);

                IRandomAccessStream rndStream = await
                                                userdetailsfile.OpenAsync(FileAccessMode.ReadWrite);

                using (IOutputStream outStream = rndStream.GetOutputStreamAt(0))
                {
                    DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                    serializer.WriteObject(outStream.AsStreamForWrite(), objekt);
                    var xx = await outStream.FlushAsync();

                    rndStream.Dispose();
                    outStream.Dispose();
                }
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Convert the given MemoryStream to a stream that allows random access
        /// </summary>
        /// <param name="memoryStream">The MemoryStream to convert</param>
        /// <returns>Stream that allows random access</returns>
        public static async Task <IRandomAccessStream> ConvertToRandomAccessStream(MemoryStream memoryStream)
        {
            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
            MemoryStream contentStream = new MemoryStream();

            memoryStream.CopyTo(contentStream);
            using (IOutputStream outputStream = randomAccessStream.GetOutputStreamAt(0))
            {
                using (DataWriter dw = new DataWriter(outputStream))
                {
                    Task task = new Task(() => dw.WriteBytes(contentStream.ToArray()));
                    task.Start();

                    await task;
                    await dw.StoreAsync();

                    await outputStream.FlushAsync();

                    await dw.FlushAsync();

                    outputStream.Dispose();
                    dw.DetachStream();
                    dw.Dispose();
                }
            }
            return(randomAccessStream);
        }
Beispiel #8
0
        internal async void SaveProfile()
        {
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("profile", new List <string>()
            {
                ".prof"
            });
            savePicker.FileTypeChoices.Add("csv", new List <string>()
            {
                ".csv"
            });

            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "new profile";

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                IRandomAccessStream sessionRandomAccess = await file.OpenAsync(FileAccessMode.ReadWrite);

                IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
                XmlSerializer serializer;
                serializer = new XmlSerializer(typeof(Profile));
                serializer.Serialize(sessionOutputStream.AsStreamForWrite(), CurrentProfile);

                sessionRandomAccess.Dispose();
                await sessionOutputStream.FlushAsync();

                sessionOutputStream.Dispose();
            }
        }
Beispiel #9
0
        public async Task ExportCurrentPath()
        {
            // Code to call file picker
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("Xml", new List <string>()
            {
                ".xml"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = _currentPathData.Name;

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                IRandomAccessStream sessionRandomAccess = await file.OpenAsync(FileAccessMode.ReadWrite);

                IOutputStream        sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
                List <List <Point> > Allpaths            = CurrentPath.AllPoints;
                var serializer = new XmlSerializer(typeof(List <List <Point> >));
                serializer.Serialize(sessionOutputStream.AsStreamForWrite(), Allpaths);
                sessionRandomAccess.Dispose();
                await sessionOutputStream.FlushAsync();

                sessionOutputStream.Dispose();
            }
        }
 public void CheckShutdown()
 {
     // cryptor?.Dispose();
     // cryptor = null;
     // outboundChan = null;
     if (recvData != null)
     {
         ZeroMemory(recvData);
     }
     if (udpClient != null)
     {
         udpClient.MessageReceived -= UdpClient_MessageReceived;
     }
     try
     {
         tcpInputStream?.Dispose();
         udpOutputStream?.Dispose();
     }
     catch (ObjectDisposedException) { }
     // networkStream = null;
     try
     {
         client?.Dispose();
         udpClient?.Dispose();
     }
     catch (ObjectDisposedException) { }
     try
     {
         udpSendLock.Dispose();
     }
     catch (ObjectDisposedException) { }
     // client = null;
     // udpClient = null;
 }
Beispiel #11
0
        public async Task StartUPnPDiscoveryAsync()
        {
            _socket = new DatagramSocket();
            _socket.MessageReceived += _socket_MessageReceived;

            IOutputStream stream = await _socket.GetOutputStreamAsync(new HostName("239.255.255.250"), "1900");

            const string message = "M-SEARCH * HTTP/1.1\r\n" +
                                   "HOST: 239.255.255.250:1900\r\n" +
                                   "ST:upnp:rootdevice\r\n" +
                                   "MAN:\"ssdp:discover\"\r\n" +
                                   "MX:3\r\n\r\n";

            var writer = new DataWriter(stream)
            {
                UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8
            };

            writer.WriteString(message);

            _upnpDiscoveryStart    = DateTime.Now;
            _upnpListener          = new DispatcherTimer();
            _upnpListener.Interval = new TimeSpan(0, 0, 1);  //1 second
            _upnpListener.Tick    += _upnpListener_Tick;
            _upnpListener.Start();

            await writer.StoreAsync();

            await stream.FlushAsync();

            stream.Dispose();
        }
Beispiel #12
0
        public static async void init(TiSettings settings)
        {
            if (!settings.ContainsKey("logToken") || settings["logToken"].Length == 0)
            {
                return;
            }

            logToken = settings["logToken"];

            multicastSocket = new DatagramSocket();
            multicastSocket.MessageReceived += multicastSocket_MessageReceived;

            HostName hostname = new HostName("239.6.6.6");

            try {
                await multicastSocket.BindServiceNameAsync("8666");

                multicastSocket.JoinMulticastGroup(hostname);

                IOutputStream stream = await multicastSocket.GetOutputStreamAsync(hostname, "8666");

                DataWriter writer = new DataWriter(stream);
                writer.WriteString("TI_WP8_LOGGER");
                await writer.StoreAsync();

                writer.DetachStream();
                stream.Dispose();
            } catch (Exception ex) {
                if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }
                Debug.WriteLine(ex.ToString());
            }
        }
Beispiel #13
0
        /// <summary>
        /// Writes page content back to socket
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="html"></param>
        /// <param name="lastModifiedUtc"></param>
        /// <param name="contentType"></param>
        /// <param name="keepAlive"></param>
        /// <param name="canBeCached"></param>
        /// <returns></returns>
        private async Task WritePageContent(StreamSocket socket, string html, DateTime?lastModifiedUtc, string contentType, bool keepAlive, bool canBeCached)
        {
            // respond with the html:
            IOutputStream output = socket.OutputStream;

            //using (IOutputStream output = socket.OutputStream)   -- cannot close anything in Keep-Alive mode
            {
                //using (Stream resp = output.AsStreamForWrite())   -- cannot use this, will be blocked on Dispose()
                Stream respStream = output.AsStreamForWrite(262144);    // 256K for uninterrupted send of most sizes
                {
                    //resp.WriteTimeout = 1000;    // milliseconds  -- does not work here

                    // Look in the Data subdirectory of the app package
                    byte[]       bodyArray   = Encoding.UTF8.GetBytes(html);
                    MemoryStream stream      = new MemoryStream(bodyArray);
                    string       header      = generateHeader(lastModifiedUtc, contentType, stream.Length, keepAlive, canBeCached);
                    byte[]       headerArray = Encoding.UTF8.GetBytes(header);

                    await respStream.WriteAsync(headerArray, 0, headerArray.Length, tokenSource.Token);

                    await stream.CopyToAsync(respStream, bodyArray.Length, tokenSource.Token);

                    await respStream.FlushAsync(tokenSource.Token);
                }
            }

            if (!keepAlive)
            {
                output.Dispose();
            }
        }
        private async void Button_Savelocal_Click(object sender, RoutedEventArgs e)
        {
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("Template", new List <string>()
            {
                ".ctmpl"
            });
            savePicker.FileTypeChoices.Add("Xml", new List <string>()
            {
                ".xml"
            });
            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "New Template Collection";

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                IRandomAccessStream sessionRandomAccess = await file.OpenAsync(FileAccessMode.ReadWrite);

                IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);

                var serializer = new XmlSerializer(typeof(TemplateCollection));
                serializer.Serialize(sessionOutputStream.AsStreamForWrite(), App.CodeSettingsContext.Templates);
                sessionRandomAccess.Dispose();
                await sessionOutputStream.FlushAsync();

                sessionOutputStream.Dispose();
            }
        }
Beispiel #15
0
 public void Dispose()
 {
     _cts.Cancel();
     _input.Dispose();
     _output.Dispose();
     _serialDevice.Dispose();
 }
 public void Dispose()
 {
     _isOpen = false;
     _cts.Cancel();
     _input.Dispose();
     _output.Dispose();
     _serialDevice.Dispose();
 }
Beispiel #17
0
        public async Task SendTextMessage(User rec, Message msg, List <User> groupMessageUsers = null)
        {
            string toSend;

            if (msg.Type == Message.MessageType.Buzz && groupMessageUsers == null)
            {
                toSend = "buzz:" + ChatScreen.loggedInUser.Username;
            }
            else if (msg.Type == Message.MessageType.Buzz && groupMessageUsers != null)
            {
                //send buzz to group
                toSend  = "groupBuzz;";
                toSend += ChatScreen.loggedInUser.Username + ";";
                foreach (User u in groupMessageUsers)
                {
                    toSend += u.Username;
                    if (u != groupMessageUsers.Last())
                    {
                        toSend += ";";
                    }
                }
            }
            else
            {
                if (groupMessageUsers != null)
                {
                    toSend = ParseGroupTextMessage(groupMessageUsers, msg);
                }
                else
                {
                    toSend = ParseTextMessage(msg);
                }
            }

            try
            {
                IOutputStream stream = await textMessageSocket.GetOutputStreamAsync(new HostName(rec.IPAddress), unicastServicePort);

                using (var MyDataWriter = new DataWriter(stream))
                {
                    string encryptedMessage = StringCipher.Encrypt(toSend);
                    MyDataWriter.WriteString(encryptedMessage);
                    await MyDataWriter.StoreAsync();

                    MyDataWriter.DetachStream();
                }
                stream.Dispose();
            }
            catch (Exception ex)
            {
                if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }
            }
        }
        public void Dispose()
        {
            output?.Dispose();

            if (process?.HasExited == false)
            {
                process?.WaitForExit();
            }

            process = null;
        }
Beispiel #19
0
 public async static Task WriteFile(IBuffer buffer, IOutputStream file)
 {
     try
     {
         await file.WriteAsync(buffer);
     }
     catch (Exception)
     {
         file.Dispose();
         return;
     }
 }
Beispiel #20
0
        static async private Task SaveAsync <T>(string filename)
        {
            StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            IRandomAccessStream sessionRandomAccess = await sessionFile.OpenAsync(FileAccessMode.ReadWrite);

            IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
            var           serializer          = new XmlSerializer(typeof(List <object>), new Type[] { typeof(T) });

            serializer.Serialize(sessionOutputStream.AsStreamForWrite(), _data);
            sessionRandomAccess.Dispose();
            await sessionOutputStream.FlushAsync();

            sessionOutputStream.Dispose();
        }
Beispiel #21
0
        /// <summary>
        /// Save the settings to a file
        /// </summary>
        /// <param name="settings">Settings object to save</param>
        /// <param name="filename">Name of file to save to</param>
        /// <returns></returns>
        public static async Task SaveAsync(AppSettings settings, string filename)
        {
            StorageFile sessionFile = await SettingsFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            IRandomAccessStream sessionRandomAccess = await sessionFile.OpenAsync(FileAccessMode.ReadWrite);

            IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
            var           serializer          = new XmlSerializer(typeof(AppSettings), new Type[] { typeof(AppSettings) });

            serializer.Serialize(sessionOutputStream.AsStreamForWrite(), settings);
            sessionRandomAccess.Dispose();
            await sessionOutputStream.FlushAsync();

            sessionOutputStream.Dispose();
        }
        public async Task SaveListofLocation()
        {
            StorageFile userListofLocations = await ApplicationData.Current.LocalFolder.CreateFileAsync("userListofLocation", CreationCollisionOption.ReplaceExisting);

            IRandomAccessStream raStream = await userListofLocations.OpenAsync(FileAccessMode.ReadWrite);

            using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection <string>));
                serializer.WriteObject(outStream.AsStreamForWrite(), locationList);
                await outStream.FlushAsync();

                outStream.Dispose();
                raStream.Dispose();
            }
        }
Beispiel #23
0
        /// <summary>
        /// Save object from file
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="fileName"></param>
        public async Task SaveAsync(T obj, string fileName)
        {
            fileName = fileName + GetFileExtension();
            try
            {
                if (obj != null)
                {
                    //Get file
                    StorageFile   file   = null;
                    StorageFolder folder = await GetFolderAsync().ConfigureAwait(false);

                    file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);


                    //Serialize object with JSON or XML serializer
                    string storageString = null;
                    switch (_serializerType)
                    {
                    case StorageSerializer.JSON:
                        storageString = JsonConvert.SerializeObject(obj);
                        //Write content to file
                        await FileIO.WriteTextAsync(file, storageString);

                        break;

#if USE_XML_SERIALIZER
                    case StorageSerializer.XML:

                        IRandomAccessStream sessionRandomAccess = await file.OpenAsync(FileAccessMode.ReadWrite);

                        IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
                        XmlSerializer serializer          = new XmlSerializer(typeof(T));
                        serializer.Serialize(sessionOutputStream.AsStreamForWrite(), obj);
                        sessionRandomAccess.Dispose();
                        await sessionOutputStream.FlushAsync();

                        sessionOutputStream.Dispose();
                        break;
#endif
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #24
0
        public static async void SaveProjecList()
        {
            StorageFile storageFile = await Globals.storageLocation.CreateFileAsync("projectList", CreationCollisionOption.ReplaceExisting);

            IRandomAccessStream raStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);

            using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
            {
                //Serialize the Session State
                DataContractSerializer serializer = new DataContractSerializer(typeof(List <ProjectList>));
                serializer.WriteObject(outStream.AsStreamForWrite(), Globals.projects);
                await outStream.FlushAsync();

                outStream.Dispose();
                raStream.Dispose();
            }
        }
    async Task OnDestroy()
    {
        await audioFrameReader.StopAsync();

        await videoFrameReader.StopAsync();

        audioFrameReader.FrameArrived -= AudioFrameArrived;
        audioStream.FlushAsync();
        audioStream.Dispose();
        audioStream = null;
        videoFrameReader.FrameArrived -= VideoFrameArrived;
        videoStream.FlushAsync();
        videoStream.Dispose();
        videoStream = null;

        mediaCapture.Dispose();
    }
Beispiel #26
0
        private async void addNewButton_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new AddProjectDialog();
            var result = await dialog.ShowAsync();

            bool exists = false;

            if (result == ContentDialogResult.Primary)
            {
                foreach (var rec in Globals.projects)
                {
                    if (rec.projectName == dialog.Text)
                    {
                        exists = true;
                    }
                }
                if (exists == false)
                {
                    Globals.projects.Add(new ProjectList
                    {
                        projectName  = dialog.Text,
                        dateCreated  = DateTime.Now,
                        lastModified = DateTime.Now
                    });
                    Globals.SortProjectList();
                }
            }

            //Save List To File
            StorageFile storageFile = await Globals.storageLocation.CreateFileAsync("projectList", CreationCollisionOption.ReplaceExisting);

            IRandomAccessStream raStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);

            using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
            {
                //Serialize the Session State
                DataContractSerializer serializer = new DataContractSerializer(typeof(List <ProjectList>));
                serializer.WriteObject(outStream.AsStreamForWrite(), Globals.projects);
                await outStream.FlushAsync();

                outStream.Dispose();
                raStream.Dispose();
            }
            this.Frame.Navigate(typeof(MainPage));
        }
        // ReSharper disable once MemberCanBeMadeStatic.Local
        private async void DoShipping(Order order)
        {
            try
            {
                string      fileName = $"dispatch-{order.OrderId}.txt";
                StorageFile file     = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName);

                if (file != null)
                {
                    string dispatchNote =
                        "Order Summary: \r\n" +
                        $"Order ID: {order.OrderId}\r\n" +
                        $"Order Total: {order.TotalValue:C}";

                    IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite);

                    IOutputStream writeStream = stream.GetOutputStreamAt(0);
                    DataWriter    writer      = new DataWriter(writeStream);

                    writer.WriteString(dispatchNote);

                    await writer.StoreAsync();

                    await writeStream.FlushAsync();

                    writeStream.Dispose();
                }
                else
                {
                    MessageDialog messageDialog = new MessageDialog($"Unable to save to file: {fileName}", "Not saved");

                    await messageDialog.ShowAsync();
                }
            }
            catch (Exception exception)
            {
                MessageDialog messageDialog = new MessageDialog(exception.Message, "Exception");

                await messageDialog.ShowAsync();
            }
            finally
            {
                ShipProcessingComplete?.Invoke($"Dispatch note generated for Order {order.OrderId}");
            }
        }
Beispiel #28
0
 public void CheckShutdown()
 {
     try
     {
         inputStream?.Dispose();
     }
     catch (ObjectDisposedException) { }
     try
     {
         outputStream?.Dispose();
     }
     catch (ObjectDisposedException) { }
     try
     {
         socket.Dispose();
     }
     catch (ObjectDisposedException) { }
 }
Beispiel #29
0
        /// <summary>
        /// Elementy z listBoxa przekazywane są do odpowiedniej Listy (Array), dzięki czemu możemy te dane przechowywać w osobnej klasie.
        /// Dodatkowo te dane z Listy zapisujemy do pliku.
        /// </summary>
        /// <param name="list">Lista, do której chcesz się odwołać.</param>
        /// <param name="nameFileList">Nazwa pliku, w której przechowywane są dane o liście.</param>
        /// <param name="nameList">Nazwa listy nadana podczas tworzenia.</param>
        /// <param name="nameFileName">Nazwa pliku, w którym przechowywana jest nazwa listy.</param>
        private async void SaveList(List <string> list, string nameFileList, string nameFileName, string nameList)
        {
            list.Clear();
            //Przekazywanie danych z listBoxa do listy.
            for (int i = 0; i < listBoxPurchases.Items.Count; i++)
            {
                list.Add((string)listBoxPurchases.Items[i]);
            }

            //Przekazywanie nazwy do pliku .txt
            StorageFile nameData = await ApplicationData.Current.LocalFolder.CreateFileAsync
                                       (nameFileName, CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(nameData, nameList);

            //Dzięki drugiemu parametrowi, jeśli edytujemy dane, to aktualny plik zostanie nadpisany, a nie utworzony nowy.

            //Przekazywanie danych z listy do pliku .txt
            StorageFile listData = await ApplicationData.Current.LocalFolder.CreateFileAsync
                                       (nameFileList, CreationCollisionOption.ReplaceExisting);

            IRandomAccessStream randStream = await listData.OpenAsync(FileAccessMode.ReadWrite);

            using (IOutputStream outStream = randStream.GetOutputStreamAt(0))
            {
                //Stan sesji.

                //Przekazujemy dane w struemieniu określonego typu, u nas jest to List<string>
                DataContractSerializer serializer = new DataContractSerializer(typeof(List <string>));

                //Zapisujemy dane do strumienia/pliku
                serializer.WriteObject(outStream.AsStreamForWrite(), list);

                //Zwolnienie zasobów
                await outStream.FlushAsync();

                outStream.Dispose();
                randStream.Dispose();
            }

            ListboxData.list1Edited = false; ListboxData.list2Edited = false; ListboxData.list3Edited = false;
            //Ponieważ konczymy edytowanie wybranej listy.
            this.Frame.GoBack();
        }
Beispiel #30
0
        public async void WritePersonObjects()
        {
            StorageFile slateUsersFile = await ApplicationData.Current.LocalFolder.CreateFileAsync
                                             ("SlateUsers", CreationCollisionOption.ReplaceExisting);

            IRandomAccessStream raStream = await slateUsersFile.OpenAsync(FileAccessMode.ReadWrite);

            using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
            {
                // Serialize the Session State
                DataContractSerializer serializer = new DataContractSerializer(typeof(List <Person>));

                serializer.WriteObject(outStream.AsStreamForWrite(), slateUsers);

                await outStream.FlushAsync();

                outStream.Dispose();
                raStream.Dispose();
            }
        }