public QueryPermissions(
            CHBaseClient client,
            RecordReference record,
            RequestBody body,
            Type responseType)
            : base(client)
        {
            if (record == null)
            {
                throw new ArgumentNullException("record");
            }

            if (body == null)
            {
                throw new ArgumentNullException("body");
            }

            if (responseType == null)
            {
                throw new ArgumentNullException("responseType");
            }

            m_record = record;
            m_requestBody = body;
            m_responseType = responseType;
        }
 public QueryPermissions(
     CHBaseClient client,
     string personID, 
     string recordID,
     RequestBody body,
     Type responseType)
     : this(client, new RecordReference(personID, recordID), body, responseType)
 {
 }
Beispiel #3
0
        public Request(string method, int methodVersion, RequestBody body)
        {
            m_requestId = NextId();

            if (method != null)
            {
                Header.Method = method;
            }
            if (methodVersion > 0)
            {
                Header.MethodVersion = methodVersion;
            }
            Body = body;
        }
        public SearchVocabulary(CHBaseClient client, RequestBody body, Type responseType)
            : base(client)
        {
            if (body == null)
            {
                throw new ArgumentNullException("body");
            }
            if (responseType == null)
            {
                throw new ArgumentNullException("responseType");
            }

            m_body = body;
            m_responseType = responseType;
        }
        public GetThingType(HealthVaultClient client, RequestBody body, Type responseType)
            : base(client)
        {
            if (body == null)
            {
                throw new ArgumentNullException("body");
            }
            if (responseType == null)
            {
                throw new ArgumentNullException("responseType");
            }

            m_body = body;
            m_responseType = responseType;
        }
        public RemoveThings(CHBaseClient client, RecordReference record, RequestBody body)
            : base(client)
        {
            if (record == null)
            {
                throw new ArgumentNullException("record");
            }
            if (body == null)
            {
                throw new ArgumentNullException("body");
            }

            m_record = record;
            m_body = body;
        }
        public SelectInstance(HealthVaultClient client, RequestBody requestBody, Type responseType) 
            : base(client)
        {
            if (requestBody == null)
            {
                throw new ArgumentNullException("requestBody");
            }

            if (responseType == null)
            {
                throw new ArgumentNullException("responseType");
            }

            m_requestBody = requestBody;
            m_responseType = responseType;
        }
        public CreateRecord(CHBaseClient client, RequestBody requestBody, Type responseType)
            : base(client)
        {
            if (requestBody == null)
            {
                throw new ArgumentNullException("requestBody");
            }

            if (responseType == null)
            {
                throw new ArgumentNullException("responseType");
            }

            m_requestBody = requestBody;
            m_responseType = responseType;
        }
        private WebRequest GetRequestForTrigger(Trigger trigger)
        {
            var request = WebRequest.Create(GetRequestUriFromTrigger(trigger));
            request.Method = "POST";

            var body = new RequestBody {TriggerId = trigger.Id};
            var bodyBytes = Encoding.UTF8.GetBytes(JsonConvert.ToString(body));
            request.ContentLength = bodyBytes.Length;
            request.ContentType = "application/json";

            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bodyBytes, 0, bodyBytes.Length);
            }

            return request;
        }
 public static FormUrlEncodedContent GetRequestBody(RequestBody type, params object[] parameters)
 {
     switch(type)
     {
         case RequestBody.SwitchTeam:
             return GetSwitchTeamBody(parameters[0] as string, parameters[1] as string);
         case RequestBody.SetClaimQueue:
             return GetSetClaimQueueBody(parameters[0] as string, parameters[1] as string, parameters[2] as string);
         case RequestBody.SetOfferStashQueue:
             return GetSetOfferStashQueueBody(parameters[0] as List<string>, parameters[1] as List<string>);
         case RequestBody.CancelBetData:
             return GetCancelBetData(parameters[0] as string, parameters[1] as string);
         case RequestBody.ConfirmAsSolved:
             return GetConfirmAsSolvedBody(parameters[0] as string);
     }
     return null;
 }
Beispiel #11
0
        public void Run()
        {
            var data = new UserData
            {
                Version   = "0.1",
                Id        = "1", // id пользователя
                DeviceId  = _deviceId,
                TimeStart = DateTime.Now
            };

            string json = JsonConvert.SerializeObject(data);

            RequestBody body = RequestBody.Create(MediaType.Parse("application/json; charset=utf-8"), json);

            Request request = new Request.Builder()
                              .Url(_ipAddress)
                              .AddHeader("Phone-Action", "hello")
                              .AddHeader("Content-Type", "application/json; charset=utf-8")
                              .Post(body)
                              .Build();

            client.NewCall(request).Enqueue(this);
        }
Beispiel #12
0
        private void Authenticate()
        {
            try
            {
                Client      c  = new Client();
                RequestBody rb = RequestBody.Create("AuthorizationController",
                                                    "Authorize")
                                 .AddParameter("user", txUser.Text)
                                 .AddParameter("password", txPassword.Text);
                c.SendRequest(rb);
                OperationResult result = c.GetResult();
                Token = result.Entity.ToString();

                PreviousUser   = txUser.Text;
                PreviousPasswd = txPassword.Text;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        //ORIGINAL LINE: @Test public void testOneway() throws ThreadInterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void testOneway()
        {
            RequestBody req = new RequestBody(2, "hello world oneway");

            for (int i = 0; i < invokeTimes; i++)
            {
                try
                {
                    client.oneway(addr, req);
                    Thread.Sleep(100);
                }
                catch (RemotingException e)
                {
                    string errMsg = "RemotingException caught in oneway!";
                    logger.LogError(errMsg, e);
                    Assert.Null(errMsg);
                }
            }

            Assert.True(serverConnectProcessor.Connected);
            Assert.Equal(1, serverConnectProcessor.ConnectTimes);
            Assert.Equal(invokeTimes, serverUserProcessor.InvokeTimes);
        }
Beispiel #14
0
        internal GetPositionsMessageRequest(InstrumentType instrumentType, long balanceId)
        {
            var name = "get-positions";

            if (instrumentType == InstrumentType.Forex)
            {
                name = "trading-fx-option.get-positions";
            }
            if (instrumentType == InstrumentType.CFD)
            {
                name = "digital-options.get-positions";
            }

            Message = new RequestBody <GetPositionRequestBody>
            {
                RequestBodyType = "digital-options.get-positions",
                Body            = new GetPositionRequestBody
                {
                    InstrumentsType = name,
                    UserBalanceId   = (int)balanceId
                }
            };
        }
        //ORIGINAL LINE: @Test public void testOneway() throws ThreadInterruptedException
        //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void testOneway()
        {
            NormalRequestBodyCustomSerializer s1 = new NormalRequestBodyCustomSerializer();
            NormalStringCustomSerializer      s2 = new NormalStringCustomSerializer();

            //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
            CustomSerializerManager.registerCustomSerializer(typeof(RequestBody), s1);
            //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
            CustomSerializerManager.registerCustomSerializer(typeof(string), s2);

            RequestBody req = new RequestBody(2, "hello world oneway");

            for (int i = 0; i < invokeTimes; i++)
            {
                try
                {
                    byte          testCodec     = (byte)i;
                    InvokeContext invokeContext = new InvokeContext();
                    invokeContext.put(InvokeContext.BOLT_CUSTOM_SERIALIZER, testCodec);
                    client.oneway(addr, req, invokeContext);

                    Assert.Equal(testCodec, s1.ContentSerializer);
                    Assert.Equal(255, s2.ContentSerializer);
                    Thread.Sleep(100);
                }
                catch (RemotingException e)
                {
                    string errMsg = "RemotingException caught in oneway!";
                    logger.LogError(errMsg, e);
                    Assert.Null(errMsg);
                }
            }

            Assert.True(serverConnectProcessor.Connected);
            Assert.Equal(1, serverConnectProcessor.ConnectTimes);
            Assert.Equal(invokeTimes, serverUserProcessor.InvokeTimes);
        }
        //ORIGINAL LINE: @Test public void testUnsupportedException() throws ThreadInterruptedException, com.alipay.remoting.exception.RemotingException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void testUnsupportedException()
        {
            client.getConnection(addr, 1000);

            RequestBody req       = new RequestBody(1, RequestBody.DEFAULT_SERVER_STR);
            string      clientres = null;

            for (int i = 0; i < invokeTimes; i++)
            {
                try
                {
                    // only when client invoked, the remote address can be get by UserProcessor
                    // otherwise, please use ConnectionEventProcessor
                    string remoteAddr = serverUserProcessor.RemoteAddr;
                    Assert.Null(remoteAddr);
                    remoteAddr = serverConnectProcessor.RemoteAddr;
                    Assert.NotNull(remoteAddr);
                    clientres = (string)server.RpcServer.invokeSync(remoteAddr, req, 1000);
                    Assert.Null("Connection removed! Should throw UnsupportedOperationException here.");
                }
                catch (RemotingException e)
                {
                    logger.LogError(e.Message);
                    Assert.Null("Connection removed! Should throw UnsupportedOperationException here.");
                }
                catch (NotSupportedException e)
                {
                    logger.LogError(e.Message);
                    Assert.Null(clientres);
                }
            }

            Assert.True(serverConnectProcessor.Connected);
            Assert.Equal(1, serverConnectProcessor.ConnectTimes);
            Assert.Equal(0, serverUserProcessor.InvokeTimes);
            Assert.Equal(0, clientUserProcessor.InvokeTimes);
        }
Beispiel #17
0
        public IHttpActionResult Main()
        {
            var body = new RequestBody();

            if (!body.IsUserLoggin)
            {
                return(Unauthorized());
            }

            var password        = body.GetPostString("password");
            var newPassword     = body.GetPostString("newPassword");
            var confirmPassword = body.GetPostString("confirmPassword");

            string userName;
            string errorMessage;

            if (string.IsNullOrEmpty(password) || !BaiRongDataProvider.UserDao.ValidateAccount(body.UserName, password, out userName, out errorMessage))
            {
                return(BadRequest("原密码输入错误,请重新输入"));
            }
            if (password == newPassword)
            {
                return(BadRequest("新密码不能与原密码一致,请重新输入"));
            }

            if (BaiRongDataProvider.UserDao.ChangePassword(body.UserName, newPassword, out errorMessage))
            {
                LogUtils.AddUserLog(body.UserName, EUserActionType.UpdatePassword, string.Empty);

                return(Ok(new
                {
                    LastResetPasswordDate = DateTime.Now
                }));
            }

            return(BadRequest(errorMessage));
        }
        public void Main(int publishmentSystemId, int nodeId, int contentId)
        {
            var body = new RequestBody();

            var publishmentSystemInfo = PublishmentSystemManager.GetPublishmentSystemInfo(publishmentSystemId);

            try
            {
                var contentInfo = DataProvider.VoteContentDao.GetContentInfo(publishmentSystemInfo, contentId);
                if ((contentInfo.EndDate - DateTime.Now).Seconds <= 0)
                {
                    throw new Exception("对不起,投票已经结束");
                }
                var cookieName = DataProvider.VoteOperationDao.GetCookieName(publishmentSystemId, nodeId, contentId);
                if (CookieUtils.IsExists(cookieName))
                {
                    throw new Exception("对不起,不能重复投票");
                }

                var optionIdArrayList = TranslateUtils.StringCollectionToIntList(HttpContext.Current.Request.Form["voteOption_" + contentId]);
                foreach (int optionId in optionIdArrayList)
                {
                    DataProvider.VoteOptionDao.AddVoteNum(optionId);
                }
                DataProvider.VoteOperationDao.Insert(new VoteOperationInfo(0, publishmentSystemId, nodeId, contentId, PageUtils.GetIpAddress(), body.UserName, DateTime.Now));

                HttpContext.Current.Response.Write(VoteTemplate.GetCallbackScript(publishmentSystemInfo, nodeId, contentId, true, string.Empty));
                CookieUtils.SetCookie(cookieName, true.ToString(), DateTime.MaxValue);
            }
            catch (Exception ex)
            {
                //HttpContext.Current.Response.Write(VoteTemplate.GetCallbackScript(publishmentSystemInfo, nodeId, contentId, false, ex.Message));
                HttpContext.Current.Response.Write(VoteTemplate.GetCallbackScript(publishmentSystemInfo, nodeId, contentId, false, "程序出错。"));
            }

            HttpContext.Current.Response.End();
        }
    public IEnumerator AskForEmotion()
    {
        if (!apiEnabled)
        {
            yield break;
        }
        requestInProgress = true;
        var rrArray     = heartRateManager.RrArray.Select(rr => rr / 1000).ToArray();
        var hrArray     = heartRateManager.HrArray;
        var requestBody = new RequestBody {
            hr = hrArray, rr = rrArray
        };

        var uri = URI + (URI.EndsWith("/") ? "classify" : "/classify");

        using (UnityWebRequest req = UnityWebRequest.Put(uri, JsonUtility.ToJson(requestBody)))
        {
            req.SetRequestHeader("Content-Type", "application/json");
            yield return(req.SendWebRequest());

            while (!req.isDone)
            {
                yield return(null);
            }

            if (!req.isHttpError && !req.isNetworkError && req.error == null)
            {
                var result  = req.downloadHandler.data;
                var json    = System.Text.Encoding.Default.GetString(result);
                var emotion = JsonUtility.FromJson <EmotionResponse>(json);
                m_LastEmotionResponse    = emotion;
                isNewEmotionSinceLastGet = true;
            }

            requestInProgress = false;
        }
    }
Beispiel #20
0
        //ORIGINAL LINE: @Test public void testServerSyncUsingConnection() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void testServerSyncUsingConnection()
        {
            Connection clientConn = client.createStandaloneConnection(ip, port, 1000);

            for (int i = 0; i < invokeTimes; i++)
            {
                RequestBody req1      = new RequestBody(1, RequestBody.DEFAULT_CLIENT_STR);
                Exception   serverres = null;
                try
                {
                    serverres = (Exception)client.invokeSync(clientConn, req1, 1000);
                    Assert.Null(serverres);
                }
                catch (RemotingException)
                {
                    Assert.Null("Should not reach here!");
                }

                Assert.NotNull(serverConnectProcessor.Connection);
                Connection  serverConn = serverConnectProcessor.Connection;
                RequestBody req        = new RequestBody(1, RequestBody.DEFAULT_SERVER_STR);
                Exception   clientres  = null;
                try
                {
                    clientres = (Exception)server.RpcServer.invokeSync(serverConn, req, 1000);
                    Assert.Null(clientres);
                }
                catch (RemotingException)
                {
                    Assert.Null("Should not reach here!");
                }
            }

            Assert.True(serverConnectProcessor.Connected);
            Assert.Equal(1, serverConnectProcessor.ConnectTimes);
            Assert.Equal(invokeTimes, serverUserProcessor.InvokeTimes);
        }
        private void future(RpcClient client, RpcServer server, int timeout)
        {
            RequestBody b1  = new RequestBody(1, RequestBody.DEFAULT_FUTURE_STR);
            object      obj = null;

            try
            {
                RpcResponseFuture future = null;
                if (null == server)
                {
                    future = client.invokeWithFuture(addr, b1, timeout);
                }
                else
                {
                    Connection conn = client.getConnection(addr, timeout);
                    Assert.NotNull(serverConnectProcessor.Connection);
                    Connection serverConn = serverConnectProcessor.Connection;
                    future = server.invokeWithFuture(serverConn, b1, timeout);
                }
                obj = future.get(timeout);
                Assert.Null("Should not reach here!");
            }
            catch (InvokeTimeoutException)
            {
                Assert.Null(obj);
            }
            catch (RemotingException e)
            {
                logger.LogError("Other RemotingException but RpcServerTimeoutException occurred in sync", e);
                Assert.Null("Should not reach here!");
            }
            catch (ThreadInterruptedException e)
            {
                logger.LogError("ThreadInterruptedException in sync", e);
                Assert.Null("Should not reach here!");
            }
        }
Beispiel #22
0
        protected override void Render(HtmlTextWriter writer)
        {
            var builder = new StringBuilder();

            var body = new RequestBody();

            var publishmentSystemId = body.AdministratorInfo.PublishmentSystemId;

            _publishmentSystemInfo = PublishmentSystemManager.GetPublishmentSystemInfo(publishmentSystemId);
            var scripts = SiteLoading.GetScript(_publishmentSystemInfo, ELoadingType.ContentTree, null);

            builder.Append(scripts);
            if (Page.Request.QueryString["PublishmentSystemID"] != null)
            {
                if (!StringUtils.EqualsIgnoreCase(publishmentSystemId.ToString(), Page.Request.QueryString["PublishmentSystemID"]))
                {
                    PageUtils.RedirectToErrorPage("你对此站点无权限!");
                    return;
                }
                try
                {
                    var publishmentSystemIdList = new List <int>();
                    publishmentSystemIdList.Add(publishmentSystemId);
                    publishmentSystemIdList.AddRange(PublishmentSystemManager.GetPublishmentSystemIdListByParentId(publishmentSystemId));
                    foreach (var publishmentSystem in publishmentSystemIdList)
                    {
                        var publishmentSystemInfo = PublishmentSystemManager.GetPublishmentSystemInfo(publishmentSystem);
                        builder.Append(SiteLoading.GetSiteRowHtml(publishmentSystemInfo, publishmentSystemId, body.AdministratorInfo.UserName, publishmentSystemId));
                    }
                }
                catch (Exception ex)
                {
                    PageUtils.RedirectToErrorPage(ex.Message);
                }
            }
            writer.Write(builder);
        }
Beispiel #23
0
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            RequestBody data = null;
            var equalityComparer = new Item.ItemEqualityComparer();

            using (StreamReader streamReader = new StreamReader(req.Body))
            {
                var requestBody = await streamReader.ReadToEndAsync();
                var defaultType = new RequestBody();
                log.LogInformation("requestBody: " + requestBody);
                data = _uniqueDataEntryUtil.Convert<RequestBody>(requestBody, defaultType);
            }

            var dictionary = data.Items.ToDictionary(x => x, x => x.FirstName, equalityComparer);
            var result = _uniqueDataEntryUtil.CanItemBeAdded(dictionary, data.Item);

            log.LogInformation($"Result is: {result}");

            return new OkObjectResult(result);
        }
Beispiel #24
0
        private bool IsMatchingBody(HttpRequestMessage httpRequestMessage)
        {
            if (RequestBody == null) // Ignored
            {
                return(true);
            }

            if (httpRequestMessage.Content == null)
            {
                return(false);
            }

            var requestBody = httpRequestMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();

            if (!RequestBody.IsSameString(requestBody))
            {
                return(false);
            }

            var contentType = httpRequestMessage.Content.Headers.ContentType;

            return(contentType.CharSet.IsSameString(RequestBodyEncoding.WebName) &&
                   contentType.MediaType.IsSameString(RequestBodyMediaType));
        }
Beispiel #25
0
        public static async Task OnHttpRequest(Microsoft.AspNetCore.Http.HttpContext e)
        {
            //Decode POST body
            RequestBody request = Program.DecodePostBody <RequestBody>(e);

            //Add to database
            var filterBuilder = Builders <DbPreregisteredUser> .Filter;
            var filter        = filterBuilder.Eq("email", request.email);
            var results       = await Program.connection.system_preregistered.FindAsync(filter);

            var r = await results.FirstOrDefaultAsync();

            if (r == null)
            {
                await Program.connection.system_preregistered.InsertOneAsync(new DbPreregisteredUser
                {
                    email = request.email,
                    time  = DateTime.UtcNow
                });
            }

            //Write ok
            await Program.QuickWriteStatusToDoc(e, true);
        }
Beispiel #26
0
        // 获取用户验证凭证
        private IEnumerator GetUserVerifyID(string userName)
        {
            FormData formData = new FormData()
                                .AddField("app_id", _appID)
                                .AddField("app_key", _appKey)
                                .AddField("app_user", userName);

            Request request = new Request(EOTAPI.VerifyRequest).Post(RequestBody.From(formData));
            Client  http    = new Client();

            yield return(http.Send(request));

            if (http.IsSuccessful())
            {
                Response resp = http.Response();
                Debug.Log("VerifyRequestResponse: " + resp.Body());

                _verifyRequestResponse = JsonUtility.FromJson <VerifyRequestResponse>(resp.Body());
            }
            else
            {
                Debug.LogError("NetWorkError: " + http.Error());
            }
        }
        public override Network.RequestBody GetRequestBody()
        {
            RequestBody body = null;

            if (srcPath != null)
            {
                FileInfo fileInfo = new FileInfo(srcPath);

                if (contentLength == -1 || contentLength + fileOffset > fileInfo.Length)
                {
                    contentLength = fileInfo.Length - fileOffset;
                }

                body = new FileRequestBody(srcPath, fileOffset, contentLength);
                body.ProgressCallback = progressCallback;
            }
            else if (data != null)
            {
                body = new ByteRequestBody(data);
                body.ProgressCallback = progressCallback;
            }

            return(body);
        }
        /// <seealso cref= CustomSerializer#deserializeContent(RequestCommand) </seealso>
        public override bool deserializeContent(RequestCommand req)
        {
            deserialFlag.set(true);
            RpcRequestCommand rpcReq = (RpcRequestCommand)req;

            byte[]      content = rpcReq.Content;
            IByteBuffer bb      = Unpooled.WrappedBuffer(content);
            int         a       = bb.ReadInt();

            byte[] dst = new byte[content.Length - 4];
            bb.ReadBytes(dst, 0, dst.Length);
            try
            {
                string      b  = Encoding.UTF8.GetString(dst);
                RequestBody bd = new RequestBody(a, b);
                rpcReq.RequestObject = bd;
            }
            catch (UnsupportedEncodingException e)
            {
                System.Console.WriteLine(e.ToString());
                System.Console.Write(e.StackTrace);
            }
            return(true);
        }
        public IHttpActionResult Main(Login model)
        {
            try
            {
                var body     = new RequestBody();
                var account  = body.GetPostString("account");
                var password = body.GetPostString("password");



                if (string.IsNullOrEmpty(account) || string.IsNullOrEmpty(password))
                {
                    return(Unauthorized());
                }
                string userName;
                string errorMessage;
                if (!BaiRongDataProvider.AdministratorDao.ValidateAccount(account, password, out userName, out errorMessage))
                {
                    LogUtils.AddAdminLog(userName, "后台管理员登录失败");
                    BaiRongDataProvider.AdministratorDao.UpdateLastActivityDateAndCountOfFailedLogin(userName);
                    return(Unauthorized());
                }

                BaiRongDataProvider.AdministratorDao.UpdateLastActivityDateAndCountOfLogin(userName);
                body.AdministratorLogin(userName);
                return(Ok(new
                {
                    UserName = userName
                }));
            }
            catch (Exception ex)
            {
                //return InternalServerError(ex);
                return(InternalServerError(new Exception("程序错误")));
            }
        }
Beispiel #30
0
        public IHttpActionResult Main()
        {
            try
            {
                var body     = new RequestBody();
                var account  = body.GetPostString("account");
                var password = body.GetPostString("password");

                string userName;
                string errorMessage;
                if (!BaiRongDataProvider.UserDao.ValidateAccount(account, password, out userName, out errorMessage))
                {
                    LogUtils.AddUserLog(userName, EUserActionType.LoginFailed, "用户登录失败");
                    BaiRongDataProvider.UserDao.UpdateLastActivityDateAndCountOfFailedLogin(userName);
                    return(BadRequest(errorMessage));
                }

                BaiRongDataProvider.UserDao.UpdateLastActivityDateAndCountOfLogin(userName);
                var userInfo  = BaiRongDataProvider.UserDao.GetUserInfoByUserName(userName);
                var user      = new User(userInfo);
                var groupInfo = UserGroupManager.GetGroupInfo(user.GroupId);

                body.UserLogin(userName);

                return(Ok(new
                {
                    User = user,
                    Group = groupInfo.Additional
                }));
            }
            catch (Exception ex)
            {
                //return InternalServerError(ex);
                return(InternalServerError(new Exception("程序错误")));
            }
        }
        public static JSONObject uploadImage(File file)
        {
            try
            {
                final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

                RequestBody req = new MultipartBuilder().SetType(MultipartBody.FORM).addFormDataPart("userid", "8457851245")
                                  .addFormDataPart("userfile", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, file)).build();

                Request request = new Request.Builder()
                                  .Url("url")
                                  .Post(req)
                                  .Build();

                OkHttpClient client   = new OkHttpClient();
                Response     response = client.newCall(request).execute();

                Log.d("response", "uploadImage:" + response.body().string());

                return(new JSONObject(response.body().string()));
            }
            catch (UnknownHostException | UnsupportedEncodingException e) {
                Log.e(TAG, "Error: " + e.getLocalizedMessage());
            } catch (Exception e)
Beispiel #32
0
        private static void Main(string[] args)
        {
            var requestBody = new RequestBody
            {
                Input = "",
                Min   = 0,
                Max   = 0
            };

            Console.WriteLine($"Amount of auctions: {Instances.AuctionService.GetAmountOfAuctions(requestBody)}");
            var cardInfo   = Instances.AuctionService.GetCardInfo(CardId.Batariel);
            var nameOfCard = Enum.GetName(typeof(CardId), CardId.Batariel);

            Console.WriteLine($"Card Info {nameOfCard}: \n{JsonConvert.SerializeObject(cardInfo)}");
            var auctionEntries      = Instances.AuctionService.GetAuctionEntriesOfPage(1, 30, requestBody);
            var firstOrDefaultEntry = auctionEntries.FirstOrDefault();

            Console.WriteLine($"AuctionEntry: {JsonConvert.SerializeObject(firstOrDefaultEntry)}");
            if (firstOrDefaultEntry != null)
            {
                Console.WriteLine(
                    $"Specific AuctionEntry: {JsonConvert.SerializeObject(Instances.AuctionService.GetAuctionEntryInfo((int) firstOrDefaultEntry.AuctionId))}");
            }
        }
Beispiel #33
0
    /// <summary>
    /// 把语音转换为文字
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    private IEnumerator GetAudioString(string url, RequestBody rb)
    {
        string req = JsonConvert.SerializeObject(rb);

        UnityWebRequest uw = new UnityWebRequest(url, "POST");

        uw.uploadHandler = new UploadHandlerRaw(Encoding.Default.GetBytes(req));

        uw.SetRequestHeader("Content-Type", "application/json");
        uw.downloadHandler = new DownloadHandlerTexture();
        uw.timeout         = 20;
        yield return(uw.Send());

        if (uw.isDone)
        {
//            Debug.Log("end");
            if (uw.error == null)
            {
                Debug.Log(uw.downloadHandler.text);
                JObject getASWJson = JsonConvert.DeserializeObject(uw.downloadHandler.text) as JObject;
                if (getASWJson["err_msg"].ToString() == "success.")
                {
                    audioToString = getASWJson["result"][0].ToString();
                    if (audioToString.Substring(audioToString.Length - 1) == ",")
                    {
                        audioToString = audioToString.Substring(0, audioToString.Length - 1);
                    }
                }
            }
            else
            {
                Debug.Log(uw.error);
                audioToString = "";
            }
        }
    }
Beispiel #34
0
        private void btConnect_Click(object sender, EventArgs e)
        {
            try
            {
                treeView.Nodes.Clear();
                Client.Configure(txAddress.Text, int.Parse(txPort.Text), ((4096 * 100) * 1000));
                Client client = new Client();

                RequestBody rb = RequestBody.Create("ServerInfoController", "FullServerInfo");
                client.SendRequest(rb);

                var result     = client.GetResult(typeof(ServerInfo));
                var serverInfo = (ServerInfo)result.Entity;

                lbDescription.Text = $"SocketAppServer, version {serverInfo.ServerVersion}, running on {serverInfo.MachineName}";

                foreach (var controllerInfo in serverInfo.ServerControllers)
                {
                    TreeNode node = new TreeNode(controllerInfo.ControllerName);
                    node.Tag = $"{controllerInfo.ControllerName}";

                    foreach (var action in controllerInfo.ControllerActions)
                    {
                        var child = new TreeNode(action);
                        child.Tag = $"{controllerInfo.ControllerName}:{action}";
                        node.Nodes.Add(child);
                    }

                    treeView.Nodes.Add(node);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: \n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public IHttpActionResult Main()
        {
            try
            {
                var body = new RequestBody();
                var form = HttpContext.Current.Request.Form;

                var isAllSites          = body.GetPostBool(StlSearch.AttributeIsAllSites.ToLower());
                var siteName            = PageUtils.FilterSqlAndXss(body.GetPostString(StlSearch.AttributeSiteName.ToLower()));
                var siteDir             = PageUtils.FilterSqlAndXss(body.GetPostString(StlSearch.AttributeSiteDir.ToLower()));
                var siteIds             = PageUtils.FilterSqlAndXss(body.GetPostString(StlSearch.AttributeSiteIds.ToLower()));
                var channelIndex        = PageUtils.FilterSqlAndXss(body.GetPostString(StlSearch.AttributeChannelIndex.ToLower()));
                var channelName         = PageUtils.FilterSqlAndXss(body.GetPostString(StlSearch.AttributeChannelName.ToLower()));
                var channelIds          = PageUtils.FilterSqlAndXss(body.GetPostString(StlSearch.AttributeChannelIds.ToLower()));
                var type                = PageUtils.FilterSqlAndXss(body.GetPostString(StlSearch.AttributeType.ToLower()));
                var word                = PageUtils.FilterSql(body.GetPostString(StlSearch.AttributeWord.ToLower()));
                var dateAttribute       = PageUtils.FilterSqlAndXss(body.GetPostString(StlSearch.AttributeDateAttribute.ToLower()));
                var dateFrom            = PageUtils.FilterSqlAndXss(body.GetPostString(StlSearch.AttributeDateFrom.ToLower()));
                var dateTo              = PageUtils.FilterSqlAndXss(body.GetPostString(StlSearch.AttributeDateTo.ToLower()));
                var since               = PageUtils.FilterSqlAndXss(body.GetPostString(StlSearch.AttributeSince.ToLower()));
                var pageNum             = body.GetPostInt(StlSearch.AttributePageNum.ToLower());
                var isHighlight         = body.GetPostBool(StlSearch.AttributeIsHighlight.ToLower());
                var isDefaultDisplay    = body.GetPostBool(StlSearch.AttributeIsDefaultDisplay.ToLower());
                var publishmentSystemId = body.GetPostInt("publishmentsystemid");
                var ajaxDivId           = PageUtils.FilterSqlAndXss(body.GetPostString("ajaxdivid"));
                var template            = TranslateUtils.DecryptStringBySecretKey(body.GetPostString("template"));
                var pageIndex           = body.GetPostInt("page", 1) - 1;

                var templateInfo          = new TemplateInfo(0, publishmentSystemId, string.Empty, ETemplateType.FileTemplate, string.Empty, string.Empty, string.Empty, ECharset.utf_8, false);
                var publishmentSystemInfo = PublishmentSystemManager.GetPublishmentSystemInfo(publishmentSystemId);
                var pageInfo       = new PageInfo(publishmentSystemId, 0, publishmentSystemInfo, templateInfo, body.UserInfo);
                var contextInfo    = new ContextInfo(pageInfo);
                var contentBuilder = new StringBuilder(StlRequestEntities.ParseRequestEntities(form, template));

                var stlLabelList = StlParserUtility.GetStlLabelList(contentBuilder.ToString());

                if (StlParserUtility.IsStlElementExists(StlPageContents.ElementName, stlLabelList))
                {
                    var stlElement             = StlParserUtility.GetStlElement(StlPageContents.ElementName, stlLabelList);
                    var stlPageContentsElement = stlElement;
                    var stlPageContentsElementReplaceString = stlElement;

                    bool isDefaultCondition;
                    var  whereString = DataProvider.ContentDao.GetWhereStringByStlSearch(isAllSites, siteName, siteDir, siteIds, channelIndex, channelName, channelIds, type, word, dateAttribute, dateFrom, dateTo, since, publishmentSystemId, ActionsSearch.ExlcudeAttributeNames, form, out isDefaultCondition);

                    //没搜索条件时不显示搜索结果
                    if (isDefaultCondition && !isDefaultDisplay)
                    {
                        return(NotFound());
                    }

                    var stlPageContents = new StlPageContents(stlPageContentsElement, pageInfo, contextInfo, pageNum, publishmentSystemInfo.AuxiliaryTableForContent, whereString);

                    int totalNum;
                    var pageCount = stlPageContents.GetPageCount(out totalNum);

                    if (totalNum == 0)
                    {
                        return(NotFound());
                    }

                    for (var currentPageIndex = 0; currentPageIndex < pageCount; currentPageIndex++)
                    {
                        if (currentPageIndex != pageIndex)
                        {
                            continue;
                        }

                        var pageHtml     = stlPageContents.Parse(totalNum, currentPageIndex, pageCount, false);
                        var pagedBuilder = new StringBuilder(contentBuilder.ToString().Replace(stlPageContentsElementReplaceString, pageHtml));

                        StlParserManager.ReplacePageElementsInSearchPage(pagedBuilder, pageInfo, stlLabelList, ajaxDivId, pageInfo.PageNodeId, currentPageIndex, pageCount, totalNum);

                        if (isHighlight && !string.IsNullOrEmpty(word))
                        {
                            var pagedContents = pagedBuilder.ToString();
                            pagedBuilder = new StringBuilder();
                            pagedBuilder.Append(RegexUtils.Replace(
                                                    $"({word.Replace(" ", "\\s")})(?!</a>)(?![^><]*>)", pagedContents,
                                                    $"<span style='color:#cc0000'>{word}</span>"));
                        }

                        StlUtility.ParseStl(publishmentSystemInfo, pageInfo, contextInfo, pagedBuilder, string.Empty, false);
                        return(Ok(pagedBuilder.ToString()));
                    }
                }

                StlUtility.ParseStl(publishmentSystemInfo, pageInfo, contextInfo, contentBuilder, string.Empty, false);
                return(Ok(contentBuilder.ToString()));
            }
            catch (Exception ex)
            {
                //return InternalServerError(ex);
                return(InternalServerError(new Exception("程序错误")));
            }
        }
 public HttpRequest(RequestHeader header)
 {
     this.header = header;
     this.body = null;
 }
Beispiel #37
0
        IEnumerator StartVoiceRequest(string url, object parameter)
        {
            string accessToken = string.Empty;

            while (!JwtCache.TryGetToken(
                       "*****@*****.**", out accessToken))
            {
                yield return(JwtCache.GetToken(
                                 "coffee-wnsicn-d620de1e3173",
                                 "*****@*****.**"));
            }

            byte[] samples = (byte[])parameter;
            //TODO: convert float[] samples into bytes[]
            //byte[] sampleByte = new byte[samples.Length * 4];
            //Buffer.BlockCopy(samples, 0, sampleByte, 0, sampleByte.Length);

            string sampleString = System.Convert.ToBase64String(samples);

            if (samples != null)
            {
                UnityWebRequest postRequest = new UnityWebRequest(url, "POST");
                RequestBody     requestBody = new RequestBody();
                requestBody.queryInput             = new QueryInput();
                requestBody.queryInput.audioConfig = new InputAudioConfig();
                requestBody.queryInput.audioConfig.audioEncoding = AudioEncoding.AUDIO_ENCODING_UNSPECIFIED;
                //TODO: check if that the sample rate hertz
                requestBody.queryInput.audioConfig.sampleRateHertz = 16000;
                requestBody.queryInput.audioConfig.languageCode    = "en";
                requestBody.inputAudio = sampleString;

                string jsonRequestBody = JsonUtility.ToJson(requestBody, true);
                Debug.Log(jsonRequestBody);

                byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonRequestBody);
                postRequest.SetRequestHeader("Authorization", "Bearer " + accessToken);
                postRequest.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bodyRaw);
                postRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
                postRequest.SetRequestHeader("Content-Type", "application/json");

                yield return(postRequest.SendWebRequest());

                if (postRequest.isNetworkError || postRequest.isHttpError)
                {
                    Debug.Log(postRequest.responseCode);
                    Debug.Log(postRequest.error);
                }
                else
                {
                    Debug.Log("Response: " + postRequest.downloadHandler.text);

                    // Or retrieve results as binary data
                    byte[] resultbyte = postRequest.downloadHandler.data;
                    string result     = System.Text.Encoding.UTF8.GetString(resultbyte);
                    Debug.Log("Result String: " + result);
                    ResponseBody content = (ResponseBody)JsonUtility.FromJson <ResponseBody>(postRequest.downloadHandler.text);
                    Debug.Log(content.queryResult.fulfillmentText);
                    Debug.Log(content.queryResult.intent.displayName);

                    string responseintent = content.queryResult.intent.displayName;
                    Debug.Log("Return: " + responseintent);

                    showPanel(responseintent);
                    // Debug.Log(content.outputAudio);
                    // Debug.Log(audioSource);
                    audioSource.clip = WavUtility.ToAudioClip(System.Convert.FromBase64String(content.outputAudio), 0);
                    audioSource.Play();
                }
            }
            else
            {
                Debug.LogError("The audio file is null");
            }
        }
Beispiel #38
0
        protected async Task <IResponseResult <T> > ExecuteRequestAsync <T>(HttpMethod method, TUrlParams urlParams, RequestBody body = null, IQueryString queryString = null, IHeaderCollection headers = null)
        {
            string url = this.GenerateUrl(urlParams, queryString);

            return(await RestHandler.Current.ExecuteRequestAsync <T>(method, url, body, headers));
        }
Beispiel #39
0
        public string GenerateCurlCode(HttpMethod method, TUrlParams urlParams = default(TUrlParams), RequestBody body = null, IQueryString queryString = null, IHeaderCollection headers = null)
        {
            string curl = $"curl --location --request {method.ToString().ToUpper()} '{this.GenerateUrl(urlParams, queryString)}' \\" + Environment.NewLine;

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    curl += $"--header '{header.Key}: {header.Value}' \\" + Environment.NewLine;
                }
            }

            if (body != null)
            {
                curl += $"--data-raw '{body.Context}'";
            }

            return(curl);
        }
Beispiel #40
0
        private IEnumerator<object> RequestTask(ListenerContext context, SocketDataAdapter adapter)
        {
            var startedWhen = DateTime.UtcNow;
            bool successful = false;

            try {
                const int headerBufferSize = 1024 * 32;
                const int bodyBufferSize = 1024 * 128;
                const double requestLineTimeout = 5;

                // RFC2616:
                // Words of *TEXT MAY contain characters from character sets other than ISO-8859-1 [22]
                //  only when encoded according to the rules of RFC 2047 [14].
                Encoding headerEncoding;
                try {
                    headerEncoding = Encoding.GetEncoding("ISO-8859-1");
                } catch {
                    headerEncoding = Encoding.ASCII;
                }

                Request request;
                RequestBody body;
                HeaderCollection headers;
                long bodyBytesRead = 0;
                long? expectedBodyLength = null;

                var reader = new AsyncTextReader(adapter, headerEncoding, headerBufferSize, false);
                string requestLineText;

                while (true) {
                    var fRequestLine = reader.ReadLine();
                    var fRequestOrTimeout = Scheduler.Start(new WaitWithTimeout(fRequestLine, requestLineTimeout));

                    yield return fRequestOrTimeout;

                    if (fRequestOrTimeout.Failed) {
                        if (!(fRequestOrTimeout.Error is TimeoutException))
                            OnRequestError(fRequestOrTimeout.Error);

                        yield break;
                    }

                    if (fRequestLine.Failed) {
                        if (!(fRequestLine.Error is SocketDisconnectedException))
                            OnRequestError(fRequestLine.Error);

                        yield break;
                    }

                    requestLineText = fRequestLine.Result;

                    // RFC2616:
                    // In the interest of robustness, servers SHOULD ignore any empty line(s) received where a
                    //  Request-Line is expected. In other words, if the server is reading the protocol stream
                    //   at the beginning of a message and receives a CRLF first, it should ignore the CRLF.
                    if ((requestLineText != null) && (requestLineText.Trim().Length == 0))
                        continue;

                    break;
                }

                var requestLineParsed = DateTime.UtcNow;

                headers = new HeaderCollection();
                while (true) {
                    var fHeaderLine = reader.ReadLine();
                    yield return fHeaderLine;

                    if (String.IsNullOrWhiteSpace(fHeaderLine.Result))
                        break;

                    headers.Add(new Header(fHeaderLine.Result));
                }

                var headersParsed = DateTime.UtcNow;

                var expectHeader = (headers.GetValue("Expect") ?? "").ToLowerInvariant();
                var expectsContinue = expectHeader.Contains("100-continue");

                string hostName;
                if (headers.Contains("Host")) {
                    hostName = String.Format("http://{0}", headers["Host"].Value);
                } else {
                    var lep = (IPEndPoint)adapter.Socket.LocalEndPoint;
                    hostName = String.Format("http://{0}:{1}", lep.Address, lep.Port);
                }

                var requestLine = new RequestLine(hostName, requestLineText);

                var remainingBytes = reader.DisposeAndGetRemainingBytes();
                bodyBytesRead += remainingBytes.Count;

                var connectionHeader = (headers.GetValue("Connection") ?? "").ToLowerInvariant();
                var shouldKeepAlive =
                    ((requestLine.Version == "1.1") || connectionHeader.Contains("keep-alive")) &&
                    !connectionHeader.Contains("close");

                if (headers.Contains("Content-Length"))
                    expectedBodyLength = long.Parse(headers["Content-Length"].Value);

                body = new RequestBody(remainingBytes, expectedBodyLength);

                if (expectsContinue)
                    yield return adapter.Write(Continue100, 0, Continue100.Length);

                request = new Request(
                    this, adapter, shouldKeepAlive,
                    requestLine, headers, body
                );

                IncomingRequests.Enqueue(request);

                var requestEnqueued = DateTime.UtcNow;
                DateTime? requestBodyRead = null;

                // FIXME: I think it's technically accepted to send a body without a content-length, but
                //  it seems to be impossible to make that work right.
                if (expectedBodyLength.HasValue) {
                    using (var bodyBuffer = BufferPool<byte>.Allocate(bodyBufferSize))
                    while (bodyBytesRead < expectedBodyLength.Value) {
                        long bytesToRead = Math.Min(expectedBodyLength.Value - bodyBytesRead, bodyBufferSize);

                        if (bytesToRead <= 0)
                            break;

                        var fBytesRead = adapter.Read(bodyBuffer.Data, 0, (int)bytesToRead);
                        yield return fBytesRead;

                        if (fBytesRead.Failed) {
                            if (fBytesRead.Error is SocketDisconnectedException)
                                break;

                            body.Failed(fBytesRead.Error);
                            OnRequestError(fBytesRead.Error);
                            yield break;
                        }

                        var bytesRead = fBytesRead.Result;

                        bodyBytesRead += bytesRead;
                        body.Append(bodyBuffer.Data, 0, bytesRead);
                    }

                    requestBodyRead = DateTime.UtcNow;
                }

                body.Finish();
                successful = true;

                request.Timing = new Request.TimingData {
                    Line = (requestLineParsed - startedWhen),
                    Headers = (headersParsed - requestLineParsed),
                    Queue = (requestEnqueued - headersParsed),
                    Body = (requestBodyRead - requestEnqueued)
                };
            } finally {
                if (!successful)
                    adapter.Dispose();
            }
        }
Beispiel #41
0
            internal Request(
                HttpServer server, SocketDataAdapter adapter, bool shouldKeepAlive,
                RequestLine line, HeaderCollection headers, RequestBody body
            )
            {
                QueuedWhenUTC = DateTime.UtcNow;
                WeakServer = new WeakReference(server);

                LocalEndPoint = adapter.Socket.LocalEndPoint;
                RemoteEndPoint = adapter.Socket.RemoteEndPoint;

                Line = line;
                Headers = headers;
                Body = body;
                Response = new Response(this, adapter, shouldKeepAlive);

                server.OnRequestCreated(this);
            }
Beispiel #42
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
            var url      = new Java.Net.URL(java_uri);

            var body = default(RequestBody);

            if (request.Content != null)
            {
                var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                body = RequestBody.Create(MediaType.Parse(request.Content.Headers.ContentType.MediaType), bytes);
            }

            var builder = new Request.Builder()
                          .Method(request.Method.Method.ToUpperInvariant(), body)
                          .Url(url);

            var keyValuePairs = request.Headers
                                .Union(request.Content != null ?
                                       (IEnumerable <KeyValuePair <string, IEnumerable <string> > >)request.Content.Headers :
                                       Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >());

            foreach (var kvp in keyValuePairs)
            {
                builder.AddHeader(kvp.Key, String.Join(",", kvp.Value));
            }

            cancellationToken.ThrowIfCancellationRequested();

            var rq   = builder.Build();
            var call = client.NewCall(rq);

            cancellationToken.Register(() => call.Cancel());

            var resp = default(Response);

            try {
                resp = await call.EnqueueAsync().ConfigureAwait(false);
            } catch (IOException ex) {
                if (ex.Message.ToLowerInvariant().Contains("canceled"))
                {
                    throw new OperationCanceledException();
                }

                throw;
            }

            var respBody = resp.Body();

            cancellationToken.ThrowIfCancellationRequested();

            var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());

            if (respBody != null)
            {
                var content = new ProgressStreamContent(respBody.ByteStream(), cancellationToken);
                content.Progress = getAndRemoveCallbackFromRegister(request);
                ret.Content      = content;
            }
            else
            {
                ret.Content = new ByteArrayContent(new byte[0]);
            }

            var respHeaders = resp.Headers();

            foreach (var k in respHeaders.Names())
            {
                ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
                ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
            }

            return(ret);
        }
        private RequestBody ConvertBody(PST.Body body)
        {
            if (body == null)
            {
                return(new RequestBody());
            }

            var result = new RequestBody();

            if (body.Mode == "raw")
            {
                // Set raw body text
                switch (body.Options?.Raw?.Language)
                {
                case "json":
                    result.JsonBody = body.Raw;
                    result.BodyType = RequestBodyType.Json;
                    break;

                case "xml":
                    result.XmlBody  = body.Raw;
                    result.BodyType = RequestBodyType.Xml;
                    break;

                default:
                    result.TextBody = body.Raw;
                    result.BodyType = RequestBodyType.Text;
                    break;
                }
            }
            else if (body.Mode == "urlencoded" && body.Urlencoded != null)
            {
                result.BodyType = RequestBodyType.FormEncoded;

                foreach (var postmanUrlEncoded in body.Urlencoded)
                {
                    var parameter = new Parameter
                    {
                        Type  = ParamType.FormEncodedData,
                        Key   = postmanUrlEncoded.Key,
                        Value = postmanUrlEncoded.Value
                    };

                    result.FormEncodedData?.Add(parameter);
                }
            }
            else if (body.Mode == "formdata" && body.Formdata != null)
            {
                result.BodyType = RequestBodyType.FormData;

                foreach (var postmanForm in body.Formdata)
                {
                    var nightingaleForm = new FormData
                    {
                        ContentType = postmanForm.ContentType,
                        Key         = postmanForm.Key,
                        Value       = postmanForm.Value,
                        FilePaths   = new List <string>(),
                        Enabled     = !postmanForm.Disabled
                    };

                    if (postmanForm.Type == "text")
                    {
                        nightingaleForm.FormDataType = FormDataType.Text;
                    }
                    else if (postmanForm.Type == "file")
                    {
                        nightingaleForm.FormDataType = FormDataType.File;
                    }

                    if (postmanForm.Src is string[] src)
                    {
                        foreach (var s in src)
                        {
                            if (string.IsNullOrWhiteSpace(s))
                            {
                                continue;
                            }

                            nightingaleForm.FilePaths.Add(s.TrimStart('/'));
                        }
                    }

                    result.FormDataList?.Add(nightingaleForm);
                }
            }
            else if (body.Mode == "file" && body.File?.Src != null)
            {
                result.BinaryFilePath = body.File.Src.TrimStart('/');
                result.BodyType       = RequestBodyType.Binary;
            }

            return(result);
        }
 public HttpRequest(RequestHeader header, RequestBody body)
 {
     this.header = header;
     this.body = body;
 }
 public GetThings(HealthVaultClient client, string personID, string recordID, RequestBody body, Type responseType)
     : this(client, new RecordReference(personID, recordID), body, responseType)
 {
 }
 public RemoveThings(CHBaseClient client, string personID, string recordID, RequestBody body)
     : this(client, new RecordReference(personID, recordID), body)
 {
 }