private void abbreviationsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dict = new Dictionary <string, string>();
            var ser  = new JsonSerializer <Dictionary <string, string> >();

            if (File.Exists("abbreviations.dict"))
            {
                try
                {
                    using (var streamReader = File.OpenText("abbreviations.dict"))
                    {
                        dict = ser.DeserializeFromReader(streamReader);
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                }
            }

            var abbreviationsDictForm
                = new SimpleReflectionForm <Dictionary <string, string> >(dict ?? new Dictionary <string, string>(), true, "Abbreviations");
            var dialogResult = abbreviationsDictForm.ShowDialog(this);

            if (dialogResult != DialogResult.OK)
            {
                return;
            }
            dict = abbreviationsDictForm.Obj;
            using (var streamWriter = new StreamWriter("abbreviations.dict"))
            {
                ser.SerializeToWriter(dict, streamWriter);
            }
        }
Example #2
0
        private MultiboxProcess FetchProcessMultiboxInfo(Process process)
        {
            List <Signature> sigList = new List <Signature>();
            string           file    = Path.Combine(Program.appBase, "signatures.json");

            using (var streamReader = new StreamReader(file)) {
                sigList = JsonSerializer.DeserializeFromReader <List <Signature> >(streamReader);
            }

            // Initialize process scanner
            FFMemoryParser.Memory memory = new FFMemoryParser.Memory(process);
            // Get memory addresses
            memory.SearchMemory(sigList);
            // Fetch memory data
            memory.MemoryLoop();

            if (memory.actorsData.currentActors.Count > 0)
            {
                ActorData localPlayer = memory.actorsData.currentActors.First().Value;
                return(new MultiboxProcess {
                    characterId = memory.charIdData.id,
                    characterName = localPlayer.name
                });
            }
            return(new MultiboxProcess());
        }
Example #3
0
        // Merges the comments returned from multiple HTTP requests and returns the last 50.
        private List <GitHubComment> GetComments(ListParameters p, Task <HttpWebResponse>[] tasks)
        {
            // concatenate all the response URIs and ETags; we will use this to build our own ETag
            var responseETags = new List <string>();

            // download comments as JSON and deserialize them
            List <GitHubComment> comments = new List <GitHubComment>();

            foreach (Task <HttpWebResponse> task in tasks)
            {
                using (HttpWebResponse response = task.Result)
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new ApplicationException("GitHub server returned " + response.StatusCode);
                    }

                    // if the response has an ETag, add it to the list of all ETags
                    string eTag = response.Headers[HttpResponseHeader.ETag];
                    if (!string.IsNullOrEmpty(eTag))
                    {
                        responseETags.Add(response.ResponseUri.AbsoluteUri + ":" + eTag);
                    }

                    // TODO: Use asynchronous reads on this asynchronous stream
                    // TODO: Read encoding from Content-Type header; don't assume UTF-8
                    using (Stream stream = response.GetResponseStream())
                        using (TextReader reader = new StreamReader(stream, Encoding.UTF8))
                            comments.AddRange(JsonSerializer.DeserializeFromReader <List <GitHubComment> >(reader));
                }
            }

            // if each response had an ETag, build our own ETag from that data
            if (responseETags.Count == tasks.Length)
            {
                // concatenate all the ETag data
                string eTagData = p.Version + "\n" + responseETags.Join("\n");

                // hash it
                byte[] md5;
                using (MD5 hash = MD5.Create())
                    md5 = hash.ComputeHash(Encoding.UTF8.GetBytes(eTagData));

                // the ETag is the quoted MD5 hash
                string responseETag = "\"" + string.Join("", md5.Select(by => by.ToString("x2", CultureInfo.InvariantCulture))) + "\"";
                Response.AppendHeader("ETag", responseETag);

                if (m_requestETag == responseETag)
                {
                    SetResult(new HttpStatusCodeResult((int)HttpStatusCode.NotModified));
                    return(null);
                }
            }

            return(comments
                   .OrderByDescending(c => c.created_at)
                   .Take(50)
                   .ToList());
        }
        static void Main(string[] args)
        {
            // Parse args
            Parser.Default.ParseArguments <Options>(args).WithParsed <Options>(options => { programOptions = options; });


            if (GetConsoleWindow() != IntPtr.Zero)
            {
                Console.OutputEncoding = System.Text.Encoding.UTF8;
            }

            List <Process> processes    = new List <Process>(Process.GetProcessesByName("ffxiv_dx11"));
            Process        ffxivProcess = null;

            if (processes.Count > 0)
            {
                ffxivProcess = processes[0];
                foreach (Process proc in processes)
                {
                    if (proc.Id == programOptions.HookPid)
                    {
                        ffxivProcess = proc;
                        break;
                    }
                }
            }
            if (ffxivProcess != null)
            {
                PipeMemory       mem     = new PipeMemory(ffxivProcess);
                List <Signature> sigList = new List <Signature>();

                string file = programOptions.LoadSignatureFile;
                if (string.IsNullOrEmpty(file))
                {
                    file = "signatures.json";
                }
                using (var streamReader = new StreamReader(file)) {
                    sigList = JsonSerializer.DeserializeFromReader <List <Signature> >(streamReader);
                }

                mem.SearchMemory(sigList);

                int MemoryDelay = programOptions.PollingRate;
                Console.WriteLine(string.Format("-- Start thread ({0})", MemoryDelay));
                do
                {
                    while (true)
                    {
                        while (!Console.KeyAvailable)
                        {
                            mem.MemoryLoop();
                            Thread.Sleep(MemoryDelay);
                        }
                    }
                } while (Console.ReadKey(true).Key != ConsoleKey.NoName);
            }
        }
Example #5
0
        public ContentResult Report()
        {
            var s = new JsonSerializer<List<ConnectionStringConfig>>();

            var x = s.DeserializeFromReader(new StreamReader(HttpContext.Server.MapPath("../json") +  "\\" + "ConnectionStrings.json"));
            var reportConfig = new SqlReportConfig { ReportTemplateRoot = HttpContext.Server.MapPath("../sql") + "\\", ReportName = "employeeList", ConnectionString = "Data Source=CORPSPLRPTDB1;Initial Catalog=ApplicationLog;Persist Security Info=True;Trusted_Connection=True;" };
            var jsonHtmlTableGenerator = new JsonHtmlTableGenerator(reportConfig);
            var jsonHtmlTable = jsonHtmlTableGenerator.GetJsonTable(JsonHtmlTableType.DataTables);

            return new ContentResult { Content = jsonHtmlTable, ContentType = "application/json" };
        }
Example #6
0
        private Task <List <GitHubComment> > GetCommits(ListParameters p, List <GitHubComment> comments)
        {
            List <Task> tasks = new List <Task>();

            if (p.Version == 2)
            {
                object lockObject = new object();
                m_commits = new Dictionary <string, GitHubCommit>();

                foreach (var commitId in comments.Select(c => c.commit_id).Distinct())
                {
                    // look up commit in cache
                    var commit = (GitHubCommit)HttpContext.Cache.Get("commit:" + commitId);

                    if (commit != null)
                    {
                        // if found, store it locally (in case it gets evicted from cache)
                        lock (lockObject)
                            m_commits.Add(commitId, commit);
                    }
                    else
                    {
                        // if not found, request it
                        string baseUri     = p.Server == "api.github.com" ? @"https://{0}/repos/" : @"http://{0}/api/v3/repos/";
                        string uriTemplate = baseUri + @"{1}/{2}/commits/{3}";
                        Uri    uri         = new Uri(string.Format(CultureInfo.InvariantCulture, uriTemplate, Uri.EscapeDataString(p.Server),
                                                                   Uri.EscapeDataString(p.User), Uri.EscapeDataString(p.Repo), Uri.EscapeDataString(commitId)));

                        var request = GitHubApi.CreateRequest(uri, p.UserName, p.Password);
                        tasks.Add(request.GetHttpResponseAsync().ContinueWith(t =>
                        {
                            // parse the commit JSON
                            GitHubCommit downloadedCommit;
                            using (HttpWebResponse response = t.Result)
                                using (Stream stream = response.GetResponseStream())
                                    using (TextReader reader = new StreamReader(stream, Encoding.UTF8))
                                        downloadedCommit = JsonSerializer.DeserializeFromReader <GitHubCommit>(reader);

                            // store in cache
                            string downloadedCommitId = downloadedCommit.sha;
                            HttpContext.Cache.Insert("commit:" + downloadedCommitId, downloadedCommit);

                            // also store it locally (in case it gets evicted from cache)
                            lock (lockObject)
                                m_commits.Add(downloadedCommitId, downloadedCommit);
                        }));
                    }
                }
            }

            return(TaskUtility.ContinueWhenAll(tasks.ToArray(), t => comments));
        }
Example #7
0
        List <MessageDtoModelV1> DeserializeChunk(TextReader reader)
        {
            DateTime start, stop;

            start = DateTime.UtcNow;
            var chunk = JsonSerializer.DeserializeFromReader <List <MessageDtoModelV1> >(reader);

            stop = DateTime.UtcNow;
#if LOG4NET && MSGBUF_DEBUG
            f_Logger.DebugFormat("DeserializeChunk(): {0} items took: {1:0.00} ms",
                                 chunk.Count,
                                 (stop - start).TotalMilliseconds);
#endif
            return(chunk);
        }
Example #8
0
        public List <Element> GetAllFromFile(string source)
        {
            List <Element> result = null;

            if (!File.Exists(source))
            {
                return(result);
            }

            using (TextReader reader = new StreamReader(source))
            {
                result = JsonSerializer.DeserializeFromReader <List <Element> >(reader);
            }


            return(result);
        }
        public Task <InputFormatterResult> ReadAsync(InputFormatterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var request = context.HttpContext.Request;
            var reader  = context.ReaderFactory(request.Body, Encoding.UTF8);
            var scope   = JsConfig.BeginScope();

            scope.DateHandler = DateHandler.ISO8601;
            var result = JsonSerializer.DeserializeFromReader(reader, context.ModelType);

            scope.Dispose();
            reader.Dispose();
            return(InputFormatterResult.SuccessAsync(result));
        }
Example #10
0
 private static GeneratorOptions LoadProject(string fileName)
 {
     if (File.Exists(fileName))
     {
         using (var fileStream = File.OpenRead(fileName))
         {
             using (var streamReader = new StreamReader(fileStream))
             {
                 var ser     = new JsonSerializer <GeneratorOptions>();
                 var options = ser.DeserializeFromReader(streamReader);
                 Settings.Default.OutputDirectory = options.OutputDirectory;
                 Settings.Default.ProjectFile     = options.ProjectFile;
                 return(options);
             }
         }
     }
     return(null);
 }
        public Configuration GetConfiguration()
        {
            var dir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;

            if (dir == null)
            {
                throw new Exception("Could not access application directory.");
            }
            var           curFolder      = dir.FullName;
            var           configJsonFile = Path.Combine(curFolder, "config-live.json");
            Configuration config;

            if (!File.Exists(configJsonFile))
            {
                throw new ConfigurationErrorsException(
                          "Missing config-live.json file. You must have at least one of the config files.");
            }
            try
            {
                using (var stream = new StreamReader(configJsonFile))
                {
                    config = JsonSerializer.DeserializeFromReader <Configuration>(stream);
                }
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException(ex.Message);
            }

            if (config != null)
            {
                config.LocalStoragePath = Path.Combine(curFolder, "localstore.json");
            }

            ValidateConfiguration(config);

            return(config);
        }
Example #12
0
        public void UpdateApp(Object sender, EventArgs args)
        {
            currentVersion = UpdateVersion.Version;

            Uri updateJson = new Uri(Program.urlBase + string.Format("update?v2={0}", UpdateVersion.Version.ToString()));

            Console.WriteLine("Updatejson: " + updateJson.ToString());
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(updateJson);

            IAsyncResult res = request.BeginGetResponse(null, null);

            while (!res.IsCompleted)
            {
                if (worker.CancellationPending)
                {
                    return;
                }
            }
            HttpWebResponse response = request.EndGetResponse(res) as HttpWebResponse;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
                    version = JsonSerializer.DeserializeFromReader <UpdateVersion>(reader);
                }
                if (version == null)
                {
                    return;
                }

                this.DialogResult = (version.updateVersion > UpdateVersion.Version) ? DialogResult.Yes : DialogResult.No;
                if (UpdateVersion.Version > version.updateVersion)
                {
                    this.DialogResult = DialogResult.Ignore;
                }
            }
        }
        public void UpdateApp(Object sender, DoWorkEventArgs args)
        {
            Uri            url     = (args.Argument as Uri);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            IAsyncResult res = request.BeginGetResponse(null, null);

            while (!res.IsCompleted)
            {
                if (worker.CancellationPending)
                {
                    return;
                }
            }
            HttpWebResponse response = request.EndGetResponse(res) as HttpWebResponse;

            args.Result = new DonatorResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
                    args.Result = JsonSerializer.DeserializeFromReader <DonatorResponse>(reader);
                }
            }
        }
Example #14
0
        public void Does_escape_string_when_serializing_to_TextWriter()
        {
            var expected = @"String with backslashes '\', 'single' and ""double quotes"", (along		with	other	special	symbols	like	tabs) wich may broke incorrect serializing/deserializing implementation ;)";

            var json = "\"String with backslashes '\\\\', 'single' and \\\"double quotes\\\", (along\\t\\twith\\tother\\tspecial\\tsymbols\\tlike\\ttabs) wich may broke incorrect serializing/deserializing implementation ;)\"";

            using (var ms = new MemoryStream())
            {
                var sw = new StreamWriter(ms);
                JsonSerializer.SerializeToWriter(expected, sw);
                sw.Flush();

                using (var sr = new StreamReader(ms))
                {
                    ms.Position = 0;
                    var ssJson = sr.ReadToEnd();
                    Assert.That(ssJson, Is.EqualTo(json));

                    ms.Position = 0;
                    var ssString = JsonSerializer.DeserializeFromReader(sr, typeof(string));
                    Assert.That(ssString, Is.EqualTo(expected));
                }
            }
        }
Example #15
0
        private Task<MusicModel> LoadModelAsync()
        {
            var t1 = new Task<MusicModel>(() =>
            {
                Busy = true;
                MusicModel musicModel;
                if (File.Exists(StorageFileLocation))
                {
                    using (var reader = new StreamReader(StorageFileLocation))
                    {
                        var serializer = new JsonSerializer<MusicModel>();
                        musicModel = serializer.DeserializeFromReader(reader);
                    }
                }
                else
                {
                    musicModel = new MusicModel(MusicLocation, MusicDestination);
                }

                return musicModel;
            });

            t1.Start();
            return t1;
        }
Example #16
0
        public async Task AssociateDiskAsync(DiskViewModel diskView)
        {
            DiskRecord resp;
            try
            {
                resp = await _serviceClient.GetAsync(new GetDiskInfo { DiskName = diskView.Name });
            }
            catch (WebServiceException e)
            {
                if (e.StatusCode == 404)
                {
                    resp = null;
                }
                else
                {
                    throw;
                }
            }

            var capacity = diskView.Disk.Capacity;
            diskView.SynchronizingDisk.ServerAssociation = diskView.Name;
            var oldNotificationDispatcher = diskView.Disk.NotificationDispatcher;

            if (resp == null)
            {
                // need to upload the disk first
                StatusText = String.Format("Disk {0} is being uploaded to the server. Please wait...", diskView.Name);
                try
                {
                    diskView.SynchronizingDisk.NotifySynchronized();
                    diskView.Disk.Dispose();
                    // ReSharper disable AssignNullToNotNullAttribute
                    diskView.Disk = null;
                    // ReSharper restore AssignNullToNotNullAttribute

                    using (var fs = new FileStream(diskView.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        var request = new UploadDisk
                            {
                                Capacity = capacity,
                                DiskName = diskView.Name,
                                RequestStream = fs
                            };
                        var requestUrl = String.Format("{0}{1}?Capacity={2}", _serverUrl,
                            request.ToUrl("PUT").Substring(1), capacity);

                        //resp = await _serviceClient.PutAsync(request);
                        var req = WebRequest.CreateHttp(requestUrl);
                        req.Method = "PUT";
                        req.Accept = "application/json";

                        var reqStr = await req.GetRequestStreamAsync();
                        await fs.CopyToAsync(reqStr);
                        var rawResp = await req.GetResponseAsync();
                        var responseStream = rawResp.GetResponseStream();
                        if (responseStream != null)
                        {
                            using (var respReader = new StreamReader(responseStream, Encoding.UTF8))
                            {
                                var s = new JsonSerializer<DiskRecord>();
                                resp = s.DeserializeFromReader(respReader);
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException("Missing response from upload.");
                        }

                        StatusText = string.Format("Disk {0} successfully uploaded to server.", diskView.Name);
                        await RefreshServerDisksAsync(suppressStatusMessage: true);
                    }
                }
                finally
                {
                    diskView.Disk = VirtualDisk.OpenExisting(diskView.FileName);
                    diskView.Disk.NotificationDispatcher = oldNotificationDispatcher;
                }
            }
            StatusText = String.Format("Disk {0} associated with server as {1}.", diskView.Name, resp.Name);
        }
Example #17
0
        private List<ConnectionStringConfig> ConnectionStrings()
        {
            using(var reader = new StreamReader(BaseReportConfig().ReportTemplateRoot.Replace("sql", "json") + "ConnectionStrings.json"))
            {
                var serializer = new JsonSerializer<List<ConnectionStringConfig>>();
                var connectionStrings = serializer.DeserializeFromReader(reader);
                System.Web.HttpContext.Current.Cache.Insert("ConnectionStrings", connectionStrings);

                return connectionStrings;
            }
        }