Пример #1
0
        /// <summary>
        /// Send Http Post Failure Response helper
        /// </summary>
        private void HttpPostFailure(HttpPost httpPost, string faultMessage)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.ExpectationFailed, faultMessage);

            httpPost.ResponsePort.Post(rsp);
        }
Пример #2
0
        /// <summary>
        /// Send Http Post Success Response
        /// </summary>
        private void HttpPostSuccess(HttpPost httpPost)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.OK, _state, _transform);

            httpPost.ResponsePort.Post(rsp);
        }
Пример #3
0
        public virtual IEnumerator <ITask> HttpGetHandler(HttpGet httpGet)
        {
            HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transform);

            httpGet.ResponsePort.Post(rsp);
            yield break;
        }
Пример #4
0
        public void DriveHttpGetHandler(Microsoft.Dss.Core.DsspHttp.HttpGet httpget)
        {
            this.state.DriveState.TimeStamp = DateTime.Now;
            HttpResponseType resp = new HttpResponseType(HttpStatusCode.OK, this.state.DriveState);

            httpget.ResponsePort.Post(resp);
        }
Пример #5
0
        /// <summary>
        /// Send Http Post Failure Response
        /// </summary>
        private void HttpPostFailure(HttpPost httpPost)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.BadRequest, _state, _transform);

            httpPost.ResponsePort.Post(rsp);
        }
Пример #6
0
        /// <summary>
        /// Send Http Post Failure Response
        /// </summary>
        /// <param name="httpPost"></param>
        /// <param name="fault"></param>
        private static void HttpPostFailure(HttpPost httpPost, Fault fault)
        {
            HttpResponseType rsp =
                new HttpResponseType(HttpStatusCode.BadRequest, fault);

            httpPost.ResponsePort.Post(rsp);
        }
Пример #7
0
        public SettingHttpResponseAttribute(HttpResponseType responseType)
        {
            if (responseType == HttpResponseType.Custom)
            {
                throw new ArgumentOutOfRangeException(nameof(responseType), "Invalid constructor for custom range");
            }

            ResponseType = responseType;
        }
        public string MakeHttpRequest(string url, HttpResponseType requestResponseType)
        {
            HttpClient          client   = PrepareHttpClient(requestResponseType);
            HttpResponseMessage response = client.GetAsync(url).Result;

            if (response.IsSuccessStatusCode)
            {
                return(response.Content.ReadAsStringAsync().Result);
            }

            return(null);
        }
Пример #9
0
        public virtual IEnumerator <ITask> HttpGetHandler(HttpGet httpGet)
        {
            HttpListenerRequest  request  = httpGet.Body.Context.Request;
            HttpListenerResponse response = httpGet.Body.Context.Response;

            string path = request.Url.AbsolutePath;

            HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transform);

            httpGet.ResponsePort.Post(rsp);
            yield break;
        }
        public string MakeHttpRequest(string url, HttpResponseType requestResponseType)
        {
            HttpClient client = PrepareHttpClient(requestResponseType);
            HttpResponseMessage response = client.GetAsync(url).Result;

            if (response.IsSuccessStatusCode)
            {
                return response.Content.ReadAsStringAsync().Result;
            }

            return null;
        }
        private HttpClient PrepareHttpClient(HttpResponseType httpResponseType)
        {
            var httpClientHandler = new HttpClientHandler
            {
                Proxy = new WebProxy(settings.ZapProxy, false, new string[] { }),
                UseProxy = true
            };

            var client = new HttpClient(httpClientHandler);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/" + httpResponseType.ToString()));

            return client;
        }
        public virtual IEnumerator <ITask> HttpGetHandler(HttpGet httpGet)
        {
            HttpListenerRequest  request  = httpGet.Body.Context.Request;
            HttpListenerResponse response = httpGet.Body.Context.Response;

            HttpResponseType rsp = null;

            rsp = new HttpResponseType(HttpStatusCode.OK, _state, base.StateTransformPath);
            //rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transformPololuMaestroData);

            httpGet.ResponsePort.Post(rsp);
            yield break;
        }
Пример #13
0
        void HttpGetHandler(HttpGet httpGet)
        {
            HttpListenerRequest  request  = httpGet.Body.Context.Request;
            HttpListenerResponse response = httpGet.Body.Context.Response;

            Stream image = null;

            string path = request.Url.AbsolutePath;

            if (path == _cylinder)
            {
                image = GenerateCylinder();
            }
            else if (path == _top)
            {
                image = GenerateTop(400);
            }
            else if (path.StartsWith(_topw))
            {
                int    width;
                string remain = path.Substring(_topw.Length);

                if (int.TryParse(remain, out width))
                {
                    image = GenerateTop(width);
                }
            }
            else if (path == _root)
            {
                HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK,
                                                            _state,
                                                            //base.StateTransformPath,
                                                            _transform);
                httpGet.ResponsePort.Post(rsp);
            }



            if (image != null)
            {
                SendJpeg(httpGet.Body.Context, image);
            }
            else
            {
                httpGet.ResponsePort.Post(Fault.FromCodeSubcodeReason(
                                              W3C.Soap.FaultCodes.Receiver,
                                              DsspFaultCodes.OperationFailed,
                                              "Unable to generate Image"));
            }
        }
        private HttpClient PrepareHttpClient(HttpResponseType httpResponseType)
        {
            var httpClientHandler = new HttpClientHandler
            {
                Proxy    = new WebProxy(settings.ZapProxy, false, new string[] { }),
                UseProxy = true
            };

            var client = new HttpClient(httpClientHandler);

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/" + httpResponseType.ToString()));

            return(client);
        }
Пример #15
0
 public virtual ActionResult <HttpResponseType <string> > Add(T dto)
 {
     try
     {
         using (ISession session = sessionFactory.OpenSession())
         {
             string obj = session.Save(dto) as string;
             session.Flush();
             return(HttpResponseType.Success(obj));
         }
     }
     catch (Exception ex)
     {
         return(HttpResponseType.Failure <string>(ex.Message, HttpResponseTypeCode.Exception));
     }
 }
Пример #16
0
 public virtual ActionResult <HttpResponseType <bool> > update(T dto)
 {
     try
     {
         using (ISession session = sessionFactory.OpenSession())
         {
             session.Update(dto);
             session.Flush();
             return(HttpResponseType.Success(true));
         }
     }
     catch (Exception ex)
     {
         return(HttpResponseType.Failure <bool>(ex.Message, HttpResponseTypeCode.Exception));
     }
 }
Пример #17
0
 public virtual ActionResult <HttpResponseType <T> > GetById([FromQuery] string id)
 {
     try
     {
         using (ISession session = sessionFactory.OpenSession())
         {
             T obj = session.Get <T>(id);
             if (obj == null)
             {
                 return(HttpResponseType.Failure <T>("id不存在"));
             }
             return(HttpResponseType.Success <T>(obj));
         }
     }
     catch (Exception ex)
     {
         return(HttpResponseType.Failure <T>(ex.Message, HttpResponseTypeCode.Exception));
     }
 }
Пример #18
0
        public virtual ActionResult <HttpResponseType <bool> > DeleteById(string id)
        {
            try
            {
                using (ISession session = sessionFactory.OpenSession())
                {
                    T query = session.Get <T>(id);
                    if (query == null)
                    {
                        return(HttpResponseType.Failure <bool>("id不存在"));
                    }

                    session.Delete(query);
                    session.Flush();
                    return(HttpResponseType.Success(true));
                }
            }
            catch (Exception ex)
            {
                return(HttpResponseType.Failure <bool>(ex.Message, HttpResponseTypeCode.Exception));
            }
        }
Пример #19
0
        public IEnumerator <ITask> DriveHttpGetHandler(Microsoft.Dss.Core.DsspHttp.HttpGet httpget)
        {
            drive.Get get = new drive.Get();

            this.controllerDrivePort.Post(get);

            yield return(get.ResponsePort.Choice());

            drive.DriveDifferentialTwoWheelState newState = (drive.DriveDifferentialTwoWheelState)get.ResponsePort;

            if (newState != null)
            {
                HttpResponseType resp = new HttpResponseType(HttpStatusCode.OK, newState);
                httpget.ResponsePort.Post(resp);
            }
            else
            {
                HttpResponseType resp = new HttpResponseType(HttpStatusCode.InternalServerError, (soap.Fault)get.ResponsePort);
                httpget.ResponsePort.Post(resp);
            }

            yield break;
        }
Пример #20
0
        /// <summary>   Stream file. </summary>
        /// <remarks>   ebrown, 2/15/2011. </remarks>
        /// <exception cref="ArgumentNullException">    Thrown when one or more required arguments are null. </exception>
        /// <exception cref="Exception">                Thrown when exception. </exception>
        /// <param name="requestedResponseType">    Type of the requested response. </param>
        /// <param name="downloadProperties">       The download properties. </param>
        /// <param name="rangeRequests">            The range requests. </param>
        /// <param name="ifRangeEntityTag">         if range entity tag. </param>
        /// <param name="forceDownload">            true to force download. </param>
        /// <returns>   . </returns>
        public StreamWriteStatus StreamFile(HttpResponseType requestedResponseType, StreamLoaderResult downloadProperties, IEnumerable<RangeRequest> rangeRequests, string ifRangeEntityTag, bool forceDownload)
        {
            if (null == downloadProperties) { throw new ArgumentNullException("downloadProperties"); }
            if (null == rangeRequests) { throw new ArgumentNullException("rangeRequests"); }

            try
            {
                string contentType = !string.IsNullOrEmpty(downloadProperties.ContentType) ?
                    downloadProperties.ContentType : MimeTypes.GetMimeTypeForFileExtension(Path.GetExtension(downloadProperties.Metadata.FileName));

                if (forceDownload)
                {
                    this._response.AppendHeader("content-disposition", String.Format(CultureInfo.InvariantCulture, "attachment; filename={0}", downloadProperties.Metadata.FileName));
                }

                bool isMultipart = RangeRequestHelpers.IsMultipartRequest(rangeRequests),
                    isActionableRangeRequest = IsActionableRangeRequest(downloadProperties.Metadata, rangeRequests, ifRangeEntityTag);

                //TODO: is this response.Clear() necessary here?
                this._response.Clear();

                long responseContentLength = CalculateContentLength(downloadProperties.Metadata, rangeRequests, ifRangeEntityTag, contentType, isMultipart);
                this._response.StatusCode = isActionableRangeRequest ? (int)HttpStatusCode.PartialContent : (int)HttpStatusCode.OK;

                if (isActionableRangeRequest && !isMultipart)
                {
                    var first = rangeRequests.First();
                    //must indicate the Response Range of in the initial HTTP Header since this isn't multipart
                    this._response.AppendHeader(HttpHeaderFields.ContentRange.ToEnumValueString(),
                        String.Format(CultureInfo.InvariantCulture, "bytes {0}-{1}/{2}", first.Start, first.End, downloadProperties.Metadata.Size.Value));
                }

                this._response.AppendHeader(HttpHeaderFields.ContentLength.ToEnumValueString(), responseContentLength.ToString(CultureInfo.InvariantCulture));
                //don't go off the DB insert date for last modified b/c the file system file could be older (b/c multiple files records inserted at different dates could share the same physical file)
                if (downloadProperties.Metadata.LastWriteTimeUtc.HasValue)
                    this._response.AppendHeader(HttpHeaderFields.LastModified.ToEnumValueString(), downloadProperties.Metadata.LastWriteTimeUtc.Value.ToString("r", CultureInfo.InvariantCulture));
                this._response.AppendHeader(HttpHeaderFields.AcceptRanges.ToEnumValueString(), "bytes");
                this._response.AppendHeader(HttpHeaderFields.EntityTag.ToEnumValueString(), String.Format(CultureInfo.InvariantCulture, "\"{0}\"", downloadProperties.Metadata.ExpectedMD5));
                //not sure if we should use the Keep-Alive header?
                //this._response.AppendHeader(HttpHeaderFields.HTTP_HEADER_KEEP_ALIVE, "timeout=15, max=30");

                //multipart messages are special -> file's actual mime type written into Response later
                this._response.ContentType = (isMultipart ? MultipartNames.MultipartContentType : contentType);

                //we've dumped our HEAD and can return now
                if (HttpResponseType.HeadOnly == requestedResponseType)
                {
                    // Flush the HEAD information to the client...
                    this._response.Flush();

                    return StreamWriteStatus.SentHttpHead;
                }

                StreamWriteStatus result = BufferStreamToResponse(downloadProperties, rangeRequests, contentType);
                return (StreamWriteStatus.ClientDisconnected == result) ? result : StreamWriteStatus.SentFile;

                //this causes a ThreadAbortException
                //Response.End();
            }
            catch (IOException ex)
            {
                string userName = string.Empty;
                using (var identity = WindowsIdentity.GetCurrent()) { userName = identity.Name; }

                //, this._request.ToLogString()
                log.Error(String.Format(CultureInfo.InvariantCulture, "File read failure for user {0}", userName), ex);
                return StreamWriteStatus.StreamReadError;
            }
            catch (Exception ex)
            {
                HttpException httpEx = ex as HttpException;
                //suck up the remote connection failure
                if ((null != httpEx) && (HttpExceptionErrorCodes.ConnectionAborted == httpEx.ErrorCode))
                    return StreamWriteStatus.ClientDisconnected;

                //bubble up to the caller, and let them log it -- this maintains the identity of our original exception as the innerexception
                throw;
                //log.Error("Unexpected failure for " + WindowsIdentity.GetCurrent().Name, ex);

                //error = "Unexpected File Transfer Error - FileId [" + FileId.ToString() + "] - User Id [" + context.OnyxUser().Identity.OCPUser.Individual.OnyxId.ToString() + "] / Name [" + ((userProperties.Name == null) ? string.Empty : userProperties.Name) + "] / Email [" + ((userProperties.Email == null) ? string.Empty : userProperties.Email) + "]" + Environment.NewLine + "File Path [ " + properties.MappedPath + " ]";
                //return DownloadFileStatus.UnexpectedError;
            }
        }
        public virtual IEnumerator<ITask> HttpGetHandler(HttpGet httpGet)
        {
            HttpListenerRequest request = httpGet.Body.Context.Request;
            HttpListenerResponse response = httpGet.Body.Context.Response;

            HttpResponseType rsp = null;

            rsp = new HttpResponseType(HttpStatusCode.OK, _state, base.StateTransformPath);
            //rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transformPololuMaestroData);

            httpGet.ResponsePort.Post(rsp);
            yield break;
        }
        public void HttpGetHandler(HttpGet httpGet)
        {
            HttpListenerRequest request = httpGet.Body.Context.Request;
            HttpListenerResponse response = httpGet.Body.Context.Response;
            string path = string.Empty;

            Stream image = null;
            Stream text = null;

            if (!_state.Dropping)
            {
                path = request.Url.AbsolutePath;

                //Tracer.Trace("Path: '" + path + "'");

                if (path == _north)
                {
                    image = lastStatusGraphics.northMemory;
                }
                else if (path == _composite)
                {
                    image = lastStatusGraphics.compositeMemory;
                }
                else if (path == _status)
                {
                    image = lastStatusGraphics.statusMemory;
                }
                else if (path == _historySaid)
                {
                    text = lastStatusGraphics.historySaidMemory;
                }
                else if (path == _historyDecisions)
                {
                    text = lastStatusGraphics.historyDecisionsMemory;
                }
                else if (path == _root || path == _root + "/raw")
                {
                    HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, base.StateTransformPath);
                    //HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, getStateTransformPath());
                    httpGet.ResponsePort.Post(rsp);
                    return;
                }
            }

            if (text != null)
            {
                SendHttp(httpGet.Body.Context, text, MediaTypeNames.Text.Html);
            }
            else if (image != null)
            {
                SendHttp(httpGet.Body.Context, image, MediaTypeNames.Image.Jpeg);
            }
            else
            {
                httpGet.ResponsePort.Post(Fault.FromCodeSubcodeReason(
                    W3C.Soap.FaultCodes.Receiver,
                    DsspFaultCodes.OperationFailed,
                    "Unable to generate text or image for path '" + path + "'"));
            }
        }
Пример #23
0
        public void HttpGetHandler(Microsoft.Dss.Core.DsspHttp.HttpGet httpGet)
        {
            HttpListenerRequest request = httpGet.Body.Context.Request;
            HttpListenerResponse response = httpGet.Body.Context.Response;

            Stream image = null;
            bool isMyPath = false;

            string path = request.Url.AbsolutePath;

            //Tracer.Trace("GET: path='" + path + "'");

            if (path.StartsWith(_root))
            {
                path = path.Substring(_root.Length);
                isMyPath = true;
            }
            else if (path.StartsWith(_root1))
            {
                path = path.Substring(_root1.Length);
                isMyPath = true;
            }
            else if (path.StartsWith(_root2))
            {
                path = path.Substring(_root2.Length);
                isMyPath = true;
            }

            if (isMyPath && path.StartsWith("/"))
            {
                path = path.Substring(1);
            }

            if (path == _cylinder)
            {
                image = GenerateCylinder();
            }
            else if (path == _top)
            {
                image = GenerateTop(540);
            }
            else if (path.StartsWith(_topw))
            {
                int width;
                string remain = path.Substring(_topw.Length);

                if (int.TryParse(remain, out width))
                {
                    image = GenerateTop(width);
                }
            }
            else if (path == "" || path == _raw1)
            {
                HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, base.StateTransformPath);
                httpGet.ResponsePort.Post(rsp);
                return;
            }

            if (image != null)
            {
                SendJpeg(httpGet.Body.Context, image);
            }
            else
            {
                httpGet.ResponsePort.Post(Fault.FromCodeSubcodeReason(
                    W3C.Soap.FaultCodes.Receiver,
                    DsspFaultCodes.OperationFailed,
                    "Unable to generate Image for path '" + path + "'"));
            }
        }
Пример #24
0
 /// <summary>
 /// Send Http Post Success Response
 /// </summary>
 /// <param name="httpPost"></param>
 private void HttpPostSuccess(HttpPost httpPost)
 {
     HttpResponseType rsp =
         new HttpResponseType(HttpStatusCode.OK, _state, _transformGpsData);
     httpPost.ResponsePort.Post(rsp);
 }
        public virtual IEnumerator<ITask> HttpGetHandler(HttpGet httpGet)
        {
            HttpListenerRequest request = httpGet.Body.Context.Request;
            HttpListenerResponse response = httpGet.Body.Context.Response;

            HttpResponseType rsp = null;

            string path = request.Url.AbsolutePath.ToLowerInvariant();

            rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transformChrData);
            httpGet.ResponsePort.Post(rsp);
            yield break;
        }
Пример #26
0
 public void BatteryHttpGetHandler(Microsoft.Dss.Core.DsspHttp.HttpGet httpget)
 {
     HttpResponseType resp = new HttpResponseType(HttpStatusCode.OK, this.state.BatteryState);
     httpget.ResponsePort.Post(resp);
 }
Пример #27
0
 /// <summary>
 /// Send Http Post Failure Response
 /// </summary>
 private void HttpPostFailure(HttpPost httpPost)
 {
     HttpResponseType rsp =
         new HttpResponseType(HttpStatusCode.BadRequest, _state, _transform);
     httpPost.ResponsePort.Post(rsp);
 }
Пример #28
0
        public void BatteryHttpGetHandler(Microsoft.Dss.Core.DsspHttp.HttpGet httpget)
        {
            HttpResponseType resp = new HttpResponseType(HttpStatusCode.OK, this.state.BatteryState);

            httpget.ResponsePort.Post(resp);
        }
Пример #29
0
        public void IRSensorsHttpGetHandler(HttpGet httpget)
        {
            HttpResponseType resp = new HttpResponseType(HttpStatusCode.OK, this.state.InfraredSensorState);

            httpget.ResponsePort.Post(resp);
        }
Пример #30
0
        public virtual IEnumerator<ITask> HttpPostHandler(HttpPost httpPost)
        {
            Fault fault = null;
            NameValueCollection parameters = new NameValueCollection();

            ReadFormData readForm = new ReadFormData(httpPost);
            _httpUtilities.Post(readForm);

            // Wait for result
            yield return Arbiter.Choice(
                readForm.ResultPort,
                delegate(NameValueCollection col)
                {
                    parameters = col;
                },
                delegate(Exception e)
                {
                    fault = Fault.FromException(e);
                }
            );

            if(fault != null)
            {
                httpPost.ResponsePort.Post(fault);
                yield break;
            }

            if (!string.IsNullOrEmpty(parameters["NewMode"]))
            {
                int mod = int.Parse(parameters["NewMode"]);
                _biclops.setMode(mod);
            }

            if(!string.IsNullOrEmpty(parameters["pos1"]))
            {
                double newr = double.Parse(parameters["pos1"]);
                _biclops.setJointPosition(0, newr);
            }

            if(!string.IsNullOrEmpty(parameters["pos2"]))
            {
                double newr = double.Parse(parameters["pos2"]);
                _biclops.setJointPosition(1, newr);
            }

            HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transform);
            httpPost.ResponsePort.Post(rsp);

            SaveState(_state);
        }
Пример #31
0
 public HttpStatusCodeException(HttpResponseType statusCode)
 {
     this.StatusCode = (int)statusCode;
 }
        public void HttpGetHandler(Microsoft.Dss.Core.DsspHttp.HttpGet get)
        {
            var rsp = new HttpResponseType(HttpStatusCode.OK, this.state, this.xslttransform);

            get.ResponsePort.Post(rsp);
        }
Пример #33
0
 public HttpStatusCodeException(HttpResponseType statusCode, string message) : base(message)
 {
     this.StatusCode = (int)statusCode;
 }
Пример #34
0
        public virtual IEnumerator<ITask> HttpGetHandler(HttpGet httpGet)
        {
            HttpListenerRequest request = httpGet.Body.Context.Request;
            HttpListenerResponse response = httpGet.Body.Context.Response;

            Stream image = null;
            HttpResponseType rsp = null;

            string path = request.Url.AbsolutePath.ToLowerInvariant();

            if (path.StartsWith(_root, StringComparison.InvariantCultureIgnoreCase))
            {
                if (path.EndsWith(_showTop, StringComparison.InvariantCultureIgnoreCase))
                {
                    image = GenerateTop(800);
                    if (image != null)
                    {
                        SendJpeg(httpGet.Body.Context, image);
                    }
                    else
                    {
                        httpGet.ResponsePort.Post(Fault.FromCodeSubcodeReason(
                            W3C.Soap.FaultCodes.Receiver,
                            DsspFaultCodes.OperationFailed,
                            "Unable to generate Image"));
                    }
                    yield break;
                }
                else if (path.EndsWith(_showMap, StringComparison.InvariantCultureIgnoreCase))
                {
                    rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transformGpsMap);
                    httpGet.ResponsePort.Post(rsp);
                    yield break;
                }
            }

            rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transformGpsData);
            httpGet.ResponsePort.Post(rsp);
            yield break;

        }
Пример #35
0
 public HttpStatusCodeException(HttpResponseType statusCode, Exception inner) : this(statusCode, inner.ToString())
 {
 }
Пример #36
0
 /// <summary>
 /// Send Http Post Failure Response
 /// </summary>
 /// <param name="httpPost"></param>
 /// <param name="fault"></param>
 private static void HttpPostFailure(HttpPost httpPost, Fault fault)
 {
     HttpResponseType rsp =
         new HttpResponseType(HttpStatusCode.BadRequest, fault);
     httpPost.ResponsePort.Post(rsp);
 }
Пример #37
0
 public HttpStatusCodeException(HttpResponseType statusCode, JObject errorObject) : this(statusCode, errorObject.ToString())
 {
     this.ContentType = @"application/json";
 }
Пример #38
0
 public void SonarSensorsHttpGetHandler(HttpGet httpget)
 {
     HttpResponseType resp = new HttpResponseType(HttpStatusCode.OK, this.state.SonarSensorState);
     httpget.ResponsePort.Post(resp);
 }
Пример #39
0
        /// <summary>   Stream file. </summary>
        /// <remarks>   ebrown, 2/15/2011. </remarks>
        /// <exception cref="ArgumentNullException">    Thrown when one or more required arguments are null. </exception>
        /// <exception cref="Exception">                Thrown when exception. </exception>
        /// <param name="requestedResponseType">    Type of the requested response. </param>
        /// <param name="downloadProperties">       The download properties. </param>
        /// <param name="rangeRequests">            The range requests. </param>
        /// <param name="ifRangeEntityTag">         if range entity tag. </param>
        /// <param name="forceDownload">            true to force download. </param>
        /// <returns>   . </returns>
        public StreamWriteStatus StreamFile(HttpResponseType requestedResponseType, StreamLoaderResult downloadProperties, IEnumerable <RangeRequest> rangeRequests, string ifRangeEntityTag, bool forceDownload)
        {
            if (null == downloadProperties)
            {
                throw new ArgumentNullException("downloadProperties");
            }
            if (null == rangeRequests)
            {
                throw new ArgumentNullException("rangeRequests");
            }

            try
            {
                string contentType = !string.IsNullOrEmpty(downloadProperties.ContentType) ?
                                     downloadProperties.ContentType : MimeTypes.GetMimeTypeForFileExtension(Path.GetExtension(downloadProperties.Metadata.FileName));

                if (forceDownload)
                {
                    this._response.AppendHeader("content-disposition", String.Format(CultureInfo.InvariantCulture, "attachment; filename={0}", downloadProperties.Metadata.FileName));
                }

                bool isMultipart = RangeRequestHelpers.IsMultipartRequest(rangeRequests),
                     isActionableRangeRequest = IsActionableRangeRequest(downloadProperties.Metadata, rangeRequests, ifRangeEntityTag);

                //TODO: is this response.Clear() necessary here?
                this._response.Clear();

                long responseContentLength = CalculateContentLength(downloadProperties.Metadata, rangeRequests, ifRangeEntityTag, contentType, isMultipart);
                this._response.StatusCode = isActionableRangeRequest ? (int)HttpStatusCode.PartialContent : (int)HttpStatusCode.OK;

                if (isActionableRangeRequest && !isMultipart)
                {
                    var first = rangeRequests.First();
                    //must indicate the Response Range of in the initial HTTP Header since this isn't multipart
                    this._response.AppendHeader(HttpHeaderFields.ContentRange.ToEnumValueString(),
                                                String.Format(CultureInfo.InvariantCulture, "bytes {0}-{1}/{2}", first.Start, first.End, downloadProperties.Metadata.Size.Value));
                }

                this._response.AppendHeader(HttpHeaderFields.ContentLength.ToEnumValueString(), responseContentLength.ToString(CultureInfo.InvariantCulture));
                //don't go off the DB insert date for last modified b/c the file system file could be older (b/c multiple files records inserted at different dates could share the same physical file)
                if (downloadProperties.Metadata.LastWriteTimeUtc.HasValue)
                {
                    this._response.AppendHeader(HttpHeaderFields.LastModified.ToEnumValueString(), downloadProperties.Metadata.LastWriteTimeUtc.Value.ToString("r", CultureInfo.InvariantCulture));
                }
                this._response.AppendHeader(HttpHeaderFields.AcceptRanges.ToEnumValueString(), "bytes");
                this._response.AppendHeader(HttpHeaderFields.EntityTag.ToEnumValueString(), String.Format(CultureInfo.InvariantCulture, "\"{0}\"", downloadProperties.Metadata.ExpectedMD5));
                //not sure if we should use the Keep-Alive header?
                //this._response.AppendHeader(HttpHeaderFields.HTTP_HEADER_KEEP_ALIVE, "timeout=15, max=30");

                //multipart messages are special -> file's actual mime type written into Response later
                this._response.ContentType = (isMultipart ? MultipartNames.MultipartContentType : contentType);

                //we've dumped our HEAD and can return now
                if (HttpResponseType.HeadOnly == requestedResponseType)
                {
                    // Flush the HEAD information to the client...
                    this._response.Flush();

                    return(StreamWriteStatus.SentHttpHead);
                }

                StreamWriteStatus result = BufferStreamToResponse(downloadProperties, rangeRequests, contentType);
                return((StreamWriteStatus.ClientDisconnected == result) ? result : StreamWriteStatus.SentFile);

                //this causes a ThreadAbortException
                //Response.End();
            }
            catch (IOException ex)
            {
                string userName = string.Empty;
                using (var identity = WindowsIdentity.GetCurrent()) { userName = identity.Name; }

                //, this._request.ToLogString()
                log.Error(String.Format(CultureInfo.InvariantCulture, "File read failure for user {0}", userName), ex);
                return(StreamWriteStatus.StreamReadError);
            }
            catch (Exception ex)
            {
                HttpException httpEx = ex as HttpException;
                //suck up the remote connection failure
                if ((null != httpEx) && (HttpExceptionErrorCodes.ConnectionAborted == httpEx.ErrorCode))
                {
                    return(StreamWriteStatus.ClientDisconnected);
                }

                //bubble up to the caller, and let them log it -- this maintains the identity of our original exception as the innerexception
                throw;
                //log.Error("Unexpected failure for " + WindowsIdentity.GetCurrent().Name, ex);

                //error = "Unexpected File Transfer Error - FileId [" + FileId.ToString() + "] - User Id [" + context.OnyxUser().Identity.OCPUser.Individual.OnyxId.ToString() + "] / Name [" + ((userProperties.Name == null) ? string.Empty : userProperties.Name) + "] / Email [" + ((userProperties.Email == null) ? string.Empty : userProperties.Email) + "]" + Environment.NewLine + "File Path [ " + properties.MappedPath + " ]";
                //return DownloadFileStatus.UnexpectedError;
            }
        }
Пример #40
0
        public void HttpGetHandler(HttpGet get)
        {
            HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, this.state, this.transform);

            get.ResponsePort.Post(rsp);
        }
Пример #41
0
        public void HttpGetHandler(Microsoft.Dss.Core.DsspHttp.HttpGet httpGet)
        {
            HttpListenerRequest  request  = httpGet.Body.Context.Request;
            HttpListenerResponse response = httpGet.Body.Context.Response;

            Stream image    = null;
            bool   isMyPath = false;

            string path = request.Url.AbsolutePath;

            //Tracer.Trace("GET: path='" + path + "'");

            if (path.StartsWith(_root))
            {
                path     = path.Substring(_root.Length);
                isMyPath = true;
            }
            else if (path.StartsWith(_root1))
            {
                path     = path.Substring(_root1.Length);
                isMyPath = true;
            }
            else if (path.StartsWith(_root2))
            {
                path     = path.Substring(_root2.Length);
                isMyPath = true;
            }

            if (isMyPath && path.StartsWith("/"))
            {
                path = path.Substring(1);
            }

            if (path == _cylinder)
            {
                image = GenerateCylinder();
            }
            else if (path == _top)
            {
                image = GenerateTop(540);
            }
            else if (path.StartsWith(_topw))
            {
                int    width;
                string remain = path.Substring(_topw.Length);

                if (int.TryParse(remain, out width))
                {
                    image = GenerateTop(width);
                }
            }
            else if (path == "" || path == _raw1)
            {
                HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, base.StateTransformPath);
                httpGet.ResponsePort.Post(rsp);
                return;
            }

            if (image != null)
            {
                SendJpeg(httpGet.Body.Context, image);
            }
            else
            {
                httpGet.ResponsePort.Post(Fault.FromCodeSubcodeReason(
                                              W3C.Soap.FaultCodes.Receiver,
                                              DsspFaultCodes.OperationFailed,
                                              "Unable to generate Image for path '" + path + "'"));
            }
        }
Пример #42
0
        void HttpGetHandler(HttpGet httpGet)
        {
            HttpListenerRequest request = httpGet.Body.Context.Request;
            HttpListenerResponse response = httpGet.Body.Context.Response;

            Stream image = null;

            string path = request.Url.AbsolutePath;

            if (path == _cylinder)
            {
                image = GenerateCylinder();
            }
            else if (path == _top)
            {
                image = GenerateTop(400);
            }
            else if (path.StartsWith(_topw))
            {
                int width;
                string remain = path.Substring(_topw.Length);

                if (int.TryParse(remain, out width))
                {
                    image = GenerateTop(width);
                }
            }
            else if (path == _root)
            {
                HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK,
                _state,
                //base.StateTransformPath,
                _transform);
                httpGet.ResponsePort.Post(rsp);
            }

            if (image != null)
            {
                SendJpeg(httpGet.Body.Context, image);
            }
            else
            {
                httpGet.ResponsePort.Post(Fault.FromCodeSubcodeReason(
                    W3C.Soap.FaultCodes.Receiver,
                    DsspFaultCodes.OperationFailed,
                    "Unable to generate Image"));
            }
        }
Пример #43
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"
        /// />interface.
        /// </summary>
        /// <remarks>	ebrown, 2/10/2011. </remarks>
        /// <exception cref="ObjectDisposedException">	Thrown when a supplied object has been disposed. </exception>
        /// <exception cref="ArgumentNullException">	Thrown when one or more required arguments are null. </exception>
        /// <param name="context">	An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects
        ///                         (for example, Request, Response, Session, and Server) used to service HTTP requests. </param>
        public override void ProcessRequest(HttpContextBase context)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("this");
            }
            stopwatch.Start();
            //TODO: 5-1-09 -- Response.Redirect doesn't make any sense... maybe we should just give them an 'unauthorized' empty file thing
            if (null == context)
            {
                throw new ArgumentNullException("context");
            }

            this._context = context;
            //assign to local fields for micro-perf since these are virtuals
            this._request  = context.Request;
            this._response = context.Response;

            try
            {
                var method = this._request.HttpMethod;
                //we only accept GET or HEAD - don't log these
                if ((HttpMethodNames.Get.ToEnumValueString() != method) &&
                    (HttpMethodNames.Header.ToEnumValueString() != method))
                {
                    this._response.StatusCode = (int)HttpStatusCode.NotImplemented;
                    this._response.Redirect(_configuration.UnauthorizedErrorRedirectUrl, false);
                    return;
                }

                _statusLogger.Log(context, StreamWriteStatus.ApplicationRestarted);

                //now pass the HttpRequestBase to our class responsible for examining specific state and loading the Stream
                using (StreamLoaderResult fileDetails = _streamLoader.ParseRequest(this._request))
                {
                    if (fileDetails.Status != StreamLoadStatus.Success)
                    {
                        RedirectOnFailedStatus(fileDetails);
                        return;
                    }

                    IEnumerable <RangeRequest> rangeRequests;
                    if (!HeadersValidate(fileDetails, out rangeRequests))
                    {
                        return;
                    }

                    HttpResponseType responseStreamType = method == HttpMethodNames.Header.ToEnumValueString() ?
                                                          HttpResponseType.HeadOnly : HttpResponseType.Complete;
                    //we've passed our credential checking and we're ready to send out our response
                    StreamWriteStatus streamWriteStatus = new ResponseStreamWriter(this._response, this._configuration.FileTransferBufferSizeInKBytes)
                                                          .StreamFile(responseStreamType, fileDetails, rangeRequests, this._request.RetrieveHeader(HttpHeaderFields.IfRange), true);
                    HandleStreamWriteStatus(streamWriteStatus);
                }
            }
            catch (HttpException hex)
            {
                //remote host closed the connection
                if (HttpExceptionErrorCodes.ConnectionAborted == hex.ErrorCode)
                {
                    //log.Warn(String.Format("Remote Host Closed Transfer - Identity [{0}] - FileId [{1}] - User Id [{2}] / Name [{3}] / Email [{4}]{5}{5}{6}", WindowsIdentity.GetCurrent().Name, FileId, context.OnyxUser().Identity.OCPUser.Individual.OnyxId, context.OnyxUser().Identity.OCPUser.Individual.UserName, context.OnyxUser().Identity.OCPUser.Individual.UserEmailAddress, Environment.NewLine, this._request.ToLogString()), ex);
                }
            }
            //eat it -- nothing we can do
            catch (ThreadAbortException)
            { }
            //log.Error(String.Format("Unexpected Download Exception Occurred - Identity [{0}] - FileId [{1}] - User Id [{2}] / Name [{3}] / Email [{4}]{5}{5}{6}", WindowsIdentity.GetCurrent().Name, FileId, context.OnyxUser().Identity.OCPUser.Individual.OnyxId, context.OnyxUser().Identity.OCPUser.Individual.UserName, context.OnyxUser().Identity.OCPUser.Individual.UserEmailAddress, Environment.NewLine, this._request.ToLogString()), ex);
            //SafeInternalServerError(context);
        }