private async Task<WebResponse> HomePage(WebRequest request)
        {
            // Prepare the response object
            var response = new WebResponse
            {
                // Create a new dictionary for headers - this could be done using a more advanced class for 
                // WebResponse object - I just used a simple structure
                Header = new Dictionary<string, string>
                {
                    // Add content type header
                    {
                        "Content-Type",
                        "application/json'"
                    }
                }
            };

            // Build the response content
            Stream responseText = new MemoryStream();
            var contentWriter = new StreamWriter(responseText);
            contentWriter.WriteLine(
                "{\"status\":200,\"message\":\"The API is available at http://" + IpAddress + ":" + Port +
                "/?color=######\"}"
                );
            contentWriter.Flush();

            // Assign the response
            response.Content = responseText;

            // Return the response
            return response;
        }
        private async Task<WebResponse> ApiPage(WebRequest request)
        {
            // Prepare the response object
            var response = new WebResponse
            {
                // Create a new dictionary for headers - this could be done using a more advanced class for 
                // WebResponse object - I just used a simple structure
                Header = new Dictionary<string, string>
                {
                    // Add content type header
                    {
                        "Content-Type",
                        "application/json'"
                    }
                }
            };

            Stream responseText = new MemoryStream();

            if (request.Uri.IndexOf('?') > -1)
            {
                var queryString = request.Uri.Substring(request.Uri.IndexOf('?'));

                var decoder = new WwwFormUrlDecoder(queryString);

                foreach (var color in decoder.Where(param => param.Name == "color").Select(param => Color.FromArgb(255,
                    Convert.ToByte(param.Value.Substring(0, 2), 16),
                    Convert.ToByte(param.Value.Substring(2, 2), 16),
                    Convert.ToByte(param.Value.Substring(4, 2), 16))))
                {
                    try
                    {
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                            () =>
                            {
                                var colorBrush = new SolidColorBrush(color);
                                LightColor = colorBrush;

                                var contentWriter = new StreamWriter(responseText);
                                contentWriter.WriteLine(
                                    "{\"status\":200,\"message\":\"Color was set to " + LightColor.Color + "\"}"
                                    );
                                contentWriter.Flush();
                            }
                            );
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e);
                    }
                }
            }

            // Assign the response
            response.Content = responseText;

            // Return the response
            return response;
        }
Beispiel #3
0
        /// <summary>
        ///     Method which parses the request and decides about the action
        /// </summary>
        /// <param name="requestFile">Path to the temporary file holding the request packet</param>
        /// <param name="socket">Socket used with the request (required for response)</param>
        public async void ParseRequest(string requestFile, StreamSocket socket)
        {
            // Open and read the request: needs stream reading support for large files
            var plika = _isf.OpenFile(requestFile, FileMode.Open);
            var reada = new StreamReader(plika);

            // Read the first ling to get request type
            var linge = reada.ReadLine();

            // Create new request object (same type as response object - possibly better class naming needs to be used)
            var request = new WebRequest();

            // If there is any data...
            if (!string.IsNullOrEmpty(linge))
            {
                // Get the method (currently GET only supported really) and the request URL
                if (linge.Substring(0, 3) == "GET")
                {
                    request.Method = "GET";
                    request.Uri = linge.Substring(4);
                }
                else if (linge.Substring(0, 4) == "POST")
                {
                    request.Method = "POST";
                    request.Uri = linge.Substring(5);
                }

                // Remove the HTTP version
                request.Uri = Regex.Replace(request.Uri, " HTTP.*$", string.Empty);

                // Create a dictionary for the sent headers
                var headers = new Dictionary<string, string>();

                // Read HTTP headers into the dictionary
                string line;
                do
                {
                    line = reada.ReadLine();
                    var sepa = new string[1];
                    sepa[0] = ":";
                    var elems = line.Split(sepa, 2, StringSplitOptions.RemoveEmptyEntries);
                    if (elems.Length > 0)
                    {
                        headers.Add(elems[0], elems[1]);
                    }
                } while (line.Length > 0);

                // Assign headers to the request object
                request.Header = headers;

                // Assign rest of the content to the request object in a form of a stream handle moved to the part with content after previous read line operations
                request.Content = reada.BaseStream;

                // Determines if we found a matching URL rule
                var foundrule = false;

                // Create a stream writer to the output stream (response)
                var writ = new DataWriter(socket.OutputStream);

                // If there are any server rules
                if (_serverRules != null)
                {
                    // For every rule...
                    foreach (
                        var toSendTask in
                            from rulePart in _serverRules.Keys
                            where rulePart.IsMatch(request.Uri)
                            select _serverRules[rulePart](request))
                    {
                        // Mark that we found a rule
                        foundrule = true;

                        // Wait for the response to get fulfilled
                        var toSend = await toSendTask;

                        // If the rule is meant to redirect...
                        writ.WriteString(toSend.Header.ContainsKey("Location")
                            ? "HTTP/1.1 302\r\n"
                            : "HTTP/1.1 200 OK\r\n");

                        // Write content length to the buffer
                        writ.WriteString("Content-Length: " + (toSend.Content == null ? 0 : toSend.Content.Length) +
                                         "\r\n");

                        // For each of the response headers (returned by the delegate assigned to the URL rule
                        foreach (var header in toSend.Header)
                        {
                            // Write it to the output
                            writ.WriteString(header.Key + ": " + header.Value + "\r\n");
                        }

                        // Add connection: close header
                        writ.WriteString("Connection: close\r\n");

                        // New line before writing content
                        writ.WriteString("\r\n");

                        // We lock the web server until response is finished
                        lock (this)
                        {
                            // Reset the output stream
                            if (toSend.Content != null)
                            {
                                toSend.Content.Seek(0, SeekOrigin.Begin);
                                Task.Run(async () =>
                                {
                                    await writ.StoreAsync(); // Wait for the data to be saved in the output
                                    await writ.FlushAsync(); // Flush (send to the output)

                                    // Write the data to the output using 1024 buffer (store and flush after every loop)
                                    while (toSend.Content.Position < toSend.Content.Length)
                                    {
                                        var buffer = toSend.Content.Length - toSend.Content.Position < 1024
                                            ? new byte[toSend.Content.Length - toSend.Content.Position]
                                            : new byte[1024];
                                        toSend.Content.Read(buffer, 0, buffer.Length);
                                        writ.WriteBytes(buffer);

                                        await writ.StoreAsync();
                                        await writ.FlushAsync();
                                    }
                                    toSend.Content.Dispose();
                                });
                            }
                            else
                            {
                                writ.WriteString("HTTP/1.1 200 OK\r\n");
                                writ.WriteString("Content-Type: text/html\r\n");
                                writ.WriteString("Content-Length: 0\r\n");
                                writ.WriteString("Pragma: no-cache\r\n");
                                writ.WriteString("Connection: close\r\n");
                                writ.WriteString("\r\n");
                                Task.Run(async () => { await writ.StoreAsync(); });
                            }
                        }
                        break;
                    }
                }

                if (foundrule) return;

                writ.WriteString("HTTP/1.1 404 Not Found\r\n");
                writ.WriteString("Content-Type: text/html\r\n");
                writ.WriteString("Content-Length: 9\r\n");
                writ.WriteString("Pragma: no-cache\r\n");
                writ.WriteString("Connection: close\r\n");
                writ.WriteString("\r\n");
                writ.WriteString("Not found");
                Task.Run(async () => { await writ.StoreAsync(); });
            }
        }