public void SerializeDictionary_Test() { var dics = new Dictionary<string, object> { { "Name", "gang.yang" }, { "Age", 28 }, { "Time", DateTime.Now} }; var json = new NewtonsoftJsonSerializer(); var result = json.Serialize(dics); // {"Name":"gang.yang","Age":28,"Time":"2016-03-09 14:11:13"} Assert.IsNull(result, result); }
public void Serialize_Test() { var model = new JsonTest() { Str = "gang.yang", Integer = 22, Number = 20.2020, Time = DateTime.Now }; var json = new NewtonsoftJsonSerializer(); var result = json.Serialize(model); Assert.IsNull(result, result); }
public void UseDataMemberNameWhenSpecified() { NewtonsoftJsonSerializer serializer = new NewtonsoftJsonSerializer(new DataMemberContractResolver(Enumerable.Empty<JsonConverter>())); String json; using (var memoryStream = new MemoryStream()) { serializer.Serializer.Formatting = Formatting.None; serializer.Serialize(memoryStream, new ClassWithDataMember("Test String"), typeof(Object)); json = Encoding.UTF8.GetString(memoryStream.ToArray()); } Assert.Contains("{\"$type\":\"Test.Spark.Serialization.UsingNewtonsoftJsonSerializer.WhenSerializingData+ClassWithDataMember, Spark.Serialization.Newtonsoft.Tests\",\"t\":\"Test String\"}", json); }
public void SerializationShouldBeCompressed() { // Arrange. var filter = new GzipCompressionMessageFilter(); var envelope = Envelope.Create(new CreateOrderCommand { Id = "abc" }) .Property("Something", 123); var serializer = new NewtonsoftJsonSerializer(); var serializedBody = serializer.Serialize(envelope.Body).Result; // Act. var compressedBody = filter.AfterSerialization(envelope, serializedBody).Result; // Assert. Assert.True(compressedBody.Length < serializedBody.Length); }
public void DeserializationShouldWorkCorrectly() { // Arrange. var filter = new GzipCompressionMessageFilter(); var envelope = Envelope.Create(new CreateOrderCommand { Id = "abc" }) .Property("Something", 123); var serializer = new NewtonsoftJsonSerializer(); var serializedBody = serializer.Serialize(envelope.Body).Result; var compressedBody = filter.AfterSerialization(envelope, serializedBody).Result; // Act. var decompressedBody = filter.BeforeDeserialization(envelope, compressedBody).Result; var command = serializer.Deserialize<CreateOrderCommand>(decompressedBody).Result; // Assert. Assert.Equal(envelope.Body.Id, command.Id); }
/// <summary> /// override, 重写执行结果 /// </summary> /// <param name="context"></param> public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("The request http method is denied."); } var response = context.HttpContext.Response; response.ContentType = !string.IsNullOrEmpty(this.ContentType) ? this.ContentType : "application/json"; if (this.ContentEncoding != null) response.ContentEncoding = this.ContentEncoding; if (this.Data != null) { var json = new NewtonsoftJsonSerializer(); response.Write(json.Serialize(this.Data)); } }
public async void UploadVideo(AudioUoW audio, OauthTokenModel otm, List<VideoUploadedEventHandler> videoUploaded = null) { try { Video returnedVideo = null; using (var stream = File.OpenRead(audio.VideoPath)) { var video = new Video { Snippet = new VideoSnippet { Title = audio.Title, Description = audio.Description, Tags = audio.Tags, //TODO get category list info CategoryId = "22" }, Status = new VideoStatus { PrivacyStatus = "unlisted", Embeddable = true, License = "youtube" } }; var headers = new Dictionary<string, string>(); headers["Authorization"] = otm.TokenType + " " + otm.AccessToken; headers["X-Upload-Content-Length"] = stream.Length.ToString(); headers["x-upload-content-type"] = "application/octet-stream"; IJsonSerializer js = new NewtonsoftJsonSerializer(); var videoData = js.Serialize(video); var response = await WebHelper.GetRawResponsePost( "https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status,contentDetails", videoData, headers); var uploadUrl = response.Headers.Location; returnedVideo = await WebHelper.Post<Video>( uploadUrl.AbsoluteUri, stream, headers); audio.YouTubeUrl = "https://www.youtube.com/watch?v=" + returnedVideo.Id; } if (videoUploaded == null) return; foreach (var vu in videoUploaded) { vu(this, new VideoUploadedEventArgs() {Audio = audio}); } } catch (Exception ex) { Log.Error(ex.Message, ex); } }
public static string Serialize(object obj) { return(_serializer.Serialize(obj)); }
/// <summary> /// The entry point of the program, where the program control starts and ends. /// </summary> /// <param name="args">The command-line arguments.</param> public static void Main(string[] args) { var fbEmailFile = @"../../facebook.email.dontcommit"; var fbPasswordFile = @"../../facebook.pw.dontcommit"; var fbAuthInfoFile = @"../../facebook.auth.dontcommit"; var tndrAuthInfoFile = @"../../tinder.auth.dontcommit"; var fbEmailAddress = File.ReadAllText (fbEmailFile); var fbPassword = File.ReadAllText (fbPasswordFile); var recommendationsFolderPath = "nyc_recommendations"; var nopeFolderPath = "nope"; var yesFolderPath = "yes"; var startTime = DateTime.Now; var runForTimeSpan = new TimeSpan (4, 0, 0); var hitCountDictionaryFile = DateTime.Now.ToString ("MM.dd.yyyy.hh.mm.ss") + "_hitcountdict.dontcommit.txt"; var recsIntervalRandomizer = new Random (); var recsIntervalTimeSpanMininum = new TimeSpan (0, 0, 1, 0); var recsIntervalTimeSpanMaximum = new TimeSpan (0, 0, 2, 0); var totalRecommendations = 0.0; var hitCountDictionary = new Dictionary<string, int> (); var disposables = new List<IDisposable> (); var jsonSerializer = new NewtonsoftJsonSerializer (); var webDriverFactory = new PhantomJSWebDriverFactory (); var webDriverForFacebookAuthenticator = webDriverFactory.CreateWebDriver (); disposables.Add (webDriverForFacebookAuthenticator); Console.Clear (); try { FacebookSession fbSession = null; if(File.Exists (fbAuthInfoFile)) { var fbAuthInfo = File.ReadAllLines (fbAuthInfoFile); if(fbAuthInfo.Any ()) { var fbAccessToken = fbAuthInfo[0]; var fbId = fbAuthInfo[1]; fbSession = new FacebookSession (fbAccessToken, fbId); } } if(fbSession != null) { Console.WriteLine ("Using previous Facebook session authentication."); } else { Console.WriteLine ("Reauthenticating with Facebook..."); var fbAuthenticator = new SeleniumFacebookAuthenticator (webDriverForFacebookAuthenticator, fbEmailAddress, fbPassword); fbSession = fbAuthenticator.Authenticate (); } if(fbSession != null) { Console.WriteLine ("Authenticated with Facebook: '{0}'.", fbSession); File.WriteAllLines (fbAuthInfoFile, new string[] { fbSession.AccessToken, fbSession.Id }); } else { Console.WriteLine ("Authentication with Facebook failed."); if(File.Exists (fbAuthInfoFile)) { File.Delete (fbAuthInfoFile); } goto end; } string tndrAccessToken = null; TndrClient tndrClient = null; if(File.Exists (tndrAuthInfoFile)) { var tndrAuthInfo = File.ReadAllLines (tndrAuthInfoFile); if(tndrAuthInfoFile.Any ()) { tndrAccessToken = tndrAuthInfo[0]; } } if(tndrAccessToken != null) { Console.WriteLine ("Using previous Tinder session authentication."); tndrClient = new TndrClient (tndrAccessToken); try { var tndrUpdatesResponse = tndrClient.GetUpdates (); if(tndrUpdatesResponse == null || tndrUpdatesResponse.LastActiveDate == null) { tndrAccessToken = null; } } catch { tndrAccessToken = null; } } if(tndrAccessToken == null) { Console.WriteLine ("Reauthenticating with Tinder using current FacebookSession..."); var tndrAuthenticationResponse = TndrClient.Authenticate (fbSession); if(tndrAuthenticationResponse != null) { tndrAccessToken = tndrAuthenticationResponse.AccessToken; } } if(tndrAccessToken != null) { Console.WriteLine ("Authenticated with Tinder: '{0}'.", tndrAccessToken); File.WriteAllLines (tndrAuthInfoFile, new string[] { tndrAccessToken }); tndrClient = new TndrClient (tndrAccessToken); } else { Console.WriteLine ("Authentication with Tinder failed."); if(File.Exists (tndrAuthInfoFile)) { File.Delete (tndrAuthInfoFile); } if(File.Exists (fbAuthInfoFile)) { File.Delete (fbAuthInfoFile); } goto end; } var webClient = new WebClient (); disposables.Add (webClient); //IWebDriver photoWebDriver = null; while((DateTime.Now - startTime) < runForTimeSpan) { var tndrUpdatesResponse = tndrClient.GetUpdates (); if(tndrUpdatesResponse.Matches != null) { Console.WriteLine ("Tinder matches: {0}.", tndrUpdatesResponse.Matches.Count ()); } var tndrReccomendationsResponse = tndrClient.GetRecommendations (); if(tndrReccomendationsResponse.StatusCode != 200) { Console.WriteLine ("No Tinder recommendations available or requesting too fast."); } else { if(tndrReccomendationsResponse.Recommendations.Any (r => r.TinderId.StartsWith ("tinder_rate_limited_id"))) { Console.WriteLine ("Tinder Rate Limit Reached"); goto end; } totalRecommendations += tndrReccomendationsResponse.Recommendations.Count (); Console.WriteLine ("Tinder recommendations: {0}.", tndrReccomendationsResponse.Recommendations.Count ()); if(tndrReccomendationsResponse.Recommendations.Any ()) { //try //{ // var urlTest = photoWebDriver.Url; //} //catch //{ // photoWebDriver = new FirefoxDriver (); // webDrivers.Add (photoWebDriver); //} foreach(var tndrRecommendation in tndrReccomendationsResponse.Recommendations) { if(hitCountDictionary.ContainsKey (tndrRecommendation.TinderId)) { hitCountDictionary[tndrRecommendation.TinderId]++; } else { hitCountDictionary[tndrRecommendation.TinderId] = 1; } //photoWebDriver.Url = tndrRecommendation.Photos.First ().Url; //photoWebDriver.Navigate (); //photoWebDriver.FindElement (By.TagName ("body")).SendKeys (Keys.Command + "t"); var recommendationFolderPath = Path.Combine (recommendationsFolderPath, tndrRecommendation.TinderId); var nopeRecommendationFolderPath = Path.Combine (nopeFolderPath, tndrRecommendation.TinderId); var yesRecommendationFolderPath = Path.Combine (yesFolderPath, tndrRecommendation.TinderId); if(!Directory.Exists (recommendationFolderPath) && !Directory.Exists (nopeRecommendationFolderPath) && !Directory.Exists (yesRecommendationFolderPath)) { Console.WriteLine ("\tNEW=> Name: {0, -20} Age: {1, -10} Recommended {2} time(s).", tndrRecommendation.Name, DateTime.Now.Year - DateTime.Parse (tndrRecommendation.BirthDate).Year, hitCountDictionary[tndrRecommendation.TinderId]); Directory.CreateDirectory (recommendationFolderPath); Directory.CreateDirectory (Path.Combine (recommendationFolderPath, "photos")); var recommendationFile = Path.Combine (recommendationFolderPath, string.Format ("{0}_{1}_{2}.txt", tndrRecommendation.Name, DateTime.Now.Year - DateTime.Parse (tndrRecommendation.BirthDate).Year, tndrRecommendation.TinderId)); File.WriteAllText (recommendationFile, jsonSerializer.Serialize (tndrRecommendation, indented: true)); foreach(var photo in tndrRecommendation.Photos) { //Console.WriteLine ("\t\tPhoto: {0}", photo.Url); var photoUri = new Uri (photo.Url); var photoFileName = Path.GetFileName (photoUri.AbsoluteUri); var photoLocalFilePath = Path.Combine (recommendationFolderPath, "photos", photoFileName); { try { webClient.DownloadFile (photoUri.ToString (), photoLocalFilePath); } catch { } } } } else { Console.WriteLine ("\tOLD=> Name: {0, -20} Age: {1, -10} Recommended {2} time(s).", tndrRecommendation.Name, DateTime.Now.Year - DateTime.Parse (tndrRecommendation.BirthDate).Year, hitCountDictionary[tndrRecommendation.TinderId]); } } try { var jsonHitCountDictionary = jsonSerializer.Serialize (hitCountDictionary.OrderByDescending (h => h.Value), true); File.WriteAllText (Path.Combine (recommendationsFolderPath, hitCountDictionaryFile), jsonHitCountDictionary); } catch { } } else { Console.WriteLine ("No recommendations provided."); } } var average = hitCountDictionary.Average (x => x.Value); Console.WriteLine ("Top 20 Hits:"); foreach(var hitCountEntry in hitCountDictionary.OrderByDescending (h => h.Value).Take (20)) { Console.WriteLine ("\tId: {0}\tTotal Hits: {1} ({2:P2})\tLiked You: {3:P2}", hitCountEntry.Key, hitCountEntry.Value, (hitCountEntry.Value / totalRecommendations), (1 - (average / hitCountEntry.Value))); } Console.WriteLine ("Time left {0}...", runForTimeSpan - (DateTime.Now - startTime)); TimeSpan timeLapsed; var sleepForMs = recsIntervalRandomizer.Next (Convert.ToInt32 (recsIntervalTimeSpanMininum.TotalMilliseconds), Convert.ToInt32 (recsIntervalTimeSpanMaximum.TotalMilliseconds)); var sleepForTimeSpan = TimeSpan.FromMilliseconds (sleepForMs); var sleepStart = DateTime.Now; while((timeLapsed = DateTime.Now - sleepStart) < sleepForTimeSpan) { Console.WriteLine ("Sleeping for {0} {1}", (sleepForTimeSpan - timeLapsed), GenerateProgressBar (timeLapsed.TotalMilliseconds, sleepForTimeSpan.TotalMilliseconds)); if(Console.KeyAvailable) { if(Console.ReadKey (true).Key == ConsoleKey.Escape) { Console.WriteLine ("\nExiting Tndr tester..."); goto end; } } Console.CursorTop = Console.CursorTop - 1; } } } catch(Exception ex) { Console.WriteLine (ex); } finally { foreach(var webDriver in disposables) { webDriver.Dispose (); } } end: Console.WriteLine ("Ran for {0}.", (DateTime.Now - startTime)); Console.WriteLine ("Press enter to quit."); Console.ReadLine (); }
public async void UploadVideo(AudioUoW audio, OauthTokenModel otm, List <VideoUploadedEventHandler> videoUploaded = null) { try { Video returnedVideo = null; using (var stream = File.OpenRead(audio.VideoPath)) { var video = new Video { Snippet = new VideoSnippet { Title = audio.Title, Description = audio.Description, Tags = audio.Tags, //TODO get category list info CategoryId = "22" }, Status = new VideoStatus { PrivacyStatus = "unlisted", Embeddable = true, License = "youtube" } }; var headers = new Dictionary <string, string>(); headers["Authorization"] = otm.TokenType + " " + otm.AccessToken; headers["X-Upload-Content-Length"] = stream.Length.ToString(); headers["x-upload-content-type"] = "application/octet-stream"; IJsonSerializer js = new NewtonsoftJsonSerializer(); var videoData = js.Serialize(video); var response = await WebHelper.GetRawResponsePost( "https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status,contentDetails", videoData, headers); var uploadUrl = response.Headers.Location; returnedVideo = await WebHelper.Post <Video>( uploadUrl.AbsoluteUri, stream, headers); audio.YouTubeUrl = "https://www.youtube.com/watch?v=" + returnedVideo.Id; } if (videoUploaded == null) { return; } foreach (var vu in videoUploaded) { vu(this, new VideoUploadedEventArgs() { Audio = audio }); } } catch (Exception ex) { Log.Error(ex.Message, ex); } }
private async Task Get(IHttpResourceRequest request, IHttpResourceResponse response) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (response == null) { throw new ArgumentNullException(nameof(response)); } if (_messageJournal == null) { // Message journaling is not enabled response.StatusCode = (int)HttpStatusCode.NotImplemented; return; } var authorized = _authorizationService == null || await _authorizationService.IsAuthorizedToQueryJournal(request.Principal); if (!authorized) { response.StatusCode = (int)HttpStatusCode.Unauthorized; response.StatusDescription = "Unauthorized"; return; } var responseModel = new JournalGetResponseModel(); var start = await GetStartPosition(request, responseModel.Errors); var count = GetCount(request, responseModel.Errors); var filter = ConfigureFilter(request, responseModel.Errors); if (responseModel.Errors.Any()) { response.StatusCode = (int)HttpStatusCode.BadRequest; } else { var result = await _messageJournal.Read(start, count, filter); responseModel.Start = start.ToString(); responseModel.Next = result.Next.ToString(); responseModel.EndOfJournal = result.EndOfJournal; responseModel.Entries = result.Entries.Select(entry => new MessageJournalEntryModel { Position = entry.Position.ToString(), Category = entry.Category, Timestamp = entry.Timestamp, Data = new MessageJournalEntryDataModel { Headers = entry.Data.Headers.ToDictionary(h => (string)h.Key, h => h.Value), Content = entry.Data.Content } }).ToList(); response.StatusCode = (int)HttpStatusCode.OK; } response.ContentType = "application/json"; var encoding = response.ContentEncoding; if (encoding == null) { encoding = Encoding.UTF8; response.ContentEncoding = encoding; } var serializedContent = _serializer.Serialize(responseModel); var encodedContent = encoding.GetBytes(serializedContent); response.StatusCode = 200; await response.OutputStream.WriteAsync(encodedContent, 0, encodedContent.Length); }
public string Serialize() { return(_serializer.Serialize(Item)); }