public ConnectionManager(ILogger logger,
            ICredentialProvider credentialProvider,
            INetworkConnection networkConnectivity,
            IServerLocator serverDiscovery,
            string applicationName,
            string applicationVersion,
            IDevice device,
            ClientCapabilities clientCapabilities,
            ICryptographyProvider cryptographyProvider,
            Func<IClientWebSocket> webSocketFactory = null,
            ILocalAssetManager localAssetManager = null)
        {
            _credentialProvider = credentialProvider;
            _networkConnectivity = networkConnectivity;
            _logger = logger;
            _serverDiscovery = serverDiscovery;
            _httpClient = AsyncHttpClientFactory.Create(logger);
            ClientCapabilities = clientCapabilities;
            _webSocketFactory = webSocketFactory;
            _cryptographyProvider = cryptographyProvider;
            _localAssetManager = localAssetManager;

            Device = device;
            ApplicationVersion = applicationVersion;
            ApplicationName = applicationName;
            ApiClients = new Dictionary<string, IApiClient>(StringComparer.OrdinalIgnoreCase);
            SaveLocalCredentials = true;

            Device.ResumeFromSleep += Device_ResumeFromSleep;

            var jsonSerializer = new NewtonsoftJsonSerializer();
            _connectService = new ConnectService(jsonSerializer, _logger, _httpClient, _cryptographyProvider, applicationName, applicationVersion);
        }
        public async Task Given_No_Topic_When_Getting_Then_Topic_List_Returned()
        {
            var mockSubscriptionTrackingService = new Mock<ISubscriptionTrackingService>();
            var topics = new TopicName[] {"topic-1", "topic-2", "topic-3"};
            var controller = new TopicController(mockSubscriptionTrackingService.Object, topics);

            var mockRequest = new Mock<IHttpResourceRequest>();
            var requestUri = new UriBuilder
            {
                Scheme = "http",
                Host = "localhost",
                Path = "/platibus/topic/"
            }.Uri;

            mockRequest.Setup(r => r.HttpMethod).Returns("GET");
            mockRequest.Setup(r => r.Url).Returns(requestUri);

            var mockResponse = new Mock<IHttpResourceResponse>();
            var responseOutputStream = new MemoryStream();
            var responseEncoding = Encoding.UTF8;
            mockResponse.Setup(r => r.ContentEncoding).Returns(responseEncoding);
            mockResponse.Setup(r => r.OutputStream).Returns(responseOutputStream);

            await controller.Process(mockRequest.Object, mockResponse.Object, Enumerable.Empty<string>());

            mockResponse.VerifySet(r => r.StatusCode = 200);
            var responseContent = responseEncoding.GetString(responseOutputStream.GetBuffer());
            var topicsFromResponse = new NewtonsoftJsonSerializer().Deserialize<string[]>(responseContent);

            Assert.That(topicsFromResponse.Length, Is.EqualTo(3));
            Assert.That(topicsFromResponse, Contains.Item("topic-1"));
            Assert.That(topicsFromResponse, Contains.Item("topic-2"));
            Assert.That(topicsFromResponse, Contains.Item("topic-3"));
        }
        public void DeserializeDictionary_Test()
        {
            var deserializeStr = "\"Name\":\"gang.yang\",\"Age\":28,\"Time\":\"2016-03-09 14:11:13\"";
            var json = new NewtonsoftJsonSerializer();
            var result = json.Deserialize<Dictionary<string, string>>(deserializeStr);

            // error
            Assert.IsNull(result);
        }
        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);
        }
Exemple #5
0
		/// <summary>
		/// Clear all custom global options and set default values.
		/// </summary>
		public void ResetDefaults() {
			DefaultTimeout = new HttpClient().Timeout;
			AllowedHttpStatusRange = null;
			HttpClientFactory = new DefaultHttpClientFactory();
			JsonSerializer = new NewtonsoftJsonSerializer(null);
			UrlEncodedSerializer = new DefaultUrlEncodedSerializer();
			BeforeCall = null;
			BeforeCallAsync = null;
			AfterCall = null;
			AfterCallAsync = null;
			OnError = null;
			OnErrorAsync = null;
		}
Exemple #6
0
            public void CanUseCustomDataMemberNames()
            {
                Byte[] json = Encoding.UTF8.GetBytes("{\"$type\":\"Test.Spark.Serialization.UsingNewtonsoftJsonSerializer.WhenDeserializingData+ClassWithCustomMemberName, Spark.Serialization.Newtonsoft.Tests\",\"t\":\"Test String\"}");
                NewtonsoftJsonSerializer  serializer = new NewtonsoftJsonSerializer(new DataMemberContractResolver(Enumerable.Empty <JsonConverter>()));
                ClassWithCustomMemberName graph;

                using (var memoryStream = new MemoryStream(json, writable: false))
                {
                    serializer.Serializer.Formatting = Formatting.None;

                    graph = (ClassWithCustomMemberName)serializer.Deserialize(memoryStream, typeof(Object));
                }

                Assert.Equal("Test String", graph.Test);
            }
            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 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);
        }
Exemple #9
0
            protected override async Task <IEnumerable <byte> > HandleCall(HttpListenerRequest request, HttpListenerResponse response)
            {
                var ret = await base.HandleCall(request, response);

                var serializer = new NewtonsoftJsonSerializer();

                if (Requests.Count == 1)
                {
                    Request = serializer.Deserialize <TRequest>(request.InputStream);
                }
                var responseBody = new MemoryStream();

                serializer.Serialize(_expectedResponse, responseBody);
                return(responseBody.ToArray());
            }
        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 DeserializePeopleResponse()
        {
            string         json     = TestData["PeopleResponse.json"];
            PeopleResponse response = NewtonsoftJsonSerializer
                                      .Create(JsonNamingStrategy.CamelCase)
                                      .Deserialize <PeopleResponse>(json);

            DateTime expectedDate0 = new DateTime(2017, 08, 05, 17, 03, 51).AddTicks(7279382);
            DateTime expectedDate1 = new DateTime(2017, 07, 22, 12, 55, 43).AddTicks(7301922);
            DateTime expectedDate2 = new DateTime(2013, 07, 01, 15, 10, 28).AddTicks(4600000);

            Assert.AreEqual(3, response.TotalCount);

            Assert.IsNotEmpty(response.People);
            Assert.AreEqual(3, response.People.Length);

            Assert.IsFalse(response.People[0].IsKnown);
            Assert.IsTrue(response.People[0].IsFavorite);
            Assert.IsTrue(response.People[0].IsFollowedByCaller);
            Assert.IsTrue(response.People[0].IsFollowingCaller);
            Assert.IsFalse(response.People[0].IsUnfollowingFeed);
            Assert.AreEqual(2580478784034343, response.People[0].Xuid);
            Assert.AreEqual(expectedDate0, response.People[0].AddedDateTimeUtc);
            Assert.IsNotNull(response.People[0].SocialNetworks);
            Assert.IsEmpty(response.People[0].SocialNetworks);

            Assert.IsFalse(response.People[1].IsKnown);
            Assert.IsTrue(response.People[1].IsFavorite);
            Assert.IsTrue(response.People[1].IsFollowedByCaller);
            Assert.IsTrue(response.People[1].IsFollowingCaller);
            Assert.IsFalse(response.People[1].IsUnfollowingFeed);
            Assert.AreEqual(2535771801919068, response.People[1].Xuid);
            Assert.AreEqual(expectedDate1, response.People[1].AddedDateTimeUtc);
            Assert.IsNotNull(response.People[1].SocialNetworks);
            Assert.IsEmpty(response.People[1].SocialNetworks);

            Assert.IsFalse(response.People[2].IsKnown);
            Assert.IsTrue(response.People[2].IsFavorite);
            Assert.IsTrue(response.People[2].IsFollowedByCaller);
            Assert.IsTrue(response.People[2].IsFollowingCaller);
            Assert.IsFalse(response.People[2].IsUnfollowingFeed);
            Assert.AreEqual(2508565379774180, response.People[2].Xuid);
            Assert.AreEqual(expectedDate2, response.People[2].AddedDateTimeUtc);
            Assert.IsNotNull(response.People[2].SocialNetworks);
            Assert.IsNotEmpty(response.People[2].SocialNetworks);
            Assert.AreEqual(1, response.People[2].SocialNetworks.Length);
            Assert.AreEqual("LegacyXboxLive", response.People[2].SocialNetworks[0]);
        }
Exemple #12
0
        internal ApiClientBase(ClientConfiguration configuration)
        {
            _configuration = configuration;

            var jsonSerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                },
                Formatting        = Formatting.Indented,
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
            };

            _newtonsoftJsonSerializer = new NewtonsoftJsonSerializer(jsonSerializerSettings);
        }
Exemple #13
0
        public void DeserializePeopleSummaryResponse()
        {
            string json = TestData["PeopleSummaryResponse.json"];
            PeopleSummaryResponse response = NewtonsoftJsonSerializer
                                             .Create(JsonNamingStrategy.CamelCase)
                                             .Deserialize <PeopleSummaryResponse>(json);

            Assert.IsInstanceOf(typeof(IStringable), response);
            Assert.IsFalse(response.IsTargetFollowingCaller);
            Assert.IsFalse(response.HasCallerMarkedTargetAsFavorite);
            Assert.IsTrue(response.IsCallerFollowingTarget);
            Assert.AreEqual("None", response.LegacyFriendStatus);
            Assert.IsFalse(response.HasCallerMarkedTargetAsKnown);
            Assert.AreEqual(94, response.TargetFollowingCount);
            Assert.AreEqual(3747535, response.TargetFollowerCount);
        }
Exemple #14
0
        private RestRequest BuildRestRequest(Method method)
        {
            var serializer = new NewtonsoftJsonSerializer();
            var rv         = new RestRequest
            {
                Method         = method,
                JsonSerializer = serializer,
            };

            if (null != requestHostHeader)
            {
                rv.AddHeader("Host", requestHostHeader);
            }

            return(rv);
        }
Exemple #15
0
        public void TestDeSerializeJsonNet()
        {
            var jsonSerializer = new NewtonsoftJsonSerializer();

            var r = jsonSerializer.Serialize(new ValueObject
            {
                A = 10,
                B = 20,
            });

            Assert.AreNotEqual(r, null);

            var s = jsonSerializer.Deserialize <ValueObject>(r);

            Assert.AreEqual(s.A, 10);
        }
Exemple #16
0
        public void Deserialize_Should_EquivalentToOrigin()
        {
            var rawCard            = faker.PredefinedRawSignedModel(null, true);
            var serializer         = new NewtonsoftJsonSerializer();
            var serializedRawCard  = serializer.Serialize(rawCard);
            var deserializeRawCard = serializer.Deserialize <RawSignedModel>(serializedRawCard);

            Assert.IsTrue(deserializeRawCard.ContentSnapshot.SequenceEqual(rawCard.ContentSnapshot));

            var first = deserializeRawCard.Signatures.First();
            var sec   = rawCard.Signatures.First();

            Assert.AreEqual(first.Signature, sec.Signature);
            Assert.AreEqual(first.Snapshot, sec.Snapshot);
            Assert.IsTrue(deserializeRawCard.ContentSnapshot.SequenceEqual(rawCard.ContentSnapshot));
        }
Exemple #17
0
            public void UseDefaultConstructorWhenSpecified()
            {
                Byte[] json = Encoding.UTF8.GetBytes("{\"$type\":\"Test.Spark.Serialization.UsingNewtonsoftJsonSerializer.WhenDeserializingData+ClassWithDefaultConstructor, Spark.Serialization.Newtonsoft.Tests\",\"test\":\"Test String\"}");
                NewtonsoftJsonSerializer    serializer = new NewtonsoftJsonSerializer(new DataMemberContractResolver(Enumerable.Empty <JsonConverter>()));
                ClassWithDefaultConstructor graph;

                using (var memoryStream = new MemoryStream(json, writable: false))
                {
                    serializer.Serializer.Formatting = Formatting.None;

                    graph = (ClassWithDefaultConstructor)serializer.Deserialize(memoryStream, typeof(Object));
                }

                Assert.Equal("Test String", graph.Test);
                Assert.True(graph.DefaultConstructorInvoked);
            }
Exemple #18
0
        public void DeserializeConversationsResponse()
        {
            string json = TestData["MessageConversationsResponse.json"];
            ConversationsResponse response = NewtonsoftJsonSerializer
                                             .Create(JsonNamingStrategy.CamelCase)
                                             .Deserialize <ConversationsResponse>(json);

            Assert.IsInstanceOf(typeof(IStringable), response);
            Assert.IsNotNull(response.Results);
            Assert.IsNotEmpty(response.Results);
            Assert.AreEqual(2, response.Results.Length);
            Assert.IsNotNull(response.Results[0].LastMessage);
            Assert.IsNotNull(response.Results[1].LastMessage);
            Assert.IsNotEmpty(response.Results[0].LastMessage.Actions);
            Assert.IsNull(response.Results[1].LastMessage.Actions);
        }
Exemple #19
0
        public async Task AddProject_WhenRequiredFieldHasIncorrectData_ShouldReturnBadRequest(
            string serializedProject, string typeOfError)
        {
            //Arrange
            SetAuthorization();

            //Act
            var projectModel = NewtonsoftJsonSerializer.DefaultDeserialize <RequestProjectModel>(serializedProject);
            var response     = await ProjectService.AddProject(projectModel);

            //Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);

            var errorResponse = response.GetErrors();

            ErrorAssert.ValidateErrorMessage(errorResponse, typeOfError);
        }
 /// <summary>
 /// Creates client service
 /// </summary>
 /// <param name="url">URL to loyalty server</param>
 /// <param name="token">Auth token to login</param>
 /// <param name="debugMode">If set, requests may be logged on server side (can be slower, avoid production usage)</param>
 public CheckpointClient(string url, string token, bool debugMode = false)
 {
     _debugMode = debugMode;
     if (!url.EndsWith("/"))
     {
         url += "/";
     }
     _baseUrl    = new Uri(url).GetLeftPart(UriPartial.Authority);
     _token      = token;
     _restClient = new RestClient(url)
     {
         ThrowOnAnyError = true
     };
     _serializer = new NewtonsoftJsonSerializer();
     _restClient.AddHandler("application/json", () => _serializer);
     _restClient.AddHandler("text/json", () => _serializer);
 }
        public static T ExecuteRequest <T>(string url, Method method, T body, RestClient client, IDictionary <string, object> requestParameters)
            where T : new()
        {
            var request = new RestRequest(url, method);

            if (requestParameters != null)
            {
                foreach (var requestParameter in requestParameters)
                {
                    request.AddParameter(requestParameter.Key, requestParameter.Value);
                }
            }

            if (ShouldAddBody(method))
            {
                var serializer = new NewtonsoftJsonSerializer(
                    JsonSerializer.Create(
                        new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));

                request.JsonSerializer = serializer;
                request.RequestFormat  = DataFormat.Json;
                request.AddBody(body);
            }

            //Fixed bug that prevents RestClient for adding custom headers to the request
            //https://stackoverflow.com/questions/22229393/why-is-restsharp-addheaderaccept-application-json-to-a-list-of-item

            client.ClearHandlers();
            client.AddHandler("application/json", new JsonDeserializer());
            var result = ExectueRequest <T>(method, client, request);

            if (result.ErrorException != null)
            {
                throw new WebException("REST client encountered an error: " + result.ErrorMessage, result.ErrorException);
            }
            // This is a hack in order to allow this method to work for simple types as well
            // one example of this is the GetRevisionRaw method
            if (RequestingSimpleType <T>())
            {
                return(result.Content as dynamic);
            }
            return(result.Data);
        }
        public void CreateMessageSendRequest()
        {
            string expectedXuid     = TestData["MessageSendMessageXuidRequest.json"];
            string expectedGamertag = TestData["MessageSendMessageGtRequest.json"];

            ulong[]            xuids       = new ulong[] { 2580478784034343, 2535771801919068, 2508565379774180 };
            string[]           gamertags   = new string[] { "Gamertag1", "Gamertag2" };
            MessageSendRequest requestXuid = new MessageSendRequest("TestString", xuids);
            MessageSendRequest requestGt   = new MessageSendRequest("TestString", gamertags);
            string             bodyXuid    = NewtonsoftJsonSerializer.Create(JsonNamingStrategy.CamelCase)
                                             .Serialize(requestXuid);
            string bodyGt = NewtonsoftJsonSerializer.Create(JsonNamingStrategy.CamelCase)
                            .Serialize(requestGt);

            Assert.AreEqual(expectedXuid, bodyXuid);
            Assert.AreEqual(expectedGamertag, bodyGt);
        }
        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);
        }
Exemple #24
0
        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 EditLoanRequest(Loan loan) : base("lender/loan/{loan_id}", Method.PUT)
        {
            JsonSerializer = new NewtonsoftJsonSerializer(new JsonSerializer()
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling     = NullValueHandling.Ignore,
                DefaultValueHandling  = DefaultValueHandling.Include
            });

            AddParameter("loan_id", loan.Id, ParameterType.UrlSegment);

            var request = new Request();

            Utils.DictionaryToJsonFields(request, loan.GetDirtyFieldsForRequest());

            AddJsonBody(request);
        }
        public void Download_Error_JsonResponse()
        {
            var downloadUri = "http://www.sample.com";
            var chunkSize   = 100;
            var error       = new RequestError {
                Code = 12345, Message = "Text", Errors = new[] { new SingleError {
                                                                     Message = "Nested error"
                                                                 } }
            };
            var response = new StandardResponse <object> {
                Error = error
            };
            var responseText = new NewtonsoftJsonSerializer().Serialize(response);

            var handler = new MultipleChunksMessageHandler {
                ErrorResponse = responseText
            };

            handler.StatusCode = HttpStatusCode.BadRequest;
            handler.ChunkSize  = chunkSize;
            // The media downloader adds the parameter...
            handler.DownloadUri = new Uri(downloadUri + "?alt=media");

            using (var service = CreateMockClientService(handler))
            {
                var downloader = new MediaDownloader(service);
                downloader.ChunkSize = chunkSize;
                IList <IDownloadProgress> progressList = new List <IDownloadProgress>();
                downloader.ProgressChanged += (p) =>
                {
                    progressList.Add(p);
                };

                var outputStream = new MemoryStream();
                downloader.Download(downloadUri, outputStream);

                var lastProgress = progressList.LastOrDefault();
                Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                GoogleApiException exception = (GoogleApiException)lastProgress.Exception;
                Assert.That(exception.HttpStatusCode, Is.EqualTo(handler.StatusCode));
                // Just a smattering of checks - if these two pass, it's surely okay.
                Assert.That(exception.Error.Code, Is.EqualTo(error.Code));
                Assert.That(exception.Error.Errors[0].Message, Is.EqualTo(error.Errors[0].Message));
            }
        }
Exemple #27
0
        public static void Configure()
        {
            FlurlHttp.Configure(settings => {
                var jsonSettings = new JsonSerializerSettings
                {
                    ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                    NullValueHandling = NullValueHandling.Ignore,
                    Converters        = new List <Newtonsoft.Json.JsonConverter>
                    {
                        new Newtonsoft.Json.Converters.StringEnumConverter()
                    }
                };

                var serializer = new NewtonsoftJsonSerializer(jsonSettings);

                settings.JsonSerializer = serializer;
            });
        }
Exemple #28
0
        public TwitchAuthHttpService() : base(Constants.TwitchApiUri)
        {
            //placeholder logic check
            string userString = SecureStorage.GetAsync(Constants.AppName).Result;

            if (userString != null)
            {
                List <Account> user_object = JsonConvert.DeserializeObject <List <Account> >(userString);
                CurrentUser = user_object[0];
            }
            else
            {
                CurrentUser = new Account();
                CurrentUser.Properties["access_token"] = "";
            }

            Serializer = new NewtonsoftJsonSerializer();
        }
Exemple #29
0
        public static IEnumerable <object[]> IncorrectValuesForUpdateSuite()
        {
            var moreThanMaxLength = SuiteFactory.GetSuiteModel();

            moreThanMaxLength.Name = RandomUtils.GenerateString(
                Constants.ValidationConstants.Constants.RequestProjectModel.NotesMaxLength + 1);

            var serializedSuite = NewtonsoftJsonSerializer.Serialize(moreThanMaxLength);

            return(new List <object[]>
            {
                new object[]
                {
                    serializedSuite,
                    ErrorMessage.MoreThanMaxValue
                }
            });
        }
        protected BitbucketRestClientBase(Connection connection) : base(connection.ApiUrl)
        {
            Connection = connection;

            var serializer = new NewtonsoftJsonSerializer();

            this.AddHandler("application/json", serializer);
            this.AddHandler("text/json", serializer);
            this.AddHandler("text/plain", serializer);
            this.AddHandler("text/x-json", serializer);
            this.AddHandler("text/javascript", serializer);
            this.AddHandler("*+json", serializer);

            var auth = new Authenticator(connection.Credentials);

            this.Authenticator   = auth.CreatedAuthenticator;
            this.FollowRedirects = false;
        }
        protected YouTrackRestClientBase(Connection connection) : base(connection.ApiUrl)
        {
            Connection = connection;

            var serializer = new NewtonsoftJsonSerializer();

            AddHandler("application/json", serializer);
            AddHandler("text/json", serializer);
            AddHandler("text/plain", serializer);
            AddHandler("text/x-json", serializer);
            AddHandler("text/javascript", serializer);
            AddHandler("*+json", serializer);

            //var auth = new Authenticator(connection.Credentials);
            //Authenticator = auth.CreatedAuthenticator;
            FollowRedirects = false;
            CookieContainer = new CookieContainer();
        }
        public void MessagePack_SerializeAndDeSerialize_ReturnSame()
        {
            // arrange
            var sut    = new NewtonsoftJsonSerializer();
            var actual = new RefTypeObject
            {
                foo     = 1,
                bar     = "test",
                Created = DateTime.UtcNow
            };

            // act
            var bytes    = sut.Serialize(actual);
            var expected = sut.Deserialize <RefTypeObject>(bytes);

            // assert
            Assert.Equal(expected, actual);
        }
        public async Task GetPullRequestsPage_ShouldCallCorrectUrlAndResult()
        {
            var responseJson = Utilities.LoadFile(Paths.GetStandardDataPath("GetPullRequestsPageResponse.json"));
            var responseData = new NewtonsoftJsonSerializer().Deserialize <IteratorBasedPage <PullRequest> >(responseJson);

            var response = MockRepository.GenerateMock <IRestResponse <IteratorBasedPage <PullRequest> > >();

            response.Stub(x => x.Data).Return(responseData);

            var result = _restClient
                         .Capture()
                         .Args <IRestRequest, IRestResponse <IteratorBasedPage <PullRequest> > >(
                (s, req) => s.ExecuteTaskAsync <IteratorBasedPage <PullRequest> >(req), response);

            var resultData = await _sut.GetPullRequestsPage("repoName", "owner", 2);

            Assert.AreEqual(1, result.CallCount);

            var args = result.Args[0];

            Assert.Multiple(() =>
            {
                Assert.AreEqual("repositories/owner/repoName/pullrequests", args.Resource);
                Assert.AreEqual(Method.GET, args.Method);

                var pageLen = args.Parameters.First(x => x.Name == "pagelen").Value;
                var page    = args.Parameters.First(x => x.Name == "page").Value;

                Assert.AreEqual("50", pageLen);
                Assert.AreEqual("2", page);

                Assert.AreEqual(3, resultData.Values.Count);
                Assert.AreEqual(1, resultData.Page);
                Assert.AreEqual(3, resultData.Size);
                Assert.AreEqual(null, resultData.Next);
                Assert.AreEqual(50, resultData.PageLen);

                var firstPq = resultData.Values.First();

                Assert.AreEqual("short description", firstPq.Description);
                Assert.AreEqual("testbranch1122", firstPq.Title);
            });
        }
Exemple #34
0
        public async Task GetPullRequestsPage_ShouldCallCorrectUrlAndResult()
        {
            var responseJson = Utilities.LoadFile(Paths.GetEnterpriseDataPath("GetPullRequestsPageResponse.json"));
            var responseData = new NewtonsoftJsonSerializer().Deserialize <EnterpriseIteratorBasedPage <EnterprisePullRequest> >(responseJson);

            var response = MockRepository.GenerateMock <IRestResponse <EnterpriseIteratorBasedPage <EnterprisePullRequest> > >();

            response.Stub(x => x.Data).Return(responseData);

            var result = _restClient
                         .Capture()
                         .Args <IRestRequest, IRestResponse <EnterpriseIteratorBasedPage <EnterprisePullRequest> > >(
                (s, req) => s.ExecuteTaskAsync <EnterpriseIteratorBasedPage <EnterprisePullRequest> >(req), response);

            var resultData = await _sut.GetPullRequestsPage("repoName", "owner", 2);

            Assert.AreEqual(1, result.CallCount);

            var args = result.Args[0];

            Assert.Multiple(() =>
            {
                Assert.AreEqual("projects/owner/repos/repoName/pull-requests", args.Resource);
                Assert.AreEqual(Method.GET, args.Method);

                var limit = args.Parameters.First(x => x.Name == "limit").Value;
                var start = args.Parameters.First(x => x.Name == "start").Value;

                Assert.AreEqual("50", limit);
                Assert.AreEqual("50", start);

                Assert.AreEqual(5, resultData.Values.Count);
                Assert.AreEqual(0, resultData.Page);
                Assert.AreEqual(5, resultData.Size);
                Assert.AreEqual("0", resultData.Next);
                Assert.AreEqual(null, resultData.PageLen);

                var firstPq = resultData.Values.First();

                Assert.AreEqual("* asd\r\n* asd", firstPq.Description);
                Assert.AreEqual("hhhhhhhhhhhhhhhh", firstPq.Title);
            });
        }
Exemple #35
0
        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);
        }
        protected BitbucketRestClientBase(Connection connection) : base(connection.ApiUrl)
        {
            Connection = connection;

            var serializer = new NewtonsoftJsonSerializer();

            this.ClearHandlers();
            this.AddHandler("application/json", serializer);
            this.AddHandler("text/json", serializer);
            this.AddHandler("text/x-json", serializer);
            this.AddHandler("text/javascript", serializer);
            this.AddHandler("*+json", serializer);

            var auth = new Authenticator(connection.Credentials);

            this.Authenticator   = auth.CreatedAuthenticator;
            this.FollowRedirects = false;
            Proxy = Proxy ?? (WebRequest.DefaultWebProxy ?? WebRequest.GetSystemWebProxy());
        }
Exemple #37
0
        public async Task GetCommitsRange_ShouldCallCorrectUrlAndGetResult()
        {
            var sourceBranch = new Branch()
            {
                Target = new Commit()
                {
                    Hash = "firstHash"
                }
            };
            var destBranch = new Branch()
            {
                Target = new Commit()
                {
                    Hash = "secondHash"
                }
            };

            var responseJson = Utilities.LoadFile(Paths.GetEnterpriseDataPath("GetCommitsRangeResponse.json"));
            var responseData = new NewtonsoftJsonSerializer().Deserialize <EnterpriseIteratorBasedPage <EnterpriseCommit> >(responseJson);

            var result = _restClient
                         .Capture()
                         .Args <string, int, QueryString, IEnumerable <EnterpriseCommit> >((s, url, limit, queryString) => s.GetAllPages <EnterpriseCommit>(url, limit, queryString), responseData.Values);

            var resultData = (await _sut.GetCommitsRange("reponame", "owner", sourceBranch, destBranch)).ToList();

            Assert.AreEqual(1, result.CallCount);

            var args = result.Args[0];

            Assert.Multiple(() =>
            {
                Assert.AreEqual("projects/owner/repos/reponame/commits", args.arg1);
                Assert.AreEqual(50, args.arg2);
                Assert.AreEqual("?until=firstHash&since=secondHash", args.arg3.ToString());

                var firstCommit = resultData[0];

                Assert.AreEqual("short message", firstCommit.Message);
                Assert.AreEqual("28ca84f2acf43e0f935c27d6d96b24e9c09d5fc4", firstCommit.Hash);
            });
        }
Exemple #38
0
        public MasterDataDbGenerator(IUnitOfWorkFactory unitOfWorkFactory, IDbContextFactory dbContextFactory)
        {
            _dbContextFactory = dbContextFactory;

            var dateTimeProvider = new DefaultDateTimeProvider();
            var jsonSerializer   = new NewtonsoftJsonSerializer();

            var classifierTreeRepository = new DbClassifierTreeRepository(dbContextFactory);
            var classifierTypeRepository = new DbClassifierTypeRepository(dbContextFactory);

            var fieldProviderRegistry = new DefaultFieldProviderRegistry();

            fieldProviderRegistry.AddFieldType(typeof(TextField));
            fieldProviderRegistry.AddFieldType(typeof(TextAreaField));

            var dbFieldMetadataRepository = new DbFieldMetadataRepository(dbContextFactory, fieldProviderRegistry, jsonSerializer);
            var dbFieldDataRepository     = new DbFieldDataRepository(dbContextFactory, fieldProviderRegistry);
            var dbFieldMetadataService    = new DbFieldMetadataService(dbContextFactory, dateTimeProvider, jsonSerializer);

            _classifierTypeService           = new DbClassifierTypeService(dbContextFactory, classifierTypeRepository);
            _getClassifierTreeListHandler    = new GetClassifierTreeListHandler(classifierTreeRepository);
            _insertClassifierTreeTypeHandler = new InsertClassifierTreeHandler(unitOfWorkFactory, dbContextFactory, _classifierTypeService);
            _insertClassifierTypeHandler     = new InsertClassifierTypeHandler(unitOfWorkFactory, _classifierTypeService, dbFieldMetadataService);
            _insertClassifierGroupHandler    = new InsertClassifierGroupHandler(unitOfWorkFactory, dbContextFactory, _classifierTypeService);

            _classifierTypeRegistrator = new DefaultClassifierTypeRegistrator(new NullLogger <DefaultClassifierTypeRegistrator>(),
                                                                              unitOfWorkFactory, _classifierTypeService, dbFieldMetadataService);

            var classifierTypeMetadataService = new ClassifierTypeMetadataService(dbFieldMetadataRepository);
            var classifierTreeService         = new DefaultClassifierTreeService(classifierTreeRepository);
            var dbNumberGenerator             = new DbNumberGenerator(dbContextFactory, null, dateTimeProvider, null);

            var classifierRepositoryFactory = new ClassifierRepositoryFactory(new DbClassifierRepository <Classifier>(
                                                                                  dbContextFactory, _classifierTypeService, classifierTreeService,
                                                                                  classifierTypeMetadataService, dbFieldDataRepository, dbNumberGenerator));

            _insertClassifierHandler      = new InsertClassifierHandler(unitOfWorkFactory, classifierRepositoryFactory);
            _updateClassifierGroupHandler = new UpdateClassifierGroupHandler(unitOfWorkFactory, dbContextFactory, _classifierTypeService);
            _deleteClassifierGroupHandler = new DeleteClassifierGroupHandler(unitOfWorkFactory, dbContextFactory, _classifierTypeService);
            _insertClassifierLinkHandler  = new InsertClassifierLinkHandler(unitOfWorkFactory, dbContextFactory, _classifierTypeService);
            _getClassifierLinkListHandler = new GetClassifierLinkListHandler(dbContextFactory, _classifierTypeService);
        }
Exemple #39
0
        public async Task GetCommitsRange_ShouldCallCorrectUrlAndGetResult()
        {
            var sourceBranch = new Branch()
            {
                Name = "sourcebranch", Target = new Commit()
                {
                    Hash = "firstHash"
                }
            };
            var destBranch = new Branch()
            {
                Name = "destBranch", Target = new Commit()
                {
                    Hash = "secondHash"
                }
            };

            var responseJson = Utilities.LoadFile(Paths.GetStandardDataPath("GetCommitsRangeResponse.json"));
            var responseData = new NewtonsoftJsonSerializer().Deserialize <IteratorBasedPage <Commit> >(responseJson);

            var result = _restClient
                         .Capture()
                         .Args <string, int, QueryString, IEnumerable <Commit> >((s, url, limit, queryString) => s.GetAllPages <Commit>(url, limit, queryString), responseData.Values);

            var resultData = (await _sut.GetCommitsRange("reponame", "owner", sourceBranch, destBranch)).ToList();

            Assert.AreEqual(1, result.CallCount);

            var args = result.Args[0];

            Assert.Multiple(() =>
            {
                Assert.AreEqual("repositories/owner/reponame/commits/sourcebranch", args.arg1);
                Assert.AreEqual(50, args.arg2);
                Assert.AreEqual("?exclude=destBranch", args.arg3.ToString());

                var firstCommit = resultData[0];

                Assert.AreEqual("NEWFILE created online with Bitbucket", firstCommit.Message);
                Assert.AreEqual("a35d9f3a6642da77a66674fb77cbb9d4fae3f8c1", firstCommit.Hash);
            });
        }
        public ActionResult Notify()
        {
            Notification notification =
                new NewtonsoftJsonSerializer().Deserialize<Notification>(Request.InputStream);
            String userId = notification.UserToken;
            MirrorService service = new MirrorService(new BaseClientService.Initializer()
            {
                Authenticator = Utils.GetAuthenticatorFromState(Utils.GetStoredCredentials(userId))
            });

            if (notification.Collection == "locations")
            {
                HandleLocationsNotification(notification, service);
            }
            else if (notification.Collection == "timeline")
            {
                HandleTimelineNotification(notification, service);
            }

            return new HttpStatusCodeResult((int)HttpStatusCode.OK);
        }
        /// <summary>
        /// Attemps to discover the server within a local network
        /// </summary>
        public ServerInfo FindServer()
        {
            // Create a udp client
            var client = new UdpClient(new IPEndPoint(IPAddress.Any, GetRandomUnusedPort()));
            client.Client.ReceiveTimeout = 5000;

            // Construct the message the server is expecting
            var bytes = Encoding.UTF8.GetBytes("who is EmbyServer?");

            // Send it - must be IPAddress.Broadcast, 7359
            var targetEndPoint = new IPEndPoint(IPAddress.Broadcast, 7359);

            // Send it
            client.Send(bytes, bytes.Length, targetEndPoint);

            // Get a result back
            try
            {
                var result = client.Receive(ref targetEndPoint);

                // Convert bytes to text
                var json = Encoding.UTF8.GetString(result);

                var info = new NewtonsoftJsonSerializer().DeserializeFromString<ServerDiscoveryInfo>(json);

                return new ServerInfo
                       {
                           Name = info.Name,
                           Id = info.Id,
                           LocalAddress = info.Address
                       };
            }
            catch (Exception exception)
            {
                // We'll return null
            }
            return null;
        }
        /// <summary>
        /// Retrieves the list of APIs of the specified discovery reposistory.
        /// </summary>
        public static IEnumerable<DirectoryList.ItemsData> RetrieveDiscovery(Uri listUri)
        {
            string document = Utils.FetchDocument(listUri);
            var items = new NewtonsoftJsonSerializer().Deserialize<DirectoryList>(document).Items 
                            ?? Enumerable.Empty<DirectoryList.ItemsData>();

            // Make the path references rooted. We do this so that we can use just the ItemsData object
            // to generate an API.
            string basePath = listUri.ToString().Substring(0, listUri.ToString().LastIndexOf('/') + 1);
            foreach (DirectoryList.ItemsData api in items)
            {
                if (api.DiscoveryLink.StartsWith("./"))
                {
                    api.DiscoveryLink = basePath + api.DiscoveryLink.Substring("./".Length);
                }
                else if (api.DiscoveryLink.StartsWith("../"))
                {
                    api.DiscoveryLink = basePath + api.DiscoveryLink;
                }
            }

            return items;
        }
        /// <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));
            }
        }
        internal void RestoreDefaults()
        {
            MaxRetries = 10;

            #if __IOS__
            MaxOpenHttpConnections = 8;
            #else
            MaxOpenHttpConnections = 16;
            #endif

            MaxRevsToGetInBulk = 50;

            RequestTimeout = TimeSpan.FromSeconds(90);

            #if __UNITY__
            CallbackScheduler = Couchbase.Lite.Unity.UnityMainThreadScheduler.TaskScheduler;
            #else
            TaskScheduler scheduler = null;
            try {
                scheduler = TaskScheduler.FromCurrentSynchronizationContext ();
            } catch (InvalidOperationException) {
                // Running in the unit test runner will throw an exception.
                // Just swallow.
            } finally {
                CallbackScheduler =  scheduler ?? TaskScheduler.Current ?? TaskScheduler.Default;
            }
            #endif

            SerializationEngine = new NewtonsoftJsonSerializer();
        }
 static ManagerOptions()
 {
     SerializationEngine = new NewtonsoftJsonSerializer();
     Default = new ManagerOptions();
 }
        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 void Download_Error_JsonResponse()
        {
            var downloadUri = "http://www.sample.com";
            var chunkSize = 100;
            var error = new RequestError { Code = 12345, Message = "Text", Errors = new[] { new SingleError { Message = "Nested error" } } };
            var response = new StandardResponse<object> { Error = error };
            var responseText = new NewtonsoftJsonSerializer().Serialize(response);

            var handler = new MultipleChunksMessageHandler { ErrorResponse = responseText };
            handler.StatusCode = HttpStatusCode.BadRequest;
            handler.ChunkSize = chunkSize;
            // The media downloader adds the parameter...
            handler.DownloadUri = new Uri(downloadUri + "?alt=media");

            using (var service = CreateMockClientService(handler))
            {
                var downloader = new MediaDownloader(service);
                downloader.ChunkSize = chunkSize;
                IList<IDownloadProgress> progressList = new List<IDownloadProgress>();
                downloader.ProgressChanged += (p) =>
                    {
                        progressList.Add(p);
                    };

                var outputStream = new MemoryStream();
                downloader.Download(downloadUri, outputStream);

                var lastProgress = progressList.LastOrDefault();
                Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed));
                GoogleApiException exception = (GoogleApiException) lastProgress.Exception;
                Assert.That(exception.HttpStatusCode, Is.EqualTo(handler.StatusCode));
                // Just a smattering of checks - if these two pass, it's surely okay.
                Assert.That(exception.Error.Code, Is.EqualTo(error.Code));
                Assert.That(exception.Error.Errors[0].Message, Is.EqualTo(error.Errors[0].Message));
            }
        }
            public void CanUsePrivateSetterInFullTrustEnvironment()
            {
                Byte[] json = Encoding.UTF8.GetBytes("{\"$type\":\"Test.Spark.Serialization.UsingNewtonsoftJsonSerializer.WhenDeserializingData+ClassWithPrivateSetter, Spark.Serialization.Newtonsoft.Tests\",\"t\":\"Test String\"}");
                NewtonsoftJsonSerializer serializer = new NewtonsoftJsonSerializer(new DataMemberContractResolver(Enumerable.Empty<JsonConverter>()));
                ClassWithPrivateSetter graph;

                using (var memoryStream = new MemoryStream(json, writable: false))
                {
                    serializer.Serializer.Formatting = Formatting.None;

                    graph = (ClassWithPrivateSetter)serializer.Deserialize(memoryStream, typeof(Object));
                }

                Assert.Equal("Test String", graph.Test);
            }
            public void UseDefaultConstructorWhenSpecified()
            {
                Byte[] json = Encoding.UTF8.GetBytes("{\"$type\":\"Test.Spark.Serialization.UsingNewtonsoftJsonSerializer.WhenDeserializingData+ClassWithDefaultConstructor, Spark.Serialization.Newtonsoft.Tests\",\"test\":\"Test String\"}");
                NewtonsoftJsonSerializer serializer = new NewtonsoftJsonSerializer(new DataMemberContractResolver(Enumerable.Empty<JsonConverter>()));
                ClassWithDefaultConstructor graph;

                using (var memoryStream = new MemoryStream(json, writable: false))
                {
                    serializer.Serializer.Formatting = Formatting.None;

                    graph = (ClassWithDefaultConstructor)serializer.Deserialize(memoryStream, typeof(Object));
                }

                Assert.Equal("Test String", graph.Test);
                Assert.True(graph.DefaultConstructorInvoked);
            }
        /// <summary>
        /// Run a simple HTTP server that listens for a few test URIs.
        /// The server exits when a client requests "/Quit".
        /// </summary>
        /// <param name="prefix">Prefix at which the server should listen</param>
        private async Task RunTestServer(string prefix)
        {
            using (var httpListener = new HttpListener())
            {
                httpListener.Prefixes.Add(prefix);
                httpListener.Start();

                while (httpListener.IsListening)
                {
                    var context = await httpListener.GetContextAsync();

                    var requestUri = context.Request.Url;
                    var response = context.Response;

                    if (requestUri.AbsolutePath.EndsWith("/Quit"))
                    {
                        // Shut down the HTTP server.
                        response.Close();
                        httpListener.Stop();
                        continue;
                    }

                    // All downloader requests should include ?alt=media.
                    Assert.AreEqual("media", context.Request.QueryString["alt"]);

                    response.ContentType = "text/plain";
                    response.SendChunked = true;  // Avoid having to set Content-Length.

                    Stream outStream = new MemoryStream();

                    if (requestUri.AbsolutePath.EndsWith("/EchoUrl"))
                    {
                        // Return the URL that we saw.
                        byte[] uriBytes = Encoding.UTF8.GetBytes(requestUri.AbsoluteUri);
                        outStream.Write(uriBytes, 0, uriBytes.Length);
                    }
                    else if (requestUri.AbsolutePath.EndsWith("/BadRequestJson"))
                    {
                        // Return 400 with a JSON-encoded error.
                        var apiResponse = new StandardResponse<object> { Error = BadRequestError };
                        var apiResponseText = new NewtonsoftJsonSerializer().Serialize(apiResponse);
                        byte[] apiResponseBytes = Encoding.UTF8.GetBytes(apiResponseText);

                        response.StatusCode = (int)HttpStatusCode.BadRequest;
                        outStream.Write(apiResponseBytes, 0, apiResponseBytes.Length);
                    }
                    else if (requestUri.AbsolutePath.EndsWith("/NotFoundPlainText"))
                    {
                        // Return 404 with a plaintext error.
                        response.StatusCode = (int)HttpStatusCode.NotFound;
                        byte[] errorBytes = Encoding.UTF8.GetBytes(NotFoundError);
                        outStream.Write(errorBytes, 0, errorBytes.Length);
                    }
                    else if (requestUri.AbsolutePath.EndsWith("/GzipContent"))
                    {
                        // Return gzip-compressed content.
                        using (var gzipStream = new GZipStream(outStream, CompressionMode.Compress, true))
                        {
                            gzipStream.Write(MediaContent, 0, MediaContent.Length);
                        }
                        response.AddHeader("Content-Encoding", "gzip");
                    }
                    else
                    {
                        // Return plaintext content.
                        outStream.Write(MediaContent, 0, MediaContent.Length);
                    }

                    outStream.Position = 0;

                    // Provide rudimentary, non-robust support for Range.
                    // MediaDownloader doesn't exercise this code anymore, but it was useful for
                    // testing previous implementations that did. It remains for posterity.
                    string rangeHeader = context.Request.Headers["Range"];
                    if (rangeHeader != null && response.StatusCode == (int)HttpStatusCode.OK)
                    {
                        var range = RangeHeaderValue.Parse(rangeHeader);
                        var firstRange = range.Ranges.First();

                        long from = firstRange.From ?? 0;
                        long to = Math.Min(outStream.Length - 1, firstRange.To ?? long.MaxValue);

                        var contentRangeHeader = new ContentRangeHeaderValue(from, to, outStream.Length);
                        response.AddHeader("Content-Range", contentRangeHeader.ToString());

                        outStream.Position = from;
                        outStream.SetLength(to + 1);
                    }

                    await outStream.CopyToAsync(response.OutputStream);

                    response.Close();
                }
            }
        }
Exemple #51
0
        /// <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 ();
        }