BinaryRead() публичный Метод

public BinaryRead ( int count ) : byte[]
count int
Результат byte[]
Пример #1
0
 public override byte [] BinaryRead(int count)
 {
     return(w.BinaryRead(count));
 }
Пример #2
0
        /// <summary>
        /// Processes an incoming request.
        /// </summary>
        /// <param name="provider">The provider that triggered the request.</param>
        /// <param name="httpRequest">The http information.</param>
        /// <returns>The result from the client method.</returns>
        internal static DirectExecutionResponse Execute(DirectProvider provider, HttpRequest httpRequest, IEnumerable<JsonConverter> converters)
        {
            List<DirectResponse> responses = new List<DirectResponse>();
            if (!String.IsNullOrEmpty(httpRequest[DirectRequest.RequestFormAction]))
            {
                DirectRequest request = new DirectRequest()
                {
                    Action = httpRequest[DirectRequest.RequestFormAction] ?? string.Empty,
                    Method = httpRequest[DirectRequest.RequestFormMethod] ?? string.Empty,
                    Type = httpRequest[DirectRequest.RequestFormType] ?? string.Empty,
                    IsUpload = Convert.ToBoolean(httpRequest[DirectRequest.RequestFormUpload]),
                    TransactionId = Convert.ToInt32(httpRequest[DirectRequest.RequestFormTransactionId]),
                    Data = new object[] { httpRequest }
                };
                responses.Add(DirectProcessor.ProcessRequest(provider, request));
            }
            else
            {
                UTF8Encoding encoding = new UTF8Encoding();
                string json = encoding.GetString(httpRequest.BinaryRead(httpRequest.TotalBytes));
                /**************************************************************************************
                 skygreen:解决bug:Self referencing loop
                 参考:http://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type
                 **************************************************************************************/
                if (substr_count(json,"data")>1)
                {
                    List<DirectRequest> requests = JsonConvert.DeserializeObject<List<DirectRequest>>(json);
                    if (requests.Count > 0)
                    {
                        JArray raw = JArray.Parse(json);
                        int i = 0;
                        foreach (DirectRequest request in requests)
                        {
                            request.RequestData = (JObject)raw[i];
                            responses.Add(DirectProcessor.ProcessRequest(provider, request));
                            ++i;
                        }
                    }
                    else
                    {
                        DirectRequest request = JsonConvert.DeserializeObject<DirectRequest>(json);
                        request.RequestData = JObject.Parse(json);
                        responses.Add(DirectProcessor.ProcessRequest(provider, request));
                    }
                }
                else
                {
                    DirectRequest request = JsonConvert.DeserializeObject<DirectRequest>(json);
                    request.RequestData = JObject.Parse(json);
                    responses.Add(DirectProcessor.ProcessRequest(provider, request));
                }
            }
            DirectExecutionResponse response = new DirectExecutionResponse();

            JsonSerializerSettings outputSettings = new JsonSerializerSettings() { 
                DefaultValueHandling = DefaultValueHandling.Ignore,
                ReferenceLoopHandling =ReferenceLoopHandling.Ignore
            };
            foreach (JsonConverter converter in converters)
            {
                outputSettings.Converters.Add(converter);
            }
            if (responses.Count > 1 || !responses[0].IsUpload)
            {
                response.Data = JsonConvert.SerializeObject(responses, Formatting.None, outputSettings);
            }
            else
            {
                response.IsUpload = true;
                string outputJson = JsonConvert.SerializeObject(responses[0], Formatting.None, outputSettings);
                response.Data = String.Format("<html><body><textarea>{0}</textarea></body></html>", outputJson.Replace("&quot;", "\\&quot;"));
            }
            return response;
        }
Пример #3
0
        /// <summary>
        /// 获取客户端提交的文件流
        /// </summary>
        /// <param name="request">客户端请求对象</param>
        /// <param name="index">当上传多个文件时为文件流列表项的索引,单个文件时应为零,默认为零</param>
        /// <returns>返回获取到的二进制流对象</returns>
        public static Stream GetRequestFile(HttpRequest request, int index = 0)
        {
            Stream stream = null;
            if (request != null && index >= 0)
            {
                if (request.Files.Count > 0)
                {
                    HttpPostedFile postedfile = request.Files.Get(index);
                    stream = postedfile.InputStream;
                }
                else
                {
                    string disposition = request.ServerVariables["HTTP_CONTENT_DISPOSITION"];
                    if (!string.IsNullOrEmpty(disposition))
                    {
                        byte[] file = request.BinaryRead(request.TotalBytes);
                        stream = new MemoryStream(file, 0, file.Length);
                    }
                }
            }

            return stream;
        }
Пример #4
0
 public override byte[] BinaryRead(int count)
 {
     return(_httpRequest.BinaryRead(count));
 }
Пример #5
0
        public override CallbackInfo ProcessCallback( Order order, HttpRequest request, IDictionary<string, string> settings )
        {
            CallbackInfo callbackInfo = null;

              try {
            order.MustNotBeNull( "order" );
            request.MustNotBeNull( "request" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "business", "settings" );

            //Write data when testing
            if ( settings.ContainsKey( "isSandbox" ) && settings[ "isSandbox" ] == "1" ) {
              LogRequest<PayPal>( request, logPostData: true );
            }

            //Verify callback
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            string response = MakePostRequest( settings.ContainsKey( "isSandbox" ) && settings[ "isSandbox" ] == "1" ? "https://www.sandbox.paypal.com/cgi-bin/webscr" : "https://www.paypal.com/cgi-bin/webscr", Encoding.ASCII.GetString( request.BinaryRead( request.ContentLength ) ) + "&cmd=_notify-validate" );

            if ( settings.ContainsKey( "isSandbox" ) && settings[ "isSandbox" ] == "1" ) {
              using ( StreamWriter writer = new StreamWriter( File.Create( HostingEnvironment.MapPath( "~/paypal-callback-data-2.txt" ) ) ) ) {
            writer.WriteLine( response );
            writer.Flush();
              }
            }

            if ( response == "VERIFIED" ) {

              string receiverId = request.Form[ "receiver_id" ];
              string receiverEmail = request.Form[ "receiver_email" ];
              string transaction = request.Form[ "txn_id" ];
              decimal amount = decimal.Parse( request.Form[ "mc_gross" ], CultureInfo.InvariantCulture );
              string state = request.Form[ "payment_status" ];

              string businessSetting = settings[ "business" ];

              //Check if the business email is the same in the callback
              if ( !string.IsNullOrEmpty( transaction ) && ( ( !string.IsNullOrEmpty( receiverId ) && businessSetting == receiverId ) || ( !string.IsNullOrEmpty( receiverEmail ) && businessSetting == receiverEmail ) ) ) {

            //Pending
            if ( state == "Pending" ) {

              if ( request.Form[ "pending_reason" ] == "authorization" ) {
                if ( request.Form[ "transaction_entity" ] == "auth" ) {
                  callbackInfo = new CallbackInfo( amount, transaction, PaymentState.Authorized );
                }
              } else if ( request.Form[ "pending_reason" ] == "multi_currency" ) {
                callbackInfo = new CallbackInfo( amount, transaction, PaymentState.PendingExternalSystem );
              }

              //Completed - auto capture
            } else if ( state == "Completed" ) {
              callbackInfo = new CallbackInfo( amount, transaction, PaymentState.Captured );
            }
              } else {
            LoggingService.Instance.Warn<PayPal>( "PayPal(" + order.CartNumber + ") - Business isn't identical - settings: " + businessSetting + " | request-receiverId: " + receiverId + " | request-receiverEmail: " + receiverEmail );
              }
            } else {
              LoggingService.Instance.Warn<PayPal>( "PayPal(" + order.CartNumber + ") - Couldn't verify response: " + response );
            }
              } catch ( Exception exp ) {
            LoggingService.Instance.Error<PayPal>( "PayPal(" + order.CartNumber + ") - Process callback", exp );
              }

              return callbackInfo;
        }
Пример #6
0
        public string Upload()
        {
            string inputname = "filedata";
            string attachdir = "/Resources/upimages";     // 上传文件保存路径,结尾不要带/

            System.Web.HttpRequest request = HttpContextUtil.CurrentHttpContext.Request;


            string disposition = request.ServerVariables["HTTP_CONTENT_DISPOSITION"];
            Stream fileData;
            string localname;

            if (disposition != null)
            {
                // HTML5上传
                byte[] file = request.BinaryRead(request.TotalBytes);
                fileData  = new MemoryStream(file);
                localname = HttpUtility.UrlDecode(Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value);// 读取原始文件名
            }
            else
            {
                HttpFileCollection filecollection = request.Files;
                HttpPostedFile     postedfile     = filecollection.Get(inputname);

                // 读取原始文件名
                localname = postedfile.FileName;

                fileData = postedfile.InputStream;

                filecollection = null;
            }

            string extension = localname.Substring(localname.LastIndexOf('.') + 1);
            bool   extFlag   = ExtArrayString.IndexOf(extension) >= 0;

            ThrowExceptionUtil.ArgumentConditionTrue(extFlag, "fileName", "不能上传该文件。");

            ThrowExceptionUtil.ArgumentConditionTrue(fileData.Length > 0 && fileData.Length < MaxFileLength, "filedata", "文件大小超过{0}字节".FormatWith(MaxFileLength));

            string attach_dir, attach_subdir, err;

            attach_subdir = "day_" + DateTime.Now.ToString("yyMMdd");

            attach_dir = attachdir + "/" + attach_subdir + "/";

            Random random   = new Random(DateTime.Now.Millisecond);
            string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension;

            try
            {
                string dir = HttpContextUtil.CurrentHttpContext.Server.MapPath(attach_dir);
                IOUtil.SafeCreateDirectory(dir);

                System.IO.FileStream fs = new System.IO.FileStream(IOUtil.CombinePath(dir, filename)
                                                                   , System.IO.FileMode.Create, System.IO.FileAccess.Write);

                int    buffSize = (int)fileData.Length;
                byte[] buff     = new Byte[buffSize];
                fileData.Read(buff, 0, buffSize);
                fileData.Close();

                fs.Write(buff, 0, buffSize);

                fs.Flush();
                fs.Close();
            }
            catch (Exception ex)
            {
                err = ex.Message.ToString();
            }


            return(attach_dir + filename);
        }