public void AttachShouldFailOnNullBuilder()
        {
            var testContext = new TestClientContext
            {
                GetMetadataBuilderFunc = (set, e) => null
            };

            Action action = () => testContext.AttachTo("FakeSet", new SingleKeyType { Property = "foo" });
            action.ShouldThrow<InvalidOperationException>().WithMessage(Strings.Context_EntityMetadataBuilderIsRequired);
        }
        public void AttachShouldUseBuilder()
        {
            const string fakeEditLink = "http://thisIsTheEditLink.org/";
            const string fakeId = "http://thisIsTheId.org/";

            var simulator = new EntityMetadataBuilderSimulator 
            { 
                GetEditLinkFunc = () => new Uri(fakeEditLink),
                GetIdFunc = () => new Uri(fakeId),
            };

            var testContext = new TestClientContext(new Uri("http://temp.org/"))
            { 
                GetMetadataBuilderFunc = (set, e) => simulator 
            };

            testContext.AttachTo("FakeSet", new SingleKeyType { Property = "foo" });
            EntityDescriptor entityDescriptor = testContext.Entities[0];
            entityDescriptor.EditLink.Should().Be(fakeEditLink);
            entityDescriptor.Identity.Should().Be(fakeId);
        }
        public void QueryProperty()
        {
            // Load property and navigation property from type declared in main model
            var outsideGeoFenceAlarm = (TestClientContext.Trucks.Where(t => t.Key == "Key1")).Select(t => t.OutsideGeoFenceAlarm).Single();

            Assert.AreEqual(3, outsideGeoFenceAlarm.Severity);

            var truck = (TestClientContext.Trucks.Where(t => t.Key == "Key1")).Single();

            TestClientContext.LoadProperty(truck, "VehicleGPS");
            Assert.IsTrue(truck.VehicleGPS != null);

            // Load property from type declared in referenced model
            var currentLocation = (TestClientContext.VehicleGPSSet.Where(t => t.Key == "VehicleKey2")).Select(t => t.CurrentLocation).Single();

            Assert.AreEqual(12.3, currentLocation.Long);

            // Load property from type derived from declared in referenced model
            var displayName = (TestClientContext.DerivedVehicleGPSSet.Where(t => t.Key == "VehicleKey4")).Select(t => t.DisplayName).Single();

            Assert.AreEqual("DisplayName4", displayName);
        }
Esempio n. 4
0
        public void AddDeleteLink(string mimeType)
        {
            TestClientContext.MergeOption      = MergeOption.OverwriteChanges;
            TestClientContext.SendingRequest2 += (sender, eventArgs) => ((Microsoft.OData.Client.HttpWebRequestMessage)eventArgs.RequestMessage).SetHeader("Accept", mimeType);
            if (mimeType.StartsWith(MimeTypes.ApplicationAtomXml))
            {
                TestClientContext.Format.UseAtom();
            }
            else
            {
                TestClientContext.Format.UseJson(Model);
            }
            //preparation
            //currently service does not support $expand, so need to query the navigation Orders first
            var uri = new Uri(ServiceBaseUri + "Products(5)/Details");
            var detailsInAProdct      = TestClientContext.Execute <ProductDetail>(uri);
            var intOriginalOrderCount = detailsInAProdct.Count();
            var prodct = TestClientContext.Products.Where(c => c.ProductID == 5).SingleOrDefault();

            TestClientContext.SendingRequest2 += (sender, eventArgs) => ((Microsoft.OData.Client.HttpWebRequestMessage)eventArgs.RequestMessage).SetHeader(TestHeader, "EditLink");//this is make sure EditLink is replaced with a random value.

            var productDetail = TestClientContext.ProductDetails.Where(o => o.ProductDetailID == 1 && o.ProductID == 6).SingleOrDefault();

            //add a link between customer and order
            TestClientContext.AddLink(prodct, "Details", productDetail);
            TestClientContext.SaveChanges();
            detailsInAProdct = TestClientContext.Execute <ProductDetail>(uri);
            var intOrderCountAfterAddLink = detailsInAProdct.Count();

            Assert.AreEqual(intOriginalOrderCount + 1, intOrderCountAfterAddLink, "The link is added.");

            //delete the added link
            TestClientContext.DeleteLink(prodct, "Details", productDetail);
            TestClientContext.SaveChanges();
            detailsInAProdct = TestClientContext.Execute <ProductDetail>(uri);
            var intOrderCountAfterDeleteLink = detailsInAProdct.Count();

            Assert.AreEqual(intOriginalOrderCount, intOrderCountAfterDeleteLink, "The added link is deleted.");
        }
Esempio n. 5
0
        private void QueryObjectsWhenTheyAreTransient(string mimeType)
        {
            TestClientContext.MergeOption      = MergeOption.OverwriteChanges;
            TestClientContext.SendingRequest2 += (sender, eventArgs) => ((Microsoft.OData.Client.HttpWebRequestMessage)eventArgs.RequestMessage).SetHeader(TestHeader, "IsTransient");

            TestClientContext.SendingRequest2 += (sender, eventArgs) => ((Microsoft.OData.Client.HttpWebRequestMessage)eventArgs.RequestMessage).SetHeader("Accept", mimeType);
            if (mimeType.StartsWith(MimeTypes.ApplicationAtomXml))
            {
                TestClientContext.Format.UseAtom();
            }
            else
            {
                TestClientContext.Format.UseJson(Model);
            }

            var entryResults = TestClientContext.Execute <Person>(new Uri(ServiceBaseUri + "/People?$filter=PersonID eq 1")).ToArray();

            Assert.AreEqual(1, entryResults.Count(), "Unexpected number of Products returned");
            var entityDescriptor = TestClientContext.GetEntityDescriptor(entryResults[0]);

            Assert.IsNull(entityDescriptor);
        }
Esempio n. 6
0
        private async Task TestCURCreateParquet(string reportName)
        {
            string Json = GenerateCreateJsonParquet(reportName);

            CustomResourceRequest Request = JsonConvert.DeserializeObject <CustomResourceRequest>(Json);

            TestLambdaLogger  TestLogger    = new TestLambdaLogger();
            TestClientContext ClientContext = new TestClientContext();

            TestLambdaContext Context = new TestLambdaContext()
            {
                FunctionName       = "CostAndUsageReportResource",
                FunctionVersion    = "1",
                Logger             = TestLogger,
                ClientContext      = ClientContext,
                InvokedFunctionArn = "arn:aws:lambda:us-east-1:123456789012:function:FunctionName"
            };

            // ACT
            Entrypoint Ep = new Entrypoint();
            await Ep.Execute(Request, Context);
        }
Esempio n. 7
0
 public void TestOrderByDescendingOption()
 {
     foreach (var entitySet in entitySetsList)
     {
         foreach (var keyName in entitySet.Value)
         {
             IQueryable iqueryableProperty = typeof(InMemoryEntities).GetProperty(entitySet.Key).GetValue(TestClientContext, null) as IQueryable;
             Uri        executeUri         = new Uri(String.Format("{0}?$orderby={1} desc", iqueryableProperty.ToString(), keyName));
             Type       clientType         = iqueryableProperty.ElementType;
             var        orderedResults     = this.ExecuteUri(TestClientContext, executeUri, clientType);
             foreach (var entity in orderedResults)
             {
                 EntityDescriptor eDescriptor = TestClientContext.GetEntityDescriptor(entity);
                 //Self link was not read
                 Assert.NotNull(eDescriptor.SelfLink);
                 //Edit link was not read
                 Assert.NotNull(eDescriptor.EditLink);
                 //Identity was not read
                 Assert.NotNull(eDescriptor.Identity);
             }
         }
     }
 }
        public void AttachShouldUseBuilder()
        {
            const string fakeEditLink = "http://thisIsTheEditLink.org/";
            const string fakeId       = "http://thisIsTheId.org/";

            var simulator = new EntityMetadataBuilderSimulator
            {
                GetEditLinkFunc = () => new Uri(fakeEditLink),
                GetIdFunc       = () => new Uri(fakeId),
            };

            var testContext = new TestClientContext(new Uri("http://temp.org/"))
            {
                GetMetadataBuilderFunc = (set, e) => simulator
            };

            testContext.AttachTo("FakeSet", new SingleKeyType {
                Property = "foo"
            });
            EntityDescriptor entityDescriptor = testContext.Entities[0];

            entityDescriptor.EditLink.Should().Be(fakeEditLink);
            entityDescriptor.Identity.Should().Be(fakeId);
        }
Esempio n. 9
0
        private void UpdateObject(string mimeType)
        {
            TestClientContext.MergeOption = MergeOption.OverwriteChanges;

            TestClientContext.SendingRequest2 += (sender, eventArgs) => ((Microsoft.OData.Client.HttpWebRequestMessage)eventArgs.RequestMessage).SetHeader(TestHeader, "EditLink");

            TestClientContext.SendingRequest2 += (sender, eventArgs) => ((Microsoft.OData.Client.HttpWebRequestMessage)eventArgs.RequestMessage).SetHeader("Accept", mimeType);
            if (mimeType.StartsWith(MimeTypes.ApplicationAtomXml))
            {
                TestClientContext.Format.UseAtom();
            }
            else
            {
                TestClientContext.Format.UseJson(Model);
            }
            var person = TestClientContext.People.Where(p => p.PersonID == 2).SingleOrDefault();
            var stringOfErrorMessage = "";

            try
            {
                person.FirstName = "bla";
                TestClientContext.UpdateObject(person);
                //The EditLink in payload looks like http://potato987654321098, more infomation can be found in Microsoft.Test.OData.Services.ODataWCFService.ResponseWriter.WriteEntry()
                TestClientContext.SaveChanges();
            }
            catch (Exception ex)
            {
                stringOfErrorMessage = ex.InnerException.Message;
            }
            //The test is to make sure that the request is sent to server incorrectly, so it is supposed to throw exception.
            //TODO: This verification may fail in other languages.
            Assert.IsTrue(stringOfErrorMessage.Contains("No such host is known") || //if fiddler is open
                          stringOfErrorMessage.Contains("The remote name could not be resolved") || //if fiddler is not open
                          stringOfErrorMessage.Contains("Unable to connect to the remote server")
                          , String.Format("Exception message is expected to contain 'No such host is known' or 'The remote name could not be resolved', but actually not. The actual message is '{0}'.", stringOfErrorMessage));
        }
Esempio n. 10
0
        public async Task TestCreate()
        {
            // ARRANGE
            AWSConfigs.AWSProfilesLocation = $"{Environment.GetEnvironmentVariable("UserProfile")}\\.aws\\credentials";

            string StreamName         = "test-stream";
            string PresignedUrlBucket = "pre-sign-url-bucket";
            string AccountNumber      = "123456789012";
            string Region             = "us-east-1";

            IAmazonS3 S3Client = new AmazonS3Client();

            GetPreSignedUrlRequest Req = new GetPreSignedUrlRequest()
            {
                BucketName = PresignedUrlBucket,
                Key        = "result.txt",
                Expires    = DateTime.Now.AddMinutes(2),
                Protocol   = Protocol.HTTPS,
                Verb       = HttpVerb.PUT
            };

            string PreSignedUrl = S3Client.GetPreSignedURL(Req);

            string Json = $@"
{{
""requestType"":""create"",
""responseUrl"":""{PreSignedUrl}"",
""stackId"":""arn:aws:cloudformation:{Region}:{AccountNumber}:stack/stack-name/{Guid.NewGuid().ToString()}"",
""requestId"":""12345678"",
""resourceType"":""Custom::KinesisStreamAwaiter"",
""logicalResourceId"":""KinesisStreamAwaiter"",
""resourceProperties"":{{
""StreamName"":""{StreamName}""
}}
}}";


            CustomResourceRequest Request = JsonConvert.DeserializeObject <CustomResourceRequest>(Json);

            TestLambdaLogger  TestLogger    = new TestLambdaLogger();
            TestClientContext ClientContext = new TestClientContext();

            TestLambdaContext Context = new TestLambdaContext()
            {
                FunctionName    = "KinesisStreamAwaiter",
                FunctionVersion = "1",
                Logger          = TestLogger,
                ClientContext   = ClientContext,
                LogGroupName    = "aws/lambda/KinesisStreamAwaiter",
                LogStreamName   = Guid.NewGuid().ToString(),
                RemainingTime   = TimeSpan.FromSeconds(300)
            };


            Entrypoint Entrypoint = new Entrypoint();

            // ACT
            IAmazonKinesis      KinesisClient = new AmazonKinesisClient();
            CreateStreamRequest CreateReq     = new CreateStreamRequest()
            {
                ShardCount = 1,
                StreamName = StreamName
            };


            CreateStreamResponse CreateResponse = await KinesisClient.CreateStreamAsync(CreateReq);

            try
            {
                CustomResourceResult Response = await Entrypoint.ExecuteAsync(Request, Context);

                // ASSERT

                Assert.True(Response.IsSuccess);
            }
            finally
            {
                DeleteStreamRequest DeleteReq = new DeleteStreamRequest()
                {
                    StreamName = StreamName
                };

                await KinesisClient.DeleteStreamAsync(DeleteReq);
            }
        }
Esempio n. 11
0
        public void PostTunning()
        {
            this.TestClientContext.MergeOption      = MergeOption.OverwriteChanges;
            this.TestClientContext.UsePostTunneling = true;
            //Entity of Derived type
            //Entity has a complex property of derived type
            DataServiceCollection <PersonPlus> people =
                new DataServiceCollection <PersonPlus>(this.TestClientContext, "People", null, null)
            {
                new CustomerPlus()
                {
                    FirstNamePlus  = "Nelson",
                    MiddleNamePlus = "S.",
                    LastNamePlus   = "Black",
                    NumbersPlus    = new ObservableCollection <string> {
                        "111-111-1111"
                    },
                    EmailsPlus = new ObservableCollection <string> {
                        "*****@*****.**"
                    },
                    PersonIDPlus = 10001,
                    BirthdayPlus = new DateTimeOffset(new DateTime(1957, 4, 3)),
                    CityPlus     = "London",
                    HomePlus     = GeographyPoint.Create(32.1, 23.1),
                    TimeBetweenLastTwoOrdersPlus = new TimeSpan(1),
                    HomeAddressPlus = new HomeAddressPlus()
                    {
                        CityPlus       = "London",
                        PostalCodePlus = "98052",
                        StreetPlus     = "1 Microsoft Way",
                        FamilyNamePlus = "Black's Family"
                    },
                }
            };

            DataServiceCollection <OrderPlus> orders = new DataServiceCollection <OrderPlus>(TestClientContext)
            {
                new OrderPlus()
                {
                    OrderIDPlus         = 11111111,
                    OrderDatePlus       = new DateTimeOffset(new DateTime(2011, 5, 29, 14, 21, 12)),
                    ShelfLifePlus       = new TimeSpan(1),
                    OrderShelfLifesPlus = new ObservableCollection <TimeSpan>()
                    {
                        new TimeSpan(1)
                    }
                }
            };

            //Singleton of derived type
            //Singleton is of an open entity type
            DataServiceCollection <CompanyPlus> publicCompany =
                new DataServiceCollection <CompanyPlus>(this.TestClientContext.PublicCompanyPlus);

            //Entity with open complex type
            //Entity with contained Navigation
            DataServiceCollection <AccountPlus> accounts =
                new DataServiceCollection <AccountPlus>(this.TestClientContext)
            {
                new AccountPlus()
                {
                    AccountIDPlus     = 110,
                    CountryRegionPlus = "CN",
                    AccountInfoPlus   = new AccountInfoPlus()
                    {
                        FirstNamePlus = "New",
                        LastNamePlus  = "Boy"
                    }
                }
            };

            var gc = new GiftCardPlus()
            {
                GiftCardIDPlus     = 30000,
                GiftCardNOPlus     = "AAA123A",
                AmountPlus         = 19.9,
                ExperationDatePlus = new DateTimeOffset(new DateTime(2013, 12, 30))
            };

            //Entity with Enum property and collection of Enum property
            DataServiceCollection <ProductPlus> products =
                new DataServiceCollection <ProductPlus>(this.TestClientContext)
            {
                new  ProductPlus()
                {
                    NamePlus            = "Apple",
                    ProductIDPlus       = 1000000,
                    QuantityInStockPlus = 20,
                    QuantityPerUnitPlus = "Pound",
                    UnitPricePlus       = 0.35f,
                    DiscontinuedPlus    = false,
                    SkinColorPlus       = ColorPlus.RedPlus,
                    CoverColorsPlus     = new ObservableCollection <ColorPlus>()
                    {
                        ColorPlus.BluePlus
                    },
                    UserAccessPlus = AccessLevelPlus.ReadPlus
                }
            };

            TestClientContext.UpdateRelatedObject(accounts[0], "MyGiftCard", gc);
            this.TestClientContext.SaveChanges();

            var customer = this.TestClientContext.CustomersPlus.Where(c => c.PersonIDPlus == people[0].PersonIDPlus).First();

            TestClientContext.AddLink(customer, "Orders", orders[0]);
            this.TestClientContext.SaveChanges();

            bool isEntity = true;
            int  expectedPropertyCount = 0;
            Action <WritingEntryArgs> onEntryEndingAction = (arg) =>
            {
                if (isEntity)
                {
                    Assert.AreEqual(expectedPropertyCount, arg.Entry.Properties.Count());
                }
            };

            this.TestClientContext.Configurations.RequestPipeline.OnEntryEnding(onEntryEndingAction);

            //Update Enum type and collection of enum property in entity
            products[0].CoverColorsPlus.Add(ColorPlus.GreenPlus);
            products[0].UserAccessPlus = AccessLevelPlus.ExecutePlus;
            products[0].SkinColorPlus  = ColorPlus.GreenPlus;
            expectedPropertyCount      = 3;
            this.TestClientContext.SaveChanges();

            //this.TestClientContext.Detach(products[0]);
            var product = this.TestClientContext.ProductsPlus.Where((it) => it.ProductIDPlus == products[0].ProductIDPlus).First();

            Assert.AreEqual(2, product.CoverColorsPlus.Count);
            Assert.AreEqual(ColorPlus.GreenPlus, product.SkinColorPlus);
            Assert.AreEqual(AccessLevelPlus.ExecutePlus, product.UserAccessPlus);
            Assert.AreEqual(2, product.CoverColorsPlus.Count);

            // Update primitive type and collection property under entity
            people[0].FirstNamePlus = "Balck";
            people[0].EmailsPlus.Add("*****@*****.**");

            expectedPropertyCount = 2;
            this.TestClientContext.SaveChanges();

            // Update primitive type and collection property under entity (inherited)
            var datetime = new DateTimeOffset(new DateTime(1957, 4, 3));;

            ((CustomerPlus)people[0]).BirthdayPlus = new DateTimeOffset(new DateTime(1957, 4, 3));

            expectedPropertyCount = 1;
            this.TestClientContext.SaveChanges();

            // Update the property under complex type.
            people[0].HomeAddressPlus.CityPlus = "Redmond";

            bool isComplex = true;

            isEntity = false;
            Action <WritingEntryArgs> onEntryEndingAction1 = (arg) =>
            {
                if (isComplex && arg.Entry.TypeName.EndsWith("HomeAddressPlus"))
                {
                    Assert.AreEqual("Redmond", arg.Entry.Properties.Single(p => p.Name == "City").Value);
                }
            };

            this.TestClientContext.Configurations.RequestPipeline.OnEntryEnding(onEntryEndingAction1);
            this.TestClientContext.SaveChanges();

            // Update the property under complex type (inherited).
            ((HomeAddressPlus)people[0].HomeAddressPlus).FamilyNamePlus = "Microsoft";

            Action <WritingEntryArgs> onEntryEndingAction2 = (arg) =>
            {
                if (isComplex && arg.Entry.TypeName.EndsWith("HomeAddressPlus"))
                {
                    Assert.AreEqual("Microsoft", arg.Entry.Properties.Single(p => p.Name == "FamilyName").Value);
                }
            };

            this.TestClientContext.Configurations.RequestPipeline.OnEntryEnding(onEntryEndingAction2);
            this.TestClientContext.SaveChanges();

            isComplex = false;
            isEntity  = true;

            this.TestClientContext.LoadProperty(customer, "Orders");
            // Update Navigation property
            customer.OrdersPlus.First().OrderDatePlus = datetime;
            customer.OrdersPlus.First().OrderShelfLifesPlus.Add(new TimeSpan(2));
            expectedPropertyCount = 2;
            this.TestClientContext.SaveChanges();

            //Verify all updated property
            //this.TestClientContext.Detach(customer);
            var people0 = this.TestClientContext.CustomersPlus.Expand(it => it.OrdersPlus).Where((it) => it.PersonIDPlus == people[0].PersonIDPlus).Single();

            Assert.AreEqual(2, people0.EmailsPlus.Count);
            Assert.AreEqual(datetime, (people0 as CustomerPlus).BirthdayPlus);
            Assert.AreEqual("Redmond", people0.HomeAddressPlus.CityPlus);
            Assert.AreEqual("Microsoft", (people0.HomeAddressPlus as HomeAddressPlus).FamilyNamePlus);
            Assert.AreEqual("98052", people0.HomeAddressPlus.PostalCodePlus);
            Assert.AreEqual(datetime, people0.OrdersPlus.First().OrderDatePlus);
            Assert.AreEqual(2, people0.OrdersPlus.First().OrderShelfLifesPlus.Count());

            TestClientContext.LoadProperty(accounts[0], "MyGiftCard");
            //  Update single vlue navigation property .
            accounts[0].MyGiftCardPlus.ExperationDatePlus = datetime;

            expectedPropertyCount = 1;
            this.TestClientContext.SaveChanges();

            // Update open complex type
            accounts[0].AccountInfoPlus.MiddleNamePlus = "S.";
            isEntity  = false;
            isComplex = true;
            Action <WritingEntryArgs> onEntryEndingAction3 = (arg) =>
            {
                if (isComplex && arg.Entry.TypeName.EndsWith("AccountInfoPlus"))
                {
                    Assert.AreEqual("S.", arg.Entry.Properties.Single(p => p.Name == "MiddleName").Value);
                }
            };

            this.TestClientContext.Configurations.RequestPipeline.OnEntryEnding(onEntryEndingAction3);
            this.TestClientContext.SaveChanges();
            isComplex = false;
            isEntity  = true;

            //this.TestClientContext.Detach(accounts[0]);
            var account = this.TestClientContext.AccountsPlus.Expand("MyGiftCard").Where((it) => it.AccountIDPlus == accounts[0].AccountIDPlus).Single();

            Assert.AreEqual(datetime, account.MyGiftCardPlus.ExperationDatePlus);
            Assert.AreEqual("S.", account.AccountInfoPlus.MiddleNamePlus);
            Assert.AreEqual("New", account.AccountInfoPlus.FirstNamePlus);

            // Update property in open singleton
            publicCompany.Single().TotalAssetsPlus = 10;
            publicCompany.Single().FullNamePlus    = "MS Ltd.";
            expectedPropertyCount = 2;
            this.TestClientContext.SaveChanges();

            //this.TestClientContext.Detach(publicCompany);
            var company = this.TestClientContext.PublicCompanyPlus.GetValue();

            Assert.AreEqual(company.TotalAssetsPlus, 10);
            Assert.AreEqual(company.FullNamePlus, "MS Ltd.");

            // Update object by update object without change => redo the PATCH all
            this.TestClientContext.UpdateObject(people[0]);

            isEntity = false;
            Action <WritingEntryArgs> onEntryEndingAction4 = (arg) =>
            {
                if (arg.Entry.TypeName.EndsWith("PersonPlus"))
                {
                    Assert.AreEqual(expectedPropertyCount, arg.Entry.Properties.Count());
                }
            };

            this.TestClientContext.Configurations.RequestPipeline.OnEntryEnding(onEntryEndingAction4);

            expectedPropertyCount = 10;
            this.TestClientContext.SaveChanges();
        }
Esempio n. 12
0
        public void ClientTest()
        {
            // Query Entity Contain Date/TimeOfDay
            TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges;

            // Query Property
            var shipDate = TestClientContext.Orders.ByKey(new Dictionary <string, object>()
            {
                { "OrderID", 7 }
            }).Select(o => o.ShipDate).GetValue();

            Assert.AreEqual(new Date(2014, 8, 31), shipDate);

            var shipTime = TestClientContext.Orders.ByKey(new Dictionary <string, object>()
            {
                { "OrderID", 7 }
            }).Select(o => o.ShipTime).GetValue();

            Assert.AreEqual(new TimeOfDay(12, 40, 05, 50), shipTime);

            // Projection Select
            var projOrder = TestClientContext.Orders.ByKey(new Dictionary <string, object>()
            {
                { "OrderID", 7 }
            }).Select(o => new Order()
            {
                ShipDate = o.ShipDate, ShipTime = o.ShipTime
            }).GetValue();

            Assert.IsTrue(projOrder != null);
            Assert.AreEqual(new Date(2014, 8, 31), projOrder.ShipDate);
            Assert.AreEqual(new TimeOfDay(12, 40, 05, 50), projOrder.ShipTime);

            // Update Properties
            var order = TestClientContext.Orders.ByKey(new Dictionary <string, object>()
            {
                { "OrderID", 7 }
            }).GetValue();

            Assert.IsTrue(order != null);
            Assert.AreEqual(new Date(2014, 8, 31), order.ShipDate);
            Assert.AreEqual(new TimeOfDay(12, 40, 05, 50), order.ShipTime);

            order.ShipDate = new Date(2014, 9, 30);
            TestClientContext.UpdateObject(order);
            TestClientContext.SaveChanges();

            var updatedOrder = TestClientContext.Orders.ByKey(new Dictionary <string, object>()
            {
                { "OrderID", 7 }
            }).GetValue();

            Assert.AreEqual(new Date(2014, 9, 30), updatedOrder.ShipDate);

            // Function
            var date = TestClientContext.Orders.ByKey(new Dictionary <string, object>()
            {
                { "OrderID", 7 }
            }).GetShipDate().GetValue();

            Assert.AreEqual(new Date(2014, 9, 30), date);

            // Action
            TestClientContext.Orders.ByKey(new Dictionary <string, object>()
            {
                { "OrderID", 7 }
            }).ChangeShipTimeAndDate(Date.MaxValue, TimeOfDay.MaxValue).GetValue();
            updatedOrder = TestClientContext.Orders.ByKey(new Dictionary <string, object>()
            {
                { "OrderID", 7 }
            }).GetValue();
            Assert.AreEqual(Date.MaxValue, updatedOrder.ShipDate);
            Assert.AreEqual(TimeOfDay.MaxValue, updatedOrder.ShipTime);
        }
Esempio n. 13
0
 public void Cleanup()
 {
     _sut = null;
 }
        public void EntitySetDeclaredInReferencedModelE2E()
        {
            // Query Entity Set in GPS
            TestClientContext.MergeOption = MergeOption.OverwriteChanges;
            var vehicleGPSSetInGPS = TestClientContext.VehicleGPSSetInGPS;

            foreach (var vehicleGPS in vehicleGPSSetInGPS)
            {
                Assert.IsTrue(vehicleGPS != null);
            }
            Assert.AreEqual(3, vehicleGPSSetInGPS.Count());

            // Create an entity in VehicleGPSSetInGPS
            var newVehicleGPS = new VehicleGPSType()
            {
                Key           = "101",
                VehicleSpeed  = 100.1,
                StartLocation = new GeoLocation()
                {
                    Lat  = 1,
                    Long = 2,
                },
                EndLocation = new GeoLocation()
                {
                    Lat  = 3,
                    Long = 4,
                },
                CurrentLocation = new GeoLocation()
                {
                    Lat  = 1.2,
                    Long = 2.4,
                },
                LostSignalAlarm = new GPSLostSignalAlarmType()
                {
                    Severity          = 1,
                    LastKnownLocation = new GeoLocation()
                    {
                        Lat  = 2.1,
                        Long = 1.2,
                    }
                },
                Map = new MapType()
                {
                    MBytesDownloaded = 1.2,
                    ProviderName     = "TESTNEW",
                    Uri = "TESTNEW.TEST",
                }
            };

            TestClientContext.AddToVehicleGPSSetInGPS(newVehicleGPS);
            TestClientContext.SaveChanges();

            // Get the created entity
            var            queryable  = TestClientContext.VehicleGPSSetInGPS.Where(vehicleGPS => vehicleGPS.Key == "101");
            VehicleGPSType newCreated = queryable.Single();

            Assert.AreEqual(100.1, newCreated.VehicleSpeed);

            // Update the created entity
            newCreated.VehicleSpeed = 200.1;
            TestClientContext.UpdateObject(newCreated);
            TestClientContext.SaveChanges();

            // Query and Delete entity
            VehicleGPSType updated = queryable.Single();

            Assert.AreEqual(200.1, newCreated.VehicleSpeed);

            TestClientContext.DeleteObject(updated);
            TestClientContext.SaveChanges();
            Assert.AreEqual(3, vehicleGPSSetInGPS.Count());
        }
Esempio n. 15
0
        public async Task CreateCustomResourceWithHandlerTest()
        {
            // ARRANGE
            string AccountNumber      = "123456789012";
            string Region             = "us-east-1";
            string InputBucket        = $"{Environment.UserName}-rawvideo";
            string OutputBucket       = $"{Environment.UserName}-video";
            string PresignedUrlBucket = $"{Environment.UserName}-presigned-url-test";
            string ThumbnailBucket    = $"{Environment.UserName}-thumbnails";
            string IAMRole            = $"arn:aws:iam::{AccountNumber}:role/LambdaElasticTranscoderPipeline";
            string NotificationTopic  = $"arn:aws:sns:{Region}:{AccountNumber}:ElasticTranscoderNotifications";
            string Key = "result.txt";

            AWSConfigs.AWSProfilesLocation = $"{Environment.GetEnvironmentVariable("UserProfile")}\\.aws\\credentials";

            Mock <IAmazonS3> s3Client = new Mock <IAmazonS3>();

            s3Client.Setup(x => x.GetPreSignedURL(It.IsAny <GetPreSignedUrlRequest>())).Returns($"https://{PresignedUrlBucket}.s3.amazonaws.com/{Key}?AWSAccessKeyId=AKIA1234567890123456&Expires=1559247929&Signature=OTgL4H7i%2FQOcTFpLM%2AV2LsFjONE%3D");

            GetPreSignedUrlRequest preSignedUrlRequest = new GetPreSignedUrlRequest()
            {
                BucketName = PresignedUrlBucket,
                Key        = Key,
                Expires    = DateTime.Now.AddMinutes(2),
                Protocol   = Protocol.HTTPS,
                Verb       = HttpVerb.PUT
            };

            string PreSignedUrl = s3Client.Object.GetPreSignedURL(preSignedUrlRequest);
            string Json         = $@"
{{
""requestType"":""create"",
""responseUrl"":""{PreSignedUrl}"",
""stackId"":""arn:aws:cloudformation:{Region}:{AccountNumber}:stack/stack-name/{Guid.NewGuid().ToString()}"",
""requestId"":""12345678"",
""resourceType"":""Custom::TestResource"",
""logicalResourceId"":""MyTestResource"",
""resourceProperties"":{{
""Role"":""{IAMRole}"",
""Name"":""TestPipeline"",
""InputBucket"":""{InputBucket}"",
""Notifications"":{{
""Error"": ""{NotificationTopic}"",
}},
""ContentConfig"":{{
""Bucket"":""{OutputBucket}""
}},
""ThumbnailConfig"":{{
""Bucket"":""{ThumbnailBucket}""
}}
}}
}}";

            Json = Json.Trim().Replace("\r", "").Replace("\n", "").Replace("\t", "");

            Func <CustomResourceRequest, ILambdaContext, Task <CustomResourceResponse> > Create = async(request, context) =>
            {
                try
                {
                    //AmazonElasticTranscoderConfig Config = new AmazonElasticTranscoderConfig();
                    //IAmazonElasticTranscoder Client = new AmazonElasticTranscoderClient(Config);
                    Mock <IAmazonElasticTranscoder> mockClient = new Mock <IAmazonElasticTranscoder>();
                    mockClient.Setup(x => x.CreatePipelineAsync(It.IsAny <CreatePipelineRequest>(), default(CancellationToken)))
                    .ReturnsAsync(new CreatePipelineResponse()
                    {
                        HttpStatusCode = HttpStatusCode.OK
                    });

                    context.LogInfo("Attempting to create a pipeline.");
                    CreatePipelineRequest  PipelineRequest = JsonConvert.DeserializeObject <CreatePipelineRequest>(JsonConvert.SerializeObject(request.ResourceProperties));
                    CreatePipelineResponse CreateResponse  = await mockClient.Object.CreatePipelineAsync(PipelineRequest);

                    if ((int)CreateResponse.HttpStatusCode < 200 || (int)CreateResponse.HttpStatusCode > 299)
                    {
                        return(new CustomResourceResponse(CustomResourceResponse.RequestStatus.FAILED, $"Received HTTP status code {(int)CreateResponse.HttpStatusCode}.", request));
                    }
                    else
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.SUCCESS,
                                   $"See the details in CloudWatch Log Stream: {context.LogStreamName}.",
                                   CreateResponse.Pipeline.Id,
                                   request.StackId,
                                   request.RequestId,
                                   request.LogicalResourceId,
                                   false,
                                   new Dictionary <string, object>()
                        {
                            { "Name", CreateResponse.Pipeline.Name },
                            { "Arn", CreateResponse.Pipeline.Arn },
                            { "Id", CreateResponse.Pipeline.Id }
                        }
                                   ));
                    }
                }
                catch (AmazonElasticTranscoderException e)
                {
                    context.LogError(e);

                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               Guid.NewGuid().ToString(),
                               request.StackId,
                               request.RequestId,
                               request.LogicalResourceId
                               ));
                }
                catch (Exception e)
                {
                    context.LogError(e);

                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               Guid.NewGuid().ToString(),
                               request.StackId,
                               request.RequestId,
                               request.LogicalResourceId
                               ));
                }
            };

            Func <CustomResourceRequest, ILambdaContext, Task <CustomResourceResponse> > Update = async(request, context) =>
            {
                try
                {
                    context.LogInfo("Initiating update for pipeline.");

                    UpdatePipelineRequest PipelineRequest = JsonConvert.DeserializeObject <UpdatePipelineRequest>(JsonConvert.SerializeObject(request.ResourceProperties));

                    ListPipelinesRequest Listing = new ListPipelinesRequest();

                    List <Pipeline>       Pipelines = new List <Pipeline>();
                    ListPipelinesResponse Pipes;

                    AmazonElasticTranscoderConfig Config = new AmazonElasticTranscoderConfig();
                    IAmazonElasticTranscoder      Client = new AmazonElasticTranscoderClient(Config);

                    do
                    {
                        Pipes = await Client.ListPipelinesAsync(Listing);

                        Pipelines.AddRange(Pipes.Pipelines.Where(x => x.Name.Equals(request.ResourceProperties["Name"] as string) &&
                                                                 x.InputBucket.Equals(request.ResourceProperties["InputBucket"]) &&
                                                                 x.Role.Equals(request.ResourceProperties["Role"])
                                                                 ));
                    } while (Pipes.NextPageToken != null);

                    if (Pipelines.Count > 1)
                    {
                        context.LogWarning($"{Pipelines.Count} pipelines were found matching the Name, InputBucket, and Role specified.");
                    }

                    if (Pipelines.Count > 0)
                    {
                        PipelineRequest.Id = Pipelines.First().Id;

                        UpdatePipelineResponse UpdateResponse = await Client.UpdatePipelineAsync(PipelineRequest);

                        if ((int)UpdateResponse.HttpStatusCode < 200 || (int)UpdateResponse.HttpStatusCode > 299)
                        {
                            return(new CustomResourceResponse(CustomResourceResponse.RequestStatus.FAILED, $"Received HTTP status code {(int)UpdateResponse.HttpStatusCode}.", request));
                        }
                        else
                        {
                            return(new CustomResourceResponse(
                                       CustomResourceResponse.RequestStatus.SUCCESS,
                                       $"See the details in CloudWatch Log Stream: {context.LogStreamName}.",
                                       request,
                                       false,
                                       new Dictionary <string, object>()
                            {
                                { "Name", UpdateResponse.Pipeline.Name },
                                { "Arn", UpdateResponse.Pipeline.Arn },
                                { "Id", UpdateResponse.Pipeline.Id }
                            }
                                       ));
                        }
                    }
                    else
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.FAILED,
                                   "No pipelines could be found with the matching characteristics.",
                                   request
                                   ));
                    }
                }
                catch (AmazonElasticTranscoderException e)
                {
                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               request
                               ));
                }
                catch (Exception e)
                {
                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               request
                               ));
                }
            };

            Func <CustomResourceRequest, ILambdaContext, Task <CustomResourceResponse> > Delete = async(request, context) =>
            {
                try
                {
                    context.LogInfo("Attempting to delete a pipeline.");

                    ListPipelinesRequest Listing = new ListPipelinesRequest();

                    List <Pipeline>       Pipelines = new List <Pipeline>();
                    ListPipelinesResponse Pipes;

                    AmazonElasticTranscoderConfig Config = new AmazonElasticTranscoderConfig();
                    IAmazonElasticTranscoder      Client = new AmazonElasticTranscoderClient(Config);

                    do
                    {
                        Pipes = await Client.ListPipelinesAsync(Listing);

                        Pipelines.AddRange(Pipes.Pipelines.Where(x => x.Name.Equals(request.ResourceProperties["Name"] as string) &&
                                                                 x.InputBucket.Equals(request.ResourceProperties["InputBucket"]) &&
                                                                 x.Role.Equals(request.ResourceProperties["Role"])
                                                                 ));
                    } while (Pipes.NextPageToken != null);

                    if (Pipelines.Count > 1)
                    {
                        context.LogWarning($"{Pipelines.Count} pipelines were found matching the Name, InputBucket, and Role specified.");
                    }

                    if (Pipelines.Count > 0)
                    {
                        DeletePipelineRequest PipelineRequest = new DeletePipelineRequest()
                        {
                            Id = Pipelines.First().Id
                        };

                        DeletePipelineResponse DeleteResponse = await Client.DeletePipelineAsync(PipelineRequest);

                        if ((int)DeleteResponse.HttpStatusCode < 200 || (int)DeleteResponse.HttpStatusCode > 299)
                        {
                            return(new CustomResourceResponse(CustomResourceResponse.RequestStatus.FAILED, $"Received HTTP status code {(int)DeleteResponse.HttpStatusCode}.", request));
                        }
                        else
                        {
                            return(new CustomResourceResponse(
                                       CustomResourceResponse.RequestStatus.SUCCESS,
                                       $"See the details in CloudWatch Log Stream: {context.LogStreamName}.",
                                       request,
                                       false
                                       ));
                        }
                    }
                    else
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.SUCCESS,
                                   "No pipelines could be found with the matching characteristics.",
                                   request
                                   ));
                    }
                }
                catch (AmazonElasticTranscoderException e)
                {
                    // If the pipeline doesn't exist, consider it deleted
                    if (e.StatusCode == HttpStatusCode.NotFound)
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.SUCCESS,
                                   $"See the details in CloudWatch Log Stream: {context.LogStreamName}.",
                                   request
                                   ));
                    }
                    else
                    {
                        return(new CustomResourceResponse(
                                   CustomResourceResponse.RequestStatus.FAILED,
                                   e.Message,
                                   request
                                   ));
                    }
                }
                catch (Exception e)
                {
                    return(new CustomResourceResponse(
                               CustomResourceResponse.RequestStatus.FAILED,
                               e.Message,
                               request
                               ));
                }
            };

            CustomResourceRequest        customResourceRequest = JsonConvert.DeserializeObject <CustomResourceRequest>(Json);
            Mock <ICustomResourceHelper> mockHelper            = new Mock <ICustomResourceHelper>();

            mockHelper.Setup(x => x.PutCustomResourceResponseAsync(It.IsAny <CustomResourceRequest>(), It.IsAny <CustomResourceResponse>()))
            .ReturnsAsync(new CustomResourceResult(customResourceRequest, new CustomResourceResponse(RequestStatus.SUCCESS, "", customResourceRequest), new HttpResponseMessage(HttpStatusCode.OK)));

            ICustomResourceHandler Handler = new CustomResourceFactory(Create, Update, Delete, mockHelper.Object);

            TestLambdaLogger  TestLogger    = new TestLambdaLogger();
            TestClientContext ClientContext = new TestClientContext();

            TestLambdaContext Context = new TestLambdaContext()
            {
                FunctionName    = "ElasticTranscoderPipelineCreation",
                FunctionVersion = "1",
                Logger          = TestLogger,
                ClientContext   = ClientContext,
                LogGroupName    = "aws/lambda/ElasticTranscoderPipeline",
                LogStreamName   = Guid.NewGuid().ToString()
            };

            // ACT

            CustomResourceResult Response = await Handler.ExecuteAsync(customResourceRequest, Context);

            // ASSERT
            Assert.NotNull(Response);
            Assert.NotNull(Response.Response);
            Assert.NotNull(Response.S3Response);
            Assert.True(Response.IsSuccess);
        }
Esempio n. 16
0
        public void BasicModify()
        {
            TestClientContext.MergeOption             = Microsoft.OData.Client.MergeOption.OverwriteChanges;
            TestClientContext.IgnoreMissingProperties = true;
            // AddRelatedObject
            AccountPlus newAccount1 = new AccountPlus()
            {
                AccountIDPlus     = 110,
                CountryRegionPlus = "CN",
                AccountInfoPlus   = new AccountInfoPlus()
                {
                    FirstNamePlus = "New",
                    LastNamePlus  = "Boy"
                }
            };

            PaymentInstrumentPlus newPI = new PaymentInstrumentPlus()
            {
                PaymentInstrumentIDPlus = 110901,
                FriendlyNamePlus        = "110's first PI",
                CreatedDatePlus         = new DateTimeOffset(new DateTime(2012, 12, 10))
            };

            TestClientContext.AddToAccountsPlus(newAccount1);
            TestClientContext.AddRelatedObject(newAccount1, "MyPaymentInstruments", newPI);
            TestClientContext.SaveChanges();

            var r1 = TestClientContext.AccountsPlus.Where(account => account.AccountIDPlus == 110).Single();

            Assert.AreEqual("Boy", r1.AccountInfoPlus.LastNamePlus);
            var r2 = TestClientContext.CreateQuery <PaymentInstrumentPlus>("Accounts(110)/MyPaymentInstruments")
                     .Where(pi => pi.PaymentInstrumentIDPlus == 110901).Single();

            Assert.AreEqual("110's first PI", r2.FriendlyNamePlus);

            //UpdateObject
            newAccount1.CountryRegionPlus = "US";
            TestClientContext.UpdateObject(newAccount1);
            TestClientContext.SaveChanges();

            r1 = TestClientContext.AccountsPlus.Where(account => account.AccountIDPlus == 110).Single();
            Assert.AreEqual("US", r1.CountryRegionPlus);

            //UpdateRelatedObject
            var myGiftCard = new GiftCardPlus()
            {
                GiftCardIDPlus     = 11111,
                GiftCardNOPlus     = "11111",
                AmountPlus         = 20,
                ExperationDatePlus = new DateTimeOffset(2015, 12, 1, 0, 0, 0, new TimeSpan(0))
            };

            TestClientContext.UpdateRelatedObject(newAccount1, "MyGiftCard", myGiftCard);
            TestClientContext.SaveChanges();

            r1 = TestClientContext.AccountsPlus.Expand(account => account.MyGiftCardPlus).Where(account => account.AccountIDPlus == 110).Single();
            Assert.AreEqual(11111, r1.MyGiftCardPlus.GiftCardIDPlus);

            //Add Derived Object
            CustomerPlus customerPlus = new CustomerPlus()
            {
                FirstNamePlus  = "Nelson",
                MiddleNamePlus = "S.",
                LastNamePlus   = "Black",
                NumbersPlus    = new ObservableCollection <string> {
                    "111-111-1111"
                },
                EmailsPlus = new ObservableCollection <string> {
                    "*****@*****.**"
                },
                PersonIDPlus = 10001,
                BirthdayPlus = new DateTimeOffset(new DateTime(1957, 4, 3)),
                CityPlus     = "London",
                HomePlus     = GeographyPoint.Create(32.1, 23.1),
                TimeBetweenLastTwoOrdersPlus = new TimeSpan(1),
                HomeAddressPlus = new HomeAddressPlus()
                {
                    CityPlus       = "London",
                    PostalCodePlus = "98052",
                    StreetPlus     = "1 Microsoft Way",
                    FamilyNamePlus = "Black's Family"
                },
            };

            var ordersPlus = new ODataClient.DataServiceCollection <OrderPlus>(TestClientContext)
            {
                new OrderPlus()
                {
                    OrderIDPlus         = 11111111,
                    OrderDatePlus       = new DateTimeOffset(new DateTime(2011, 5, 29, 14, 21, 12)),
                    ShelfLifePlus       = new TimeSpan(1),
                    OrderShelfLifesPlus = new ObservableCollection <TimeSpan>()
                    {
                        new TimeSpan(1)
                    }
                }
            };

            TestClientContext.AddToPeoplePlus(customerPlus);
            TestClientContext.SaveChanges();
            var customer1 = TestClientContext.CustomersPlus.Where(c => c.PersonIDPlus == 10001).Single();

            TestClientContext.AddLink(customer1, "Orders", ordersPlus[0]);
            TestClientContext.SaveChanges();

            TestClientContext.Detach(customerPlus);
            TestClientContext.SaveChanges();

            var customer = TestClientContext.CustomersPlus.Expand(p => (p as CustomerPlus).OrdersPlus).Where(p => p.PersonIDPlus == 10001).SingleOrDefault();

            Assert.AreEqual(((CustomerPlus)customer).CityPlus, "London");
            Assert.AreEqual(((HomeAddressPlus)(customer.HomeAddressPlus)).FamilyNamePlus, "Black's Family");
            Assert.AreEqual(((CustomerPlus)customer).OrdersPlus.Count, 1);

            var order = TestClientContext.OrdersPlus.Where(p => p.OrderIDPlus == 11111111).SingleOrDefault();

            Assert.AreEqual(order.OrderShelfLifesPlus.Count, 1);

            // DeleteObject
            TestClientContext.DeleteObject(newAccount1);
            TestClientContext.SaveChanges();
            var accounts = TestClientContext.AccountsPlus.ToList();

            Assert.IsTrue(!accounts.Any(ac => ac.AccountIDPlus == 110));

            // SetLink
            var person1 = TestClientContext.PeoplePlus.Where((p) => p.PersonIDPlus == 1).Single();
            var person2 = TestClientContext.PeoplePlus.Where((p) => p.PersonIDPlus == 2).Single();

            TestClientContext.SetLink(person1, "Parent", person2);
            TestClientContext.SaveChanges();

            person1 = TestClientContext.PeoplePlus.Expand(d => d.ParentPlus).Where((p) => p.PersonIDPlus == 1).Single();
            Assert.IsNotNull(person1.ParentPlus);
            Assert.IsNotNull(person1.ParentPlus.PersonIDPlus == 2);

            // SetLink : Bug, SetLink to Null will not update the client object.
            TestClientContext.SetLink(person1, "Parent", null);
            TestClientContext.SaveChanges();

            person1.ParentPlus = null;
            var person3 = TestClientContext.PeoplePlus.Expand(d => d.ParentPlus).Where((p) => p.PersonIDPlus == 1).Single();

            Assert.IsNull(person3.ParentPlus);

            //AddLink
            var            companyPlus = TestClientContext.CompanyPlus.GetValue();
            DepartmentPlus department  = new DepartmentPlus()
            {
                DepartmentIDPlus = 100001,
                NamePlus         = "ID" + 100001,
            };

            TestClientContext.AddToDepartmentsPlus(department);
            TestClientContext.AddLink(companyPlus, "Departments", department);
            TestClientContext.SaveChanges();

            TestClientContext.LoadProperty(companyPlus, "Departments");
            Assert.IsTrue(companyPlus.DepartmentsPlus.Any(d => d.DepartmentIDPlus == department.DepartmentIDPlus));

            //Delete Link
            TestClientContext.DeleteLink(companyPlus, "Departments", department);
            TestClientContext.SaveChanges();

            TestClientContext.LoadProperty(companyPlus, "Departments");
            Assert.IsTrue(!companyPlus.DepartmentsPlus.Any(d => d.DepartmentIDPlus == department.DepartmentIDPlus));
        }
Esempio n. 17
0
        public void DerivedTypeSingletonClientTest()
        {
            //Query Singleton
            TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges;
            var company = TestClientContext.PublicCompany.GetValue();

            Assert.IsTrue(company != null);

            //Update DerivedType Property and Verify
            PublicCompany publicCompany = company as PublicCompany;

            publicCompany.Name          = "UpdatedName";
            publicCompany.StockExchange = "Updated StockExchange";
            TestClientContext.UpdateObject(publicCompany);
            TestClientContext.SaveChanges(Microsoft.OData.Client.SaveChangesOptions.ReplaceOnUpdate);

            //Query Singleton Property - Select
            var name = TestClientContext.PublicCompany.Select(c => c.Name).GetValue();

            Assert.IsTrue(name == "UpdatedName");
            company = TestClientContext.CreateSingletonQuery <Company>("PublicCompany").Single();
            Assert.IsTrue((company as PublicCompany).StockExchange == "Updated StockExchange");

            //Query properties of DerivedType
            var stockExchange = TestClientContext.PublicCompany.Select(c => (c as PublicCompany).StockExchange).GetValue();

            Assert.IsTrue(stockExchange == "Updated StockExchange");

            //Projection with properties - Select
            publicCompany = TestClientContext.PublicCompany.Select(c =>
                                                                   new PublicCompany {
                CompanyID = c.CompanyID, Name = c.Name, StockExchange = (c as PublicCompany).StockExchange
            }).GetValue();
            Assert.IsTrue(publicCompany != null);
            Assert.IsTrue(publicCompany.Name == "UpdatedName");
            Assert.IsTrue(publicCompany.StockExchange == "Updated StockExchange");

            company = TestClientContext.CreateSingletonQuery <Company>("PublicCompany").Single();

            //Load Navigation Property
            //Collection
            TestClientContext.LoadProperty(company, "Assets");
            Assert.IsTrue((company as PublicCompany).Assets != null);
            Assert.IsTrue((company as PublicCompany).Assets.Count == 2);

            ////Single Enity
            TestClientContext.LoadProperty(company, "Club");
            Assert.IsTrue((company as PublicCompany).Club != null);

            //Singleton
            TestClientContext.LoadProperty(publicCompany, "LabourUnion");
            Assert.IsTrue((company as PublicCompany).LabourUnion != null);

            //Add Contained Navigation Property - Collection of derived type
            Random rand        = new Random();
            int    tmpAssertId = rand.Next();
            Asset  tmpAssert   = new Asset()
            {
                AssetID = tmpAssertId,
                Name    = tmpAssertId + "Name",
                Number  = tmpAssertId
            };

            TestClientContext.AddRelatedObject(publicCompany, "Assets", tmpAssert);
            TestClientContext.SaveChanges();

            //Query contained Navigation Property - Collection of derived type
            company = TestClientContext.PublicCompany.Expand(c => (c as PublicCompany).Assets).GetValue();
            Assert.IsTrue(company != null);
            Assert.IsTrue((company as PublicCompany).Assets.Any(a => a.AssetID == tmpAssertId));

            TestClientContext.DeleteObject(tmpAssert);
            TestClientContext.SaveChanges();

            company = TestClientContext.PublicCompany.Expand(c => (c as PublicCompany).Assets).GetValue();
            Assert.IsTrue(company != null);
            Assert.IsTrue(!(company as PublicCompany).Assets.Any(a => a.AssetID == tmpAssertId));

            company = TestClientContext.PublicCompany.Expand(c => (c as PublicCompany).Club).GetValue();
            Assert.IsTrue(company != null);
            Assert.IsTrue((company as PublicCompany).Club != null);

            //Updated Conatined Navigation Property - SingleEntity of derived type
            var club = (company as PublicCompany).Club;

            club.Name = "UpdatedClubName";
            TestClientContext.UpdateRelatedObject(company, "Club", club);
            TestClientContext.SaveChanges();

            //Query Contained Navigation Property - Single Entity of derived type
            publicCompany = TestClientContext.PublicCompany.Select(c => new PublicCompany {
                CompanyID = c.CompanyID, Club = (c as PublicCompany).Club
            }).GetValue();
            Assert.IsTrue(publicCompany != null);
            Assert.IsTrue(publicCompany.Club != null);
            Assert.IsTrue(publicCompany.Club.Name == "UpdatedClubName");

            //Projection with Navigation property of derived type - Singleton
            company = TestClientContext.PublicCompany.Expand(c => (c as PublicCompany).LabourUnion).GetValue();

            //Update Navigation property of derived Type - Singleton
            var labourUnion = (company as PublicCompany).LabourUnion;

            labourUnion.Name = "UpdatedLabourUnionName";
            TestClientContext.UpdateRelatedObject(publicCompany, "LabourUnion", labourUnion);
            TestClientContext.SaveChanges();

            //Query singleton of derived type.
            publicCompany = TestClientContext.PublicCompany.Select(c => new PublicCompany {
                CompanyID = c.CompanyID, LabourUnion = (c as PublicCompany).LabourUnion
            }).GetValue();
            Assert.IsTrue(publicCompany != null);
            Assert.IsTrue(publicCompany.LabourUnion != null);
        }
Esempio n. 18
0
        public void SingletonClientTest()
        {
            Random rand = new Random();

            ODataFormat[] formats = { ODataFormat.Json };
            foreach (var format in formats)
            {
                //Query Singleton
                TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges;
                var company = TestClientContext.Company.GetValue();
                Assert.IsTrue(company != null);

                //Update Singleton Property and Verify
                company.CompanyCategory = CompanyCategory.Communication;
                company.Name            = "UpdatedName";
                company.Address.City    = "UpdatedCity";
                TestClientContext.UpdateObject(company);
                TestClientContext.SaveChanges(Microsoft.OData.Client.SaveChangesOptions.ReplaceOnUpdate);

                //Query Singleton Property - Select
                var companyCategory = TestClientContext.Company.Select(c => c.CompanyCategory).GetValue();
                Assert.IsTrue(companyCategory == CompanyCategory.Communication);
                var city = TestClientContext.CreateSingletonQuery <string>("Company/Address/City").Execute().Single();
                Assert.IsTrue(city == "UpdatedCity");
                var name = TestClientContext.Execute <string>(new Uri("Company/Name", UriKind.Relative)).Single();
                Assert.IsTrue(name == "UpdatedName");

                //Projection with properties - Select
                company = TestClientContext.Company.Select(c => new Company {
                    CompanyID = c.CompanyID, Address = c.Address, Name = c.Name
                }).GetValue();
                Assert.IsTrue(company != null);
                Assert.IsTrue(company.Name == "UpdatedName");

                //Load Navigation Property
                //Singleton
                TestClientContext.LoadProperty(company, "VipCustomer");
                Assert.IsTrue(company.VipCustomer != null);

                //Collection
                TestClientContext.LoadProperty(company, "Departments");
                Assert.IsTrue(company.Departments != null);
                Assert.IsTrue(company.Departments.Count > 0);

                //Single Entity
                TestClientContext.LoadProperty(company, "CoreDepartment");
                Assert.IsTrue(company.CoreDepartment != null);

                //Add Navigation Property - Collection
                company = TestClientContext.Company.GetValue();
                int        tmpDepartmentID     = rand.Next();
                int        tmpCoreDepartmentID = rand.Next();
                Department department          = new Department()
                {
                    DepartmentID = tmpDepartmentID,
                    Name         = "ID" + tmpDepartmentID,
                };
                Department coreDepartment = new Department()
                {
                    DepartmentID = tmpCoreDepartmentID,
                    Name         = "ID" + tmpCoreDepartmentID,
                };
                TestClientContext.AddToDepartments(department);
                TestClientContext.AddLink(company, "Departments", department);
                TestClientContext.SaveChanges();

                TestClientContext.AddToDepartments(coreDepartment);
                TestClientContext.AddLink(company, "Departments", coreDepartment);
                TestClientContext.SaveChanges();

                TestClientContext.Departments.ToList();
                //Projection with Navigation properties - Select
                company = TestClientContext.Company.Select(c => new Company {
                    CompanyID = c.CompanyID, Departments = c.Departments
                }).GetValue();
                Assert.IsTrue(company != null);
                Assert.IsTrue(company.Departments.Any(c => c.DepartmentID == tmpDepartmentID));
                Assert.IsTrue(company.Departments.Any(c => c.DepartmentID == tmpCoreDepartmentID));

                //Update Navigation Property - Single Entity
                TestClientContext.SetLink(company, "CoreDepartment", coreDepartment);
                TestClientContext.SaveChanges();

                //Projection with Navigation properties - Select
                company = TestClientContext.Company.Select(c => new Company {
                    CompanyID = c.CompanyID, CoreDepartment = c.CoreDepartment
                }).GetValue();
                Assert.IsTrue(company != null);
                Assert.IsTrue(company.CoreDepartment.DepartmentID == tmpCoreDepartmentID);

                //Update EntitySet's Navigation Property - Singleton
                TestClientContext.SetLink(department, "Company", company);
                TestClientContext.SaveChanges(Microsoft.OData.Client.SaveChangesOptions.ReplaceOnUpdate);

                //Query(Expand) EntitySet's Navigation Property - Singleton
                department = TestClientContext.Departments.Expand(d => d.Company).Where(d => d.DepartmentID == tmpDepartmentID).Single();
                Assert.IsTrue(department != null);
                Assert.IsTrue(department.Company.CompanyID == company.CompanyID);

                //Delete Navigation Property - EntitySet
                TestClientContext.DeleteLink(company, "Departments", department);
                TestClientContext.SaveChanges();

                //Projection with Navigation Property - EntitySet
                company.Departments = null;
                company             = TestClientContext.Company.Select(c => new Company {
                    CompanyID = c.CompanyID, Departments = c.Departments
                }).GetValue();
                Assert.IsTrue(company != null);
                Assert.IsTrue(!company.Departments.Any(c => c.DepartmentID == tmpDepartmentID));

                //Query Singleton's Navigation Property - Singleton
                company = TestClientContext.Company.Select(c => new Company {
                    CompanyID = c.CompanyID, VipCustomer = c.VipCustomer
                }).GetValue();
                Assert.IsTrue(company != null);
                Assert.IsTrue(company.VipCustomer != null);

                //Query Singleton again with Execute
                var vipCustomer = TestClientContext.Execute <Customer>(new Uri("VipCustomer", UriKind.Relative)).Single();

                //Update Singleton's Navigation property - Singleton
                vipCustomer.LastName = "UpdatedLastName";
                TestClientContext.UpdateRelatedObject(company, "VipCustomer", vipCustomer);
                TestClientContext.SaveChanges();

                company.VipCustomer = null;
                company             = TestClientContext.Company.Expand(c => c.VipCustomer).GetValue();
                Assert.IsTrue(company != null);
                Assert.IsTrue(company.VipCustomer != null);
                Assert.IsTrue(company.VipCustomer.LastName == "UpdatedLastName");

                //Update Navigation Property - Delete the Singleton navigation
                TestClientContext.SetLink(company, "VipCustomer", null);
                TestClientContext.SaveChanges();

                //Expand Navigation Property - Singleton
                company.VipCustomer = null;
                company             = TestClientContext.Company.Expand(c => c.VipCustomer).GetValue();
                Assert.IsTrue(company != null);
                Assert.IsTrue(company.VipCustomer == null);

                //TODO: AttachTo doesn't support singleton.
                //TestClientContext = new InMemoryEntities(ServiceBaseUri);
                //TestClientContext.AttachTo("Company", company);
                //TestClientContext.AttachTo("VipCustomer", vipCustomer);
                //TestClientContext.SetLink(company, "VipCustomer", vipCustomer);
                //TestClientContext.SaveChanges();

                //Update Navigation Property - Singleton
                vipCustomer = TestClientContext.VipCustomer.GetValue();
                TestClientContext.SetLink(company, "VipCustomer", vipCustomer);
                TestClientContext.SaveChanges();
                company = TestClientContext.Company.Select(c => new Company {
                    CompanyID = c.CompanyID, VipCustomer = c.VipCustomer
                }).GetValue();
                Assert.IsTrue(company != null);
                Assert.IsTrue(company.VipCustomer != null);
            }
        }
Esempio n. 19
0
        private async Task TestManifestFile()
        {
            // ARRANGE
            string            Json          = $@"
{{
    ""Records"": [
      {{
        ""eventVersion"": ""2.0"",
        ""eventSource"": ""aws:s3"",
        ""awsRegion"": ""{Region}"",
        ""eventTime"": ""2018-10-01T01:00:00.000Z"",
        ""eventName"": ""ObjectCreated:Put"",
        ""userIdentity"": {{
          ""principalId"": ""EXAMPLE""
        }},
        ""requestParameters"": {{
          ""sourceIPAddress"": ""127.0.0.1""
        }},
        ""responseElements"": {{
          ""x-amz-request-id"": ""EXAMPLE123456789"",
          ""x-amz-id-2"": ""EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH""
        }},
        ""s3"": {{
          ""s3SchemaVersion"": ""1.0"",
          ""configurationId"": ""testConfigRule"",
          ""bucket"": {{
            ""name"": ""{SourceBucket}"",
            ""ownerIdentity"": {{
              ""principalId"": ""EXAMPLE""
            }},
            ""arn"": ""arn:{AWSPartition}:s3:::{SourceBucket}""
          }},
          ""object"": {{
            ""key"": ""{SourceManifestKey}"",
            ""size"": 7658,
            ""eTag"": ""0409fb62239b5d5daa27a2a1982c4dc2"",
            ""sequencer"": ""0A1B2C3D4E5F678901""
          }}
      }}
    }}
  ]
}}
";
            TestLambdaLogger  TestLogger    = new TestLambdaLogger();
            TestClientContext ClientContext = new TestClientContext();

            TestLambdaContext Context = new TestLambdaContext()
            {
                FunctionName       = "CURManager",
                FunctionVersion    = "1",
                Logger             = TestLogger,
                ClientContext      = ClientContext,
                LogGroupName       = "aws/lambda/CURManager",
                LogStreamName      = Guid.NewGuid().ToString(),
                RemainingTime      = TimeSpan.FromSeconds(300),
                InvokedFunctionArn = $"arn:{AWSPartition}:lambda:{Region}:{AccountNumber}:function:CURManager"
            };

            S3Event Event = JsonConvert.DeserializeObject <S3Event>(Json);

            Environment.SetEnvironmentVariable("DESTINATION_S3_BUCKET", DestinationBucket);

            Entrypoint Entry = new Entrypoint();

            // ACT

            await Entry.Exec(Event, Context);

            // ASSERT

            // No exception
        }
        public void AttachPinningTestWithEntitySetResolver()
        {
            const string expectedOutput = @"http://resolved.org/EntityS%C3%A9t1('foo%2B%2Fbar')
http://resolved.org/EntityS%C3%A9t2(Property1='fo%2Bo',Property2='b%2Far')
http://resolved.org/EntitySet1('foo')
http://resolved.org/EntitySet2(Property1='foo',Property2='bar')
http://resolved.org/EntitySet1('foo')
http://resolved.org/EntitySet2(Property1='foo',Property2='bar')
http://resolved.org/EntitySet1/Fake(1)('foo')
http://resolved.org/EntitySet1/Fake(1)('foo')
http://resolved.org/EntitySet1/Fake(1)('foo')
http://resolved.org/EntitySet1/Fake(1)('foo')
http://resolved.org/EntitySet2/Fake(1)/Navigation(Property1='foo',Property2='bar')
http://resolved.org/EntitySet2/Fake(1)/Navigation(Property1='foo',Property2='bar')
http://resolved.org/EntitySet2/Fake(1)/Navigation(Property1='foo',Property2='bar')
http://resolved.org/EntitySet2/Fake(1)/Navigation(Property1='foo',Property2='bar')
";
            var ctx = new TestClientContext { ResolveEntitySet = s => new Uri("http://resolved.org/" + s) };
            RunAttachPinningTest(ctx, expectedOutput);

            ctx = new TestClientContext { ResolveEntitySet = s => new Uri("http://resolved.org/" + s + '/') };
            RunAttachPinningTest(ctx, expectedOutput);
        }
Esempio n. 21
0
 public void Setup()
 {
     _sut = new TestClientContext();
 }
Esempio n. 22
0
        public void DelayQueryOnSingleton()
        {
            TestClientContext.MergeOption = MergeOption.OverwriteChanges;

            var company = TestClientContext.Company.GetValue();

            Assert.IsNotNull(company);

            //LoadProperty
            TestClientContext.LoadProperty(company, "Departments");
            Assert.IsNotNull(company.Departments);

            //Query Property
            var name = TestClientContext.Company.Select(c => c.Name).GetValue();

            Assert.AreEqual(company.Name, name);

            //Projection
            var companyQuery = TestClientContext.Company.Select(c => new Company()
            {
                Name = c.Name, Address = c.Address
            });
            var company2 = companyQuery.GetValue();

            Assert.IsTrue(companyQuery.RequestUri.OriginalString.EndsWith("/Company?$select=Name,Address"));
            Assert.IsNotNull(company2.Address);

            //Expand
            companyQuery = TestClientContext.Company.Expand(c => c.VipCustomer.Company);
            var company3 = companyQuery.GetValue();

            Assert.IsTrue(companyQuery.RequestUri.OriginalString.EndsWith("/Company?$expand=VipCustomer($expand=Company)"));
            Assert.IsNotNull(company);

            //Projection with Navigation
            companyQuery = TestClientContext.Company.Select(c => new Company()
            {
                Name = c.Name, Address = c.Address, Departments = c.Departments
            });
            companyQuery.GetValue();
            Assert.IsTrue(companyQuery.RequestUri.OriginalString.EndsWith("/Company?$expand=Departments&$select=Name,Address"));
            Assert.IsNotNull(company2.Address);

            //Query navigation property which is an collection
            var employeesQuery = TestClientContext.Company.Employees;
            var employees      = employeesQuery.Execute();

            Assert.IsTrue(employeesQuery.RequestUri.OriginalString.EndsWith("/Company/Employees"));
            Assert.IsNotNull(employees);

            //Query Navigation Property which is an single entity
            var company4Query = TestClientContext.Company.VipCustomer.Company;
            var company4      = company4Query.GetValue();

            Assert.IsTrue(company4Query.RequestUri.OriginalString.EndsWith("/Company/VipCustomer/Company"));
            Assert.IsNotNull(company4Query);

            //Query navigation property which is from a singleton
            var coreDepartmentQuery = TestClientContext.Company.CoreDepartment;
            var coreDepartment      = coreDepartmentQuery.GetValue();

            Assert.IsTrue(coreDepartmentQuery.RequestUri.OriginalString.EndsWith("/Company/CoreDepartment"));
            Assert.IsNotNull(coreDepartment);

            //QueryOption on navigation property
            employeesQuery = TestClientContext.Company.Employees.Where(e => e.PersonID > 0) as DataServiceQuery <Employee>;
            employees      = employeesQuery.Execute();
            Assert.IsTrue(employeesQuery.RequestUri.OriginalString.EndsWith("/Company/Employees?$filter=PersonID gt 0"));
            Assert.IsNotNull(employees);

            //Function Bound on Singleton
            var getEmployeesCountQuery = TestClientContext.Company.GetEmployeesCount();
            var count = getEmployeesCountQuery.GetValue();

            Assert.IsTrue(getEmployeesCountQuery.RequestUri.OriginalString.EndsWith("/Company/Microsoft.Test.OData.Services.ODataWCFService.GetEmployeesCount()"));
            Assert.IsTrue(count > 0);

            //Function Bound on Singleton
            var company5 = TestClientContext.Company.GetValue();

            getEmployeesCountQuery = company.GetEmployeesCount();
            count = getEmployeesCountQuery.GetValue();
            Assert.IsTrue(getEmployeesCountQuery.RequestUri.OriginalString.EndsWith("/Company/Microsoft.Test.OData.Services.ODataWCFService.GetEmployeesCount()"));
            Assert.IsTrue(count > 0);

            //Query Action bound on Navigation Property
            var getHomeAddressQuery = TestClientContext.Company.VipCustomer.GetHomeAddress();
            var address             = getHomeAddressQuery.GetValue();

            Assert.IsTrue(getHomeAddressQuery.RequestUri.OriginalString.EndsWith("/Company/VipCustomer/Microsoft.Test.OData.Services.ODataWCFService.GetHomeAddress()"));
            Assert.IsNotNull(address);
        }
Esempio n. 23
0
        public void OpenComplexType()
        {
            //Update entity with open complex type
            AccountPlus account = new AccountPlus()
            {
                AccountIDPlus     = 1000000,
                CountryRegionPlus = "CN",
                AccountInfoPlus   = new AccountInfoPlus()
                {
                    FirstNamePlus  = "Peter",
                    MiddleNamePlus = "White",
                    LastNamePlus   = "Andy",
                    IsActivePlus   = true
                }
            };

            TestClientContext.AddToAccountsPlus(account);
            TestClientContext.SaveChanges();

            //Check account can be correctly desirialized.
            account = TestClientContext.AccountsPlus.Where(a => a.AccountIDPlus == 1000000).Single();
            Assert.IsNotNull(account);
            Assert.AreEqual(account.AccountInfoPlus.MiddleNamePlus, "White");
            Assert.IsTrue(account.AccountInfoPlus.IsActivePlus);

            //Update entity with open complex type
            var entry = new ODataEntry()
            {
                TypeName = ServerSideNameSpacePrefix + "Account"
            };

            entry.Properties = new[]
            {
                new ODataProperty {
                    Name = "AccountID", Value = 1000000
                },
                new ODataProperty
                {
                    Name  = "AccountInfo",
                    Value = new ODataComplexValue
                    {
                        TypeName   = ServerSideNameSpacePrefix + "AccountInfo",
                        Properties = new[]
                        {
                            new ODataProperty
                            {
                                Name  = "FirstName",
                                Value = "Peter"
                            },
                            new ODataProperty
                            {
                                Name  = "LastName",
                                Value = "Andy"
                            },
                            //Property that exists in Customer-Defined client code.
                            new ODataProperty
                            {
                                Name  = "MiddleName",
                                Value = "White2"
                            },
                            new ODataProperty
                            {
                                Name  = "IsActive",
                                Value = false,
                            },
                            //Property that doesn't exist in Customer-Defined client code.
                            new ODataProperty
                            {
                                Name  = "ShippingAddress",
                                Value = "#999, ZiXing Road"
                            }
                        }
                    }
                }
            };

            var settings = new ODataMessageWriterSettings();

            settings.PayloadBaseUri = ServiceBaseUri;

            var accountType = Model.FindDeclaredType(ServerSideNameSpacePrefix + "Account") as IEdmEntityType;
            var accountSet  = Model.EntityContainer.FindEntitySet("Accounts");

            var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri + "Accounts(1000000)"));

            requestMessage.SetHeader("Content-Type", MimeTypes.ApplicationJson);
            requestMessage.SetHeader("Accept", MimeTypes.ApplicationJson);
            requestMessage.Method = "PATCH";
            using (var messageWriter = new ODataMessageWriter(requestMessage, settings))
            {
                var odataWriter = messageWriter.CreateODataEntryWriter(accountSet, accountType);
                odataWriter.WriteStart(entry);
                odataWriter.WriteEnd();
            }

            var responseMessage = requestMessage.GetResponse();

            TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges;
            //Check account can be correctly desirialized.
            account = TestClientContext.AccountsPlus.Where(a => a.AccountIDPlus == 1000000).Single();
            Assert.IsNotNull(account);
            Assert.AreEqual(account.AccountInfoPlus.MiddleNamePlus, "White2");
            Assert.IsTrue(!account.AccountInfoPlus.IsActivePlus);
        }
Esempio n. 24
0
        public void DelayQueryOnEntitySet()
        {
            TestClientContext.MergeOption = MergeOption.OverwriteChanges;

            //Post an Product
            var product = Product.CreateProduct(10001, "10001", "2", 2.0f, 2, true);

            TestClientContext.AddToProducts(product);
            TestClientContext.SaveChanges();

            //Function Bound on EntitySet
            //TODO: Enable this support on server side
            var querySeniorEmployee = (TestClientContext.People.OfType <Employee>() as DataServiceQuery <Employee>).GetSeniorEmployees();

            Assert.IsTrue(querySeniorEmployee.RequestUri.OriginalString.EndsWith(
                              "People/Microsoft.Test.OData.Services.ODataWCFService.Employee/Microsoft.Test.OData.Services.ODataWCFService.GetSeniorEmployees()"));
            var queryEmployeeAddress = querySeniorEmployee.GetHomeAddress();

            Assert.IsTrue(queryEmployeeAddress.RequestUri.OriginalString.EndsWith(
                              "People/Microsoft.Test.OData.Services.ODataWCFService.Employee/Microsoft.Test.OData.Services.ODataWCFService.GetSeniorEmployees()/Microsoft.Test.OData.Services.ODataWCFService.GetHomeAddress()"));
            //var employee = querySeniorEmployee.GetValue();
            //Assert.IsNotNull(employee);

            //Action Bound on EntitySet
            var discountAction = TestClientContext.Products.Discount(50);

            Assert.IsTrue(discountAction.RequestUri.OriginalString.EndsWith("/Products/Microsoft.Test.OData.Services.ODataWCFService.Discount"));
            var products = discountAction.Execute();

            Assert.IsTrue(products.Count() > 0);

            //ByKey
            var queryProduct = TestClientContext.Products.ByKey(new Dictionary <string, object> {
                { "ProductID", 10001 }
            });

            product = queryProduct.GetValue();
            Assert.AreEqual(1, product.UnitPrice);
            Assert.IsTrue(queryProduct.RequestUri.OriginalString.EndsWith("/Products(10001)"));

            //Action Bound on Entity
            var expectedAccessLevel = AccessLevel.ReadWrite | AccessLevel.Execute;
            var accessLevelAction   = TestClientContext.Products.ByKey(new Dictionary <string, object> {
                { "ProductID", 10001 }
            }).AddAccessRight(expectedAccessLevel);

            Assert.IsTrue(accessLevelAction.RequestUri.OriginalString.EndsWith("/Products(10001)/Microsoft.Test.OData.Services.ODataWCFService.AddAccessRight"));
            var accessLevel = accessLevelAction.GetValue();

            Assert.IsTrue(accessLevel.Value.HasFlag(expectedAccessLevel));

            //Function Bound on Entity and return Collection of Entity
            var getProductDetailsAction = TestClientContext.Products.ByKey(new Dictionary <string, object> {
                { "ProductID", 5 }
            }).GetProductDetails(1);

            Assert.IsTrue(getProductDetailsAction.RequestUri.OriginalString.EndsWith("/Products(5)/Microsoft.Test.OData.Services.ODataWCFService.GetProductDetails(count=1)"));
            foreach (var pd in getProductDetailsAction)
            {
                //Check whether GetEnumerator works
                Assert.AreEqual(5, pd.ProductID);
            }

            //Composable Function
            //Won't execute since ODL doesn't support it now.
            var getRelatedProductAction = getProductDetailsAction.ByKey(new Dictionary <string, object> {
                { "ProductID", 5 }, { "ProductDetailID", 2 }
            }).GetRelatedProduct();

            Assert.IsTrue(getRelatedProductAction.RequestUri.OriginalString.EndsWith("/Products(5)/Microsoft.Test.OData.Services.ODataWCFService.GetProductDetails(count=1)(ProductID=5,ProductDetailID=2)/Microsoft.Test.OData.Services.ODataWCFService.GetRelatedProduct()"));
            //getRelatedProductAction.GetValue();

            //Complex query option
            var queryProducts = TestClientContext.Products.Where(p => p.ProductID > 3)
                                .Select(p => new Product()
            {
                Details = p.Details, Name = p.Name, ProductID = p.ProductID
            })
                                .Skip(3).Take(2) as DataServiceQuery <Product>;

            Assert.IsTrue(queryProducts.RequestUri.OriginalString.EndsWith("/Products?$filter=ProductID gt 3&$skip=3&$top=2&$expand=Details&$select=Name,ProductID"));
            foreach (var p in queryProducts)
            {
                Assert.IsTrue(p.ProductID > 3);
            }
        }
Esempio n. 25
0
        public void BasicQuery()
        {
            TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges;
            // Query a entity set
            var products1 = TestClientContext.ProductsPlus.ToList();

            Assert.AreEqual(5, products1.Count);

            // Query with expand (Linq)
            var products2 = TestClientContext.ProductsPlus.Expand(p => p.DetailsPlus).ToList();

            Assert.AreEqual(5, products2.Single(p => p.ProductIDPlus == 5).DetailsPlus.Count);

            // Query with expand (PropertyName)
            var products3 = TestClientContext.ProductsPlus.Expand("Details").ToList();

            Assert.AreEqual(5, products3.Single(p => p.ProductIDPlus == 5).DetailsPlus.Count);

            // Query a individual primitive property
            var product4 = TestClientContext.ProductsPlus.Where(p => p.ProductIDPlus == 5).Single();

            Assert.AreEqual("Cheetos", product4.NamePlus);

            // Query an Navigation Property
            TestClientContext.LoadProperty(product4, "Details");
            Assert.AreEqual(5, product4.DetailsPlus.Count);

            // Query a Derived entity.
            var people5 = TestClientContext.PeoplePlus.Where(p => p.PersonIDPlus == 1).Single();

            // Check the property from the derived type.
            Assert.AreEqual("Tokyo", people5.HomeAddressPlus.CityPlus);
            // Check the derived complex property.
            Assert.AreEqual("Cats", ((HomeAddressPlus)(people5.HomeAddressPlus)).FamilyNamePlus);
            // Check collection of PrimitiveTypes
            Assert.AreEqual(1, people5.EmailsPlus.Count);

            // Query with $select & $expand
            var accounts6 = TestClientContext.AccountsPlus
                            .Where(a => a.AccountIDPlus == 103)
                            .Select(a => new AccountPlus()
            {
                AccountIDPlus = a.AccountIDPlus, MyGiftCardPlus = a.MyGiftCardPlus, CountryRegionPlus = a.CountryRegionPlus
            });
            var account6 = accounts6.Single();

            Assert.IsNotNull(account6.MyGiftCardPlus);
            Assert.AreEqual(103, account6.AccountIDPlus);
            Assert.IsNull(account6.AccountInfoPlus);

            // Query with $filter by non-key property.
            var accounts7 = TestClientContext.AccountsPlus.Where(a => a.CountryRegionPlus == "CN").ToList();

            Assert.AreEqual(3, accounts7.Count);

            // Query with OrderBy
            var people8 = TestClientContext.PeoplePlus.OrderBy((p) => p.LastNamePlus).First();

            Assert.AreEqual(5, people8.PersonIDPlus);

            // Query with $count
            var count = TestClientContext.AccountsPlus.Count();

            Assert.AreEqual(count, 7);

            // Query with MultiKeys
            var productReview10 = TestClientContext.ProductReviewsPlus.Where(pd =>
                                                                             pd.ProductDetailIDPlus == 2 &&
                                                                             pd.ProductIDPlus == 5 &&
                                                                             pd.ReviewTitlePlus == "Special" &&
                                                                             pd.RevisionIDPlus == 1).First();

            Assert.AreEqual("Andy", productReview10.AuthorPlus);
        }
        public void AddNavigationProperty()
        {
            TestClientContext.MergeOption = MergeOption.OverwriteChanges;
            var truck = (TestClientContext.Trucks.Where(t => t.Key == "Key1")).Single();

            // Add Navigation Property to VehicleGPS in TruckType
            var newVehicleGPS = new VehicleGPSType()
            {
                Key           = "99",
                VehicleSpeed  = 100.1,
                StartLocation = new GeoLocation()
                {
                    Lat  = 1,
                    Long = 2,
                },
                EndLocation = new GeoLocation()
                {
                    Lat  = 3,
                    Long = 4,
                },
                CurrentLocation = new GeoLocation()
                {
                    Lat  = 1.2,
                    Long = 2.4,
                },
                LostSignalAlarm = new GPSLostSignalAlarmType()
                {
                    Severity          = 1,
                    LastKnownLocation = new GeoLocation()
                    {
                        Lat  = 2.1,
                        Long = 1.2,
                    }
                },
                Map = new MapType()
                {
                    MBytesDownloaded = 1.2,
                    ProviderName     = "TESTNEW",
                    Uri = "TESTNEW.TEST",
                }
            };

            TestClientContext.AddRelatedObject(truck, "VehicleGPSGroup", newVehicleGPS);
            TestClientContext.SaveChanges();

            TestClientContext.LoadProperty(truck, "VehicleGPSGroup");
            Assert.AreEqual(2, truck.VehicleGPSGroup.Count);

            // Add Navigation Property to VehicleGPSGroupFromGPS in TruckType
            var newVehicleGPSInGPS = new VehicleGPSType()
            {
                Key           = "102",
                VehicleSpeed  = 100.1,
                StartLocation = new GeoLocation()
                {
                    Lat  = 1,
                    Long = 2,
                },
                EndLocation = new GeoLocation()
                {
                    Lat  = 3,
                    Long = 4,
                },
                CurrentLocation = new GeoLocation()
                {
                    Lat  = 1.2,
                    Long = 2.4,
                },
                LostSignalAlarm = new GPSLostSignalAlarmType()
                {
                    Severity          = 1,
                    LastKnownLocation = new GeoLocation()
                    {
                        Lat  = 2.1,
                        Long = 1.2,
                    }
                },
                Map = new MapType()
                {
                    MBytesDownloaded = 1.2,
                    ProviderName     = "TESTNEW",
                    Uri = "TESTNEW.TEST",
                }
            };

            TestClientContext.AddRelatedObject(truck, "VehicleGPSGroupFromGPS", newVehicleGPSInGPS);
            TestClientContext.SaveChanges();

            TestClientContext.LoadProperty(truck, "VehicleGPSGroupFromGPS");
            Assert.AreEqual(2, truck.VehicleGPSGroupFromGPS.Count);
        }
Esempio n. 27
0
        public void OpenEntityType()
        {
            //UpdateOpenTypeSingleton
            var entry = new ODataEntry()
            {
                TypeName = ServerSideNameSpacePrefix + "PublicCompany"
            };

            entry.Properties = new[]
            {
                new ODataProperty
                {
                    Name  = "FullName",
                    Value = "MS Ltd."
                },
                new ODataProperty
                {
                    Name  = "PhoneNumber",
                    Value = "123-45678"
                },

                new ODataProperty
                {
                    Name  = "TotalAssets",
                    Value = 500000L,
                }
            };
            var settings = new ODataMessageWriterSettings();

            settings.PayloadBaseUri = ServiceBaseUri;
            settings.AutoComputePayloadMetadataInJson = true;

            var companyType      = Model.FindDeclaredType(ServerSideNameSpacePrefix + "PublicCompany") as IEdmEntityType;
            var companySingleton = Model.EntityContainer.FindSingleton("PublicCompany");

            var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri + "PublicCompany"));

            requestMessage.SetHeader("Content-Type", MimeTypes.ApplicationJson);
            requestMessage.SetHeader("Accept", MimeTypes.ApplicationJson);
            requestMessage.Method = "PATCH";
            using (var messageWriter = new ODataMessageWriter(requestMessage, settings))
            {
                var odataWriter = messageWriter.CreateODataEntryWriter(companySingleton, companyType);
                odataWriter.WriteStart(entry);
                odataWriter.WriteEnd();
            }

            var responseMessage = requestMessage.GetResponse();

            Assert.AreEqual(204, responseMessage.StatusCode);

            //Check account can be correctly desirialized.
            var company = TestClientContext.PublicCompanyPlus.GetValue();

            Assert.IsNotNull(company);
            Assert.AreEqual("MS Ltd.", company.FullNamePlus);
            Assert.AreEqual(500000, company.TotalAssetsPlus);

            TestClientContext.MergeOption = Microsoft.OData.Client.MergeOption.OverwriteChanges;
            company.FullNamePlus          = "MS2 Ltd.";
            company.TotalAssetsPlus       = 1000000;
            TestClientContext.UpdateObject(company);
            TestClientContext.SaveChanges();

            company.FullNamePlus    = null;
            company.TotalAssetsPlus = 0;
            company = TestClientContext.PublicCompanyPlus.GetValue();
            Assert.IsNotNull(company);
            Assert.AreEqual("MS2 Ltd.", company.FullNamePlus);
            Assert.AreEqual(1000000, company.TotalAssetsPlus);
        }
Esempio n. 28
0
        public void InsertAndUpdatePropertyValueUsingLinq()
        {
            TimeSpan timespan  = new TimeSpan((new Random()).Next());
            var      queryable = TestClientContext.Orders.Where(c => c.ShelfLife == timespan) as ODataClient.DataServiceQuery <Order>;

            Assert.IsTrue(queryable.RequestUri.OriginalString.EndsWith("/Orders?$filter=ShelfLife eq duration'" + XmlConvert.ToString(timespan) + "'", StringComparison.Ordinal));

            var result1 = queryable.ToList();

            Assert.IsTrue(result1.Count == 0);

            int orderID = (new Random()).Next();

            // create an entity
            Order order = new Order()
            {
                OrderID         = orderID,
                OrderDate       = new DateTimeOffset(new DateTime(2011, 3, 4, 16, 3, 57)),
                ShelfLife       = timespan,
                OrderShelfLifes = new ObservableCollection <TimeSpan>()
                {
                    timespan
                }
            };

            TestClientContext.AddToOrders(order);
            TestClientContext.SaveChanges();

            // query and verify
            var result2 = queryable.ToList();

            Assert.AreEqual(1, result2.Count);
            Assert.AreEqual(orderID, result2[0].OrderID);

            // update the Duration properties
            timespan              = new TimeSpan((new Random()).Next());
            order.ShelfLife       = timespan;
            order.OrderShelfLifes = new ObservableCollection <TimeSpan>()
            {
                timespan
            };
            TestClientContext.UpdateObject(order);
            TestClientContext.SaveChanges(ODataClient.SaveChangesOptions.ReplaceOnUpdate);

            // query Duration property
            var queryable2 = TestClientContext.Orders.Where(c => c.OrderID == orderID).Select(c => c.ShelfLife).FirstOrDefault();

            Assert.IsTrue(queryable2 != null);
            Assert.AreEqual(timespan, queryable2);

            // query collection of Duration property
            var queryable3 = (from c in TestClientContext.Orders
                              where c.OrderID == orderID
                              select c.OrderShelfLifes).FirstOrDefault();

            Assert.IsTrue(queryable3.Count == 1);
            Assert.AreEqual(timespan, queryable3[0]);

            // delete entity and validate
            TestClientContext.DeleteObject(order);
            TestClientContext.SaveChanges(ODataClient.SaveChangesOptions.ReplaceOnUpdate);
            var queryable4 = TestClientContext.Execute <Order>(new Uri("Orders()?$filter=ShelfLife eq duration'" + XmlConvert.ToString(timespan) + "'", UriKind.Relative));

            Assert.IsTrue(queryable4.Count() == 0);
        }
        public void FunctionImportTest()
        {
            var result = TestClientContext.GetDefaultColor().GetValue();

            Assert.AreEqual(result, Color.Red);
        }