Beispiel #1
1
        public void Can_Deserialize_Weight()
        {
            string content = File.ReadAllText(SampleData.PathFor("Weight.txt"));
            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            deserializer.RootElement = "weight";

            Weight result = deserializer.Deserialize<Weight>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Weights.Count == 2);

            WeightLog log = result.Weights[0];
            Assert.AreEqual(log.LogId, 1330991999000);
            Assert.AreEqual(log.Bmi, 23.566633224487305);
            Assert.AreEqual(log.Date, new DateTime(2012, 3, 5));
            Assert.AreEqual(log.Time, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59));
            Assert.AreEqual(log.Weight, 73);
            Assert.AreEqual(log.DateTime, new DateTime(2012, 3, 5, 23, 59, 59));

            log = result.Weights[1];
            Assert.AreEqual(log.LogId, 1330991999000);
            Assert.AreEqual(log.Bmi, 22.566633224487305);
            Assert.AreEqual(log.Date, new DateTime(2012, 3, 5));
            Assert.AreEqual(log.Time, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 21, 10, 59));
            Assert.AreEqual(log.Weight, 72.5);
            Assert.AreEqual(log.DateTime, new DateTime(2012, 3, 5, 21, 10, 59));
        }
Beispiel #2
0
        public void Can_Deserialize_HeartRateResponse()
        {
            string content = File.ReadAllText(SampleData.PathFor("HeartLogResponse.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            deserializer.RootElement = "heartLog";

            HeartRateLog result = deserializer.Deserialize <HeartRateLog>(new RestResponse()
            {
                Content = content
            });

            Assert.IsNotNull(result);

            Assert.AreEqual(150, result.HeartRate);
            Assert.AreEqual(1424, result.LogId);

            var      now      = DateTime.Now;
            DateTime expected = new DateTime(now.Year, now.Month, now.Day, 12, 20, 0);

            Assert.AreEqual(expected, result.Time);

            Assert.AreEqual("Running", result.Tracker);
        }
Beispiel #3
0
        public void Can_Deserialize_Profile()
        {
            string content = File.ReadAllText(SampleData.PathFor("UserProfile.txt"));
            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            deserializer.RootElement = "user";

            UserProfile result = deserializer.Deserialize<UserProfile>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);
            Assert.AreEqual("I live in San Francisco.", result.AboutMe);
            Assert.AreEqual("http://www.fitbit.com/images/profile/defaultProfile_100_male.gif", result.Avatar);
            Assert.AreEqual("San Francisco", result.City);
            Assert.AreEqual("US", result.Country);
            Assert.AreEqual(new DateTime(1971, 2, 18), result.DateOfBirth);
            Assert.AreEqual("Nick", result.Nickname);
            Assert.AreEqual("en_US", result.DistanceUnit);
            Assert.AreEqual("2295YW", result.EncodedId);
            Assert.AreEqual("Fitbit User", result.FullName);
            Assert.AreEqual(Gender.MALE, result.Gender);
            Assert.AreEqual("METRIC", result.GlucoseUnit);
            Assert.AreEqual((double)176.75, result.Height);
            Assert.AreEqual("en_US", result.HeightUnit);
            Assert.AreEqual("en_GB", result.Locale);
            Assert.AreEqual(new DateTime(2010, 2, 7), result.MemberSince);
            Assert.AreEqual("Nick", result.Nickname);
            Assert.AreEqual(-25200000, result.OffsetFromUTCMillis);
            Assert.AreEqual("CA", result.State);
            Assert.AreEqual(0, result.StrideLengthRunning);
            Assert.AreEqual(0, result.StrideLengthWalking);
            Assert.AreEqual("America/Los_Angeles", result.Timezone);
            Assert.AreEqual("METRIC", result.VolumeUnit);
            Assert.AreEqual((double)80.55, result.Weight);
            Assert.AreEqual("METRIC", result.WeightUnit);

        }
Beispiel #4
0
        public static XmlMeta ResponseDeserialization(IRestResponse restResponse)
        {
            RestSharp.Deserializers.XmlDeserializer deserializer = new RestSharp.Deserializers.XmlDeserializer();
            var metaObject = deserializer.Deserialize <XmlMeta>(restResponse);

            return(metaObject);
        }
Beispiel #5
0
        public void Can_Deserialize_Devices_Single()
        {
            string content      = File.ReadAllText(SampleData.PathFor("GetDevices-Single.txt"));
            var    deserializer = new RestSharp.Deserializers.XmlDeserializer();

            List <Device> result = deserializer.Deserialize <List <Device> >(new RestResponse()
            {
                Content = content
            });

            Assert.IsNotNull(result);


            Assert.IsTrue(result.Count == 1);

            /*
             * Assert.AreEqual("Full", result[0].Battery);
             * Assert.AreEqual("123456", result[0].Id);
             * //TODO: compare the date
             *
             * Assert.AreEqual("TRACKER", result[0].Type);
             * Assert.AreEqual("Ultra", result[0].DeviceVersion);
             */

            Assert.AreEqual("Medium", result[0].Battery);
            Assert.AreEqual("473384", result[0].Id);
            //TODO: compare the date

            Assert.AreEqual(DeviceType.Tracker, result[0].Type);
            Assert.AreEqual("Ultra", result[0].DeviceVersion);
        }
Beispiel #6
0
        public void Can_Deserialize_Weight()
        {
            string content      = File.ReadAllText(SampleData.PathFor("Weight.txt"));
            var    deserializer = new RestSharp.Deserializers.XmlDeserializer();

            deserializer.RootElement = "weight";

            Weight result = deserializer.Deserialize <Weight>(new RestResponse()
            {
                Content = content
            });

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Weights.Count == 2);

            WeightLog log = result.Weights[0];

            Assert.AreEqual(log.LogId, 1330991999000);
            Assert.AreEqual(log.Bmi, 23.566633224487305);
            Assert.AreEqual(log.Date, new DateTime(2012, 3, 5));
            Assert.AreEqual(log.Time, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59));
            Assert.AreEqual(log.Weight, 73);
            Assert.AreEqual(log.DateTime, new DateTime(2012, 3, 5, 23, 59, 59));

            log = result.Weights[1];
            Assert.AreEqual(log.LogId, 1330991999000);
            Assert.AreEqual(log.Bmi, 22.566633224487305);
            Assert.AreEqual(log.Date, new DateTime(2012, 3, 5));
            Assert.AreEqual(log.Time, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 21, 10, 59));
            Assert.AreEqual(log.Weight, 72.5);
            Assert.AreEqual(log.DateTime, new DateTime(2012, 3, 5, 21, 10, 59));
        }
Beispiel #7
0
        public void Can_Deserialize_IntradayActivitiesCalories()
        {
            string content = File.ReadAllText(SampleData.PathFor("IntradayActivitiesCalories.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            //var deserializer = new RestSharp.Deserializers.JsonDeserializer();
            deserializer.DateFormat = "HH:mm:ss";
            //TimeSeriesResourceType type = TimeSeriesResourceType.Steps.GetRootElement();

            //deserializer.RootElement = "dataset";
            deserializer.RootElement = "activities-log-calories-intraday";

            IntradayData result = deserializer.Deserialize <IntradayData>(new RestResponse()
            {
                Content = content
            });

            //var result = deserializer.Deserialize<dynamic>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);

            Assert.AreEqual(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day), result.DataSet[0].Time);
            Assert.AreEqual("1.3125", result.DataSet[0].Value);
            Assert.AreEqual("0", result.DataSet[0].Level);

            Assert.AreEqual(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 1, 0), result.DataSet[1].Time);
            Assert.AreEqual("1.3125", result.DataSet[1].Value);
            Assert.AreEqual("1", result.DataSet[1].Level);

            //Assert.AreEqual(1440, result.DataSet.Count);

            //Assert.AreEqual(8, result.Count);
        }
Beispiel #8
0
        public void Can_Deserialize_Fat()
        {
            string content = File.ReadAllText(SampleData.PathFor("Fat.txt"));
            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            deserializer.RootElement = "fat";

            Fat result = deserializer.Deserialize<Fat>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);
            Assert.IsTrue(result.FatLogs.Count == 2);

            FatLog log = result.FatLogs[0];
            Assert.AreEqual(log.LogId, 1330991999000);
            Assert.AreEqual(log.Date, new DateTime(2012, 3, 5));
            Assert.AreEqual(log.Time, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59));
            Assert.AreEqual(log.Fat, 14);
            Assert.AreEqual(log.DateTime, new DateTime(2012, 3, 5, 23, 59, 59));

            log = result.FatLogs[1];
            Assert.AreEqual(log.LogId, 1330991999000);
            Assert.AreEqual(log.Date, new DateTime(2012, 3, 5));
            Assert.AreEqual(log.Time, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 21, 20, 59));
            Assert.AreEqual(log.Fat, 13.5);
            Assert.AreEqual(log.DateTime, new DateTime(2012, 3, 5, 21, 20, 59));
        }
Beispiel #9
0
        public void Can_Deserialize_Devices_Double()
        {
            string content      = File.ReadAllText(SampleData.PathFor("GetDevices-Double.txt"));
            var    deserializer = new RestSharp.Deserializers.XmlDeserializer();

            List <Device> result = deserializer.Deserialize <List <Device> >(new RestResponse()
            {
                Content = content
            });

            Assert.IsNotNull(result);


            Assert.IsTrue(result.Count == 2);
            Assert.AreEqual("Full", result[0].Battery);
            Assert.AreEqual("123456", result[0].Id);
            //test date
            //Assert.AreEqual("TRACKER", result[0].Type);
            Assert.AreEqual(DeviceType.Tracker, result[0].Type);

            Assert.AreEqual("Ultra", result[0].DeviceVersion);

            Assert.AreEqual("High", result[1].Battery);
            //test date
            Assert.AreEqual("987654", result[1].Id);
            Assert.AreEqual(DeviceType.Scale, result[1].Type);
            Assert.AreEqual("Aria", result[1].DeviceVersion);

            //TODO: More tests of the data objects coming in
        }
Beispiel #10
0
        public void Can_Deserialize_TimeSeriesActivitiesStepsInt()
        {
            string content = File.ReadAllText(SampleData.PathFor("TimeSeriesActivitiesSteps.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            //var deserializer = new RestSharp.Deserializers.JsonDeserializer();

            //TimeSeriesResourceType type = TimeSeriesResourceType.Steps.GetRootElement();

            deserializer.RootElement = "activities-steps";


            List <TimeSeriesDataListInt.Data> result = deserializer.Deserialize <List <TimeSeriesDataListInt.Data> >(new RestResponse()
            {
                Content = content
            });

            Assert.IsNotNull(result);

            Assert.AreEqual(new DateTime(2012, 5, 19), result[0].DateTime);
            Assert.AreEqual(11546, result[0].Value);

            Assert.AreEqual(8, result.Count);
        }
Beispiel #11
0
        /// <summary>
        /// This fetches a dimension's related data.
        /// </summary>
        /// <returns>List of RestrictedData objects.</returns>
        public List <RestrictedData> GetDimensionRestrictedData(IntacctModel model)
        {
            string cacheKey             = INTACCT_CACHE_PREFIX + model.GetType().Name.ToUpper() + "_" + model.Id;
            List <RestrictedData> items = RockCache.Get(cacheKey) as List <RestrictedData>;

            if (items == null)
            {
                var request = GetRequest();
                var getDimensionRestrictedData = new GetDimensionRestrictedData();
                getDimensionRestrictedData.Function.DimensionValue.Dimension = model.GetType().Name.ToUpper();
                getDimensionRestrictedData.Function.DimensionValue.Value     = model.ApiId;
                request.Operation.Content.Function = getDimensionRestrictedData;

                var restRequest = new RestRequest("", Method.POST);
                restRequest.AddHeader("Content-Type", "application/xml");
                restRequest.RequestFormat = DataFormat.Xml;
                restRequest.AddBody(request);

                var response = client.Execute <List <RestrictedData> >(restRequest);

                var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer();
                var responseObj     = xmlDeserializer.Deserialize <Response>(response);
                if (responseObj?.Operation?.Result?.Status != "success" && !string.IsNullOrWhiteSpace(responseObj?.ErrorMessage?.Error?.Description))
                {
                    CheckResponse(response);
                }

                items = response.Data;

                RockCache.AddOrUpdate(cacheKey, items);
            }
            return(items);
        }
Beispiel #12
0
        private bool CreateKanbanizeTask(Backlogitem backlogitem)
        {
            KanbanizeTaskList kanbanizeTasks = new KanbanizeTaskList();
            KanbasID          kanbasID       = new KanbasID();

            backlogitem = VariableFitter(backlogitem);
            if (backlogitem.status == "arkiv")
            {
                return(true);
            }
            RestClient  client  = new RestClient(_apiurl);
            RestRequest request = new RestRequest("create_new_task", Method.POST);

            request.AddHeader(_apiKey, _apiKeyValue);
            request.AddJsonBody(new
            {
                boardid     = _boardID,
                column      = backlogitem.status,
                lane        = _lane,
                priority    = backlogitem.priority,
                type        = backlogitem.type,
                title       = backlogitem.name,
                description = backlogitem.description
            });

            var response        = client.Post(request);
            var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer();

            kanbasID = xmlDeserializer.Deserialize <KanbasID>(response);
            backlogitem.externalID = kanbasID.id;
            _scrumwiseConnection.setBacklogItemExternalID(backlogitem);
            //Scrum.API.UpdateExternalID(backlogITem.ExternalID)
            return(true);
        }
Beispiel #13
0
 public Response <T> HandleResponse <T>(IRestResponse response)
 {
     if (response.StatusCode == HttpStatusCode.NotAcceptable || response.StatusCode.ToString() == "422")
     {
         RestSharp.Deserializers.DotNetXmlDeserializer deserial = new RestSharp.Deserializers.DotNetXmlDeserializer();
         try
         {
             var errors = deserial.Deserialize <ErrorsResponse>(response);
             return(new Response <T>(default(T), errors, response.StatusCode));
         }
         catch (Exception ex)
         {
             var error = new ErrorsResponse(); error.Errors.Add("DESERALIZE EXCEPTION!");
             return(new Response <T>(default(T), error, response.StatusCode));
         }
     }
     else if (response.StatusCode == HttpStatusCode.OK)
     {
         RestSharp.Deserializers.XmlDeserializer deserial = new RestSharp.Deserializers.XmlDeserializer();
         var deserialResponse = deserial.Deserialize <T>(response);
         return(new Response <T>(deserialResponse, null, response.StatusCode));
     }
     //TODO:HANDLE INTERNAL SERVER ERROR, REPRODUCED BY SETTING WRONG AUTHENTICTY TOKEN
     return(new Response <T>(default(T), null, response.StatusCode));
 }
Beispiel #14
0
        public void Can_Deserialize_Fat()
        {
            string content      = File.ReadAllText(SampleData.PathFor("Fat.txt"));
            var    deserializer = new RestSharp.Deserializers.XmlDeserializer();

            deserializer.RootElement = "fat";

            Fat result = deserializer.Deserialize <Fat>(new RestResponse()
            {
                Content = content
            });

            Assert.IsNotNull(result);
            Assert.IsTrue(result.FatLogs.Count == 2);

            FatLog log = result.FatLogs[0];

            Assert.AreEqual(log.LogId, 1330991999000);
            Assert.AreEqual(log.Date, new DateTime(2012, 3, 5));
            Assert.AreEqual(log.Time, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59));
            Assert.AreEqual(log.Fat, 14);
            Assert.AreEqual(log.DateTime, new DateTime(2012, 3, 5, 23, 59, 59));

            log = result.FatLogs[1];
            Assert.AreEqual(log.LogId, 1330991999000);
            Assert.AreEqual(log.Date, new DateTime(2012, 3, 5));
            Assert.AreEqual(log.Time, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 21, 20, 59));
            Assert.AreEqual(log.Fat, 13.5);
            Assert.AreEqual(log.DateTime, new DateTime(2012, 3, 5, 21, 20, 59));
        }
Beispiel #15
0
        public void Can_Deserialize_Api_Subscription_List()
        {
            string content = File.ReadAllText(SampleData.PathFor("ListApiSubscriptions.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            //var deserializer = new RestSharp.Deserializers.JsonDeserializer();
            //deserializer.DateFormat = "HH:mm:ss";
            //TimeSeriesResourceType type = TimeSeriesResourceType.Steps.GetRootElement();

            //deserializer.RootElement = "dataset";
            //deserializer.RootElement = "updates";

            List <ApiSubscription> result = deserializer.Deserialize <List <ApiSubscription> >(new RestResponse()
            {
                Content = content
            });

            //var result = deserializer.Deserialize<dynamic>(new RestResponse() { Content = content });

            Assert.AreEqual(1, result.Count);
            Assert.AreEqual(APICollectionType.user, result[0].CollectionType);
            Assert.AreEqual("227YZL", result[0].OwnerId);
            Assert.AreEqual("1", result[0].SubscriberId);
            Assert.AreEqual("323", result[0].SubscriptionId);
        }
Beispiel #16
0
        public void Can_Deserialize_Friends()
        {
            string content      = File.ReadAllText(SampleData.PathFor("GetFriends.txt"));
            var    deserializer = new RestSharp.Deserializers.XmlDeserializer();

            deserializer.RootElement = "friends";

            List <Friend> result = deserializer.Deserialize <List <Friend> >(new RestResponse()
            {
                Content = content
            });

            Assert.IsNotNull(result);

            List <UserProfile> userProfiles = new List <UserProfile>();

            foreach (Friend friend in result)
            {
                userProfiles.Add(friend.User);
            }

            Assert.IsTrue(userProfiles.Count == 4);
            Assert.AreEqual("User A.", userProfiles[0].DisplayName);

            //TODO: More tests of the data objects coming in
        }
		public void CatBrowseDeserializationTest()
		{
			const string content =
				"<aws:CategoryBrowseResponse xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:Response xmlns:aws='http://awis.amazonaws.com/doc/2005-07-11'><aws:OperationRequest><aws:RequestId>cadde770-fe83-483c-9bcc-465a77d4ea0c</aws:RequestId></aws:OperationRequest><aws:CategoryBrowseResult><aws:Alexa><aws:CategoryBrowse><aws:Categories><aws:Category><aws:Path>Top/Business/Consumer_Goods_and_Services/Electronics/Accessories</aws:Path><aws:Title>Accessories</aws:Title><aws:SubCategoryCount>2</aws:SubCategoryCount><aws:TotalListingCount>186</aws:TotalListingCount></aws:Category><aws:Category><aws:Path>Top/Business/Consumer_Goods_and_Services/Electronics/Audio</aws:Path><aws:Title>Audio</aws:Title><aws:SubCategoryCount>8</aws:SubCategoryCount><aws:TotalListingCount>1135</aws:TotalListingCount></aws:Category></aws:Categories><aws:LetterBars/></aws:CategoryBrowse></aws:Alexa></aws:CategoryBrowseResult><aws:ResponseStatus xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:CategoryBrowseResponse>";
			var xml = new RestSharp.Deserializers.XmlDeserializer();
			var output = xml.Deserialize<CategoryBrowseResponse>(new RestResponse { Content = content });
			Assert.AreEqual(186, output.CategoryBrowseResult.Alexa.CategoryBrowse.Categories[0].TotalListingCount);
		}
		public void SitesDeserializationTest()
		{
			const string content =
				"<aws:SitesLinkingInResponse xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:Response xmlns:aws='http://awis.amazonaws.com/doc/2005-07-11'><aws:OperationRequest><aws:RequestId>08876c86-2c4d-bc5a-108f-ca30d1cf70b7</aws:RequestId></aws:OperationRequest><aws:SitesLinkingInResult><aws:Alexa><aws:SitesLinkingIn><aws:Site><aws:Title>google.com</aws:Title><aws:Url>ibm-pc.com:80</aws:Url></aws:Site><aws:Site><aws:Title>linkedin.com</aws:Title><aws:Url>blog.linkedin.com:80/2007/09/27/a-pictures-wort</aws:Url></aws:Site></aws:SitesLinkingIn></aws:Alexa></aws:SitesLinkingInResult><aws:ResponseStatus xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:SitesLinkingInResponse>";
			var xml = new RestSharp.Deserializers.XmlDeserializer();
			var output = xml.Deserialize<SitesLinkingInResponse>(new RestResponse { Content = content });
			Assert.AreEqual("linkedin.com", output.SitesLinkingInResult.Alexa.SitesLinkingIn.Sites[1].Title);
		}
		public void CatListingsDeserializationTest()
		{
			const string content =
				"<aws:CategoryListingsResponse xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:Response xmlns:aws='http://awis.amazonaws.com/doc/2005-07-11'><aws:OperationRequest><aws:RequestId>0bf0a4b0-a441-49e7-9cfe-44b71e0df086</aws:RequestId></aws:OperationRequest><aws:CategoryListingsResult><aws:Alexa><aws:CategoryListings><aws:RecursiveCount>1804</aws:RecursiveCount><aws:Count>217</aws:Count><aws:Listings><aws:Listing><aws:DataUrl type='navigable'>http://www.sony.com</aws:DataUrl><aws:Title>Sony Electronics</aws:Title><aws:PopularityRank>882</aws:PopularityRank></aws:Listing><aws:Listing><aws:DataUrl type='navigable'>http://www.samsung.com/</aws:DataUrl><aws:Title>Samsung Electronics</aws:Title><aws:PopularityRank>899</aws:PopularityRank></aws:Listing></aws:Listings></aws:CategoryListings></aws:Alexa></aws:CategoryListingsResult><aws:ResponseStatus xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:CategoryListingsResponse>";
			var xml = new RestSharp.Deserializers.XmlDeserializer();
			var output = xml.Deserialize<CategoryListingsResponse>(new RestResponse { Content = content });
			Assert.AreEqual(882, output.CategoryListingsResult.Alexa.CategoryListings.Listings[0].PopularityRank);
		}
Beispiel #20
0
        public void Can_Deserialize_Food()
        {
            string content      = File.ReadAllText(SampleData.PathFor("Food.txt"));
            var    deserializer = new RestSharp.Deserializers.XmlDeserializer();

            Food result = deserializer.Deserialize <Food>(new RestResponse()
            {
                Content = content
            });

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Foods);
            Assert.IsNotNull(result.Goals);
            Assert.IsNotNull(result.Summary);

            Assert.IsTrue(result.Foods.Count == 1);
            FoodLog food = result.Foods[0];

            Assert.IsTrue(food.IsFavorite);
            Assert.AreEqual(food.LogDate, new DateTime(2011, 06, 29));
            Assert.AreEqual(food.LogId, 1924);

            Assert.IsNotNull(food.LoggedFood);
            LoggedFood logged = food.LoggedFood;

            Assert.AreEqual(logged.AccessLevel, "PUBLIC");
            Assert.AreEqual(logged.Amount, 132.57f);
            Assert.IsNull(logged.Brand);
            Assert.AreEqual(logged.Calories, 752);
            Assert.AreEqual(logged.FoodId, 18828);
            Assert.AreEqual(logged.MealTypeId, 4);
            Assert.AreEqual(logged.Locale, "en_US");
            Assert.AreEqual(logged.Name, "Chocolate, Milk");

            Assert.IsNotNull(food.NutritionalValues);
            NutritionalValues values = food.NutritionalValues;

            Assert.AreEqual(values.Calories, 752);
            Assert.AreEqual(values.Carbs, 66.5);
            Assert.AreEqual(values.Fat, 49);
            Assert.AreEqual(values.Fiber, .5);
            Assert.AreEqual(values.Protein, 12.5);
            Assert.AreEqual(values.Sodium, 186);

            FoodSummary summary = result.Summary;

            Assert.AreEqual(summary.Calories, 752);
            Assert.AreEqual(summary.Carbs, 66.5);
            Assert.AreEqual(summary.Fat, 49);
            Assert.AreEqual(summary.Fiber, .5);
            Assert.AreEqual(summary.Protein, 12.5);
            Assert.AreEqual(summary.Sodium, 186);
            Assert.AreEqual(summary.Water, 0);

            FoodGoals goals = result.Goals;

            Assert.AreEqual(goals.Calories, 2286);
        }
		public void UrlInfoDeserializationTest()
		{
			const string content =
				"<aws:UrlInfoResponse xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:Response xmlns:aws='http://awis.amazonaws.com/doc/2005-07-11'><aws:OperationRequest><aws:RequestId>5486794a-0d03-4d47-a45b-e95764c3f0ee</aws:RequestId></aws:OperationRequest><aws:UrlInfoResult><aws:Alexa><aws:ContentData><aws:DataUrl type='canonical'>yahoo.com/</aws:DataUrl><aws:Asin>B00006D2TC</aws:Asin><aws:SiteData><aws:Title>Yahoo!</aws:Title><aws:Description>Personalized content and search options. Chatrooms, free e-mail, clubs, and pager.</aws:Description><aws:OnlineSince>18-Jan-1995</aws:OnlineSince></aws:SiteData><aws:Speed><aws:MedianLoadTime>2242</aws:MedianLoadTime><aws:Percentile>51</aws:Percentile></aws:Speed><aws:AdultContent>no</aws:AdultContent><aws:Language><aws:Locale>en</aws:Locale></aws:Language><aws:LinksInCount>76894</aws:LinksInCount><aws:OwnedDomains><aws:OwnedDomain><aws:Domain>yahooligans.com</aws:Domain><aws:Title>yahooligans.com</aws:Title></aws:OwnedDomain></aws:OwnedDomains></aws:ContentData><aws:Related><aws:DataUrl type='canonical'>yahoo.com/</aws:DataUrl><aws:Asin>B00006D2TC</aws:Asin><aws:RelatedLinks><aws:RelatedLink><aws:DataUrl type='canonical'>aol.com/</aws:DataUrl><aws:NavigableUrl>http://aol.com/</aws:NavigableUrl><aws:Asin>B00006ARD3</aws:Asin><aws:Relevance>301</aws:Relevance></aws:RelatedLink></aws:RelatedLinks><aws:Categories><aws:CategoryData><aws:Title>On the Web/Web Portals</aws:Title><aws:AbsolutePath>Top/Computers/Internet/On_the_Web/Web_Portals</aws:AbsolutePath></aws:CategoryData></aws:Categories></aws:Related><aws:TrafficData><aws:DataUrl type='canonical'>yahoo.com/</aws:DataUrl><aws:Asin>B00006D2TC</aws:Asin><aws:Rank>1</aws:Rank><aws:UsageStatistics><aws:UsageStatistic><aws:TimeRange><aws:Days>1</aws:Days></aws:TimeRange><aws:Rank><aws:Value>1</aws:Value><aws:Delta>+0</aws:Delta></aws:Rank><aws:Reach><aws:Rank><aws:Value>2</aws:Value><aws:Delta>+0</aws:Delta></aws:Rank><aws:PerMillion><aws:Value>252,500</aws:Value><aws:Delta>-1%</aws:Delta></aws:PerMillion></aws:Reach><aws:PageViews><aws:PerMillion><aws:Value>51,400</aws:Value><aws:Delta>-1%</aws:Delta></aws:PerMillion><aws:Rank><aws:Value>1</aws:Value><aws:Delta>+0</aws:Delta></aws:Rank><aws:PerUser><aws:Value>13.7</aws:Value><aws:Delta>-1%</aws:Delta></aws:PerUser></aws:PageViews></aws:UsageStatistic></aws:UsageStatistics></aws:TrafficData></aws:Alexa></aws:UrlInfoResult><aws:ResponseStatus xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:UrlInfoResponse>";
			var xml = new RestSharp.Deserializers.XmlDeserializer();
			//xml.DateFormat = "yyyy-MM-dd";
			var output = xml.Deserialize<UrlInfoResponse>(new RestResponse { Content = content });
			Assert.AreEqual("B00006D2TC", output.UrlInfoResult.Alexa.ContentData.Asin);
		}
        public List<UpdatedResource> ProcessUpdateReponseBody(string bodyContent)
        {
            bodyContent = StripSignatureString(bodyContent);

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            List<UpdatedResource> result = deserializer.Deserialize<List<UpdatedResource>>(new RestResponse() { Content = bodyContent });

            return result;
        }
		public void TrafficHistoryDeserializationTest()
		{
			const string content =
				"<aws:TrafficHistoryResponse xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:Response xmlns:aws='http://awis.amazonaws.com/doc/2005-07-11'><aws:OperationRequest><aws:RequestId>39ab4736-ec1a-492d-924b-d0d768d2692d</aws:RequestId></aws:OperationRequest><aws:TrafficHistoryResult><aws:Alexa><aws:TrafficHistory><aws:Range>31</aws:Range><aws:Site>amazon.com</aws:Site><aws:Start>2005-01-01</aws:Start><aws:HistoricalData><aws:Data><aws:Date>2005-01-01</aws:Date><aws:PageViews><aws:PerMillion>2801</aws:PerMillion><aws:PerUser>5.0</aws:PerUser></aws:PageViews><aws:Rank>18</aws:Rank><aws:Reach><aws:PerMillion>26041</aws:PerMillion></aws:Reach></aws:Data></aws:HistoricalData></aws:TrafficHistory></aws:Alexa></aws:TrafficHistoryResult><aws:ResponseStatus xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:TrafficHistoryResponse>";
			var xml = new RestSharp.Deserializers.XmlDeserializer();
			//xml.DateFormat = "yyyy-MM-dd";
			var output = xml.Deserialize<TrafficHistoryResponse>(new RestResponse { Content = content });
			Assert.AreEqual(2801, output.TrafficHistoryResult.Alexa.
				TrafficHistory.HistoricalData.Datas[0].PageViews.PerMillion);
		}
Beispiel #24
0
        public void SitesDeserializationTest()
        {
            const string content =
                "<aws:SitesLinkingInResponse xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:Response xmlns:aws='http://awis.amazonaws.com/doc/2005-07-11'><aws:OperationRequest><aws:RequestId>08876c86-2c4d-bc5a-108f-ca30d1cf70b7</aws:RequestId></aws:OperationRequest><aws:SitesLinkingInResult><aws:Alexa><aws:SitesLinkingIn><aws:Site><aws:Title>google.com</aws:Title><aws:Url>ibm-pc.com:80</aws:Url></aws:Site><aws:Site><aws:Title>linkedin.com</aws:Title><aws:Url>blog.linkedin.com:80/2007/09/27/a-pictures-wort</aws:Url></aws:Site></aws:SitesLinkingIn></aws:Alexa></aws:SitesLinkingInResult><aws:ResponseStatus xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:SitesLinkingInResponse>";
            var xml    = new RestSharp.Deserializers.XmlDeserializer();
            var output = xml.Deserialize <SitesLinkingInResponse>(new RestResponse {
                Content = content
            });

            Assert.AreEqual("linkedin.com", output.SitesLinkingInResult.Alexa.SitesLinkingIn.Sites[1].Title);
        }
Beispiel #25
0
        public void CatListingsDeserializationTest()
        {
            const string content =
                "<aws:CategoryListingsResponse xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:Response xmlns:aws='http://awis.amazonaws.com/doc/2005-07-11'><aws:OperationRequest><aws:RequestId>0bf0a4b0-a441-49e7-9cfe-44b71e0df086</aws:RequestId></aws:OperationRequest><aws:CategoryListingsResult><aws:Alexa><aws:CategoryListings><aws:RecursiveCount>1804</aws:RecursiveCount><aws:Count>217</aws:Count><aws:Listings><aws:Listing><aws:DataUrl type='navigable'>http://www.sony.com</aws:DataUrl><aws:Title>Sony Electronics</aws:Title><aws:PopularityRank>882</aws:PopularityRank></aws:Listing><aws:Listing><aws:DataUrl type='navigable'>http://www.samsung.com/</aws:DataUrl><aws:Title>Samsung Electronics</aws:Title><aws:PopularityRank>899</aws:PopularityRank></aws:Listing></aws:Listings></aws:CategoryListings></aws:Alexa></aws:CategoryListingsResult><aws:ResponseStatus xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:CategoryListingsResponse>";
            var xml    = new RestSharp.Deserializers.XmlDeserializer();
            var output = xml.Deserialize <CategoryListingsResponse>(new RestResponse {
                Content = content
            });

            Assert.AreEqual(882, output.CategoryListingsResult.Alexa.CategoryListings.Listings[0].PopularityRank);
        }
Beispiel #26
0
        public void CatBrowseDeserializationTest()
        {
            const string content =
                "<aws:CategoryBrowseResponse xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:Response xmlns:aws='http://awis.amazonaws.com/doc/2005-07-11'><aws:OperationRequest><aws:RequestId>cadde770-fe83-483c-9bcc-465a77d4ea0c</aws:RequestId></aws:OperationRequest><aws:CategoryBrowseResult><aws:Alexa><aws:CategoryBrowse><aws:Categories><aws:Category><aws:Path>Top/Business/Consumer_Goods_and_Services/Electronics/Accessories</aws:Path><aws:Title>Accessories</aws:Title><aws:SubCategoryCount>2</aws:SubCategoryCount><aws:TotalListingCount>186</aws:TotalListingCount></aws:Category><aws:Category><aws:Path>Top/Business/Consumer_Goods_and_Services/Electronics/Audio</aws:Path><aws:Title>Audio</aws:Title><aws:SubCategoryCount>8</aws:SubCategoryCount><aws:TotalListingCount>1135</aws:TotalListingCount></aws:Category></aws:Categories><aws:LetterBars/></aws:CategoryBrowse></aws:Alexa></aws:CategoryBrowseResult><aws:ResponseStatus xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:CategoryBrowseResponse>";
            var xml    = new RestSharp.Deserializers.XmlDeserializer();
            var output = xml.Deserialize <CategoryBrowseResponse>(new RestResponse {
                Content = content
            });

            Assert.AreEqual(186, output.CategoryBrowseResult.Alexa.CategoryBrowse.Categories[0].TotalListingCount);
        }
Beispiel #27
0
        public void UrlInfoDeserializationTest()
        {
            const string content =
                "<aws:UrlInfoResponse xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:Response xmlns:aws='http://awis.amazonaws.com/doc/2005-07-11'><aws:OperationRequest><aws:RequestId>5486794a-0d03-4d47-a45b-e95764c3f0ee</aws:RequestId></aws:OperationRequest><aws:UrlInfoResult><aws:Alexa><aws:ContentData><aws:DataUrl type='canonical'>yahoo.com/</aws:DataUrl><aws:Asin>B00006D2TC</aws:Asin><aws:SiteData><aws:Title>Yahoo!</aws:Title><aws:Description>Personalized content and search options. Chatrooms, free e-mail, clubs, and pager.</aws:Description><aws:OnlineSince>18-Jan-1995</aws:OnlineSince></aws:SiteData><aws:Speed><aws:MedianLoadTime>2242</aws:MedianLoadTime><aws:Percentile>51</aws:Percentile></aws:Speed><aws:AdultContent>no</aws:AdultContent><aws:Language><aws:Locale>en</aws:Locale></aws:Language><aws:LinksInCount>76894</aws:LinksInCount><aws:OwnedDomains><aws:OwnedDomain><aws:Domain>yahooligans.com</aws:Domain><aws:Title>yahooligans.com</aws:Title></aws:OwnedDomain></aws:OwnedDomains></aws:ContentData><aws:Related><aws:DataUrl type='canonical'>yahoo.com/</aws:DataUrl><aws:Asin>B00006D2TC</aws:Asin><aws:RelatedLinks><aws:RelatedLink><aws:DataUrl type='canonical'>aol.com/</aws:DataUrl><aws:NavigableUrl>http://aol.com/</aws:NavigableUrl><aws:Asin>B00006ARD3</aws:Asin><aws:Relevance>301</aws:Relevance></aws:RelatedLink></aws:RelatedLinks><aws:Categories><aws:CategoryData><aws:Title>On the Web/Web Portals</aws:Title><aws:AbsolutePath>Top/Computers/Internet/On_the_Web/Web_Portals</aws:AbsolutePath></aws:CategoryData></aws:Categories></aws:Related><aws:TrafficData><aws:DataUrl type='canonical'>yahoo.com/</aws:DataUrl><aws:Asin>B00006D2TC</aws:Asin><aws:Rank>1</aws:Rank><aws:UsageStatistics><aws:UsageStatistic><aws:TimeRange><aws:Days>1</aws:Days></aws:TimeRange><aws:Rank><aws:Value>1</aws:Value><aws:Delta>+0</aws:Delta></aws:Rank><aws:Reach><aws:Rank><aws:Value>2</aws:Value><aws:Delta>+0</aws:Delta></aws:Rank><aws:PerMillion><aws:Value>252,500</aws:Value><aws:Delta>-1%</aws:Delta></aws:PerMillion></aws:Reach><aws:PageViews><aws:PerMillion><aws:Value>51,400</aws:Value><aws:Delta>-1%</aws:Delta></aws:PerMillion><aws:Rank><aws:Value>1</aws:Value><aws:Delta>+0</aws:Delta></aws:Rank><aws:PerUser><aws:Value>13.7</aws:Value><aws:Delta>-1%</aws:Delta></aws:PerUser></aws:PageViews></aws:UsageStatistic></aws:UsageStatistics></aws:TrafficData></aws:Alexa></aws:UrlInfoResult><aws:ResponseStatus xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:UrlInfoResponse>";
            var xml = new RestSharp.Deserializers.XmlDeserializer();
            //xml.DateFormat = "yyyy-MM-dd";
            var output = xml.Deserialize <UrlInfoResponse>(new RestResponse {
                Content = content
            });

            Assert.AreEqual("B00006D2TC", output.UrlInfoResult.Alexa.ContentData.Asin);
        }
Beispiel #28
0
        public KanbanizeTaskList GetKanbanizeTasks()
        {
            KanbanizeTaskList kanbanizeTasks = new KanbanizeTaskList();
            RestClient        client         = new RestClient(_apiurl);
            RestRequest       request        = new RestRequest("/get_all_tasks", Method.POST);

            request.AddHeader(_apiKey, _apiKeyValue);
            request.AddJsonBody(new { boardid = _boardID, lane = _lane });
            var response        = client.Post(request);
            var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer();

            return(kanbanizeTasks = xmlDeserializer.Deserialize <KanbanizeTaskList>(response));
        }
Beispiel #29
0
        public void TrafficHistoryDeserializationTest()
        {
            const string content =
                "<aws:TrafficHistoryResponse xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:Response xmlns:aws='http://awis.amazonaws.com/doc/2005-07-11'><aws:OperationRequest><aws:RequestId>39ab4736-ec1a-492d-924b-d0d768d2692d</aws:RequestId></aws:OperationRequest><aws:TrafficHistoryResult><aws:Alexa><aws:TrafficHistory><aws:Range>31</aws:Range><aws:Site>amazon.com</aws:Site><aws:Start>2005-01-01</aws:Start><aws:HistoricalData><aws:Data><aws:Date>2005-01-01</aws:Date><aws:PageViews><aws:PerMillion>2801</aws:PerMillion><aws:PerUser>5.0</aws:PerUser></aws:PageViews><aws:Rank>18</aws:Rank><aws:Reach><aws:PerMillion>26041</aws:PerMillion></aws:Reach></aws:Data></aws:HistoricalData></aws:TrafficHistory></aws:Alexa></aws:TrafficHistoryResult><aws:ResponseStatus xmlns:aws='http://alexa.amazonaws.com/doc/2005-10-05/'><aws:StatusCode>Success</aws:StatusCode></aws:ResponseStatus></aws:Response></aws:TrafficHistoryResponse>";
            var xml = new RestSharp.Deserializers.XmlDeserializer();
            //xml.DateFormat = "yyyy-MM-dd";
            var output = xml.Deserialize <TrafficHistoryResponse>(new RestResponse {
                Content = content
            });

            Assert.AreEqual(2801, output.TrafficHistoryResult.Alexa.
                            TrafficHistory.HistoricalData.Datas[0].PageViews.PerMillion);
        }
Beispiel #30
0
        public List <UpdatedResource> ProcessUpdateReponseBody(string bodyContent)
        {
            bodyContent = StripSignatureString(bodyContent);

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            List <UpdatedResource> result = deserializer.Deserialize <List <UpdatedResource> >(new RestResponse()
            {
                Content = bodyContent
            });

            return(result);
        }
Beispiel #31
0
        public void Can_Deserialize_Food()
        {
            string content = File.ReadAllText(SampleData.PathFor("Food.txt"));
            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            Food result = deserializer.Deserialize<Food>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.Foods);
            Assert.IsNotNull(result.Goals);
            Assert.IsNotNull(result.Summary);

            Assert.IsTrue(result.Foods.Count == 1);
            FoodLog food = result.Foods[0];
            Assert.IsTrue(food.IsFavorite);
            Assert.AreEqual(food.LogDate, new DateTime(2011, 06, 29));
            Assert.AreEqual(food.LogId, 1924);

            Assert.IsNotNull(food.LoggedFood);
            LoggedFood logged = food.LoggedFood;
            Assert.AreEqual(logged.AccessLevel, "PUBLIC");
            Assert.AreEqual(logged.Amount, 132.57f);
            Assert.IsNull(logged.Brand);
            Assert.AreEqual(logged.Calories, 752);
            Assert.AreEqual(logged.FoodId, 18828);
            Assert.AreEqual(logged.MealTypeId, 4);
            Assert.AreEqual(logged.Locale, "en_US");
            Assert.AreEqual(logged.Name, "Chocolate, Milk");

            Assert.IsNotNull(food.NutritionalValues);
            NutritionalValues values = food.NutritionalValues;
            Assert.AreEqual(values.Calories, 752);
            Assert.AreEqual(values.Carbs, 66.5);
            Assert.AreEqual(values.Fat, 49);
            Assert.AreEqual(values.Fiber, .5);
            Assert.AreEqual(values.Protein, 12.5);
            Assert.AreEqual(values.Sodium, 186);

            FoodSummary summary = result.Summary;
            Assert.AreEqual(summary.Calories, 752);
            Assert.AreEqual(summary.Carbs, 66.5);
            Assert.AreEqual(summary.Fat, 49);
            Assert.AreEqual(summary.Fiber, .5);
            Assert.AreEqual(summary.Protein, 12.5);
            Assert.AreEqual(summary.Sodium, 186);
            Assert.AreEqual(summary.Water, 0);

            FoodGoals goals = result.Goals;
            Assert.AreEqual(goals.Calories, 2286);
        }
Beispiel #32
0
 public Response <T, U> HandleResponse <T, U>(IRestResponse response, Func <bool> whenToDeserializeToSecondGenericParam)
 {
     if (response.StatusCode == HttpStatusCode.NotAcceptable || (int)response.StatusCode == 422)
     {
         RestSharp.Deserializers.DotNetXmlDeserializer deserial = new RestSharp.Deserializers.DotNetXmlDeserializer();
         try
         {
             var errors  = deserial.Deserialize <ErrorsResponse>(response);
             var headers = response.Headers.Select(x => new { Name = x.Name, Value = x.Value }).ToDictionary(t => t.Name, t => t.Value?.ToString());
             return(new Response <T, U>(default(T), default(U), errors, response.StatusCode, headers));
         }
         catch (Exception)
         {
             var error = new ErrorsResponse(); error.Errors.Add("DESERALIZE EXCEPTION!");
             return(new Response <T, U>(default(T), default(U), error, response.StatusCode, null));
         }
     }
     else if (response.StatusCode == HttpStatusCode.OK)
     {
         RestSharp.Deserializers.XmlDeserializer deserial = new RestSharp.Deserializers.XmlDeserializer();
         if (whenToDeserializeToSecondGenericParam())
         {
             var deserialResponse = deserial.Deserialize <U>(response);
             var headers          = response.Headers.Select(x => new { Name = x.Name, Value = x.Value }).ToDictionary(t => t.Name, t => t.Value?.ToString());
             return(new Response <T, U>(default(T), deserialResponse, null, response.StatusCode, headers));
         }
         else
         {
             var deserialResponse = deserial.Deserialize <T>(response);
             var headers          = response.Headers.Select(x => new { Name = x.Name, Value = x.Value }).ToDictionary(t => t.Name, t => t.Value?.ToString());
             return(new Response <T, U>(deserialResponse, default(U), null, response.StatusCode, headers));
         }
     }
     //TODO:HANDLE INTERNAL SERVER ERROR, REPRODUCED BY SETTING WRONG AUTHENTICTY TOKEN
     return(new Response <T, U>(default(T), default(U), null, response.StatusCode, null));
 }
Beispiel #33
0
        public static string AlbumIdDeserialization(IRestResponse restResponse)
        {
            RestSharp.Deserializers.XmlDeserializer deserializer = new RestSharp.Deserializers.XmlDeserializer();
            var           resultObject = deserializer.Deserialize <XmlResult>(restResponse);
            List <string> IdList       = new List <string>();

            foreach (var item in resultObject.Result)
            {
                var itemObject = item.Substring(4, 4);
                IdList.Add(itemObject);
            }
            string id = IdList[0];

            return(id);
        }
Beispiel #34
0
        public void Can_Deserialize_IntradayActivitiesCalories()
        {
            string content = File.ReadAllText(SampleData.PathFor("IntradayActivitiesCalories.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            //var deserializer = new RestSharp.Deserializers.JsonDeserializer();
            deserializer.DateFormat = "HH:mm:ss";
            //TimeSeriesResourceType type = TimeSeriesResourceType.Steps.GetRootElement();

            //deserializer.RootElement = "dataset";
            //deserializer.RootElement = "activities-log-calories-intraday";
            XDocument doc = XDocument.Parse(content);

            var rootElement = doc.Descendants("result").FirstOrDefault().Descendants().Where(t => t.Name.LocalName.Contains("-intraday")).FirstOrDefault();

            //sometimes the API doesn't return that node, for isnstance a date queried before the start of an account
            if (rootElement != null && !string.IsNullOrWhiteSpace(rootElement.Name.LocalName))
            {
                deserializer.RootElement = rootElement.Name.LocalName;
            }

            IntradayData result = deserializer.Deserialize <IntradayData>(new RestResponse()
            {
                Content = content
            });

            //var result = deserializer.Deserialize<dynamic>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);

            Assert.AreEqual(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day), result.DataSet[0].Time);
            Assert.AreEqual("1.159999966621399", result.DataSet[0].Value);
            Assert.AreEqual("0", result.DataSet[0].Level);
            Assert.AreEqual("10", result.DataSet[0].METs);


            Assert.AreEqual(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 1, 0), result.DataSet[1].Time);
            Assert.AreEqual("1.159999966621399", result.DataSet[1].Value);
            Assert.AreEqual("2", result.DataSet[1].Level);
            Assert.AreEqual("32", result.DataSet[1].METs);

            //Assert.AreEqual(1440, result.DataSet.Count);

            //Assert.AreEqual(8, result.Count);
        }
Beispiel #35
0
        public void Can_Deserialize_SubscriptionResponse()
        {
            string content      = File.ReadAllText(SampleData.PathFor("SubscriptionResponse.txt"));
            var    deserializer = new RestSharp.Deserializers.XmlDeserializer();

            SubscriptionResponse result = deserializer.Deserialize <SubscriptionResponse>(new RestResponse()
            {
                Content = content
            });

            Assert.IsNotNull(result);

            Assert.AreEqual("user", result.CollectionType);
            Assert.AreEqual("227YZL", result.OwnerId);
            Assert.AreEqual("user", result.OwnerType);
            Assert.AreEqual("1", result.SubscriberId);
            Assert.AreEqual("323", result.SubscriptionId);
        }
Beispiel #36
0
        public static Queryresult AskWolfram(string question)
        {
            string pattern = "\\s+";
            Regex rgx = new Regex(pattern);
            string questionParsed = rgx.Replace(question, "+");
            RestClient client = new RestClient("http://api.wolframalpha.com/v2/");
            RestRequest request = new RestRequest("query?input="+ questionParsed +"&format=plaintext&output=XML&appid="+ EnvironmentVariables.WolframAPIKey);
            RestResponse response = new RestResponse();
            Task.Run(async () =>
            {
                response = await GetResponseContentAsync(client, request) as RestResponse;

            }).Wait();
            var XmlDS = new RestSharp.Deserializers.XmlDeserializer();
            var responseCSharp = XmlDS.Deserialize<Queryresult>(response);
            Debug.WriteLine("wolfram response:" + responseCSharp);
            return (responseCSharp);
        }
Beispiel #37
0
        public void Can_Deserialize_Rate_Limit()
        {
            string content = File.ReadAllText(SampleData.PathFor("RateLimitError.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            List <ApiError> result = deserializer.Deserialize <List <ApiError> >(new RestResponse()
            {
                Content = content
            });

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Count == 1);
            ApiError error = result.First();

            Assert.AreEqual(ErrorType.Request, error.ErrorType);
            Assert.AreEqual("n/a", error.FieldName);
        }
Beispiel #38
0
        public T Execute <T>(RestSharp.RestRequest request)
        {
            var client = CreateHttpClient();

            T         result   = default(T);
            Exception ex       = null;
            var       response = client.Execute(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                if (response.ErrorException != null)
                {
                    ex = response.ErrorException;
                }
                else if (response.ContentType.IndexOf("application/json") != -1)
                {
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(response.Content);
                }
                else if (response.ContentType.IndexOf("text/plain") != -1)
                {
                    result = (T)System.Convert.ChangeType(response.Content, typeof(T));
                }
                else if (response.ContentType == "")
                {
                    ex = CreateException(response);
                }
                else
                {
                    var d = new RestSharp.Deserializers.XmlDeserializer();
                    result = d.Deserialize <T>(response);
                }
            }
            else
            {
                ex = CreateException(response);
            }

            if (ex != null)
            {
                throw ex;
            }

            return(result);
        }
Beispiel #39
0
        /// <summary>
        /// Generic handling of status responses
        /// See: https://wiki.fitbit.com/display/API/API+Response+Format+And+Errors
        /// </summary>
        /// <param name="httpStatusCode"></param>
        private void HandleResponse(IRestResponse response)
        {
            System.Net.HttpStatusCode httpStatusCode = response.StatusCode;
            if (httpStatusCode == System.Net.HttpStatusCode.OK ||        //200
                httpStatusCode == System.Net.HttpStatusCode.Created ||   //201
                httpStatusCode == System.Net.HttpStatusCode.NoContent)   //204
            {
                return;
            }
            else
            {
                Console.WriteLine("HttpError:" + httpStatusCode.ToString());
                IList <ApiError> errors;
                try
                {
                    var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer()
                    {
                        RootElement = "errors"
                    };
                    errors = xmlDeserializer.Deserialize <List <ApiError> >(new RestResponse {
                        Content = response.Content
                    });
                }
                catch (Exception) // If there's an issue deserializing the error we still want to raise a fitbit exception
                {
                    errors = new List <ApiError>();
                }

                FitbitException exception = new FitbitException("Http Error:" + httpStatusCode.ToString(), httpStatusCode, errors);

                var retryAfterHeader = response.Headers.FirstOrDefault(h => h.Name == "Retry-After");
                if (retryAfterHeader != null)
                {
                    int retryAfter;
                    if (int.TryParse(retryAfterHeader.Value.ToString(), out retryAfter))
                    {
                        exception.retryAfter = retryAfter;
                    }
                }
                throw exception;
            }
        }
Beispiel #40
0
        public void Can_Deserialize_Subscription_Notification()
        {
            string content = File.ReadAllText(SampleData.PathFor("UpdatedResources.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            //var deserializer = new RestSharp.Deserializers.JsonDeserializer();
            //deserializer.DateFormat = "HH:mm:ss";
            //TimeSeriesResourceType type = TimeSeriesResourceType.Steps.GetRootElement();

            //deserializer.RootElement = "dataset";
            //deserializer.RootElement = "updates";

            List <UpdatedResource> result = deserializer.Deserialize <List <UpdatedResource> >(new RestResponse()
            {
                Content = content
            });

            //var result = deserializer.Deserialize<dynamic>(new RestResponse() { Content = content });

            Assert.AreEqual(2, result.Count);
        }
Beispiel #41
0
        public void Can_Deserialize_Friends()
        {
            string content = File.ReadAllText(SampleData.PathFor("GetFriends.txt"));
            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            deserializer.RootElement = "friends";

            List<Friend> result = deserializer.Deserialize<List<Friend>>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);

            List<UserProfile> userProfiles = new List<UserProfile>();

            foreach (Friend friend in result)
            {
                userProfiles.Add(friend.User);
            }

            Assert.IsTrue(userProfiles.Count == 4);
            Assert.AreEqual("User A.", userProfiles[0].DisplayName);

            //TODO: More tests of the data objects coming in


        }
Beispiel #42
0
        public void Can_Deserialize_SubscriptionResponse()
        {
            string content = File.ReadAllText(SampleData.PathFor("SubscriptionResponse.txt"));
            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            SubscriptionResponse result = deserializer.Deserialize<SubscriptionResponse>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);

            Assert.AreEqual("user", result.CollectionType);
            Assert.AreEqual("227YZL", result.OwnerId);
            Assert.AreEqual("user", result.OwnerType);
            Assert.AreEqual("1", result.SubscriberId);
            Assert.AreEqual("323", result.SubscriptionId);


        }
Beispiel #43
0
        /// <summary>
        /// Generic handling of status responses
        /// See: https://wiki.fitbit.com/display/API/API+Response+Format+And+Errors
        /// </summary>
        /// <param name="httpStatusCode"></param>
        private void HandleResponse(IRestResponse response)
        {
            System.Net.HttpStatusCode httpStatusCode = response.StatusCode;
            if (httpStatusCode == System.Net.HttpStatusCode.OK ||        //200
                httpStatusCode == System.Net.HttpStatusCode.Created ||   //201
                httpStatusCode == System.Net.HttpStatusCode.NoContent)   //204
            {
                return;
            }
            else
            {
                Console.WriteLine("HttpError:" + httpStatusCode.ToString());
                IList<ApiError> errors;
                try
                {
                    var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer() { RootElement = "errors" };
                    errors = xmlDeserializer.Deserialize<List<ApiError>>(new RestResponse { Content = response.Content });
                }
                catch (Exception) // If there's an issue deserializing the error we still want to raise a fitbit exception
                {
                    errors = new List<ApiError>();
                }

                FitbitException exception = new FitbitException("Http Error:" + httpStatusCode.ToString(), httpStatusCode, errors);

                var retryAfterHeader = response.Headers.FirstOrDefault(h => h.Name == "Retry-After");
                if (retryAfterHeader != null)
                {
                    int retryAfter;
                    if (int.TryParse(retryAfterHeader.Value.ToString(), out retryAfter))
                    {
                        exception.RetryAfter = retryAfter;
                    }
                }
                throw exception;
            }
        }
Beispiel #44
0
        public void Can_Deserialize_IntradayActivitiesCalories()
        {
            string content = File.ReadAllText(SampleData.PathFor("IntradayActivitiesCalories.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            //var deserializer = new RestSharp.Deserializers.JsonDeserializer();
            deserializer.DateFormat = "HH:mm:ss";
            //TimeSeriesResourceType type = TimeSeriesResourceType.Steps.GetRootElement();

            //deserializer.RootElement = "dataset";
            deserializer.RootElement = "activities-log-calories-intraday";

            IntradayData result = deserializer.Deserialize<IntradayData>(new RestResponse() { Content = content });
            //var result = deserializer.Deserialize<dynamic>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);

            Assert.AreEqual(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day), result.DataSet[0].Time);
            Assert.AreEqual("1.3125", result.DataSet[0].Value);
            Assert.AreEqual("0", result.DataSet[0].Level);

            Assert.AreEqual(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 1, 0), result.DataSet[1].Time);
            Assert.AreEqual("1.3125", result.DataSet[1].Value);
            Assert.AreEqual("1", result.DataSet[1].Level);

            //Assert.AreEqual(1440, result.DataSet.Count);

            //Assert.AreEqual(8, result.Count);

        }
Beispiel #45
0
        public void Can_Deserialize_Devices_Single()
        {
            string content = File.ReadAllText(SampleData.PathFor("GetDevices-Single.txt"));
            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            List<Device> result = deserializer.Deserialize<List<Device>>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);


            Assert.IsTrue(result.Count == 1);

            /*
            Assert.AreEqual("Full", result[0].Battery);
            Assert.AreEqual("123456", result[0].Id);
            //TODO: compare the date

            Assert.AreEqual("TRACKER", result[0].Type);
            Assert.AreEqual("Ultra", result[0].DeviceVersion);
            */

            Assert.AreEqual("Medium", result[0].Battery);
            Assert.AreEqual("473384", result[0].Id);
            //TODO: compare the date

            Assert.AreEqual(DeviceType.Tracker, result[0].Type);
            Assert.AreEqual("Ultra", result[0].DeviceVersion);


        }
Beispiel #46
0
        public void Can_Deserialize_Devices_Double()
        {
            string content = File.ReadAllText(SampleData.PathFor("GetDevices-Double.txt"));
            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            List<Device> result = deserializer.Deserialize<List<Device>>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);


            Assert.IsTrue(result.Count == 2);
            Assert.AreEqual("Full", result[0].Battery);
            Assert.AreEqual("123456", result[0].Id);
            //test date
            //Assert.AreEqual("TRACKER", result[0].Type);
            Assert.AreEqual(DeviceType.Tracker, result[0].Type);

            Assert.AreEqual("Ultra", result[0].DeviceVersion);

            Assert.AreEqual("High", result[1].Battery);
            //test date
            Assert.AreEqual("987654", result[1].Id);
            Assert.AreEqual(DeviceType.Scale, result[1].Type);
            Assert.AreEqual("Aria", result[1].DeviceVersion);

            //TODO: More tests of the data objects coming in


        }
Beispiel #47
0
        public void Can_Deserialize_Sleep_SingleSleepLog()
        {
            string content = File.ReadAllText(SampleData.PathFor("SleepData-SingleSleepLog.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            //var deserializer = new RestSharp.Deserializers.JsonDeserializer();
            //deserializer.DateFormat = "HH:mm:ss";
            //TimeSeriesResourceType type = TimeSeriesResourceType.Steps.GetRootElement();

            //deserializer.RootElement = "sleep";
            //deserializer.RootElement = "updates";

            SleepData result = deserializer.Deserialize<SleepData>(new RestResponse() { Content = content });
            //var result = deserializer.Deserialize<dynamic>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);
            //Assert.IsTrue(result.Sleep.SleepLog.Count > 0);

            Assert.IsNotNull(result.Summary);

            Assert.AreEqual(497, result.Summary.TotalMinutesAsleep);
            Assert.AreEqual(1, result.Summary.TotalSleepRecords);
            Assert.AreEqual(578, result.Summary.TotalTimeInBed);

            Assert.AreEqual(1, result.Sleep.Count);
            Assert.AreEqual(578, result.Sleep.First().MinuteData.Count); //this particular sleep had 578 minutes

            Assert.AreEqual(2, result.Sleep.First().MinuteData[1].Value);
            /*
            Assert.AreEqual(APICollectionType.user, result[0].CollectionType);
            Assert.AreEqual("227YZL", result[0].OwnerId);
            Assert.AreEqual("1", result[0].SubscriberId);
            Assert.AreEqual("323", result[0].SubscriptionId);
             */
        }
Beispiel #48
0
        public void Can_Deserialize_HeartRateResponse()
        {
            string content = File.ReadAllText(SampleData.PathFor("HeartLogResponse.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            deserializer.RootElement = "heartLog";

            HeartRateLog result = deserializer.Deserialize<HeartRateLog>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);

            Assert.AreEqual(150, result.HeartRate);
            Assert.AreEqual(1424, result.LogId);

            var now = DateTime.Now;
            DateTime expected = new DateTime(now.Year, now.Month, now.Day, 12, 20, 0);
            Assert.AreEqual(expected, result.Time);

            Assert.AreEqual("Running", result.Tracker);
        }
Beispiel #49
0
        public void Can_Deserialize_IntradayActivitiesSteps()
        {
            string content = File.ReadAllText(SampleData.PathFor("IntradayActivitiesSteps.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            //var deserializer = new RestSharp.Deserializers.JsonDeserializer();
            deserializer.DateFormat = "HH:mm:ss";
            //TimeSeriesResourceType type = TimeSeriesResourceType.Steps.GetRootElement();

            //deserializer.RootElement = "dataset";
            //deserializer.RootElement = "activities-log-calories-intraday";
            XDocument doc = XDocument.Parse(content);

            var rootElement = doc.Descendants("result").FirstOrDefault().Descendants().Where(t => t.Name.LocalName.Contains("-intraday")).FirstOrDefault();

            //sometimes the API doesn't return that node, for isnstance a date queried before the start of an account 
            if (rootElement != null && !string.IsNullOrWhiteSpace(rootElement.Name.LocalName))
                deserializer.RootElement = rootElement.Name.LocalName;

            IntradayData result = deserializer.Deserialize<IntradayData>(new RestResponse() { Content = content });
            //var result = deserializer.Deserialize<dynamic>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);

            Assert.AreEqual(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day), result.DataSet[0].Time);
            Assert.AreEqual("3", result.DataSet[0].Value);

            Assert.AreEqual(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 1, 0), result.DataSet[1].Time);
            Assert.AreEqual("10", result.DataSet[1].Value);

            //Assert.AreEqual(1440, result.DataSet.Count);

            //Assert.AreEqual(8, result.Count);

        }
Beispiel #50
0
        public void Can_Deserialize_Rate_Limit()
        {
            string content = File.ReadAllText(SampleData.PathFor("RateLimitError.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();

            List<ApiError> result = deserializer.Deserialize<List<ApiError>>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Count == 1);
            ApiError error = result.First();
            Assert.AreEqual(ErrorType.Request, error.ErrorType);
            Assert.AreEqual("n/a", error.FieldName);
        }
Beispiel #51
0
        public void Can_Deserialize_Subscription_Notification()
        {
            string content = File.ReadAllText(SampleData.PathFor("UpdatedResources.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            //var deserializer = new RestSharp.Deserializers.JsonDeserializer();
            //deserializer.DateFormat = "HH:mm:ss";
            //TimeSeriesResourceType type = TimeSeriesResourceType.Steps.GetRootElement();

            //deserializer.RootElement = "dataset";
            //deserializer.RootElement = "updates";

            List<UpdatedResource> result = deserializer.Deserialize<List<UpdatedResource>>(new RestResponse() { Content = content });
            //var result = deserializer.Deserialize<dynamic>(new RestResponse() { Content = content });

            Assert.AreEqual(2, result.Count);

        }
Beispiel #52
0
        public void Can_Deserialize_TimeSeriesActivitiesStepsInt()
        {
            string content = File.ReadAllText(SampleData.PathFor("TimeSeriesActivitiesSteps.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            //var deserializer = new RestSharp.Deserializers.JsonDeserializer();

            //TimeSeriesResourceType type = TimeSeriesResourceType.Steps.GetRootElement();

            deserializer.RootElement = "activities-steps";


            List<TimeSeriesDataListInt.Data> result = deserializer.Deserialize<List<TimeSeriesDataListInt.Data>>(new RestResponse() { Content = content });

            Assert.IsNotNull(result);

            Assert.AreEqual(new DateTime(2012, 5, 19), result[0].DateTime);
            Assert.AreEqual(11546, result[0].Value);

            Assert.AreEqual(8, result.Count);

        }
Beispiel #53
0
        public void Can_Deserialize_Api_Subscription_List()
        {
            string content = File.ReadAllText(SampleData.PathFor("ListApiSubscriptions.txt"));

            var deserializer = new RestSharp.Deserializers.XmlDeserializer();
            //var deserializer = new RestSharp.Deserializers.JsonDeserializer();
            //deserializer.DateFormat = "HH:mm:ss";
            //TimeSeriesResourceType type = TimeSeriesResourceType.Steps.GetRootElement();

            //deserializer.RootElement = "dataset";
            //deserializer.RootElement = "updates";

            List<ApiSubscription> result = deserializer.Deserialize<List<ApiSubscription>>(new RestResponse() { Content = content });
            //var result = deserializer.Deserialize<dynamic>(new RestResponse() { Content = content });

            Assert.AreEqual(1, result.Count);
            Assert.AreEqual(APICollectionType.user, result[0].CollectionType);
            Assert.AreEqual("227YZL", result[0].OwnerId);
            Assert.AreEqual("1", result[0].SubscriberId);
            Assert.AreEqual("323", result[0].SubscriptionId);
        }