LoadAsync() public method

public LoadAsync ( uint count ) : DataReaderLoadOperation
count uint
return DataReaderLoadOperation
Example #1
2
		private async void StreamSkeleton()
		{
			try
			{
                var reader = new DataReader( Client.InputStream );
                reader.InputStreamOptions = InputStreamOptions.Partial;

                while ( IsConnected ) {
                    await reader.LoadAsync( 4 );
                    var size = reader.ReadUInt32();

                    await reader.LoadAsync( size );
                    byte[] bytes = new byte[size];
                    reader.ReadBytes( bytes );

                    MemoryStream ms = new MemoryStream( bytes );
					BinaryReader br = new BinaryReader(ms);

					SkeletonFrameData frame = br.ReadSkeletonFrame();

					SkeletonFrameReadyEventArgs args = new SkeletonFrameReadyEventArgs { SkeletonFrame = frame };
					SkeletonFrame = frame;

					Context.Send(delegate
					{
						if(SkeletonFrameReady != null)
							SkeletonFrameReady(this, args);
					}, null);
				}
			}
			catch(IOException)
			{
                Disconnect();
			}
		}
Example #2
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;
    }
        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 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());
 }
Example #5
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
            }
        }
Example #6
0
		private async void ColorThread()
		{
			try
			{
                var reader = new DataReader( Client.InputStream );
                reader.InputStreamOptions = InputStreamOptions.Partial;
                reader.ByteOrder = ByteOrder.LittleEndian;

                while ( IsConnected ) {
                    await reader.LoadAsync( 4 );
                    var size = reader.ReadUInt32();

                    await reader.LoadAsync( size );
                    byte[] bytes = new byte[size];
                    reader.ReadBytes( bytes );

                    MemoryStream ms = new MemoryStream( bytes );
					BinaryReader br = new BinaryReader(ms);

                    ColorFrameReadyEventArgs args = new ColorFrameReadyEventArgs();
                    ColorFrameData cfd = new ColorFrameData();

                    cfd.Format = (ImageFormat)br.ReadInt32();
					cfd.ImageFrame = br.ReadColorImageFrame();

                    MemoryStream msData = new MemoryStream( bytes, (int)ms.Position, (int)(ms.Length - ms.Position) );
                    if (cfd.Format == ImageFormat.Raw)
                    {
                        cfd.RawImage = ms.ToArray();
                    }
                    else
                    {
                        InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
                        DataWriter dw = new DataWriter(ras.GetOutputStreamAt(0));
                        dw.WriteBytes(msData.ToArray());
                        await dw.StoreAsync();   

                        // Set to the image
                        BitmapImage bImg = new BitmapImage();
                        bImg.SetSource(ras);
                        cfd.BitmapImage = bImg;
                    }

					ColorFrame = cfd;
					args.ColorFrame = cfd;

                    if (ColorFrameReady != null)
                    {
                        ColorFrameReady(this, args);
                    }
				}
			}
			catch(IOException)
			{
				Disconnect();
			}
		}
Example #7
0
        private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.WriteLine("Connection Received on Port {0}", sender.Information.LocalPort);
            StreamSocket streamSocket = args.Socket;
            if (streamSocket != null)
            {
                DataReader reader = new DataReader(streamSocket.InputStream);
                try
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Read the length of the 'packet'.
                    uint length = reader.ReadUInt32();
                    uint actualLength = await reader.LoadAsync(length);
                    if (length != actualLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    string name = reader.ReadString(actualLength);
                    Speaker speaker = new Speaker()
                    {
                        Name = name,
                        Address = streamSocket.Information.RemoteAddress.DisplayName,
                        Status = "Connected",
                        Socket = streamSocket
                    };

                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                    () =>
                    {
                        Speakers.Add(speaker);
                    });

                    reader.DetachStream();

                    Debug.WriteLine("New speaker added " + name);

                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error in connection received: " + e);
                }
            }
        }
Example #8
0
        private async void DepthThread()
        {
            try {
                short[] depthShort = null;

                var reader = new DataReader( Client.InputStream );
                reader.InputStreamOptions = InputStreamOptions.Partial;

                while ( IsConnected ) {
                    await reader.LoadAsync( 4 );
                    var size = reader.ReadUInt32();

                    await reader.LoadAsync( size );
                    byte[] bytes = new byte[size];
                    reader.ReadBytes( bytes );

                    MemoryStream ms = new MemoryStream( bytes );
                    BinaryReader br = new BinaryReader( ms );

                    DepthFrameData dfd = new DepthFrameData();
                    dfd.PlayerIndexBitmask = br.ReadInt32();
                    dfd.PlayerIndexBitmaskWidth = br.ReadInt32();

                    DepthImageFrame frame = br.ReadDepthImageFrame();
                    dfd.ImageFrame = frame;

                    int dataLength = (int)(ms.Length - ms.Position);

                    if ( depthShort == null || depthShort.Length != dataLength / 2 )
                        depthShort = new short[dataLength / 2];

                    Buffer.BlockCopy( bytes, (int)br.BaseStream.Position, depthShort, 0, dataLength );

                    dfd.DepthData = depthShort;

                    DepthFrame = dfd;

                    DepthFrameReadyEventArgs args = new DepthFrameReadyEventArgs();
                    args.DepthFrame = dfd;

                    Context.Send( delegate
                    {
                        if ( DepthFrameReady != null )
                            DepthFrameReady( this, args );
                    }, null );
                }
            }
            catch ( IOException ) {
                Disconnect();
            }
        }
Example #9
0
        public async Task WaitForData()
        {
            var mainPageViewModel = MainPageViewModel.GetInstance();

            using (var dr = new DataReader(ServerProxy.TcpSocket.InputStream))
            {
                while (mainPageViewModel.ConnectionStatus)
                {
                    var stringHeader = await dr.LoadAsync(4);

                    if (stringHeader == 0)
                    {
                        mainPageViewModel.ConnectionStatus = false;
                        return;
                    }

                    int messageLength = dr.ReadInt32();
                    uint numBytes = await dr.LoadAsync((uint)messageLength);

                    var packetBaseBuffer = new byte[numBytes];

                    dr.ReadBytes(packetBaseBuffer);

                    var packetBase = new PacketBase();

                    using (var stream = new MemoryStream(packetBaseBuffer))
                    {
                        try
                        {
                            var reader = new BinaryReader(stream);

                            packetBase.Read(reader);
                        }
                        catch (Exception e)
                        {
#if DEBUG
                            throw;
#endif
                        }
                    }


                    var incomingMessage = IncomingMessageFactory.GetMessage(
                        packetBase.Data as PacketV1);

                    incomingMessage.HandleMessage();
                }
            }
        }
Example #10
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;
        }
Example #11
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;
		}
Example #12
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("");
        }
Example #13
0
        public async void LoadSettings()
        {
            try
            {
                string contents;

                StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                StorageFile textFile = await localFolder.GetFileAsync("settingV2");

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

                string[] lines = contents.Split('\n');

                bool.TryParse(lines[0], out AutoJoinChat);
                bool.TryParse(lines[1], out LockLandscape);
                bool.TryParse(lines[2], out LiveTilesEnabled);
            }

            catch { }
        }
Example #14
0
        public static async Task<IRandomAccessStream> ConvertToRandomAccessStream(Stream source)
        {
            Stream streamToConvert = null;
            
            if (!source.CanRead)
                throw new Exception("The source cannot be read.");

            if (!source.CanSeek)
            {
                var memStream = new MemoryStream();
                await source.CopyToAsync(memStream);
                streamToConvert = memStream;
            }
            else
            {
                streamToConvert = source;
            }

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

            var randomAccessStream = new InMemoryRandomAccessStream();
            var outputStream = randomAccessStream.GetOutputStreamAt(0);
            await outputStream.WriteAsync(buffer);
            await outputStream.FlushAsync();

            return randomAccessStream;
        }
Example #15
0
        /// <summary>
        /// Read string content from file.
        /// </summary>
        /// <param name="path">Location of file, separate by //.</param>
        /// <param name="rootFolder"> </param>
        /// <returns>Content of file.</returns>
        public async Task<string> ReadFromFileAsync(string path, StorageFolder rootFolder = null)
        {
            if (path == null)
            {
                return null;
            }

            try
            {
                var file = await GetFileToReadAsync(path, rootFolder);

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

                var readStream = await file.OpenAsync(FileAccessMode.Read);

                var inputStream = readStream.GetInputStreamAt(0);
                var dataReader = new DataReader(inputStream);

                var numBytesLoaded = await dataReader.LoadAsync((uint)readStream.Size);
                var content = dataReader.ReadString(numBytesLoaded);
                dataReader.DetachStream();
                dataReader.Dispose();
                inputStream.Dispose();
                readStream.Dispose();

                return content;
            }
            catch
            {
                return null;
            }
        }
Example #16
0
        async private void OpenGraphFile_Click(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker();
            picker.FileTypeFilter.Add(".txt");
            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.SettingsIdentifier = "GraphPicker";
            picker.CommitButtonText = "Select Files";

            var selectedFile = await picker.PickSingleFileAsync();
            using (IRandomAccessStream stream = await selectedFile.OpenReadAsync())
            {
                using (DataReader reader = new DataReader(stream))
                {
                    uint length = (uint)stream.Size;
                    await reader.LoadAsync(length);
                    string[] s = reader.ReadString(length).Split('\r');
                    string[][] str = new string[s.Length][];
                    for (int i = 0; i < s.Length; i++)
                        str[i] = s[i].Replace('\n', ' ').Split(' ');
                    int n = int.Parse(s[0]);
                    int[,] adjMatrix = new int[n, n];
                    for (int i = 0; i < n; i++)
                        for (int j = 0; j < n; j++)
                            adjMatrix[i, j] = int.Parse(str[i + 1][j + 1]);
                    adjMatrix[0, 0] += 0;
                    graph = new Graph(adjMatrix, n);
                }
            }
        }
        /// <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;
        }
        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;
        }
Example #19
0
        async Task<bool> onewireReset(string deviceId)
        {
            try
            {
                if (serialPort != null)
                    serialPort.Dispose();

                serialPort = await SerialDevice.FromIdAsync(deviceId);

                // Configure serial settings
                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate = 9600;
                serialPort.Parity = SerialParity.None;
                serialPort.StopBits = SerialStopBitCount.One;
                serialPort.DataBits = 8;
                serialPort.Handshake = SerialHandshake.None;

                dataWriteObject = new DataWriter(serialPort.OutputStream);
                dataWriteObject.WriteByte(0xF0);
                await dataWriteObject.StoreAsync();

                dataReaderObject = new DataReader(serialPort.InputStream);
                await dataReaderObject.LoadAsync(1);
                byte resp = dataReaderObject.ReadByte();
                if (resp == 0xFF)
                {
                    System.Diagnostics.Debug.WriteLine("Nothing connected to UART");
                    return false;
                }
                else if (resp == 0xF0)
                {
                    System.Diagnostics.Debug.WriteLine("No 1-wire devices are present");
                    return false;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Response: " + resp);
                    serialPort.Dispose();
                    serialPort = await SerialDevice.FromIdAsync(deviceId);

                    // Configure serial settings
                    serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                    serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                    serialPort.BaudRate = 115200;
                    serialPort.Parity = SerialParity.None;
                    serialPort.StopBits = SerialStopBitCount.One;
                    serialPort.DataBits = 8;
                    serialPort.Handshake = SerialHandshake.None;
                    dataWriteObject = new DataWriter(serialPort.OutputStream);
                    dataReaderObject = new DataReader(serialPort.InputStream);
                    return true;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
                return false;
            }
        }
        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();
            }
        }
        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;
        }
 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);
             };
         };
     };
 }
Example #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;
            }

        }
        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();
            }
        }
 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();
     }
 }
Example #26
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);
            }
        }
Example #27
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<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;
        }
Example #29
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;
                        }
                    }
                }
            }
        }
 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();
     }
 }
 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;
 }
Example #32
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);
 }
        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();
            }
        }
Example #34
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;
            }
        }
Example #35
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);
        }
        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);
        }
Example #37
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);
        }
Example #38
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));
                }
            }
        }
Example #39
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;
            }
        }
Example #40
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);
        }
Example #41
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);
        }
Example #42
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);
        }
Example #45
0
File: Print3D.cs Project: 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);
    }
Example #46
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);
            }
        }
        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();
            }
        }
Example #48
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");
            }
        }