public JsonClass Build(string json) { var jsonClass = new JsonClass(); json = ParseSubObjects(jsonClass, json); ParseProperties(jsonClass, json); return jsonClass; }
private void ParseProperties(JsonClass jsonClass, string json) { var matches = PropertyRegex.Matches(json); foreach (Match match in matches) { var name = match.Groups["name"].Value; var value = match.Groups["value"].Value.Trim(); jsonClass.Add(name, JsonObjectFactory.BuildJsonObject(value)); } }
private static void SaveDependencies() { Objects = new List<KeyValuePair<string, string>>(); Dependencies = new List<KeyValuePair<string, List<string>>>(); foreach (var obj in Selection.objects) { List<string> deps = new List<string>(); string objPath = AssetDatabase.GetAssetPath(obj); objPath = objPath.Replace("Assets/Resources/", ""); int fileExtPos = objPath.LastIndexOf('.'); objPath = objPath.Substring(0, fileExtPos); Objects.Add(new KeyValuePair<string, string>(obj.name, objPath)); var dependencies = EditorUtility.CollectDependencies(new[] { obj }); foreach (var d in dependencies) { string path = AssetDatabase.GetAssetPath(d); if (path.Contains("Assets/Resources/")) { path = path.Replace("Assets/Resources/", ""); fileExtPos = path.LastIndexOf('.'); path = path.Substring(0, fileExtPos); if (d is Texture2D || d is Material || d is Shader) { deps.Add(path); } } } Dependencies.Add(new KeyValuePair<string, List<string>>(obj.name, deps)); } JsonRoot root = new JsonRoot(); int count = 0; foreach (var obj in Objects) { JsonClass jsonObject = new JsonClass(count.ToString()); jsonObject.AddObjects(new JsonValue(ObjectFromCache.JsonName, obj.Key)); jsonObject.AddObjects(new JsonValue(ObjectFromCache.JsonPath, obj.Value)); jsonObject.AddObjects(new JsonArray(ObjectFromCache.JsonDependencies, Dependencies.Find((d)=> obj.Key == d.Key).Value)); root.AddObjects(jsonObject); count++; } string filepath = EditorUtility.SaveFilePanel("Save dependencies for selected objects", "Assets", "Dependencies", "json"); File.WriteAllText(filepath, root.ToString(), Encoding.UTF8); }
public void StructCanBeSerializedAsJsonParameter() { var input = new JsonClass(); input.SubStruct = new JsonSubStruct() { Foo = "foo", Bar = 5 }; Assert.AreEqual("{\"Bar\":5,\"Foo\":\"foo\"}", Connection().Single<string>("StructAsJsonParameter", input)); var result = Connection().Query<JsonClass, JsonSubStruct>("StructAsJsonParameter", input).First(); Assert.AreEqual(input.SubStruct.Foo, result.SubStruct.Foo); Assert.AreEqual(input.SubStruct.Bar, result.SubStruct.Bar); }
public void ClassCanBeSerializedAsJsonParameter() { var input = new JsonClass(); input.SubClass = new JsonSubClass() { Foo = "foo", Bar = 5 }; Assert.AreEqual("{\"Bar\":5,\"Foo\":\"foo\"}", Connection().Single<string>("ClassAsJsonParameter", input)); var result = Connection().Query<JsonClass, JsonSubClass>("ClassAsJsonParameter", input).First(); Assert.IsNotNull(result.SubClass); Assert.AreEqual(input.SubClass.Foo, result.SubClass.Foo); Assert.AreEqual(input.SubClass.Bar, result.SubClass.Bar); }
private string ParseSubObjects(JsonClass jsonClass, string json) { var classMatches = ClassRegex.Matches(json); foreach (Match classMatch in classMatches) { var name = classMatch.Groups["name"].Value; var value = classMatch.Groups["value"].Value; jsonClass[name] = Build(value); json = json.Replace(classMatch.Value, ""); } return json; }
public static void TestJsonSerialize() { JsonClass jsonObj = new JsonClass(); jsonObj._value = 99; string serializedObj = JsonWriter.Serialize(jsonObj); Console.WriteLine("serializedObj : {0}", serializedObj); JsonClass deserializedObj = JsonReader.Deserialize<JsonClass>(serializedObj); Console.WriteLine("value : {0}", deserializedObj._value); }
public void ListOfClassCanBeSerializedAsJsonParameter() { var input = new JsonClass(); input.ListOfClass = new List<JsonSubClass>(); input.ListOfClass.Add(new JsonSubClass() { Foo = "foo", Bar = 5 }); input.ListOfClass.Add(new JsonSubClass() { Foo = "foo2", Bar = 6 }); Assert.AreEqual("[{\"Bar\":5,\"Foo\":\"foo\"},{\"Bar\":6,\"Foo\":\"foo2\"}]", Connection().Single<string>("ListAsJsonParameter", input)); var result = Connection().Query<JsonClass, JsonSubClass>("ListAsJsonParameter", input).First(); Assert.IsNotNull(result.ListOfClass); Assert.AreEqual(input.ListOfClass.Count, result.ListOfClass.Count); Assert.AreEqual(input.ListOfClass[0].Foo, result.ListOfClass[0].Foo); }
public void TestJsonNetOverride() { JsonNetObjectSerializer.Initialize(); using (var connection = ConnectionWithTransaction()) { connection.ExecuteSql("CREATE PROC ClassAsJsonNetParameter @SubClass [varchar](max) AS SELECT SubClass=@SubClass"); var input = new JsonClass(); input.SubClass = new JsonSubClass() { Foo = "foo", Bar = 5 }; Assert.AreEqual("{\"Foo\":\"foo\",\"Bar\":5}", connection.Single<string>("ClassAsJsonNetParameter", input)); var result = connection.Query<JsonClass, JsonSubClass>("ClassAsJsonNetParameter", input).First(); Assert.IsNotNull(result.SubClass); Assert.AreEqual(input.SubClass.Foo, result.SubClass.Foo); Assert.AreEqual(input.SubClass.Bar, result.SubClass.Bar); } }
public void Leave() { Time.timeScale = 1; if (GameManager.Instance.battleType == BattleType.mine) { MineManager.battleFlag = isWin ? 1 : 2; GameManager.Instance.ChangeScene(SceneType.mine); } else { JsonClass obj = new JsonClass(); obj["win"] = isWin ? 1 : 0; obj["rivalId"] = GameServer.data["arena"]["battleData"][0]["owner"]; GameServer.Instance.Request(ServerAction.finishArenaBattle, obj, delegate() { TownManager.battleFlag = isWin ? 1 : 2; GameManager.Instance.ChangeScene(SceneType.town); }); } }
public static string getCallFile(string Date, string filename, TaskCallback call) { string[] array = FormatFunctions.CleanDate(Date); string df_text = string.Concat(new string[] { @"CDR\", array[0], @"\", array[1], @"\", array[2], @"\", filename }); string s = JsonClass.JSONSerialize <DatabaseFunctions.data>(new DatabaseFunctions.data { df_text1 = df_text }); byte[] bytes = Encoding.UTF8.GetBytes(s); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://174.114.166.80/getCusFile.php"); httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.ContentLength = (long)bytes.Length; httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length); Stream responseStream = ((HttpWebResponse)httpWebRequest.GetResponse()).GetResponseStream(); int num = 1024; byte[] buffer = new byte[num]; string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); FileStream fileStream = File.Create(path + "CHStreamFile" + filename); int count; while ((count = responseStream.Read(buffer, 0, num)) != 0) { fileStream.Write(buffer, 0, count); } httpWebRequest.Abort(); return("CHStreamFile" + filename); }
public Object OTP([FromBody] CustomerLogin OTPM) { var json = (object)null; try { DataSet ds_custdet = new DataSet(); DataTable dt_CRM = new DataTable(); string SendText = string.Empty; int OTP = OTPGENERATION(); try { string httpUrl = string.Empty; { SendText = "Mobile Number Verification OTP is :" + OTP; StreamReader objReader; //httpUrl = "http://sms.smscity.in/httpapi/httpapi?token=8c84bb208c7c7b7b72660ef51a5430b0&sender=NRNGYM&number=0" + OTPM.MobileNo + "&route=2&type=1&sms='" + SendText + "' "; //httpUrl = "http://api.textlocal.in/[email protected]&hash=f94d56486adbd53db4d28bcc515c415ef49267fc&numbers=" + OTPM.MobileNo + "&message=" + SendText + "&sender=SUCARD "; System.Net.WebRequest webRequest = System.Net.WebRequest.Create(httpUrl); Stream objstream; objstream = webRequest.GetResponse().GetResponseStream(); objReader = new StreamReader(objstream); objReader.Close(); } } catch (Exception ex) { json = "Internal Server Error" + ex.ToString(); } finally { json = Json(OTPM, JsonRequestBehavior.AllowGet); } cnn.Close(); } catch (Exception ex) { json = "Internal Server Error" + ex.ToString(); } return(json); }
public static async void SendToPhpB(bool PBX, string statement, TaskCallback call) { try { data d = new data(); d.df_text1 = statement; string requestUriString; if (inOffice()) { if (PBX) { requestUriString = "http://192.168.0.69/accessPBX.php"; } else { requestUriString = "http://192.168.0.69/access.php"; } } else { if (PBX) { requestUriString = "http://174.114.166.80/accessPBX.php"; } else { requestUriString = "http://174.114.166.80/access.php"; } } string text = JsonClass.JSONSerialize <DatabaseFunctions.data>(d); StringContent content = new StringContent(text, Encoding.UTF8); var result = await clientH.PostAsync(requestUriString, content).ConfigureAwait(false); var t = await result.Content.ReadAsStringAsync(); call(t); } catch (HttpRequestException e) { } }
public JsonResult ajax_try(string i) { Reservation reservation1 = new Reservation() { Rsid = 1, Name = "张三", Phone = 12345678911 }; Reservation reservation2 = new Reservation() { Rsid = 2, Name = "李四", Phone = 98765432111 }; //初始化list中要存放的数组 List <Reservation> list2 = new List <Reservation>(); list2.Add(reservation1); list2.Add(reservation2); JsonClass json = new JsonClass(); json.code = 200; json.dmsg = 1; // json.list = list2; //Hashtable ht = new Hashtable(); //ht.Add(1,reservation1); //ht.Add(2,reservation2); //JsonClass2 json2 = new JsonClass2(); //json2.code = 300; //json2.dmsg = 50; //json2.list = ht; return(Json(new { json, list2 })); }
public static void loginTest(string host, int port) { pc = new PomeloClient(); pc.NetWorkStateChangedEvent += (state) => { Console.WriteLine(state); }; pc.initClient(host, port, () => { pc.connect(null, data => { Console.WriteLine("on data back" + data.ToString()); JsonNode msg = new JsonClass(); msg["uid"] = new JsonData(111); pc.request("gate.gateHandler.queryEntry", msg, OnQuery); }); }); }
public Object ValidateLogin([FromBody] CustomerLogin Login) { var json = (object)null; try { DataSet ds_custdet1 = new DataSet(); DataTable dt_Login = new DataTable(); string query = "select Top 1 MobileNo,Password,EnquirePersonFirstName +' '+ EnquirePersonLastName as UserName,Address,RoleId,Lat,Long,Gender,Address,Email from CCRMMEnquireForm where MobileNo='" + Login.MobileNo + "' order by ID desc "; using (SqlDataAdapter da_custdet = new SqlDataAdapter(query, cnn)) { da_custdet.Fill(ds_custdet1); } if (ds_custdet1.Tables[0].Rows.Count > 0) { Login.MobileNo = ds_custdet1.Tables[0].Rows[0]["MobileNo"].ToString(); Login.Password = ds_custdet1.Tables[0].Rows[0]["Password"].ToString(); Login.UserName = ds_custdet1.Tables[0].Rows[0]["UserName"].ToString(); Login.Address = ds_custdet1.Tables[0].Rows[0]["Address"].ToString(); Login.RoleCode = Convert.ToInt32(ds_custdet1.Tables[0].Rows[0]["RoleId"].ToString()); Login.Lat = ds_custdet1.Tables[0].Rows[0]["Lat"].ToString(); Login.Long = ds_custdet1.Tables[0].Rows[0]["Long"].ToString(); Login.Gender = ds_custdet1.Tables[0].Rows[0]["Long"].ToString(); Login.Address = ds_custdet1.Tables[0].Rows[0]["Address"].ToString(); Login.EmailId = ds_custdet1.Tables[0].Rows[0]["Email"].ToString(); json = Json(Login, JsonRequestBehavior.AllowGet); } else { json = "User not found"; } } catch (Exception ec) { json = "Internal Server Error"; } return(json); }
public static void SendToPhp(string statement) { try { string text = JsonClass.JSONSerialize <data>(new data { df_text1 = statement }); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://192.168.0.69/access.php"); httpWebRequest.Method = "POST"; string s = text; byte[] bytes = Encoding.UTF8.GetBytes(s); httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.ContentLength = (long)bytes.Length; httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length); } catch (WebException ex) { string str = ex.ToString(); Console.WriteLine("--->" + str); } }
public void TestJsonNetOverride() { JsonNetObjectSerializer.Initialize(); using (var connection = ConnectionWithTransaction()) { connection.ExecuteSql("CREATE PROC ClassAsJsonNetParameter @SubClass [varchar](max) AS SELECT SubClass=@SubClass"); var input = new JsonClass(); input.SubClass = new JsonSubClass() { Foo = "foo", Bar = 5 }; Assert.AreEqual("{\"Foo\":\"foo\",\"Bar\":5}", connection.Single <string>("ClassAsJsonNetParameter", input)); var result = connection.Query <JsonClass, JsonSubClass>("ClassAsJsonNetParameter", input).First(); Assert.IsNotNull(result.SubClass); Assert.AreEqual(input.SubClass.Foo, result.SubClass.Foo); Assert.AreEqual(input.SubClass.Bar, result.SubClass.Bar); } }
internal override async Task <JsonNode> ToJson() { JsonClass jsonDependency = new JsonClass { { "name", this.ToString() } }; DependencyCheckStatus status = await this.GetStatus().ConfigureAwait(false); if (status.Version != null) { jsonDependency.Add("version", status.Version.ToString()); } if (status.CheckStatus != NAMEStatusLevel.Ok) { jsonDependency.Add("error", status.Message ?? "Unhandled error"); } jsonDependency.Add("status", status.CheckStatus.ToString()); jsonDependency.Add("min_version", this.MinimumVersion.ToString()); jsonDependency.Add("max_version", this.MaximumVersion?.ToString() ?? "*"); if (status.Version?.ManifestNode != null) { JsonNode infrastructureDependencies = status.Version.ManifestNode["infrastructure_dependencies"]; JsonNode serviceDependencies = status.Version.ManifestNode["service_dependencies"]; if (infrastructureDependencies != null) { jsonDependency.Add("infrastructure_dependencies", infrastructureDependencies); } if (serviceDependencies != null) { jsonDependency.Add("service_dependencies", serviceDependencies); } } return(jsonDependency); }
public void ListOfClassCanBeSerializedAsJsonParameter() { var input = new JsonClass(); input.ListOfClass = new List <JsonSubClass>(); input.ListOfClass.Add(new JsonSubClass() { Foo = "foo", Bar = 5 }); input.ListOfClass.Add(new JsonSubClass() { Foo = "foo2", Bar = 6 }); Assert.AreEqual("[{\"Bar\":5,\"Foo\":\"foo\"},{\"Bar\":6,\"Foo\":\"foo2\"}]", Connection().Single <string>("ListAsJsonParameter", input)); var result = Connection().Query <JsonClass, JsonSubClass>("ListAsJsonParameter", input).First(); Assert.IsNotNull(result.ListOfClass); Assert.AreEqual(input.ListOfClass.Count, result.ListOfClass.Count); Assert.AreEqual(input.ListOfClass[0].Foo, result.ListOfClass[0].Foo); }
public static void SendBatchToPHP(bool PBX, List <string> statement, List <TaskCallback> call) { for (int j = 0; j < statement.Count; j++) { try { data d = new data(); d.df_text1 = statement[j]; string requestUriString; if (PBX) { requestUriString = "http://174.114.166.80/accessPBX.php"; } else { requestUriString = "http://174.114.166.80/access.php"; } string text = JsonClass.JSONSerialize <DatabaseFunctions.data>(d); byte[] bytes = Encoding.UTF8.GetBytes(text); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUriString); httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.ContentLength = (long)bytes.Length; httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length); Stream responseStream = ((HttpWebResponse)httpWebRequest.GetResponse()).GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream); call[j](streamReader.ReadToEnd()); httpWebRequest.Abort(); streamReader.Close(); responseStream.Close(); } catch (WebException ex) { string str = ex.ToString(); Console.WriteLine("--->" + str); } } }
private JsonNode buildMsg(JsonNode user) { if (user == null) { user = new JsonClass(); } JsonNode msg = new JsonClass(); //Build sys option JsonNode sys = new JsonClass(); sys.Add("version", new JsonData(Version)); sys.Add("type", new JsonData(Type)); //Build handshake message msg.Add("sys", sys); msg.Add("user", user); UnityEngine.Debug.Log(msg); return(msg); }
public static void SendToPDFPrinter(string data) { try { string text = JsonClass.JSONSerialize <DatabaseFunctions.data>(new DatabaseFunctions.data { df_text1 = data }); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://174.114.166.80/SendPDF.php"); httpWebRequest.Method = "POST"; string s = text; byte[] bytes = Encoding.UTF8.GetBytes(s); httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.ContentLength = (long)bytes.Length; httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length); httpWebRequest.Abort(); } catch (WebException ex) { string str = ex.ToString(); Console.WriteLine("--->" + str); } }
public static void SendBatchToPHP(List <string> statementList) { try { string[] statements = statementList.ToArray(); string text = JsonClass.JSONSerialize <DatabaseFunctions.dataArray>(new DatabaseFunctions.dataArray { BatchLength = statements.Length, statements = statements }); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://192.168.0.69/accessBatched.php"); httpWebRequest.Method = "POST"; string s = text; byte[] bytes = Encoding.UTF8.GetBytes(s); httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.ContentLength = (long)bytes.Length; httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length); } catch (WebException ex) { string str = ex.ToString(); Console.WriteLine("--->" + str); } }
private void button6_Click(object sender, EventArgs e) { try { List <JsonClass> table = new List <JsonClass>(); var a = db.Collocation.Where(x => x.Type == 1).ToList(); foreach (var item in a) { JsonClass cc = new JsonClass(); cc.s1 = item.CollocationName.Trim().Split(' ')[0].Trim().ToLower(); cc.s2 = item.CollocationName.Trim().Split(' ')[1].Trim().ToLower(); table.Add(cc); } Utilities.DataTableToJSONWithStringBuilder(table);//json oluşturuuyor // Check if file already exists. If yes, delete it. } catch (Exception Ex) { Console.WriteLine(Ex.ToString()); } }
public MasterClient() { logger.Info("Server started"); ConnectionFactory factory = new ConnectionFactory() { UserName = "******", Password = "******", HostName = "localhost" }; connection = factory.CreateConnection(); channel = connection.CreateModel(); channel.QueueDeclare(queue: "MasterClient", durable: false, exclusive: false, autoDelete: false, arguments: null); //channel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(channel); channel.BasicConsume(queue: "MasterClient", autoAck: true, consumer: consumer); consumer.Received += (model, ea) => { IBasicProperties props = ea.BasicProperties; if (!ClientsList.Exists((c) => c.QeueuName == props.ReplyTo)) { ClientsList.Add(new ClientPeer() { QeueuName = props.ReplyTo, LastUpTime = DateTime.UtcNow }); logger.Info($"Was added a client: {props.ReplyTo}"); } Object obtained = ea.Body.Serializer(); switch (obtained) { case JsonClass j: logger.Info("JsonClass"); JsonModel jsonModel = new JsonModel() { IP = "localhost", UserName = "******", Password = "******" }; string jsonString = JsonConvert.SerializeObject(jsonModel, Formatting.Indented); JsonClass jsonClass = new JsonClass() { JsonByteArray = jsonString.Serializer() }; channel.BasicPublish(exchange: "", routingKey: props.ReplyTo, basicProperties: null, body: jsonClass.Serializer()); break; case ImageClass i: logger.Info("ImageClass"); ImageClass image = new ImageClass() { ImageByteArray = GetImage() }; channel.BasicPublish(exchange: "", routingKey: props.ReplyTo, basicProperties: null, body: image.Serializer()); break; case FileClass f: logger.Info("FileClass"); FileClass file = new FileClass() { FileByteArray = GetFile() }; channel.BasicPublish(exchange: "", routingKey: props.ReplyTo, basicProperties: null, body: file.Serializer()); break; default: logger.Error("Type is different!"); break; } //switch }; } //ctor
public void SerializationHandlerDoesNotSwitchObjectToXmlWhenNameDoesNotMatch() { ColumnMapping.All.AddHandler(new SerializationMappingHandler() { FieldName = "foo", SerializationMode = SerializationMode.Xml }); var input = new JsonClass(); input.SubClass = new JsonSubClass() { Foo = "foo", Bar = 5 }; var s = Connection().Single<string>("MappingAsJson4", input); Assert.IsFalse(Connection().Single<string>("MappingAsJson4", input).StartsWith("<MappingTests.")); }
public void SerializationHandlerSwitchesObjectToXmlWhenTypeMatches() { ColumnMapping.All.AddHandler(new SerializationMappingHandler() { FieldType = typeof(JsonSubClass), SerializationMode = SerializationMode.Xml }); var input = new JsonClass(); input.SubClass = new JsonSubClass() { Foo = "foo", Bar = 5 }; var s = Connection().Single<string>("MappingAsJson3", input); Assert.IsTrue(Connection().Single<string>("MappingAsJson3", input).StartsWith("<MappingTests.")); }
//自定义方法 /// <summary> /// 钉钉推送消息方法 /// </summary> public void SendAlarmMsg() { try { SQLHelper db = new SQLHelper(); DataTable dt = db.ExecuteDataSet(config.DBConn, CommandType.StoredProcedure, "usp_job_ISR_GetUrl", null).Tables[0]; if (dt != null && dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { string URL = dt.Rows[i]["Url"].ToString(); LogHelper.WriteLog(this.GetType().Name, "【钉钉推送消息方法】获取推送URL" + URL); //推送数据方法 SqlParameter[] commandParamers = new SqlParameter[1]; commandParamers[0] = new SqlParameter("@Url", URL); DataTable dt1 = db.ExecuteDataSet(config.DBConn, CommandType.StoredProcedure, "usp_job_ISR_GetInformationTable", commandParamers).Tables[0]; LogHelper.WriteLog(this.GetType().Name, "【钉钉推送消息方法】获取待推送数据" + dt1.Rows.Count.ToString() + "条"); if (dt1 != null && dt1.Rows.Count > 0) { for (int j = 0; j < dt1.Rows.Count; j++) { int ID = Convert.ToInt32(dt1.Rows[j]["ID"]); string AlarmContent = dt1.Rows[j]["AlarmContent"].ToString(); //推送方法 //序列化处理json转义 JsonClass js = new JsonClass(); js.msgtype = "text"; js.text = new ContextObj(); js.text.content = AlarmContent + "\n推送时间:" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); string textMsg = getJsonByObject(js); //string textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"" + msg + "\"}}"; LogHelper.WriteLog(this.GetType().Name, "【钉钉推送消息方法】推送消息 json" + textMsg); string result = PostSendMessages(URL, textMsg, null); // 解析json数据responseText ParsingResults(result, ID); //更新发送状态 Update_SendingState(ID); } } else { string SiteName = ""; DataTable dt2 = db.ExecuteDataSet(config.DBConn, CommandType.StoredProcedure, "usp_job_ISR_GetProject", null).Tables[0]; for (int k = 0; k < dt2.Rows.Count; k++) { SiteName = dt2.Rows[i]["SiteName"].ToString(); } //无发送数据 string msg = "告警项目:" + SiteName + "\n" + "告警内容:" + "数据正常\n" + "告警时间:" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); string textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"" + msg + "\"}}"; LogHelper.WriteLog(this.GetType().Name, "【钉钉推送消息方法】推送消息 json" + textMsg); string result = PostSendMessages(URL, textMsg, null); } } } else { LogHelper.WriteLog(this.GetType().Name, "【钉钉推送消息方法】获取usp_job_ISR_GetUrl中URL失败!"); } } catch (Exception ex) { LogHelper.WriteLog(this.GetType().Name, "【钉钉推送消息方法】失败" + ex.Message); } }
public string GetUpcomingMedicalTestsCount(string patientId) { Mobile_GetUpcomingMedicalTestsCountBL objMobile_GetUpcomingMedicalTestsCountBL = new Mobile_GetUpcomingMedicalTestsCountBL(); JsonClass objJsonClass = new JsonClass(); objJsonClass.medicalTestCount = objMobile_GetUpcomingMedicalTestsCountBL.Mobile_GetUpcomingMedicalTestsCount(Convert.ToInt32(patientId)); return JsonConvert.SerializeObject(objJsonClass); }
public void AccumulateInput(ref UserCommand command, float deltaTime) { if (jsonDone == false) //Create Clean json file once when game is launched { WriteJson(); } // try/catch for reading json file since updating file while game is running can cause error try { JsonObject = JsonUtility.FromJson <JsonClass>(System.IO.File.ReadAllText(@"C:\Unity\jsontestfile.txt")); } catch (IOException) { return; } // To accumulate move we store the input with max magnitude and uses that Vector2 moveInput = new Vector2(Game.Input.GetAxisRaw("Horizontal"), Game.Input.GetAxisRaw("Vertical")); //if WASD is not pressed use json as movement input if (Game.Input.GetAxisRaw("Horizontal") == 0 && Game.Input.GetAxisRaw("Vertical") == 0) { moveInput = new Vector2(JsonObject.Vertical, JsonObject.Horizontal); } float angle = Vector2.Angle(Vector2.up, moveInput); if (moveInput.x < 0) { angle = 360 - angle; } float magnitude = Mathf.Clamp(moveInput.magnitude, 0, 1); if (magnitude > maxMoveMagnitude) { maxMoveYaw = angle; maxMoveMagnitude = magnitude; } command.moveYaw = maxMoveYaw; command.moveMagnitude = maxMoveMagnitude; float invertY = Game.configInvertY.IntValue > 0 ? -1.0f : 1.0f; Vector2 deltaMousePos = new Vector2(0, 0); if (deltaTime > 0.0f) { deltaMousePos += new Vector2(Game.Input.GetAxisRaw("Mouse X"), Game.Input.GetAxisRaw("Mouse Y") * invertY); } deltaMousePos += deltaTime * (new Vector2(Game.Input.GetAxisRaw("RightStickX") * s_JoystickLookSensitivity.x, -invertY * Game.Input.GetAxisRaw("RightStickY") * s_JoystickLookSensitivity.y)); deltaMousePos += deltaTime * (new Vector2( ((Game.Input.GetKey(KeyCode.Keypad4) ? -1.0f : 0.0f) + (Game.Input.GetKey(KeyCode.Keypad6) ? 1.0f : 0.0f)) * s_JoystickLookSensitivity.x, -invertY * Game.Input.GetAxisRaw("RightStickY") * s_JoystickLookSensitivity.y)); command.lookYaw += deltaMousePos.x * Game.configMouseSensitivity.FloatValue; command.lookYaw = command.lookYaw % 360; while (command.lookYaw < 0.0f) { command.lookYaw += 360.0f; } command.lookPitch += deltaMousePos.y * Game.configMouseSensitivity.FloatValue; command.lookPitch = Mathf.Clamp(command.lookPitch, 0, 180); command.buttons.Or(UserCommand.Button.Jump, Game.Input.GetKeyDown(KeyCode.Space) || Game.Input.GetKeyDown(KeyCode.Joystick1Button0)); command.buttons.Or(UserCommand.Button.Boost, Game.Input.GetKey(KeyCode.LeftControl) || Game.Input.GetKey(KeyCode.Joystick1Button4)); command.buttons.Or(UserCommand.Button.PrimaryFire, (Game.Input.GetMouseButton(0) && Game.GetMousePointerLock()) || (Game.Input.GetAxisRaw("Trigger") < -0.5f)); command.buttons.Or(UserCommand.Button.SecondaryFire, Game.Input.GetMouseButton(1) || Game.Input.GetKey(KeyCode.Joystick1Button5)); command.buttons.Or(UserCommand.Button.Ability1, Game.Input.GetKey(KeyCode.LeftShift)); command.buttons.Or(UserCommand.Button.Ability2, Game.Input.GetKey(KeyCode.E)); command.buttons.Or(UserCommand.Button.Ability3, Game.Input.GetKey(KeyCode.Q)); command.buttons.Or(UserCommand.Button.Reload, Game.Input.GetKey(KeyCode.R) || Game.Input.GetKey(KeyCode.Joystick1Button2)); command.buttons.Or(UserCommand.Button.Melee, Game.Input.GetKey(KeyCode.V) || Game.Input.GetKey(KeyCode.Joystick1Button1)); command.buttons.Or(UserCommand.Button.Use, Game.Input.GetKey(KeyCode.E)); //Added Custom commands command.buttons.Or(UserCommand.Button.Custom1, Game.Input.GetKey(KeyCode.Alpha1)); command.buttons.Or(UserCommand.Button.Custom2, Game.Input.GetKey(KeyCode.Alpha2)); command.buttons.Or(UserCommand.Button.Custom3, Game.Input.GetKey(KeyCode.Alpha3)); command.buttons.Or(UserCommand.Button.Custom4, Game.Input.GetKey(KeyCode.Alpha4)); command.buttons.Or(UserCommand.Button.Custom5, Game.Input.GetKey(KeyCode.Alpha5)); command.emote = Game.Input.GetKeyDown(KeyCode.J) ? CharacterEmote.Victory : CharacterEmote.None; command.emote = Game.Input.GetKeyDown(KeyCode.K) ? CharacterEmote.Defeat : command.emote; }
private static IConnectionStringProvider ParseConnectionStringProvider(JsonNode node, IFilePathMapper pathMapper) { if (node.AsObject == null) { return(new StaticConnectionStringProvider(node.Value)); } JsonClass objClass = node.AsObject; SupportedConnectionStringLocators locator; if (!Enum.TryParse(node["locator"]?.Value, out locator)) { throw new NAMEException($"The locator {node["locator"]?.Value} is not supported."); } IConnectionStringProvider provider = null; string key; switch (locator) { #if NET45 case SupportedConnectionStringLocators.ConnectionStrings: key = node["key"]?.Value; provider = new ConnectionStringsConnectionStringProvider(key); break; case SupportedConnectionStringLocators.AppSettings: key = node["key"]?.Value; provider = new AppSettingsConnectionStringProvider(key); break; case SupportedConnectionStringLocators.VSSettingsFile: key = node["key"]?.Value; string section = node["section"]?.Value; if (string.IsNullOrEmpty(section)) { throw new ArgumentNullException("section", "The section must be specified."); } provider = new VisualStudioSetingsFileConnectionStringProvider(section, key); break; #endif case SupportedConnectionStringLocators.JSONPath: { key = node["expression"]?.Value; string file = node["file"]?.Value; if (string.IsNullOrEmpty(file)) { throw new ArgumentNullException("file", "The file must be specified."); } provider = new JsonPathConnectionStringProvider(pathMapper.MapPath(file), key); } break; case SupportedConnectionStringLocators.XPath: { key = node["expression"]?.Value; string file = node["file"]?.Value; if (string.IsNullOrEmpty(file)) { throw new ArgumentNullException("file", "The file must be specified."); } provider = new XpathConnectionStringProvider(pathMapper.MapPath(file), key); } break; default: throw new NAMEException($"The locator {locator.ToString()} is not supported.."); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException($"The connection string key/expression must be specified."); } return(provider); }
private static Dependency HandleDependency( JsonClass dependency, IFilePathMapper pathMapper, NAMESettings configuration, NAMEContext context, int depth = 0) { if (depth == MAX_DEPENDENCY_DEPTH) { throw new NAMEException($"Reached the maximum dependency recursion of {MAX_DEPENDENCY_DEPTH}.", NAMEStatusLevel.Warn); } if (dependency == null) { return(null); } var conditionObject = dependency["oneOf"]; if (conditionObject != null) { depth++; return(new OneOfDependency(HandleDependencyArray(conditionObject.AsArray, pathMapper, configuration, context, depth))); } var minVersion = dependency["min_version"].Value; var maxVersion = dependency["max_version"].Value; var name = dependency["name"]?.Value; var type = dependency["type"]?.Value; var osName = dependency["os_name"]?.Value; type = string.IsNullOrEmpty(type) ? SupportedDependencies.Service.ToString() : type; if (!Enum.TryParse(type, out SupportedDependencies typedType)) { throw new NAMEException($"The dependency type {type} is not supported.", NAMEStatusLevel.Warn); } VersionedDependency result; if (typedType == SupportedDependencies.OperatingSystem) { result = new OperatingSystemDependency() { OperatingSystemName = osName, MinimumVersion = ParseMinimumVersion(minVersion, osName), MaximumVersion = ParseMaximumVersion(maxVersion, osName) }; } else { var connectionStringProvider = ParseConnectionStringProvider(dependency["connection_string"], pathMapper, configuration.ConnectionStringProviderOverride); result = new ConnectedDependency(GetConnectedDependencyVersionResolver(typedType, connectionStringProvider, configuration, context)) { ConnectionStringProvider = connectionStringProvider, MinimumVersion = ParseMinimumVersion(minVersion, type), MaximumVersion = ParseMaximumVersion(maxVersion, type), ShowConnectionStringInJson = configuration.ConnectedDependencyShowConnectionString }; } result.Name = name; result.Type = typedType; return(result); }
public JsonClass GetJson(string jsonClassName) { JsonClass json = new JsonClass(jsonClassName); json.AddObjects(new JsonValue("limit_type", LimitType.ToString())); switch (LimitType) { case LimitType.Moves: json.AddObjects(new JsonValue("limit", Moves)); break; case LimitType.Time: json.AddObjects(new JsonValue("limit", TimeSpan)); break; } List<JsonClass> list = new List<JsonClass>(); foreach (var p in _prices) { JsonClass c = new JsonClass(); c.AddObjects(new JsonValue("index", p.Key), new JsonValue("price", p.Value)); list.Add(c); } json.AddObjects(new JsonArray("prices", list)); json.AddObjects(new JsonArray("stars_levels", StarsLevels)); return json; }
public JsonArray GetJson(string jsonArrayName) { List<JsonClass> classList = new List<JsonClass>(); foreach (var obj in _randomObjects) { JsonClass jclass = new JsonClass(); jclass.AddObjects(new JsonValue("index", obj.Index), new JsonValue("probability", obj.Probability)); classList.Add(jclass); } return new JsonArray(jsonArrayName, classList); }
/// <summary> /// 导出Excel /// </summary> public void Export(ExcelFormat rExcelFormat) { string rConfigFile = UtilTool.PathCombine(this.ExcelConfigRootPath, "Excel", rExcelFormat.ExcelName); string rExportDir = UtilTool.PathCombine(this.ExcelConfigRootPath, "Text"); FileStream rStream = File.Open(rConfigFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); IExcelDataReader rExcelReader = ExcelReaderFactory.CreateOpenXmlReader(rStream); DataSet rResult = rExcelReader.AsDataSet(); DataTable rDataTable = rResult.Tables[rExcelFormat.SheetName]; if (rDataTable == null) { Debug.LogErrorFormat("Excel {0} has not sheet {1}.", rExcelFormat.ExcelName, rExcelFormat.SheetName); rExcelReader.Close(); rStream.Close(); return; } int rColumns = rDataTable.Columns.Count; int rRows = rDataTable.Rows.Count; if (rRows == 0) { Debug.LogErrorFormat("Excel {0} has empty rows.", rExcelFormat.ExcelName); rExcelReader.Close(); rStream.Close(); return; } Type rDataType = MainAssemblyExpand.GetType(rExcelFormat.ClassName); if (rDataType == null) { Debug.LogErrorFormat("Excel {0} can not find Class {1}, please check it.", rExcelFormat.ExcelName, rExcelFormat.ClassName); rExcelReader.Close(); rStream.Close(); return; } var rTitleRow = rDataTable.Rows[0]; var rFields = new Dict <string, FieldInfo>(); var rKeyIDs = new Dict <string, int>(); for (int i = 0; i < rColumns; i++) { FieldInfo rFileInfo = rDataType.GetField(rTitleRow[i].ToString()); rFields.Add(rTitleRow[i].ToString(), rFileInfo); rKeyIDs.Add(rTitleRow[i].ToString(), i); } JsonNode rDataJson = new JsonClass(); for (int i = 1; i < rRows; i++) { JsonNode rItemJson = new JsonClass(); foreach (var rPair in rFields) { string rFieldValue = rDataTable.Rows[i][rKeyIDs[rPair.Key]].ToString(); JsonParser rJsonParser = new JsonParser(rFieldValue); JsonNode rTempNode = null; try { rTempNode = rJsonParser.Parser(); } catch (Exception) { rJsonParser.isValid = false; } if (!rJsonParser.isValid) { rTempNode = new JsonData(rFieldValue); } rItemJson.Add(rPair.Key, rTempNode); } rDataJson.Add(rDataTable.Rows[i][rKeyIDs[rExcelFormat.PrimaryKey]].ToString(), rItemJson); } File.WriteAllText(UtilTool.PathCombine(rExportDir, rExcelFormat.SheetName + ".json"), rDataJson.ToString()); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); rExcelReader.Close(); rStream.Close(); }
public void GiveMeJson() { JsonClass jsonData = new JsonClass(); channel.BasicPublish(exchange: "", routingKey: "MasterClient", basicProperties: props, body: jsonData.Serializer()); }
protected void Button1_Click(object sender, EventArgs e) { if (new User().ValidateUser(txt_email.Value, txt_password.Value)) { int ttid = new User().getTTId(txt_email.Value); if (new User().IsSectorSelected(ttid)) { Session["ttid"] = ttid; Response.Redirect("garage.aspx"); } else { Session["ttid"] = ttid; //Redirect user to the sector select Response.Redirect("selectsector.aspx"); } } else if (!new User().ValidateUser(txt_email.Value, txt_password.Value)) { JsonClass jc = new JsonClass(); jc.Email = txt_email.Value; jc.Password = txt_password.Value; jc.EventId = 22; string json_data = JsonConvert.SerializeObject(jc); WebClient c = new WebClient(); c.Encoding = System.Text.Encoding.UTF8; c.Headers[HttpRequestHeader.ContentType] = "application/json"; try { string cs = c.UploadString("http://www.silive.in/tt15.rest/api/Student/CheckStudent", json_data); JavaScriptSerializer json_serializer = new JavaScriptSerializer(); Student stud = new Student(); stud = json_serializer.Deserialize <Student>(cs); var i = c.ResponseHeaders; string query = "insert into user(ttid,username,password,email,cash,sector_id,confirmed) values(" + stud.TTId + ",'" + stud.Name + "','" + txt_password.Value + "','" + stud.Email + "',100000,0,1" + ")"; con = new Connect(query); Session["ttid"] = stud.TTId; Response.Redirect("selectsector.aspx"); } catch (WebException ex) { HttpWebResponse response = ex.Response as HttpWebResponse; if (response.StatusCode == HttpStatusCode.NotFound) { lbl_error.Text = "You are not registered on Techtrishna. Register Now at Techtrishna 2015 website."; lbl_error.Visible = true; } if (response.StatusCode == HttpStatusCode.Found) { con = new Connect(); string q = "update user set password= '******' where email='" + txt_email.Value + "'"; con = new Connect(q); int ttid = new User().getTTId(txt_email.Value); if (new User().IsSectorSelected(ttid)) { Session["ttid"] = ttid; Response.Redirect("garage.aspx"); } else { Session["ttid"] = ttid; //Redirect user to the sector select Response.Redirect("selectsector.aspx"); } } //lbl_error.Text = "Invalid credentials"; } } }
public void ListBlocks() { var db = Application.DocumentManager.MdiActiveDocument.Database; // Copy blocks from sourcefile into opened file var copyBlockTable = new CopyBlock(); var btrNamesToCopy = new[] { "pump", "valve", "chamber", "instrumentation tag", "channel gate", "pipe", "pipe2", "channel", "channel2" }; copyBlockTable.CopyBlockTable(db, path, btr => { System.Diagnostics.Debug.Print(btr.Name); return(btrNamesToCopy.Contains(btr.Name)); }); //var sizeProperty = new PositionProperty(); //"\nEnter number of equipment:" //var pio = new PromptIntegerOptions("\nEnter number of equipment:") { DefaultValue = 5 }; //var number = Application.DocumentManager.MdiActiveDocument.Editor.GetInteger(pio); //var intNumber = Convert.ToInt32(number.Value); //"\nEnter distance of equipment:" //var dio = new PromptIntegerOptions("\nEnter distance of equipment:") { DefaultValue = 20 }; //var distance = Application.DocumentManager.MdiActiveDocument.Editor.GetInteger(dio); //var intDistance = Convert.ToInt32(distance.Value); //"\nEnter index of equipment:" //var eio = new PromptIntegerOptions("\nEnter index of equipment:") { DefaultValue = 22 }; //var eqIndex = Application.DocumentManager.MdiActiveDocument.Editor.GetInteger(eio); //var promptEqIndex = Convert.ToInt16(eqIndex.Value); var selectorProperty = new SelectorProperty(); long numbers = JsonProcessClass.JsonProcessValue("number_of_eqPump"); long indexOfEqPump = JsonClass.JsonEquipmentValue("Equalization Tank Pump"); var promptEqIndex = Convert.ToInt16(indexOfEqPump); var eqt = new EqualizationTank(numberOfPumps: Convert.ToInt32(EquipmentSelector.EqPumpNumberSelect(selectorProperty)), distanceOfPump: 20, eqIndex: promptEqIndex); //var InsBlock = new BlockMapping(); #region old code //var blocks = new[] //{ // new InsertBlockBase(numberOfItem: 1, // blockName: "chamber", // layerName: "unit", // x: 0, // y: 0, // hostName: "Equalization Tank") // { // ActionToExecuteOnDynProp = new Action<DynamicBlockReferenceProperty>[] // { // dbrProp => // { // if (dbrProp.PropertyName == "Visibility") // dbrProp.Value = "no channel"; // } // }, // ActionToExecuteOnAttRef = new Action<AttributeReference>[] // { // ar => // { // //text for EQ tank - Attributes // if (ar.Tag == "NAME1") // ar.TextString = "EQUALIZATION"; // if (ar.Tag == "NAME2") // ar.TextString = "TANK"; // } // }, // ActionToExecuteOnDynPropAfter = new Action<DynamicBlockReferenceProperty>[] // { // dbrProp => // { // //setup chamber width // if (dbrProp.PropertyName == "Distance") // dbrProp.Value = 5.0d * 20 + 50; //last value is the free space for other items // //text position for chamber // if (dbrProp.PropertyName == "Position X") // dbrProp.Value = (5 * 20 + 50) / 2.0d; //place text middle of chamber horizontaly // } // }, // }, //}; #endregion var layers = new[] { new LayerData("unit", Color.FromRgb(255, 0, 0), 0.25, false) }; var layerCreator = new LayerCreator(); layerCreator.LayerCreatorMethod(layers); DrawBlocks(db, eqt.Blocks); //DrawBlocks(db, InsBlock.Blocks); #region oldcode ////short shortCheckValveIndex = 2; //PositionProperty.NumberOfPump = number.Value; //PositionProperty.DistanceOfPump = distance.Value; //var ed = Application.DocumentManager.MdiActiveDocument.Editor; //var aw = new AutoCadWrapper(); ////copyBlockTable.CopyBlockTableMethod(db, path, btr => true); //sizeProperty.X = 50; //// Call a transaction to create layer ////layerCreator.LayerCreatorMethod("equipment", Color.FromRgb(0, 0, 255), 0.5); ////layerCreator.LayerCreatorMethod("unit", Color.FromRgb(0, 0, 255), 0.5); //// Start transaction to write equipment //var insertEqTAnkPump = new InsertBlockBase(PositionProperty.NumberOfPump, // number of item // PositionProperty.DistanceOfPump, // disctance of item // "pump", //block name // "equipment", //layer name // "Centrifugal Pump", //dynamic property type // shortEqIndex, //visibility of equipment () // sizeProperty.X, //X // 10, //Y // "Equalization Tank", //Host name // 0); //pipe length //insertBlockTable.InsertBlockTableMethod(db, insertEqTAnkPump); //// //var insertEqTAnk = new InsertBlockBase( // 1, // number of item // 0, // disctance of item // "chamber", //block name // "unit", //layer name // "Visibility", //dynamic property type // "no channel", //visibility of equipment // 0, //X // 0, //Y // "Equalization Tank", //Host name // 0); //pipe length //insertBlockTable.InsertBlockTableMethod(db, insertEqTAnk); //// //var insertCheckValve = new InsertBlockBase( // PositionProperty.NumberOfPump, // number of item // PositionProperty.DistanceOfPump, // disctance of item // "valve", //block name // "valve", //layer name // "Block Table1", //dynamic property type // (short)5, //visibility of equipment (check valve) // sizeProperty.X, //X // 25, //Y // "Equalization Tank", //Host name // 0); //pipe length //insertBlockTable.InsertBlockTableMethod(db, insertCheckValve); //// //var insertGateValve = new InsertBlockBase( // PositionProperty.NumberOfPump, // number of item // PositionProperty.DistanceOfPump, // disctance of item // "valve", //block name // "valve", //layer name // "Block Table1", //dynamic property type // (short)0, //visibility of equipment (gate valve) // sizeProperty.X, //X // 40, //Y // "Equalization Tank", //Host name // 0); //pipe length //insertBlockTable.InsertBlockTableMethod(db, insertGateValve); //// //var insertLIT = new InsertBlockBase( // 1, // number of item // 0, // disctance of item // "instrumentation tag", //block name // "instrumentation", //layer name // "Block Table1", //dynamic property type // (short)7, //visibility of equipment (LIT) // PositionProperty.NumberOfPump // * PositionProperty.DistanceOfPump + 50, //X // 10, //Y // "Equalization Tank", //Host name // 0); //pipe length //// //var insertFIT = new InsertBlockBase( // 1, // number of item // 0, // disctance of item // "instrumentation tag", //block name // "instrumentation", //layer name // "Block Table1", //dynamic property type // (short)11, //visibility of equipment (FIT) // PositionProperty.NumberOfPump // * PositionProperty.DistanceOfPump + 50, //X // 50, //Y // "Equalization Tank", //Host name // 0); //pipe length //// //var insertJetPump = new InsertBlockBase( // 1, // number of item // 0, // disctance of item // "pump", //block name // "equipment", //layer name // "Centrifugal Pump", //dynamic property type // (short)17, //visibility of jet pump // 20, //X // 10, //Y // "Equalization Tank", //Host name // 0); //pipe length //// //var insertChannelGateSTB = new InsertBlockBase( // 1, // number of item // 0, // disctance of item // "channel gate", //block name // "equipment", //layer name // "Block Table1", //dynamic property type // (short)23, //visibility of item (Channel gate (Equalization Tank)) // -10.5, //X // 6, //Y // "Equalization Tank", //Host name // 0); //pipe length //// //var insertChannelGateDTY = new InsertBlockBase( // 1, // number of item // 0, // disctance of item // "channel gate", //block name // "equipment", //layer name // "Block Table1", //dynamic property type // (short)23, //visibility of item (Channel gate (Equalization Tank)) // -10.5, //X // -24, //Y // "Equalization Tank", //Host name // 0); //pipe length //var insertPipe1 = new InsertBlockBase( // PositionProperty.NumberOfPump, // number of item // PositionProperty.DistanceOfPump, // disctance of item // "pipe", //block name // "sewer", //layer name // "Visibility1", //dynamic property type // "sewer", //visibility of item (sewer pipe) // 50, //X // 14, //Y // "Equalization Tank", //Host name // 36); //var blocks = new[] { // insertPipe1, insertChannelGateDTY, insertChannelGateSTB //}; #endregion }
public virtual JsonClass GetJson() { var json = new JsonClass(); json.AddObjects(new JsonValue("type", Type)); json.AddObjects(new JsonValue("play_on_awake", PlayOnAwake)); json.AddObjects(new JsonValue("is_local", IsLocal)); json.AddObjects(new JsonValue("is_dependent", IsDependent)); json.AddObjects(new JsonArray("target", Target)); json.AddObjects(new JsonValue("time", Time)); json.AddObjects(new JsonValue("ease", Ease)); json.AddObjects(new JsonValue("is_loop", IsLoop)); json.AddObjects(new JsonValue("loops", Loops)); json.AddObjects(new JsonValue("loop_type", LoopType)); return json; }
public string GetUpcomingAppointmentsCount(string patientId) { Mobile_GetUpcomingAppointmentsCountBL objMobile_GetUpcomingAppointmentsCountBL = new Mobile_GetUpcomingAppointmentsCountBL(); JsonClass objJsonClass = new JsonClass(); objJsonClass.appointmentCount = objMobile_GetUpcomingAppointmentsCountBL.Mobile_GetUpcomingAppointmentsCount(patientId); return JsonConvert.SerializeObject(objJsonClass, Formatting.Indented); }
public Object Login([FromBody] CustomerLogin Login) { string sJSONResponse = ""; DataTable dt_Login = new DataTable(); var json = (Object)null; try { if (Login.MobileNo != null && Login.EmailId == null || Login.MobileNo != null && Login.EmailId != null) { dt_Login = LoginMobileCheck(Login.MobileNo); if (dt_Login.Rows.Count > 0) { List <CustomerLoginNestedModel> CustomerLogin = new List <CustomerLoginNestedModel>(); CustomerLoginNestedModel CustomerLoginNeste = new CustomerLoginNestedModel(); CustomerLoginNeste.status = "Success"; CustomerLoginNeste.hasDetailsConfirmed = Convert.ToBoolean(dt_Login.Rows[0]["HasDetailsConfirmed"].ToString()); CustomerLoginNeste.errorMessage = "Mobile Number Exist In Our Records"; CustomerLoginNeste.isExist = true; CustomerLoginNeste.personalDetails = PersonalDetailsEmail(dt_Login); CustomerLoginNeste.isUserLoggedIn = Convert.ToBoolean(dt_Login.Rows[0]["isUserLoggedIn"].ToString()); if (Convert.ToBoolean(dt_Login.Rows[0]["isUserLoggedIn"].ToString()) == false) { CustomerLoginNeste.OTP = OTP(Login.MobileNo); } UpdateMobileDeviceId(Login.MobileNo, Login.MobileDeviceID, 1); sJSONResponse = JsonConvert.SerializeObject(CustomerLoginNeste); } else { List <CustomerLoginNonNestedModel> CustomerLogin = new List <CustomerLoginNonNestedModel>(); CustomerLoginNonNestedModel CustomerLoginNonNeste = new CustomerLoginNonNestedModel(); CustomerLoginNonNeste.status = "Success"; CustomerLoginNonNeste.hasDetailsConfirmed = false; CustomerLoginNonNeste.errorMessage = ""; CustomerLoginNonNeste.OTP = OTP(Login.MobileNo); CustomerLoginNonNeste.isExist = false; CustomerLoginNonNeste.isUserLoggedIn = false; sJSONResponse = JsonConvert.SerializeObject(CustomerLoginNonNeste); } } else if (Login.MobileNo == null && Login.EmailId != null) { dt_Login = LoginEmailCheck(Login.EmailId); if (dt_Login.Rows.Count > 0) { List <CustomerLoginEmailNestedModel> CustomerLogin = new List <CustomerLoginEmailNestedModel>(); CustomerLoginEmailNestedModel CustomerLoginNeste = new CustomerLoginEmailNestedModel(); CustomerLoginNeste.status = "Success"; CustomerLoginNeste.hasDetailsConfirmed = Convert.ToBoolean(dt_Login.Rows[0]["HasDetailsConfirmed"].ToString()); CustomerLoginNeste.isUserLoggedIn = Convert.ToBoolean(dt_Login.Rows[0]["IsUserLoggedIn"].ToString()); CustomerLoginNeste.isExist = true; if (Convert.ToBoolean(dt_Login.Rows[0]["IsUserLoggedIn"].ToString()) == false) { CustomerLoginNeste.OTP = OTP(dt_Login.Rows[0]["MobileNo"].ToString()); } CustomerLoginNeste.errorMessage = "EmailID Exist In Our Records"; CustomerLoginNeste.personalDetails = PersonalDetailsMobileNo(dt_Login); UpdateMobileDeviceId(Login.MobileNo, Login.MobileDeviceID, 2); sJSONResponse = JsonConvert.SerializeObject(CustomerLoginNeste); } else { List <CustomerLoginEmailNonNestedModel> CustomerLogin = new List <CustomerLoginEmailNonNestedModel>(); CustomerLoginEmailNonNestedModel CustomerLoginNeste = new CustomerLoginEmailNonNestedModel(); CustomerLoginNeste.status = "Success"; CustomerLoginNeste.hasDetailsConfirmed = false; CustomerLoginNeste.isUserLoggedIn = false; CustomerLoginNeste.errorMessage = ""; CustomerLoginNeste.isExist = false; sJSONResponse = JsonConvert.SerializeObject(CustomerLoginNeste); } } } catch (Exception ec) { json = ec.Message; } return(sJSONResponse); }
public string a() { string url = "http://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json"; string appcode = "9b5eda2cae234efdb318b4344af42782"; string img_file = "D:\\20190409144755.jpg"; //如果输入带有inputs, 设置为True,否则设为False bool is_old_format = false; //如果没有configure字段,config设为'' //String config = ''; string config = "{\\\"side\\\":\\\"face\\\"}"; string method = "POST"; string querys = ""; using (FileStream fs = new FileStream(img_file, FileMode.Open)) { BinaryReader br = new BinaryReader(fs); byte[] contentBytes = br.ReadBytes(Convert.ToInt32(fs.Length)); string base64 = Convert.ToBase64String(contentBytes); string bodys; if (is_old_format) { bodys = "{\"inputs\" :" + "[{\"image\" :" + "{\"dataType\" : 50," + "\"dataValue\" :\"" + base64 + "\"" + "}"; if (config.Length > 0) { bodys += ",\"configure\" :" + "{\"dataType\" : 50," + "\"dataValue\" : \"" + config + "\"}" + "}"; } bodys += "]}"; } else { bodys = "{\"image\":\"" + base64 + "\""; if (config.Length > 0) { bodys += ",\"configure\" :\"" + config + "\""; } bodys += "}"; } HttpWebRequest httpRequest = null; HttpWebResponse httpResponse = null; if (0 < querys.Length) { url = url + "?" + querys; } if (url.Contains("https://")) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url)); } else { httpRequest = (HttpWebRequest)WebRequest.Create(url); } httpRequest.Method = method; httpRequest.Headers.Add("Authorization", "APPCODE " + appcode); //根据API的要求,定义相对应的Content-Type httpRequest.ContentType = "application/json; charset=UTF-8"; if (0 < bodys.Length) { byte[] data = Encoding.UTF8.GetBytes(bodys); using (Stream stream = httpRequest.GetRequestStream()) { stream.Write(data, 0, data.Length); } } try { httpResponse = (HttpWebResponse)httpRequest.GetResponse(); } catch (WebException ex) { httpResponse = (HttpWebResponse)ex.Response; } if (httpResponse.StatusCode != HttpStatusCode.OK) { Console.WriteLine("http error code: " + httpResponse.StatusCode); Console.WriteLine("error in header: " + httpResponse.GetResponseHeader("X-Ca-Error-Message")); Console.WriteLine("error in body: "); Stream st = httpResponse.GetResponseStream(); StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8")); var json = reader.ReadToEnd(); Console.WriteLine(reader.ReadToEnd()); return(json); } else { Stream st = httpResponse.GetResponseStream(); StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8")); var json = reader.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); //JsonClass jo = (JsonClass)JsonConvert.DeserializeObject(json); JsonClass s = JsonConvert.DeserializeObject <JsonClass>(json); List <JsonClass> jc = js.Deserialize <List <JsonClass> >(json); return(json); } Console.WriteLine("\n"); } }
public static JsonNode ToJsonNode(object rObject) { Type rType = rObject.GetType(); JsonNode rRootNode = null; if (rType.IsGenericType && typeof(IList).IsAssignableFrom(rType.GetGenericTypeDefinition())) { rRootNode = new JsonArray(); IList rListObj = (IList)rObject; foreach (var rItem in rListObj) { JsonNode rNode = ToJsonNode(rItem); rRootNode.Add(rNode); } } else if (rType.IsArray) { rRootNode = new JsonArray(); Array rArrayObj = (Array)rObject; foreach (var rItem in rArrayObj) { JsonNode rNode = ToJsonNode(rItem); rRootNode.Add(rNode); } } else if (rType.IsGenericType && typeof(IDictionary).IsAssignableFrom(rType.GetGenericTypeDefinition())) { rRootNode = new JsonClass(); IDictionary rDictObj = (IDictionary)rObject; foreach (var rKey in rDictObj.Keys) { JsonNode rValueNode = ToJsonNode(rDictObj[rKey]); rRootNode.Add(rKey.ToString(), rValueNode); } } else if (rType.IsGenericType && typeof(IDict).IsAssignableFrom(rType.GetGenericTypeDefinition())) { rRootNode = new JsonClass(); IDict rDictObj = (IDict)rObject; foreach (var rItem in rDictObj.OriginCollection) { JsonNode rValueNode = ToJsonNode(rItem.Value); rRootNode.Add(rItem.Key.ToString(), rValueNode); } } else if (rType.IsClass) { if (rType == typeof(string)) { rRootNode = new JsonData((string)rObject); } else { rRootNode = new JsonClass(); PropertyInfo[] rPropInfos = rType.GetProperties(ReflectionAssist.flags_public); for (int i = 0; i < rPropInfos.Length; i++) { object rValueObj = rPropInfos[i].GetValue(rObject, null); JsonNode rValueNode = ToJsonNode(rValueObj); rRootNode.Add(rPropInfos[i].Name, rValueNode); } FieldInfo[] rFieldInfos = rType.GetFields(ReflectionAssist.flags_public); for (int i = 0; i < rFieldInfos.Length; i++) { object rValueObj = rFieldInfos[i].GetValue(rObject); JsonNode rValueNode = ToJsonNode(rValueObj); rRootNode.Add(rFieldInfos[i].Name, rValueNode); } } } else if (rType.IsPrimitive) { if (rType.Equals(typeof(int))) { rRootNode = new JsonData((int)rObject); } else if (rType.Equals(typeof(uint))) { rRootNode = new JsonData((uint)rObject); } else if (rType.Equals(typeof(long))) { rRootNode = new JsonData((long)rObject); } else if (rType.Equals(typeof(ulong))) { rRootNode = new JsonData((ulong)rObject); } else if (rType.Equals(typeof(float))) { rRootNode = new JsonData((float)rObject); } else if (rType.Equals(typeof(double))) { rRootNode = new JsonData((double)rObject); } else if (rType.Equals(typeof(bool))) { rRootNode = new JsonData((bool)rObject); } else if (rType.Equals(typeof(string))) { rRootNode = new JsonData((string)rObject); } else { Debug.LogError(string.Format("Type = {0}, 不支持序列化的变量类型!", rObject.GetType())); } } return(rRootNode); }
//Thread for reading online json //Threaded to prevent slowdown public void UpdateThread() { _threadRunning = true; workDone = false; //try/catch because switching online json file can will cause error and/or freeze try { while (_threadRunning && !workDone) { //read web page as stream line by line var client = new WebClient(); using (var stream = client.OpenRead(url)) using (var reader = new StreamReader(stream)) { string line; while ((line = reader.ReadLine()) != null) { //Parse line to ProjectileObject ProjectileObject = JsonUtility.FromJson <JsonClass>(line); //If ID matches update type and position if (ProjectileObject.ID == ProjCounterObj.Count) { //If current type doesn't match destroy old prefab and update new one if (typeStr != ProjectileObject.Type) { DestroyMyPrefab = true; typeStr = ProjectileObject.Type; boolUpdatePrefab = true; } typeStr = ProjectileObject.Type; //Update local ID ID = ProjectileObject.ID; position = new Vector3(ProjectileObject.X, ProjectileObject.Y, ProjectileObject.Z); //WorkDone = true exits loop and Thread.Sleep() can be used to further reduce slowdown if here are many projectiles workDone = true; //Thread sleep set to 1000 milliseconds for demo Thread.Sleep(1000); } } } } _threadRunning = false; } catch (ArgumentException e) { Debug.Log("ArgumentException Error:"); Debug.LogException(e); _threadRunning = false; return; } catch (Exception e) { Debug.Log("Exception Error:"); Debug.LogException(e); _threadRunning = false; return; } }