private async void Button_Savelocal_Click(object sender, RoutedEventArgs e)
        {
            FileSavePicker savePicker = new FileSavePicker();

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

            StorageFile file = await savePicker.PickSaveFileAsync();

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

                IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);

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

                sessionOutputStream.Dispose();
            }
        }
Esempio n. 2
0
        public async Task BlobOpenWriteTestAsync()
        {
            byte[]             buffer    = GetRandomBuffer(2 * 1024);
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob        = container.GetPageBlobReference("blob1");
                MemoryStream  memStream   = new MemoryStream(buffer);
                IOutputStream iBlobStream = await blob.OpenWriteAsync(2048);

                using (Stream blobStream = iBlobStream.AsStreamForWrite())
                {
                    await blobStream.WriteAsync(buffer, 0, 2048);

                    byte[]       testBuffer = new byte[2048];
                    MemoryStream dstStream  = new MemoryStream(testBuffer);
                    await blob.DownloadRangeToStreamAsync(dstStream.AsOutputStream(), null, null);

                    await iBlobStream.FlushAsync();

                    TestHelper.AssertStreamsAreEqual(memStream, dstStream);
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
        private async Task WriteThumbnailAsync(IOutputStream os)
        {
            Debug.WriteLine("Trying to send thumbnail stream");
            Stream resp = os.AsStreamForWrite();

            statusMutex.WaitOne();
            var thumbnailRef = playbackStatus.thumbnail;

            statusMutex.ReleaseMutex();
            if (thumbnailRef == null)
            {
                await WriteEmptyResponseAsync(os, 503, "Service Unavailable"); return;
            }
            try
            {
                var fs = await thumbnailRef.OpenReadAsync();

                string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                              "Content-Length: {0}\r\n" +
                                              "Content-Type: image/jpeg\r\n" +
                                              "Connection: close\r\n\r\n",
                                              fs.Size);
                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                await resp.WriteAsync(headerArray, 0, headerArray.Length);

                await fs.AsStream().CopyToAsync(resp);

                await resp.FlushAsync();
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                await WriteEmptyResponseAsync(os, 503, "Service Unavailable"); return;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Write response error.
        /// </summary>
        /// <param name="os">The current output stream.</param>
        /// <returns>The async task.</returns>
        private async Task WriteResponseErrorAsync(IOutputStream os)
        {
            // Get the output stream.
            using (Stream resp = os.AsStreamForWrite())
            {
                // Set the body of the response.
                byte[]       bodyArray = Encoding.UTF8.GetBytes("");
                MemoryStream stream    = new MemoryStream(bodyArray);

                // Set the headers.
                string header = String.Format(
                    "HTTP/1.1 500 Internal Server Error\r\n" +
                    "Content-Length: {0}\r\n" +
                    "Connection: close\r\n\r\n",
                    stream.Length);

                // Write the headers.
                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                await resp.WriteAsync(headerArray, 0, headerArray.Length);

                // Write the body to the output stream.
                await stream.CopyToAsync(resp);

                await resp.FlushAsync();
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Async helper to write file to stream
        /// </summary>
        /// <param name="file"></param>
        /// <param name="os"></param>
        /// <returns></returns>
        private static async Task WriteFileToStreamHelper(StorageFile file, IOutputStream os)
        {
            using (Stream resp = os.AsStreamForWrite())
            {
                try
                {
                    using (Stream fs = await file.OpenStreamForReadAsync())
                    {
                        string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                                      "Content-Length: {0}\r\n" +
                                                      "Connection: close\r\n\r\n",
                                                      fs.Length);
                        byte[] headerArray = Encoding.UTF8.GetBytes(header);
                        await resp.WriteAsync(headerArray, 0, headerArray.Length);

                        await fs.CopyToAsync(resp);
                    }
                }
                catch (FileNotFoundException ex)
                {
                    byte[] headerArray = Encoding.UTF8.GetBytes(
                        "HTTP/1.1 404 Not Found\r\n" +
                        "Content-Length:0\r\n" +
                        "Connection: close\r\n\r\n");
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);
                }
                await resp.FlushAsync();
            }
        }
Esempio n. 6
0
        private async Task WriteResponseAsync(string request, IOutputStream os)
        {
            using (Stream resp = os.AsStreamForWrite())
            {
                using (Stream sourceStream = await File.OpenStreamForWriteAsync())
                {
                    string mime;
                    string header = string.Format("HTTP/1.1 200 OK\r\n" +
                                                  $"Date: {DateTime.Now.ToString("R")}\r\n" +
                                                  "Server: MeoGoEmbedded/1.0\r\n" +
                                                  "Content-Length: {0}\r\n" +
                                                  "Content-Type: {1}\r\n" +
                                                  "Connection: close\r\n\r\n",
                                                  sourceStream.Length,
                                                  _mimeTypeMappings.TryGetValue(File.FileType, out mime) ? mime : "application/octet-stream");
                    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);

                    var b     = new byte[1 << 16]; // 64k
                    int count = 0;
                    while ((count = sourceStream.Read(b, 0, b.Length)) > 0)
                    {
                        await resp.WriteAsync(b, 0, count);
                    }
                    await resp.FlushAsync();
                };
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Send a HTTP response.
        /// </summary>
        /// <param name="outputStream">output stream</param>
        /// <param name="httpStatusCode">HTTP status code</param>
        /// <param name="httpStatusText">HTTP status text</param>
        /// <param name="content">response content body</param>
        /// <param name="mimeType">mime type</param>
        /// <param name="cache">whether the response should be cached</param>
        private async void SendResponse(IOutputStream outputStream, int httpStatusCode, string httpStatusText, byte[] content, string mimeType, bool cache)
        {
            // Send a response back
            using (IOutputStream output = outputStream)
            {
                using (Stream response = output.AsStreamForWrite())
                {
                    var bodyStream = new MemoryStream(content);

                    var cacheControl = cache ? "Cache-Control: public, max-age=315360000\r\n" : "Cache-Control: no-cache, no-store, must-revalidate\r\n";

                    // This is a standard HTTP header so the client browser knows the bytes returned are a valid http response
                    var header = $"HTTP/1.1 {httpStatusCode} {httpStatusText}\r\n" +
                                 "Server:Raspberry Pi 3\r\n" +
                                 $"Content-Length: {bodyStream.Length}\r\n" +
                                 $"Content-Type: {mimeType}\r\n" +
                                 cacheControl +
                                 "Connection: close\r\n\r\n";

                    byte[] headerArray = Encoding.UTF8.GetBytes(header);

                    // send the header with the body inclded to the client
                    await response.WriteAsync(headerArray, 0, headerArray.Length);

                    await bodyStream.CopyToAsync(response);

                    await response.FlushAsync();
                }
            }
        }
Esempio n. 8
0
        public async Task <bool> SaveEpisodeList()
        {
            var filename = "Episodes.json";

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

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

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

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

                    await outStream.FlushAsync();

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

                    Debug.WriteLine("Episodelist saved");
                    return(true);
                }
            }
            catch (Exception) { Debug.WriteLine("episodelist failed to save"); return(false); }
        }
Esempio n. 9
0
        private async Task WriteResponseAsync(string[] requestTokens, IOutputStream outstream)
        {
            // NOTE: If you change the respBody format, change the Content-Type (below) accordingly
            //string respBody = weatherData.HTML;
            //string respBody = weatherData.XML;
            string respBody = weatherData.JSON;

            string htmlCode = "200 OK";

            using (Stream resp = outstream.AsStreamForWrite())
            {
                byte[] bodyArray = Encoding.UTF8.GetBytes(respBody);
                MemoryStream stream = new MemoryStream(bodyArray);

                // NOTE: If you change the respBody format (above), change the Content-Type accordingly
                string header = string.Format("HTTP/1.1 {0}\r\n" +
                                              //"Content-Type: text/html\r\n" + // HTML only
                                              //"Content-Type: text/xml\r\n" +  // XML only
                                              "Content-Type: text/json\r\n" + // JSON only
                                              "Content-Length: {1}\r\n" +
                                              "Connection: close\r\n\r\n",
                                              htmlCode, stream.Length);

                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                await resp.WriteAsync(headerArray, 0, headerArray.Length);
                await stream.CopyToAsync(resp);
                await resp.FlushAsync();
            }
        }
Esempio n. 10
0
        private async Task WriteResponseAsync(string v, IOutputStream output)
        {
            string sendPage = ParseInput(v);

            using (Stream response = output.AsStreamForWrite())
            {
                // For now we are just going to reply to anything with Hello World!
                byte[] bodyArray = Encoding.UTF8.GetBytes(sendPage);

                var bodyStream = new MemoryStream(bodyArray);

                // This is a standard HTTP header so the client browser knows the bytes returned are a valid http response
                var header = "HTTP/1.1 200 OK\r\n" +
                             $"Content-Length: {bodyStream.Length}\r\n" +
                             "Connection: close\r\n\r\n";

                byte[] headerArray = Encoding.UTF8.GetBytes(header);

                // send the header with the body inclded to the client
                await response.WriteAsync(headerArray, 0, headerArray.Length);

                await bodyStream.CopyToAsync(response);

                await response.FlushAsync();
            }
        }
Esempio n. 11
0
        public async Task BlobReadWhenOpenWriteAsync()
        {
            byte[]             buffer    = GetRandomBuffer(2 * 1024);
            bool               thrown    = false;
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob         = container.GetPageBlobReference("blob1");
                MemoryStream  memoryStream = new MemoryStream(buffer);
                using (IOutputStream blobStream = await blob.OpenWriteAsync(2048))
                {
                    Stream blobStreamForWrite = blobStream.AsStreamForWrite();
                    await blobStreamForWrite.WriteAsync(buffer, 0, 2048);

                    byte[] testBuffer = new byte[2048];
                    try
                    {
                        await blobStreamForWrite.ReadAsync(testBuffer, 0, 2048);
                    }
                    catch (NotSupportedException)
                    {
                        thrown = true;
                    }

                    Assert.IsTrue(thrown);
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Esempio n. 12
0
        public async Task BlobOpenReadWriteTestAsync()
        {
            byte[]             buffer    = GetRandomBuffer(2 * 1024);
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                await container.CreateAsync();

                CloudPageBlob blob        = container.GetPageBlobReference("blob1");
                IOutputStream iBlobStream = await blob.OpenWriteAsync(2048);

                MemoryStream memoryStream = new MemoryStream(buffer);
                using (Stream blobStream = iBlobStream.AsStreamForWrite())
                {
                    await blobStream.WriteAsync(buffer, 0, 2048);

                    await blobStream.AsOutputStream().FlushAsync();
                }
                IInputStream iDstStream = await blob.OpenReadAsync();

                using (Stream dstStream = iDstStream.AsStreamForRead())
                {
                    dstStream.Seek(dstStream.Length, 0);
                    memoryStream.Seek(memoryStream.Length, 0);
                    TestHelper.AssertStreamsAreEqual(memoryStream, dstStream);
                }
            }
            finally
            {
                container.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Esempio n. 13
0
        /// <summary>
        /// wites the webservers response to the outputstream
        /// </summary>
        /// <param name="message">teh MEssage to return to the client</param>
        /// <param name="os">Inputstream</param>
        /// <returns></returns>
        private async Task WriteResponseAsync(HttpResponseMessage message, IOutputStream os)
        {
            try
            {
                using (Stream resp = os.AsStreamForWrite())
                {
                    byte[] bodyArray = await message.Content.ReadAsByteArrayAsync();

                    MemoryStream stream = new MemoryStream(bodyArray);
                    message.Content.Headers.ContentLength = stream.Length;
                    string header = string.Format("HTTP/" + message.Version + " " + (int)message.StatusCode + " " + message.StatusCode + Environment.NewLine
                                                  + "Content-Type: " + message.Content.Headers.ContentType + Environment.NewLine
                                                  + "Content-Length: " + message.Content.Headers.ContentLength + Environment.NewLine
                                                  + "Connection: close\r\n\r\n");
                    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);

                    await stream.CopyToAsync(resp);

                    await resp.FlushAsync();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error in WriteResponseAsync: " + ex);
            }
        }
Esempio n. 14
0
        //Write the response for HTTP GET's and POST's
        private async Task WriteResponseAsync(string RequestMsg, string ResponseMsg, bool urlFound, byte[] bodyArray, IOutputStream os)
        {
            try  //The appService will die after a day or so. Let 's try catch it seperatly so the server will still return
            {
                var updateMessage = new ValueSet();
                updateMessage.Add("Request", RequestMsg);
                updateMessage.Add("Response", ResponseMsg);
                var responseStatus = await appServiceConnection.SendMessageAsync(updateMessage);
            }
            catch (Exception) { }

            try
            {
                MemoryStream bodyStream = new MemoryStream(bodyArray);
                using (Stream response = os.AsStreamForWrite())
                {
                    string header      = GetHeader(urlFound, bodyStream.Length.ToString());
                    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    await response.WriteAsync(headerArray, 0, headerArray.Length);

                    if (urlFound)
                    {
                        await bodyStream.CopyToAsync(response);
                    }
                    await response.FlushAsync();
                }
            }
            catch (Exception) { }
        }
Esempio n. 15
0
        /// <summary>
        /// Writes page content back to socket
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="html"></param>
        /// <param name="lastModifiedUtc"></param>
        /// <param name="contentType"></param>
        /// <param name="keepAlive"></param>
        /// <param name="canBeCached"></param>
        /// <returns></returns>
        private async Task WritePageContent(StreamSocket socket, string html, DateTime?lastModifiedUtc, string contentType, bool keepAlive, bool canBeCached)
        {
            // respond with the html:
            IOutputStream output = socket.OutputStream;

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

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

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

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

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

            if (!keepAlive)
            {
                output.Dispose();
            }
        }
Esempio n. 16
0
        public async Task FileReadWhenOpenWriteAsync()
        {
            byte[]         buffer = GetRandomBuffer(2 * 1024);
            bool           thrown = false;
            CloudFileShare share  = GetRandomShareReference();

            try
            {
                await share.CreateAsync();

                CloudFile    file         = share.GetRootDirectoryReference().GetFileReference("file1");
                MemoryStream memoryStream = new MemoryStream(buffer);
                using (IOutputStream fileStream = await file.OpenWriteAsync(2048))
                {
                    Stream fileStreamForWrite = fileStream.AsStreamForWrite();
                    await fileStreamForWrite.WriteAsync(buffer, 0, 2048);

                    byte[] testBuffer = new byte[2048];
                    try
                    {
                        await fileStreamForWrite.ReadAsync(testBuffer, 0, 2048);
                    }
                    catch (NotSupportedException)
                    {
                        thrown = true;
                    }

                    Assert.IsTrue(thrown);
                }
            }
            finally
            {
                share.DeleteIfExistsAsync().AsTask().Wait();
            }
        }
Esempio n. 17
0
        public static async Task <bool> writeObjektAsync <T>(string file, T objekt)
        {
            try
            {
                StorageFile userdetailsfile = await
                                              ApplicationData.Current.LocalFolder.CreateFileAsync(file, CreationCollisionOption.ReplaceExisting);

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

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

                    rndStream.Dispose();
                    outStream.Dispose();
                }
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Esempio n. 18
0
        private async Task WriteResponseAsync(string[] requestTokens, IOutputStream outstream)
        {
            // NOTE: If you change the respBody format, change the Content-Type (below) accordingly
            //string respBody = weatherData.HTML;
            //string respBody = weatherData.XML;
            string respBody = weatherData.JSON;

            string htmlCode = "200 OK";

            using (Stream resp = outstream.AsStreamForWrite())
            {
                byte[]       bodyArray = Encoding.UTF8.GetBytes(respBody);
                MemoryStream stream    = new MemoryStream(bodyArray);

                // NOTE: If you change the respBody format (above), change the Content-Type accordingly
                string header = string.Format("HTTP/1.1 {0}\r\n" +
                                                                              //"Content-Type: text/html\r\n" + // HTML only
                                                                              //"Content-Type: text/xml\r\n" +  // XML only
                                              "Content-Type: text/json\r\n" + // JSON only
                                              "Content-Length: {1}\r\n" +
                                              "Connection: close\r\n\r\n",
                                              htmlCode, stream.Length);

                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                await resp.WriteAsync(headerArray, 0, headerArray.Length);

                await stream.CopyToAsync(resp);

                await resp.FlushAsync();
            }
        }
Esempio n. 19
0
        private static void WriteResponse(HttpContentType?mimeType,
                                          byte[] content,
                                          HttpStatusCode httpStatusCode,
                                          IOutputStream outputStream)
        {
            var stream = outputStream.AsStreamForWrite();

            var responseHeader = new StringBuilder();

            responseHeader.Append($"{HttpStatusCodeHelper.GetHttpStatusCodeForHttpHeader(httpStatusCode)}\r\n");
            responseHeader.Append($"Access-Control-Allow-Origin: {ALLOW_ORIGIN_DOMAIN}\r\n");
            //responseHeader.Append("Cache-Control: no-store\r\n");

            if (httpStatusCode != HttpStatusCode.HttpCode204)
            {
                responseHeader.Append($"Content-Type: {MimeTypeHelper.GetHttpContentType(mimeType.Value)}\r\n");
                responseHeader.Append($"Content-Length: {content.Length}\r\n");
            }

            responseHeader.Append("Connection: Close\r\n\r\n");

            var responsHeaderBytes = Encoding.UTF8.GetBytes(responseHeader.ToString());

            stream.Write(responsHeaderBytes, 0, responsHeaderBytes.Length);

            if (content != null)
            {
                stream.Write(content, 0, content.Length);
            }

            stream.Flush();
            stream.Dispose();
        }
Esempio n. 20
0
        /// <summary>
        /// 把实体类对象序列化成XML格式存储到文件里面
        /// </summary>
        /// <typeparam name="T">实体类类型</typeparam>
        /// <param name="data">实体类对象</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static async Task WriteAsync <T>(T data, string filename)
        {
            try
            {
                // 获取存储数据的文件夹
                IStorageFolder applicationFolder = await GetDataFolder();

                StorageFile file = await applicationFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);

                // 获取文件的数据流来进行操作
                using (IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
                    {
                        // 创建序列化对象写入数据
                        DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                        serializer.WriteObject(outStream.AsStreamForWrite(), data);
                        await outStream.FlushAsync();
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("StorageFileHelper: " + e.Message);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// 序列化到文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static async Task <bool> WriteAsync <T>(T data, string fileName)
        {
            bool result = false;

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

                using (IRandomAccessStream rastream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                {
                    using (IOutputStream outStream = rastream.GetOutputStreamAt(0))
                    {
                        DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                        serializer.WriteObject(outStream.AsStreamForWrite(), data);
                        await outStream.FlushAsync();

                        result = true;
                    }
                }
            }
            catch (Exception)
            {
                result = false;
            }
            return(result);
        }
Esempio n. 22
0
        public async Task ExportCurrentPath()
        {
            // Code to call file picker
            FileSavePicker savePicker = new FileSavePicker();

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

            StorageFile file = await savePicker.PickSaveFileAsync();

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

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

                sessionOutputStream.Dispose();
            }
        }
Esempio n. 23
0
        internal async void SaveProfile()
        {
            FileSavePicker savePicker = new FileSavePicker();

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

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

            StorageFile file = await savePicker.PickSaveFileAsync();

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

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

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

                sessionOutputStream.Dispose();
            }
        }
Esempio n. 24
0
        public async Task Send(IOutputStream output)
        {
            using (Stream responseStream = output.AsStreamForWrite())
            {
                byte[] contentData;

                if (this.StatusCode != HttpStatusCode.NoContent)
                {
                    contentData = await Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                }
                else
                {
                    contentData = Array.Empty <byte>();
                }

                // This is a standard HTTP header so the client browser knows the bytes returned are a valid http response
                var header = $"HTTP/{Version} {(int)StatusCode} {ReasonPhrase}\r\n" +
                             $"Content-Length: {contentData.Length}\r\n" +
                             "Connection: close\r\n\r\n";

                // send the header with the body inclded to the client
                byte[] headerData = Encoding.UTF8.GetBytes(header);
                await responseStream.WriteAsync(headerData, 0, headerData.Length).ConfigureAwait(false);

                if (contentData.Length > 0)
                {
                    using (Stream contentStream = new MemoryStream(contentData))
                    {
                        await contentStream.CopyToAsync(responseStream).ConfigureAwait(false);
                    }
                }

                await responseStream.FlushAsync().ConfigureAwait(false);
            }
        }
        public virtual async Task <bool> WriteDataAsync(IList <T> data)
        {
            try
            {
                StorageFolder store = await ApplicationData.Current.LocalFolder.GetFolderAsync(Constants.DataFilesFolder);

                StorageFile sessionFile = await store.CreateFileAsync(SourcePath, CreationCollisionOption.ReplaceExisting);

                using (IRandomAccessStream sessionRandomAccess = await sessionFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0))
                    {
                        var sessionSerializer = new DataContractSerializer(typeof(T[]), new Type[] { typeof(T[]) });
                        sessionSerializer.WriteObject(sessionOutputStream.AsStreamForWrite(), data.ToArray());
                        await sessionOutputStream.FlushAsync();
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Esempio n. 26
0
        /*************************
        * OutputWebPages checks whether the data coming in is "Request=Feedback" if it is then
        * only the feedback variable is sent back prefixed with "Result: ". Thus the jquery
        * in HTML webpage can look for this keyword at the begining of the text to take any
        * action.
        * If Feedback info is not requested, a webpage is constructed and sent. Note that the
        * Header and body tags are added to the webpage while the contents are read from
        * respective files. A line for providing the log is added at the end with an ID of retVal for
        * calling theme benefit. The log line provides decoded input passed by webpage
        * ***********************/
        private async void OutputWebPage(StreamSocketListenerConnectionReceivedEventArgs args, string inputString)
        {
            bAction = inputString.Contains("Action");

            //Use the next two lines for event logging
            //lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
            //lc.LogMessage(inputString.ToString());

            string data = string.IsNullOrWhiteSpace(feedBack) ? "None" : feedBack;

            try
            {
                using (IOutputStream output = args.Socket.OutputStream)
                {
                    using (Stream response = output.AsStreamForWrite())
                    {
                        if (bAction)
                        {
                            //data = "Results: " + feedBack;
                            //data = DateTime.Now.TimeOfDay.ToString();
                            byte[] fbArray = Encoding.UTF8.GetBytes(data);
                            await response.WriteAsync(fbArray, 0, fbArray.Length);

                            await response.FlushAsync();

                            //Use the next two lines for event logging
                            //lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
                            //lc.LogMessage(feedBack);
                        }
                        else
                        {
                            byte[] bodyArray = Encoding.UTF8.GetBytes(
                                $"<!DOCTYPE html>\n<html>\n<head>{headerFile}<style>{cssFile}</style>\n</head>\n<body>{bodyFile}<p>Feedback Received: <span id=\"retVal\">{data}</span></p>\n</body>\n</html>");

                            var bodyStream = new MemoryStream(bodyArray);

                            var header = "HTTP/1.1 200 OK\r\n" +
                                         $"Content-Length: {bodyStream.Length}\r\n" +
                                         "Connection: close\r\n\r\n";

                            byte[] headerArray = Encoding.UTF8.GetBytes(header);
                            await response.WriteAsync(headerArray, 0, headerArray.Length);

                            await bodyStream.CopyToAsync(response);

                            await response.FlushAsync();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception Occured: {0}", ex);
                //Uncomment next two lines for logging the exception errors
                lc = new LoggingChannel("my provider", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
                lc.LogMessage("Exception at Output Page: " + ex);
                bMsg = false;
            }
        }
Esempio n. 27
0
    async void OnApplicationPause(bool pauseStatus)
    {
        if (pauseStatus)
        {
            Debug.Log("in background");
            // action on going background
            try
            {
                Stream outputStream = outStream.AsStreamForWrite();

                var streamWriter = new StreamWriter(outputStream, System.Text.Encoding.UTF8, 1024, true);

                await streamWriter.WriteLineAsync("bcgrd");

                await streamWriter.FlushAsync();

                Debug.Log("notifcation sent from Hololens");
            }
            catch (System.Exception e)
            {
                Debug.Log(e.ToString());
            }
        }
        else
        {
            // action on coming from background
            try
            {
                #if WINDOWS_UWP
                Stream outputStream = outStream.AsStreamForWrite();

                var streamWriter = new StreamWriter(outputStream, System.Text.Encoding.UTF8, 1024, true);

                await streamWriter.WriteLineAsync("back");

                await streamWriter.FlushAsync();

                Debug.Log("notifcation sent from Hololens");
                #endif
            }
            catch (System.Exception e)
            {
                Debug.Log(e.ToString());
            }
        }
    }
        public async Task Start(FarmController theFarmController)
        {
            webFarmController = theFarmController;
            var listener = new StreamSocketListener();

            await listener.BindServiceNameAsync("80");

            listener.ConnectionReceived += async(sender, args) =>
            {
                StringBuilder request = new StringBuilder();

                using (IInputStream input = args.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;
                    }
                }

                string query = GetQuery(request);
                Parse(query);
                PerformActions();

                //now respond to the request and display the current status
                string myhtml = BuildMyHTMLResponse(query);

                using (IOutputStream output = args.Socket.OutputStream)
                {
                    using (Stream response = output.AsStreamForWrite())
                    {
                        //byte[] html = Encoding.GetEncoding("iso-8859-1").GetBytes(myhtml);
                        byte[]       html       = Encoding.UTF8.GetBytes(myhtml);
                        MemoryStream bodyStream = new MemoryStream(html);

                        string header = "HTTP/1.1 200 OK\r\n" +
                                        $"Content-Length: {bodyStream.Length}\r\n" +
                                        "Connection: close\r\n\r\n";                                //var headerArray = Encoding.UTF8.GetBytes(header);
                        //byte[] headerArray = Encoding.GetEncoding("iso-8859-1").GetBytes(header);
                        byte[] headerArray = Encoding.UTF8.GetBytes(header);
                        await response.WriteAsync(headerArray,
                                                  0, headerArray.Length);

                        await bodyStream.CopyToAsync(response);

                        await response.FlushAsync();
                    }
                }
            };
        }
        public async Task BlockBlobWriteStreamBasicTestAsync()
        {
            byte[] buffer = GetRandomBuffer(3 * 1024 * 1024);

            CryptographicHash hasher     = HashAlgorithmProvider.OpenAlgorithm("MD5").CreateHash();
            CloudBlobClient   blobClient = GenerateCloudBlobClient();

            blobClient.DefaultRequestOptions.ParallelOperationThreadCount = 2;
            string             name      = GetRandomContainerName();
            CloudBlobContainer container = blobClient.GetContainerReference(name);

            try
            {
                await container.CreateAsync();

                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");
                using (MemoryStream wholeBlob = new MemoryStream())
                {
                    BlobRequestOptions options = new BlobRequestOptions()
                    {
                        StoreBlobContentMD5 = true,
                    };
                    using (IOutputStream writeStream = await blob.OpenWriteAsync(null, options, null))
                    {
                        Stream blobStream = writeStream.AsStreamForWrite();

                        for (int i = 0; i < 3; i++)
                        {
                            await blobStream.WriteAsync(buffer, 0, buffer.Length);

                            await wholeBlob.WriteAsync(buffer, 0, buffer.Length);

                            Assert.AreEqual(wholeBlob.Position, blobStream.Position);
                            hasher.Append(buffer.AsBuffer());
                        }

                        await blobStream.FlushAsync();
                    }

                    string md5 = CryptographicBuffer.EncodeToBase64String(hasher.GetValueAndReset());
                    await blob.FetchAttributesAsync();

                    Assert.AreEqual(md5, blob.Properties.ContentMD5);

                    using (MemoryOutputStream downloadedBlob = new MemoryOutputStream())
                    {
                        await blob.DownloadToStreamAsync(downloadedBlob);

                        TestHelper.AssertStreamsAreEqual(wholeBlob, downloadedBlob.UnderlyingStream);
                    }
                }
            }
            finally
            {
                container.DeleteAsync().AsTask().Wait();
            }
        }
Esempio n. 30
0
        private async Task WriteResponseAsync(string request, IOutputStream os)
        {
            // See if the request is for blinky.html, if yes get the new state
            string state        = "Unspecified";
            bool   stateChanged = false;

            if (request.Contains("blinky.html?relay1=on"))
            {
                state        = "On1";
                stateChanged = true;
            }
            else if (request.Contains("blinky.html?relay1=off"))
            {
                state        = "Off1";
                stateChanged = true;
            }

            if (request.Contains("blinky.html?relay2=on"))
            {
                state        = "On2";
                stateChanged = true;
            }
            else if (request.Contains("blinky.html?relay2=off"))
            {
                state        = "Off2";
                stateChanged = true;
            }

            if (stateChanged)
            {
                var updateMessage = new ValueSet();
                updateMessage.Add("State", state);
                var responseStatus = await appServiceConnection.SendMessageAsync(updateMessage);
            }



            string html = HtmlString;//state == "On" ? onHtmlString : offHtmlString;

            // Show the html
            using (Stream resp = os.AsStreamForWrite())
            {
                // Look in the Data subdirectory of the app package
                byte[]       bodyArray = Encoding.UTF8.GetBytes(html);
                MemoryStream stream    = new MemoryStream(bodyArray);
                string       header    = String.Format("HTTP/1.1 200 OK\r\n" +
                                                       "Content-Length: {0}\r\n" +
                                                       "Connection: close\r\n\r\n",
                                                       stream.Length);
                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                await resp.WriteAsync(headerArray, 0, headerArray.Length);

                await stream.CopyToAsync(resp);

                await resp.FlushAsync();
            }
        }
Esempio n. 31
0
        public async void HandleRequest(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            StringBuilder request      = new StringBuilder();
            string        responseHTML = "<html><body>ERROR</body></html>";

            // Handle a incoming request
            // First read the request
            using (IInputStream input = args.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;
                }
            }

            responseHTML = PrepareResponse(ParseRequest(request.ToString()));

            // Send a response back
            using (IOutputStream output = args.Socket.OutputStream)
            {
                using (Stream response = output.AsStreamForWrite())
                {
                    byte[] bodyArray = Encoding.UTF8.GetBytes(responseHTML);

                    var bodyStream = new MemoryStream(bodyArray);

                    var header = String.Empty;

                    header = "HTTP/1.1 200 OK\r\n" +
                             $"Content-Length: {bodyStream.Length}\r\n" +
                             "Connection: close\r\n\r\n";

                    if (request.ToString().Contains("csv"))
                    {
                        header = "HTTP/1.1 200 OK\r\n" +
                                 $"Content-Length: {bodyStream.Length}\r\n" +
                                 $"Content-Type: application/csv" +
                                 "Connection: close\r\n\r\n";
                    }

                    byte[] headerArray = Encoding.UTF8.GetBytes(header);

                    await response.WriteAsync(headerArray, 0, headerArray.Length);

                    await bodyStream.CopyToAsync(response);

                    await response.FlushAsync();
                }
            }
        }
Esempio n. 32
0
 private async Task WriteResponseAsync(IRestResponse response, IOutputStream os)
 {
     using (Stream resp = os.AsStreamForWrite())
     {
         // Look in the Data subdirectory of the app package
         byte[] bodyArray = Encoding.UTF8.GetBytes(response.Data);
         MemoryStream stream = new MemoryStream(bodyArray);
         string header = string.Format("HTTP/1.1 {0} {1}\r\n" +
                           "Content-Length: {2}\r\n" +
                           "Content-Type: application/json\r\n" +
                           "Connection: close\r\n\r\n",
                           response.StatusCode,
                           HttpHelpers.GetHttpStatusCodeText(response.StatusCode),
                           stream.Length);
         byte[] headerArray = Encoding.UTF8.GetBytes(header);
         await resp.WriteAsync(headerArray, 0, headerArray.Length);
         await stream.CopyToAsync(resp);
         await resp.FlushAsync();
     }
 }
Esempio n. 33
0
        async Task WriteResponseAsync(string request, IOutputStream os)
        {
            

            var RtnString = "Unable to processRequest";
            if (!request.StartsWith("error -", StringComparison.CurrentCulture))
            {
                var apiString = "/api/";
                if (request.ToLower().Contains(apiString))
                {
                    request = request.Substring(request.IndexOf(apiString, StringComparison.CurrentCulture) + apiString.Length);
                    RtnString = ApiProccessor(request);
                }
                else
                {
                    try
                    {
                        var file = await MapPath(request);
                        RtnString = await ReadFile(file);
                    }
                    catch (Exception ex)
                    {
                        var header = "<!DOCTYPE html><html><body>";
                        var footer = "</body></html>";

                        RtnString = header + "Path: " + request + "<br />" + "Error: " + ex.Message + "<br />" + "Stacktrace: " + ex.StackTrace.Replace("\r\n", "<br/>") + footer;
                    }
                }
            }
            else
            {
                RtnString = request;
            }
            // Show the html 
            using (Stream resp = os.AsStreamForWrite())
            {
                // Look in the Data subdirectory of the app package
                byte[] bodyArray = Encoding.UTF8.GetBytes(RtnString);
                var stream = new MemoryStream(bodyArray);
                string header = string.Format("HTTP/1.1 200 OK\r\n" +                                    
                                  "Content-Length: {0}\r\n" +
                                  AllowOriginsHeader +
                                  "Connection: close\r\n\r\n",
                                  stream.Length);
                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                await resp.WriteAsync(headerArray, 0, headerArray.Length);
                await stream.CopyToAsync(resp);
                await resp.FlushAsync();
            }

        }
        private async Task WriteResponseAsync(string request, IOutputStream os)
        {
            // See if the request is for text.html, if yes get the new state
            string message = "Unspecified";
            string repeat = "0"; // we'll convert this to an int in the client side
            bool stateChanged = false;
            if (request.Contains("text.html?message="))
            {

                // sadly we don't have HttpUtility class
                // this is so wrong
                var stringUrl = "http://localhost" + request; // I have to spoof the url
             
                var parameters = UriExtensions.ParseQueryString(new Uri(stringUrl));
                message = parameters["message"];
                message = Uri.UnescapeDataString(message);
                message = message.Replace("+", " ");

                repeat = parameters["repeat"];
                stateChanged = true;
            }

            if (stateChanged)
            {
                var updateMessage = new ValueSet();
                updateMessage.Add("message", message);
                updateMessage.Add("repeat", repeat);
                var responseStatus = await appServiceConnection.SendMessageAsync(updateMessage);
            }

            // Show the html 
            using (Stream resp = os.AsStreamForWrite())
            {
                // Look in the Data subdirectory of the app package
                byte[] bodyArray = Encoding.UTF8.GetBytes(htmlString);
                MemoryStream stream = new MemoryStream(bodyArray);
                string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                  "Content-Length: {0}\r\n" +
                                  "Connection: close\r\n\r\n",
                                  stream.Length);
                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                await resp.WriteAsync(headerArray, 0, headerArray.Length);
                await stream.CopyToAsync(resp);
                await resp.FlushAsync();
            }

        }
Esempio n. 35
0
        /// <summary>
        /// Sends data to the browser (client)
        /// </summary>
        /// <param name="bSendData">Byte Array</param>
        /// <param name="mySocket">Socket reference</param>
        private async Task SendToBrowser([ReadOnlyArray()] byte[] bSendData, [ReadOnlyArray()]byte[] header, IOutputStream os)
        {
            try
            {
                MemoryStream bodyStream = new MemoryStream(bSendData);
                using (Stream response = os.AsStreamForWrite())
                {

                    await response.WriteAsync(header, 0, header.Length);
                    await bodyStream.CopyToAsync(response);
                    await response.FlushAsync();
                    //System.Diagnostics.Debug.WriteLine("No. of bytes send {0}", bSendData.Length);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error writing response: " + ex.Message);
            }

        }
        private async Task WriteResponseAsync(string[] requestTokens, IOutputStream outstream)
        {
            string respBody = string.Empty;
            try
            {
                string urlPath = requestTokens.Length > 1 ? requestTokens[1] : string.Empty;

                if (urlPath.Equals("/LastHour", StringComparison.OrdinalIgnoreCase))
                {
                    respBody = temperatureData.JsonLastHour;
                }
                else if (urlPath.Equals("/LastDay", StringComparison.OrdinalIgnoreCase))
                {
                    respBody = temperatureData.JsonLast24Hours;
                }
                else if (urlPath.Equals("/LastMonth", StringComparison.OrdinalIgnoreCase))
                {
                    respBody = temperatureData.JsonLastMonth;
                }
                else
                {
                    respBody = temperatureData.JsonCurrent;
                }
            }
            catch (Exception ex)
            {
                await LogExceptionAsync(nameof(WriteResponseAsync) + "(part 1: getting content)", ex);
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }

            try
            {
                string htmlCode = "200 OK";

                using (Stream resp = outstream.AsStreamForWrite())
                {
                    byte[] bodyArray = Encoding.UTF8.GetBytes(respBody);
                    MemoryStream stream = new MemoryStream(bodyArray);

                    // NOTE: If you change the respBody format (above), change the Content-Type accordingly
                    string header = $"HTTP/1.1 {htmlCode}\r\n" +
                                    "Content-Type: text/json\r\n" +
                                    $"Content-Length: {stream.Length}\r\n" +
                                    "Connection: close\r\n\r\n";

                    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);
                    await stream.CopyToAsync(resp);
                    await resp.FlushAsync();
                }

            }
            catch (Exception ex)
            {
                await LogExceptionAsync(nameof(WriteResponseAsync) + "(part) 2: sending results)", ex);
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }
        }
Esempio n. 37
0
 public SocketStream(IInputStream inputStream, IOutputStream outputStream)
 {
     this.inputStream = inputStream.AsStreamForRead();
     this.outputStream = outputStream.AsStreamForWrite();
 }
Esempio n. 38
0
        private async Task WriteResponseAsync(string request, IOutputStream os)
        {
            // See if the request is for blinky.html, if yes get the new state
            string state = "Unspecified";
            bool stateChanged = false;
            if (request.Contains("blinky.html?state=on"))
            {
                state = "On";
                stateChanged = true;
            }
            else if (request.Contains("blinky.html?state=off"))
            {
                state = "Off";
                stateChanged = true;
            }

            if (stateChanged)
            {
                //var updateMessage = new ValueSet();
                //updateMessage.Add("State", state);
                //var responseStatus = await appServiceConnection.SendMessageAsync(updateMessage);
            }

            string html = state == "On" ? onHtmlString : offHtmlString;
            // Show the html 
            using (Stream resp = os.AsStreamForWrite())
            {
                // Look in the Data subdirectory of the app package
                byte[] bodyArray = Encoding.UTF8.GetBytes(html);
                MemoryStream stream = new MemoryStream(bodyArray);
                string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                  "Content-Length: {0}\r\n" +
                                  "Connection: close\r\n\r\n",
                                  stream.Length);
                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                await resp.WriteAsync(headerArray, 0, headerArray.Length);
                await stream.CopyToAsync(resp);
                await resp.FlushAsync();
            }

        }
Esempio n. 39
0
        //Write the response for HTTP GET's and POST's 
        private async Task WriteResponseAsync(string RequestMsg, string ResponseMsg, bool urlFound, byte[] bodyArray, IOutputStream os)
        {
            //try  //The appService will die after a day or so. Let 's try catch it seperatly so the server will still return
            //{
            //    var updateMessage = new ValueSet();
            //    updateMessage.Add("Request", RequestMsg);
            //    updateMessage.Add("Response", ResponseMsg);
            //    var responseStatus = await appServiceConnection.SendMessageAsync(updateMessage);
            //}
            //catch (Exception) { }

            try
            {
                MemoryStream bodyStream = new MemoryStream(bodyArray);
                using (Stream response = os.AsStreamForWrite())
                {
                    string header = GetHeader(urlFound, bodyStream.Length.ToString());
                    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    await response.WriteAsync(headerArray, 0, headerArray.Length);
                    if (urlFound)
                        await bodyStream.CopyToAsync(response);
                    await response.FlushAsync();
                }
            }
            catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine("Error writing response: " + ex.Message);
            }
        }
Esempio n. 40
0
        private async Task writeResponseAsync(string request, IOutputStream os, StreamSocketInformation socketInfo)
        {
            try
            {
                string[] requestParts = request.Split('/');

                // Request for the root page, so redirect to home page
                if (request.Equals("/"))
                {
                    await redirectToPage(NavConstants.HOME_PAGE, os);
                }
                // Request for the home page
                else if(request.Contains(NavConstants.HOME_PAGE))
                {
                    // Generate the default config page
                    string html = await helper.GenerateStatusPage();
                    await WebHelper.WriteToStream(html, os);
                }
                // Request for the settings page
                else if (request.Contains(NavConstants.SETTINGS_PAGE))
                {
                    // Process the GET parameters
                    if (request.Contains("?"))
                    {
                        // Format the URI with the get parameters
                        Uri uri = new Uri("http://1.2.3.4:8000" + request);

                        // Take the parameters from the URL and put it into Settings
                        helper.ParseUriIntoSettings(uri);
                        await AppSettings.SaveAsync(App.Controller.XmlSettings, "Settings.xml");

                        // This is an event that lets us know what the controller is done restarting after the settings are applied
                        AutoResetEvent ase = new AutoResetEvent(false);

                        // Dispose and Initialize need to be called on UI thread because of DispatcherTimers
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                        {
                            try
                            {
                                // Restart the controller to apply new settings
                                App.Controller.Dispose();
                                await App.Controller.Initialize();

                                // Create the settings page and add a confirmation message that the settings were applied successfully
                                string html = helper.GeneratePage("Security System Config", "Security System Config", helper.CreateHtmlFormFromSettings(), "<span style='color:Green'>Configuration saved!</span><br><br>");
                                await WebHelper.WriteToStream(html, os);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine("Error restarting controller: " + ex.Message);
                            }

                            // Signal that the restart is done
                            ase.Set();
                        });

                        // Wait for controller restart to finish
                        ase.WaitOne();
                    }
                    else
                    {
                        // Generate the default config page
                        string html = helper.GeneratePage("Security System Config", "Security System Config", helper.CreateHtmlFormFromSettings());
                        await WebHelper.WriteToStream(html, os);
                    }
                }
                // Request for the OneDrive page
                else if (request.Contains(NavConstants.ONEDRIVE_PAGE))
                {
                    // Take in the parameters and try to login to OneDrive
                    if (request.Contains("?"))
                    {
                        // I just put some arbitrary IP and port just so I have a correctly formatted URI, it's not important to have an actual IP + port
                        Uri uri = new Uri("http://1.2.3.4:8000" + request);
                        await helper.ParseOneDriveUri(uri);

                        var oneDrive = App.Controller.Storage as OneDrive;
                        if (oneDrive != null)
                        {
                            if (oneDrive.IsLoggedIn())
                            {
                                // Save tokens to settings file if we successfully logged in
                                await AppSettings.SaveAsync(App.Controller.XmlSettings, "Settings.xml");
                            }
                        }
                    }

                    // Generate page and write to stream
                    string html = helper.GenerateOneDrivePage();
                    await WebHelper.WriteToStream(html, os);
                }
                // Request for gallery page
                else if(request.Contains(NavConstants.GALLERY_PAGE))
                {
                    string html = "";
                    var storageType = App.Controller.Storage.GetType();
                    // If the storage type is OneDrive, generate page with link to OneDrive
                    if (storageType == typeof(OneDrive))
                    {
                        html = helper.GeneratePage("Gallery", "Gallery", "<b>" + storageType.Name + "</b> is set as your storage provider.&nbsp;&nbsp;"
                            + "Please view your pictures on <a href='http://www.onedrive.com' target='_blank'>OneDrive</a>.<br><br>"
                            + "To view your pictures here, please select <b>" + StorageProvider.Local + "</b> as your storage provider.");
                    }
                    // Otherwise show the gallery for the files on the device
                    else
                    {
                        StorageFolder folder = KnownFolders.PicturesLibrary;
                        int page = 1;
                        int pageSize = 30;

                        // Parse GET parameters
                        if (request.Contains("?"))
                        {
                            Uri uri = new Uri("http://1.2.3.4:8000" + request);
                            var parameters = helper.ParseGetParametersFromUrl(uri);
                            try
                            {
                                // Find the folder that's specified in the parameters
                                folder = await StorageFolder.GetFolderFromPathAsync(parameters["folder"]);

                                if(parameters.ContainsKey("page"))
                                {
                                    try
                                    {
                                        page = Convert.ToInt32(parameters["page"]);
                                    }
                                    catch (Exception) { }
                                }

                                if (parameters.ContainsKey("pageSize"))
                                {
                                    try
                                    {
                                        pageSize = Convert.ToInt32(parameters["pageSize"]);
                                    }
                                    catch (Exception) { }
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine("Exception finding folder: " + ex.Message);
                                folder = await folder.GetFolderAsync(AppSettings.FolderName);

                                // Log telemetry event about this exception
                                var events = new Dictionary<string, string> { { "WebServer", ex.Message } };
                                TelemetryHelper.TrackEvent("FailedToGetFolderFromPath", events);
                            }
                        }
                        else
                        {
                            folder = await folder.GetFolderAsync(AppSettings.FolderName);
                        }

                        // Generate gallery page and write to stream
                        string galleryHtml = await helper.GenerateGallery(folder, page, pageSize);
                        html = helper.GeneratePage("Gallery", "Gallery", galleryHtml);
                    }

                    await WebHelper.WriteToStream(html, os);
                }
                // Request for API
                else if(request.Contains("api"))
                {
                    try
                    {
                        if (requestParts.Length > 2)
                        {
                            switch (requestParts[2].ToLower())
                            {
                                // An image from the gallery was requested
                                case "gallery":
                                    var temp = request.Split(new string[] { "gallery/" }, StringSplitOptions.None);
                                    // HTML decode the file path
                                    string decodedPath = WebUtility.UrlDecode(temp[1]);

                                    // Retrieve the file
                                    StorageFile file = await StorageFile.GetFileFromPathAsync(decodedPath);

                                    // Write the file to the stream
                                    await WebHelper.WriteFileToStream(file, os);
                                    break;
                            }
                        }
                    }catch(Exception ex)
                    {
                        Debug.WriteLine("Exception in web API: " + ex.Message);

                        // Log telemetry event about this exception
                        var events = new Dictionary<string, string> { { "WebServer", ex.Message } };
                        TelemetryHelper.TrackEvent("FailedToProcessApiRequest", events);
                    }
                }
                // Request for a file that is in the Assets\Web folder (e.g. logo, css file)
                else
                {
                    using (Stream resp = os.AsStreamForWrite())
                    {
                        bool exists = true;
                        try
                        {
                            var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

                            // Map the requested path to Assets\Web folder
                            string filePath = @"Assets\Web" + request.Replace('/', '\\');
                            
                            // Open the file and write it to the stream
                            using (Stream fs = await folder.OpenStreamForReadAsync(filePath))
                            {
                                string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                                "Content-Length: {0}\r\n{1}" +
                                                "Connection: close\r\n\r\n",
                                                fs.Length,
                                                ((request.Contains("css")) ? "Content-Type: text/css\r\n" : ""));
                                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                                await resp.WriteAsync(headerArray, 0, headerArray.Length);
                                await fs.CopyToAsync(resp);
                            }
                        }
                        catch (FileNotFoundException ex)
                        {
                            exists = false;

                            // Log telemetry event about this exception
                            var events = new Dictionary<string, string> { { "WebServer", ex.Message } };
                            TelemetryHelper.TrackEvent("FailedToOpenStream", events);
                        }

                        // Send 404 not found if can't find file
                        if (!exists)
                        {
                            byte[] headerArray = Encoding.UTF8.GetBytes(
                                                  "HTTP/1.1 404 Not Found\r\n" +
                                                  "Content-Length:0\r\n" +
                                                  "Connection: close\r\n\r\n");
                            await resp.WriteAsync(headerArray, 0, headerArray.Length);
                        }

                        await resp.FlushAsync();
                    }
                }
            }catch(Exception ex)
            {
                Debug.WriteLine("Exception in writeResponseAsync(): " + ex.Message);
                Debug.WriteLine(ex.StackTrace);

                // Log telemetry event about this exception
                var events = new Dictionary<string, string> { { "WebServer", ex.Message } };
                TelemetryHelper.TrackEvent("FailedToWriteResponse", events);

                try
                {
                    // Try to send an error page back if there was a problem servicing the request
                    string html = helper.GeneratePage("Error", "Error", "There's been an error: " + ex.Message + "<br><br>" + ex.StackTrace);
                    await WebHelper.WriteToStream(html, os);
                }
                catch (Exception e)
                {
                    TelemetryHelper.TrackException(e);
                }
            }
        }
        protected virtual async Task WriteResponseAsync(HttpResponseMessage response, IOutputStream os)
        {
            if (response.Content == null && EnforceHtmlResponseBody)
                response.Content = CreateHtmlResponse(response.StatusCode);

            using (Stream resp = os.AsStreamForWrite()) {

                string header = response.ToHeaderString();
                byte[] headerArray = Encoding.UTF8.GetBytes(header);

                await resp.WriteAsync(headerArray, 0, headerArray.Length);
                if (response.Content != null)
                    await response.Content.CopyToAsync(resp);

                await resp.FlushAsync();
            }
        }
Esempio n. 42
0
        private async Task writeResponseAsync(string request, IOutputStream os, StreamSocketInformation socketInfo)
        {
            try
            {
                request = request.TrimEnd('\0'); //remove possible null from POST request

                string[] requestParts = request.Split('/');

                // Request for the root page, so redirect to home page
                if (request.Equals("/"))
                {
                    await redirectToPage(NavConstants.HOME_PAGE, os);
                }
                // Request for the home page
                else if (request.Contains(NavConstants.HOME_PAGE))
                {
                    // Generate the default config page
                    string html = await GeneratePageHtml(NavConstants.HOME_PAGE);
                    string onState = (this.playbackManager.PlaybackState == PlaybackState.Playing) ? "On" : "Off";

                    html = html.Replace("#onState#", onState);
                    html = html.Replace("#radioVolume#", (this.playbackManager.Volume * 100).ToString());
                    html = html.Replace("#currentTrack#", this.playlistManager.CurrentTrack.Name);

                    await WebHelper.WriteToStream(html, os);

                }
                // Request for the settings page
                else if (request.Contains(NavConstants.SETTINGS_PAGE))
                {
                    if (!string.IsNullOrEmpty(request))
                    {
                        string settingParam = "";
                        IDictionary<string, string> parameters = WebHelper.ParseGetParametersFromUrl(new Uri(string.Format("http://0.0.0.0/{0}", request)));
                        bool waitForPlaying = (this.playbackManager.PlaybackState == PlaybackState.Playing);
                        bool waitForTrackChange = false;
                        string trackName = this.playlistManager.CurrentTrack.Name;

                        settingParam = "onStateVal";
                        if (parameters.ContainsKey(settingParam) && !string.IsNullOrWhiteSpace(parameters[settingParam]))
                        {
                            switch (parameters[settingParam])
                            {
                                case "On":
                                    if (!waitForPlaying)
                                        this.playbackManager.Play(new Uri(this.playlistManager.CurrentTrack.Address));
                                    waitForPlaying = true;
                                    break;
                                case "Off":
                                    this.playbackManager.Pause();
                                    waitForPlaying = false;
                                    break;
                            }
                        }
                        settingParam = "volumeSlide";
                        if (parameters.ContainsKey(settingParam) && !string.IsNullOrWhiteSpace(parameters[settingParam]))
                        {
                            double newVolume = this.playbackManager.Volume;
                            if (double.TryParse(parameters[settingParam], out newVolume))
                            {
                                newVolume = Math.Round(newVolume / 100, 2);
                                if (newVolume >= 0 && newVolume <= 1 && newVolume != this.playbackManager.Volume)
                                {
                                    this.playbackManager.Volume = newVolume;
                                }
                            }
                        }
                        settingParam = "trackAction";
                        if (parameters.ContainsKey(settingParam) && !string.IsNullOrWhiteSpace(parameters[settingParam]))
                        {
                            waitForTrackChange = true;
                            switch (parameters[settingParam])
                            {
                                case "prev":
                                    this.playbackManager.Pause();
                                    this.playlistManager.PreviousTrack();
                                    break;
                                case "next":
                                    this.playbackManager.Pause();
                                    this.playlistManager.NextTrack();
                                    break;
                                case "track":
                                    if (parameters.ContainsKey("trackName") && !string.IsNullOrWhiteSpace(parameters["trackName"]))
                                    {
                                        if (trackName != parameters["trackName"])
                                        {
                                            this.playbackManager.Pause();
                                            this.playlistManager.PlayTrack(parameters["trackName"]);
                                        }
                                        else
                                            waitForTrackChange = false;
                                    }
                                    break;
                            }
                            if (waitForTrackChange) { waitForPlaying = true; }
                        }

                        DateTime timeOut = DateTime.Now.AddSeconds(30);
                        Debug.WriteLine("Waiting on State: playback={0}; trackname={1}", (waitForPlaying)?"Playing":"NotPlaying", trackName);
                        while (DateTime.Now.CompareTo(timeOut) < 0 && (
                            (this.playbackManager.PlaybackState == PlaybackState.Playing) != waitForPlaying
                            || (this.playlistManager.CurrentTrack.Name != trackName) != waitForTrackChange
                            ));

                        if (DateTime.Now.CompareTo(timeOut) >= 0)
                        {
                            Debug.WriteLine("track did not start playing in time limit");
                        }
                    }
                    //handle UI interaction
                    await redirectToPage(NavConstants.HOME_PAGE, os);
                }
                else if (request.Contains(NavConstants.ADDSTATION_PAGE))
                {
                    string html = await GeneratePageHtml(NavConstants.ADDSTATION_PAGE);
                    string trackName = "";
                    string trackUrl = "";
                    if (!string.IsNullOrEmpty(request))
                    {
                        string settingParam = "trackName";
                        IDictionary<string, string> parameters = WebHelper.ParseGetParametersFromUrl(new Uri(string.Format("http://0.0.0.0/{0}", request)));
                        if (parameters.ContainsKey(settingParam) && !string.IsNullOrWhiteSpace(parameters[settingParam]))
                        {
                            Track trackToUpdate = playlistManager.CurrentPlaylist.Tracks.First(t => t.Name == parameters[settingParam]);
                            if (null != trackToUpdate)
                            {
                                trackName = trackToUpdate.Name;
                                trackUrl = trackToUpdate.Address;
                            }
                        }
                    }
                    html = html.Replace("var stationName = '';", string.Format("var stationName = '{0}';", trackName));
                    html = html.Replace("var stationUrl = '';", string.Format("var stationUrl = '{0}';", trackUrl));
                    await WebHelper.WriteToStream(html, os);
                }
                else if (request.Contains(NavConstants.ADDSTATIONSET_PAGE))
                {
                    if (!string.IsNullOrEmpty(request))
                    {
                        Track origTrack = null;
                        Track newTrack = null;
                        string trackAction = "";
                        IDictionary<string, string> parameters = WebHelper.ParseGetParametersFromUrl(new Uri(string.Format("http://0.0.0.0/{0}", request)));
                        if (parameters.ContainsKey("name") && !string.IsNullOrWhiteSpace(parameters["name"]))
                        {
                            if (parameters.ContainsKey("url") && !string.IsNullOrWhiteSpace(parameters["url"]))
                            {
                                newTrack = new Track() { Name = parameters["name"], Address = parameters["url"] };
                            }
                        }
                        if (parameters.ContainsKey("nameOrig") && !string.IsNullOrWhiteSpace(parameters["nameOrig"]))
                        {
                            origTrack = this.playlistManager.CurrentPlaylist.Tracks.First(t => t.Name == parameters["nameOrig"]);
                        }
                        if (parameters.ContainsKey("trackAction") && !string.IsNullOrWhiteSpace(parameters["trackAction"]))
                        {
                            trackAction = parameters["trackAction"];
                        }

                        if (null != newTrack)
                        {
                            switch (trackAction)
                            {
                                case "Update":
                                    if (null != origTrack)
                                    {
                                        this.playlistManager.CurrentPlaylist.Tracks[this.playlistManager.CurrentPlaylist.Tracks.IndexOf(origTrack)] = newTrack;
                                    }
                                    else
                                    { 
                                        this.playlistManager.CurrentPlaylist.Tracks.Add(newTrack);
                                    }
                                    break;
                                case "Remove":
                                    if (null != origTrack)
                                        this.playlistManager.CurrentPlaylist.Tracks.Remove(origTrack);
                                    break;
                                case "":
                                case "Add":
                                    this.playlistManager.CurrentPlaylist.Tracks.Add(newTrack);
                                    break;
                            }
                        }
                    }
                    await redirectToPage(NavConstants.HOME_PAGE, os);
                }
                // Request for a file that is in the Assets\Web folder (e.g. logo, css file)
                else
                {
                    using (Stream resp = os.AsStreamForWrite())
                    {
                        bool exists = true;
                        try
                        {
                            var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

                            // Map the requested path to Assets\Web folder
                            string filePath = NavConstants.ASSETSWEB + request.Replace('/', '\\');

                            // Open the file and write it to the stream
                            using (Stream fs = await folder.OpenStreamForReadAsync(filePath))
                            {
                                string contentType = "";
                                if (request.Contains("css"))
                                {
                                    contentType = "Content-Type: text/css\r\n";
                                }
                                if (request.Contains("htm"))
                                {
                                    contentType = "Content-Type: text/html\r\n";
                                }
                                string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                                "Content-Length: {0}\r\n{1}" +
                                                "Connection: close\r\n\r\n",
                                                fs.Length,
                                                contentType);
                                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                                await resp.WriteAsync(headerArray, 0, headerArray.Length);
                                await fs.CopyToAsync(resp);
                            }
                        }
                        catch (FileNotFoundException ex)
                        {
                            exists = false;

                            // Log telemetry event about this exception
                            var events = new Dictionary<string, string> { { "WebServer", ex.Message } };
                            TelemetryManager.WriteTelemetryEvent("FailedToOpenStream", events);
                        }

                        // Send 404 not found if can't find file
                        if (!exists)
                        {
                            byte[] headerArray = Encoding.UTF8.GetBytes(
                                                  "HTTP/1.1 404 Not Found\r\n" +
                                                  "Content-Length:0\r\n" +
                                                  "Connection: close\r\n\r\n");
                            await resp.WriteAsync(headerArray, 0, headerArray.Length);
                        }

                        await resp.FlushAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception in writeResponseAsync(): " + ex.Message);
                Debug.WriteLine(ex.StackTrace);

                // Log telemetry event about this exception
                var events = new Dictionary<string, string> { { "WebServer", ex.Message } };
                TelemetryManager.WriteTelemetryEvent("FailedToWriteResponse", events);

                try
                {
                    // Try to send an error page back if there was a problem servicing the request
                    string html = helper.GenerateErrorPage("There's been an error: " + ex.Message + "<br><br>" + ex.StackTrace);
                    await WebHelper.WriteToStream(html, os);
                }
                catch (Exception e)
                {
                    TelemetryManager.WriteTelemetryException(e);
                }
            }
        }
Esempio n. 43
0
        protected override async Task WriteResponseAsync(string request, IOutputStream os)
        {
            var response = new StatusResponse();

            if (request.StartsWith("/api/seed"))
            {
                var sql = new SqlHelper();

                sql.SeedDatabase();
            }

            if (request.StartsWith("/api/status"))
            {
                var sql = new SqlHelper();

                var info = sql.Get();

                response.Status = info.CurrentStatus.ToString();

                if (info.CurrentStatus == DishwasherStatus.Clean)
                {
                    response.Details = new StatusResponse.CleanStatusDetails
                    {
                        DishwasherRun = sql.GetDishwasherRun()
                    };
                }
                else if (info.CurrentStatus == DishwasherStatus.Dirty)
                {
                    response.Details = new StatusResponse.DirtyStatusDetails
                    {
                        DirtyTime = info.DirtyDateTime
                    };
                }
                else if (info.CurrentStatus == DishwasherStatus.Running)
                {
                    response.Details = new StatusResponse.RunningStatusDetails
                    {
                        StartTime = info.CurrentRunStart,
                        RunCycle = info.CurrentCycle
                    };
                }
            }
            
            // Show the html 
            using (Stream resp = os.AsStreamForWrite())
            {
                string json;
                using (MemoryStream jsonStream = new MemoryStream())
                {
                    var serializer = new DataContractJsonSerializer(typeof(StatusResponse));
                    serializer.WriteObject(jsonStream, response);
                    jsonStream.Position = 0;
                    StreamReader sr = new StreamReader(jsonStream);
                    json = sr.ReadToEnd();
                }

                byte[] bodyArray = Encoding.UTF8.GetBytes(json);
                using (MemoryStream stream = new MemoryStream(bodyArray))
                {
                    string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                                  "Content-Length: {0}\r\n" +
                                                  "Content-Type: application/json\r\n" +
                                                  "Connection: close\r\n\r\n",
                        stream.Length);
                    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);
                    await stream.CopyToAsync(resp);
                }
                await resp.FlushAsync();
            }
        }
        /// <summary>
        /// 輸出的資料
        /// </summary>
        /// <param name="request">http://網址  以後的東西 
        /// ex. http://1xx.xx.xx.xx/sample.html 則此參數呈現  /sample.html</param>
        /// <param name="os"></param>
        /// <returns></returns>
        private async Task WriteResponseAsync(string request, IOutputStream os)
        {
            string file = @"Assets\html" + request.Replace("\\", "/");


            if (request == "/")
            {
                file = @"Assets\html\index.html";
            }
            else if (!System.IO.File.Exists(file))
            {
                file = @"Assets\html\404.html";
            }
            using (Stream resp = os.AsStreamForWrite())
            {
                var contentType = "text/html";
                if (System.IO.Path.GetExtension(file).ToLower() == ".jpg" ||
                    System.IO.Path.GetExtension(file).ToLower() == ".png" ||
                    System.IO.Path.GetExtension(file).ToLower() == ".jpeg")
                {
                    contentType = "image/jpeg";
                }

                //很簡單的處理jpg and html 只是測試,別太講究
                //Handling MIME and Head roughly.
                byte[] bodyArray = File.ReadAllBytes(file);
                MemoryStream stream = new MemoryStream(bodyArray);
                string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                              "Content-Length: {0}\r\n" +
                                               "content-type: {1}\r\n" +
                                              "Connection: close\r\n\r\n",
                    stream.Length, contentType);
                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                await resp.WriteAsync(headerArray, 0, headerArray.Length);
                await stream.CopyToAsync(resp);
                await resp.FlushAsync();
            }
            
        }
 private async Task WriteResponseAsync(string request, IOutputStream os)
 {
     // Show the html 
     using (Stream resp = os.AsStreamForWrite())
     {
         using (var file = File.OpenRead(htmlPath))
         {
             string header = $"HTTP/1.1 200 OK\r\nContent-Length: {file.Length}\r\n" +
                              "Content-Type:text/html\r\nConnection: close\r\n\r\n";
             byte[] headerArray = Encoding.UTF8.GetBytes(header);
             await resp.WriteAsync(headerArray, 0, headerArray.Length);
             await file.CopyToAsync(resp);
         }
     }
 }
Esempio n. 46
0
        //----------------------------------------
        //
        // BLOBS
        //
        //-----------------------------------------
        public IAsyncAction DownloadBlob(Blob blob, IOutputStream destination)
        {
            blob.ValidateRequired("blob");
            if (destination == null)
            {
                throw new ArgumentNullException("destination");
            }

            Stream stream = destination.AsStreamForWrite();
            return AsyncInfo.Run(cancelToken => Client.Streamer.DownloadAsync(new Uri(blob.Url), stream, cancelToken));
        }
Esempio n. 47
0
 private async Task WriteResponseAsync(IOutputStream os, string method, string data = null)
 {
     string html = String.Format(RestString, GetContentRequestData == null ? String.Empty : GetContentRequestData(method,data));
     using (Stream resp = os.AsStreamForWrite())
     {
         byte[] bodyArray = Encoding.UTF8.GetBytes(html);
         MemoryStream stream = new MemoryStream(bodyArray);
         string header = String.Format("HTTP/1.1 200 OK\r\n" + "Content-Length: {0}\r\n" + "Connection: close\r\n\r\n", stream.Length);
         byte[] headerArray = Encoding.UTF8.GetBytes(header);
         await resp.WriteAsync(headerArray, 0, headerArray.Length);
         await stream.CopyToAsync(resp);
         await resp.FlushAsync();
     }
 }
Esempio n. 48
0
        private async Task WriteResponseAsync(string[] requestTokens, IOutputStream outstream)
        {
            // Content body
            //string respBody = string.Format(@"<html>
            //                                        <head>
            //                                            <title>SHT15 Sensor Values</title>
            //                                            <meta http-equiv='refresh' content='2' />
            //                                        </head>
            //                                        <body>
            //                                            <p><font size='6'><b>Windows 10 IoT Core and SHT15 Sensor</b></font></p>
            //                                            <hr/>
            //                                            <br/>
            //                                            <table>
            //                                                <tr>
            //                                                    <td><font size='3'>Time</font></td>
            //                                                    <td><font size='3'>{0}</font></td>
            //                                                </tr>
            //                                                <tr>
            //                                                    <td><font size='5'>Temperature</font></td>
            //                                                    <td><font size='6'><b>{1}&deg;C</b></font></td>
            //                                                </tr>
            //                                                <tr>
            //                                                    <td><font size='5'>Temperature</font></td>
            //                                                    <td><font size='6'><b>{2}F</b></font></td>
            //                                                </tr>
            //                                                <tr>
            //                                                    <td><font size='5'>Humidity</font></td>
            //                                                    <td><font size='6'><b>{3}%</b></font></td>
            //                                                </tr>
            //                                                <tr>
            //                                                    <td><font size='5'>Dew Point</font></td>
            //                                                    <td><font size='6'><b>{4}&deg;C</b></font></td>
            //                                                </tr>
            //                                            </table>
            //                                        </body>
            //                                      </html>",

            //                                DateTime.Now.ToString("h:mm:ss tt"),
            //                                String.Format("{0:0.00}", MainPage.TemperatureC),
            //                                String.Format("{0:0.00}", MainPage.TemperatureF),
            //                                String.Format("{0:0.00}", MainPage.Humidity),
            //                                String.Format("{0:0.00}", MainPage.CalculatedDewPoint));

            string respBody = MainPage.TemperatureC + ";" + MainPage.TemperatureF + ";" + MainPage.Humidity;

            string htmlCode = "200 OK";

            using (Stream resp = outstream.AsStreamForWrite())
            {
                byte[] bodyArray = Encoding.UTF8.GetBytes(respBody);
                MemoryStream stream = new MemoryStream(bodyArray);

                // Response heeader
                string header = string.Format("HTTP/1.1 {0}\r\n" +
                                              "Content-Type: text/html\r\n" +
                                              "Content-Length: {1}\r\n" +
                                              "Connection: close\r\n\r\n",
                                              htmlCode, stream.Length);

                byte[] headerArray = Encoding.UTF8.GetBytes(header);
                await resp.WriteAsync(headerArray, 0, headerArray.Length);
                await stream.CopyToAsync(resp);
                await resp.FlushAsync();
            }
        }
Esempio n. 49
0
        private async Task WriteResponseAsync(string request, IOutputStream os)
        {
            using (Stream resp = os.AsStreamForWrite())
            {
                using (FileStream sourceStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
                {
                    string mime;
                    string header = string.Format("HTTP/1.1 200 OK\r\n" +
                                      "Date: " + DateTime.Now.ToString("R") + "\r\n" +
                                      "Server: MeoGoEmbedded/1.0\r\n" +
                                      //"Transfer-Encoding: chunked\r\n" +
                                      "Last-Modified: {2}\r\n" +
                                      "Content-Length: {0}\r\n" +
                                      "Content-Type: {1}\r\n" +
                                      "Connection: close\r\n\r\n",
                                      sourceStream.Length,
                                      _mimeTypeMappings.TryGetValue(Path.GetExtension(FilePath), out mime) ? mime : "application/octet-stream", File.GetLastWriteTime(FilePath).ToString("r"));
                    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);

                    var b = new byte[1 << 15]; // 32k
                    int count = 0;
                    while ((count = sourceStream.Read(b, 0, b.Length)) > 0)
                    {
                        await resp.WriteAsync(b, 0, count);

                    }
                    await resp.FlushAsync();
                };
            }
        }
Esempio n. 50
0
 /// <summary>
 /// Redirect to a page
 /// </summary>
 /// <param name="path">Relative path to page</param>
 /// <param name="os"></param>
 /// <returns></returns>
 private async Task redirectToPage(string path, IOutputStream os)
 {
     using (Stream resp = os.AsStreamForWrite())
     {
         byte[] headerArray = Encoding.UTF8.GetBytes(
                           "HTTP/1.1 302 Found\r\n" +
                           "Content-Length:0\r\n" +
                           "Location: /" + path + "\r\n" +
                           "Connection: close\r\n\r\n");
         await resp.WriteAsync(headerArray, 0, headerArray.Length);
         await resp.FlushAsync();
     }
 }
Esempio n. 51
0
        private async Task WriteResponseAsync(HttpServerRequest request, IOutputStream os)
        {
            using (Stream response = os.AsStreamForWrite())
            {
                bool exists = true;
                try
                {
                    if (ServerResponseCallback != null)
                    {
                        byte[] bytes = ServerResponseCallback(request);
                        await response.WriteAsync(bytes, 0, bytes.Length);
                    }
                    else if (ServerResponseCallbackAsync != null)
                    {
                        byte[] bytes = await ServerResponseCallbackAsync(request);

                        System.Diagnostics.Debug.WriteLine(System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length));

                        await response.WriteAsync(bytes, 0, bytes.Length);
                    }
                    else
                    {
                        // Look in the Data subdirectory of the app package
                        string filePath = "Data" + request.Path.Replace('/', '\\');
                        using (Stream fs = await LocalFolder.OpenStreamForReadAsync(filePath))
                        {
                            string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                             "Content-Length: {0}\r\n" +
                                             "Connection: close\r\n\r\n",
                                             fs.Length);
                            byte[] headerArray = Encoding.UTF8.GetBytes(header);
                            await response.WriteAsync(headerArray, 0, headerArray.Length);
                            await fs.CopyToAsync(response);
                        }
                    }
                }
                catch (FileNotFoundException)
                {
                    exists = false;
                }

                if (!exists)
                {
                    byte[] headerArray = Encoding.UTF8.GetBytes(
                                          "HTTP/1.1 404 Not Found\r\n" +
                                          "Content-Length:0\r\n" +
                                          "Connection: close\r\n\r\n");
                    await response.WriteAsync(headerArray, 0, headerArray.Length);
                }

                await response.FlushAsync();
            }
        }
Esempio n. 52
0
 /// <summary>
 /// Writes html data to the stream
 /// </summary>
 /// <param name="data"></param>
 /// <param name="os"></param>
 /// <returns></returns>
 public static async Task WriteToStream(string data, IOutputStream os)
 {
     using (Stream resp = os.AsStreamForWrite())
     {
         // Look in the Data subdirectory of the app package
         byte[] bodyArray = Encoding.UTF8.GetBytes(data);
         MemoryStream stream = new MemoryStream(bodyArray);
         string header = String.Format("HTTP/1.1 200 OK\r\n" +
                           "Content-Length: {0}\r\n" +
                           "Connection: close\r\n\r\n",
                           stream.Length);
         byte[] headerArray = Encoding.UTF8.GetBytes(header);
         await resp.WriteAsync(headerArray, 0, headerArray.Length);
         await stream.CopyToAsync(resp);
         await resp.FlushAsync();
     }
 }
Esempio n. 53
0
        /// <summary>
        /// Writes a file to the stream
        /// </summary>
        /// <param name="file"></param>
        /// <param name="os"></param>
        /// <returns></returns>
        public static async Task WriteFileToStream(StorageFile file, IOutputStream os)
        {
            using (Stream resp = os.AsStreamForWrite())
            {
                bool exists = true;
                try
                {
                    using (Stream fs = await file.OpenStreamForReadAsync())
                    {
                        string header = String.Format("HTTP/1.1 200 OK\r\n" +
                                        "Content-Length: {0}\r\n" +
                                        "Connection: close\r\n\r\n",
                                        fs.Length);
                        byte[] headerArray = Encoding.UTF8.GetBytes(header);
                        await resp.WriteAsync(headerArray, 0, headerArray.Length);
                        await fs.CopyToAsync(resp);
                    }
                }
                catch (FileNotFoundException ex)
                {
                    exists = false;

                    // Log telemetry event about this exception
                    var events = new Dictionary<string, string> { { "WebHelper", ex.Message } };
                    App.Controller.TelemetryClient.TrackEvent("FailedToWriteFileToStream", events);
                }

                if (!exists)
                {
                    byte[] headerArray = Encoding.UTF8.GetBytes(
                                          "HTTP/1.1 404 Not Found\r\n" +
                                          "Content-Length:0\r\n" +
                                          "Connection: close\r\n\r\n");
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);
                }

                await resp.FlushAsync();
            }
        }
Esempio n. 54
0
        /// <summary>
        /// Write the HTTP response to the request out to the output
        /// stream on the socket.
        /// </summary>
        /// <param name="resourceName">The resource name to retrieve.</param>
        /// <param name="outputStream">The output stream to write to.</param>
        /// <returns>A task object.</returns>
        private async Task WriteResponseAsync(string resourceName, IOutputStream outputStream)
        {
            using (var writeStream = outputStream.AsStreamForWrite())
            {
                var resourceParts = resourceName.Split('?');
                var requestPath = resourceParts[0];

                // check the extension is supported.
                var extension = Path.GetExtension(requestPath);

                if (_contentTypes.ContainsKey(extension))
                {
                    try
                    {
                        string contentType = _contentTypes[extension];

                        // read the local data.

                        var requestedFile = await GetFileAsync(SplitToPath(requestPath));
                        var fileStream = await requestedFile.OpenReadAsync();
                        var size = fileStream.Size;

                        // write out the HTTP headers.
                        var header = String.Format("HTTP/1.1 200 OK\r\n" +
                                                 "Content-Type: {0}\r\n" +
                                                 "Content-Length: {1}\r\n" +
                                                 "Connection: close\r\n" +
                                                 "\r\n",
                                                 contentType,
                                                 fileStream.Size);

                        var headerArray = Encoding.UTF8.GetBytes(header);

                        await writeStream.WriteAsync(headerArray, 0, headerArray.Length);

                        // copy the requested file to the output stream.
                        await fileStream.AsStreamForRead().CopyToAsync(writeStream);
                    } catch (Exception e) {
                        Debug.WriteLine("e:{0}", e);
                        SendNotFound(writeStream);
                    }
                }
                else
                {
                    // unrecognised file type.
                    // handle as 404 not found.

                    SendNotFound(writeStream);
                }
                await writeStream.FlushAsync();
            }
        }
        private async Task WriteResponseAsync(string path, IOutputStream os)
        {
            using (Stream resp = os.AsStreamForWrite())
            {
                bool exists = true;
                try
                {
                    // Look in the Data subdirectory of the app package
                    string filePath = "Data" + path.Replace('/', '\\');
                    //using (Stream fs = await LocalFolder.OpenStreamForReadAsync(filePath))
                    //{
                    //    string header = String.Format("HTTP/1.1 200 OK\r\n" +
                    //                                  "Content-Length: {0}\r\n" +
                    //                                  "Connection: close\r\n\r\n",
                    //        fs.Length);
                    //    byte[] headerArray = Encoding.UTF8.GetBytes(header);
                    //    await resp.WriteAsync(headerArray, 0, headerArray.Length);
                    //    await fs.CopyToAsync(resp);
                    //}
                }
                catch (FileNotFoundException)
                {
                    exists = false;
                }

                if (!exists)
                {
                    byte[] headerArray = Encoding.UTF8.GetBytes(
                        "HTTP/1.1 404 Not Found\r\n" +
                        "Content-Length:0\r\n" +
                        "Connection: close\r\n\r\n");
                    await resp.WriteAsync(headerArray, 0, headerArray.Length);
                }

                await resp.FlushAsync();
            }
        }
Esempio n. 56
0
        public IAsyncAction DownloadRangeToStreamAsync(IOutputStream target, long? offset, long? length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
        {
            CommonUtils.AssertNotNull("target", target);
            BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.PageBlob, this.ServiceClient);

            // We should always call AsStreamForWrite with bufferSize=0 to prevent buffering. Our
            // stream copier only writes 64K buffers at a time anyway, so no buffering is needed.
            return AsyncInfo.Run(async (token) => await Executor.ExecuteAsyncNullReturn(
                CloudBlobSharedImpl.GetBlobImpl(this, this.attributes, target.AsStreamForWrite(0), offset, length, accessCondition, modifiedOptions),
                modifiedOptions.RetryPolicy,
                operationContext,
                token));
        }
Esempio n. 57
0
 public IAsyncAction DownloadRangeToStreamAsync(IOutputStream target, long? offset, long? length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
 {
     CommonUtils.AssertNotNull("target", target);
     BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.PageBlob, this.ServiceClient);
     return AsyncInfo.Run(async (token) => await Executor.ExecuteAsyncNullReturn(
         CloudBlobSharedImpl.GetBlobImpl(this, this.attributes, target.AsStreamForWrite(), offset, length, accessCondition, modifiedOptions),
         modifiedOptions.RetryPolicy,
         operationContext,
         token));
 }