Beispiel #1
0
        private static async Task WriteFileToStreamHelper(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 }
                    };
                    TelemetryManager.WriteTelemetryEvent("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();
            }
        }
Beispiel #2
0
        private async Task <bool> RetrieveFile(string requestUri, StorageFolder folder, Stream resp)
        {
            bool exists = false;

            try
            {
                string filePath = requestUri.Replace('/', '\\').Replace("%20", " ");

                // Open the file and write it to the stream
                using (Stream fs = await folder.OpenStreamForReadAsync(filePath))
                {
                    string contentType = "";
                    //https://developer.mozilla.org/es/docs/Web/HTTP/Basics_of_HTTP/MIME_types
                    if (requestUri.Contains(".css"))
                    {
                        contentType = "Content-Type: text/css\r\n";
                    }
                    else if (requestUri.Contains(".htm"))
                    {
                        contentType = "Content-Type: text/html\r\n";
                    }
                    else if (requestUri.Contains(".js"))
                    {
                        contentType = "Content-Type: application/javascript\r\n";
                    }
                    else if (requestUri.Contains(".jpg") || requestUri.Contains(".png") || requestUri.Contains(".gif") || requestUri.Contains(".ico"))//image
                    {
                        contentType = "Content-Type: image/gif, image/png, image/jpeg, image/jpg, image/bmp, image/webp, image/ico\r\n";
                    }
                    else if (requestUri.Contains(".mp4"))//video
                    {
                        contentType = "Content-Type: video/mp4\r\n";
                    }
                    else if (requestUri.Contains(".mp3"))//audio
                    {
                        contentType = "Content-Type: audio/mp3, audio/midi, audio/mpeg, audio/webm, audio/ogg, audio/wav\r\n";
                    }

                    else
                    {
                        //unknown content type or not implemented yet
                        return(false);
                    }


                    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);

                    exists = true;
                }
            }
            catch (FileNotFoundException ex)
            {
                exists = false;

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


            return(exists);
        }
Beispiel #3
0
        private async Task WriteResponseAsync(string requestUri, IOutputStream os, StreamSocketInformation socketInfo)
        {
            try
            {
                requestUri = requestUri.TrimEnd('\0'); //remove possible null from POST request

                string[] uriParts = requestUri.Split('/');


                if (requestUri == "/")
                {
                    // Request for the root page, so redirect to home page
                    await redirectToPage(NavConstants.HOME_PAGE, os);

                    return;
                }
                else if (uriParts[1].ToLower().Contains("home") || uriParts[1].ToLower().Contains("index") || uriParts[1].ToLower().Contains("default"))
                {
                    // Request for the home page
                    string html = await GeneratePageHtml(NavConstants.HOME_PAGE);

                    await WebHelper.WriteToStream(html, os);

                    return;
                }
                else if (uriParts[1].ToLower() == "api")
                {
                    string json = await _webApiHelper.Execute(requestUri);

                    await WebHelper.WriteToStream(json, os);

                    return;
                }
                else// Request for a file that is in the Assets\Web folder (e.g. logo, css file)
                {
                    using (Stream resp = os.AsStreamForWrite())
                    {
                        // Map the requested path to Assets\Web folder
                        StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(NavConstants.ASSETSWEB);

                        bool exists = await RetrieveFile(requestUri, folder, resp);

                        if (!exists)
                        {
                            if (requestUri.Contains(NavConstants.TEMP_FOLDER))
                            {
                                folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
                                exists = await RetrieveFile(requestUri, folder, resp);

                                if (!exists)
                                {
                                    // Send 404 not found if can't find file
                                    byte[] headerArray = Encoding.UTF8.GetBytes("HTTP/1.1 404 Not Found\r\nContent-Length:0\r\nConnection: close\r\n\r\n");
                                    await resp.WriteAsync(headerArray, 0, headerArray.Length);
                                }
                            }
                            else
                            {
                                if (requestUri.Contains("favicon.ico"))//https://en.wikipedia.org/wiki/Favicon
                                {
                                    folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(NavConstants.ASSETSWEB);

                                    exists = await RetrieveFile(requestUri, folder, resp);

                                    if (!exists)
                                    {
                                        // Send 404 not found if can't find file
                                        byte[] headerArray = Encoding.UTF8.GetBytes("HTTP/1.1 404 Not Found\r\nContent-Length:0\r\nConnection: close\r\n\r\n");
                                        await resp.WriteAsync(headerArray, 0, headerArray.Length);
                                    }
                                }
                                else
                                {
                                    //It raise warning message because web request shouldn't access to root installed folder
                                    byte[] headerArray = Encoding.UTF8.GetBytes("HTTP/1.1 403 Forbidden\r\nContent-Length:0\r\nConnection: 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 = _webhelper.GenerateErrorPage("There's been an error: " + ex.Message + "<br><br>" + ex.StackTrace);
                    await WebHelper.WriteToStream(html, os);
                }
                catch (Exception e)
                {
                    TelemetryManager.WriteTelemetryException(e);
                }
            }
        }