/** * Proxies any request made to this web server to the clientconfig service. Rewrites the response * to have any chat servers point to localhost at the specified port. */ private async Task ProxyAndRewriteResponse(string configUrl, int chatPort, IHttpContext ctx) { var url = configUrl + ctx.Request.RawUrl; using (var message = new HttpRequestMessage(HttpMethod.Get, url)) { // Cloudflare bitches at us without a user agent. message.Headers.TryAddWithoutValidation("User-Agent", ctx.Request.Headers["user-agent"]); // Add authorization headers for player config. if (ctx.Request.Headers["x-riot-entitlements-jwt"] != null) { message.Headers.TryAddWithoutValidation("X-Riot-Entitlements-JWT", ctx.Request.Headers["x-riot-entitlements-jwt"]); } if (ctx.Request.Headers["authorization"] != null) { message.Headers.TryAddWithoutValidation("Authorization", ctx.Request.Headers["authorization"]); } var result = await _client.SendAsync(message); var content = await result.Content.ReadAsStringAsync(); var modifiedContent = content; try { var configObject = (JsonObject)SimpleJson.DeserializeObject(content); // Set chat.affinities (a dictionary) to all localhost. if (configObject.ContainsKey("chat.affinities")) { var affinities = (JsonObject)configObject["chat.affinities"]; foreach (var key in new List <string>(affinities.Keys)) // clone to prevent concurrent modification { affinities[key] = "127.0.0.1"; } } string riotChatHost = null; var riotChatPort = 0; // Set fallback host to localhost. if (configObject.ContainsKey("chat.host")) { riotChatHost = configObject["chat.host"].ToString(); configObject["chat.host"] = "127.0.0.1"; } // Set chat port. if (configObject.ContainsKey("chat.port")) { riotChatPort = int.Parse(configObject["chat.port"].ToString()); configObject["chat.port"] = chatPort; } // Allow an invalid cert. if (configObject.ContainsKey("chat.allow_bad_cert.enabled")) { configObject["chat.allow_bad_cert.enabled"] = true; } modifiedContent = SimpleJson.SerializeObject(configObject); if (riotChatHost != null && riotChatPort != 0) { PatchedChatServer?.Invoke(this, new ChatServerEventArgs { ChatHost = riotChatHost, ChatPort = riotChatPort }); } } catch (Exception ex) { Trace.WriteLine(ex); // Show a message instead of failing silently. MessageBox.Show( "Deceive was unable to rewrite a League of Legends configuration file. This normally happens because Riot changed something on their end. Please check if there's a new version of Deceive available, or contact the creator through GitHub (https://github.com/molenzwiebel/deceive) or Discord if there's not.\n\n" + ex, StartupHandler.DeceiveTitle, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1 ); Application.Exit(); } // Using the builtin EmbedIO methods for sending the response adds some garbage in the front of it. // This seems to do the trick. var responseBytes = Encoding.UTF8.GetBytes(modifiedContent); ctx.Response.StatusCode = (int)result.StatusCode; ctx.Response.SendChunked = false; ctx.Response.ContentLength64 = responseBytes.Length; ctx.Response.ContentType = "application/json"; ctx.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length); ctx.Response.OutputStream.Close(); } }
public static void startMinecraft(string version, string name, string ram, string uuid, string accessToken) { string arg = ""; if (Form1.isOnline) { if (version[version.Length - 1] != 'F') { string minecraft_json = Form1.webClient.DownloadString("http://s3.amazonaws.com/Minecraft.Download/versions/" + version + "/" + version + ".json"); dynamic decoded = SimpleJson.DeserializeObject(minecraft_json); var minecraft_dir = Form1.appdata + "\\skymin\\minecraft"; string temp = decoded["libraries"][0]["name"]; string[] temp_lines = temp.Split(' ', ':'); string temp_natives; if (string.IsNullOrEmpty(Form1.readXml(Form1.appdata + "\\skymin\\config\\user.xml", "Java-args")) || Form1.readXml(Form1.appdata + "\\skymin\\config\\user.xml", "Java-args").Equals("false")) { arg += " -XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump -Xmx{0}M "; } else { arg += " -XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump -Xmx{0}M " + Form1.readXml(Form1.appdata + "\\skymin\\config\\user.xml", "Java-args") + " "; } arg += @"-Djava.library.path=" + minecraft_dir + "\\versions\\" + version + "\\natives "; arg += @"-cp " + minecraft_dir + "\\libraries\\" + temp_lines[0].Replace(".", "\\") + "\\" + temp_lines[1] + "\\" + temp_lines[2] + "\\" + temp_lines[1] + "-" + temp_lines[2] + ".jar;"; for (int i = 1; i <= (decoded["libraries"].Count) - 1; i++) { temp = decoded["libraries"][i]["name"]; try { temp_natives = decoded["libraries"][i]["natives"]["windows"]; } catch { temp_lines = temp.Split(' ', ':'); arg += minecraft_dir + "\\libraries\\" + temp_lines[0].Replace(".", "\\") + "\\" + temp_lines[1] + "\\" + temp_lines[2] + "\\" + temp_lines[1] + "-" + temp_lines[2] + ".jar;"; } } arg += minecraft_dir + "\\versions\\" + version + "\\" + version + ".jar"; arg += @" " + decoded["mainClass"] + " --username " + name + " --version " + decoded["id"] + " --gameDir " + minecraft_dir + " --assetsDir " + minecraft_dir + "\\assets" + " --assetIndex " + decoded["assets"] + " --uuid " + uuid + " --accessToken " + accessToken + " --userProperties [] "; Form1.editXml(Form1.appdata + "\\skymin\\config\\launcher.xml", "Launcher", "Minecraft_Launch_Code", arg); } else //else { string forge_json = Form1.webClient.DownloadString("https://raw.githubusercontent.com/dom133/SkyMin-Launcher/master/Forge/" + version + ".json"); dynamic forge_decoded = SimpleJson.DeserializeObject(forge_json); string minecraft_json = Form1.webClient.DownloadString("http://s3.amazonaws.com/Minecraft.Download/versions/" + forge_decoded["jar"] + "/" + forge_decoded["jar"] + ".json"); dynamic decoded = SimpleJson.DeserializeObject(minecraft_json); var minecraft_dir = Form1.appdata + "\\skymin\\minecraft"; string temp = decoded["libraries"][0]["name"]; string[] temp_lines = temp.Split(' ', ':'); string temp_natives; if (string.IsNullOrEmpty(Form1.readXml(Form1.appdata + "\\skymin\\config\\user.xml", "Java-args")) || Form1.readXml(Form1.appdata + "\\skymin\\config\\user.xml", "Java-args").Equals("false")) { arg += " -XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump -Xmx{0}M "; } else { arg += " -XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump -Xmx{0}M " + Form1.readXml(Form1.appdata + "\\skymin\\config\\user.xml", "Java-args") + " "; } arg += @"-Djava.library.path=" + minecraft_dir + "\\versions\\" + forge_decoded["jar"] + "\\natives "; arg += @"-cp " + minecraft_dir + "\\libraries\\" + temp_lines[0].Replace(".", "\\") + "\\" + temp_lines[1] + "\\" + temp_lines[2] + "\\" + temp_lines[1] + "-" + temp_lines[2] + ".jar;"; for (int i = 0; i <= (forge_decoded["libraries"].Count) - 1; i++) { temp = forge_decoded["libraries"][i]["name"]; temp_lines = temp.Split(' ', ':'); arg += minecraft_dir + "\\libraries\\" + temp_lines[0].Replace(".", "\\") + "\\" + temp_lines[1] + "\\" + temp_lines[2] + "\\" + temp_lines[1] + "-" + temp_lines[2] + ".jar;"; } for (int i = 1; i <= (decoded["libraries"].Count) - 1; i++) { temp = decoded["libraries"][i]["name"]; try { temp_natives = decoded["libraries"][i]["natives"]["windows"]; } catch { temp_lines = temp.Split(' ', ':'); arg += minecraft_dir + "\\libraries\\" + temp_lines[0].Replace(".", "\\") + "\\" + temp_lines[1] + "\\" + temp_lines[2] + "\\" + temp_lines[1] + "-" + temp_lines[2] + ".jar;"; } } arg += minecraft_dir + "\\versions\\" + forge_decoded["jar"] + "\\" + forge_decoded["jar"] + ".jar"; arg += @" " + forge_decoded["mainClass"] + " --username " + name + " --version " + decoded["id"] + " --gameDir " + minecraft_dir + " --assetsDir " + minecraft_dir + "\\assets" + " --assetIndex " + decoded["assets"] + " --uuid " + uuid + " --accessToken " + accessToken + " --userProperties [] "; arg += @" --tweakClass " + forge_decoded["tweakClass"]; Form1.editXml(Form1.appdata + "\\skymin\\config\\launcher.xml", "Launcher", "Minecraft_Launch_Code", arg); } } else { arg = Form1.readXml(Form1.appdata + "\\skymin\\config\\launcher.xml", "Minecraft_Launch_Code"); } arg = String.Format(arg, ram); Process p = new Process(); p.StartInfo.FileName = Form1.java_patch; p.StartInfo.Arguments = arg; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.EnableRaisingEvents = true; p.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler); p.ErrorDataReceived += new DataReceivedEventHandler(SortOutputHandler); p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit(); if (Konsola.Instance != null) { Form1.WriteLine(Environment.NewLine); } if (Form1.Instance.launcher_state == 1) { Action button4 = () => Form1.Instance.button4.Enabled = true; Form1.Instance.button4.Invoke(button4); Action button3 = () => Form1.Instance.button3.Enabled = true; Form1.Instance.button3.Invoke(button3); Action button2 = () => Form1.Instance.button2.Enabled = true; Form1.Instance.button2.Invoke(button2); Action button1 = () => Form1.Instance.button1.Enabled = true; Form1.Instance.button1.Invoke(button1); } else if (Form1.Instance.launcher_state == 2) { Form1.Instance.CloseApplication(); } else if (Form1.Instance.launcher_state == 3) { Action visible = () => Form1.Instance.Visible = true; Form1.Instance.Invoke(visible); } Form1.WriteLine("Minecraft zostal wylaczony"); }
public static Plan DeserializeJsonTravelDomain(int whichOne) { //var problemFile = @"D:\Unity projects\BoltFreezer\travel_domain.travel\travel_domain.travel\1\1.json"; var problemFile = @"D:\Documents\workspace\travel_domain.travel\" + whichOne.ToString() + @"\" + whichOne.ToString() + @".json"; //var problemFile = @"D:\Unity projects\BoltFreezer\travel_domain.travel\travel_domain.travel\" + whichOne.ToString() + @"\" + whichOne.ToString() + @".json"; //problemFile var travelProblem = Parser.GetProblem(@"D:\Documents\workspace\travel_domain.travel\" + whichOne.ToString() + @"\travel-" + whichOne.ToString() + @".pddl"); var problemText = System.IO.File.ReadAllText(problemFile); var jsonArray = SimpleJson.DeserializeObject(problemText) as JsonArray; //Console.WriteLine("CHERE"); GroundActionFactory.GroundActions = new List <IOperator>(); GroundActionFactory.GroundLibrary = new Dictionary <int, IOperator>(); CacheMaps.CausalTupleMap = new TupleMap <IPredicate, List <int> >(); CacheMaps.ThreatTupleMap = new TupleMap <IPredicate, List <int> >(); Operator initialOp = new Operator(); Operator goalOp = new Operator(); // for each operator in the list foreach (JsonObject jsonObject in jsonArray) { // ID, Name, Terms, Preconditions, Effects var ID = jsonObject["ID"]; var Name = jsonObject["Name"].ToString(); var Terms = JsonTermListtoTerms(jsonObject["Terms"] as JsonArray); var Preconditions = JsonPreconditionsToPreconditions(jsonObject["Preconditions"] as JsonArray) as List <IPredicate>; var Effects = new List <IPredicate>(); var Height = int.Parse(jsonObject["height"].ToString()); if (Name.Equals("dummy_goal")) { Name = "goal"; } if (Name.Equals("dummy_init")) { Name = "initial"; Effects = travelProblem.Initial; Preconditions = new List <IPredicate>(); } var action = new Operator(Name, Terms, new Hashtable(), Preconditions, Effects, int.Parse(ID.ToString())) { Height = Height }; if (Height > 0) { var init = GroundActionFactory.GroundLibrary[int.Parse(jsonObject["DummyInitial"].ToString())]; var goal = GroundActionFactory.GroundLibrary[int.Parse(jsonObject["DummyGoal"].ToString())]; var subSteps = SubStepsFromJson(jsonObject["SubSteps"] as JsonArray); var subOrderingTuples = SubOrderingsFromJson(jsonObject["SubOrderings"] as JsonArray); // hack : find the substep in subSteps and assign ID var subLinks = CausalLinksFromJsonArray(jsonObject["SubLinks"] as JsonArray); foreach (var substep in subSteps) { foreach (var tuple in subOrderingTuples) { if (tuple.First.Action.ID == substep.Action.ID) { tuple.First.ID = substep.ID; } if (tuple.Second.Action.ID == substep.Action.ID) { tuple.Second.ID = substep.ID; } } foreach (var cl in subLinks) { if (cl.Head.Action.ID == substep.Action.ID) { cl.Head.ID = substep.ID; } if (cl.Tail.Action.ID == substep.Action.ID) { cl.Tail.ID = substep.ID; //substep.OpenConditions = cl.Tail.OpenConditions; } } } action = new Composite(action, new PlanStep(init), new PlanStep(goal), subSteps, subOrderingTuples, subLinks); } if (Name.Equals("goal")) { goalOp = action; } else if (Name.Equals("initial")) { initialOp = action; } else { GroundActionFactory.GroundActions.Add(action); GroundActionFactory.GroundLibrary[action.ID] = action; } if (jsonObject.ContainsKey("CausalMap")) { var CausalMap = jsonObject["CausalMap"] as JsonObject; foreach (var keyvalue in CausalMap) { var predKey = StringToPredicate(keyvalue.Key); if (!CacheMaps.CausalTupleMap.Get(predKey.Sign).ContainsKey(predKey)) { CacheMaps.CausalTupleMap.Get(predKey.Sign)[predKey] = IntListFromJsonArray(keyvalue.Value as JsonArray); } } } if (jsonObject.ContainsKey("ThreatMap")) { var ThreatMap = jsonObject["ThreatMap"] as JsonObject; foreach (var keyvalue in ThreatMap) { var predKey = StringToPredicate(keyvalue.Key); if (!CacheMaps.ThreatTupleMap.Get(predKey.Sign).ContainsKey(predKey)) { var intList = new List <object>(); var jsonList = keyvalue.Value as JsonArray; var enumItems = from item in jsonList select int.Parse(item.ToString()); } } } } GroundActionFactory.GroundLibrary[initialOp.ID] = null; GroundActionFactory.GroundLibrary[goalOp.ID] = null; Operator.SetCounterExternally(GroundActionFactory.GroundActions.Count + 1); var plan = new Plan(initialOp, goalOp); foreach (var goal in plan.Goal.Predicates) { plan.Flaws.Add(plan, new OpenCondition(goal, plan.GoalStep as IPlanStep)); } Console.WriteLine("Insert First Ordering"); plan.Orderings.Insert(plan.InitialStep, plan.GoalStep); return(plan); }
private async Task <MsSqlAppendResult> AppendToStreamExpectedVersion( SqlConnection connection, SqlTransaction transaction, SqlStreamId sqlStreamId, int expectedVersion, NewStreamMessage[] messages, CancellationToken cancellationToken) { var sqlDataRecords = CreateSqlDataRecords(messages); using (var command = new SqlCommand(_scripts.AppendStreamExpectedVersion, connection, transaction)) { command.Parameters.Add(new SqlParameter("streamId", SqlDbType.Char, 42) { Value = sqlStreamId.Id }); command.Parameters.AddWithValue("expectedStreamVersion", expectedVersion); var eventsParam = CreateNewMessagesSqlParameter(sqlDataRecords); command.Parameters.Add(eventsParam); try { using (var reader = await command .ExecuteReaderAsync(cancellationToken) .NotOnCapturedContext()) { await reader.ReadAsync(cancellationToken).NotOnCapturedContext(); var currentVersion = reader.GetInt32(0); var currentPosition = reader.GetInt64(1); int?maxCount = null; await reader.NextResultAsync(cancellationToken).NotOnCapturedContext(); if (await reader.ReadAsync(cancellationToken).NotOnCapturedContext()) { var jsonData = reader.GetString(0); var metadataMessage = SimpleJson.DeserializeObject <MetadataMessage>(jsonData); maxCount = metadataMessage.MaxCount; } return(new MsSqlAppendResult(maxCount, currentVersion, currentPosition)); } } catch (SqlException ex) { if (ex.Errors.Count == 1) { var sqlError = ex.Errors[0]; if (sqlError.Message == "WrongExpectedVersion") { // Idempotency handling. Check if the Messages have already been written. var page = await ReadStreamInternal( sqlStreamId, expectedVersion + 1, // when reading for already written Messages, it's from the one after the expected messages.Length, ReadDirection.Forward, false, null, connection, transaction, cancellationToken); if (messages.Length > page.Messages.Length) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, expectedVersion), ex); } // Iterate all messages an check to see if all message ids match for (int i = 0; i < Math.Min(messages.Length, page.Messages.Length); i++) { if (messages[i].MessageId != page.Messages[i].MessageId) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, expectedVersion), ex); } } return(new MsSqlAppendResult( null, page.LastStreamVersion, page.LastStreamPosition)); } } if (ex.IsUniqueConstraintViolation()) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, expectedVersion), ex); } throw; } } }
public IMessage <T> Deserialize <T>(byte[] message) { var decoded = Encoding.UTF8.GetString(message); return(SimpleJson.DeserializeObject <Message <T> >(decoded, strategy)); }
/// <summary> /// Deserialize JSON /// </summary> /// <param name="input">JSON representation</param> /// <returns>An object representing <paramref name="input"/></returns> public object DeserializeObject(string input) { return(SimpleJson.DeserializeObject(input, null, this.serializerStrategy, this.globalizationConfiguration.DateTimeStyles)); }
static Payload GetPayload(byte[] bytes) { var json = Encoding.UTF8.GetString(bytes); return(SimpleJson.DeserializeObject <Payload>(json)); }
public void ReadHexidecimalWithAllLetters() { string json = @"{""text"":0xabcdef12345}"; var o = SimpleJson.DeserializeObject(json); }
public void ParseIncompleteArray() { var o = SimpleJson.DeserializeObject("[1"); }
public void UnexpectedEndWhenParsingUnquotedProperty() { var result = SimpleJson.DeserializeObject(@"{aww"); }
public void ReadOcatalNumber() { var json = @"[0372, 0xFA, 0XFA]"; var o = SimpleJson.DeserializeObject(json); }
public void UnexpectedEndOfControlCharacter() { var result = SimpleJson.DeserializeObject(@"'h\"); }
public void UnexpectedEndOfHex() { var result = SimpleJson.DeserializeObject(@"'h\u006"); }
public void ReadNullTerminiatorString() { var result = SimpleJson.DeserializeObject("\"h\0i\""); Assert.AreEqual("h\0i", result); }
public static async Task <UpdateManager> GitHubUpdateManager( string repoUrl, string applicationName = null, string rootDirectory = null, IFileDownloader urlDownloader = null, bool prerelease = false, string accessToken = null) { var repoUri = new Uri(repoUrl); var userAgent = new ProductInfoHeaderValue("Squirrel", Assembly.GetExecutingAssembly().GetName().Version.ToString()); if (repoUri.Segments.Length != 3) { throw new Exception("Repo URL must be to the root URL of the repo e.g. https://github.com/myuser/myrepo"); } var releasesApiBuilder = new StringBuilder("repos") .Append(repoUri.AbsolutePath) .Append("/releases"); if (!string.IsNullOrWhiteSpace(accessToken)) { releasesApiBuilder.Append("?access_token=").Append(accessToken); } Uri baseAddress; if (repoUri.Host.EndsWith("github.com", StringComparison.OrdinalIgnoreCase)) { baseAddress = new Uri("https://api.github.com/"); } else { // if it's not github.com, it's probably an Enterprise server // now the problem with Enterprise is that the API doesn't come prefixed // it comes suffixed // so the API path of http://internal.github.server.local API location is // http://interal.github.server.local/api/v3. baseAddress = new Uri(string.Format("{0}{1}{2}/api/v3/", repoUri.Scheme, Uri.SchemeDelimiter, repoUri.Host)); } // above ^^ notice the end slashes for the baseAddress, explained here: http://stackoverflow.com/a/23438417/162694 using (var client = new HttpClient() { BaseAddress = baseAddress }) { client.DefaultRequestHeaders.UserAgent.Add(userAgent); var response = await client.GetAsync(releasesApiBuilder.ToString()); response.EnsureSuccessStatusCode(); var releases = SimpleJson.DeserializeObject <List <Release> >(await response.Content.ReadAsStringAsync()); var latestRelease = releases .Where(x => prerelease || !x.Prerelease) .OrderByDescending(x => x.PublishedAt) .First(); var latestReleaseUrl = latestRelease.HtmlUrl.Replace("/tag/", "/download/"); return(new UpdateManager(latestReleaseUrl, applicationName, rootDirectory, urlDownloader)); } }
public void DeserializeInvaildEscapedSurrogatePair() { string json = "\"\\uD867\\u0000 is Arabesque greenling(fish)\""; var o = SimpleJson.DeserializeObject(json); }
public void Magic() { c3poSpeakProgram.HelloMaster(); var cfgs = app.GetC3poConfigurations(); c3poSpeakProgram.StartedCreating(); foreach (var cfg in cfgs) { IEnumerable <IRestResponse> r2d2Responses = null; var enviromentResponse = gocd.CreateEnvironmentIfDoesntExists(cfg.Environment); try { if (!ReferenceEquals(null, enviromentResponse)) { c3poSpeakProgram.R2d2Responded(enviromentResponse.StatusCode, cfg.Environment, cfg.GetApplication(), SimpleJson.DeserializeObject <dynamic>(enviromentResponse.Content).Message); } if (cfg.GetC3poType().Equals(MonoRepo, System.StringComparison.OrdinalIgnoreCase)) { c3poSpeakProgram.CreatingMonoRepoPipeline(cfg.GetApplication(), cfg.GetPipelineName()); r2d2Responses = gocd.CreateBuildMonoRepoPipeline(cfg); } else if (cfg.GetC3poType().Equals(Repo, System.StringComparison.OrdinalIgnoreCase)) { c3poSpeakProgram.CreatingRepoPipeline(cfg.GetApplication(), cfg.GetPipelineName()); r2d2Responses = gocd.CreateBuildPipelines(cfg).ToList(); } else if (cfg.GetC3poType().Equals(Deploy, System.StringComparison.OrdinalIgnoreCase)) { c3poSpeakProgram.CreatingDeployPipeline(cfg.GetApplication(), cfg.GetPipelineName()); r2d2Responses = gocd.CreateDeployPipeline(cfg); } if (ReferenceEquals(null, r2d2Responses) == false) { foreach (var r2d2Response in r2d2Responses) { c3poSpeakProgram.R2d2Responded(r2d2Response.StatusCode, cfg.GetPipelineName(), cfg.GetApplication(), SimpleJson.DeserializeObject <dynamic>(r2d2Response.Content).message); } } } catch (Exception ex) { c3poSpeakProgram.ThereIsError(ex.Message); } } }
public void UnexpectedEndOfString() { var result = SimpleJson.DeserializeObject("hi"); }
private BeginData ParseBeginMessage(JsonObject jsonObject) { return(SimpleJson.DeserializeObject <BeginData> (jsonObject.ToString())); }
private static SessionSummary getSessionSummayData() { if (SoftwareCoUtil.SessionSummaryFileExists()) { string sessionSummary = SoftwareCoUtil.getSessionSummaryFileData(); if (!string.IsNullOrEmpty(sessionSummary)) { IDictionary <string, object> jsonObj = (IDictionary <string, object>)SimpleJson.DeserializeObject(sessionSummary); _sessionSummary = DictionaryToObject <SessionSummary>(jsonObj); } else { return(_sessionSummary); } } return(_sessionSummary); }
private async Task <MsSqlAppendResult> AppendToStreamExpectedVersionNoStream( SqlConnection connection, SqlTransaction transaction, SqlStreamId sqlStreamId, NewStreamMessage[] messages, CancellationToken cancellationToken) { using (var command = new SqlCommand(_scripts.AppendStreamExpectedVersionNoStream, connection, transaction)) { command.Parameters.Add(new SqlParameter("streamId", SqlDbType.Char, 42) { Value = sqlStreamId.Id }); command.Parameters.AddWithValue("streamIdOriginal", sqlStreamId.IdOriginal); if (messages.Length != 0) { var sqlDataRecords = CreateSqlDataRecords(messages); var eventsParam = CreateNewMessagesSqlParameter(sqlDataRecords); command.Parameters.Add(eventsParam); command.Parameters.AddWithValue("hasMessages", true); } else { // Must use a null value for the table-valued param if there are no records var eventsParam = CreateNewMessagesSqlParameter(null); command.Parameters.Add(eventsParam); command.Parameters.AddWithValue("hasMessages", false); } try { using (var reader = await command .ExecuteReaderAsync(cancellationToken) .NotOnCapturedContext()) { await reader.ReadAsync(cancellationToken).NotOnCapturedContext(); var currentVersion = reader.GetInt32(0); var currentPosition = reader.GetInt64(1); int?maxCount = null; await reader.NextResultAsync(cancellationToken).NotOnCapturedContext(); if (await reader.ReadAsync(cancellationToken).NotOnCapturedContext()) { var jsonData = reader.GetString(0); var metadataMessage = SimpleJson.DeserializeObject <MetadataMessage>(jsonData); maxCount = metadataMessage.MaxCount; } return(new MsSqlAppendResult(maxCount, currentVersion, currentPosition)); } } catch (SqlException ex) { // Check for unique constraint violation on // https://technet.microsoft.com/en-us/library/aa258747%28v=sql.80%29.aspx if (ex.IsUniqueConstraintViolationOnIndex("IX_Streams_Id")) { // Idempotency handling. Check if the Messages have already been written. var page = await ReadStreamInternal( sqlStreamId, StreamVersion.Start, messages.Length, ReadDirection.Forward, false, null, connection, transaction, cancellationToken) .NotOnCapturedContext(); if (messages.Length > page.Messages.Length) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, ExpectedVersion.NoStream), ex); } for (int i = 0; i < Math.Min(messages.Length, page.Messages.Length); i++) { if (messages[i].MessageId != page.Messages[i].MessageId) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, ExpectedVersion.NoStream), ex); } } return(new MsSqlAppendResult( null, page.LastStreamVersion, page.LastStreamPosition)); } if (ex.IsUniqueConstraintViolation()) { throw new WrongExpectedVersionException( ErrorMessages.AppendFailedWrongExpectedVersion(sqlStreamId.IdOriginal, ExpectedVersion.NoStream), ex); } throw; } } }
private static async Task <SessionSummaryResult> GetSessionSummaryStatusAsync(bool forceRefresh = false) { SessionSummaryResult sessionSummaryResult = new SessionSummaryResult(); _sessionSummary = getSessionSummayData(); //if (SoftwareCoUtil.SessionSummaryFileExists()) //{ if (_sessionSummary.currentDayMinutes == 0 || forceRefresh) { bool online = await SoftwareUserSession.IsOnlineAsync(); if (!online) { sessionSummaryResult.sessionSummary = _sessionSummary; sessionSummaryResult.status = "OK"; updateStatusBarWithSummaryData(); return(sessionSummaryResult); } HttpResponseMessage response = await SoftwareHttpManager.SendRequestAsync(HttpMethod.Get, "/sessions/summary", null); if (SoftwareHttpManager.IsOk(response)) { string responseBody = await response.Content.ReadAsStringAsync(); IDictionary <string, object> jsonObj = (IDictionary <string, object>)SimpleJson.DeserializeObject(responseBody); _sessionSummary = DictionaryToObject <SessionSummary>(jsonObj); saveSessionSummaryToDisk(_sessionSummary); updateStatusBarWithSummaryData(); sessionSummaryResult.sessionSummary = _sessionSummary; sessionSummaryResult.status = "OK"; } } else { updateStatusBarWithSummaryData(); } //} //else //{ // updateStatusBarWithSummaryData(); //} sessionSummaryResult.sessionSummary = _sessionSummary; sessionSummaryResult.status = "OK"; return(sessionSummaryResult); }
public void volibotBehaviour(JsonObject payload) { var uri = (string)payload["uri"]; //Console.WriteLine(uri); var data = (JsonObject)payload["data"]; var eventType = (string)payload["eventType"]; var status = eventType.Equals("Create") || eventType.Equals("Update") ? 200 : 404; var message = "[1, \"" + uri + "\", " + status + ", " + SimpleJson.SerializeObject(data) + "]"; /** TODO: we definitly need a better way... **/ if (eventType == "Delete") { return; } switch (uri) { /** honor popped up. **/ case "/lol-honor-v2/v1/ballot": //Console.WriteLine(payload); if (data == null) { return; } var eligiblePlayers = (JsonArray)data["eligiblePlayers"]; int index = new Random().Next(eligiblePlayers.Count); var randomPlayer = (JsonObject)eligiblePlayers[index]; /** we honor a random player. lucky bastard ( ͡° ͜ʖ ͡°) **/ long gameId = Convert.ToInt64(data["gameId"]); string honorCategory = "HEART"; long summonerId = Convert.ToInt64(randomPlayer["summonerId"]); updateStatus("We are honoring: " + randomPlayer["skinName"]); leagueSocket.makeRequest("/lol-honor-v2/v1/honor-player", "POST", "{ \"gameId\": " + gameId + ", \"honorCategory\": \"" + honorCategory + "\", \"summonerId\": " + summonerId + "}"); updateStatus("Game ended. Creating again an ARAM Lobby."); leagueSocket.makeRequest("/lol-lobby/v2/lobby/", "POST", "{\"customGameLobby\":{\"configuration\":{\"gameMode\":\"ARAM\",\"gameMutator\":\"\",\"gameServerRegion\":\"EUW\",\"gameTypeConfig\":{},\"mapId\":12,\"maxPlayerCount\":5,\"mutators\":{},\"spectatorPolicy\":\"NotAllowed\",\"teamSize\":5,\"tournamentGameMode\":\"string\",\"tournamentPassbackDataPacket\":\"string\",\"tournamentPassbackUrl\":\"string\"},\"gameId\":11,\"lobbyName\":\"\",\"lobbyPassword\":\"\",\"spectators\":[],\"teamOne\":[],\"teamTwo\":[]},\"isCustom\":false,\"queueId\":65}"); break; case "/lol-champ-select-legacy/v1/session": inQueue = false; if (!inChampSelect) { updateStatus("In Champion Selection."); inChampSelect = true; } break; case "/lol-matchmaking/v1/search": if (!inQueue) { inQueue = true; inChampSelect = false; updateStatus("In Queue (Estimated Queue Time: " + Math.Round((double)data["estimatedQueueTime"], 0) + "s)"); } break; case "/data-store/v1/install-settings/gameflow-process-info": inChampSelect = false; updateStatus("Starting League of Legends..."); break; /** auto accept any incoming ready-check **/ case "/lol-matchmaking/v1/ready-check": leagueSocket.makeRequest("/lol-matchmaking/v1/ready-check/accept", "POST"); break; /** observe login request state **/ case "/lol-login/v1/session": if (data == null) { return; } RiotAPI.lol_login.v1.Session session = SimpleJson.DeserializeObject <RiotAPI.lol_login.v1.Session>(data.ToString()); switch (session.state) { case "SUCCEEDED": updateStatus("Successfully logged in. Waiting for full initialisation."); break; case "LOGGING_OUT": updateStatus("Logging out"); leagueSocket.Destroy(); break; case "ERROR": updateStatus("Credentials are wrong, or another error occured."); break; case "IN_PROGRESS": if (session.queueStatus != null) { updateStatus("In Login Queue Position: " + session.queueStatus.estimatedPositionInQueue + " (" + session.queueStatus.approximateWaitTimeSeconds + ")"); } break; default: updateStatus("Unknown Login Status: " + data["state"]); break; } curSession = session; break; /** Trying to join the matchmaking queue with the current party. **/ case "/lol-lobby/v2/lobby": /** can we start? **/ if (data == null) { return; } if ((bool)data["canStartActivity"] == true) { canQueue = false; updateStatus("Can start activity, starting queue."); leagueSocket.makeRequest("/lol-matchmaking/v1/search", "POST"); } else { updateStatus("Failed to initialize lobby: " + (string)data["state"]); } break; /** Waiting for full initialization. This incoming is unique when logged in. **/ case "/lol-gameflow/v1/availability": if ((bool)data["isAvailable"] && canQueue) { updateStatus("Creating now an ARAM Lobby."); leagueSocket.makeRequest("/lol-lobby/v2/lobby/", "POST", "{\"customGameLobby\":{\"configuration\":{\"gameMode\":\"ARAM\",\"gameMutator\":\"\",\"gameServerRegion\":\"EUW\",\"gameTypeConfig\":{},\"mapId\":12,\"maxPlayerCount\":5,\"mutators\":{},\"spectatorPolicy\":\"NotAllowed\",\"teamSize\":5,\"tournamentGameMode\":\"string\",\"tournamentPassbackDataPacket\":\"string\",\"tournamentPassbackUrl\":\"string\"},\"gameId\":11,\"lobbyName\":\"\",\"lobbyPassword\":\"\",\"spectators\":[],\"teamOne\":[],\"teamTwo\":[]},\"isCustom\":false,\"queueId\":65}"); } break; /** send a login request when recieving basic info **/ case "/riotclient/system-info/v1/basic-info": leagueSocket.makeRequest("/lol-login/v1/session", "POST", "{\"password\": \"" + Password + "\", \"username\": \"" + Username + "\"}"); break; } }
public static SamplingSetting ParseSamplingSettings(string settingsText, string identifier) { var settings = SimpleJson.DeserializeObject(settingsText) as JsonObject; if (settings == null) { System.Diagnostics.Debug.WriteLine("Invalid Json was provided: " + settingsText); return(null); } if (String.IsNullOrEmpty(identifier)) { System.Diagnostics.Debug.WriteLine($"A site name must be provided for {nameof(identifier)}"); return(null); } if (settings.ContainsKey(ROOT_CONFIGURATION_PROPERTY_NAME) == false) { System.Diagnostics.Debug.WriteLine($"Expected property \"{ROOT_CONFIGURATION_PROPERTY_NAME}\" in the JSON values: {settingsText}"); return(null); } var siteSettings = settings[ROOT_CONFIGURATION_PROPERTY_NAME] as JsonArray; foreach (JsonObject siteSetting in siteSettings) { var expectedKeys = new[] { IDENTIFIER_PROPERTY_NAME, SAMPLING_METHOD_PROPERTY_NAME, SAMPLING_CONFIG_PROPERTY_NAME, SAMPLING_OVERRIDES_PROPERTY_NAME }; var containsAllKeys = true; foreach (var expectedKey in expectedKeys) { containsAllKeys = siteSetting.ContainsKey(expectedKey); if (!containsAllKeys) { System.Diagnostics.Debug.WriteLine($"Expected property {expectedKey} in the JSON values: {settingsText}"); break; } } if (!containsAllKeys || (string)siteSetting[IDENTIFIER_PROPERTY_NAME] != identifier) { continue; } var samplingMethod = (DataSamplingMethod)(long)siteSetting[SAMPLING_METHOD_PROPERTY_NAME]; var policy = new SamplingPolicy(samplingMethod, (string)siteSetting[SAMPLING_CONFIG_PROPERTY_NAME]); var overrides = new List <UrlSamplingOverride>(); var overrideJsonArray = (JsonArray)siteSetting[SAMPLING_OVERRIDES_PROPERTY_NAME]; if (overrideJsonArray == null || overrideJsonArray.Count == 0) { return(new SamplingSetting(policy, overrides)); } foreach (JsonObject overrideSetting in overrideJsonArray) { var overrideType = (int)Convert.ChangeType(overrideSetting[OVERRIDE_TYPE_PROPERTY_NAME], typeof(int)); // Type 0: URL overrides if (overrideType == 0) { var overrideConfigurationData = (string)overrideSetting[OVERRIDE_DATA_PROPERTY_NAME]; var overrideSettingConfiguration = SimpleJson.DeserializeObject(overrideConfigurationData) as JsonObject; if (overrideSettingConfiguration != null) { if (overrideSettingConfiguration.ContainsKey(OVERRIDE_URL_PROPERTY_NAME) == false || overrideSettingConfiguration.ContainsKey(OVERRIDE_SAMPLE_OPTION_PROPERTY_NAME) == false) { System.Diagnostics.Debug.WriteLine($"Expected properties \"{OVERRIDE_URL_PROPERTY_NAME}\" and \"{OVERRIDE_SAMPLE_OPTION_PROPERTY_NAME}\" in the JSON values: {overrideSettingConfiguration}"); continue; } var overrideUrl = (string)overrideSettingConfiguration[OVERRIDE_URL_PROPERTY_NAME]; var overridePolicyTypeRaw = (string)overrideSettingConfiguration[OVERRIDE_SAMPLE_OPTION_PROPERTY_NAME]; var overridePolicyType = (SamplingOption)Enum.Parse(typeof(SamplingOption), overridePolicyTypeRaw); var dataSamplingMethod = overridePolicyType == SamplingOption.Traces ? DataSamplingMethod.Simple : DataSamplingMethod.Thumbprint; var overridePolicy = new SamplingPolicy(dataSamplingMethod, overrideConfigurationData); var samplingOverride = new UrlSamplingOverride(overrideUrl, overridePolicy); overrides.Add(samplingOverride); } } } return(new SamplingSetting(policy, overrides)); } return(null); }
public T Deserialize <T>(string json) { return(SimpleJson.DeserializeObject <T>(json, _serializationStrategy)); }
/// <summary> /// TODO: Extend an SSO token daily. This should be an internal method /// </summary> /// <returns></returns> public async static Task CheckAndExtendTokenIfNeeded() { // get the existing token if (String.IsNullOrEmpty(ActiveSession.CurrentAccessTokenData.AccessToken)) { // If there is no token, do nothing return; } // check if its issue date is over 24 hours and if so, renew it if (DateTime.UtcNow - ActiveSession.CurrentAccessTokenData.Issued > TimeSpan.FromHours(24)) // one day { var client = new HttpClient(); String tokenExtendUri = "https://graph.facebook.com/v2.1"; client.BaseAddress = new Uri(tokenExtendUri); var request = new HttpRequestMessage(); var mfdc = new MultipartFormDataContent(); var _appId = Session.AppId; mfdc.Add(new StringContent(_appId), name: "batch_app_id"); String extensionString = "[{\"method\":\"GET\",\"relative_url\":\"oauth\\/access_token?grant_type=fb_extend_sso_token&access_token=" + ActiveSession.CurrentAccessTokenData.AccessToken + "\"}]"; mfdc.Add(new StringContent(extensionString), name: "batch"); HttpResponseMessage response = await client.PostAsync(tokenExtendUri, mfdc); String resultContent = await response.Content.ReadAsStringAsync(); var result = SimpleJson.DeserializeObject(resultContent); // extract the access token and save it in the session var data = (List <object>)result; var dictionary = (IDictionary <string, object>)data[0]; var code = (long)dictionary["code"]; if (code == 200) { // the API succeeded var body = (IDictionary <string, object>)SimpleJson.DeserializeObject((string)dictionary["body"]); var access_token = (string)body["access_token"]; var expires_at = (long)body["expires_at"]; var accessTokenData = new AccessTokenData(); // token extension failed... accessTokenData.AccessToken = access_token; // parse out other types long expiresInValue; var now = DateTime.UtcNow; accessTokenData.Expires = now + TimeSpan.FromSeconds(expires_at); accessTokenData.Issued = now - (TimeSpan.FromDays(60) - TimeSpan.FromSeconds(expires_at)); accessTokenData.AppId = _appId; // Assign the accessTokenData object over, this saves it to the disk as well. ActiveSession.CurrentAccessTokenData = accessTokenData; } else { // return an error?? Since this is token extension, maybe we should wait until the token is finally expired before throwing an error. } } }
public async Task <TSagaData> Read <TSagaData>() where TSagaData : class, IContainSagaData { var json = await streamReader.ReadToEndAsync().ConfigureAwait(false); return(SimpleJson.DeserializeObject <TSagaData>(json, EnumAwareStrategy.Instance)); }
public IEnumerable <OnlineIssue> GetClosedIssues(GitReleaseNotesArguments arguments, DateTimeOffset?since) { string jql; if (since.HasValue) { var sinceFormatted = since.Value.ToString("yyyy-MM-d HH:mm"); jql = string.Format("{0} AND updated > '{1}'", arguments.Jql, sinceFormatted).Replace("\"", "\\\""); } else { jql = arguments.Jql; } var baseUrl = new Uri(arguments.JiraServer, UriKind.Absolute); var searchUri = new Uri(baseUrl, "/rest/api/latest/search"); var httpRequest = WebRequest.CreateHttp(searchUri); var usernameAndPass = string.Format("{0}:{1}", arguments.Username, arguments.Password); var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(usernameAndPass)); httpRequest.Headers.Add("Authorization", string.Format("Basic {0}", token)); httpRequest.Method = "POST"; httpRequest.ContentType = "application/json"; using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream())) { string json = "{\"jql\": \"" + jql + "\",\"startAt\": 0, \"maxResults\": 100, \"fields\": [\"summary\",\"issuetype\"]}"; streamWriter.Write(json); streamWriter.Flush(); streamWriter.Close(); } var response = (HttpWebResponse)httpRequest.GetResponse(); if ((int)response.StatusCode == 400) { throw new Exception("Jql query error, please review your Jql"); } if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("Failed to query Jira: " + response.StatusDescription); } using (var responseStream = response.GetResponseStream()) using (var responseReader = new StreamReader(responseStream)) { dynamic responseObject = SimpleJson.DeserializeObject(responseReader.ReadToEnd()); foreach (var issue in responseObject.issues) { string summary = issue.fields.summary; string id = issue.key; string issueType = issue.fields.issuetype.name; yield return(new OnlineIssue { Id = id, Title = summary, IssueType = IssueType.Issue, HtmlUrl = new Uri(baseUrl, string.Format("browse/{0}", id)) }); } } }
static void Main(string[] args) { int index; string content; Boolean exists; exists = File.Exists(@"C:\Users\cft60\Downloads\data.txt"); if (exists) { content = File.ReadAllText(@"C:\Users\cft60\Downloads\data.txt"); } else { var client = new RestClient("https://rickandmortyapi.com/api/character/?page=1"); var request = new RestRequest(Method.GET); IRestResponse response = client.Execute(request); content = response.Content; } RootObject res = SimpleJson.DeserializeObject <RootObject>(content); int userInput = 0; do { userInput = DisplayMenu(); switch (userInput) { case 1: AddCharacter(res); break; //method to add character, prompts questions one at a time case 2: int counter = 0; Console.Clear(); Console.WriteLine("Here are all the characters\n"); foreach (var item in res.results) { Console.WriteLine("The characters name is {0} with an ID of {1}", item.name, counter); counter++; } Console.WriteLine("\nPress Enter to continue back to the menu"); Console.ReadLine(); //method to display list of all characters with there ID # break; case 3: Console.Clear(); Console.WriteLine("Please enter a character ID between 0 and {0}", res.results.Count - 1); index = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(res.results[index].name); Console.WriteLine(res.results[index].status); Console.WriteLine(res.results[index].species); Console.WriteLine(res.results[index].gender); Console.WriteLine("\nPress Enter to continue back to the menu"); Console.ReadLine(); //call method to display chosen character by ID and any information on them. break; case 4: Console.WriteLine("Which ID would you like to delete?"); Console.WriteLine("Please enter a character ID between 0 and {0}", res.results.Count - 1); index = Convert.ToInt32(Console.ReadLine()); res.results.RemoveAt(index); //call method for to enter ID# and delete it from list break; } }while (userInput != 5); //saves any changes inputed through method and updates file. string data = SimpleJson.SerializeObject(res); System.IO.File.WriteAllText(@"C:\Users\cft60\Downloads\data.txt", data); }
public T Deserialize <T>(byte[] bytes) where T : class { return(SimpleJson.DeserializeObject <T>(bytes.Utf8String())); }