Close() public method

public Close ( ) : void
return void
Esempio n. 1
0
		public void Process(HttpListenerRequest request, HttpListenerResponse response)
		{
			try
			{
				if (request.HttpMethod != "GET")
				{
					response.StatusCode = 405;
					response.StatusDescription = "Method Not Supported";
					response.Close();
					return;
				}

				string version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;
				string status = GetStatusDescription();
				string timestamp = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "Z";

				FormatJsonResponse(response, version, status, timestamp);
			}
			catch (HttpListenerException hlex)
			{
				Supervisor.LogException(hlex, TraceEventType.Error, request.RawUrl);

				response.StatusCode = 500;
				response.StatusDescription = "Error Occurred";
				response.Close();
			}
		}
Esempio n. 2
0
        internal void Close()
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this);
            }

            try
            {
                _response?.Close();
            }
            finally
            {
                try
                {
                    Request.Close();
                }
                finally
                {
                    IDisposable user = _user == null ? null : _user.Identity as IDisposable;

                    // For unsafe connection ntlm auth we dont dispose this identity as yet since its cached
                    if ((user != null) &&
                        (_user.Identity.AuthenticationType != NegotiationInfoClass.NTLM) &&
                        (!_listener.UnsafeConnectionNtlmAuthentication))
                    {
                        user.Dispose();
                    }
                }
            }
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Exit(this);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// http响应
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="response"></param>
        /// <param name="type"></param>
        public void ResponseWrite(string msg, System.Net.HttpListenerResponse response, string type = "text/plain")
        {
            try
            {
                //使用Writer输出http响应代码
                if (type == "text/plain")
                {
                    //using (System.IO.StreamWriter writer = new System.IO.StreamWriter(response.OutputStream, new UTF8Encoding()))
                    //{
                    //    response.ContentType = type + ";charset=utf-8";
                    //    writer.WriteLine(msg);
                    //    writer.Close();
                    //    response.Close();
                    //}
                }

                using (StreamWriter writer = new StreamWriter(response.OutputStream))
                {
                    response.StatusCode = 200;
                    response.Headers.Add("Access-Control-Allow-Origin", "*");
                    response.ContentType     = "application/json";
                    response.ContentEncoding = Encoding.UTF8;

                    writer.WriteLine(msg);
                    writer.Close();
                    response.Close();
                }
            }
            catch (Exception exception)
            {
            }
        }
Esempio n. 4
0
 public static void SendResponse(HttpListenerResponse response, byte[] buffer)
 {
     response.ContentLength64 = buffer.Length;
     response.OutputStream.Write(buffer, 0, buffer.Length);
     response.OutputStream.Close();
     response.Close();
 }
Esempio n. 5
0
        public static void SendResponse(HttpListenerResponse response, string str)
        {
            var result = Encoding.UTF8.GetBytes(str);

            response.ContentLength64 = result.Length;
            response.OutputStream.Write(result, 0, result.Count());
            response.Close();
        }
Esempio n. 6
0
        // Send HTTP Response
        private void sendHTMLResponse(string request)
        {
            try
            {
                // Get the file content of HTTP Request
                FileStream   fs = new FileStream(request, FileMode.Open, FileAccess.Read, FileShare.None);
                BinaryReader br = new BinaryReader(fs);

                // The content Length of HTTP Request
                byte[] respByte = new byte[(int)fs.Length];
                br.Read(respByte, 0, (int)fs.Length);

                br.Close();
                fs.Close();

                // 以Response屬性取得HTTP伺服端的輸出串流,則HTTP伺服端之回應
                httpResponse = httpContext.Response;

                // HTTP回應資料內容的大小
                httpResponse.ContentLength64 = respByte.Length;

                // HTTP回應資料內容的MIME格式
                httpResponse.ContentType = getContentType(request);

                // 取得伺服端HTTP回應之資料串流
                System.IO.Stream output = httpResponse.OutputStream;

                // 回應HTML網頁內容至用戶端瀏覽器
                output.Write(respByte, 0, respByte.Length);

                output.Close();
                httpResponse.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.StackTrace.ToString());

                if (httpResponse != null)
                {
                    httpResponse.Close();
                }
            }
        }
Esempio n. 7
0
 static void ResponseWrite(string type, string msg, System.Net.HttpListenerResponse response)
 {
     //使用Writer输出http响应代码
     using (System.IO.StreamWriter writer = new System.IO.StreamWriter(response.OutputStream, new UTF8Encoding()))
     {
         response.ContentType = type + ";charset=utf-8";
         writer.WriteLine(msg);
         writer.Close();
         response.Close();
     }
 }
Esempio n. 8
0
 public static void SendResponse(HttpListenerResponse response, string content)
 {
     byte[] buffer = Encoding.UTF8.GetBytes(content);
     response.StatusCode = (int) HttpStatusCode.OK;
     response.StatusDescription = "OK";
     response.ContentType = "text/html; charset=UTF-8";
     response.ContentLength64 = buffer.Length;
     response.ContentEncoding = Encoding.UTF8;
     response.OutputStream.Write(buffer, 0, buffer.Length);
     response.OutputStream.Close();
     response.Close();
 }
Esempio n. 9
0
        public void authenticate(HttpListenerRequest req, HttpListenerResponse res, HTTPSession session)
        {
            // use the session object to store state between requests
            session["nonce"] = RandomString();
            session["state"] = RandomString();

            // TODO make authentication request

            // TODO insert the redirect URL
            string login_url = null;
            res.Redirect(login_url);
            res.Close();
        }
Esempio n. 10
0
 public static void SendResponse(HttpListenerResponse response, string pluginName, string content)
 {
     CoreManager.ServerCore.GetStandardOut().PrintDebug("WebAdmin Response [" + pluginName + "]: " + content);
     byte[] buffer = Encoding.UTF8.GetBytes(content);
     response.StatusCode = (int) HttpStatusCode.OK;
     response.StatusDescription = "OK";
     response.ContentType = "text/html; charset=UTF-8";
     response.ContentLength64 = buffer.Length;
     response.ContentEncoding = Encoding.UTF8;
     response.AddHeader("plugin-name", pluginName);
     response.OutputStream.Write(buffer, 0, buffer.Length);
     response.OutputStream.Close();
     response.Close();
 }
Esempio n. 11
0
 /// <summary>
 /// http响应
 /// </summary>
 /// <param name="msg"></param>
 /// <param name="response"></param>
 /// <param name="type"></param>
 public void ResponseWrite(string msg, System.Net.HttpListenerResponse response, string type = "text/plain")
 {
     try
     {
         //使用Writer输出http响应代码
         using (System.IO.StreamWriter writer = new System.IO.StreamWriter(response.OutputStream, new UTF8Encoding()))
         {
             response.ContentType = type + ";charset=utf-8";
             writer.WriteLine(msg);
             writer.Close();
             response.Close();
         }
     }
     catch (Exception exception)
     {
     }
 }
Esempio n. 12
0
        public void SendResponse(HttpListenerRequest request, HttpListenerResponse response)
        {
            var stream = new FileLoader(request.Url.AbsolutePath).LoadStream();

            response.ContentLength64 = stream.Length;
            response.SendChunked = false;
            response.ContentType = request.ContentType;
            response.AddHeader("Content-disposition", "attachment; filename=" + request.RawUrl.Remove(0, 1));

            writeTo(stream, response.OutputStream);

            response.StatusCode = (int)HttpStatusCode.OK;
            response.StatusDescription = "OK";

            stream.Close();
            response.Close();

            Console.WriteLine("200");
        }
Esempio n. 13
0
        public override void OnGetRequest(HttpListenerRequest request, HttpListenerResponse response)
		{
            string url = request.Url.ToString().Remove(0, host.Length - 1);
            if (url.Contains("?v")) {
                url = url.Substring(0, url.IndexOf("?v"));
            }
            string filename = AssetPath + url;

            string responseString = string.Empty;
            if (url.EndsWith("/")) {
                responseString = "<html><body><h1>SimpleFramework WebServer 0.1.0</h1>";
                responseString += "Current Time: " + DateTime.Now.ToString() + "<br>";
                responseString += "url : " + request.Url + "<br>";
                responseString += "Asset Path: " + filename;

                goto label;
            } else {
                if (File.Exists(filename)) {
                    using (Stream fs = File.Open(filename, FileMode.Open)) {
                        response.ContentLength64 = fs.Length;
                        response.ContentType = GetMimeType(filename) + "; charset=UTF-8";

                        fs.CopyTo(response.OutputStream);
                        response.OutputStream.Flush();
                        response.Close(); return;
                    }
                } else {
                    responseString = "<h1>404</h1>";
                    goto label;
                }
            }
            label: 
                try {
                    response.ContentLength64 = Encoding.UTF8.GetByteCount(responseString);
                    response.ContentType = "text/html; charset=UTF-8";
                } finally {
                    Stream output = response.OutputStream;
                    StreamWriter writer = new StreamWriter(output);
                    writer.Write(responseString);
                    writer.Close();
                }
        }
Esempio n. 14
0
        private void UpdateEmployee(HttpListenerRequest request, HttpListenerResponse response)
        {
            // Deserialize Employee object.
            string body = String.Empty;
            using (StreamReader reader = new StreamReader(request.InputStream))
            {
                body = reader.ReadToEnd();
            }

            Employee employee = null;
            try
            {
                if (_dataFormat == "application/xml")
                {
                    employee = UtilityXml.DeserializeXml<Employee>(body);
                }
                else if (_dataFormat == "application/json")
                {
                    employee = UtilityJson.DeserializeJson<Employee>(body);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(@"ERROR: Failed to deserialize the Employee object - {ex.Message}");
            }

            if (employee == null)
            {
                response.StatusCode = 400;
                response.Close();
                return;
            }

            // Perform the actual update.
            _repository.Update(employee);

            // Construct and send the response.
            response.StatusCode = 200;
            response.Close();

            Console.WriteLine(@"POST: Updated employee with ID {employee.EmployeeId}");
        }
        private HttpListener OnBeginGetContextReceived(IAsyncResult result)
        {
            if (_response != null)
            {
                try
                {
                    _response.Close();
                    _response = null;
                }
                catch
                { }
            }

            var context = _listener.EndGetContext(result);
            var request = context.Request;

            var url = request.Url;
            //Console.WriteLine("streaming request: " + request.Url);

            lock (_gate)
            {
                _response = context.Response;
            }
            try
            {
                SendClusterData();
            }
            catch(Exception e)
            {
                Console.WriteLine("Error sending cluster data");
                Console.WriteLine(e);

                _response.Close();
                _response = null;
            }

            return _listener;
        }
        private void DisposeCore()
        {
            byte[]       bytes   = null;
            MemoryStream ms      = GetHeaders(true);
            bool         chunked = _response.SendChunked;

            if (_stream.CanWrite)
            {
                try
                {
                    if (ms != null)
                    {
                        long start = ms.Position;
                        if (chunked && !_trailer_sent)
                        {
                            bytes       = GetChunkSizeBytes(0, true);
                            ms.Position = ms.Length;
                            ms.Write(bytes, 0, bytes.Length);
                        }
                        InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start));
                        _trailer_sent = true;
                    }
                    else if (chunked && !_trailer_sent)
                    {
                        bytes = GetChunkSizeBytes(0, true);
                        InternalWrite(bytes, 0, bytes.Length);
                        _trailer_sent = true;
                    }
                }
                catch (HttpListenerException)
                {
                    // Ignore error due to connection reset by peer
                }
            }
            _response.Close();
        }
Esempio n. 17
0
 public override void Close()
 {
     if (disposed == false)
     {
         disposed = true;
         byte []      bytes   = null;
         MemoryStream ms      = GetHeaders(true);
         bool         chunked = response.SendChunked;
         if (stream.CanWrite)
         {
             try {
                 if (ms != null)
                 {
                     long start = ms.Position;
                     if (chunked && !trailer_sent)
                     {
                         bytes       = GetChunkSizeBytes(0, true);
                         ms.Position = ms.Length;
                         ms.Write(bytes, 0, bytes.Length);
                     }
                     InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start));
                     trailer_sent = true;
                 }
                 else if (chunked && !trailer_sent)
                 {
                     bytes = GetChunkSizeBytes(0, true);
                     InternalWrite(bytes, 0, bytes.Length);
                     trailer_sent = true;
                 }
             } catch (IOException) {
                 // Ignore error due to connection reset by peer
             }
         }
         response.Close();
     }
 }
Esempio n. 18
0
 public void SendNotModified(HttpListenerResponse response)
 {
     response.StatusCode = (int)HttpStatusCode.NotModified;
     response.Close();
 }
Esempio n. 19
0
 void WriteAndFlushResponse(HttpListenerResponse response, byte[] buffer)
 {
     response.ContentLength64 = buffer.Length;
     using(Stream output = response.OutputStream)
     {
         output.Write(buffer, 0, buffer.Length);
     }
     response.Close();
 }
Esempio n. 20
0
		private static void FinalizeAcceptedResponse(HttpListenerRequest request, HttpListenerResponse response, RevaleeTask task)
		{
			string remoteAddress = request.RemoteEndPoint.Address.ToString();

			try
			{
				response.StatusCode = 200;
				response.StatusDescription = "OK";
				byte[] confirmation_number = Encoding.UTF8.GetBytes(task.CallbackId.ToString());
				response.ContentLength64 = confirmation_number.LongLength;
				response.OutputStream.Write(confirmation_number, 0, confirmation_number.Length);
			}
			finally
			{
				response.Close();
			}

			Supervisor.Telemetry.RecordAcceptedRequest();
			Supervisor.LogEvent(string.Format("Request accepted for {0} @ {1:d} {1:t} from {2}. [{3}]", task.CallbackUrl.OriginalString, task.CallbackTime, remoteAddress, task.CallbackId), TraceEventType.Verbose);
		}
Esempio n. 21
0
		private static void FinalizeRejectedResponse(HttpListenerRequest request, HttpListenerResponse response, int statusCode, string statusDescription, Uri callbackUrl)
		{
			string remoteAddress = request.RemoteEndPoint.Address.ToString();

			try
			{
				response.StatusCode = statusCode;
				response.StatusDescription = statusDescription;
			}
			finally
			{
				response.Close();
			}

			Supervisor.Telemetry.RecordRejectedRequest();
			if (callbackUrl == null)
			{
				Supervisor.LogEvent(string.Format("Request rejected from {0} due to: {1}.", remoteAddress, statusDescription), TraceEventType.Verbose);
			}
			else
			{
				Supervisor.LogEvent(string.Format("Request rejected for {0} from {1} due to: {2}.", callbackUrl.OriginalString, remoteAddress, statusDescription), TraceEventType.Verbose);
			}
		}
Esempio n. 22
0
        /// <summary>
        /// Http servers message processor. This method reads a message from a socket and calls downstream
        /// processes that parse the request, dispatch to a method and returns a response.
        /// </summary>
        /// <remarks>The parameters should always be set to null. See IWsTransportMessageProcessor for details.</remarks>
        public void ProcessRequest()
        {
            try
            {   // Retrieval of Request causes reading of data from network and parsing request.
                m_httpRequest = m_httpContext.Request;
                m_httpResponse = m_httpContext.Response;

                System.Ext.Console.Write("Request From: " + m_httpRequest.RemoteEndPoint.ToString());

                // Checks and process headers important for DPWS
                if (!ProcessKnownHeaders())
                {
                    return;
                }

                byte[] messageBuffer = null;

                int messageLength = (int)m_httpRequest.ContentLength64;
                if (messageLength > 0)
                {
                    // If there is content length for the message, we read it complete.
                    messageBuffer = new byte[messageLength];

                    for ( int offset = 0; offset < messageLength; )
                    {
                        int noRead = m_httpRequest.InputStream.Read(messageBuffer, offset, messageLength - offset);
                        if (noRead == 0)
                        {
                            throw new IOException("Http server got only " + offset + " bytes. Expected to read " + messageLength + " bytes.");
                        }

                        offset += noRead;
                    }
                }
                else
                {
                    // In this case the message is chunk encoded, but m_httpRequest.InputStream actually does processing.
                    // So we we read until zero bytes are read.
                    bool readComplete = false;
                    int bufferSize = ReadPayload;
                    messageBuffer = new byte[bufferSize];
                    int offset = 0;
                    while (!readComplete)
                    {
                        while (offset < ReadPayload)
                        {
                            int noRead = m_httpRequest.InputStream.Read(messageBuffer, offset, messageLength - offset);
                            // If we read zero bytes - means this is end of message. This is how InputStream.Read for chunked encoded data.
                            if (noRead == 0)
                            {
                                readComplete = true;
                                break;
                            }

                            offset += noRead;
                        }

                        // If read was not complete - increase the buffer.
                        if (!readComplete)
                        {
                            bufferSize += ReadPayload;
                            byte[] newMessageBuf = new byte[bufferSize];
                            Array.Copy(messageBuffer, newMessageBuf, offset);
                            messageBuffer = newMessageBuf;
                        }
                    }

                    m_chunked = false;
                }

                // Process the soap request.
                try
                {
                    // Message byte buffer
                    byte[] soapRequest;
                    byte[] soapResponse = null;

                    // If this is an mtom message process attachments, else process the raw message
                    if (m_mtomHeader != null)
                    {
                        // Process the message
                        WsMessage response = ProcessRequestMessage(new WsMessage(messageBuffer, m_mtomHeader.boundary, m_mtomHeader.start));
                        if (response != null)
                        {

                            soapResponse = response.Message;
                            if (response.MessageType == WsMessageType.Mtom)
                            {
                                m_mtomHeader.boundary = response.BodyParts.Boundary;
                                m_mtomHeader.start = response.BodyParts.Start;
                            }
                        }
                    }
                    else
                    {
                        // Convert the message buffer to a byte array
                        soapRequest = messageBuffer;

                        // Performance debuging
                        DebugTiming timeDebuger = new DebugTiming();
                        timeDebuger.ResetStartTime("***Request Debug timer started");

                        // Process the message
                        WsMessage response = ProcessRequestMessage(new WsMessage(soapRequest));
                        if (response != null)
                            soapResponse = response.Message;

                        // Performance debuging
                        timeDebuger.PrintElapsedTime("***ProcessMessage Took");
                    }

                    // Display remote endpoint
                    System.Ext.Console.Write("Response To: " + m_httpRequest.RemoteEndPoint.ToString());

                    // Send the response
                    SendResponse(soapResponse);
                }
                catch (Exception e)
                {
                    System.Ext.Console.Write(e.Message + " " + e.InnerException);
                    SendError(400, "Bad Request");
                }
            }
            catch
            {
                System.Ext.Console.Write("Invalid request format. Request ignored.");
                SendError(400, "Bad Request");
            }
            finally
            {
                m_httpResponse.Close();
            }
        }
Esempio n. 23
0
		private static void FormatJsonResponse(HttpListenerResponse response, string version, string status, string timestamp)
		{
			try
			{
				response.StatusCode = 200;
				response.StatusDescription = "OK";
				response.ContentType = "application/json";

				var messageBuffer = new StringBuilder();
				messageBuffer.Append("{ \"version\": \"");
				messageBuffer.Append(version);
				messageBuffer.Append("\", \"status\": \"");
				messageBuffer.Append(status);
				messageBuffer.Append("\", \"timestamp\": \"");
				messageBuffer.Append(timestamp);
				messageBuffer.Append("\" }");

				byte[] binaryPayload = Encoding.UTF8.GetBytes(messageBuffer.ToString());
				response.ContentLength64 = binaryPayload.LongLength;
				response.OutputStream.Write(binaryPayload, 0, binaryPayload.Length);
			}
			finally
			{
				response.Close();
			}
		}
Esempio n. 24
0
        void HandlePost(HttpListenerResponse response, HttpListenerRequest request)
        {
            using (var reader = new BinaryReader(request.InputStream))
            {
                var receivedTransportMessage = new ReceivedTransportMessage
                    {
                        Id = request.Headers[RebusHttpHeaders.Id],
                        Body = reader.ReadBytes((int) request.ContentLength64)
                    };

                var headers = new Dictionary<string, string>();

                foreach (var rebusHeaderKey in request.Headers.AllKeys.Where(k => k.StartsWith(RebusHttpHeaders.CustomHeaderPrefix)))
                {
                    var value = request.Headers[rebusHeaderKey];
                    var key = rebusHeaderKey.Substring(RebusHttpHeaders.CustomHeaderPrefix.Length);

                    headers.Add(key, value);
                }

                log.Info("Got headers in request: {0}", string.Join(", ", headers.Keys));

                receivedTransportMessage.Headers = headers;

                log.Info("Received message {0}", receivedTransportMessage.Id);

                using (var queue = MsmqMessageQueue.Sender())
                {
                    queue.Send(destinationQueue, receivedTransportMessage.ToForwardableMessage());
                }

                log.Info("Message was sent to {0}", destinationQueue);

                response.StatusCode = (int) HttpStatusCode.OK;
                response.Close();
            }
        }
        public override void Handle(HttpListenerRequest request, HttpListenerResponse response)
        {
            TimeSpan expires = m_NextVendorUpdate - DateTime.Now;
            response.ContentType = "application/json";

            SetCacheHeaders(response.Headers, expires);
            Stream outputStream = PrepareOutputStream(request, response);
            QueryParams queryParams = new QueryParams(request);

            int start = queryParams.Start;
            int end = start + queryParams.Limit;
            List<MyVendorItem> subList;
            string query = queryParams.Query;
            if (query != null && query.Trim().Length != 0)
            {
                subList = m_ItemCache.Get(queryParams.Query) as List<MyVendorItem>;
                if (subList == null)
                {
                    string[] qps = query.Split(' ');
                    IEnumerable<MyVendorItem> results = null;
                    Func<MyVendorItem, bool> currentFunc = null;
                    //FIXME make this more dynamic/cleaner
                    for(int i = 0, j = qps.Length; i < j; i++)
                    {
                        string q = qps[i].Trim();
                        if(q.Length < 3) // ignore queries less than 3 characters
                        {
                            continue;
                        }
                        char first = q[0];
                        if (first == '-')
                        {
                            currentFunc = NotContains(q.Substring(1));
                        }
                        else if (first == '+')
                        {
                            currentFunc = Contains(q.Substring(1));
                        }
                        else
                        {
                            currentFunc = Contains(q);
                        }
                        results = results == null ? m_VendorItems.Where(currentFunc) : results.Where(currentFunc);
                    }
                    subList = results.ToList();
                    m_ItemCache.Add(query, subList, null, m_NextVendorUpdate, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
                }
            }
            else
            {
                subList = m_VendorItems;
            }
            string sort = queryParams.Sort;
            QueryParams.SortDirection dir = queryParams.Direction;
            if (StringUtils.HasText(sort))
            {
                subList = dir.Equals(QueryParams.SortDirection.Ascending) ? subList.OrderBy(p => typeof(MyVendorItem).GetProperty(sort).GetValue(p, null)).ToList() : subList.OrderByDescending(p => typeof(MyVendorItem).GetProperty(sort).GetValue(p, null)).ToList();
            }
            int totalCount = subList.Count;
            if (start > subList.Count || subList.Count == 0)
            {
                sendResponse(outputStream, subList, queryParams.Callback, totalCount);
                return;
            }
            if (end > subList.Count)
            {
                end = subList.Count;
            }
            subList = subList.GetRange(start, end - start);
            sendResponse(outputStream, subList, queryParams.Callback, totalCount);

            response.StatusCode = 200;
            response.StatusDescription = "OK";
            response.Close();
        }
Esempio n. 26
0
		void Exception (HttpListenerResponse response, Exception exception)
		{
			var id = CreateExceptionId ();
			exceptions [id] = exception;
			response.AddHeader (ExceptionHeaderName, id.ToString ());
			if (exception == null)
				return;
			response.StatusCode = 500;
			using (var writer = new StreamWriter (response.OutputStream)) {
				writer.WriteLine (string.Format ("EXCEPTION: {0}", exception));
			}
			response.Close ();
		}
Esempio n. 27
0
        public override Task Post(HttpListenerResponse response, string relativePath, UrlEncodedMessage message)
        {
            var payload = message["payload"];
            if( payload == null ) {
                response.StatusCode = 500;
                response.Close();
                return "".AsResultTask();
            }

            var result = Task.Factory.StartNew( () => {
                try {
                    dynamic json = JObject.Parse(payload);
                    Console.WriteLine("MSG Process begin {0}", json.commits.Count);

                    var count = json.commits.Count;
                    var doSiteRebuild = false;
                    for (int i = 0; i < count; i++) {
                        var username = json.commits[i].author.username.Value;
                        var commitMessage = json.commits[i].message.Value;
                        var repository = json.repository.name.Value;

                        var url = (string)json.commits[i].url.Value;
                        if (repository == "coapp.org") {
                            doSiteRebuild = true;
                        }

                        Bitly.Shorten(url).ContinueWith( (bitlyAntecedent) => {
                            var commitUrl = bitlyAntecedent.Result;

                            var handle = _aliases.ContainsKey(username) ? _aliases[username] : username;
                            var sz = repository.Length + handle.Length + commitUrl.Length + commitMessage.Length + 10;
                            var n = 140 - sz;

                            if (n < 0) {
                                commitMessage = commitMessage.Substring(0, (commitMessage.Length + n) - 3) + "...";
                            }
                            _tweeter.Tweet("{0} => {1} via {2} {3}", repository, commitMessage, handle, commitUrl);
                            Console.WriteLine("{0} => {1} via {2} {3}", repository, commitMessage, handle, commitUrl);
                        });

                    }
                    // just rebuild the site once for a given batch of rebuild commit messages.
                    if( doSiteRebuild) {
                        Task.Factory.StartNew(() => {
                            try {
                                Console.WriteLine("Rebuilding website.");
                                Environment.CurrentDirectory = Environment.GetEnvironmentVariable("STORAGE");
                                if (_cmdexe.Exec(@"/c rebuild_site.cmd") != 0) {
                                    Console.WriteLine("Site rebuild result:\r\n{0}", _cmdexe.StandardOut);
                                    return;
                                }

                                Console.WriteLine("Rebuilt Website.");
                            } catch( Exception e ) {
                                Listener.HandleException(e);
                            }

                        });
                    }
                } catch(Exception e) {
                    Console.WriteLine("Error handling uploaded package: {0} -- {1}\r\n{2}", e.GetType(), e.Message, e.StackTrace);
                    Listener.HandleException(e);
                    response.StatusCode = 500;
                    response.Close();
                }
            }, TaskCreationOptions.AttachedToParent);

            result.ContinueWith( antecedent => {
                if (result.IsFaulted) {
                    var e = antecedent.Exception.InnerException;
                    Console.WriteLine("Error handling commit message: {0} -- {1}\r\n{2}", e.GetType(), e.Message, e.StackTrace);
                    Listener.HandleException(e);
                    response.StatusCode = 500;
                    response.Close();
                }
            }, TaskContinuationOptions.OnlyOnFaulted);

            return result;
        }
Esempio n. 28
0
        public void ShowError(ref HttpListenerResponse hlrs, int error)
        {
            hlrs.StatusCode = error;
            switch (error) {
                case 403: hlrs.StatusDescription = "File Not found.";   break;
                case 404: hlrs.StatusDescription = "Forbidden.";        break;
                default:  hlrs.StatusDescription = "Unknown!.";         break;
            }

            try {
                using ( StreamReader fs = new StreamReader( cfg.ConfigPath + error + ".cfg" ) ) {
                    string content = fs.ReadToEnd();
                    hlrs.OutputStream.Write( utf8.GetBytes( content ), 0, content.Length );
                }
            }
            catch ( FileNotFoundException ) {
                string s = "IRONY! Error grabbing error page ( " + error + " )";
                hlrs.OutputStream.Write( utf8.GetBytes( s ), 0, s.Length );
            }
            hlrs.Close();
        }
Esempio n. 29
0
 public void SendResponse(HttpListenerRequest request, HttpListenerResponse response)
 {
     response.StatusCode = 404;
     Console.WriteLine("404");
     response.Close();
 }
Esempio n. 30
0
        /*
        public override Task Post(HttpListenerResponse response, string relativePath, Toolkit.Pipes.UrlEncodedMessage message) {
            var fileData = message["file"].ToString();
            if( string.IsNullOrEmpty(fileData) ) {
                response.StatusCode = 500;
                response.Close();
                return "".AsResultTask();
            }

            var data = fileData.UrlDecode();
        }
        */
        public override Task Put(HttpListenerResponse response, string relativePath, byte[] data)
        {
            if( data.Length < 1 ) {
                response.StatusCode = 500;
                response.Close();
                return "".AsResultTask();
            }

            var result = Task.Factory.StartNew(
                () => {
                    var filename = "UploadedFile.bin".GenerateTemporaryFilename();
                    File.WriteAllBytes(filename, data);

                    PackageManager.Instance.ConnectAndWait("RepositoryService", null, 5000);

                    // verify that the file is actually a valid package
                    PackageManager.Instance.GetPackages(filename, messages: RepositoryServiceMain._messages).ContinueWith(
                        antecedent => {
                            if( antecedent.IsFaulted ) {
                                Console.WriteLine("Fault occurred after upload: {0}", filename);
                                filename.TryHardToDelete();
                                response.StatusCode = 400;
                                response.Close();
                                return;
                            }

                            if( antecedent.IsCanceled) {
                                Console.WriteLine("Request was cancelled");
                                filename.TryHardToDelete();
                                response.StatusCode = 400;
                                response.Close();
                                return;
                            }

                            var pkg = antecedent.Result.FirstOrDefault();
                            if( pkg == null ) {
                                Console.WriteLine("File uploaded is not recognized as a package: {0}", filename);
                                filename.TryHardToDelete();
                                response.StatusCode = 400;
                                response.Close();
                                return;
                            }

                            var targetFilename = (pkg.CanonicalName + ".msi").ToLower();
                            var location = new Uri(_packagePrefixUrl, targetFilename);
                            PackageManager.Instance.GetPackageDetails(pkg.CanonicalName, RepositoryServiceMain._messages).Wait();

                            //copy the package to the destination
                            if (_cloudFileSystem != null) {
                                // copy file to azure storage
                                _cloudFileSystem.WriteBlob(_packageStorageFolder, targetFilename, filename, false, (progress) => {
                                    ConsoleExtensions.PrintProgressBar("{0} => {1}".format(pkg.CanonicalName, _packageStorageFolder), progress);
                                });

                                if (pkg.Name.Equals("coapp.toolkit", StringComparison.CurrentCultureIgnoreCase) && pkg.PublicKeyToken.Equals("1e373a58e25250cb", StringComparison.CurrentCultureIgnoreCase)) {
                                    // update the default toolkit too
                                    _cloudFileSystem.WriteBlob(_packageStorageFolder, "coapp.toolkit.msi", filename, false, (progress) => {
                                        ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation, _packageStorageFolder), progress);
                                    });
                                    Console.WriteLine();
                                }

                                if (pkg.Name.Equals("coapp.devtools", StringComparison.CurrentCultureIgnoreCase) && pkg.PublicKeyToken.Equals("1e373a58e25250cb", StringComparison.CurrentCultureIgnoreCase)) {
                                    // update the default toolkit too
                                    _cloudFileSystem.WriteBlob(_packageStorageFolder, "coapp.devtools.msi", filename, false, (progress) => {
                                        ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation, _packageStorageFolder), progress);
                                    });
                                    Console.WriteLine();
                                }

                                // remove the local file, since we don't need it anymore.
                                filename.TryHardToDelete();

                                Console.WriteLine();
                            } else {
                                var targetLocation = Path.Combine(_packageStorageFolder, targetFilename);
                                if( File.Exists(targetLocation)) {
                                    targetLocation.TryHardToDelete();
                                }

                                File.Copy(filename, targetLocation);
                            }

                            lock(typeof(UploadedFileHandler)) {
                                // update the feed
                                var Feed = new AtomFeed();

                                if (!string.IsNullOrEmpty(_localfeedLocation) && File.Exists(_localfeedLocation)) {
                                    var originalFeed = AtomFeed.LoadFile(_localfeedLocation);
                                    Feed.Add(originalFeed.Items.Where(each => each is AtomItem).Select(each => each as AtomItem));
                                }

                                if (!string.IsNullOrEmpty(pkg.PackageItemText)) {
                                    var item = SyndicationItem.Load<AtomItem>(XmlReader.Create(new StringReader(pkg.PackageItemText)));

                                    var feedItem = Feed.Add(item);

                                    // first, make sure that the feeds contains the intended feed location.
                                    if (feedItem.Model.Feeds == null) {
                                        feedItem.Model.Feeds = new List<Uri>();
                                    }

                                    if (!feedItem.Model.Feeds.Contains(_canonicalFeedUrl)) {
                                        feedItem.Model.Feeds.Insert(0, _canonicalFeedUrl);
                                    }

                                    if (feedItem.Model.Locations == null) {
                                        feedItem.Model.Locations = new List<Uri>();
                                    }

                                    if (!feedItem.Model.Locations.Contains(location)) {
                                        feedItem.Model.Locations.Insert(0, location);
                                    }
                                }

                                Feed.Save(_localfeedLocation);
                                if (_cloudFileSystem != null) {
                                    _cloudFileSystem.WriteBlob(_packageStorageFolder, Path.GetFileName(_localfeedLocation).ToLower() , _localfeedLocation, false, (progress) => {
                                        ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation, _packageStorageFolder), progress);
                                    });
                                    Console.WriteLine();

                                    _cloudFileSystem.WriteBlob(_packageStorageFolder, Path.GetFileName(_localfeedLocation).ToLower()+".gz", _localfeedLocation, true, (progress) => {
                                        ConsoleExtensions.PrintProgressBar("{0} => {1}".format(_localfeedLocation+".gz", _packageStorageFolder), progress);
                                    });
                                    Console.WriteLine();

                                }
                            }

                            // Advertise the package on twitter
                            if (_tweeter != null) {
                                // pkg.Name
                                Bitly.Shorten(location.AbsoluteUri).ContinueWith(
                                    (x) => {
                                        var name = "[{0}-{1}-{2}]".format(pkg.Name, pkg.Version, pkg.Architecture);

                                        var summary = pkg.Summary;
                                        var l1 = 138 - (name.Length + x.Result.Length);
                                        if( summary.Length > l1 ) {
                                            summary = summary.Substring(0, l1 - 1) + "\u2026";
                                        }
                                        var text = "{0} {1} {2}".format(name, summary, x.Result);
                                        Console.WriteLine("Tweet: {0}",text);
                                        _tweeter.Tweet(text);
                                    });
                            }

                            response.StatusCode = 200;
                            response.Close();
                        }, TaskContinuationOptions.AttachedToParent);

                });

            result.ContinueWith(
                antecedent => {
                    if (result.IsFaulted) {
                        var e = antecedent.Exception.InnerException;
                        Console.WriteLine("Error handling uploaded package: {0} -- {1}\r\n{2}", e.GetType(), e.Message, e.StackTrace);
                        response.StatusCode = 500;
                        response.Close();
                    }
                }, TaskContinuationOptions.OnlyOnFaulted);

            return result;
        }
Esempio n. 31
0
 /// <summary>
 /// Writes status page to a browser
 /// </summary>
 private void WriteStatusPage(HttpListenerResponse response)
 {
     try
     {
         StringBuilder html = new StringBuilder();
         //setup html doc
         html.Append(String.Format("<html><body><h1>NRobotRemote</h1><p><table><tr><td>Version</td><td>{0}</td></tr></table><h2>Available Keywords</h2>",Assembly.GetExecutingAssembly().GetName().Version));
         //per map html
         foreach(KeywordMap map in _service._keywordmaps)
         {
             html.Append(map.GetHTMLDoc());
         }
         //finish html
         html.Append("</body></html>");
         response.StatusCode = 200;
         byte[] buffer = System.Text.Encoding.UTF8.GetBytes(html.ToString());
         response.OutputStream.Write(buffer,0,buffer.Length);
     }
     catch (Exception e)
     {
         log.Error(e.ToString());
         response.StatusCode = 500;
     }
     response.Close();
 }
Esempio n. 32
0
		void Error (HttpListenerResponse response, string format, params object[] args)
		{
			response.StatusCode = 500;
			using (var writer = new StreamWriter (response.OutputStream)) {
				writer.WriteLine (format, args);
			}
			response.Close ();
		}
Esempio n. 33
0
    private void ServeResourceFile(HttpListenerResponse response, string name, 
      string ext) 
    {
      // resource names do not support the hyphen
      name = "OpenHardwareMonitor.Resources." + 
        name.Replace("custom-theme", "custom_theme");

      string[] names =
        Assembly.GetExecutingAssembly().GetManifestResourceNames();
      for (int i = 0; i < names.Length; i++) {
        if (names[i].Replace('\\', '.') == name) {
          using (Stream stream = Assembly.GetExecutingAssembly().
            GetManifestResourceStream(names[i])) {
            response.ContentType = GetcontentType("." + ext);
            response.ContentLength64 = stream.Length;
            byte[] buffer = new byte[512 * 1024];
            int len;
            try {
              Stream output = response.OutputStream;
              while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) {
                output.Write(buffer, 0, len);
              }
              output.Flush();
              output.Close();              
              response.Close();
            } catch (HttpListenerException) { 
            } catch (InvalidOperationException) { 
            }
            return;
          }          
        }
      }

      response.StatusCode = 404;
      response.Close();
    }
Esempio n. 34
0
    private void ServeResourceImage(HttpListenerResponse response, string name) {
      name = "OpenHardwareMonitor.Resources." + name;

      string[] names =
        Assembly.GetExecutingAssembly().GetManifestResourceNames();
      for (int i = 0; i < names.Length; i++) {
        if (names[i].Replace('\\', '.') == name) {
          using (Stream stream = Assembly.GetExecutingAssembly().
            GetManifestResourceStream(names[i])) {

            Image image = Image.FromStream(stream);
            response.ContentType = "image/png";
            try {
              Stream output = response.OutputStream;
              using (MemoryStream ms = new MemoryStream()) {
                image.Save(ms, ImageFormat.Png);
                ms.WriteTo(output);
              }
              output.Close();
            } catch (HttpListenerException) {              
            }
            image.Dispose();
            response.Close();
            return;
          }
        }
      }

      response.StatusCode = 404;
      response.Close();
    }
Esempio n. 35
0
    private void SendJSON(HttpListenerResponse response) {

      string JSON = "{\"id\": 0, \"Text\": \"Sensor\", \"Children\": [";
      nodeCount = 1;
      JSON += GenerateJSON(root);
      JSON += "]";
      JSON += ", \"Min\": \"Min\"";
      JSON += ", \"Value\": \"Value\"";
      JSON += ", \"Max\": \"Max\"";
      JSON += ", \"ImageURL\": \"\"";
      JSON += "}";

      var responseContent = JSON;
      byte[] buffer = Encoding.UTF8.GetBytes(responseContent);

      response.AddHeader("Cache-Control", "no-cache");

      response.ContentLength64 = buffer.Length;
      response.ContentType = "application/json";

      try {
        Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);
        output.Close();
      } catch (HttpListenerException) {
      }

      response.Close();
    }
Esempio n. 36
0
        static void HandleServerError(HttpListenerResponse response, Exception e)
        {
            log.Error(e, "An error occurred while handling HTTP request");

            response.StatusCode = (int) HttpStatusCode.InternalServerError;
            response.ContentEncoding = Encoding;
            response.ContentType = Encoding.WebName;

            var bytes = Encoding.GetBytes(e.ToString());
            response.ContentLength64 = bytes.Length;
            response.OutputStream.Write(bytes, 0, bytes.Length);

            response.Close();
        }
Esempio n. 37
0
        static void WriteAndCloseResponse(HttpResponse httpResp, HttpListenerResponse respCtx)
        {
            try
            {
                respCtx.StatusCode = (int)httpResp.StatusCode;
                respCtx.StatusDescription = httpResp.StatusDescription;
                respCtx.ContentType = httpResp.ContentType;

                if (httpResp.Headers != null && httpResp.Headers.Count > 0)
                {
                    foreach (var kvp in httpResp.Headers)
                    {
                        respCtx.Headers[kvp.Key] = kvp.Value;
                    }
                }

                var body = httpResp.Body;
                if (body != null && body.Length > 0)
                {
                    respCtx.ContentLength64 = body.Length;
                    respCtx.OutputStream.Write(body, 0, body.Length);
                    respCtx.OutputStream.Flush();
                    respCtx.OutputStream.Close();
                }

                respCtx.Close();
            }
            catch (Exception)
            {
                return;
            }
        }