internal Link(JsonTextReader jsonReader) { int depth = jsonReader.Depth; while (jsonReader.Read()) { switch (jsonReader.TokenType) { case JsonToken.PropertyName: switch (jsonReader.Value.ToString()) { case "href": Href = new Uri(jsonReader.ReadAsString()); break; case "method": Method = jsonReader.ReadAsString(); break; case "templated": Templated = jsonReader.ReadAsBoolean().Value; break; } break; case JsonToken.EndObject: if (jsonReader.Depth == depth) { return; } break; } } }
protected virtual JsonTextReader ReadAllText(string textToParse) { JsonTextReader reader = new JsonTextReader(new StringReader(textToParse)); configVersion = reader.ReadAsInt32() ?? 1; name = reader.ReadAsString(); info = reader.ReadAsString(); reader.Read(); levelResources = (LevelResource[])reader.Value; reader.Read(); tags = (string[])reader.Value; handCount = reader.ReadAsInt32() ?? 1; moreInfoURL = reader.ReadAsString(); speed = reader.ReadAsDouble() ?? 15; lives = reader.ReadAsInt32() ?? 5; maxLives = reader.ReadAsInt32() ?? 5; musicFile = reader.ReadAsString(); musicTime = reader.ReadAsDouble() ?? 10; iconFile = reader.ReadAsString(); environmentType = reader.ReadAsInt32() ?? -1; reader.Read(); unlockConditions = (object[])reader.Value; hidden = reader.ReadAsBoolean() ?? false; reader.Read(); checkpoints = (double[])reader.Value; reader.Read(); events = (Event[])reader.Value; return(reader); }
public static List <Punishment> DeserializePun(this string json) { JsonTextReader reader = new JsonTextReader(new StringReader(json)); List <Punishment> Punisment = new List <Punishment>(); reader.Read(); reader.Read(); while (reader.Read()) { if (reader.Value != null) { IPAddress ip = IPAddress.Parse(reader.ReadAsString()); reader.Read(); RevokedPerms revoked = (RevokedPerms)reader.ReadAsInt32(); reader.Read(); bool tempban = (bool)reader.ReadAsBoolean(); reader.Read(); DateTime start = DateTime.Parse(reader.ReadAsString()); reader.Read(); DateTime end = DateTime.Parse(reader.ReadAsString()); reader.Read(); Punisment.Add(new Punishment(ip, revoked, tempban, start, end)); } } return(Punisment); }
private LibraryStub ReadOneLibrary(JsonTextReader reader) { string hash = null; string type = null; bool serviceable = false; string path = null; string hashPath = null; string runtimeStoreManifestName = null; reader.ReadStartObject(); while (reader.Read() && reader.TokenType == JsonToken.PropertyName) { switch ((string)reader.Value) { case DependencyContextStrings.Sha512PropertyName: hash = reader.ReadAsString(); break; case DependencyContextStrings.TypePropertyName: type = reader.ReadAsString(); break; case DependencyContextStrings.ServiceablePropertyName: serviceable = reader.ReadAsBoolean().GetValueOrDefault(false); break; case DependencyContextStrings.PathPropertyName: path = reader.ReadAsString(); break; case DependencyContextStrings.HashPathPropertyName: hashPath = reader.ReadAsString(); break; case DependencyContextStrings.RuntimeStoreManifestPropertyName: runtimeStoreManifestName = reader.ReadAsString(); break; default: reader.Skip(); break; } } reader.CheckEndObject(); return(new LibraryStub() { Hash = hash, Type = Pool(type), Serviceable = serviceable, Path = path, HashPath = hashPath, RuntimeStoreManifestName = runtimeStoreManifestName }); }
/// <summary> /// Populate APIData object from a JSON string. /// </summary> /// <param name="json">JSON string representing the data.</param> /// <param name="dataObject">The object to populate.</param> public static void PopulateFromJSON(string json, APIData dataObject) { dataObject.AssignedData = false; using (var sr = new StringReader(json)) using (var reader = new JsonTextReader(sr)) { // Use buffer reader.ArrayPool = JSONArrayPool.Instance; while (reader.Read()) { if ((reader.TokenType == JsonToken.PropertyName) && (reader.Depth == 1)) { switch (reader.Value.ToString()) { case "action": dataObject.Action = reader.ReadAsString(); break; case "device_id": case "from": dataObject.DeviceId = reader.ReadAsInt32(); break; case "uid": dataObject.StringData = reader.ReadAsString(); break; case "ad_was_shown": dataObject.StateData = reader.ReadAsBoolean(); break; default: // Reset StringBuilder dataObject.Data.Length = 0; using (var sw = new StringWriter(dataObject.Data)) using (var writer = new JsonTextWriter(sw)) { // Use buffer writer.ArrayPool = JSONArrayPool.Instance; reader.Read(); writer.WriteToken(reader); } dataObject.AssignedData = true; break; } } } // while(reader.Read()) }// using StringReader / JsonTextReader - Dispose } // PopulateFromJSON()
public static World LoadFromFile(string filename) { using (System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open)) using (System.IO.TextReader textReader = new System.IO.StreamReader(stream)) using (JsonReader reader = new JsonTextReader(textReader)) { reader.Read(); // Start root object reader.Read(); // grids property reader.Read(); // Begin grids array reader.Read(); // Begin grid object or end of array List <Grid> grids = new List <Grid>(); while (reader.TokenType != JsonToken.EndArray) { reader.Read(); // x property int x = reader.ReadAsInt32().Value; reader.Read(); // y property int y = reader.ReadAsInt32().Value; reader.Read(); // palettePath property string palettePath = reader.ReadAsString(); reader.Read(); int width = reader.ReadAsInt32().Value; reader.Read(); int height = reader.ReadAsInt32().Value; reader.Read(); // tiles property reader.Read(); // start array Grid grid = new Grid(x, y, palettePath, width, height); int i = 0; reader.Read(); // Read the beginning of the object while (reader.TokenType != JsonToken.EndArray) { reader.Read(); int paletteIndex = reader.ReadAsInt32().Value; reader.Read(); bool collides = reader.ReadAsBoolean().Value; reader.Read(); reader.Read(); // Read the beginning of the next object or the end of the array grid.Tiles[i % width, i / width].PaletteIndex = paletteIndex; grid.Tiles[i % width, i / width].Collides = collides; i++; } reader.Read(); // End grid object reader.Read(); // Begin next grid object or end of array grids.Add(grid); } return(new World(grids)); } }
internal Disk(JsonTextReader jsonReader) { int depth = jsonReader.Depth; while (jsonReader.Read()) { switch (jsonReader.TokenType) { case JsonToken.PropertyName: switch (jsonReader.Value.ToString()) { case "max_file_size": MaxFileSize = long.Parse(jsonReader.ReadAsString()); break; case "total_space": TotalSpace = long.Parse(jsonReader.ReadAsString()); break; case "trash_size": TrashSize = long.Parse(jsonReader.ReadAsString()); break; case "is_paid": IsPaid = jsonReader.ReadAsBoolean().Value; break; case "used_space": UsedSpace = long.Parse(jsonReader.ReadAsString()); break; case "system_folders": SystemFolders = new SystemFolders(jsonReader); break; case "revision": Revision = long.Parse(jsonReader.ReadAsString()); break; } break; case JsonToken.EndObject: if (jsonReader.Depth == depth) { return; } break; } } }
private LibraryStub ReadOneLibrary(JsonTextReader reader) { string hash = null; string type = null; bool serviceable = false; string path = null; reader.ReadStartObject(); while (reader.Read() && reader.TokenType == JsonToken.PropertyName) { switch ((string)reader.Value) { case DependencyContextStrings.Sha512PropertyName: hash = reader.ReadAsString(); break; case DependencyContextStrings.TypePropertyName: type = reader.ReadAsString(); break; case DependencyContextStrings.ServiceablePropertyName: serviceable = reader.ReadAsBoolean().GetValueOrDefault(false); break; case DependencyContextStrings.PathPropertyName: path = reader.ReadAsString(); break; default: throw new FormatException($"Unknown property name '{reader.Value}'"); } } reader.CheckEndObject(); return(new LibraryStub() { Hash = hash, Type = Pool(type), Serviceable = serviceable, Path = path }); }
public Form1() { string limits = "2018/11/28 12:00"; #if TESTUSE if (DateTime.Now < DateTime.Parse(limits)) { if (MessageBox.Show("当前是测试版本,该版本在" + limits + "后过期,是否继续试用?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) { System.Environment.Exit(-1); } } else { MessageBox.Show("该版本已经过期,请使用正版软件!"); System.Environment.Exit(-1); } #endif #if CHECKSERVER string myLimit = ""; bool notify = false; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(BaseConfig.checkServer); try { JsonTextReader reader = new JsonTextReader(new StringReader(client.GetStringAsync("/status").Result)); while (reader.Read()) { if (reader.TokenType == JsonToken.PropertyName) { switch (reader.Value) { case "ProductId": reader.Read(); break; case "Enable": reader.ReadAsBoolean(); if (!((bool)reader.Value)) { MessageBox.Show("您没有该软件的使用权限,请联系软件管理员!"); System.Environment.Exit(-1); } break; case "Limit": reader.Read(); myLimit = reader.Value as String; break; case "Notify": reader.ReadAsBoolean(); notify = (bool)reader.Value; break; } } } if (myLimit.Length > 5) { if (DateTime.Now > DateTime.Parse(myLimit)) { MessageBox.Show("该版本已经过期(" + myLimit + "),请使用正版软件!"); System.Environment.Exit(-1); } else { if (notify) { if (MessageBox.Show("该软件于" + myLimit + "后过期,是否继续使用?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) { System.Environment.Exit(-1); } } } } }catch (AggregateException e) { e.Handle((err) => { MessageBox.Show("服务器获取信息失败,软件无法正常使用!"); System.Environment.Exit(-1); return(true); }); } #endif this.StartPosition = FormStartPosition.CenterScreen; try { DataBaseService.InitDefaultBase(); } catch (Exception es) { MessageBox.Show(es.Message); System.Environment.Exit(-1); } this.InitWorkComponent(new SimultaneousWork()); InitializeComponent(); this.initDataGrid(); this.InitDatabase(); this.comboBox1.SelectedIndex = 0; this.eventLog1.Source = "Application"; //this.eventLog1.WriteEntry("Form Load? Hafrans", System.Diagnostics.EventLogEntryType.FailureAudit); }
internal bool Login(string username, string password, string refreshToken) { string postData; if (refreshToken == "") { postData = "client_id=" + "bYGKuGVw91e0NMfPGp44euvGt59s" + "&" + "client_secret=" + "HP3RmkgAmEGro0gn1x9ioawQE8WMfvLXDz3ZqxpK" + "&" + "grant_type=password" + "&" + "username="******"&" + "password="******"client_id=" + "bYGKuGVw91e0NMfPGp44euvGt59s" + "&" + "client_secret=" + "HP3RmkgAmEGro0gn1x9ioawQE8WMfvLXDz3ZqxpK" + "&" + "grant_type=refresh_token" + "&" + "refresh_token=" + refreshToken; } string response; try { response = HttpHelper.POST(LOGIN_URL, postData); } catch { return(false); } var reader = new JsonTextReader(new StringReader(response)); while (reader.Read()) { switch (reader.Path) { case "response.access_token": AccessToken = reader.ReadAsString(); break; case "response.refresh_token": RefreshToken = reader.ReadAsString(); break; case "response.user.profile_image_urls.px_170x170": AvatarUrl = reader.ReadAsString(); break; case "response.user.id": Id = reader.ReadAsString(); break; case "response.user.name": Name = reader.ReadAsString(); break; case "response.user.account": Account = reader.ReadAsString(); break; case "response.user.is_premium": IsPremium = reader.ReadAsBoolean().Value; break; } } return(true); }
/// <summary> /// Function to convert a JSON formatted string into a <see cref="IGorgonAnimation"/> object. /// </summary> /// <param name="renderer">The renderer for the animation.</param> /// <param name="json">The JSON string containing the animation data.</param> /// <returns>A new <see cref="IGorgonAnimation"/>.</returns> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="renderer"/>, or the <paramref name="json"/> parameter is <b>null</b>.</exception> /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="json"/> parameter is empty.</exception> /// <exception cref="GorgonException">Thrown if the JSON string does not contain animation data, or there is a version mismatch.</exception> public IGorgonAnimation FromJson(Gorgon2D renderer, string json) { if (renderer == null) { throw new ArgumentNullException(nameof(renderer)); } if (json == null) { throw new ArgumentNullException(nameof(json)); } if (string.IsNullOrWhiteSpace(json)) { throw new ArgumentEmptyException(nameof(json)); } string animName = string.Empty; float animLength = 0; int loopCount = 0; bool isLooped = false; var colorConvert = new JsonGorgonColorKeyConverter(); var textureConvert = new JsonTextureKeyConverter(renderer.Graphics); var vec3Converter = new JsonVector3KeyConverter(); var rectConverter = new JsonRectKeyConverter(); TrackInterpolationMode posInterp = TrackInterpolationMode.None; TrackInterpolationMode scaleInterp = TrackInterpolationMode.None; TrackInterpolationMode rotInterp = TrackInterpolationMode.None; TrackInterpolationMode sizeInterp = TrackInterpolationMode.None; TrackInterpolationMode colorInterp = TrackInterpolationMode.None; TrackInterpolationMode boundInterp = TrackInterpolationMode.None; List <GorgonKeyVector3> positions = null; List <GorgonKeyVector3> rotations = null; List <GorgonKeyVector3> scales = null; List <GorgonKeyVector3> sizes = null; List <GorgonKeyGorgonColor> colors = null; List <GorgonKeyRectangle> bounds = null; List <GorgonKeyTexture2D> textures = null; using (var baseReader = new StringReader(json)) using (var reader = new JsonTextReader(baseReader)) { if (!IsReadableJObject(reader)) { throw new GorgonException(GorgonResult.CannotRead, Resources.GOR2DIO_ERR_JSON_NOT_ANIM); } while (reader.Read()) { if (reader.TokenType != JsonToken.PropertyName) { continue; } string propName = reader.Value.ToString().ToUpperInvariant(); switch (propName) { case "POSITIONS": positions = ReadVector3(reader, vec3Converter, out posInterp); break; case "SCALES": scales = ReadVector3(reader, vec3Converter, out scaleInterp); break; case "ROTATIONS": rotations = ReadVector3(reader, vec3Converter, out rotInterp); break; case "SIZE": sizes = ReadVector3(reader, vec3Converter, out sizeInterp); break; case "BOUNDS": bounds = ReadRects(reader, rectConverter, out boundInterp); break; case "COLORS": colors = ReadColors(reader, colorConvert, out colorInterp); break; case "TEXTURES": textures = ReadTextures(reader, textureConvert); break; case "NAME": animName = reader.ReadAsString(); break; case "LENGTH": animLength = (float)(reader.ReadAsDecimal() ?? 0); break; case "ISLOOPED": isLooped = (reader.ReadAsBoolean() ?? false); break; case "LOOPCOUNT": loopCount = (reader.ReadAsInt32() ?? 0); break; } } } // There's no name, so it's a broken JSON. if (string.IsNullOrWhiteSpace(animName)) { throw new GorgonException(GorgonResult.CannotRead, Resources.GOR2DIO_ERR_JSON_NOT_ANIM); } var builder = new GorgonAnimationBuilder(); if ((positions != null) && (positions.Count > 0)) { builder.PositionInterpolationMode(posInterp) .EditPositions() .SetKeys(positions) .EndEdit(); } if ((scales != null) && (scales.Count > 0)) { builder.ScaleInterpolationMode(scaleInterp) .EditScale() .SetKeys(scales) .EndEdit(); } if ((rotations != null) && (rotations.Count > 0)) { builder.RotationInterpolationMode(rotInterp) .EditRotation() .SetKeys(rotations) .EndEdit(); } if ((sizes != null) && (sizes.Count > 0)) { builder.SizeInterpolationMode(sizeInterp) .EditSize() .SetKeys(sizes) .EndEdit(); } if ((colors != null) && (colors.Count > 0)) { builder.ColorInterpolationMode(colorInterp) .EditColors() .SetKeys(colors) .EndEdit(); } if ((bounds != null) && (bounds.Count > 0)) { builder.RotationInterpolationMode(boundInterp) .EditRectangularBounds() .SetKeys(bounds) .EndEdit(); } if ((textures != null) && (textures.Count > 0)) { builder.Edit2DTexture() .SetKeys(textures) .EndEdit(); } IGorgonAnimation result = builder.Build(animName, animLength); result.LoopCount = loopCount; result.IsLooped = isLooped; result.Speed = 1.0f; return(result); }
/// <summary> /// Populate AirConsole device object from a JSON string. /// </summary> /// <param name="json">JSON string representing the data.</param> /// <param name="deviceObject">The object to populate.</param> public static void PopulateFromJSON(string json, Device deviceObject) { using (var sr = new StringReader(json)) using (var reader = new JsonTextReader(sr)) { // Use buffer reader.ArrayPool = JSONArrayPool.Instance; while (reader.Read()) { if (reader.TokenType == JsonToken.PropertyName) { switch (reader.Value.ToString()) { case "location": if (reader.Depth == 1) { deviceObject.Location = reader.ReadAsString(); } break; case "uid": if (reader.Depth == 1) { deviceObject.UID = reader.ReadAsString(); } break; case "nickname": if (reader.Depth == 1) { deviceObject.Nickname = reader.ReadAsString(); } break; case "auth": if (reader.Depth == 1) { deviceObject.IsLoggedIn = reader.ReadAsBoolean() ?? false; } break; case "premium": if (reader.Depth == 1) { deviceObject.IsHero = reader.ReadAsBoolean() ?? false; } break; case "app": if (reader.Depth == 2) { deviceObject.IsUsingBrowser = reader.ReadAsString() == "web"; } break; case "slow_connection": if (reader.Depth == 1) { deviceObject.HasSlowConnection = reader.ReadAsBoolean() ?? false; } break; case "custom": if (reader.Depth != 1) { break; } // Reset StringBuilder deviceObject.CustomData.Length = 0; using (var sw = new StringWriter(deviceObject.CustomData)) using (var writer = new JsonTextWriter(sw)) { // Use buffer writer.ArrayPool = JSONArrayPool.Instance; reader.Read(); writer.WriteToken(reader); } break; default: break; } } // if(reader.TokenType == JsonToken.PropertyName) } // while(reader.Read()) }// using StringReader / JsonTextReader - Dispose } // PopulateFromJSON()
// Loads config from file and resets Test Mode to Disabled public static bool LoadConfig() { try { FileStream fs = File.Open("config.json", FileMode.Open, FileAccess.Read); JsonReader jsonConfig = new JsonTextReader(new StreamReader(fs)); jsonConfig.Read(); // Comment jsonConfig.Read(); // StartObject jsonConfig.Read(); // PropertyName ConfigVersion = jsonConfig.ReadAsString(); if (Version == ConfigVersion) { jsonConfig.Read(); // PropertyName. Etc... BRBDirectory = jsonConfig.ReadAsString(); jsonConfig.Read(); StartPlayerOnDifferentScreen = (bool)jsonConfig.ReadAsBoolean(); jsonConfig.Read(); MakePlayerTopMost = (bool)jsonConfig.ReadAsBoolean(); TestMode = false; jsonConfig.Read(); Chapter = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); PermittedOvertimeMinutes = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); PermittedUndertimePercent = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); AvoidForChaptersAfterPlay = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); PreferredPlayAfterChapters = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); ChapterHistoryConsidered = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); ReservedChanceForPriorityBRBs = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); AutoGuaranteedPlaysForNewBRBs = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); AutoPriorityPlaysForNewBRBs = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); FavouriteMultiplier = (double)jsonConfig.ReadAsDouble(); jsonConfig.Read(); SortingMode = (BRBPlaylistSortingMode)jsonConfig.ReadAsInt32(); jsonConfig.Read(); StandardPlayerVolume = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); InterBRBCountdown = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); TimeUntilHobbVLC = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); HobbVLCCountdown = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); HobbVLCMaxDuration = (int)jsonConfig.ReadAsInt32(); jsonConfig.Read(); HobbVLCIgnoreMaxDurationAfterTries = (int)jsonConfig.ReadAsInt32(); // That is all, no need to continue reading jsonConfig.Close(); fs.Close(); return(true); } else // There has been an app update { jsonConfig.Close(); fs.Close(); return(UpdateToNewAppVersion()); } } catch (IOException) { return(false); } catch (JsonException) { return(false); } }
public static bool ReadAsBoolean(this JsonTextReader source, bool defaultValue) { bool?nullableBool = source.ReadAsBoolean(); return(nullableBool ?? defaultValue); }
private void OnEnable() { if (!File.Exists(SettingsPath)) { return; } var settingsStream = File.OpenRead(SettingsPath); TextReader textReader = new StreamReader(settingsStream); var jsonReader = new JsonTextReader(textReader); if (jsonReader.Read() && jsonReader.TokenType != JsonToken.StartObject) { throw new Exception("GLTF settings must be an object"); } while (jsonReader.Read() && jsonReader.TokenType == JsonToken.PropertyName) { var curProp = jsonReader.Value.ToString(); switch (curProp) { case "OutputPath": OutputPath = jsonReader.ReadAsString(); break; case "ExportNames": GLTFSceneExporter.ExportNames = jsonReader.ReadAsBoolean().Value; break; case "ExportFullPath": GLTFSceneExporter.ExportFullPath = jsonReader.ReadAsBoolean().Value; break; case "RequireExtensions": GLTFSceneExporter.RequireExtensions = jsonReader.ReadAsBoolean().Value; break; case "ExportPhysicsColliders": GLTFSceneExporter.ExportPhysicsColliders = jsonReader.ReadAsBoolean().Value; break; case "DisableYMovement": AnimationCorrector.DisableYMovement = jsonReader.ReadAsBoolean().Value; break; case "DisableXZMovement": AnimationCorrector.DisableXZMovement = jsonReader.ReadAsBoolean().Value; break; case "DealtWithBoneName": AnimationCorrector.DealtWithBoneName = jsonReader.ReadAsString(); break; case "EnableAnimationCorrector": AnimationCorrector.Enable = jsonReader.ReadAsBoolean().Value; break; } } jsonReader.Close(); textReader.Close(); }
/// <summary> /// Reads any existing cache index file, building the in-memory representation, without bringing in actual item data until actually requested. /// </summary> private void RestoreIndex() { if (DefaultStorageStrategy == CacheStorageStrategy.OnlyMemory) { return; } try { var fn = Path.Combine(RootDirectory, "index.json"); if (File.Exists(fn)) { using (var jr = new JsonTextReader(new StreamReader(File.OpenRead(fn)))) { // Should be start array jr.Read(); while (jr.Read() && jr.TokenType != JsonToken.EndArray) { // Should be start object jr.Read(); var i = new MFSEntry(); i.FileName = jr.ReadAsString(); jr.Read(); i.ObjectTypeName = jr.ReadAsString(); jr.Read(); i.ByQuerySHA = jr.ReadAsString(); jr.Read(); i.QueryForAll = jr.ReadAsBoolean().GetValueOrDefault(); jr.Read(); i.ByIdentityComposite = jr.ReadAsString(); jr.Read(); i.ExpiryDate = jr.ReadAsDateTime().GetValueOrDefault(); jr.Read(); if (i.ExpiryDate > DateTime.Now) { i.Active = true; i.Persisted = true; _index.Add(i); } } } } else { FlushAll(RootDirectory); _index.Clear(); } } catch (Exception ex) { CEFDebug.WriteInfo($"Exception in cache restore index: {ex.Message}"); // Any problems, go with an empty cache FlushAll(RootDirectory); _index.Clear(); } }
/// <summary> /// Process inputs. /// </summary> /// <param name="playerId">Player identifier.</param> /// <param name="data">Input data as JSON formatted string.</param> public void ProcessInput(int playerId, string data) { int diffPlayerCount = playerId - VInput.Inputs.Count; // First input from this player? for (int i = 0; i <= diffPlayerCount; i++) { VInput.Inputs.Add(new Dictionary <string, ElementInput>()); } string currentElementName = null; bool stopReading = false; // Read input name identifier using (var sr = new StringReader(data)) using (var reader = new JsonTextReader(sr)) { // Use buffer reader.ArrayPool = JSONArrayPool.Instance; while (!stopReading && reader.Read()) { if ((reader.TokenType == JsonToken.PropertyName) && (reader.Path == "volplane.name")) { currentElementName = reader.ReadAsString(); stopReading = true; } } } // No volplane input if (currentElementName == null) { return; } // Get input object by name, or create new one if not specified yet if (!VInput.Inputs[playerId].TryGetValue(currentElementName, out tempInput)) { tempInput = new ElementInput(); VInput.Inputs[playerId].Add(currentElementName, tempInput); if (Config.DebugLog == (int)DebugState.All) { VDebug.LogFormat("[Volplane (Input Handling)] New input registered: '{0:G}'.", currentElementName); } } // Enqueue processing if the same input changed state in the same frame if (tempInput.Dirty) { updateQueue.Enqueue(delegate { ProcessInput(playerId, data); }); if (Config.DebugLog == (int)DebugState.All) { VDebug.Log("[Volplane (Input Handling)] Queueing multiple inputs from same element."); } return; } // Read and processing input data using (var sr = new StringReader(data)) using (var reader = new JsonTextReader(sr)) { // Use buffer reader.ArrayPool = JSONArrayPool.Instance; while (reader.Read()) { if (reader.TokenType == JsonToken.PropertyName) { switch (reader.Path) { // Input type case "volplane.type": reader.Read(); switch (reader.Value.ToString()) { case "dpad": tempInput.Type = ElementInput.InputType.DPad; break; case "joystick": tempInput.Type = ElementInput.InputType.Joystick; break; case "swipe": tempInput.Type = ElementInput.InputType.SwipeField; break; case "touch": tempInput.Type = ElementInput.InputType.TouchArea; break; case "motion": tempInput.Type = ElementInput.InputType.Motion; break; default: tempInput.Type = ElementInput.InputType.Button; break; } break; // Input state case "volplane.data.state": tempInput.State = reader.ReadAsBoolean() ?? false; break; // Input timestamp case "volplane.data.timeStamp": reader.Read(); tempInput.Delay = (int)(VolplaneController.AirConsole.GetServerTime() - Int64.Parse(reader.Value.ToString())); break; // Coordinate X case "volplane.data.x": tempInput.X = (float)(reader.ReadAsDouble() ?? 0d); break; // Coordinate X case "volplane.data.y": tempInput.Y = (float)(reader.ReadAsDouble() ?? 0d); break; // Trigger indicator case "volplane.data.hadDirections": tempInput.HadDirections = reader.ReadAsBoolean() ?? false; break; // Swipe distance case "volplane.data.distance": tempInput.Distance = (float)(reader.ReadAsDouble() ?? 0d); break; // Swipe angle in radians case "volplane.data.angle": tempInput.Angle = (float)(reader.ReadAsDouble() ?? 0d); break; // Swipe angle in degree case "volplane.data.degree": tempInput.Degree = (float)(reader.ReadAsDouble() ?? 0d); break; // Swipe speed case "volplane.data.speed": tempInput.Speed = (float)(reader.ReadAsDouble() ?? 0d); break; // Accelerometer X case "volplane.data.ax": tempInput.AX = (float)(reader.ReadAsDouble() ?? 0d); break; // Accelerometer Y case "volplane.data.ay": tempInput.AY = (float)(reader.ReadAsDouble() ?? 0d); break; // Accelerometer Z case "volplane.data.az": tempInput.AZ = (float)(reader.ReadAsDouble() ?? 0d); break; // Gyroscope alpha case "volplane.data.alpha": tempInput.Alpha = (float)(reader.ReadAsDouble() ?? 0d); break; // Gyroscope beta case "volplane.data.beta": tempInput.Beta = (float)(reader.ReadAsDouble() ?? 0d); break; // Gyroscope gamma case "volplane.data.gamma": tempInput.Gamma = (float)(reader.ReadAsDouble() ?? 0d); break; } } } } // Set dirty tempInput.Dirty = true; // Fire events switch (tempInput.Type) { case ElementInput.InputType.Button: // Event if (VInput.ButtonEvents && (OnButton != null)) { updateQueue.Enqueue(delegate { OnButton(playerId, currentElementName, tempInput.State); }); } break; case ElementInput.InputType.DPad: // Event if (VInput.DPadEvents && (OnDPad != null)) { updateQueue.Enqueue(delegate { OnDPad(playerId, currentElementName, new Vector2(tempInput.X, tempInput.Y)); }); } break; case ElementInput.InputType.Joystick: // Event if (VInput.JoystickEvents && (OnJoystick != null)) { updateQueue.Enqueue(delegate { OnJoystick(playerId, currentElementName, new Vector2(tempInput.X, tempInput.Y)); }); } break; case ElementInput.InputType.SwipeField: // Event if (VInput.SwipeEvents && (OnSwipe != null)) { updateQueue.Enqueue(delegate { OnSwipe(playerId, currentElementName, new Vector2(tempInput.X, tempInput.Y)); }); } break; case ElementInput.InputType.TouchArea: // Event if (VInput.TouchEvents && (OnTouch != null)) { updateQueue.Enqueue(delegate { OnTouch(playerId, currentElementName, new Vector2(tempInput.X, tempInput.Y)); }); } break; default: // Events if (VInput.MotionEvents && (OnAccelerometer != null)) { updateQueue.Enqueue(delegate { OnAccelerometer(playerId, new Vector3(tempInput.AX, tempInput.AY, tempInput.AZ)); }); } if (VInput.MotionEvents && (OnGyroscope != null)) { updateQueue.Enqueue(delegate { OnGyroscope(playerId, new Vector3(tempInput.Alpha, tempInput.Beta, tempInput.Gamma)); }); } break; } }
/// <summary> /// Reads the next JSON token from the stream as a <see cref="bool" /><c>?</c>. /// </summary> /// <returns> /// A <see cref="bool" /><c>?</c>. This method will return <see langword="null"/> at the end of an array. /// </returns> public override bool?ReadAsBoolean() => jsonTextReader.ReadAsBoolean();
public bool?ReadAsNullableBoolean() { Debug.Assert(IsTokenTypeProperty()); return(_reader.ReadAsBoolean()); }