Inheritance: IDataReader, IClosable
Exemplo n.º 1
0
        public async Task <string> ReadLogFile(string fileName)
        {
            if (fileName != this.FQP)
            {
                int index = fileName.IndexOf(DIRECTORY_NAME);
                fileName = fileName.Substring(index);
                var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

                if (file == null)
                {
                    return("");
                }

                return(await Windows.Storage.FileIO.ReadTextAsync(file));
            }

            if (_logFile != null)
            {
                using (var inputStream = _stream.GetInputStreamAt(0))
                {
                    Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(inputStream);
                    await reader.LoadAsync((uint)_stream.Size);

                    string data = reader.ReadString((uint)_stream.Size);
                    reader.DetachStream();
                    return(data);
                }
            }

            return("");
        }
Exemplo n.º 2
0
		public static async Task<bool> LoadFrom ( ObservableCollection<RecentData> datas )
		{
			try
			{
				StorageFile sf = await ApplicationData.Current.LocalFolder.GetFileAsync ( "data.dat" );
				FileRandomAccessStream stream = await sf.OpenAsync ( FileAccessMode.Read ) as FileRandomAccessStream;
				DataReader dr = new DataReader ( stream );
				dr.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
				dr.ByteOrder = ByteOrder.LittleEndian;

				await dr.LoadAsync ( ( uint ) stream.Size );

				int len = dr.ReadInt32 ();
				for ( int i = 0; i < len; i++ )
				{
					RecentData data = new RecentData ();
					uint srclen = dr.ReadUInt32 ();
					data.Source = dr.ReadString ( srclen );
					data.SourceIndex = dr.ReadInt32 ();
					data.TargetIndex = dr.ReadInt32 ();
					datas.Add ( data );
				}

				stream.Dispose ();
			}
			catch { return false; }
			return true;
		}
        private async void ReadBlock_Click(object sender, RoutedEventArgs e)
        {
            var fx2Device = DeviceList.Current.GetSelectedDevice();

            if (fx2Device == null)
            {
                rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage);
                return;
            }

            var button = (Button)sender;
            button.IsEnabled = false;

            var dataReader = new DataReader(fx2Device.InputStream);

            // load the data reader from the stream.  For purposes of this 
            // sample, assume all messages read are < 64 bytes

            int counter = readCounter++;

            LogMessage("Read {0} begin", counter);
            await dataReader.LoadAsync(64);
            
            // Get the message string out of the buffer
            var message = dataReader.ReadString(dataReader.UnconsumedBufferLength);

            LogMessage("Read {0} end: {1}", counter, message);

            button.IsEnabled = true;
        }
Exemplo n.º 4
0
        public async Task<bool> Connect()
        {
            if (_connected) return false;
            var hostname = new HostName("62.4.24.188");
            //var hostname = new HostName("192.168.1.12");
            CancellationTokenSource cts = new CancellationTokenSource();
            try
            {
                cts.CancelAfter(5000);
                await _clientSocket.ConnectAsync(hostname, "4242").AsTask(cts.Token);
            }
            catch (TaskCanceledException)
            {
                _connected = false;
                return false;
            }
            _connected = true;
            _dataReader = new DataReader(_clientSocket.InputStream)
            {
                InputStreamOptions = InputStreamOptions.Partial
            };
            ReadData();
            return true;

        }
Exemplo n.º 5
0
        private async void OnRead(Object sender, RoutedEventArgs e)
        {
            StorageFolder local = ApplicationData.Current.LocalFolder;

            StorageFile file = await local.GetFileAsync("demo.dat");
            if(file != null)
            {
                string strres = "读到的内容:\n";
                using(IRandomAccessStream stream = await file.OpenReadAsync())
                {
                    DataReader dr = new DataReader(stream);
                    dr.UnicodeEncoding = UnicodeEncoding.Utf8;
                    await dr.LoadAsync((uint)stream.Size);
                    bool b = dr.ReadBoolean();
                    strres += b.ToString() + "\n";
                    DateTimeOffset dt = dr.ReadDateTime();
                    strres += dt.ToString("yyyy-M-d") + "\n";
                    uint len = dr.ReadUInt32();
                    if(len > 0)
                    {
                        strres += dr.ReadString(len);
                    }
                    dr.Dispose();
                }
                tbResult.Text = strres;
            }
        }
Exemplo n.º 6
0
        private async void Read()
        {
            _reader = new DataReader(_socket.InputStream);
            try
            {
                while (true)
                {
                    uint sizeFieldCount = await _reader.LoadAsync(sizeof(uint));
                    //if desconneted
                    if (sizeFieldCount != sizeof(uint))
                        return;

                    uint stringLenght = _reader.ReadUInt32();
                    uint actualStringLength = await _reader.LoadAsync(stringLenght);
                    //if desconneted
                    if (stringLenght != actualStringLength)
                        return;
                    if (OnDataRecived != null)
                        OnDataRecived(_reader.ReadString(actualStringLength));
                }

            }
            catch (Exception ex)
            {
                if (OnError != null)
                    OnError(ex.Message);
            }
        }
 public void ReadAllText(string filename, Action<string> completed)
 {
     StorageFolder localFolder = 
                     ApplicationData.Current.LocalFolder;
     IAsyncOperation<StorageFile> createOp = 
                     localFolder.GetFileAsync(filename);
     createOp.Completed = (asyncInfo1, asyncStatus1) =>
     {
         IStorageFile storageFile = asyncInfo1.GetResults();
         IAsyncOperation<IRandomAccessStreamWithContentType> 
             openOp = storageFile.OpenReadAsync();
         openOp.Completed = (asyncInfo2, asyncStatus2) =>
         {
             IRandomAccessStream stream = asyncInfo2.GetResults();
             DataReader dataReader = new DataReader(stream);
             uint length = (uint)stream.Size;
             DataReaderLoadOperation loadOp = 
                                 dataReader.LoadAsync(length);
             loadOp.Completed = (asyncInfo3, asyncStatus3) =>
             {
                 string text = dataReader.ReadString(length);
                 dataReader.Dispose();
                 completed(text);
             };
         };
     };
 }
Exemplo n.º 8
0
 private async Task<string> DoCommand(string command)
 {
     StringBuilder strBuilder = new StringBuilder();
     using (StreamSocket clientSocket = new StreamSocket())
     {
         await clientSocket.ConnectAsync(new HostName("192.168.9.108"),  "9001");
         using (DataWriter writer = new DataWriter(clientSocket.OutputStream))
         {
             writer.WriteString(command);
             await writer.StoreAsync();
             writer.DetachStream();
         }
         using (DataReader reader = new DataReader(clientSocket.InputStream))
         {
             reader.InputStreamOptions = InputStreamOptions.Partial;
             await reader.LoadAsync(8192);
             while (reader.UnconsumedBufferLength > 0)
             {
                 strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
                 await reader.LoadAsync(8192);
             }
             reader.DetachStream();
         }
     }
     return (strBuilder.ToString());
 }
Exemplo n.º 9
0
 byte [] LoadModel(Windows.Storage.StorageFolder folder, string path)
 {
     try
     {
         var task = folder.GetFileAsync(path).AsTask();
         task.Wait();
         var streamTask = task.Result.OpenReadAsync().AsTask();
         streamTask.Wait();
         using (var stream = streamTask.Result)
         {
             using (var reader = new Windows.Storage.Streams.DataReader(stream))
             {
                 var len = stream.Size;
                 reader.LoadAsync((uint)len).AsTask().Wait();
                 byte[] content = new byte[len];
                 reader.ReadBytes(content);
                 return(content);
             }
         }
     } catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.Message);
         System.Diagnostics.Debug.WriteLine(ex.StackTrace);
     }
     return(null);
 }
Exemplo n.º 10
0
        private static async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            ConnectionStatus = ConnectionStatus.Connected;
            DataReader reader = new DataReader(args.Socket.InputStream);
            try
            {
                while (true)
                {
                    uint sizeFieldCount = await reader.LoadAsync(sizeof (uint));
                    if (sizeFieldCount != sizeof (uint))
                    {
                        return;
                    }
                    
                    uint stringLength = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        return;
                    }

                    Message = reader.ReadString(actualStringLength);
                }
            }
            catch (Exception e)
            {
                ConnectionStatus = ConnectionStatus.Failed;
                //TODO:send a connection status message with error
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Receive message through bluetooth.
        /// </summary>
        protected async Task<byte[]> ReceiveMessages(DataReader dataReader)
        {
            try
            {
                
                // Read the message. 
                List<Byte> all = new List<byte>();

                while (true)
                {
                    var bytesAvailable = await dataReader.LoadAsync(1000);
                    var byteArray = new byte[bytesAvailable];
                    dataReader.ReadBytes(byteArray);
                    if (byteArray.Length > 0 && byteArray[0] != byte.MinValue)
                    {
                        if (OnDataRead != null) OnDataRead(byteArray);
                        return byteArray;
                    }

                    Thread.Sleep(100);
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return null;
        }
Exemplo n.º 12
0
        public static async Task<AppModel> DeserializeAppData()
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            AppModel appModel = null;
            try
            {
                // Getting JSON from file if it exists, or file not found exception if it does not  
                StorageFile textFile = await localFolder.GetFileAsync("app.json");
                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                    // Read text stream     
                    using (DataReader textReader = new DataReader(textStream))
                    {
                        //get size                       
                        uint textLength = (uint)textStream.Size;
                        await textReader.LoadAsync(textLength);
                        // read it                    
                        string jsonContents = textReader.ReadString(textLength);
                        // deserialize back to our product!  
                        appModel = JsonConvert.DeserializeObject<AppModel>(jsonContents);
                       
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return appModel;
        }
Exemplo n.º 13
0
        internal async Task ConnectAsync(
            HostName hostName,
            string serviceName,
            string user,
            string password)
        {
            if (controlStreamSocket != null)
            {
                throw new InvalidOperationException("Control connection already started.");
            }

            this.hostName = hostName;

            controlStreamSocket = new StreamSocket();
            await controlStreamSocket.ConnectAsync(hostName, serviceName);

            reader = new DataReader(controlStreamSocket.InputStream);
            reader.InputStreamOptions = InputStreamOptions.Partial;

            writer = new DataWriter(controlStreamSocket.OutputStream);

            readCommands = new List<string>();
            loadCompleteEvent = new AutoResetEvent(false);
            readTask = InfiniteReadAsync();

            FtpResponse response;
            response = await GetResponseAsync();
            VerifyResponse(response, 220);

            response = await UserAsync(user);
            VerifyResponse(response, 331);

            response = await PassAsync(password);
            VerifyResponse(response, 230);
        }
Exemplo n.º 14
0
 public void OnDataReadCompletion(UInt32 bytesRead, DataReader readPacket)
 {
    
     if (readPacket == null)
     {
         Debug.WriteLine("DataReader is null");
     }
     else if (readPacket.UnconsumedBufferLength != 0)
     {
         Byte[] numArray = new Byte[bytesRead];
         readPacket.ReadBytes(numArray);
         Response response = parser.processRawBytes(numArray);
         if (response != null)
         {
             DispatchResponseThreadSafe(response);
         }
         PostSocketRead(16);
     }
     else
     {
         Debug.WriteLine("Received zero bytes from the socket. Server must have closed the connection.");
         Debug.WriteLine("Try disconnecting and reconnecting to the server");
     }
     
 }
Exemplo n.º 15
0
        private async void ReceiveImage(StreamSocket socket)
        {
            UpdateStatus("Empfange Daten...");

            // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
            var reader = new DataReader(socket.InputStream);

            // Anzahl der Bytes abrufen, aus denen das Bild besteht
            // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
            await reader.LoadAsync(4);
            int imageSize = reader.ReadInt32();

            // Bytearray des Bildes laden
            await reader.LoadAsync((uint)imageSize);
            byte[] imageBytes = new byte[imageSize];
            reader.ReadBytes(imageBytes);

            // Bytearray in Stream laden und anzeigen
            Dispatcher.BeginInvoke(() =>
            {
                using (var ms = new MemoryStream(imageBytes))
                {
                    var image = new BitmapImage();
                    image.SetSource(ms);

                    ReceivedImage.Source = image;
                }
            });
            UpdateStatus("Bild empfangen.");

            // Ressourcen freigeben
            reader.Dispose();
        }
        private async void save_Video(object sender, RoutedEventArgs e)
        {
            // Adding try catch block in case of occurence of an exception
            try
            {
                // Creating object of FileSavePicker and adding few values to the properties of the object.
                FileSavePicker fs = new FileSavePicker();
                fs.FileTypeChoices.Add("Video", new List<string>() { ".mp4",".3gp" });
                fs.DefaultFileExtension = ".mp4";
                fs.SuggestedFileName = "Video" + DateTime.Today.ToString();
                fs.SuggestedStartLocation = PickerLocationId.VideosLibrary;

                // Using storagefile object defined earlier in above method to save the file using filesavepicker.
                fs.SuggestedSaveFile = sf;

                // Saving the file
                var s = await fs.PickSaveFileAsync();
                if (s != null)
                {
                    using (var dataReader = new DataReader(rs.GetInputStreamAt(0)))
                    {
                        await dataReader.LoadAsync((uint)rs.Size);
                        byte[] buffer = new byte[(int)rs.Size];
                        dataReader.ReadBytes(buffer);
                        await FileIO.WriteBytesAsync(s, buffer);
                    }
                }
            }
            catch (Exception ex)
            {
                var messageDialog = new MessageDialog("Something went wrong.");
                await messageDialog.ShowAsync();
            }
        }
Exemplo n.º 17
0
        private async void getButton_Click(object sender, RoutedEventArgs e)
        {
            // This constructs a string of the form "http://www.google.com:80/"
            HttpWebRequest request = WebRequest.CreateHttp( "http://" + this.hostnameText.Text + ":" + this.portText.Text + this.resourceText.Text);

            try
            {
                using (var response = await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null))
                {
                    // Create a datareader off of our response stream
                    DataReader dr = new DataReader(response.GetResponseStream().AsInputStream());

                    // Throw the HTTP text into our textOutput
                    this.textOutput.Text = await readHTTPMessage(dr);

                    // As this was a successful request, make the text green:
                    this.textOutput.Foreground = new SolidColorBrush(Color.FromArgb(255, 128, 255, 128));
                }
            }
            catch (Exception ex)
            {
                // We ran into some kind of problem; output it to the user!
                this.textOutput.Text = "Error: " + ex.Message;
                this.textOutput.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 128, 128));
            }
        }
Exemplo n.º 18
0
    private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
    {
        socket = args.Socket;
        var dr = new DataReader(socket.InputStream);

        /// GET ヘッダを取り出し
        StringBuilder request = new StringBuilder();
        uint BufferSize = 1024;
        using (IInputStream input = socket.InputStream)
        {
            byte[] data = new byte[BufferSize];
            IBuffer buffer = data.AsBuffer();
            uint dataRead = BufferSize;
            while (dataRead == BufferSize)
            {
                await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
                request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                dataRead = buffer.Length;
            }
        }
        // GET method を取り出し
        string requestMethod = request.ToString().Split('\n')[0];
        string[] requestParts = requestMethod.Split(' ');
        var text = requestParts[1];

        /// GETコマンドの受信イベント
        if (this.OnReceived != null)
        {
            OnReceived(text);
        }
    }
Exemplo n.º 19
0
        public async static Task<IRandomAccessStream> AsRandomAccessStreamAsync(this Stream stream)
        {
            Stream streamToConvert = null;

            if (!stream.CanRead)
            {
                throw new Exception("Cannot read the source stream-");
            }
            if (!stream.CanSeek)
            {
                MemoryStream memoryStream = new MemoryStream();
                await stream.CopyToAsync(memoryStream);
                streamToConvert = memoryStream;
            }
            else
            {
                streamToConvert = stream;
            }

            DataReader dataReader = new DataReader(streamToConvert.AsInputStream());
            streamToConvert.Position = 0;
            await dataReader.LoadAsync((uint)streamToConvert.Length);
            IBuffer buffer = dataReader.ReadBuffer((uint)streamToConvert.Length);

            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
            IOutputStream outputstream = randomAccessStream.GetOutputStreamAt(0);
            await outputstream.WriteAsync(buffer);
            await outputstream.FlushAsync();

            return randomAccessStream;
        }
 private async Task<RfidReaderResult> Read()
 {
     RfidReaderResult retvalue = new RfidReaderResult();
     var dataReader = new DataReader(_rfidReader.InputStream);
     try
     {
         SetStatus("Awaiting Data from RFID Reader");
         var numBytesRecvd = await dataReader.LoadAsync(1024);
         retvalue.Result = new byte[numBytesRecvd];
         if (numBytesRecvd > 0)
         {
             SetStatus("Data successfully read from RFID Reader");
             dataReader.ReadBytes(retvalue.Result);
             retvalue.IsSuccessful = true;
             retvalue.Message = "Data successfully read from RFID Reader";
         }
     }
     catch (Exception ex)
     {
         retvalue.IsSuccessful = false;
         retvalue.Message = ex.Message;
     }
     finally
     {
         if (dataReader != null)
         {
             dataReader.DetachStream();
             dataReader = null;
         }
     }
     return retvalue;
 }
 private async void ReadFromStreamButton_Click(object sender, RoutedEventArgs e)
 {
     StorageFile file = rootPage.sampleFile;
     if (file != null)
     {
         try
         {
             using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
             {
                 using (DataReader dataReader = new DataReader(readStream))
                 {
                     UInt64 size = readStream.Size;
                     if (size <= UInt32.MaxValue)
                     {
                         UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
                         string fileContent = dataReader.ReadString(numBytesLoaded);
                         rootPage.NotifyUser(String.Format("The following text was read from '{0}' using a stream:{1}{2}", file.Name, Environment.NewLine, fileContent), NotifyType.StatusMessage);
                     }
                     else
                     {
                         rootPage.NotifyUser(String.Format("File {0} is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync.", file.Name), NotifyType.ErrorMessage);
                     }
                 }
             }
         }
         catch (FileNotFoundException)
         {
             rootPage.NotifyUserFileNotExist();
         }
     }
     else
     {
         rootPage.NotifyUserFileNotExist();
     }
 }
Exemplo n.º 22
0
 public async Task ConnectToDevice(DeviceInformation device)
 {
     this.State = ConnectionState.Connecting;
     try
     {
         serialConnection = await SerialDevice.FromIdAsync(device.Id);
         if (serialConnection != null)
         {
             serialConnection.BaudRate = 115200;
             serialConnection.DataBits = 8;
             serialConnection.Parity = SerialParity.None;
             writer = new DataWriter(serialConnection.OutputStream);
             reader = new DataReader(serialConnection.InputStream);
             Task listen = ListenForMessagesAsync();
             this.State = ConnectionState.Connected;
         }
         else {
             Debugger.ReportToDebugger(this, "Unable to create service.\nMake sure that the 'serialcommunication' capability is declared with a function of type 'name:serialPort' in Package.appxmanifest.", Debugger.Device.Pc);
             this.State = ConnectionState.Failure;
         }
     }
     catch (TaskCanceledException ex)
     {
         this.State = ConnectionState.Failure;
         Debugger.ReportToDebugger(this, ex.Message, Debugger.Device.Pc);
     }
     catch (Exception ex)
     {
         this.State = ConnectionState.Failure;
         Debugger.ReportToDebugger(this, ex.Message, Debugger.Device.Pc);
     }
 }
Exemplo n.º 23
0
        public async Task<IEnumerable<Event>> Read() 
        {
            List<Event> events = null;
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            try
            {
                StorageFile textFile = await localFolder.GetFileAsync("SavedContent");
                events = new List<Event>();
                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                    using (DataReader textReader = new DataReader(textStream))
                    {
                        uint textLength = (uint)textStream.Size;
                        await textReader.LoadAsync(textLength);
                        string jsonContents = textReader.ReadString(textLength);
                        events = JsonConvert.DeserializeObject<IList<Event>>(jsonContents) as List<Event>;
                    }
                    return events;
                }
            }
            catch (Exception ex)
            {
                return null;
            }

        }
        public async void OnOpen()
        {
            try
            {
                var picker = new FileOpenPicker()
                {
                    SuggestedStartLocation = PickerLocationId.DocumentsLibrary
                };
                picker.FileTypeFilter.Add(".txt");

                StorageFile file = await picker.PickSingleFileAsync();
                if (file != null)
                {
                    IRandomAccessStreamWithContentType stream = await file.OpenReadAsync();
                    using (var reader = new DataReader(stream))
                    {
                        await reader.LoadAsync((uint)stream.Size);

                        text1.Text = reader.ReadString((uint)stream.Size);
                    }
                }
            }
            catch (Exception ex)
            {
                var dlg = new MessageDialog(ex.Message, "Error");
                await dlg.ShowAsync();
            }
        }
 //Connects to server
 public async Task connect(string address, int port)
 {
     if (!this.connected)
     {
         try
         {
             this.socket = new StreamSocket();
             this.hostname = new HostName(address);
             this.port = port;
             await this.socket.ConnectAsync(this.hostname, port.ToString());
             this.writer = new DataWriter(this.socket.OutputStream);
             this.reader = new DataReader(this.socket.InputStream);
             this.reader.InputStreamOptions = InputStreamOptions.Partial;
             connected = true;
         }
         catch (Exception e)
         {
             connected = false;
             Debug.WriteLine(e.Message);
         }
     }
     else
     {
         await new MessageDialog("Already connected", "Information").ShowAsync();
         connected = true;
         
     }
 }
Exemplo n.º 26
0
		public WinRtTransferHandler(StreamSocket socket)
		{
			if (socket == null) throw new ArgumentNullException("socket");

			_reader = new DataReader(socket.InputStream);
			_writer = new DataWriter(socket.OutputStream);
		}
Exemplo n.º 27
0
        private async void ProtectData()
        {
            if (await storageFolder.TryGetItemAsync("config.txt") != null) // if user file exists
            {
                configSF = await storageFolder.GetFileAsync("config.txt");

                var stream = await configSF.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);

                        IBuffer textBuffer = dataReader.ReadBuffer(numBytesLoaded);
                        string  text       = await SampleDataUnprotectStream(textBuffer, encoding);

                        if (text.Length != 0 && text.IndexOf(" ") > 0)
                        {
                            Username.Text     = text.Substring(0, text.IndexOf(" "));
                            Password.Password = text.Substring(text.IndexOf(" ") + 1);
                            saveLogin         = true;
                            SavePasswordCheckBox.IsChecked = true;
                        }
                    }
                }
            }
        }
Exemplo n.º 28
0
        async void OnFileOpenButtonClick(object sender, RoutedEventArgs args) {
            FileOpenPicker picker = new FileOpenPicker();
            picker.FileTypeFilter.Add(".txt");
            StorageFile storageFile = await picker.PickSingleFileAsync();

            // If user presses Cancel, result is null
            if (storageFile == null)
                return;

            Exception exception = null;

            try {
                using (IRandomAccessStream stream = await storageFile.OpenReadAsync()) {
                    using (DataReader dataReader = new DataReader(stream)) {
                        uint length = (uint)stream.Size;
                        await dataReader.LoadAsync(length);
                        txtbox.Text = dataReader.ReadString(length);
                    }
                }
            }
            catch (Exception exc) {
                exception = exc;
            }

            if (exception != null) {
                MessageDialog msgdlg = new MessageDialog(exception.Message, "File Read Error");
                await msgdlg.ShowAsync();
            }
        }
Exemplo n.º 29
0
        private async Task SaveBitmap(RenderTargetBitmap rtb, SoftwareBitmap swBmp)
        {
            FileSavePicker filePicker = new Windows.Storage.Pickers.FileSavePicker();

            filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            filePicker.FileTypeChoices.Add("JPG file", new List <string>()
            {
                ".jpg"
            });
            StorageFile file = await filePicker.PickSaveFileAsync();

            if (file != null)
            {
                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    IBuffer buffer = await rtb.GetPixelsAsync();

                    Windows.Storage.Streams.DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer);
                    byte[] generatedImage = new byte[buffer.Length];
                    dataReader.ReadBytes(generatedImage);
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);

                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied, (uint)rtb.PixelWidth, (uint)rtb.PixelHeight, swBmp.DpiX, swBmp.DpiY, generatedImage);
                    await encoder.FlushAsync();
                }
            }
        }
        public static async Task<DiscoveryServiceCache> LoadAsync()
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            try
            {
                _lock.EnterReadLock();
                StorageFile textFile = await localFolder.GetFileAsync(FileName);

                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                    using (DataReader textReader = new DataReader(textStream))
                    {
                        uint textLength = (uint)textStream.Size;

                        await textReader.LoadAsync(textLength);
                        return Load(textReader);
                    }
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                _lock.ExitReadLock();
            }

            return null;
        }
Exemplo n.º 31
0
    private async void read_data()
    {
        ifListening = true;
        // int read_msg_counter = 2;
        using (var reader = new Windows.Storage.Streams.DataReader(streamSocket.InputStream)){
            reader.InputStreamOptions = Windows.Storage.Streams.InputStreamOptions.ReadAhead;
            reader.UnicodeEncoding    = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            reader.ByteOrder          = Windows.Storage.Streams.ByteOrder.LittleEndian;

            await reader.LoadAsync(4);

            while (reader.UnconsumedBufferLength > 0)
            {
                // read_msg_counter--;
                int bytesToRerad = reader.ReadInt32();
                // Debug.Log("bytes to read: " + bytesToRerad);
                if (bytesToRerad <= 0)
                {
                    return;
                }
                await reader.LoadAsync(Convert.ToUInt32(bytesToRerad));

                byte[] buffer = new byte[bytesToRerad];
                reader.ReadBytes(buffer);
                processReceivedData(buffer, bytesToRerad);

                await reader.LoadAsync(4);
            }

            reader.DetachStream();
        }
        ifListening = false;
    }
        public SocketHandler(StreamSocket socket)
        {
            this.socket = socket;

            this.reader = new DataReader(this.socket.InputStream);
            this.writer = new DataWriter(this.socket.OutputStream);
        }
Exemplo n.º 33
0
 private async void ReadFromStreamButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         rootPage.ResetScenarioOutput(OutputTextBlock);
         StorageFile file = rootPage.sampleFile;
         if (file != null)
         {
             using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
             {
                 using (DataReader dataReader = new DataReader(readStream))
                 {
                     UInt64 size = readStream.Size;
                     if (size <= UInt32.MaxValue)
                     {
                         UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
                         string fileContent = dataReader.ReadString(numBytesLoaded);
                         OutputTextBlock.Text = "The following text was read from '" + file.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + fileContent;
                     }
                     else
                     {
                         OutputTextBlock.Text = "File " + file.Name + " is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync.";
                     }
                 }
             }
         }
     }
     catch (FileNotFoundException)
     {
         rootPage.NotifyUserFileNotExist();
     }
 }
 public void Open()
 {
   OpenConnection();
   dataReader = new DataReader(streamSocket.InputStream);
   dataWriter = new DataWriter(streamSocket.OutputStream);
   readable = writeable = true;
 }
Exemplo n.º 35
0
        private async Task<string> readHTTPMessage(DataReader dr)
        {
            // Make sure we are allowed to return early
            dr.InputStreamOptions = InputStreamOptions.Partial;

            // This is the value we will return
            string ret = "";

            // This is the amount of data ready to be read in
            uint readyLen;
            while (true)
            {
                // Wait until we've got a kilobyte, or the stream closed
                readyLen = await dr.LoadAsync(1024 * 1024);

                // Check to see if we actually have any data
                if (readyLen > 0)
                {
                    // Read in that string, append it to ret
                    ret += dr.ReadString(readyLen);

                    // Check for the "\r\n\r\n" at the end of messages
                    if (ret.Substring(ret.Length - 4, 4) == "\r\n\r\n")
                        break;
                }
                else
                {
                    // If not, the connection is closed!
                    return ret;
                }
            }

            // Finally, return that string
            return ret;
        }
Exemplo n.º 36
0
        protected override async void Loop()
        {
            Streams.DataReader reader = null;

            try
            {
                while (true)
                {
                    if (socket == null)
                    {
                        socket = new StreamSocket();
                        await socket.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
                    }

                    var readBuf = new Streams.Buffer((uint)NetworkBufferSize);
                    var readOp  = socket.InputStream.ReadAsync(readBuf, (uint)NetworkBufferSize, Streams.InputStreamOptions.Partial);

                    readOp.Completed = (IAsyncOperationWithProgress <Streams.IBuffer, uint> asyncAction, AsyncStatus asyncStatus) =>
                    {
                        switch (asyncStatus)
                        {
                        case AsyncStatus.Completed:
                            Debug.WriteLine("Config:Completed ");
                            try
                            {
                                Streams.IBuffer localBuf  = asyncAction.GetResults();
                                uint            bytesRead = localBuf.Length;
                                Debug.WriteLine("Config:Buffer (" + bytesRead + ")");
                                reader = Streams.DataReader.FromBuffer(localBuf);
                                OnDataReadCompletion(bytesRead, reader);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e.ToString());
                            }
                            break;

                        case AsyncStatus.Canceled:
                            Debug.WriteLine("Config:Canceled ");
                            break;

                        case AsyncStatus.Error:
                            Debug.WriteLine("Config:Error ");
                            break;
                        }
                    };
                    //socket.Dispose();
                    await Task.Delay(500);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                Stop();
            }
        }
Exemplo n.º 37
0
        public static async Task <byte[]> AsByteArrayAsync(this IRandomAccessStream iRandomAccessStream)
        {
            IRandomAccessStream fileStream = iRandomAccessStream;
            var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
            await reader.LoadAsync((uint)fileStream.Size);

            byte[] pixels = new byte[fileStream.Size];
            reader.ReadBytes(pixels);
            return(pixels);
        }
Exemplo n.º 38
0
        public static async Task <byte[]> GetBytesFromStorageFile(StorageFile file)
        {
            IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read);

            var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
            await reader.LoadAsync((uint)fileStream.Size);

            byte[] pixels = new byte[fileStream.Size];
            reader.ReadBytes(pixels);
            return(pixels);
        }
Exemplo n.º 39
0
        public static async Task <byte[]> GetBytesAsync(this storage.StorageFile file)
        {
            sStream.IRandomAccessStream fileStream = await file.OpenAsync(storage.FileAccessMode.Read);

            var reader = new sStream.DataReader(fileStream.GetInputStreamAt(0));
            await reader.LoadAsync((uint)fileStream.Size);

            byte[] bytes = new byte[fileStream.Size];
            reader.ReadBytes(bytes);
            return(bytes);
        }
Exemplo n.º 40
0
        public async Task <T> LoadASync(string FileName)
        {
            FileName = FileName + ".xml";
            try
            {
                StorageFile   file   = null;
                StorageFolder folder = GetFolder(storageType);
                file = await folder.GetFileAsync(FileName);

                //using (var readStream = await file.OpenAsync(FileAccessMode.Read))
                //{
                //    Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(readStream);

                //    await reader.LoadAsync((uint)readStream.Size);
                //    string data = reader.ReadString((uint)readStream.Size);

                //    if (data == null)
                //    {
                //    }
                //}


                using (var readStream = await file.OpenAsync(FileAccessMode.Read))
                {
                    //Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;
                    //return (T)serializer.Deserialize(inStream);

                    var inStream = readStream.GetInputStreamAt(0);
                    Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(inStream);
                    await reader.LoadAsync((uint)readStream.Size);

                    string data = reader.ReadString((uint)readStream.Size);
                    reader.DetachStream();

                    MemoryStream ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(data));
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                    T result = (T)ser.ReadObject(ms);
                    return(result);
                }
            }
            catch (FileNotFoundException)
            {
                //file not existing is perfectly valid so simply return the default
                return(default(T));
                //throw;
            }
            catch (Exception)
            {
                //Unable to load contents of file
                throw;
            }
        }
Exemplo n.º 41
0
        internal async void InitPreviewImage()
        {
            if (this.Source == null)
            {
                return;
            }

            using (var fileStream = await this.Source.OpenReadAsync())
            {
                InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();

                using (var readStream = fileStream.GetInputStreamAt(0))
                {
                    var reader = new Windows.Storage.Streams.DataReader(readStream);
                    await reader.LoadAsync((uint)fileStream.Size);

                    byte[] bytes = new byte[fileStream.Size];
                    reader.ReadBytes(bytes);

                    var writeStream = memoryStream.GetOutputStreamAt(0).AsStreamForWrite();
                    writeStream.WriteAsync(bytes, 0, (int)fileStream.Size);
                    await writeStream.FlushAsync();
                }

                this.modifiedBitmapStream = memoryStream.CloneStream();
                this.previewBitmapStream  = this.modifiedBitmapStream;
            }

            var decoder = await BitmapDecoder.CreateAsync(this.previewBitmapStream);

            //   this.originalBitmapStream = await this.Source.OpenReadAsync();
            //  this.previewBitmapStream = await this.Source.OpenReadAsync();
            var properties = await this.Source.Properties.GetImagePropertiesAsync();

            System.Threading.SynchronizationContext.Current.Post((args) =>
            {
                System.Threading.SynchronizationContext.Current.Post((args2) =>
                {
                    this.previewBitmap  = new WriteableBitmap((int)properties.Width, (int)properties.Height);
                    this.originalBitmap = new WriteableBitmap((int)properties.Width, (int)properties.Height);
                    this.previewBitmap.SetSource(this.modifiedBitmapStream);
                    this.originalBitmap.SetSource(this.modifiedBitmapStream);

                    this.previewBitmap.Invalidate();
                    this.originalBitmap.Invalidate();

                    this.ModifiedImage = this.previewBitmap;
                }, null);
            }, null);
        }
Exemplo n.º 42
0
        private static byte[] ExtractBytesFromBuffer(Windows.Storage.Streams.IBuffer buffer)
        {
            List <byte> data = new List <byte>(capacity: (int)buffer.Length);

            using (Windows.Storage.Streams.DataReader dr = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
            {
                while (dr.UnconsumedBufferLength > 0)
                {
                    data.Add(dr.ReadByte());
                }
            }

            return(data.ToArray());
        }
Exemplo n.º 43
0
        public static async Task <byte[]> AsByteArrayAsync(this StorageFile file, string ReplaceLocalFileNameWithExtension, uint ImageWidthHeight)
        {
            var imgThumbnail = await file.GetThumbnailAsync(ThumbnailMode.PicturesView, ImageWidthHeight, ThumbnailOptions.ResizeThumbnail);

            BitmapImage bitmapImage = new BitmapImage();

            bitmapImage.DecodePixelHeight = (int)ImageWidthHeight;
            bitmapImage.DecodePixelWidth  = (int)ImageWidthHeight;
            bitmapImage.SetSource(imgThumbnail);

            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(imgThumbnail.CloneStream());

            SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();

            var         LocalFolder = ApplicationData.Current.LocalFolder;
            StorageFile file_Save   = await LocalFolder.CreateFileAsync(ReplaceLocalFileNameWithExtension, CreationCollisionOption.ReplaceExisting);

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId, await file_Save.OpenAsync(FileAccessMode.ReadWrite));

            encoder.SetSoftwareBitmap(softwareBitmap);
            encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;
            encoder.BitmapTransform.ScaledHeight      = ImageWidthHeight;
            encoder.BitmapTransform.ScaledWidth       = ImageWidthHeight;
            encoder.BitmapTransform.Bounds            = new BitmapBounds()
            {
                Width  = ImageWidthHeight,
                Height = ImageWidthHeight,
            };

            await encoder.FlushAsync();

            IRandomAccessStream fileStream = await file_Save.OpenAsync(FileAccessMode.ReadWrite);

            var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
            await reader.LoadAsync((uint)fileStream.Size);

            byte[] pixels = new byte[fileStream.Size];

            reader.ReadBytes(pixels);

            return(pixels);
        }
Exemplo n.º 44
0
    private void WebSocket_MessageReceived(Windows.Networking.Sockets.MessageWebSocket sender, Windows.Networking.Sockets.MessageWebSocketMessageReceivedEventArgs args)
    {
        try
        {
            using (Windows.Storage.Streams.DataReader dataReader = args.GetDataReader())
            {
                dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                string message = dataReader.ReadString(dataReader.UnconsumedBufferLength);
                Debug.Log("Message received from MessageWebSocket: " + message);
                cmds.Enqueue(message);
                //m_Socket.Dispose();
            }
        }
        catch (Exception ex)
        {
            Windows.Web.WebErrorStatus webErrorStatus = Windows.Networking.Sockets.WebSocketError.GetStatus(ex.GetBaseException().HResult);
            // Add additional code here to handle exceptions.
        }

    }
Exemplo n.º 45
0
        public async void StartReader(ConnectedPeer connectedPeer)
        {
            try
            {
                using (var socketReader = new Windows.Storage.Streams.DataReader(connectedPeer._socket.InputStream))
                {
                    // Read the message sent by the remote peer
                    uint bytesRead = await socketReader.LoadAsync(sizeof(uint));

                    if (bytesRead > 0)
                    {
                        uint strLength = (uint)socketReader.ReadUInt32();
                        bytesRead = await socketReader.LoadAsync(strLength);

                        if (bytesRead > 0)
                        {
                            String message = socketReader.ReadString(strLength);
                            OnRaiseMessageEvent(new MessageEventArgs("Got message: " + message));
                            StartReader(connectedPeer); // Start another reader
                        }
                        else
                        {
                            OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket"));
                        }
                    }
                    else
                    {
                        OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket"));
                    }

                    socketReader.DetachStream();
                }
            }
            catch (Exception e)
            {
                if (!connectedPeer._socketClosed)
                {
                    OnRaiseSocketErrorEvent(new SocketEventArgs("Reading from socket failed: " + e.Message));
                }
            }
        }
Exemplo n.º 46
0
        private async void LoadImage(object sender, RoutedEventArgs e)
        {
            FileOpenPicker open = new FileOpenPicker();

            open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            open.ViewMode = PickerViewMode.Thumbnail;

            // Filter to include a sample subset of file types
            open.FileTypeFilter.Clear();
            open.FileTypeFilter.Add(".bmp");
            open.FileTypeFilter.Add(".png");
            open.FileTypeFilter.Add(".jpeg");
            open.FileTypeFilter.Add(".jpg");

            StorageFile file = await open.PickSingleFileAsync();

            if (file != null)
            {
                // Ensure the stream is disposed once the image is loaded
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    // Set the image source to the selected bitmap

                    /* BitmapImage bitmapImage = new BitmapImage();
                     * bitmapImage.DecodePixelHeight = 250;
                     * bitmapImage.DecodePixelWidth = 250;
                     *
                     * await bitmapImage.SetSourceAsync(fileStream);
                     * _image = bitmapImage;*/

                    var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
                    await reader.LoadAsync((uint)fileStream.Size);

                    byte[] pixels = new byte[fileStream.Size];

                    reader.ReadBytes(pixels);

                    _image = pixels;
                }
            }
        }
        public override void save(java.io.InputStream image, java.io.OutputStream response, string format, int width, int height, float quality)
        {
            CanvasBitmapFileFormat fileFormat = CanvasBitmapFileFormat.Png;

            if (format.Equals(FORMAT_JPEG))
            {
                fileFormat = CanvasBitmapFileFormat.Jpeg;
            }
            CodenameOneImage           img         = (CodenameOneImage)SilverlightImplementation.instance.createImage(image);
            CodenameOneImage           scaledImage = (CodenameOneImage)SilverlightImplementation.instance.scale(img, width, height);
            InMemoryRandomAccessStream ms          = new InMemoryRandomAccessStream();

            scaledImage.image.SaveAsync(ms, fileFormat, quality).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
            ms.Seek(0);
            byte[] buf = new byte[ms.Size];
            var    dr  = new Windows.Storage.Streams.DataReader(ms);

            dr.LoadAsync((uint)ms.Size).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
            dr.ReadBytes(buf);
            response.write(buf);
        }
        protected override void saveImage(com.codename1.ui.Image image, java.io.OutputStream response, string format, float quality)
        {
            CanvasBitmapFileFormat fileFormat = CanvasBitmapFileFormat.Png;

            if (format.Equals(FORMAT_JPEG))
            {
                fileFormat = CanvasBitmapFileFormat.Jpeg;
            }
            CodenameOneImage           img = (CodenameOneImage)image.getImage();
            CanvasBitmap               cb  = img.image;
            InMemoryRandomAccessStream ms  = new InMemoryRandomAccessStream();

            cb.SaveAsync(ms, fileFormat, quality).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();;
            ms.Seek(0);
            byte[] buf = new byte[ms.Size];
            var    dr  = new Windows.Storage.Streams.DataReader(ms);

            dr.LoadAsync((uint)ms.Size).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();;
            dr.ReadBytes(buf);
            response.write(buf);
        }
Exemplo n.º 49
0
        private async void Sck_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            //[email protected]("Message received " + args);

            if (args.MessageType == SocketMessageType.Utf8)
            {
                Windows.Storage.Streams.DataReader messageReader = args.GetDataReader();
                messageReader.UnicodeEncoding = UnicodeEncoding.Utf8;
                string messageString = messageReader.ReadString(messageReader.UnconsumedBufferLength);
                com.codename1.io.websocket.WebSocket.messageReceived(id, messageString);
            }
            else
            {
                Windows.Storage.Streams.IInputStream readStream = args.GetDataStream();
                byte[] readBuffer = new byte[4096];
                try
                {
                    while (true)
                    {
                        if (sender != sck)
                        {
                            return;
                        }

                        IBuffer res = await readStream.ReadAsync(readBuffer.AsBuffer(), (uint)readBuffer.Length, 0);

                        if (res.Length == 0)
                        {
                            return;
                        }
                        byte[] resArr = new byte[res.Length];
                        res.CopyTo(resArr);
                        com.codename1.io.websocket.WebSocket.messageReceived(1, resArr);
                    }
                } catch (Exception ex)
                {
                    com.codename1.io.websocket.WebSocket.errorReceived(id, ex.Message, ex.HResult);
                }
            }
        }
Exemplo n.º 50
0
        private void OnDataReadCompletion(uint bytesRead, Streams.DataReader reader)
        {
            if (reader == null)
            {
                return;
            }

            uint unreadLength = reader.UnconsumedBufferLength;

            if (unreadLength == 0)
            {
                return;
            }

            byte[] buffer = new byte[unreadLength];
            reader.ReadBytes(buffer);

            StringBuilder stringBuffer = new StringBuilder();

            stringBuffer.Append(Encoding.UTF8.GetString(buffer, 0, buffer.Length));
            Debug.WriteLine("Configuration Brute: " + stringBuffer.ToString());

            var packet = new ConfigurationPacket
            {
                Timestamp = DateTime.UtcNow.Ticks,
                Data      = buffer
            };

            if (UpdateConfiguration(packet))
            {
                if (_DroneClient.RequestedState == RequestedState.GetConfiguration)
                {
                    _DroneClient.RequestedState = RequestedState.None;
                }
                ConfigurationViewModelHelper.UpdateConfigurationSections(_DroneClient.ConfigurationSectionsViewModel, _DroneClient.Configuration);
            }
        }
Exemplo n.º 51
0
Arquivo: Print3D.cs Projeto: ice0/test
    private async static Task <bool> SaveStreamTo3MF(Windows.Storage.Streams.IRandomAccessStream stream)
    {
        // set back
        stream.Seek(0);
        using (var dataReader = new Windows.Storage.Streams.DataReader(stream))
        {
            var dataLoad = await dataReader.LoadAsync((uint)stream.Size);

            if (dataLoad > 0)
            {
                var buffer = dataReader.ReadBuffer((uint)stream.Size);

                StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                var           outputfile  = await localFolder.CreateFileAsync("output.3mf", CreationCollisionOption.ReplaceExisting);

                await Windows.Storage.FileIO.WriteBufferAsync(outputfile, buffer);

                var options = new Windows.System.LauncherOptions();
                options.TargetApplicationPackageFamilyName = "Microsoft.3DBuilder_8wekyb3d8bbwe";
            }
        }

        return(true);
    }
Exemplo n.º 52
0
        private async Task TryPostJsonAsync()
        {
            try
            {
                // Construct the HttpClient and Uri. This endpoint is for test purposes only.
                //var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                //myFilter.AllowUI = false;

                //Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                //Windows.Storage.StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
                fileOpenPicker.FileTypeFilter.Add(".json");

                /*fileOpenPicker.FileTypeFilter.Add(".txt");
                 * Windows.Storage.StorageFile credentialsFile = await fileOpenPicker.PickSingleFileAsync();
                 * string text = await Windows.Storage.FileIO.ReadTextAsync(credentialsFile);
                 * string username = text.Split(',')[0];
                 * string password = text.Split(',')[1];
                 * string domain = text.Split(',')[2];*/

                HttpClientHandler handler = new HttpClientHandler();
                handler.Credentials = new NetworkCredential("", "", "");

                System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(handler);

                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                Uri uri = new Uri("https://prodigalcompany.com/npjTest/SurveyStuff/testSurveyFile.json");

                // Construct the JSON to post.
                //fileOpenPicker.FileTypeChoices.Add("JSON", new List<string>() { ".json" });

                IStorageFile jsonFile = await fileOpenPicker.PickSingleFileAsync();

                IRandomAccessStream stream = await jsonFile.OpenAsync(FileAccessMode.Read);

                System.Net.Http.MultipartFormDataContent postContent = new MultipartFormDataContent();

                if (stream != null)
                {
                    using (var dataReader = new Windows.Storage.Streams.DataReader(stream))
                    {
                        uint numBytesLoaded = await dataReader.LoadAsync((uint)stream.Size);

                        string jsonText = dataReader.ReadString(numBytesLoaded);

                        System.Net.Http.StringContent streamContent = new System.Net.Http.StringContent(jsonText);
                        streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                        postContent.Add(streamContent);
                        System.Net.Http.HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
                            "https://prodigalcompany.com/npjTest/SurveyStuff/testSurveyFile.json",
                            postContent);

                        // Make sure the post succeeded, and write out the response.
                        httpResponseMessage.EnsureSuccessStatusCode();
                        var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();

                        Debug.WriteLine(httpResponseBody);
                    }
                }
                else
                {
                    Debug.WriteLine("stream is NULL.");
                }

                //HttpStringContent content = await jsonFile.OpenReadAsync();
                // Post the JSON and wait for a response.
            }
            catch (Exception ex)
            {
                // Write out any exceptions.
                Debug.WriteLine(ex);
            }
        }
Exemplo n.º 53
0
        async void beginexecblock()
        {
            if ((await Windows.Storage.ApplicationData.Current.RoamingFolder.GetFilesAsync()).Count == 0)
            {
                await ApplicationData.Current.RoamingFolder.CreateFileAsync("testfile.txt");

                ApplicationData.Current.SignalDataChanged();
                Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog("Roaming file creation success", "Sync status");
                await tdlg.ShowAsync();
            }
            try
            {
                DateTime      started = DateTime.Now;
                RenderContext mtext   = new RenderContext();
                maincontext = mtext;
                StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
                StorageFile   file   = await folder.GetFileAsync("DXInteropLib\\VertexShader.cso");

                var stream = (await file.OpenAsync(FileAccessMode.Read));
                Windows.Storage.Streams.DataReader mreader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0));
                byte[] dgram = new byte[file.Size];
                await mreader.LoadAsync((uint)dgram.Length);

                mreader.ReadBytes(dgram);
                file = await folder.GetFileAsync("DXInteropLib\\PixelShader.cso");

                stream = await file.OpenAsync(FileAccessMode.Read);

                mreader = new Windows.Storage.Streams.DataReader(stream.GetInputStreamAt(0));
                byte[] mgram = new byte[file.Size];
                await mreader.LoadAsync((uint)file.Size);

                mreader.ReadBytes(mgram);
                try
                {
                    defaultshader = mtext.CreateShader(dgram, mgram);
                    mtext.InitializeLayout(dgram);
                    defaultshader.Apply();
                    mtext.OnRenderFrame += onrenderframe;
                }
                catch (Exception er)
                {
                    Windows.UI.Popups.MessageDialog mdlg = new Windows.UI.Popups.MessageDialog(er.ToString(), "Fatal error");
                    mdlg.ShowAsync().Start();
                }
                IStorageFile[] files     = (await folder.GetFilesAsync()).ToArray();
                bool           founddata = false;
                foreach (IStorageFile et in files)
                {
                    if (et.FileName.Contains("rawimage.dat"))
                    {
                        stream = await et.OpenAsync(FileAccessMode.Read);

                        founddata = true;
                    }
                }
                int    width;
                int    height;
                byte[] rawdata;
                if (!founddata)
                {
                    file = await folder.GetFileAsync("TestProgram\\test.png");

                    stream = await file.OpenAsync(FileAccessMode.Read);

                    var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);

                    var pixeldata = await decoder.GetPixelDataAsync(Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, new Windows.Graphics.Imaging.BitmapTransform(), Windows.Graphics.Imaging.ExifOrientationMode.IgnoreExifOrientation, Windows.Graphics.Imaging.ColorManagementMode.DoNotColorManage);

                    width  = (int)decoder.PixelWidth;
                    height = (int)decoder.PixelHeight;

                    rawdata = pixeldata.DetachPixelData();
                    file    = await folder.CreateFileAsync("rawimage.dat");

                    stream = (await file.OpenAsync(FileAccessMode.ReadWrite));
                    var        realstream = stream.GetOutputStreamAt(0);
                    DataWriter mwriter    = new DataWriter(realstream);
                    mwriter.WriteInt32(width);
                    mwriter.WriteInt32(height);
                    mwriter.WriteBytes(rawdata);
                    await mwriter.StoreAsync();

                    await realstream.FlushAsync();
                }
                else
                {
                    DataReader treader = new DataReader(stream.GetInputStreamAt(0));
                    await treader.LoadAsync((uint)stream.Size);

                    rawdata = new byte[stream.Size - (sizeof(int) * 2)];
                    width   = treader.ReadInt32();
                    height  = treader.ReadInt32();
                    treader.ReadBytes(rawdata);
                }
                Texture2D mtex = maincontext.createTexture2D(rawdata, width, height);
                List <VertexPositionNormalTexture> triangle = new List <VertexPositionNormalTexture>();
                triangle.Add(new VertexPositionNormalTexture(new Vector3(-.5f, -.5f, 0), new Vector3(1, 1, 1), new Vector2(0, 0)));
                triangle.Add(new VertexPositionNormalTexture(new Vector3(0, 0.5f, 0), new Vector3(1, 1, 1), new Vector2(1, 0)));
                triangle.Add(new VertexPositionNormalTexture(new Vector3(.5f, -0.5f, 0), new Vector3(1, 1, 1), new Vector2(1, 1)));
                byte[] gpudata = VertexPositionNormalTexture.Serialize(triangle.ToArray());

                VertexBuffer mbuffer = maincontext.createVertexBuffer(gpudata, VertexPositionNormalTexture.Size);
                mbuffer.Apply(VertexPositionNormalTexture.Size);
                vertcount = 3;
                Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog("Unit tests successfully completed\nShader creation: Success\nTexture load: Success\nVertex buffer creation: Success\nTime:" + (DateTime.Now - started).ToString(), "Results");
                tdlg.ShowAsync().Start();
            }
            catch (Exception er)
            {
                Windows.UI.Popups.MessageDialog tdlg = new Windows.UI.Popups.MessageDialog(er.ToString(), "Fatal error");
                tdlg.ShowAsync().Start();
            }
        }
Exemplo n.º 54
0
        private async Task <string> ExecuteCommandLineString(string CommandString)
        {
            const string CommandLineProcesserExe         = "c:\\windows\\system32\\cmd.exe";
            const uint   CommandStringResponseBufferSize = 8192;
            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");
            }
        }