protected ApiException(string message, Response response)
			: base(message)
		{
			ResponseBody = response.Body;
			Headers = response.Headers;
			StatusCode = response.StatusCode;
		}
Exemplo n.º 2
0
        public void Run()
        {
            try
            {
                while (true)
                {
                    Socket client = server.Accept();
                    Response response = new Response(this, client);
                    Thread thread = new Thread(response.Run);
                    thread.Start();
                }

            }
            catch (Exception)
            {

            }
            finally
            {
                try
                {
                    server.Close();
                }
                catch (Exception)
                {

                }
            }
        }
Exemplo n.º 3
0
    /// <summary>
    /// Create the room
    /// </summary>
    /// <param name="name">The name.</param>
    /// <param name="owner">The owner.</param>
    /// <param name="privacy">The privacy.</param>
    /// <param name="guestAccess">if set to <c>true</c> [guest access].</param>
    /// <returns>Task&lt;IResponse&lt;Entity&gt;&gt;.</returns>
    /// <exception cref="System.NotImplementedException"></exception>
    public async Task<IResponse<bool>> CreateAsync(string name, string owner, RoomPrivacy privacy = RoomPrivacy.Public, bool guestAccess = false)
    {
      Validate.Length(name, 100, "Room Name");
      Validate.Mention(owner, "Owner");
      
      var room = new CreateRoom
      {
        Name = name,
        OwnerUserId = owner,
        GuestAccess = guestAccess,
        Privacy = privacy
      };

      var json = JsonConvert.SerializeObject(room, Formatting.None, _jsonSettings);

      var payload = new StringContent(json, Encoding.UTF8, "application/json");

      var result = await ApiConnection.Client.PostAsync("room", payload);
      var rawResponse = await result.Content.ReadAsStringAsync();
      var response = new Response<bool>(true)
      {
        Code = result.StatusCode,
        Body = rawResponse,
        ContentType = result.Content.Headers.ContentType.MediaType
      };
      return response;
    }
        protected void ValidateProductResponse(Response<Product> result)
        {
            Assert.IsNotNull(result, "Expected a result");
            Assert.IsNotNull(result.StatusCode, "Expected a status code");
            Assert.IsTrue(result.StatusCode.HasValue, "Expected a status code");
            Assert.AreEqual(HttpStatusCode.OK, result.StatusCode.Value, "Expected a 200 response");
            Assert.IsNotNull(result.Result, "Expected a result");
            Assert.IsNull(result.Error, "Expected no error");

            Assert.IsFalse(string.IsNullOrEmpty(result.Result.Id), "Expected Id to be populated");
            Assert.IsFalse(string.IsNullOrEmpty(result.Result.Name), "Expected Name to be populated");
            Assert.AreNotEqual(Category.Unknown, result.Result.Category, "Expected Category to be set");

            if (result.Result.Category == Category.Album)
            {
                Assert.That(result.Result.Tracks.Count, Is.AtLeast(1));

                foreach (var track in result.Result.Tracks)
                {
                    Assert.IsFalse(string.IsNullOrEmpty(track.Id), "Expected trackId to be populated");
                    Assert.IsFalse(string.IsNullOrEmpty(track.Name), "Expected trackName to be populated");
                    Assert.AreNotEqual(Category.Unknown, track.Category, "Expected trackCategory to be set");
                }
            }
        }
 public HttpResponseMessage Get(string Method, string Ver = null, string Device = null, string Sid = null, string Md5 = null, int channel_id = 0, int start = 0, int end = 0, string group_id = null, string filter = null, int recording_id = 0, string name = null, int channel = 0, int time_t = 0, int duration = 0)
 {
     Logger.ServiceILog("Service Request: {0}, {1}", Method, Request.RequestUri.ToString());
     object response = new Response() { ErrorCode = 0, ErrorMessage = "Unknown method." };
     try
     {
         switch ((Method ?? "").ToLower())
         {
             case "session.initiate": response = Session_Initiate(Ver, Device); break;
             case "session.login": response = Session_Login(Sid, Md5); break;
             case "channel.icon": response = Channel_Icon(channel_id); break;
             default:
             {
                 var config = new Models.Configuration();
                 int userOid = 0;
                 if (config.EnableUserSupport) /* ensure a user is found if users are enabled */
                 {
                     if (!String.IsNullOrWhiteSpace(Sid) && SessionUserOids.ContainsKey(Sid))
                         userOid = SessionUserOids[Sid];
                     else
                         throw new UnauthorizedAccessException();
                 }
                 switch ((Method ?? "").ToLower())
                 {
                     case "setting.list": response = Setting_List(); break;
                     case "channel.listings": response = Channel_Listings(userOid, channel_id, start, end); break;
                     case "channel.list": response = Channel_List(userOid, group_id); break;
                     case "channel.groups": response = Channel_Groups(userOid); break;
                     case "recording.list": response = Recording_List(userOid, filter); break;
                     case "recording.delete": response = Recording_Delete(userOid, recording_id); break;
                     case "recording.save": response = Recording_Save(userOid, name, channel, time_t, duration); break;
                 }
             }
             break;
         }
     }
     catch (InvalidSessionException)
     {
         response = new Response()
         {
             ErrorCode = 8,
             ErrorMessage = "Invalid Session",
             Stat = Response.ResponseStat.fail /* NOTE: this is a "fail" response */
         };
     }
     catch (ChannelNotFoundException)
     {
         response = new Response()
         {
             ErrorCode = 5,
             ErrorMessage = "Channel not found",
             Stat = Response.ResponseStat.failed /* NOTE: this is a "fail" response */
         };
     }
     if (response is Response)
         return new HttpResponseMessage() { Content = new StringContent(response.ToString(), System.Text.Encoding.UTF8, "application/xml") };
     else if (response == null)
         return new HttpResponseMessage(HttpStatusCode.NotFound);
     return response as HttpResponseMessage;
 }
		public void Should_set_properties_when_creating_oauth_exception()
		{
			var dummyResponse = new Response(HttpStatusCode.BadRequest,"Test Body");
			var result = new OAuthException(dummyResponse);
			Assert.That(result.ResponseBody, Is.EqualTo(dummyResponse.Body));
			Assert.That(result.StatusCode, Is.EqualTo(dummyResponse.StatusCode));
		}
Exemplo n.º 7
0
        /// <summary>
        /// 测试
        /// </summary>
        public static void Test()
        {
            MemoryStream stream = new MemoryStream();
            Response response = new Response();
            response.iii = 888;
            response.i64 = Int64.MaxValue / 2;
            response.time = DateTime.Now;
            response.Str = "大石头";
            response.Public = new IPEndPoint(IPAddress.Loopback, 1234);
            response.Private = new List<IPEndPoint>();
            response.Private.Add(response.Public);
            response.Private.Add(new IPEndPoint(IPAddress.Broadcast, 2));
            response.Private.Add(new IPEndPoint(IPAddress.IPv6Any, 33));

            ProtocolFormatter pf = new ProtocolFormatter();
            pf.Head.Config.NoHead = true;
            pf.Head.Config.EncodeInt = true;
            pf.Serialize(stream, response);

            Byte[] buffer = stream.ToArray();
            Console.WriteLine("[{0}] {1}", buffer.Length, BitConverter.ToString(buffer).Replace("-", " "));
            File.WriteAllBytes("Protocol.dat", buffer);

            stream = new MemoryStream(buffer);
            pf = new ProtocolFormatter();
            pf.Head.Config.NoHead = true;
            pf.Head.Config.EncodeInt = true;
            response = new Response();
            pf.Deserialize(stream, response);

            Console.WriteLine(response.Str);
        }
Exemplo n.º 8
0
        public HttpResponseMessage GetEmployees(long id, [FromUri]long[] loc = null)
        {
            if (id <= 0)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            IEnumerable<Employee> output = null;
            IEnumerable<EmployeeModel> employees = null;
            if (!loc.IsNullOrEmpty())
            {
                JoinTableRepository<EmployeeModel, SkillsetModel> repository = new JoinTableRepository<EmployeeModel, SkillsetModel>();
                IEnumerable<string> employeeIds = repository.GetLeft(id).Select(x => x.EmpId).ToList();
                CommonRepository<MToMTableModel<EmployeeModel, LocationModel>> repositoryEmpLoc = new CommonRepository<MToMTableModel<EmployeeModel, LocationModel>>();
                employees = repositoryEmpLoc.GetBySpecification(new Specification<MToMTableModel<EmployeeModel, LocationModel>>(x => x.LeftItem.IsActive == true && x.RightItem.IsActive == true && employeeIds.Contains(x.LeftItem.EmpId) && loc.Contains(x.RightItem.Id))).Select(x => x.LeftItem);
                output = AutoMapper.MapCollection<EmployeeModel, Employee>(employees);
            }
            else
            {
                TryGetItemEmployees(id, out output);
            }

            if (output.IsNullOrEmpty())
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            Response<IEnumerable<Employee>> results = new Response<IEnumerable<Employee>>(output);
            return Request.CreateResponse(HttpStatusCode.OK, results);
        }
		protected ApiResponseException(string message, Exception innerException, Response response)
			: base(message, innerException)
		{
			ResponseBody = response.Body;
			Headers = response.Headers;
			StatusCode = response.StatusCode;
		}
Exemplo n.º 10
0
        public Response<VideoView> DeleteVideo(Int64 Id)
        {
            if (this.videoService.DeleteVideo(Id) == true)
               {
               var response = new Response<VideoView> { Model = { } };
               response.Messages.Add(new Message
               {
                   MessageType = MessageType.Success,
                   Value = "Video Has Been Deleted"
               });

               return response;
               }
               else
               {
               var response = new Response<VideoView> { Model = { } };
               response.Messages.Add(new Message
               {
                   MessageType = MessageType.Warning,
                   Value = "Video Has Reference(s) In Renting"
               });

               return response;
               }
        }
Exemplo n.º 11
0
        static void HandleRequest(Request request, Response response)
        {
            // receive HTTP content
            byte[] content = request.Stdin.GetContents();

            // access server variables
            string serverSoftware = request.ServerSoftware.GetValueOrDefault();
            string method = request.RequestMethod.Value;

            // access HTTP headers
            string userAgent = request.Headers[RequestHeader.HttpUserAgent];
            string cookieValue = request.GetCookieValue("Keks").GetValueOrDefault();

            // set HTTP headers
            response.SetHeader(ResponseHeader.HttpExpires,
                               Response.ToHttpDate(DateTime.Now.AddDays(1.0)));
            response.SetCookie(new Cookie("Keks", "yummy"));

            // send HTTP content
            response.PutStr(
                @"<html>
                   <body>
                    <p>Hello World!</p>
                    <p>Server: " + serverSoftware + @"</p>
                    <p>User Agent: " + userAgent + @"</p>
                    <p>Received cookie value: " + cookieValue + @"</p>
                    <p>Content length as read: " + content.Length + @"</P>
                    <p>Request method: " + method + @"</p>
                   </body>
                  </html>"
                );
        }
Exemplo n.º 12
0
        public Response<UserView> DeleteUser(Int64 Id)
        {
            if (this._userService.DeleteUser(Id) == true)
            {
                //// build response
                var response = new Response<UserView> { Model = { } };
                response.Messages.Add(new Message
                {
                    MessageType = MessageType.Success,
                    Value = "User Has Been Deleted"
                });

                return response;
            }
            else
            {
                //// build response
                var response = new Response<UserView> { Model = { } };
                response.Messages.Add(new Message
                {
                    MessageType = MessageType.Warning,
                    Value = "User Has Reference(s) In Renting"
                });

                return response;
            }
        }
Exemplo n.º 13
0
 internal void AddHttpException(Exception ex, int count = 1)
 {
     for (int i = 0; i < count; i++)
     {
         var response = new Response() { Exception = ex };
         this.responses.Add(response);
     }
 }
Exemplo n.º 14
0
 internal void AddHttpResponse(IHttpResponseMessageAbstraction responseMessage, int count = 1)
 {
     for (int i = 0; i < count; i++)
     {
         var response = new Response() { ResponseMessage = responseMessage };
         this.responses.Add(response);
     }
 }
Exemplo n.º 15
0
 public void DefaultResponse()
 {
     var response = new Response();
     response.Body.Should().BeNull();
     response.ContentType.Should().BeNull();
     response.Headers.Should().BeEmpty();
     response.StatusCode.Should().Be(default(HttpStatusCode));
 }
		public void Should_create_invalid_resource_exception_when_creating_non_api_error_exception_with_2xxx_code()
		{
			var dummyResponse = new Response(HttpStatusCode.BadRequest, "Test Body");
			var error = new Error { Code = 2001 };
			var result = ExceptionFactory.CreateApiErrorException(error, dummyResponse);

			Assert.That(result, Is.TypeOf<InvalidResourceException>());
		}
        public Response<RespLogin> Login(UserModel objUserModel)
        {
            List<RespLogin> objResp = new List<RespLogin>();
            Response<RespLogin> response = new Response<RespLogin>();
            try
            {
                objDBMethod = new DBMethod();

                if (CheckRequestIsvalidornot(this.Request))
                {
                    objResp.Add(objDBMethod.Login(objUserModel));
                    switch (objResp[0].restKey)
                    {

                        case "0":
                            response.Create(false, Messages.WebError, Messages.AppVersion, objResp);
                            break;
                        case "1":
                            response.Create(true, Messages.FormatMessage(Messages.Success, "Logged in "), Messages.AppVersion, objResp);
                            break;
                        case "2":
                            response.Create(false, Messages.NotAllowedUser, Messages.AppVersion, objResp);
                            break;
                        case "3":
                            response.Create(false, Messages.InvalidPassword, Messages.AppVersion, objResp);
                            break;
                        case "4":
                            response.Create(false, Messages.EmailVerify, Messages.AppVersion, objResp);
                            break;
                        case "5":
                            response.Create(true, Messages.AccountCreated, Messages.AppVersion, objResp);
                            break;
                        case "6":
                            response.Create(false, "Sorry!!! we were unable to fetch your email please change your Facebook settings for email.", Messages.AppVersion, objResp);
                            break;
                        default:
                            response.Create(false, Messages.FormatMessage(Messages.InvalidReq), Messages.AppVersion, objResp);
                            break;
                    }
                }
                else
                {
                    response.Create(false, Messages.FormatMessage(Messages.InvalidReq), Messages.AppVersion, objResp);

                }

            }
            catch (Exception ex)
            {
                object session = new JavaScriptSerializer().Serialize(objUserModel);
                LogManager.Error("Error occured while Processing Webservice request :{0}", ex, session, ex.Message);
                response.Create(false, Messages.FormatMessage(Messages.ErrorOccure), Messages.AppVersion, objResp);
            }
            finally
            {
            }
            return response;
        }
Exemplo n.º 18
0
 public void ValidateASuccessfulResponse()
 {
     const string SuccessfulResponse = "joy";
     Response<string> response = new Response<string>(HttpStatusCode.OK, SuccessfulResponse);
     Assert.IsNotNull(response, "Expected a new Response");
     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Expected the same status code");
     Assert.AreEqual(SuccessfulResponse, response.Result, "Expected the same result");
     Assert.IsNull(response.Error, "Expected no error");
 }
Exemplo n.º 19
0
 public void ValidateAFailedResponse()
 {
     Exception e = new ApiCredentialsRequiredException();
     Response<string> response = new Response<string>(null, e);
     Assert.IsNotNull(response, "Expected a new Response");
     Assert.IsNull(response.StatusCode, "Expected no status code");
     Assert.AreEqual(e, response.Error, "Expected the same error");
     Assert.IsNull(response.Result, "Expected no result");
 }
Exemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerResponse"/> class.
 /// </summary>
 /// <param name="responseToReturn">A <see cref="Response"/> object to be sent to the remote client.</param>
 /// <param name="status">An <see cref="HttpStatusCode"/> value to set the status code of the HTTP response.</param>
 internal ServerResponse(Response responseToReturn, HttpStatusCode status)
 {
     this.returnedResponse = responseToReturn;
     this.statusCode = status;
     if (this.statusCode >= HttpStatusCode.BadRequest && this.statusCode < HttpStatusCode.InternalServerError)
     {
         this.contentType = "text/plain";
     }
 }
		public void Should_set_properties_when_creating_non_xml_response_exception()
		{
			var dummyResponse = new Response(HttpStatusCode.BadRequest, "Test Body");
			var innerException = new Exception();
			var result = new UnrecognisedErrorException(innerException, dummyResponse);

			Assert.That(result.ResponseBody, Is.EqualTo(dummyResponse.Body));
			Assert.That(result.StatusCode, Is.EqualTo(dummyResponse.StatusCode));
		}
Exemplo n.º 22
0
        public static AppAction App()
        {
            return (env, fault, result) => {
                var request = new Request(env);
                var response = new Response(result);
                if (string.IsNullOrWhiteSpace(request.GET["Url"])) {
                    response.ContentType = "text/html";
                    response
                        .Write("<form>")
                        .Write("Url <input type='text' name='Url' style='width:50%;' value='http://download.microsoft.com/download/f/e/6/fe6eb291-e187-4b06-ad78-bb45d066c30f/6.0.6001.18000.367-KRMSDK_EN.iso'/><br/>")
                        .Write("Save as <input type='text' name='SaveAs' style='width:50%;' value='6.0.6001.18000.367-KRMSDK_EN.iso'/><br/>")
                        .Write("<input type='submit' value='Go'/>")
                        .Write("</form>")
                        .Finish();
                }
                else {
                    // make remote request asynchronously
                    var remoteRequest = WebRequest.Create(request.GET["Url"]);

                    remoteRequest.BeginGetResponse(getResponseResult => fault.Guard(() => {
                        var remoteResponse = (HttpWebResponse)remoteRequest.EndGetResponse(getResponseResult);

                        // pass some response headers along
                        response.Status = (int)remoteResponse.StatusCode;
                        response.ContentType = remoteResponse.ContentType;
                        if (!string.IsNullOrWhiteSpace(request.GET["SaveAs"])) {
                            response.AddHeader("Content-Disposition", "attachment; filename=" + request.GET["SaveAs"]);
                        }

                        // pass response body along
                        var remoteStream = remoteResponse.GetResponseStream();
                        if (remoteStream == null) {
                            response.Finish();
                        }
                        else {
                            var buffer = new byte[4096];
                            response.Finish((next, error, complete) =>
                                Loop.Run((halted, continuation) => error.Guard(() =>
                                    remoteStream.BeginRead(buffer, 0, buffer.Length, streamResult => error.Guard(() => {
                                        var count = remoteStream.EndRead(streamResult);
                                        if (halted()) {
                                            return;
                                        }
                                        if (count <= 0) {
                                            complete();
                                            return;
                                        }
                                        if (!next.InvokeAsync(new ArraySegment<byte>(buffer, 0, count), continuation)) {
                                            continuation();
                                        }
                                    }), null))));
                        }
                    }), null);
                }
            };
        }
 public void Should_map_status_code_from_original_response()
 {
     // given
     var response = new Response() {StatusCode = 404};
     var httpListenerResponse = CreateHttpListenerResponse();
     // when
     new HttpListenerResponseMapper().Map(response, httpListenerResponse);
     // then
     Check.That(httpListenerResponse.StatusCode).IsEqualTo(404);
 }
Exemplo n.º 24
0
        private static Task<dynamic> CreateMethodOptionsResponse(IEnumerable<string> allowedMethods)
        {
            var response = new Response();
            response.Headers["Allow"] = string.Join(", ", allowedMethods);
            response.StatusCode = HttpStatusCode.OK;

            var tcs = new TaskCompletionSource<dynamic>();
            tcs.SetResult(response);
            return tcs.Task;
        }
		public void should_deserialize_emtpy_release_type_to_unknown()
		{
			var responseXml = File.ReadAllText("StubResponses/ArtistReleases.xml");
			var response = new Response(HttpStatusCode.OK, responseXml);

			var xmlParser = new ResponseParser<ArtistReleases>();
			var release =  xmlParser.Parse(response).Releases.First();

			Assert.That(release.Type,Is.EqualTo(ReleaseType.Unknown));
		}
Exemplo n.º 26
0
 public void Map(Response response, HttpListenerResponse result)
 {
     result.StatusCode = response.StatusCode;
     response.Headers.ToList().ForEach(pair => result.AddHeader(pair.Key, pair.Value));
     if (response.Body != null)
     {
         var content = Encoding.UTF8.GetBytes(response.Body);
         result.OutputStream.Write(content, 0, content.Length);
     }
 }
Exemplo n.º 27
0
        protected Product Deserialize(Response response)
        {
            if (response.StatusCode != HttpStatusCode.OK)
                throw Error("Unexpected status returned.", response);

            var json = ReadAll(response);

            var productJson = new Deserializer().Deserialize(json)["product"];
            return ProductDeserializer.Deserialize(productJson.ToString());
        }
		public void Should_set_properties_when_creating_non_api_error_exception()
		{
			var dummyResponse = new Response(HttpStatusCode.BadRequest, "Test Body");
			var error = new Error { Code = 1001 };
			var result = ExceptionFactory.CreateApiErrorException(error, dummyResponse);

			Assert.That(result.ResponseBody, Is.EqualTo(dummyResponse.Body));
			Assert.That(result.StatusCode, Is.EqualTo(dummyResponse.StatusCode));
			Assert.That(result.ErrorCode, Is.EqualTo(ErrorCode.RequiredParameterMissing));
		}
Exemplo n.º 29
0
        public HttpResponseMessage GetStreams()
        {
            IEnumerable<Stream> streams = null;
            if (!TryGetAllItems(out streams))
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            Response<IEnumerable<Stream>> results = new Response<IEnumerable<Stream>>(streams);
            return Request.CreateResponse(HttpStatusCode.OK, results);
        }
Exemplo n.º 30
0
 public void ValidateASuccessfulResponseWithPaging()
 {
     const string SuccessfulResponse = "joy";
     Response<string> response = new Response<string>(HttpStatusCode.OK, SuccessfulResponse, Guid.Empty);
     Assert.IsNotNull(response, "Expected a new Response");
     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Expected the same status code");
     Assert.AreEqual(SuccessfulResponse, response.Result, "Expected the same result");
     Assert.AreEqual(Guid.Empty, response.RequestId, "Expected the same request id");
     Assert.IsNull(response.Error, "Expected no error");
     Assert.IsTrue(response.Succeeded, "Expected success");
 }