public static void SaveToFile(CharlieModel model) { var pref = new Preferences { WindowX = model.WindowX, WindowY = model.WindowY, WindowHeight = model.WindowHeight, WindowWidth = model.WindowWidth, PreviousLoadedSims = model.PreviousLoaded.Get(), SimDelay = model.SimDelay, LogEveryIteration = model.LogEveryIteration, RenderHeight = model.RenderHeight, RenderWidth = model.RenderWidth }; if (!Directory.Exists(PrefenceDir)) { Directory.CreateDirectory(PrefenceDir); } File.WriteAllText(PreferenceFile, JsonNet.Serialize(pref)); }
public JsonNetResult GetDriveInfo(string path) { bool success; ulong freeBytes, totalBytes, totalFreeBytes; success = GetDiskFreeSpaceEx(path, out freeBytes, out totalBytes, out totalFreeBytes); if (success) { return(JsonNet.JsonOKRecord(new Drive() { FreeSpace = General.BytesToGigaBytes(freeBytes), TotalSpace = General.BytesToGigaBytes(totalBytes), Name = path, VolumeLabel = path })); } else { return(JsonNet.JsonError("Could not get drive info")); } }
static void Main(string[] args) { DBEntities db = new DBEntities(); //新增 User user = new User(); user.Id = Guid.NewGuid().ToString().Replace("-", ""); db.User.Add(user); db.SaveChanges(); //查询 List <User> list = db.User.ToList(); //json转化 var userJson = JsonNet.Serialize(list, JsonHelper.dateConverter); //var userList = JsonNet.Deserialize<List<User>>(userJson, JsonHelper.dateConverter); Console.WriteLine(userJson); Console.Read(); }
public JsonNetResult GetRoleOptions() { try { var roles = repo.OrderBy(r => r.Name) .Select(r => new JTableOption { DisplayText = r.Name, Value = r.ID }); if (roles.Count() > 0) { return(JsonNet.JsonOKOptions(roles)); } return(JsonNet.JsonNoOptions(StringFormatters.NotAvailable(Resources.Global.General_Roles.ToLower()))); } catch (Exception ex) { return(JsonNet.JsonError(ex.Message + '\n' + ex.StackTrace)); } }
// Issue 9 public void JsonNetIgnoreAttributeTest() { var test_object = new TestClass005 { Id = 81, Name = "Tester 005", SecurityKey = "Top Secret", NickName = "Superman" }; var json_text = JsonNet.Serialize(test_object); Assert.AreEqual(json_text, "{\"Id\":81,\"Name\":\"Tester 005\",\"NickName\":\"Superman\"}"); json_text = "{\"Id\":81,\"Name\":\"Tester 005\",\"SecurityKey\":\"Top Secret\",\"NickName\":\"Superman\"}"; var test_object2 = JsonNet.Deserialize <TestClass005>(json_text); Assert.AreEqual(test_object.Id, test_object2.Id); Assert.AreEqual(test_object.Name, test_object2.Name); Assert.AreNotEqual(test_object.SecurityKey, test_object2.SecurityKey); Assert.AreEqual(test_object.NickName, test_object2.NickName); }
private void LoadIngredient() { ingredientStr = Intent.GetStringExtra(Constants.IngredientString); if (ingredientStr != null) { original.Text = ingredientStr; } string stringExtra = Intent.GetStringExtra(Constants.Ingredient); if (stringExtra != null) { ingredient = JsonNet.Deserialize <Ingredient>(stringExtra); AssighnFormFields(); } else { ingredient = new Ingredient(); if (ingredient.TryToParseFromString(ingredientStr)) { AssighnFormFields(); } } }
public UnsubscribesResult GetUnsubscribes(UnsubscribesGetParameter parameter) { string result = base.CallApi(Config.UnsubscribesConfig.UnsubscribesGet, parameter); return(JsonNet.DeserializeToString <UnsubscribesResult>(result)); }
public InvalidStatsResult GetinInvalids(StatsParameter parameter) { string result = base.CallApi(Config.DataStatisticsConfig.StatiGetInvalid, parameter); return(JsonNet.DeserializeToString <InvalidStatsResult>(result)); }
public StatsResult GetByHours(StatsParameter parameter) { string result = base.CallApi(Config.DataStatisticsConfig.StatiGetHour, parameter); return(JsonNet.DeserializeToString <StatsResult>(result)); }
public void SerializationTest() { var petJson = JsonNet.Serialize(OriginalPet, PropertyNameTransforms.TitleToCamelCase); Assert.AreEqual(originalPetJson, petJson); }
private static Status universalObjeccctRetriver(string query, SqlCommand cmd, int type) { SqlConnection con = new SqlConnection(ConnectionInit.ConnectionString); Status status = new Status(); status.Json_data = "{"; try { con.Open(); cmd.Connection = con; cmd.CommandText = query; SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { if (reader.HasRows) { if (reader.Read()) { if (type == CHECK_IF_EXISTS_REQUESTS) { int Chat_id = reader.GetInt32(0); status.Json_data += "\"Chat_id\":" + "\"" + JsonNet.Serialize(Chat_id) + "\","; } else if (type == SENDDING_MESSAGE) { int Message_id = int.Parse(reader.GetSqlValue(0).ToString()); status.Json_data += "\"Message_id\":" + "\"" + JsonNet.Serialize(Message_id) + "\""; } } if (reader.NextResult()) { if (reader.Read()) { if (type == CHECK_IF_EXISTS_REQUESTS) { int Message_id = int.Parse(reader.GetSqlValue(0).ToString()); status.Json_data += "\"Message_id\":" + "\"" + JsonNet.Serialize(Message_id) + "\""; } } } } status.Json_data += "}"; status.State = 1; status.Exception = "Done"; } else { status.State = 0; status.Exception = "not found"; status.Json_data = ""; } reader.Close(); } catch (Exception e1) { status.State = -1; status.Exception = e1.Message; } finally { con.Close(); } return(status); }
public static void Save() { string json = JsonNet.Serialize(conf); File.WriteAllText(DEFAULT_CONF_FILE, json); }
public LabelsResult GetLabels(LabelsParameter parameter) { string result = base.CallApi(Config.LabelConfig.LabelGetList, parameter); return(JsonNet.DeserializeToString <LabelsResult>(result)); }
public static void SaveSetting(Setting st) { _setting = st; SaveFile(JsonNet.Serialize(st)); }
public JsonNetResult Get() { var settings = db.BackupSettings.FirstOrDefault(); return(JsonNet.JsonObject(settings)); }
public JsonNetResult GetBackupStatus() { var log = db.AppLogs.AsNoTracking().Where(l => l.Module == Module.Backup).OrderByDescending(l => l.ID).FirstOrDefault(); return((log != null && log.Type != AppLogType.Success) ? JsonNet.JsonError(string.Empty) : JsonNet.JsonOK()); }
private ResultColumnEntry TestSerializer <T>(dynamic ser, int numOfObjects, out int sizeInBytes, out bool success, out string regeneratedObjAsJson) { var sw = new Stopwatch(); // BINARY serializers // eg: ProtoBufs, Bin Formatter etc if (ser.IsBinary()) { byte[] binOutput; sw.Reset(); sw.Start(); for (int i = 0; i < numOfObjects; i++) { binOutput = ser.Serialize(_originalObject); _testObject = ser.Deserialize(binOutput); } sw.Stop(); // Find size outside loop to avoid timing hits binOutput = ser.Serialize(_originalObject); sizeInBytes = binOutput.Count(); } // TEXT serializers // eg. JSON, XML etc else { sw.Reset(); sw.Start(); for (int i = 0; i < numOfObjects; i++) { string strOutput = ser.Serialize(_originalObject); _testObject = ser.Deserialize(strOutput); } sw.Stop(); // Find size outside loop to avoid timing hits // Size as bytes for UTF-8 as it's most common on internet var encoding = new System.Text.UTF8Encoding(); byte[] strInBytes = encoding.GetBytes(ser.Serialize(_originalObject)); sizeInBytes = strInBytes.Count(); } var entry = new ResultColumnEntry(); entry.Iteration = numOfObjects; long avgTicks = sw.Elapsed.Ticks / numOfObjects; if (avgTicks == 0) { // sometime when running windows inside a VM this is 0! Possible vm issue? //Debugger.Break(); } entry.Time = new TimeSpan(avgTicks); // Debug: To aid printing to screen, human debugging etc. Json used as best for console presentation var jsonSer = new JsonNet <T>(); string orignalObjectAsJson = JsonHelper.FormatJson(jsonSer.Serialize(_originalObject)); regeneratedObjAsJson = JsonHelper.FormatJson(jsonSer.Serialize(_testObject)); success = true; if (orignalObjectAsJson != regeneratedObjAsJson) { Console.WriteLine(">>>> {0} FAILED <<<<", ser.GetName()); Console.WriteLine("\tOriginal and regenerated objects differ !!"); Console.WriteLine("\tRegenerated objects is:"); Console.WriteLine(regeneratedObjAsJson); success = false; } return(entry); }
public UnsubscribesResult DeleteUnsubscribe(DelUnsubscribeParameter parameter) { string result = base.CallApi(Config.UnsubscribesConfig.UnsubscribesDelete, parameter); return(JsonNet.DeserializeToString <UnsubscribesResult>(result)); }
public SendResult SendTemplateEmail(SendTemplateParameter parameter, string attachmentName, string attachmentPath) { string json = base.CallApi(Config.SendConfig.MailSendTemplate, parameter, attachmentName, attachmentPath); return(JsonNet.DeserializeToString <SendResult>(json)); }
private void MenuItem_Save(object sender, RoutedEventArgs e) { handleDialog(new System.Windows.Forms.SaveFileDialog(), path => File.WriteAllText(path, JsonNet.Serialize(getUserInput()))); }
public LabelResult UpdateLabel(LabelParameter parameter) { string result = base.CallApi(Config.LabelConfig.LabelUpdate, parameter); return(JsonNet.DeserializeToString <LabelResult>(result)); }
public void SerializationTest() { var petJson = JsonNet.Serialize(OriginalPet); Assert.AreEqual(petJson, OriginalPetJson); }
static void Main(string[] args) { Enemy enemy = new Enemy() { Weapon = 50 }; GoldBox goldBox = new GoldBox(); GoldKey goldKey = new GoldKey(); SilverKey silverKey = new SilverKey(); BronzKey bronzKey = new BronzKey(); Cell cell1 = new Cell(enemy); Cell cell2 = new Cell(goldKey); Cell cell3 = new Cell(goldBox); Cell cell4 = new Cell(); Cell[,] cells = new Cell[, ] { { cell4, cell1, cell3 }, { cell2, cell4, cell2 }, }; Player player = new Player(); player.Keys.Add(silverKey); player.Keys.Add(goldKey); player.Keys.Add(bronzKey); Board board = new Board(cells); board.Player = player; GameDirector gameDirector = new GameDirector(board); Console.WriteLine("hhhhhhhhhhh"); JsonSerializer serializer = new JsonSerializer(); var petJson = JsonNet.Serialize(gameDirector); Console.WriteLine(petJson); File.WriteAllText(@"P:\Intro Work Shop\Sample Game\PCMan\PCMan\json.json", petJson); var jsonString = File.ReadAllText(@"P:\Intro Work Shop\Sample Game\PCMan\PCMan\json.json"); Console.WriteLine($"Read From File:\n{jsonString}"); var pet = JsonNet.Deserialize <GameDirector>(jsonString); Console.WriteLine($"after Deserialization:\n{pet}"); //JsonSerializer.Deserialize<GameDirector>(jsonString); //IOcupant ocupant = new Enemy() { Weapon = 100 }; //Cell[,] cells = new Cell[,] { // { new Cell(ocupant), new Cell(ocupant), new Cell(ocupant) }, // { new Cell(ocupant), new Cell(ocupant), new Cell(ocupant) } //}; //Board board = new Board(cells); //foreach (var item in cells) //{ // if (item._ocupant is Enemy e) // { // Console.WriteLine($"----{ e.Weapon.ToString()}"); // } //} Console.WriteLine("Hello World!"); }
private void OnReceived(string json) { var packet = JsonNet.Deserialize <PacketS2C>(json); _logger.LogTrace($"Received packet: {packet}"); switch (packet.Type) { case Packet.PacketTypeS2C.AuthResult: { var state = packet.GetPayload <AuthCompleted>(); OnLoggedIn?.Invoke(this, new LoggedInEventArgs(this, state.Motd, state.GameModes)); } break; case Packet.PacketTypeS2C.GameAction: { var gameAction = packet.GetPayload <LiveGameAction>(); if (_games.ContainsKey(gameAction.GameIdentifier)) { var game = _games[gameAction.GameIdentifier]; var ownerOfEntity = game.GetOwnerOfEntity(gameAction.ControlledEntityIdentifier); if (ownerOfEntity == null) { _logger.LogError($"Corrupted game state - cannot find entity: {gameAction.ControlledEntityIdentifier} in game {gameAction.GameIdentifier}"); Send(Packet.PacketTypeC2S.ForceResync, gameAction.GameIdentifier); } else { _games[gameAction.GameIdentifier].AddActionWithoutNetworking(ownerOfEntity, gameAction); } } else { _logger.LogError($"Action in unknown game: {gameAction.GameIdentifier}"); Send(Packet.PacketTypeC2S.ForceResync, gameAction.GameIdentifier); } } break; case Packet.PacketTypeS2C.IllegalAction: { var illegalAction = packet.GetPayload <IllegalAction>(); if (!illegalAction.InsideGame) { OnIllegalAction?.Invoke(this, new MessageEventArgs(illegalAction.Message)); } else if (illegalAction.GameIdentifier != null && _games.ContainsKey(illegalAction.GameIdentifier.Value)) { _games[illegalAction.GameIdentifier.Value].HandleServerIllegalAction(illegalAction.Message); } else if (illegalAction.GameIdentifier != null) { _logger.LogError($"Server refused action in unknown game: {illegalAction.GameIdentifier}"); Send(Packet.PacketTypeC2S.ForceResync, illegalAction.GameIdentifier); } else { _logger.LogWarning("Cannot handle server packet (Claims illegal action in game, but does not specify the game identifier)"); } } break; case Packet.PacketTypeS2C.NextRound: { var gameIdentifier = packet.GetPayload <long>(); if (_games.ContainsKey(gameIdentifier)) { _games[gameIdentifier].DoNextTurn(); } else { _logger.LogError($"Server sent turn end in unknown game: {gameIdentifier}"); Send(Packet.PacketTypeC2S.ForceResync, gameIdentifier); } } break; case Packet.PacketTypeS2C.GameState: { var state = packet.GetPayload <GameState>(); _games[state.GameIdentifier] = state.State; state.State.SetGameDetails(state.YourIdentifier, state.GameIdentifier, this); OnJoinedGameInternal?.Invoke(this, new GameEventArgs(state.State)); state.State.RequestClientActions(); } break; case Packet.PacketTypeS2C.GameEnd: { var end = packet.GetPayload <GameEnd>(); if (_games.ContainsKey(end.GameIdentifier)) { var game = _games[end.GameIdentifier]; _games.Remove(end.GameIdentifier); OnLeftGameInternal?.Invoke(this, new GameEventArgs(game)); } } break; case Packet.PacketTypeS2C.QueueState: var args = new CountChangedEventArgs(packet.GetPayload <int>()); _lastQueueCount = args.Count; OnServersideQueueCountChangedInternal?.Invoke(this, args); break; default: throw new ArgumentOutOfRangeException(); } }
public IActionResult exam_Result() { string js = HttpContext.Request.Form["data"]; var jss = JsonNet.Deserialize <List <ExamTest> >(js); int testcount = jss.Count(); List <UserHistory> histories = new List <UserHistory>(); Counter judegeC = new Counter() { All = 0, right = 0 }; Counter choiceC = new Counter() { All = 0, right = 0 }; Counter blankC = new Counter() { All = 0, right = 0 }; int EachScore = 100 / jss.Count(); int score = 0; Users user = UserService.GetUser(HttpContext.Session.GetString("account")); TestStorage test; foreach (var item in jss) { if (item.value == "") { item.value = "未填写"; } test = Test.FindTestById(Convert.ToInt32(item.name)); if (test.Type == "choice") { choiceC.All++; if (test.Answer == item.value) { score += EachScore; choiceC.right++; histories.Add(new UserHistory { Answer = item.value, State = 1, UsersId = user.Id, ExamId = HttpContext.Session.GetInt32("examID"), TestId = test.Id }); } else { histories.Add(new UserHistory { Answer = item.value, State = 0, UsersId = user.Id, ExamId = HttpContext.Session.GetInt32("examID"), TestId = test.Id }); } } else if (test.Type == "judege") { judegeC.All++; if (test.Answer == item.value) { score += EachScore; judegeC.right++; histories.Add(new UserHistory { Answer = item.value, State = 1, UsersId = user.Id, ExamId = HttpContext.Session.GetInt32("examID"), TestId = test.Id }); } else { histories.Add(new UserHistory { Answer = item.value, State = 0, UsersId = user.Id, ExamId = HttpContext.Session.GetInt32("examID"), TestId = test.Id }); } } else if (test.Type == "blank") { blankC.All++; if (test.Answer == item.value) { score += EachScore; blankC.right++; histories.Add(new UserHistory { Answer = item.value, State = 1, UsersId = user.Id, ExamId = HttpContext.Session.GetInt32("examID"), TestId = test.Id }); } else { histories.Add(new UserHistory { Answer = item.value, State = 0, UsersId = user.Id, ExamId = HttpContext.Session.GetInt32("examID"), TestId = test.Id }); } } } UserService.SaveExam(histories); MemoryCache.Set <Counter>("judegeC", judegeC); MemoryCache.Set <Counter>("choiceC", choiceC); MemoryCache.Set <Counter>("blankC", blankC); MemoryCache.Set("score", score); MemoryCache.Set("EachScore", EachScore); MemoryCache.Set("name", ExamService.FindExamById(Convert.ToInt32(HttpContext.Session.GetInt32("examID")))); UserService.AddExamHistory(user.Id, Convert.ToInt32(HttpContext.Session.GetInt32("examID")), judegeC.All - judegeC.right + choiceC.All - choiceC.right + blankC.All - blankC.right, score); //ViewBag.judegeC = judegeC; //ViewBag.choiceC = choiceC; //ViewBag.blankC = blankC; //ViewBag.score = score; //ViewBag.eachscore = EachScore; //ViewBag.name =; return(Content("/user/exam_Result1")); //return View("/user/resultpage?examid"+ HttpContext.Session.GetInt32("examID").ToString()); }
private void Button1_Click(object sender, EventArgs e) { if (nome.Text == "") { MessageBox.Show("O campo 'Descrição' é obrigatório e não pode ficar vazio.", "Alerta do sistema", MessageBoxButtons.OK); } else { Cliente cliente = new Cliente(); cliente.nome = nome.Text; cliente.cpf = cpf.Text; cliente.rg = rg.Text; cliente.nascimento = nascimento.Value.Date; nascimento.CustomFormat = "dd/MM/yyyy"; Console.WriteLine(nascimento.Value); //int selectedIndex = plano.SelectedIndex; int selectedValue = (int)plano.SelectedValue; cliente.plano = selectedValue; cliente.valor = preco.Text; Console.WriteLine(selectedValue); string DATA = JsonNet.Serialize(cliente); string URL = "http://localhost:21529/PointBarber/clientes"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "POST"; request.ContentType = "application/json"; request.Accept = "application/json"; request.ContentLength = DATA.Length; try { using (Stream webStream = request.GetRequestStream()) using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII)) { requestWriter.Write(DATA); } WebResponse webResponse = request.GetResponse(); HttpStatusCode response_code = ((HttpWebResponse)webResponse).StatusCode; if (response_code == HttpStatusCode.Created) { nome.Text = preco.Text = ""; if (MessageBox.Show("Registro salvo com sucesso!" + Environment.NewLine + "Gostaria de cadastrar outra barbearia?", "Alerta do sistema", MessageBoxButtons.YesNo) == DialogResult.Yes) { TelaCadastro telaCadastrar = new TelaCadastro(); telaCadastrar.MdiParent = this; telaCadastrar.Show(); } } else { Stream webStream = webResponse.GetResponseStream(); StreamReader responseReader = new StreamReader(webStream); string response = responseReader.ReadToEnd(); MessageBox.Show("Erro no servidor:", "Alerta do sistema", MessageBoxButtons.OK); } } catch (Exception ex) { MessageBox.Show("Erro no lado do servidor.", "Alerta do sistema", MessageBoxButtons.OK); } } }