public static void WriteBoxSettings() { FileStream file = GetJSONFile(); JsonSerializer ser = new JsonSerializer(); string values = ser.Serialize(BoxProperties.refreshInfo); file.Write(Encoding.ASCII.GetBytes(values), 0, Encoding.ASCII.GetByteCount(values)); file.Close(); }
public static void WriteDriveSettings() { FileStream file = GetJSONFile(); JsonSerializer ser = new JsonSerializer(); string values = ser.Serialize(GoogleDriveRefreshInfo.Instance); file.Write(Encoding.ASCII.GetBytes(values), 0, Encoding.ASCII.GetByteCount(values)); file.Close(); }
public override void WriteToStringBuilder(StringBuilder sb, JsonSerializer serializer) { sb.AppendFormat(@"{{ ""create"" : {{ ""_index"" : ""{0}"", ""_type"" : ""{1}""", _indexName, _typeName); sb.AppendFormat(@", ""_id"" : ""{0}""", _id); sb.Append(" } }\n"); var str = _obj as string; if (str != null) sb.Append(str); else sb.Append(serializer.Serialize(_obj)); sb.Append('\n'); }
public virtual string Serialize() { var props = new Dictionary<string, object>(); var properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in properties) { props.Add( this.GetPropertyName(prop.Name), prop.GetValue(this) ); } var serializer = new JsonSerializer(); return serializer.Serialize(props); }
public void channel_data_is_encoded_as_JSON() { string channelName = "my-channel"; string socketId = "123.456"; var serializer = new JsonSerializer(); PresenceChannelData data = new PresenceChannelData() { user_id = "unique_user_id", user_info = new { twitter_id = "@leggetter" } }; string expectedChannelData = serializer.Serialize(data); ; IAuthenticationData result = _pusher.Authenticate(channelName, socketId, data); Assert.AreEqual(expectedChannelData, result.channel_data); }
public void the_auth_response_is_valid() { string channelName = "my-channel"; string socketId = "123.456"; var serializer = new JsonSerializer(); PresenceChannelData data = new PresenceChannelData() { user_id = "unique_user_id", user_info = new { twitter_id = "@leggetter" } }; string presenceJSON = serializer.Serialize(data); string expectedAuthString = Config.AppKey + ":" + CreateSignedString(channelName, socketId, presenceJSON); IAuthenticationData result = _pusher.Authenticate(channelName, socketId, data); Assert.AreEqual(expectedAuthString, result.auth); }
public string Serialize(object obj) { if (obj==null) throw new ArgumentNullException(); // Use JsonSerializer for anonymous types. if (obj.GetType().IsAnonymous()) { var serializer = new JsonSerializer(); return serializer.Serialize(obj); } // Use DataContractJsonSerializer for other types. using (var stream = new MemoryStream()) { var serializer = new DataContractJsonSerializer(obj.GetType()); serializer.WriteObject(stream, obj); byte[] bytes = stream.ToArray(); return Encoding.UTF8.GetString(bytes, 0, bytes.Length); } }
private bool CheckRequestContainsPayload(IRestRequest request, string channelName, string eventName, object eventData) { var serializer = new JsonSerializer(); var expectedBody = new TriggerBody() { name = eventName, channels = new string[]{channelName}, data = serializer.Serialize(eventData) }; var expected = serializer.Serialize(expectedBody); return request.Parameters[0].Type == ParameterType.RequestBody && request.Parameters[0].ToString().Contains( expected ); }
///================================================== /// <summary> /// POST /api/attachments /// Upload or delete an attachment /// URL: /// https://bim360field.autodesk.com/api/attachments /// Method: POST /// Description: /// Uploads an attachment, or asks the server to delete an existing attachment. /// Doc /// https://bim360field.autodesk.com/apidoc/index.html#mobile_api_method_21 /// </summary> /// <returns></returns> /// ================================================= public static string Attachments(string ticket, string project_id, string originalPath, string thumbPath, string container_id, string container_type) { // (1) Build request var client = new RestClient(); client.BaseUrl = new System.Uri(_baseUrl); // Set resource or end point var request = new RestRequest(); request.Resource = "/api/attachments"; request.Method = Method.POST; // Add parameters request.AddParameter("ticket", ticket); request.AddParameter("project_id", project_id); // Compose Attachment JSON string FileInfo original = new FileInfo(originalPath); Dictionary<string, string> att = new Dictionary<string, string>(); // date time format: "2015-08-05 15:28:17 -0500"; string dateTimeFormat = "yyyy-MM-dd HH:mm:ss zzz"; string curTime = DateTime.Now.ToString(dateTimeFormat); att["fcreate_date"] = original.CreationTime.ToString(dateTimeFormat); att["fmod_date"] = original.LastWriteTime.ToString(dateTimeFormat); att["created_at"] = curTime; att["updated_at"] = curTime; att["size"] = original.Length.ToString(); att["content_type"] = MimeMapping.GetMimeMapping(original.Name); att["filename"] = original.Name; att["container_id"] = container_id; // e.g., equipment_id att["container_type"] = container_type; // e.g., "Equipment" // Conver to JSON format JsonSerializer JsonSerial = new JsonSerializer(); string attachment = JsonSerial.Serialize(att); Debug.WriteLine("attachment parameter = " + attachment); request.AddParameter("attachment", attachment); // Add Files request.AddFile("original", originalPath); request.AddFile("thumb", thumbPath); // MH: looks like it works without it. // (2) Execute request and get response IRestResponse response = client.Execute(request); // Save response. This is to see the response for our learning. m_lastResponse = response; return response.StatusCode.ToString(); }
static void Main(string[] args) { Console.WriteLine ("Constructing example data ..."); Foo foo1 = new Foo (); foo1.bar = "foobar"; foo1.answer = "42"; Foo foo2 = new Foo (); foo2.bar = "barfoo"; foo2.answer = "none"; ListItem listItem = new ListItem (); listItem.foo1 = foo1; listItem.foo2 = foo2; ObjectList objectList = new ObjectList (); objectList.Add ("item1", listItem); objectList.Add ("item2", listItem); String realJson = "{ \"item1\":{\"foo1\":{\"bar\":\"foobar\",\"answer\":\"42\"},\"foo2\":{\"bar\":\"barfoo\",\"answer\":\"none\"}},"; realJson = realJson + "\"item2\":{\"foo1\":{\"bar\":\"foobar\",\"answer\":\"42\"},\"foo2\":{\"bar\":\"barfoo\",\"answer\":\"none\"}} }"; Console.WriteLine ("Serializing data ..."); Console.WriteLine (String.Format("Expected JSON: `{0}`", realJson)); JsonSerializer serializer = new JsonSerializer (); String json1 = serializer.Serialize (objectList); Console.WriteLine (String.Format ("RestSharp JSON: `{0}`", json1)); Console.WriteLine ("Deserializing data ..."); // Does not work. try { Console.WriteLine("Attempting to deserialize RestSharp JSON ..."); JsonDeserializer deserializer = new JsonDeserializer(); RestResponse response = new RestResponse(); response.Content = json1; var decoded = deserializer.Deserialize<ObjectList>(response); Console.WriteLine("Success ..."); } catch (Exception ex) { Console.WriteLine ("Deserialization failed:"); Console.WriteLine (ex.Message); Console.WriteLine (ex.StackTrace); } // Does not work. try { Console.WriteLine("Attempting to deserialize expected JSON with RestSharp ..."); JsonDeserializer deserializer = new JsonDeserializer(); RestResponse response = new RestResponse(); response.Content = realJson; var decoded = deserializer.Deserialize<ObjectList>(response); Console.WriteLine("Success ..."); } catch (Exception ex) { Console.WriteLine ("Deserialization failed:"); Console.WriteLine (ex.Message); Console.WriteLine (ex.StackTrace); } // Does not work. try { Console.WriteLine("Attempting to deserialize RestSharp JSON with JSON.NET ..."); ObjectList list = Newtonsoft.Json.JsonConvert.DeserializeObject<ObjectList>(json1); Console.WriteLine("Success ..."); } catch (Exception ex) { Console.WriteLine ("Deserialization failed:"); Console.WriteLine (ex.Message); Console.WriteLine (ex.StackTrace); } // Works. try { Console.WriteLine("Attempting to deserialize expected JSON with JSON.NET ..."); ObjectList list = Newtonsoft.Json.JsonConvert.DeserializeObject<ObjectList>(realJson); Console.WriteLine("Success ..."); } catch (Exception ex) { Console.WriteLine ("Deserialization failed:"); Console.WriteLine (ex.Message); Console.WriteLine (ex.StackTrace); } }
private void WriteStreamDataToFile() { var serializer = new JsonSerializer(); var writer = new StreamWriter(STREAMDATA_FILE, false); foreach (var pair in _streamData) writer.WriteLine(serializer.Serialize(pair.Value)); writer.Close(); }
public string ToJson() { var session = new { GameId = Game.Id, Game.ExecutableDirectory, StartDate = StartDateTime, EndDate = EndDateTime.Value, Version, Duration = Duration.TotalSeconds, IsInvisible, IdleDuration = AfkDuration.TotalSeconds, IdleTime = IdleTime.Select (i => new { StartDate = i.StartDateTime, i.Duration, i.IsClosed }).ToList () }; var serializer = new JsonSerializer(); return serializer.Serialize( session ); }
/// <inheritdoc/> public string Serialize(object body) { var serializer = new JsonSerializer(); return serializer.Serialize(body); }
public void FfmpegErrorTest() { //Arrange var taskData = new EncodeTaskData() { TaskId = TaskId }; var errorEncodeData = new VideoEncodeData() { FileId = ConfigurationManager.AppSettings.Get("TestVideo"), VideoParam = new VideoParam() { MediaContainer = MetadataConstant.Mp4Container }, AudioParam = new AudioParam() { AudioCodec = MetadataConstant.AacCodec } }; var serializer = new JsonSerializer(); var jsonEncodeData = serializer.Serialize(errorEncodeData); var jsonTaskData = serializer.Serialize(taskData); var getTaskHeaders = VideoGetTaskResponseHeaders(Resource); ResponseSetup(jsonTaskData, jsonEncodeData, getTaskHeaders); RestClientSetup(Resource); _restClient.Setup(m => m.Execute(_deleteRequest)).Callback(() => _token.Cancel()); //Act var task = _manager.Start(); task.Wait(); Trace.WriteLine(_deleteRequest.Parameters.FirstOrDefault(p => p.Name == EncoderStatusParameters.Result).Value); //Assert Assert.IsTrue(_deleteRequest.Parameters.Any(p => p.Name == EncoderStatusParameters.Result && (EncoderState)p.Value == EncoderState.Failed)); }
public override string Serialize() { if(this._serializeEmptyFields) return base.Serialize(); var props = new Dictionary<string, object>(); this.AddIfNeeded(props, "Name", this.Name); this.AddIfNeeded(props, "Email", this.Email); this.AddIfNeeded(props, "Company", this.Company); this.AddIfNeeded(props, "Location", this.Location); this.AddIfNeeded(props, "Bio", this.Bio); props.Add(this.GetPropertyName("Hireable"), this.Hireable); if (this.Blog != null) { props.Add(this.GetPropertyName("Blog"), this.Blog); } var json = new JsonSerializer(); return json.Serialize(props); }
/// <summary> /// Serialize and save a PackageHeader to the "Packages" directory /// </summary> /// <param name="pkgHeader"> The PackageHeader object </param> public void SavePackageHeader(PackageHeader pkgHeader) { try { var m2 = new JsonSerializer(); string s = m2.Serialize(pkgHeader); string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string pluginsPath = Path.Combine(directory, "packages"); if (!Directory.Exists(pluginsPath)) Directory.CreateDirectory(pluginsPath); // now save it string path = Path.Combine(pluginsPath, pkgHeader.name + ".json"); File.WriteAllText(path, s); } catch { dynSettings.Bench.Dispatcher.BeginInvoke( (Action) (() => dynSettings.Controller.DynamoViewModel.Log( "Failed to write package header information, won't be under source control."))); } }
public void EncodeMp4TaskTest() { //Arrange var taskData = new EncodeTaskData() { TaskId = TaskId }; var encodeData = new VideoEncodeData() { FileId = ConfigurationManager.AppSettings.Get("TestVideo"), ContentType = "video/mp4", AudioParam = new AudioParam() { AudioCodec = MetadataConstant.AacCodec, AudioBitrate = 64000 }, VideoParam = new VideoParam() { VideoWidth = 480, VideoHeight = 360, VideoCodec = MetadataConstant.AvcCodec, VideoBitrate = 500000, VideoProfile = MetadataConstant.AvcMainProfile, MediaContainer = MetadataConstant.Mp4Container, FrameRate = 25, KeyFrameRate = 10 } }; var serializer = new JsonSerializer(); var jsonEncodeData = serializer.Serialize(encodeData); var jsonTaskData = serializer.Serialize(taskData); var getTaskHeaders = VideoGetTaskResponseHeaders(Resource); ResponseSetup(jsonTaskData, jsonEncodeData, getTaskHeaders); RestClientSetup(Resource); //Act var task = _manager.Start(); task.Wait(); Trace.WriteLine(_deleteRequest.Parameters.FirstOrDefault(p => p.Name == EncoderStatusParameters.Result).Value); //Assert Assert.IsTrue(_deleteRequest.Parameters.Any(p => p.Name == EncoderStatusParameters.Result && (EncoderState)p.Value == EncoderState.Completed)); }
public void FfmpegHangingTest() { //Arrange var taskData = new EncodeTaskData() { TaskId = TaskId }; var encodeData = new VideoEncodeData() { FileId = ConfigurationManager.AppSettings.Get("HangingVideo"), ContentType = "video/webm", AudioParam = new AudioParam() { AudioCodec = MetadataConstant.VorbisCodec, AudioBitrate = 128000, }, VideoParam = new VideoParam() { VideoWidth = 480, VideoHeight = 360, VideoCodec = MetadataConstant.Vp8Codec, VideoBitrate = 500000, MediaContainer = MetadataConstant.WebmContainer, FrameRate = 25, KeyFrameRate = 10 } }; var serializer = new JsonSerializer(); var jsonEncodeData = serializer.Serialize(encodeData); var jsonTaskData = serializer.Serialize(taskData); var getTaskHeaders = VideoGetTaskResponseHeaders(Resource); ResponseSetup(jsonTaskData, jsonEncodeData, getTaskHeaders); RestClientSetup(Resource); //Act var task = _manager.Start(); task.Wait(); Trace.WriteLine(_deleteRequest.Parameters.FirstOrDefault(p => p.Name == EncoderStatusParameters.Result).Value); //Assert //Assert.IsTrue(_setStatusRequest.Parameters.Any(p=>p.Name==ProcessStatusParameters.State && (ProcessState)p.Value==ProcessState.Hanging)); Assert.IsTrue(_deleteRequest.Parameters.Any(p => p.Name == EncoderStatusParameters.Result && (EncoderState)p.Value == EncoderState.Cancelled)); }
private static void WritePackageHeader(PackageUploadRequestBody pkgHeader, DirectoryInfo rootDir) { // build the package header json, which will be stored with the pkg var jsSer = new JsonSerializer(); var pkgHeaderStr = jsSer.Serialize(pkgHeader); // write the pkg header to the root directory of the pkg var headerPath = Path.Combine(rootDir.FullName, "pkg.json"); if (File.Exists(headerPath)) File.Delete(headerPath); File.WriteAllText(headerPath, pkgHeaderStr); }
public string ToJson() { var serializer = new JsonSerializer(); return serializer.Serialize(this); }
private async void loginWebBrowser_Navigating(object sender, NavigatingEventArgs e) { Match match = Regex.Match(e.Uri.Query, @"\?code=([\w\d]+)"); if (match.Success == false) return; string code = match.Groups[1].Value; e.Cancel = true; progressBar.IsIndeterminate = true; var client = new RestClient("https://api.weibo.com"); //client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; try { SinaLogin LoginResponse; { var req = new RestRequest(); req.Resource = "oauth2/access_token"; req.Method = Method.POST; req.RequestFormat = DataFormat.Json; req.OnBeforeDeserialization = (resp) => resp.ContentType = "application/json"; req.AddParameter(new Parameter() { Name = "client_id", Value = SinaApiConfig.app_key, Type = ParameterType.GetOrPost }); req.AddParameter(new Parameter() { Name = "client_secret", Value = SinaApiConfig.app_secret, Type = ParameterType.GetOrPost }); req.AddParameter(new Parameter() { Name = "code", Value = code, Type = ParameterType.GetOrPost }); req.AddParameter(new Parameter() { Name = "grant_type", Value = "authorization_code", Type = ParameterType.GetOrPost }); req.AddParameter(new Parameter() { Name = "redirect_uri", Value = "www.google.com", Type = ParameterType.GetOrPost }); var response = await RestSharpAsync.RestSharpExecuteAsyncTask<SinaLogin>(client, req); LoginResponse = response.Data; LoginResponse.request_time_utc = DateTime.Now.ToFileTimeUtc(); } { var req = new RestRequest(); req.Resource = "/2/users/show.json"; req.Method = Method.GET; req.RequestFormat = DataFormat.Json; req.OnBeforeDeserialization = (resp) => resp.ContentType = "application/json"; req.AddParameter(new Parameter() { Name = "access_token", Value = LoginResponse.access_token, Type = ParameterType.GetOrPost }); req.AddParameter(new Parameter() { Name = "uid", Value = LoginResponse.uid, Type = ParameterType.GetOrPost }); var response = await RestSharpAsync.RestSharpExecuteAsyncTask<user>(client, req); u.name = response.Data.name; } MessageBox.Show(string.Format("{0} 登录成功", u.name)); if (LoginResponse != null) { string str = ""; if (NavigationContext.QueryString.TryGetValue("mrguokr", out str)) { JsonSerializer j = new JsonSerializer(); var t = new EmailComposeTask(); t.To = "*****@*****.**"; t.Subject = "mrGuokr access token update (" + DateTime.Now.ToString() + ")"; t.Body = j.Serialize(LoginResponse); t.Show(); } else { ViewModelLocator.ApplicationSettingsStatic.WeiboAccountSinaLogin = LoginResponse; ViewModelLocator.ApplicationSettingsStatic.WeiboAccountSinaLogin.username = u.name; if (NavigationService.CanGoBack) NavigationService.GoBack(); } } } catch (Exception ex) { MessageBox.Show("貌似有点问题,重来一次吧~"); Debug.WriteLine(ex.InnerException.ToString()); } }
public void EncodeScreenshostTaskTest() { //Arrange var taskData = new EncodeTaskData() { TaskId = TaskId }; var encodeData = new ScreenshotEncodeData() { FileId = ConfigurationManager.AppSettings.Get("TestVideo"), ContentType = "image/jpeg", ScreenshotParam = new ScreenshotParam() { TimeOffset=1 } }; var serializer = new JsonSerializer(); var jsonEncodeData = serializer.Serialize(encodeData); var jsonTaskData = serializer.Serialize(taskData); var getTaskHeaders = ScreenshotGetTaskResponseHeaders(Resource); ResponseSetup(jsonTaskData, jsonEncodeData, getTaskHeaders); RestClientSetup(Resource); //Act var task = _manager.Start(); task.Wait(); Trace.WriteLine(_deleteRequest.Parameters.FirstOrDefault(p => p.Name == EncoderStatusParameters.Result).Value); //Assert Assert.IsTrue(_deleteRequest.Parameters.Any(p => p.Name == EncoderStatusParameters.Result && (EncoderState)p.Value == EncoderState.Completed)); }
private void WritePackageHeader(Package package, IDirectoryInfo rootDir) { var pkgHeader = PackageUploadBuilder.NewRequestBody(package); // build the package header json, which will be stored with the pkg var jsSer = new JsonSerializer(); var pkgHeaderStr = jsSer.Serialize(pkgHeader); // write the pkg header to the root directory of the pkg var headerPath = Path.Combine(rootDir.FullName, PackageJsonName); if (fileSystem.FileExists(headerPath)) { fileSystem.DeleteFile(headerPath); } fileSystem.WriteAllText(headerPath, pkgHeaderStr); }
public string Serialize(object obj) { var serializer = new JsonSerializer(); serializer.ContentType = "application/json"; return serializer.Serialize(obj); }