Flush() public méthode

Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
public Flush ( ) : void
Résultat void
Exemple #1
0
        private void GetUserInfoHead()
        {
            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            string username = userMethod.CheckUserIndentity_Username();

            if (username.Trim() != "")
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WritePropertyName("username");
                writer.WriteValue(username);
                writer.WriteEndObject();
                writer.Flush();
            }
            else
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WritePropertyName("username");
                writer.WriteValue("");
                writer.WriteEndObject();
                writer.Flush();
            }
            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }
Exemple #2
0
        private void SelectEmailExist()
        {
            string email = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["email"]))
            {
                email = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["email"]));
            }
            int result = userBll.SelectEmailExist(email);

            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            if (result == 0)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WriteEndObject();
                writer.Flush();
            }
            else
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("500");
                writer.WriteEndObject();
                writer.Flush();
            }
            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;
            if (base.ContentType == null || base.ContentType.Length == 0)
            {
                response.ContentType = "application/json";
            }
            else
            {
                response.ContentType = base.ContentType;
            }

            if (base.ContentEncoding != null)
            {
                response.ContentEncoding = base.ContentEncoding;
            }

            if (base.Data != null)
            {
                var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };

                JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
                serializer.Serialize(writer, Data);

                writer.Flush();
            }
        }
Exemple #4
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (this.Data == null)
            {
                return;
            }
            var response = context.HttpContext.Response;

            response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }

            Type type = this.Data.GetType();
            // Wrap Enumerables to avoid potential Json Hijacking.
            if (TypeHelper.TryWrappingForIEnumerableGenericOrSame(ref type))
            {
                this.Data = TypeHelper.GetTypeRemappingConstructor(type).Invoke(new object[] { this.Data });
            }

            using (JsonTextWriter jsonTextWriter = new JsonTextWriter(response.Output) { CloseOutput = false })
            {
                var serializer = JsonSerializer.Create(this.SerializerSettings);
                serializer.Serialize(jsonTextWriter, this.Data);
                jsonTextWriter.Flush();
            }
        }
Exemple #5
0
		public override void ExecuteResult(ControllerContext context)
		{
			if (context == null)
			{
				throw new ArgumentNullException("context");
			}

			var response = context.HttpContext.Response;

			response.ContentType = MimeTypes.GetByExtension("json");

			if (ContentEncoding != null)
			{
				response.ContentEncoding = ContentEncoding;
			}

			if (Data != null)
			{
				var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };

				var serializer = JsonSerializer.Create(SerializerSettings);
				serializer.Serialize(writer, Data);

				writer.Flush();
			}
		}
Exemple #6
0
        private string GetICJson(List<BusinessPartner> list)
        {
            StringWriter sw = new StringWriter();
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.None;

                writer.WriteStartArray();

                foreach (var bp in list)
                {
                    writer.WriteStartObject();

                    writer.WritePropertyName("id");
                    writer.WriteValue(bp.Id);

                    writer.WritePropertyName("name");
                    writer.WriteValue(bp.ShortName);

                    writer.WriteEndObject();
                }

                writer.WriteEndArray();

                writer.Flush();
                sw.Close();
            }
            return sw.GetStringBuilder().ToString();
        }
        public void Add(IEnumerable <DocumentWithStream> documents)
        {
            if (Enabled == false)
            {
                return;
            }

            bool encrypt = Configuration.EncryptCacheItems;

            foreach (var document in documents)
            {
                string metaDataPath = Path.Combine(BaseCachePath, document.ID.ToString("D") + (encrypt ? ".e" : "") + ".meta");
                string contentPath  = Path.Combine(BaseCachePath, document.ID.ToString("D") + (encrypt ? ".e" : "") + ".data");

                using (var fileStream = File.OpenWrite(metaDataPath))
                    using (StreamWriter writer = encrypt ? new StreamWriter(CreateEncryptionStream(fileStream)) : new StreamWriter(fileStream))
                        using (var json = new Newtonsoft.Json.JsonTextWriter(writer))
                        {
                            var serializer = new Newtonsoft.Json.JsonSerializer();
                            serializer.Serialize(json, document.Document);
                            json.Flush();
                        }

                using (var fileStream = new FileStream(contentPath, FileMode.Create, FileAccess.Write))
                    using (Stream stream = encrypt ? (Stream)CreateEncryptionStream(fileStream) : fileStream)
                    {
                        document.Stream.CopyTo(stream);
                        stream.Flush();
                        document.Stream.Flush();
                    }
            }
        }
Exemple #8
0
        public static void WriteTo(this SecsMessage msg, JsonTextWriter jwtr)
        {
            jwtr.WriteStartObject();

            jwtr.WritePropertyName(nameof(msg.S));
            jwtr.WriteValue(msg.S);

            jwtr.WritePropertyName(nameof(msg.F));
            jwtr.WriteValue(msg.S);

            jwtr.WritePropertyName(nameof(msg.ReplyExpected));
            jwtr.WriteValue(msg.ReplyExpected);

            jwtr.WritePropertyName(nameof(msg.Name));
            jwtr.WriteValue(msg.Name);

            if (msg.SecsItem != null)
            {
                jwtr.WritePropertyName(nameof(msg.SecsItem));
                msg.SecsItem.WriteTo(jwtr);
            }

            jwtr.WriteEndObject();

            jwtr.Flush();
        }
Exemple #9
0
        public override void GetData(object target, Stream outgoingData)
        {
            try
            {
                ////using (var writer = new StreamWriter(outgoingData))
                //{
                //    var bin = new BinaryFormatter();
                //    bin.Serialize(outgoingData, target);
                //}

                StreamWriter writer = new StreamWriter(outgoingData);
                JsonTextWriter jsonWriter = new JsonTextWriter(writer);
                JsonSerializer ser = JsonSerializer.Create(new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
                ser.Serialize(jsonWriter, target);
                jsonWriter.Flush();

                //var serializer = new XmlSerializer(target.GetType());
                //serializer.Serialize(outgoingData, target);

                //var writer = new StreamWriter(outgoingData);
                //writer.WriteLine(target);
                //writer.Flush();
            }
            catch (Exception ex)
            { throw; }
        }
Exemple #10
0
        private static void RenderCacheFootprint(IEnumerable <ObjectCache> caches, HttpContext httpContext, ContentType outputType, bool expanded)
        {
            var response = httpContext.Response;

            switch (outputType)
            {
            case ContentType.Xml:
            {
                response.ContentEncoding = System.Text.Encoding.UTF8;
                response.Expires         = -1;
                var footprint = caches.First().GetCacheFootprintXml(expanded, httpContext.Request.Url);
                footprint.Save(response.Output);
            }
            break;

            case ContentType.Json:
            default:
                using (StreamWriter writer = new StreamWriter(response.OutputStream))
                {
                    var footprint = caches.First().GetCacheFootprintJson(expanded, httpContext.Request.Url);
                    using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(writer)
                    {
                        QuoteName = false, Formatting = Newtonsoft.Json.Formatting.Indented
                    })
                    {
                        Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                        serializer.Serialize(jsonWriter, footprint);
                        jsonWriter.Flush();
                    }
                }
                break;
            }
        }
        internal static string JsonSerializePayload(IEnumerable<KeyValuePair<string, object>> payload)
        {
            try
            {
                using (var writer = new StringWriter(CultureInfo.InvariantCulture))
                using (var jsonWriter = new JsonTextWriter(writer) { Formatting = Newtonsoft.Json.Formatting.Indented, CloseOutput = false })
                {
                    jsonWriter.WriteStartObject();

                    foreach (var item in payload)
                    {
                        JsonWriteProperty(jsonWriter, item.Key, item.Value);
                    }

                    jsonWriter.WriteEndObject();
                    jsonWriter.Flush();
                    return writer.ToString();
                }
            }
            catch (JsonWriterException jwe)
            {
                SemanticLoggingEventSource.Log.EventEntrySerializePayloadFailed(jwe.ToString());

                var errorDictionary = new Dictionary<string, object>
                {
                    {
                        "Error",
                        string.Format(CultureInfo.CurrentCulture, Properties.Resources.JsonSerializationError, jwe.Message)
                    }
                };

                return JsonConvert.SerializeObject(errorDictionary, Newtonsoft.Json.Formatting.Indented);
            }
        }
        private void WriteSchedules(IEnumerable<Schedule> schedules, string name)
        {
            var html = GrapicSchedule.GraphicSchedule;
            string json = null;

            var m = new MemoryStream();
            var t = new StreamWriter(m);
            var w = new JsonTextWriter(t);
            var s = new JsonSerializer();
            w.Formatting = Formatting.Indented;
            w.QuoteName = false;
            s.Serialize(w, schedules);
            w.Flush();
            m.Flush();
            m.Position = 0;
            var r = new StreamReader(m);
            json = r.ReadToEnd();
            t.Dispose();
            r.Dispose();


            var f = new FileStream(@"C:\Users\Stefan\SkyDrive\Modelljärnväg\Träffar\2016\Kil\Graf" + name + ".html", FileMode.Create);
            using (var sw = new StreamWriter(f, new UTF8Encoding()))
            {
                sw.Write(html.Replace("'%DATA%';", json));
            }
            f.Dispose();

        }
Exemple #13
0
        public override void ExecuteResult(ControllerContext context)
        {
            if(context == null)
                throw new ArgumentNullException("context");

            if(IsDebugEnabled)
                log.Debug(
                    "Action 처리결과를 Newtonsoft.Json의 JsonSerializer를 이용하여, 직렬화하여 HttpResponse에 씁니다... Result=[{0}]",
                    Result);

            if(Result == null)
                return;

            var response = context.HttpContext.Response;

            if(ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            response.ContentType = string.IsNullOrWhiteSpace(ContentType) ? MvcTool.JsonContentType : ContentType;

            using(var writer = new JsonTextWriter(response.Output) { Formatting = this.Formatting })
            {
                var serializer = JsonSerializer.Create(SerializerSettings);
                serializer.Serialize(writer, Result);

                writer.Flush();
            }
        }
Exemple #14
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet
                && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
            }

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = !string.IsNullOrEmpty(ContentType)
                                       ? ContentType
                                       : "application/json";

            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;

            if (Data != null)
            {
                var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
                var serializer = JsonSerializer.Create(SerializerSettings);
                serializer.Serialize(writer, Data);

                writer.Flush();
            }
        }
Exemple #15
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("Method is not allowed.");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                var writer = new JsonTextWriter(response.Output) {Formatting = Formatting};
                JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
                serializer.Serialize(writer, Data);
                writer.Flush();
            }
        }
Exemple #16
0
        public HttpStatusCode PostAsJson(Uri url, object data, JsonSerializerSettings settings)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            var postRequest = (HttpWebRequest)WebRequest.Create(url);
            postRequest.Method = "POST";
            postRequest.UserAgent = "SimpleHttp/1.0";
            postRequest.ContentType = "application/json; charset=utf-8";

            using (var stream = new StreamWriter(postRequest.GetRequestStream()))
            {
                var serializer = JsonSerializer.Create(settings);
                using (var writer = new JsonTextWriter(stream))
                {
                    serializer.Serialize(writer, data);
                    writer.Flush();
                }
            }

            using (var response = (HttpWebResponse)postRequest.GetResponse())
            {
                return response.StatusCode;
            }
        }
        public void SerializeError_serializes_httperror()
        {
            using (var stream = new MemoryStream())
            {
                var textWriter = new StreamWriter(stream);
                var writer = new JsonTextWriter(textWriter);

                var mockInnerException = new Mock<Exception>(MockBehavior.Strict);
                mockInnerException.Setup(m => m.Message).Returns("Inner exception message");
                mockInnerException.Setup(m => m.StackTrace).Returns("Inner stack trace");

                var outerException = new Exception("Outer exception message", mockInnerException.Object);

                var error = new HttpError(outerException, true)
                {
                    StackTrace = "Outer stack trace"
                };
                var jsonSerializer = new JsonSerializer();

                var mockIdProvider = new Mock<IErrorIdProvider>(MockBehavior.Strict);
                mockIdProvider.SetupSequence(p => p.GenerateId(It.IsAny<HttpError>())).Returns("OUTER-ID").Returns("INNER-ID");

                var serializer = new ErrorSerializer(mockIdProvider.Object);
                serializer.SerializeError(error, stream, writer, jsonSerializer);

                writer.Flush();

                var expectedJson = File.ReadAllText("ErrorSerializerTest.json");
                var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson);
                var output = System.Text.Encoding.ASCII.GetString(stream.ToArray());
                output.Should().Be(minifiedExpectedJson);
            }
        }
Exemple #18
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)

                throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = !string.IsNullOrEmpty(ContentType)

              ? ContentType

              : "application/json";

            if (ContentEncoding != null)

                response.ContentEncoding = ContentEncoding;

            if (Data != null)
            {

                JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting };

                JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);

                serializer.Serialize(writer, Data);

                writer.Flush();

            }
        }
        internal static string JsonSerializePayload(EventEntry entry)
        {
            try
            {
                using (var writer = new StringWriter(CultureInfo.InvariantCulture))
                using (var jsonWriter = new JsonTextWriter(writer) { Formatting = Newtonsoft.Json.Formatting.Indented, CloseOutput = false })
                {
                    EventEntryUtil.JsonWritePayload(jsonWriter, entry);
                    jsonWriter.Flush();
                    return writer.ToString();
                }
            }
            catch (JsonWriterException jwe)
            {
                SemanticLoggingEventSource.Log.EventEntrySerializePayloadFailed(jwe.ToString());

                var errorDictionary = new Dictionary<string, object>
                {
                    {
                        "Error",
                        string.Format(CultureInfo.CurrentCulture, Properties.Resources.JsonSerializationError, jwe.Message)
                    }
                };

                return JsonConvert.SerializeObject(errorDictionary, Newtonsoft.Json.Formatting.Indented);
            }
        }
Exemple #20
0
        public static Message SerializeMessage(JObject json, Message previousMessage)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(ms))
                {
                    using (JsonTextWriter jtw = new JsonTextWriter(sw))
                    {
                        json.WriteTo(jtw);
                        jtw.Flush();
                        sw.Flush();
                        Message result = Message.CreateMessage(MessageVersion.None, null, new RawBodyWriter(ms.ToArray()));
                        if (previousMessage != null)
                        {
                            result.Properties.CopyProperties(previousMessage.Properties);
                            result.Headers.CopyHeadersFrom(previousMessage.Headers);
                            previousMessage.Close();
                        }

                        result.Properties[JsonRpcConstants.JObjectMessageProperty] = json;
                        return result;
                    }
                }
            }
        }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("To allow GET requests, set JsonRequestBehavior to AllowGet.");
            }

            if (this.Data == null)
                return;

            var response = context.HttpContext.Response;
            response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;

            var serializer = JsonSerializer.Create(this.Settings);
            using (var writer = new JsonTextWriter(response.Output))
            {
                serializer.Serialize(writer, Data);
                writer.Flush();
            }
        }
Exemple #22
0
        /// <summary>
        /// Convert parameter list to json object
        /// </summary>
        public static string parameterFieldMapJson(parameters parms, string ProjectID, string QueryID)
        {
            StringWriter sw = new StringWriter();
            JsonTextWriter json = new JsonTextWriter(sw);

            json.WriteStartObject();
            json.WritePropertyName("results");
            json.WriteStartArray();
            json.WriteStartObject();
            // ProjectID and QueryID
            json.WritePropertyName("ProjectID");
            json.WriteValue(ProjectID);
            json.WritePropertyName("QueryID");
            json.WriteValue(QueryID);

            json.WritePropertyName("parameters");
            json.WriteRawValue(JsonConvert.SerializeObject(parms));

            json.WriteEndObject();
            json.WriteEndArray();
            json.WriteEndObject();

            json.Flush();
            sw.Flush();

            return sw.ToString();
        }
 protected override void SerializeMessage(Stream output, object message)
 {
     var streamWriter = new StreamWriter(output);
     var jsonWriter = new JsonTextWriter(streamWriter);
     RavenJToken.FromObject(message, this.serializer).WriteTo(jsonWriter);
     jsonWriter.Flush();
     streamWriter.Flush();
 }
 protected override void SerializeMessage(Stream output, object message)
 {
     var streamWriter = new StreamWriter(output);
     var jsonWriter = new JsonTextWriter(streamWriter);
     this.serializer.Serialize(jsonWriter, message);
     jsonWriter.Flush();
     streamWriter.Flush();
 }
 public void Serialize(object msg, TextWriter tw)
 {
     JsonSerializer ser = GetSerializer();
     JsonWriter jsw = new JsonTextWriter(tw);
     jsw.Formatting = PrettyPrint ? Formatting.Indented : Formatting.None;
     ser.Serialize(jsw, msg);
     jsw.Flush();
 }
 public Task<IHttpResponse> Provide(object value, HttpResponseCode responseCode = HttpResponseCode.Ok)
 {
     var memoryStream = new MemoryStream();
     var writer = new JsonTextWriter(new StreamWriter(memoryStream));
     var serializer = new JsonSerializer() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented};
     serializer.Serialize(writer, value);
     writer.Flush();
     return Task.FromResult<IHttpResponse>(new HttpResponse(responseCode, "application/json; charset=utf-8", memoryStream, true));
 }
 public Task<IHttpResponse> Provide(object value)
 {
     var memoryStream = new MemoryStream();
     var writer = new JsonTextWriter(new StreamWriter(memoryStream));
     var serializer = new JsonSerializer();
     serializer.Serialize(writer, value);
     writer.Flush();
     return Task.FromResult<IHttpResponse>(new HttpResponse(HttpResponseCode.Ok, "application/json; charset=utf-8", memoryStream, true));
 }
Exemple #28
0
 public JsonContent(object value)
 {
     Headers.ContentType = new MediaTypeHeaderValue("application/json");
     var jw = new JsonTextWriter(new StreamWriter(_stream)) { Formatting = Formatting.Indented };
     var serializer = new JsonSerializer();
     serializer.Serialize(jw, value);
     jw.Flush();
     _stream.Position = 0;
 }
Exemple #29
0
 public JsonContent(object value)
 {
     var jw = new JsonTextWriter(new StreamWriter(_Stream));
     jw.Formatting = Formatting.Indented;
     var serializer = new JsonSerializer();
     serializer.Serialize(jw, value);
     jw.Flush();
     _Stream.Position = 0;
 }
Exemple #30
0
 protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
 {
     using (var writer = new JsonTextWriter(new StreamWriter(stream)) { CloseOutput = false })
     {
         _serializer.Serialize(writer, _readDocument);
         writer.Flush();
     }
     return Task.FromResult(0);
 }
        public Task<uhttpsharp.HttpResponse> Get(uhttpsharp.IHttpRequest request)
        {
            var memoryStream = new MemoryStream();
            Newtonsoft.Json.JsonWriter writer = new JsonTextWriter(new StreamWriter( memoryStream));

            JsonSerializer.Create().Serialize(writer, _strings);
            writer.Flush();
            return Task.FromResult(new HttpResponse(HttpResponseCode.Ok, "application/json; charset=utf-8", memoryStream, true));
        }
        public void Render(ControllerContext context, object model) {
            var response = context.HttpContext.Response;
            var writer = new JsonTextWriter(response.Output) { Formatting = Formatting.None };

            JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings());
            serializer.Serialize(writer, model);

            writer.Flush();
        }
        protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context)
        {
            var serializer = CreateSerializer();
            // NOTE: we don't dispose or close these as they would
            // close the stream, which is used by the rest of the pipeline.
            var writer = new JsonTextWriter(new StreamWriter(stream));

            serializer.Serialize(writer, value);
            writer.Flush();
        }
 public void Write(Stream stream, object value)
 {
     using (var writer = new StreamWriter(stream))
     using (var jWriter = new JsonTextWriter(writer))
     {
         var serializer = new JsonSerializer();
         serializer.Serialize(jWriter, value);
         jWriter.Flush();
     }
 }
Exemple #35
0
        /// <summary>
        /// Writes Protocol in JSON format
        /// </summary>
        /// <returns>JSON string</returns>
        public override string ToString()
        {
            using (System.IO.StringWriter sw = new System.IO.StringWriter())
            {
                using (Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    #if (DEBUG)
                    writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                    #endif

                    WriteJson(writer, new SchemaNames());
                    writer.Flush();
                    return(sw.ToString());
                }
            }
        }
Exemple #36
0
        /// <summary>
        /// 使用第三方类库Newtonsoft将对象转换成JSON字符串。
        /// </summary>
        /// <param name="objectT">要转换的对象。</param>
        /// <returns></returns>
        public static String ToJson(object objectT)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();

            //这里使用自定义日期格式,如果不使用的话,默认是ISO8601格式
            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";

            StringBuilder sbJSON;
            string        rawJSON = JsonConvert.SerializeObject(objectT, Newtonsoft.Json.Formatting.Indented, timeConverter);

            StringWriter sw     = new StringWriter();
            JsonWriter   writer = new Newtonsoft.Json.JsonTextWriter(sw);

            writer.WriteRaw(rawJSON);
            writer.Flush();

            sbJSON = sw.GetStringBuilder();

            return(sbJSON.ToString());
        }
        protected override ArraySegment <byte> SerializeObject(object value)
        {
            var type     = value.GetType();
            var typeName = writeCache.GetOrAdd(type, TypeHelper.BuildTypeName); // Get type or Register type

            using (var ms = new MemoryStream())
                using (var tw = new StreamWriter(ms))
                    using (var jw = new Newtonsoft.Json.JsonTextWriter(tw))
                    {
                        jw.WriteStartArray();                // [
                        jw.WriteValue(typeName);             // "type",
                        jsonSerializer.Serialize(jw, value); // obj

                        jw.WriteEndArray();                  // ]

                        jw.Flush();

                        return(new ArraySegment <byte>(ms.ToArray(), 0, (int)ms.Length));
                    }
        }
Exemple #38
0
        /// <summary>
        /// 泛型对象转换到JSON表示字符串
        /// </summary>
        /// <param name="objectT">目标对象</param>
        /// <param name="totalResults">总记录数</param>
        /// <returns>返回JSON表示字符串</returns>
        public static string ToJSON(object objectT, int totalResults)
        {
            StringBuilder sbJSON;
            string        rawJSON = JsonConvert.SerializeObject(objectT);

            StringWriter sw     = new StringWriter();
            JsonWriter   writer = new Newtonsoft.Json.JsonTextWriter(sw);

            writer.WriteStartObject();

            writer.WritePropertyName("TotalRecord"); //总记录数
            writer.WriteValue(totalResults);

            writer.WritePropertyName("Data"); //数据集合
            writer.WriteRaw(rawJSON);
            writer.WriteEndObject();
            writer.Flush();

            sbJSON = sw.GetStringBuilder();
            return(sbJSON.ToString());
        }
Exemple #39
0
        System.Net.Http.HttpContent SerializeToContent(object obj)
        {
            var ms = new System.IO.MemoryStream();

            using (var sw = new System.IO.StreamWriter(ms, new UTF8Encoding(false), 1024, true))
                using (var jtw = new Newtonsoft.Json.JsonTextWriter(sw)
                {
                    Formatting = Formatting.None
                })
                {
                    var js = new JsonSerializer();
                    js.Serialize(jtw, obj);
                    jtw.Flush();
                }

            ms.Seek(0, System.IO.SeekOrigin.Begin);
            System.Net.Http.HttpContent httpContent = new System.Net.Http.StreamContent(ms);
            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            return(httpContent);
        }
        public void EncryptDecryptFile()
        {
            var    document     = new { Document = new Document(Guid.NewGuid(), "application/json", "results.json", false, 12000, null) };
            bool   encrypt      = true;
            string metaDataPath = Path.Combine("cache", document.Document.DocumentID + ".e.meta");

            //encrypt the document
            using (var fileStream = File.OpenWrite(metaDataPath))
                using (StreamWriter writer = encrypt ? new StreamWriter(CreateEncryptionStream(fileStream)) : new StreamWriter(fileStream))
                    using (var json = new Newtonsoft.Json.JsonTextWriter(writer))
                    {
                        var serializer = new Newtonsoft.Json.JsonSerializer();
                        serializer.Serialize(json, document.Document);
                        json.Flush();

                        //if (encrypt)
                        //{
                        //    ((CryptoStream)writer.BaseStream).FlushFinalBlock();
                        //}
                    }

            Document decryptedDocument = null;

            // decrypt the document
            using (var fs = File.OpenRead(metaDataPath))
                using (StreamReader reader = encrypt ? new StreamReader(CreateDecryptionStream(fs)) : new StreamReader(fs))
                    using (var jsonReader = new Newtonsoft.Json.JsonTextReader(reader))
                    {
                        var serializer = new Newtonsoft.Json.JsonSerializer();
                        serializer.Converters.Add(new DocumentCreationConverter());

                        decryptedDocument = serializer.Deserialize <Document>(jsonReader);
                    }

            Assert.IsNotNull(decryptedDocument);
        }
Exemple #41
0
        private void register()
        {
            string username = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"]))
            {
                username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["username"]));
            }
            string pwd = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"]))
            {
                pwd = Utils.Encrypt(InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["pwd"])));
            }
            string email = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["email"]))
            {
                email = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["email"]));
            }
            int sex = 2;

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["sex"]))
            {
                sex = Utils.CheckInt(HttpContext.Current.Request["sex"]);
            }
            int baby = 2;

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["baby"]))
            {
                baby = Utils.CheckInt(HttpContext.Current.Request["baby"]);
            }
            DateTime baby_date = DateTime.Now;

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["baby_date"]))
            {
                baby_date = Convert.ToDateTime(HttpContext.Current.Request["baby_date"]);
            }
            string remark = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["remark"]))
            {
                remark = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["remark"]));
            }

            int result = userBll.Add_User(username, pwd, email, sex, baby, baby_date, remark);

            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            if (result > 0)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WritePropertyName("newid");
                writer.WriteValue(result.ToString());
                writer.WriteEndObject();
                writer.Flush();
            }
            else
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("500");
                writer.WriteEndObject();
                writer.Flush();
            }
            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }
Exemple #42
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task Process(RequestDataMart reqDM)
        {
            //wait a small random amount of time before processing to try to avoid collision with webfarm containing multiple API
            System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(RandomGenerator.NextDouble() * 1500));


            var ifAdvaceStatuses = new[] {
                RoutingStatus.Completed,
                RoutingStatus.ResultsModified,
                RoutingStatus.RequestRejected,
                RoutingStatus.ResponseRejectedBeforeUpload,
                RoutingStatus.ResponseRejectedAfterUpload,
                RoutingStatus.AwaitingResponseApproval,
                RoutingStatus.Draft
            };

            var routes = await DB.RequestDataMarts.Where(x => x.RequestID == reqDM.RequestID).ToArrayAsync();

            if (routes.All(x => ifAdvaceStatuses.Contains(x.Status)))
            {
                if (ActiveProcessingRequests.ContainsKey(reqDM.RequestID))
                {
                    return;
                }


                ActiveProcessingRequests.TryAdd(reqDM.RequestID, DateTime.UtcNow);

                try
                {
                    var matrixDoc = await(from d in DB.Documents.AsNoTracking()
                                          where d.ItemID == reqDM.RequestID &&
                                          d.FileName == TrustMatrixFileAndExtension &&
                                          d.Kind == TrustMatrixKind
                                          select new { d.ID }).FirstOrDefaultAsync();

                    if (matrixDoc != null)
                    {
                        using (var docDB = new DataContext())
                            using (var sr = new StreamReader(LocalDiskCache.Instance.GetStream(DB, matrixDoc.ID)))
                            {
                                TrustMatrix = JsonConvert.DeserializeObject <TrustMatrix[]>(sr.ReadToEnd());
                                sr.Close();
                            }
                    }

                    int incrementedCount = (from res in DB.Responses
                                            join rdm in DB.RequestDataMarts on res.RequestDataMartID equals rdm.ID
                                            where rdm.RequestID == reqDM.RequestID
                                            select res.Count).Max() + 1;

                    var routeIDs = routes.Select(x => x.ID);

                    var currentTask = await PmnTask.GetActiveTaskForRequestActivityAsync(reqDM.Request.ID, reqDM.Request.WorkFlowActivityID.Value, DB);

                    List <DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem> manifestItems = new List <DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem>();

                    var q = from rd in DB.RequestDocuments
                            join rsp in DB.Responses on rd.ResponseID equals rsp.ID
                            join rdm in DB.RequestDataMarts on rsp.RequestDataMartID equals rdm.ID
                            join dm in DB.DataMarts on rdm.DataMartID equals dm.ID
                            join doc in DB.Documents on rd.RevisionSetID equals doc.RevisionSetID
                            where rsp.Count == (incrementedCount - 1) &&
                            rdm.RequestID == reqDM.Request.ID &&
                            routeIDs.Contains(reqDM.ID) &&
                            rd.DocumentType == RequestDocumentType.Output &&
                            doc.ItemID == rsp.ID &&
                            doc.ID == DB.Documents.Where(dd => dd.RevisionSetID == doc.RevisionSetID && doc.ItemID == rsp.ID).OrderByDescending(dd => dd.MajorVersion).ThenByDescending(dd => dd.MinorVersion).ThenByDescending(dd => dd.BuildVersion).ThenByDescending(dd => dd.RevisionVersion).Select(dd => dd.ID).FirstOrDefault()
                            select new
                    {
                        DocumentID            = doc.ID,
                        DocumentKind          = doc.Kind,
                        DocumentFileName      = doc.FileName,
                        ResponseID            = rd.ResponseID,
                        RevisionSetID         = rd.RevisionSetID,
                        RequestDataMartID     = rsp.RequestDataMartID,
                        DataMartID            = rdm.DataMartID,
                        DataPartnerIdentifier = dm.DataPartnerIdentifier,
                        DataMart = dm.Name
                    };

                    var documents = await(q).ToArrayAsync();

                    if (documents.Any(d => d.DocumentKind == StopProcessingTriggerDocumentKind))
                    {
                        var openRoutes = await DB.RequestDataMarts.Where(x => x.RequestID == reqDM.RequestID &&
                                                                         (x.Status == RoutingStatus.Submitted || x.Status == RoutingStatus.Resubmitted || x.Status == RoutingStatus.Draft)
                                                                         ).ToArrayAsync();

                        foreach (var route in openRoutes)
                        {
                            route.Status = RoutingStatus.Canceled;
                        }

                        currentTask.Status          = TaskStatuses.Complete;
                        currentTask.EndOn           = DateTime.UtcNow;
                        currentTask.PercentComplete = 100d;

                        reqDM.Request.WorkFlowActivityID = CompletedActivityID;

                        await DB.SaveChangesAsync();
                    }
                    else
                    {
                        List <KeyValuePair <string, Guid> > docsToSend = new List <KeyValuePair <string, Guid> >();

                        var fileListFiles = documents.Where(d => !string.IsNullOrEmpty(d.DocumentKind) && string.Equals("DistributedRegression.FileList", d.DocumentKind, StringComparison.OrdinalIgnoreCase));

                        var requestDataMarts = await(from dm in DB.DataMarts
                                                     join rdm in DB.RequestDataMarts on dm.ID equals rdm.DataMartID
                                                     where rdm.RequestID == reqDM.Request.ID
                                                     select new DTO.QueryComposer.DistributedRegressionManifestDataPartner
                        {
                            DataMartID         = dm.ID,
                            DataMartIdentifier = dm.DataPartnerIdentifier,
                            DataMartCode       = dm.DataPartnerCode,
                            RouteType          = rdm.RoutingType.Value
                        }).ToArrayAsync();

                        foreach (var fileListFile in fileListFiles)
                        {
                            //only include the files indicated in the filelist document
                            using (var stream = LocalDiskCache.Instance.GetStream(DB, fileListFile.DocumentID))
                                using (var reader = new System.IO.StreamReader(stream))
                                {
                                    //read the header line
                                    reader.ReadLine();

                                    string line, filename;
                                    bool   includeInDistribution = false;
                                    while (!reader.EndOfStream)
                                    {
                                        line = reader.ReadLine();
                                        string[] split = line.Split(',');
                                        if (split.Length > 0)
                                        {
                                            filename = split[0].Trim();
                                            if (split.Length > 1)
                                            {
                                                includeInDistribution = string.Equals(split[1].Trim(), "1");
                                            }
                                            else
                                            {
                                                includeInDistribution = false;
                                            }

                                            if (includeInDistribution == false)
                                            {
                                                continue;
                                            }

                                            if (!string.IsNullOrEmpty(filename))
                                            {
                                                Guid?revisionSetID = documents.Where(d => string.Equals(d.DocumentFileName, filename, StringComparison.OrdinalIgnoreCase) && d.DataMartID == fileListFile.DataMartID).Select(d => d.RevisionSetID).FirstOrDefault();
                                                if (revisionSetID.HasValue)
                                                {
                                                    foreach (var dp in split[2].Trim().Split(' '))
                                                    {
                                                        List <Guid> dmIDs = new List <Guid>();
                                                        dmIDs.Add(fileListFile.DataMartID);
                                                        dmIDs.Add(requestDataMarts.Where(x => x.DataMartCode == dp).Select(x => x.DataMartID).FirstOrDefault());

                                                        var isAllowed = TrustMatrix.Where(x => dmIDs.Contains(x.DataPartner1ID) && dmIDs.Contains(x.DataPartner2ID)).Select(x => x.Trusted).FirstOrDefault();

                                                        if (TrustMatrix.Length == 0 || isAllowed)
                                                        {
                                                            docsToSend.Add(new KeyValuePair <string, Guid>(dp, revisionSetID.Value));
                                                            manifestItems.AddRange(documents.Where(d => d.RevisionSetID == revisionSetID.Value).Select(d => new DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem
                                                            {
                                                                DocumentID            = d.DocumentID,
                                                                DataMart              = d.DataMart,
                                                                DataMartID            = d.DataMartID,
                                                                DataPartnerIdentifier = d.DataPartnerIdentifier,
                                                                RequestDataMartID     = d.RequestDataMartID,
                                                                ResponseID            = d.ResponseID,
                                                                RevisionSetID         = d.RevisionSetID
                                                            }).ToArray());
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    reader.Close();
                                }
                        }



                        foreach (var dp in docsToSend.GroupBy(x => x.Key))
                        {
                            var dataMart = await(from dm in DB.DataMarts
                                                 join rdm in DB.RequestDataMarts on dm.ID equals rdm.DataMartID
                                                 where rdm.RequestID == reqDM.Request.ID &&
                                                 rdm.Status != RoutingStatus.Canceled &&
                                                 dm.DataPartnerCode == dp.Key
                                                 select rdm).Include(rdm => rdm.Responses).FirstOrDefaultAsync();

                            if (dataMart != null)
                            {
                                var response = dataMart.AddResponse(IdentityID, incrementedCount);

                                await DB.SaveChangesAsync();

                                await DB.Entry(dataMart).ReloadAsync();

                                List <DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem> filteredManifestItems = new List <DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem>();

                                foreach (var revisionSet in dp)
                                {
                                    DB.RequestDocuments.Add(new RequestDocument {
                                        DocumentType = RequestDocumentType.Input, ResponseID = response.ID, RevisionSetID = revisionSet.Value
                                    });
                                    filteredManifestItems.Add(manifestItems.Where(x => x.RevisionSetID == revisionSet.Value).FirstOrDefault());
                                }

                                byte[] buffer;
                                using (var ms = new System.IO.MemoryStream())
                                    using (var sw = new System.IO.StreamWriter(ms))
                                        using (var jw = new Newtonsoft.Json.JsonTextWriter(sw))
                                        {
                                            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                                            serializer.Serialize(jw, new DTO.QueryComposer.DistributedRegressionManifestFile {
                                                Items = filteredManifestItems, DataPartners = requestDataMarts
                                            });
                                            jw.Flush();

                                            buffer = ms.ToArray();
                                        }

                                Document analysisCenterManifest = DB.Documents.Add(new Document
                                {
                                    Description  = "Contains information about the input documents and the datamart they came from.",
                                    Name         = "Internal: Routing Manifest",
                                    FileName     = "manifest.json",
                                    ItemID       = currentTask.ID,
                                    Kind         = DocumentKind.SystemGeneratedNoLog,
                                    UploadedByID = IdentityID,
                                    Viewable     = false,
                                    MimeType     = "application/json",
                                    Length       = buffer.Length
                                });

                                analysisCenterManifest.RevisionSetID = analysisCenterManifest.ID;

                                DB.RequestDocuments.Add(new RequestDocument {
                                    DocumentType = RequestDocumentType.Input, ResponseID = response.ID, RevisionSetID = analysisCenterManifest.RevisionSetID.Value
                                });

                                await DB.SaveChangesAsync();

                                analysisCenterManifest.SetData(DB, buffer);

                                dataMart.Status = dataMart.Responses.Count > 1 ? RoutingStatus.Resubmitted : RoutingStatus.Submitted;
                                await DB.SaveChangesAsync();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error($"Error processing DEC switch for requestID:{reqDM.RequestID}", ex);
                    throw;
                }
                finally
                {
                    DateTime startTime;
                    ActiveProcessingRequests.TryRemove(reqDM.RequestID, out startTime);
                }
            }
        }
Exemple #43
0
        private void Login()
        {
            //string username = "";
            //if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"]))
            //{
            //    username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["username"]));
            //}
            //string pwd = "";
            //if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"]))
            //{
            //    pwd = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["pwd"]));
            //    //pwd = WebBasic.Encryption.Encrypt(pwd);
            //    pwd = Utils.Encrypt(pwd);
            //}
            string username = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"]))
            {
                username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request.Form["username"]));
            }
            string pwd = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"]))
            {
                pwd = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request.Form["pwd"]));
                //pwd = WebBasic.Encryption.Encrypt(pwd);
                pwd = Utils.Encrypt(pwd);
            }
            int valid_type = 1;//1、根据用户名判断  2、根据邮箱判断

            if (username.Contains("@"))
            {
                valid_type = 2;
            }
            int result = 0;

            if (userBll.SelectUsernameEmailExist(username) > 0)

            {
                int count = userBll.SelectUserPwdIsTrue(username, pwd, valid_type);
                if (count > 0)
                {
                    result = UserLogin(username);//执行登录,并返回登录结果
                }
                else
                {
                    result = 2;//用户名或密码错误
                }
            }
            else
            {
                result = 4;//用户名不存在
            }
            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            writer.WriteStartObject();
            writer.WritePropertyName("status");
            writer.WriteValue("200");
            writer.WritePropertyName("result");
            writer.WriteValue(result.ToString());
            writer.WriteEndObject();
            writer.Flush();

            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }
Exemple #44
0
 /// <summary>将缓冲区中的所有内容刷新到基础流,并同时刷新基础流。</summary>
 public void Flush()
 {
     _textWriter.Flush();
 }
Exemple #45
0
        private void LoginManage()
        {
            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            int code_result = ValidCheckCode();//检测验证码:1、成功  2、验证码错误  3、请更换验证码重试

            if (code_result == 1)
            {
                string name = "";
                if (!string.IsNullOrEmpty(HttpContext.Current.Request["name"]))
                {
                    name = InText.SafeSql(HttpContext.Current.Request["name"]);
                }
                string pwd = "";
                if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"]))
                {
                    pwd = WebBasic.Encryption.Encrypt(InText.SafeSql(HttpContext.Current.Request["pwd"]));
                }

                String    sql = string.Format("select * from t_admin where name='{0}' and pwd='{1}'", name, pwd);
                DataTable dt  = artBll.SelectToDataTable(sql);
                if (dt.Rows.Count > 0)
                {
                    //将后台人员信息保存至session
                    Session["adminId"]    = dt.Rows[0]["id"].ToString();
                    Session["login_name"] = dt.Rows[0]["name"].ToString();
                    Session["pwd"]        = WebBasic.Encryption.Encrypt(dt.Rows[0]["pwd"].ToString());

                    //----将信息保存到Cookie----
                    HttpCookie hc = new HttpCookie("Cookie_admin");
                    hc.Values["adminId"]    = HttpUtility.UrlEncode(dt.Rows[0]["id"].ToString());
                    hc.Values["login_name"] = HttpUtility.UrlEncode(dt.Rows[0]["name"].ToString());
                    hc.Values["pwd"]        = WebBasic.Encryption.Encrypt(dt.Rows[0]["pwd"].ToString());//密码再次加密

                    if (cookie_domain != "")
                    {
                        hc.Domain = cookie_domain;
                    }
                    hc.Expires = DateTime.Now.AddDays(1);
                    Response.Cookies.Add(hc);

                    //writer.WriteStartArray();
                    writer.WriteStartObject();
                    writer.WritePropertyName("result");
                    writer.WriteValue("success");
                    writer.WriteEndObject();
                    writer.Flush();
                    //writer.WriteEndArray();
                }
                else
                {
                    //writer.WriteStartArray();
                    writer.WriteStartObject();
                    writer.WritePropertyName("result");
                    writer.WriteValue("failed");
                    writer.WritePropertyName("message");
                    writer.WriteValue("用户名或密码错误");
                    writer.WriteEndObject();
                    writer.Flush();
                    //writer.WriteEndArray();
                }
            }
            else
            {
                //writer.WriteStartArray();
                writer.WriteStartObject();
                writer.WritePropertyName("result");
                writer.WriteValue("failed");
                writer.WritePropertyName("message");
                if (code_result == 2)
                {
                    writer.WriteValue("验证码错误");
                }
                else
                {
                    writer.WriteValue("请更换验证码重试");
                }
                writer.WriteEndObject();
                writer.Flush();
                //writer.WriteEndArray();
            }

            string jsonText = sw.GetStringBuilder().ToString();

            //jsonText = "{\"returnValue\":" + jsonText + "}";
            Response.Write(jsonText);
        }