public void Dispose()
        {
            _stream.OnFlush -= OnFlush;

            _hashFunc.Dispose();
            _writer.Close();
            _streamWriter.Dispose();
            _stream.Dispose();
        }
Beispiel #2
0
//------no funciona en forms heredados no se pk------------------------------------------
        public static void sobreescribirJson(BindingList <Object> lista, String path)
        {
            JArray         jArray  = (JArray)JToken.FromObject(lista);
            StreamWriter   fichero = File.CreateText(path);
            JsonTextWriter writer  = new JsonTextWriter(fichero);

            jArray.WriteTo(writer);
            writer.Close();
        }
Beispiel #3
0
 private void Dispose(bool v)
 {
     disposed = true;
     if (v && !keepOpen)
     {
         writer.Close();
         stream.Close();
     }
 }
Beispiel #4
0
        /// <summary>
        /// Serializes an object to an XML string. Unlike the other SerializeObject overloads
        /// this methods *returns a string* rather than a bool result!
        /// </summary>
        /// <param name="value">Value to serialize</param>
        /// <param name="throwExceptions">Determines if a failure throws or returns null</param>
        /// <returns>
        /// null on error otherwise the Xml String.
        /// </returns>
        /// <remarks>
        /// If null is passed in null is also returned so you might want
        /// to check for null before calling this method.
        /// </remarks>
        public static string Serialize(object value, bool throwExceptions = false, bool formatJsonOutput = false)
        {
            string         jsonResult = null;
            Type           type       = value.GetType();
            JsonTextWriter writer     = null;

            try
            {
                var json = CreateJsonNet(throwExceptions);

                StringWriter sw = new StringWriter();

                writer = new JsonTextWriter(sw);

                if (formatJsonOutput)
                {
                    writer.Formatting = Formatting.Indented;
                }

                writer.QuoteChar = '"';
                json.Serialize(writer, value);

                jsonResult = sw.ToString();
                writer.Close();
            }
            catch (Exception ex)
            {
                if (throwExceptions)
                {
                    throw ex;
                }

                jsonResult = null;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }

            return(jsonResult);
        }
Beispiel #5
0
        public bool CheckResponse(string rawResponse, out string apiResponse, out SimpleRESTfulReturn type)
        {
            //XNamespace soap = "http://schemas.xmlsoap.org/soap/envelope/";
            XNamespace ns1 = Namespace; //"http://www.primeton.com/ProjectInfoManService";
            XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

            #region comments a sample response
            //              string data = @"
            // <soapenv:Envelope
            //     xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"">
            //     <soapenv:Body>
            //         <_tns_:saveContractServiceResponse
            //             xmlns:_tns_=""http://www.primeton.com/ProjectInfoManService"">
            //             <ns1:flag xsi:nil=""true""
            //                 xmlns:ns1=""http://www.primeton.com/ProjectInfoManService""
            //                 xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""/>
            //             <ns1:msg xsi:nil=""error message""
            //                 xmlns:ns1=""http://www.primeton.com/ProjectInfoManService""
            //                 xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""/>
            //         </_tns_:saveContractServiceResponse>
            //     </soapenv:Body>
            // </soapenv:Envelope>
            //             ";
            #endregion

            try
            {
                var envelope = XElement.Parse(rawResponse);
                var flag     = envelope.Descendants(ns1 + "flag")
                               .FirstOrDefault().Attribute(xsi + "nil").Value;
                var msg = envelope.Descendants(ns1 + "msg")
                          .FirstOrDefault().Attribute(xsi + "nil").Value;

                StringBuilder returnJsonBuilder = new StringBuilder();
                using (JsonWriter jwriter = new JsonTextWriter(new StringWriter(returnJsonBuilder)))
                {
                    jwriter.Formatting = Formatting.Indented;
                    jwriter.WriteStartObject();
                    jwriter.WritePropertyName("flag");
                    jwriter.WriteValue(flag);
                    jwriter.WritePropertyName("msg");
                    jwriter.WriteValue(msg);
                    jwriter.WriteEndObject();
                    jwriter.Close();
                }

                type        = SimpleRESTfulReturn.Json;
                apiResponse = returnJsonBuilder.ToString();
                return(true);
            }
            catch (Exception ex) {
                type        = SimpleRESTfulReturn.PlainText;
                apiResponse = ex.ToString() + "\r\n ****** \r\n" + rawResponse;
                return(false);
            }
        }
Beispiel #6
0
        /// <summary>
        /// 生成项目配置文件
        /// </summary>
        /// <param name="ionicCompile"></param>
        private void BuildProjectConfig(IonicCompile ionicCompile)
        {
            StringBuilder sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
            {
                JsonWriter jsonWriter = new JsonTextWriter(sw);
                jsonWriter.Formatting = Formatting.Indented;

                var frontConfig = ionicCompile.Project.Configures.OfType <FrontEndConfigure>().FirstOrDefault();
                //创建配置对象
                jsonWriter.WriteStartObject();
                #region
                jsonWriter.WritePropertyName("projectid");
                jsonWriter.WriteValue(ionicCompile.ProjectId);
                jsonWriter.WritePropertyName("name");
                jsonWriter.WriteValue(ionicCompile.Project.Identity);
                jsonWriter.WritePropertyName("title");
                jsonWriter.WriteValue(ionicCompile.Project.Root.Title);
                jsonWriter.WritePropertyName("desc");
                jsonWriter.WriteValue(ionicCompile.Project.Description);
                jsonWriter.WritePropertyName("api_endpoint");
                jsonWriter.WriteValue(frontConfig.ServerUrl + "odata" + "/" + ionicCompile.Project.Identity);
                #endregion
                jsonWriter.WriteEndObject();

                //获取JSON串
                string output = sw.ToString();
                jsonWriter.Close();
                sw.Close();

                var    targetDirectory = new System.IO.FileInfo(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath).Directory.FullName;
                string outputPath      = Path.Combine(targetDirectory.Replace("\\Wilmar.Service\\bin\\Extension", ""), @"Wilmar.Mobile\src\config", ionicCompile.Project.Identity);
                outputPath = HttpUtility.UrlDecode(outputPath);
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                var file = Path.Combine(outputPath, ionicCompile.Project.Identity + ".config.ts");
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
                string content = string.Format("export const {0}_CONFIG=", ionicCompile.Project.Identity.ToUpper()) + output;
                File.WriteAllText(file, content, System.Text.UTF8Encoding.UTF8);

                var devFile = Path.Combine(outputPath, ionicCompile.Project.Identity + ".config.dev.ts");
                if (File.Exists(devFile))
                {
                    File.Delete(devFile);
                }
                string devContent = string.Format("export const {0}_CONFIG=", ionicCompile.Project.Identity.ToUpper()) + output;
                File.WriteAllText(devFile, devContent, System.Text.UTF8Encoding.UTF8);
            }
        }
        public void SaveData(Customer c)
        {
            JsonSerializer js = new JsonSerializer();
            StreamWriter   sw = new StreamWriter(path);
            JsonWriter     jw = new JsonTextWriter(sw);

            js.Serialize(jw, c);
            jw.Close();
            sw.Close();
        }
        private static void CvtAndSave2Json(Dictionary <string, CodeTypeDeclaration> map2TypesLevelOne, string fileName)
        {
            var jsonObj = JsonConvert.SerializeObject(map2TypesLevelOne);//Prepare

            using (var jsonWriter = new JsonTextWriter(new StreamWriter(fileName)))
            {
                jsonWriter.WriteRaw(jsonObj);
                jsonWriter.Flush(); jsonWriter.Close();
            }
        }
        /**
         * NOS GUARDA EL JSON DE ACTIVIDADES
         **/
        public static void guardarJsonact()
        {
            string         arxiuact  = "actividades.json";
            JArray         jArrayAct = (JArray)JToken.FromObject(actividades);
            StreamWriter   file      = File.CreateText(arxiuact);
            JsonTextWriter writer    = new JsonTextWriter(file);

            jArrayAct.WriteTo(writer);
            writer.Close();
        }
Beispiel #10
0
        void Serialize <T>(string nFileName, T nT)
        {
            StreamWriter   streamWriter_   = new StreamWriter(nFileName);
            JsonWriter     jsonWriter_     = new JsonTextWriter(streamWriter_);
            JsonSerializer jsonSerializer_ = new JsonSerializer();

            jsonSerializer_.Serialize(jsonWriter_, nT);
            jsonWriter_.Close();
            streamWriter_.Close();
        }
        /**
         * NOS GUARDA EL JSON DE OPINIONES
         **/
        public static void guardarJsonop()
        {
            string         arxiuop   = "opiniones.json";
            JArray         jArrayOps = (JArray)JToken.FromObject(opiniones);
            StreamWriter   file      = File.CreateText(arxiuop);
            JsonTextWriter writer    = new JsonTextWriter(file);

            jArrayOps.WriteTo(writer);
            writer.Close();
        }
        /**
         * NOS GUARDA EL JSON DE USUARIOS
         **/
        public static void guardarJsonusers()
        {
            string         arxiuuser   = "******";
            JArray         jArrayUsers = (JArray)JToken.FromObject(usuarios);
            StreamWriter   file        = File.CreateText(arxiuuser);
            JsonTextWriter writer      = new JsonTextWriter(file);

            jArrayUsers.WriteTo(writer);
            writer.Close();
        }
        /**
         * NOS GUARDA EL JSON DE LIBROS
         **/
        public static void guardarJsonbooks()
        {
            string         arxiubook   = "libros.json";
            JArray         jArrayBooks = (JArray)JToken.FromObject(libros);
            StreamWriter   file        = File.CreateText(arxiubook);
            JsonTextWriter writer      = new JsonTextWriter(file);

            jArrayBooks.WriteTo(writer);
            writer.Close();
        }
        /**
         * NOS GUARDA EL JSON DE LIBRERIAS
         **/
        public static void guardarJsonlibs()
        {
            string         arxiulib   = "librerias.json";
            JArray         jArrayLibs = (JArray)JToken.FromObject(librerias);
            StreamWriter   file       = File.CreateText(arxiulib);
            JsonTextWriter writer     = new JsonTextWriter(file);

            jArrayLibs.WriteTo(writer);
            writer.Close();
        }
        /// <summary>
        /// Función para guardar los personajes (Llamaremos a esta función cuando le demos click al botón de guardar o bien cuando cerremos el formulario).
        /// </summary>
        /// <param name="personajes"></param>
        /// <param name="path_json"></param>
        private void GuardarPersonajes(BindingList <Personaje> personajes, string path_json)
        {
            JArray         arrayPersonajes = (JArray)JToken.FromObject(personajes);
            StreamWriter   ficheroSalida   = File.CreateText(path_json);
            JsonTextWriter jsonTextWriter  = new JsonTextWriter(ficheroSalida);

            arrayPersonajes.WriteTo(jsonTextWriter);
            ficheroSalida.Close();
            jsonTextWriter.Close();
        }
        private void guardar()
        {
            JArray         JArrayActividad = (JArray)JToken.FromObject(actividad); // agafem la llista i desde el objecte (fromObject) crea el JToken i el pasa a JArray
            StreamWriter   fitxer          = File.CreateText(@"actividades.json"); // agafa el fitxer i el "converteix" amb json || @ per que sapiga que es una ruta
            JsonTextWriter jsonWriter      = new JsonTextWriter(fitxer);           // escriu en el fitxer que hem creat abans

            JArrayActividad.WriteTo(jsonWriter);                                   // guarda lo del array al jsonWriter

            jsonWriter.Close();
        }
        /**
         * NOS GUARDA EL JSON DE VISITAS
         **/
        public static void guardarJsonviews()
        {
            string         arxiuviews  = "visitas.json";
            JArray         jArrayViews = (JArray)JToken.FromObject(visitas);
            StreamWriter   file        = File.CreateText(arxiuviews);
            JsonTextWriter writer      = new JsonTextWriter(file);

            jArrayViews.WriteTo(writer);
            writer.Close();
        }
Beispiel #18
0
        public static void SaveConfig(PolyConfig cfg)
        {
            StreamWriter   sw         = new StreamWriter(PolyConstants.ConfigFileName);
            JsonWriter     writer     = new JsonTextWriter(sw);
            JsonSerializer serializer = new JsonSerializer();

            serializer.Serialize(writer, cfg);
            writer.Close();
            sw.Close();
        }
Beispiel #19
0
 public void Close()
 {
     if (_isOpen)
     {
         _isOpen = false;
         _writer.WriteEndArray();
         _writer.Flush();
     }
     _writer.Close();
 }
Beispiel #20
0
        /// <summary>
        /// 生成平台配置文件
        /// </summary>
        /// <param name="ionicCompile"></param>
        private void BuildPlatformConfig(IonicCompile ionicCompile)
        {
            StringBuilder sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
            {
                JsonWriter jsonWriter = new JsonTextWriter(sw);
                jsonWriter.Formatting = Formatting.Indented;

                var frontConfig = ionicCompile.Project.Configures.OfType <FrontEndConfigure>().FirstOrDefault();
                //创建配置对象
                jsonWriter.WriteStartObject();
                #region
                jsonWriter.WritePropertyName("name");
                jsonWriter.WriteValue("kds3.0 Mobile");
                jsonWriter.WritePropertyName("title");
                jsonWriter.WriteValue("kds3.0 移动端");
                jsonWriter.WritePropertyName("version");
                jsonWriter.WriteValue("1.0.0");
                jsonWriter.WritePropertyName("desc");
                jsonWriter.WriteValue("kds3.0 移动端平台系统");
                jsonWriter.WritePropertyName("logo");
                jsonWriter.WriteValue("kds3.0 logo");

                jsonWriter.WritePropertyName("startup_page");
                jsonWriter.WriteValue(ionicCompile.Project.Identity);
                jsonWriter.WritePropertyName("login_page");
                jsonWriter.WriteValue("Login");

                jsonWriter.WritePropertyName("auth_endpoint");
                jsonWriter.WriteValue(frontConfig.ServerUrl);
                #endregion
                jsonWriter.WriteEndObject();

                //获取JSON串
                string output = sw.ToString();
                jsonWriter.Close();
                sw.Close();

                var    targetDirectory = new System.IO.FileInfo(new Uri(this.GetType().Assembly.CodeBase).AbsolutePath).Directory.FullName;
                string outputPath      = Path.Combine(targetDirectory.Replace("\\Wilmar.Service\\bin\\Extension", ""), @"Wilmar.Mobile\src\config", "platform");
                outputPath = HttpUtility.UrlDecode(outputPath);
                var file = Path.Combine(outputPath, "platform.config.ts");
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
                string content = string.Format("export const PLATFORM_CONFIG=") + output;
                File.WriteAllText(file, content, System.Text.UTF8Encoding.UTF8);
            }
        }
        private void ParseJSON()
        {
            StringBuilder stringBuilder = new StringBuilder();
            StringWriter  stringWriter  = new StringWriter(stringBuilder);
            JsonWriter    jsonWriter    = new JsonTextWriter(stringWriter);

            jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;

            jsonWriter.WriteStartObject();
            UInt64 reqTimeSinceTrackingStartMs = (m_reqTimeUTC - m_startTimeUTC) / TimeSpan.TicksPerMillisecond;

            //write out all of the service call properties
            jsonWriter.WritePropertyName("Host"); jsonWriter.WriteValue(m_host);
            jsonWriter.WritePropertyName("Id"); jsonWriter.WriteValue(m_id);
            jsonWriter.WritePropertyName("XboxUserId"); jsonWriter.WriteValue(m_xboxUserId);
            jsonWriter.WritePropertyName("BreadCrumb"); jsonWriter.WriteValue(m_breadCrumb);
            jsonWriter.WritePropertyName("StartTimeUTC"); jsonWriter.WriteValue(m_startTimeUTC);
            jsonWriter.WritePropertyName("ReqTimeUTC"); jsonWriter.WriteValue(m_reqTimeUTC);
            jsonWriter.WritePropertyName("ReqTimeSinceTrackingStartMs"); jsonWriter.WriteValue(reqTimeSinceTrackingStartMs);
            if (m_isShoulderTap)
            {
                jsonWriter.WritePropertyName("IsShoulderTap"); jsonWriter.WriteValue(m_isShoulderTap);
                jsonWriter.WritePropertyName("SessionReferenceUriPath"); jsonWriter.WriteValue(m_sessionReferenceUriPath);
                jsonWriter.WritePropertyName("Branch"); jsonWriter.WriteValue(m_branch);
                jsonWriter.WritePropertyName("ChangeNumber"); jsonWriter.WriteValue(m_changeNumber);
            }
            else
            {
                bool isSuccess = Utils.IsSucessHTTPStatusCode(m_httpStatusCode);

                jsonWriter.WritePropertyName("Uri"); jsonWriter.WriteValue(m_uri);
                jsonWriter.WritePropertyName("IsGet"); jsonWriter.WriteValue(m_isGet);
                jsonWriter.WritePropertyName("HttpStatusCode"); jsonWriter.WriteValue(m_httpStatusCode);
                jsonWriter.WritePropertyName("MultiplayerCorrelationId"); jsonWriter.WriteValue(m_multiplayerCorrelationId);
                jsonWriter.WritePropertyName("ElapsedCallTimeMs"); jsonWriter.WriteValue(m_elapsedCallTimeMs);
                jsonWriter.WritePropertyName("RequestHeaders"); jsonWriter.WriteValue(m_reqHeader);
                jsonWriter.WritePropertyName("RequestBody"); jsonWriter.WriteValue(m_reqBody);

                jsonWriter.WritePropertyName("RequestBodyHashCode"); jsonWriter.WriteValue(m_reqBody.GetHashCode());
                jsonWriter.WritePropertyName("ResponseBody"); jsonWriter.WriteValue(m_rspBody);

                if (!isSuccess)
                {
                    jsonWriter.WritePropertyName("ResponseHeaders"); jsonWriter.WriteValue(m_rspHeader);
                    jsonWriter.WritePropertyName("FullResponse"); jsonWriter.WriteValue(m_rspFullString);
                }
            }

            jsonWriter.WriteEndObject();
            m_callDataFromJSON = stringBuilder.ToString();
            stringWriter.Close();
            jsonWriter.Close();
            stringWriter = null;
            jsonWriter   = null;
        }
Beispiel #22
0
        /// <summary>
        /// DataTable 对象 转换为Json 字符串
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToJson(this DataTable dt)
        {
            //JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            //javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
            //ArrayList arrayList = new ArrayList();
            //foreach (DataRow dataRow in dt.Rows)
            //{
            //    Dictionary<string, object> dictionary = new Dictionary<string, object>();  //实例化一个参数集合
            //    foreach (DataColumn dataColumn in dt.Columns)
            //    {
            //        if (dataColumn.DataType == typeof(string) || dataColumn.DataType == typeof(DateTime))
            //            dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToStr());
            //        else
            //            dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName]);
            //    }
            //    arrayList.Add(dictionary); //ArrayList集合中添加键值
            //}
            //return javaScriptSerializer.Serialize(arrayList);  //返回一个json字符串

            //return JsonConvert.SerializeObject(dt, new DataTableConverter());

            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            using (JsonWriter jw = new JsonTextWriter(sw))
            {
                JsonSerializer ser = new JsonSerializer();
                //jw.WriteStartObject();
                //jw.WritePropertyName(dt.TableName);
                jw.WriteStartArray();
                foreach (DataRow dr in dt.Rows)
                {
                    jw.WriteStartObject();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        jw.WritePropertyName(dc.ColumnName);
                        if (dc.DataType == typeof(string) || dc.DataType == typeof(DateTime))
                        {
                            ser.Serialize(jw, dr[dc].ToString());
                        }
                        else
                        {
                            ser.Serialize(jw, dr[dc]);
                        }
                    }
                    jw.WriteEndObject();
                }
                jw.WriteEndArray();
                //jw.WriteEndObject();
                sw.Close();
                jw.Close();
            }

            return(sb.ToString());
        }
Beispiel #23
0
        public static void File(string fileName, eventVar _eventVar)
        {
            try
            {
                //Import config variables
                Config.softwareConfig cfg = new Config.softwareConfig();

                if (System.IO.File.Exists(MainWindow.workingDir + "\\Config\\" + fileName + "decrypted"))
                {
                    System.IO.File.Delete(MainWindow.workingDir + "\\Config\\" + fileName + "decrypted");

                    using (FileStream fs = System.IO.File.Open(MainWindow.workingDir + "\\Config\\" + fileName + "decrypted", FileMode.CreateNew))
                        using (StreamWriter sw = new StreamWriter(fs))
                            using (JsonWriter jw = new JsonTextWriter(sw))
                            {
                                jw.Formatting = Formatting.Indented;

                                JsonSerializer serializer = new JsonSerializer();
                                serializer.Serialize(jw, _eventVar);
                                jw.Close();
                                sw.Close();
                                fs.Close();
                            }

                    string json        = System.IO.File.ReadAllText(MainWindow.workingDir + "\\Config\\" + fileName + "decrypted");
                    string encryptJson = CryptoService.Load.Encrypt(json, cfg.cipherKey);
                    System.IO.File.WriteAllText(MainWindow.workingDir + "\\Config\\" + fileName, encryptJson);
                    System.IO.File.Delete(MainWindow.workingDir + "\\Config\\" + fileName + "decrypted");
                }
                else
                {
                    using (FileStream fs = System.IO.File.Open(MainWindow.workingDir + "\\Config\\" + fileName + "decrypted", FileMode.CreateNew))
                        using (StreamWriter sw = new StreamWriter(fs))
                            using (JsonWriter jw = new JsonTextWriter(sw))
                            {
                                jw.Formatting = Formatting.Indented;

                                JsonSerializer serializer = new JsonSerializer();
                                serializer.Serialize(jw, _eventVar);
                                jw.Close();
                                sw.Close();
                                fs.Close();

                                string json        = System.IO.File.ReadAllText(MainWindow.workingDir + "\\Config\\" + fileName + "decrypted");
                                string encryptJson = CryptoService.Load.Encrypt(json, cfg.cipherKey);
                                System.IO.File.WriteAllText(MainWindow.workingDir + "\\Config\\" + fileName, encryptJson);
                                System.IO.File.Delete(MainWindow.workingDir + "\\Config\\" + fileName + "decrypted");
                            }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Beispiel #24
0
        private string BuildTable(IEnumerable <DataRow> rows, ISampler <DataRow> sampler)
        {
            var sb     = new StringBuilder();
            var sw     = new StringWriter(sb);
            var writer = new JsonTextWriter(sw);

            BuildTable(rows, sampler, writer);

            writer.Close();
            return(sb.ToString());
        }
Beispiel #25
0
 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - GetUPCONFIG //
 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FILE WRITING ->
 public void SavingJsonFile(string filename, AsociationDataes entidad)
 {
     if (entidad != null)
     {
         JObject        jsonentidad = (JObject)JToken.FromObject(entidad);
         StreamWriter   fichero     = File.CreateText(FILE_PATH + filename + ".json");
         JsonTextWriter jsonwriter  = new JsonTextWriter(fichero);
         jsonentidad.WriteTo(jsonwriter);
         jsonwriter.Close();
     }
 }
        public void Writejson(int index, List <ConfigsItem> configs, string path)
        {
            //子集
            //Hashtable device = new Hashtable();
            //device.Add("id", "001111");
            //device.Add("name", "相机");
            //device.Add("ip", "192.168.1.1");


            GoProxyCongfigs lot = new GoProxyCongfigs(); //实体模型类

            //lot.Name = "lotname";
            //lot.Address = "wenzhou";
            lot.index   = index;
            lot.configs = configs; //注意是子集
            //lot.Doors = "4";

            //序列化
            string js1 = JsonConvert.SerializeObject(lot);
            //string js2 = JsonConvert.SerializeObject(device);

            //反序列化
            GoProxyCongfigs debc1 = JsonConvert.DeserializeObject <GoProxyCongfigs>(js1);
            //LotModel debc2 = JsonConvert.DeserializeObject<LotModel>(js2);

            //找到服务器物理路径
            //string serverAppPath = Request.PhysicalApplicationPath.ToString();
            //string serverAppPath = @"d:\";
            //构成配置文件路径
            //string con_file_path = @"" + serverAppPath + @"config.json";
            string con_file_path = path;

            if (!File.Exists(con_file_path))
            {
                //File.Create(con_file_path);
                File.Create(con_file_path).Close();
            }

            //把模型数据写到文件
            using (StreamWriter sw = new StreamWriter(con_file_path))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Converters.Add(new JavaScriptDateTimeConverter());
                serializer.NullValueHandling = NullValueHandling.Ignore;

                //构建Json.net的写入流
                JsonWriter writer = new JsonTextWriter(sw);
                //把模型数据序列化并写入Json.net的JsonWriter流中
                serializer.Serialize(writer, lot);
                //ser.Serialize(writer, ht);
                writer.Close();
                sw.Close();
            }
        }
Beispiel #27
0
        /// <summary>
        /// Выполняет сериализацию проекта по указанному пути.
        /// </summary>
        /// <param name="filePath">Путь к файлу проекта.</param>
        /// <param name="project">Текущий проект.</param>
        private void SaveProjectInternally(string filePath, Project project)
        {
            JsonSerializer serializer = new JsonSerializer();

            using (StreamWriter sw = new StreamWriter(filePath))
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    serializer.Serialize(writer, project);
                    writer.Close();
                }
        }
Beispiel #28
0
        /// <summary>
        /// Starting game
        ///     - retrieves output (startup)
        ///     - ignore output (save)
        ///
        /// Entering a command
        ///     - ignore output (startup and load)
        ///     - retrieves output (command)
        ///     - ignore output (save)
        ///
        /// </summary>
        /// <param name="package"></param>
        private void HandleOutput(Dictionary <string, string> package)
        {
            // Reset hashtable
            outputHash = package;

            //XmlWriterSettings settings = new XmlWriterSettings();
            //settings.OmitXmlDeclaration = true;
            StringWriter sWriter = new StringWriter();

            //using (XmlWriter writer = XmlWriter.Create(sWriter, settings))
            //{
            //    // Open XML stream
            //    writer.WriteStartDocument();
            //    writer.WriteStartElement("fyrevm");
            //    writer.WriteStartElement("channels");

            //    // loop through results and output to xml
            //    foreach (string channel in package.Keys)
            //    {
            //        SetChannelData(channel, package, writer);
            //    }

            //    writer.WriteEndElement();
            //    writer.WriteEndElement();
            //    writer.WriteEndDocument();

            //    writer.Flush();
            //    outputXML = sWriter.ToString();
            //}

            StringBuilder data = sWriter.GetStringBuilder();

            // Open JSON stream
            sWriter = new StringWriter();
            JsonTextWriter jWriter = new JsonTextWriter(sWriter);

            jWriter.WriteStartObject();
            jWriter.WritePropertyName("channels");
            jWriter.WriteStartArray();

            foreach (string channel in package.Keys)
            {
                jWriter.WriteStartObject();
                SetChannelDataJSON(channel, package, jWriter);
                jWriter.WriteEndObject();
            }

            jWriter.WriteEndArray();
            jWriter.WriteEndObject();
            jWriter.Close();

            data       = sWriter.GetStringBuilder();
            outputJSON = data.ToString();
        }
Beispiel #29
0
        // - - - - - - - - - - - - - - - - - - - - GRABA JSON
        private void savedata()
        {
            JArray         jsonobject = (JArray)JToken.FromObject(selidiomas);
            StreamWriter   fichero    = File.CreateText(fullpath + FILEPATH + LANGFILNAM + "E" + nExpoId + JSONEXTNSN);
            JsonTextWriter jsonwriter = new JsonTextWriter(fichero);

            jsonobject.WriteTo(jsonwriter);
            jsonwriter.Close();
            IsModify = false;
            setmessagelabel("Datos grabados...");
        }
Beispiel #30
0
        //Pasa el contenido del textBoxDescripcionRed a un objecto y ese objeto al archivo JSON.
        private void buttonPasarAJSON_Click(object sender, EventArgs e)
        {
            red.descripcion = textBoxDescripcionRed.Text;
            JObject        jObjectDescripcion = (JObject)JToken.FromObject(red);
            StreamWriter   fichero            = File.CreateText(jsonName);
            JsonTextWriter jsonWriter         = new JsonTextWriter(fichero);

            jObjectDescripcion.WriteTo(jsonWriter);

            jsonWriter.Close();
        }