Esempio n. 1
0
        public static void CreateCustomer(Resources d365)
        {
            try
            {
                var CustomerCollection = new DataServiceCollection <Customer>(d365);

                Customer obj = new Customer();
                CustomerCollection.Add(obj);
                obj.Name            = "Test 02";
                obj.CustomerAccount = "KSC-000011";
                obj.CustomerGroupId = "Group 01";
                obj.DataAreaId      = "ksc";
                obj.PartyType       = "Organization";


                obj.DAXIntegrationId = Guid.Empty;
                //obj.CustomerWithholdingContributionType = CustWhtContributionType_BR.Other;
                //d365.Customers[0] = obj;
                // d365.AddToCustomers(obj);
                d365.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);


                //d365.SaveChanges();
            }
            catch (Exception ex)
            {
                string mesd = ex.Message;
            }
        }
Esempio n. 2
0
        private void LoadCustomers()
        {
            Customers = new DataServiceCollection <Customer>(m_Context);
            var query = m_Context.Customers;

            Customers.Load(query);
        }
Esempio n. 3
0
        private void LoadInspectionAttributes()
        {
            InspectionAttributes = new DataServiceCollection <InspectionAttribute>(m_Context);
            var query = m_Context.InspectionAttributes;

            InspectionAttributes.Load(query);
        }
        private void CodeFirst_Page_Loaded(object sender, RoutedEventArgs e)
        {
            // Initialize the context and the binding collection 
            context = new ProductContext(northwindUri);
           
            products = new DataServiceCollection<Product>(context);

            context.Products.AddQueryOption("$top", 10);

            // Define a LINQ query that returns all customers.
            var query = from cust in context.Products
                        //where cust.ProductId == 2761685473
                        select cust;

            var query2 = context.Products.Take(10);
            

            // Register for the LoadCompleted event.
            products.LoadCompleted
                += new EventHandler<LoadCompletedEventArgs>(products_LoadCompleted);

            // Load the customers feed by executing the LINQ query.
            products.LoadAsync(query);



        }
Esempio n. 5
0
        public void LoadAnnouncements()
        {
            Announcements = new DataServiceCollection <Announcement>(context);
            var query = from a in context.Announcements.OrderByDescending(a => a.PublishDate) select a;

            Announcements.LoadAsync(query);
        }
Esempio n. 6
0
        public void AddRemoveNullEntity()
        {
            var ctxwrap = this.CreateWrappedContext <DefaultContainer>();
            var context = ctxwrap.Context;
            DataServiceCollection <Customer> DSC = new DataServiceCollection <Customer>(context);

            try
            {
                DSC.Add(null);
                Assert.True(false, "Expected error not thrown");
            }
            catch (InvalidOperationException e)
            {
                StringResourceUtil.VerifyDataServicesClientString(e.Message, "DataBinding_BindingOperation_ArrayItemNull", "Add");
            }

            try
            {
                DSC.Remove(null);
                Assert.True(false, "Expected error not thrown");
            }
            catch (InvalidOperationException e)
            {
                StringResourceUtil.VerifyDataServicesClientString(e.Message, "DataBinding_BindingOperation_ArrayItemNull", "Remove");
            }

            this.EnqueueTestComplete();
        }
        public void DerivedEntityTypeShouldOnlySerializeChangedProperties()
        {
            EntityType entity = new DerivedEntityType
            {
                ID      = 7,
                Complex = new ComplexType
                {
                    Name = "June",
                    Home = new Address("Xiadu", 71)
                },
                StringCollection = new ObservableCollection <string>(new string[] { "first", "second" }),
                Name             = "July",
                Home             = new HomeAddress("Xingang", 17, "Guangzhou")
            };
            DataServiceCollection <DerivedEntityType> collection = new DataServiceCollection <DerivedEntityType>(context, null, TrackingMode.AutoChangeTracking, "EntitySet", null, null);

            collection.Add((DerivedEntityType)entity);

            context.Entities.FirstOrDefault().State = EntityStates.Unchanged;
            entity.ID = 71;
            entity.Complex.Home.Code = 17;
            ((DerivedEntityType)entity).Home.City = "Guangzhou";
            Assert.AreEqual(EntityStates.Modified, context.Entities.FirstOrDefault().State);
            ValidateBodyContent(context, "{\"ID\":71,\"Complex\":{\"Name\":\"June\",\"Home\":{\"Code\":17,\"Street\":\"Xiadu\"}},\"Home\":{\"City\":\"Guangzhou\",\"Code\":17,\"Street\":\"Xingang\"}}");
        }
Esempio n. 8
0
 public DevWPhoto(DataServiceCollection<T_RubbingPhoto> rubbingPhotos, T_RubbingPhoto currentRubbingPhoto )
 {
     InitializeComponent();
     _vmPhoto = new VMPhotos(rubbingPhotos, currentRubbingPhoto);
     LoadImage();
     SetButtonEnable();
 }
Esempio n. 9
0
        public void LoadPropertyCollection()
        {
            var ctxwrap = this.CreateWrappedContext<DefaultContainer>();
            var context = ctxwrap.Context;
            var querry = (from c in context.Customer
                          where c.CustomerId == -10
                          select c) as DataServiceQuery<Customer>;

            var ar = querry.BeginExecute(null, null).EnqueueWait(this);
            var cus = querry.EndExecute(ar).First();
            DataServiceCollection<Customer> dsc = new DataServiceCollection<Customer>(context) {cus};
            var ar02 = context.BeginLoadProperty(cus, "Orders", null, null).EnqueueWait(this);
            context.EndLoadProperty(ar02);
            foreach (Order o in cus.Orders)
            {
                o.OrderId = (134);
            }

            int fristCount = context.Entities.Count;
            foreach (var ed in context.Entities)
            {
                if (ed.Entity.GetType() == cus.Orders.First().GetType())
                {
                    Assert.Equal(EntityStates.Modified, ed.State);
                }
            }

            var o1 = new Order { OrderId = 1220 };
            cus.Orders.Add(o1);
            Assert.Equal(fristCount + 1, context.Entities.Count);
            cus.Orders.Remove(o1);
            Assert.Equal(fristCount, context.Entities.Count);

            this.EnqueueTestComplete();
        }
Esempio n. 10
0
        public void LoadSessions()
        {
            Sessions = new DataServiceCollection <Session>(context);
            var query = from s in context.Sessions where s.Event_ID == Constants.EventId select s;

            Sessions.LoadAsync(query);
        }
Esempio n. 11
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (totalParticipants != 0) // Page already loaded
                return;

            id = long.Parse(NavigationContext.QueryString["debtCalculationId"]);

            _container = ApiHelper.GetContainer();

            _participants = new DataServiceCollection<Participant>(_container);

            // Cannot localize ApplicationBar unless it is created in code behind
            ApplicationBar = new ApplicationBar
                {
                    BackgroundColor = Color.FromArgb(255, 0x86, 0xC4, 0x40), //"#86C440"
                    Opacity = 1,
                    ForegroundColor = Colors.White
                };

            ContentPanel.Children.Add(new ProgressBar
                {
                    IsIndeterminate = true,
                    Width = 300,
                    Margin = new Thickness(0, 30, 0, 0)
                });

            var query = _container.Participants
                                  .Expand(p => p.User)
                                  .Where(p => p.DebtCalculation.Id == id);

            _participants.LoadCompleted += ShowExpenseParticipants;
            _participants.LoadAsync(query);
        }
Esempio n. 12
0
        public void LoadSpeakers()
        {
            Speakers = new DataServiceCollection <Person>(context);
            var query = context.CreateQuery <Person>("Speakers").AddQueryOption("eventId", Constants.EventId).OrderBy(p => p.LastName);

            Speakers.LoadAsync(query);
        }
Esempio n. 13
0
        public void LoadTracks()
        {
            Tracks = new DataServiceCollection <Track>(context);
            var query = from t in context.Tracks.Where(t => t.Event_ID == Constants.EventId) select t;

            Tracks.LoadAsync(query);
        }
Esempio n. 14
0
        private void LoadPersons()
        {
            Persons = new DataServiceCollection <Person>(m_Context);
            var query = m_Context.People;

            Persons.Load(query);
        }
Esempio n. 15
0
        public void PostFullPropertiesInBatch()
        {
            var batchFlags = new SaveChangesOptions[] { SaveChangesOptions.BatchWithSingleChangeset, SaveChangesOptions.BatchWithIndependentOperations };

            foreach (var batchFlag in batchFlags)
            {
                List <ODataResource> entries = new List <ODataResource>();
                this.TestClientContext.Configurations.RequestPipeline.OnEntryEnding((arg) =>
                {
                    entries.Add(arg.Entry);
                });

                DataServiceCollection <CustomerPlus> people =
                    new DataServiceCollection <CustomerPlus>(this.TestClientContext, "People", null, null);
                var person = new CustomerPlus();
                people.Add(person);

                person.FirstNamePlus = "Nelson";
                person.LastNamePlus  = "Black";
                person.NumbersPlus   = new ObservableCollection <string> {
                };
                person.EmailsPlus    = new ObservableCollection <string> {
                    "*****@*****.**"
                };
                person.PersonIDPlus = 10001;
                person.CityPlus     = "London";
                person.TimeBetweenLastTwoOrdersPlus = new TimeSpan(1);
                person.HomeAddressPlus = new HomeAddressPlus()
                {
                    CityPlus       = "Redmond",
                    PostalCodePlus = "98052",
                    StreetPlus     = "1 Microsoft Way"
                };

                DataServiceCollection <AccountPlus> accounts =
                    new DataServiceCollection <AccountPlus>(this.TestClientContext);
                var account = new AccountPlus();
                accounts.Add(account);
                account.AccountIDPlus     = 110;
                account.CountryRegionPlus = "CN";

                DataServiceCollection <ProductPlus> products = new DataServiceCollection <ProductPlus>(this.TestClientContext);
                ProductPlus product = new ProductPlus();
                products.Add(product);
                product.NamePlus            = "Apple";
                product.ProductIDPlus       = 1000000;
                product.QuantityInStockPlus = 20;
                product.QuantityPerUnitPlus = "Pound";
                product.UnitPricePlus       = 0.35f;
                product.DiscontinuedPlus    = false;
                product.CoverColorsPlus     = new ObservableCollection <ColorPlus>();

                //Post entity into an entity set
                this.TestClientContext.SaveChanges(batchFlag);

                Assert.Equal(10, entries.Where(e => e.TypeName.Contains("CustomerPlus")).First().Properties.Count());
                Assert.Equal(2, entries.Where(e => e.TypeName.Contains("AccountPlus")).First().Properties.Count());
                Assert.Equal(9, entries.Where(e => e.TypeName.Contains("ProductPlus")).First().Properties.Count());
            }
        }
Esempio n. 16
0
        public void UpdateByPatchPartialPropertieInBatchWithCustomizedName()
        {
            int expectedPropertyCount = 1;

            this.TestClientContext.Configurations.RequestPipeline.OnEntryEnding(
                (arg) =>
            {
                Assert.AreEqual(expectedPropertyCount, arg.Entry.Properties.Count());
            });

            DataServiceCollection <OrderPlus> orders =
                new DataServiceCollection <OrderPlus>(this.TestClientContext.OrdersPlus.Expand("OrderDetails"));

            DataServiceCollection <PersonPlus> people =
                new DataServiceCollection <PersonPlus>(this.TestClientContext.PeoplePlus);

            DataServiceCollection <PersonPlus> boss =
                new DataServiceCollection <PersonPlus>(this.TestClientContext.BossPlus);

            orders[1].OrderDatePlus = DateTimeOffset.Now;

            ((CustomerPlus)people[0]).CityPlus = "Redmond";

            boss.Single().FirstNamePlus = "Bill";

            orders[0].OrderDetailsPlus.First().QuantityPlus = 1;

            this.TestClientContext.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);
        }
Esempio n. 17
0
        private void LoadRooms()
        {
            Rooms = new DataServiceCollection <BuildingRoom>(m_Context);
            var query = m_Context.BuildingRooms.Expand("Building");

            Rooms.Load(query);
        }
Esempio n. 18
0
        private void LoadBuildings()
        {
            Buildings = new DataServiceCollection <DomainModelService.Building>(m_Context);
            var query = m_Context.Buildings.Expand("Rooms, Address");

            Buildings.Load(query);
        }
 public void ClientSerializeGeographyTest_BindingAddChangeShouldBeDetected()
 {
     DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost"));
     DataServiceCollection<SpatialEntityType> dsc = new DataServiceCollection<SpatialEntityType>(ctx, null, TrackingMode.AutoChangeTracking, "Entities", null, null);
     dsc.Add(testEntity);
     ClientSerializeGeographyTest_Validate(ctx);
 }
Esempio n. 20
0
        private static void DataServiceCollectionSubQueryTrackingItems(
            DataServiceContextWrapper <DefaultContainer> contextWrapper)
        {
            var query = from p in contextWrapper.Context.Customer
                        where p.Name != null
                        select new Customer()
            {
                Name   = p.Name,
                Orders = new DataServiceCollection <Order>(
                    from r in p.Orders
                    select new Order()
                {
                    OrderId    = r.OrderId,
                    CustomerId = r.CustomerId
                })
            };
            var tmpResult0 = query.ToList()[0];
            DataServiceCollection <Order> collection = tmpResult0.Orders; // the collection tracking items
            int tmpCount = collection.Count;

            collection.Load(contextWrapper.Context.Execute(collection.Continuation));

            // for testing newly loaded item's tracking
            Assert.IsTrue(collection.Count > tmpCount, "Should have loaded another page.");
            bool someItemNotTracked = false;

            tmpResult0.Orders.ToList().ForEach(s =>
            {
                EntityStates state = contextWrapper.Context.GetEntityDescriptor(s).State;
                s.CustomerId       = s.CustomerId + 1;
                state = contextWrapper.Context.GetEntityDescriptor(s).State;
                someItemNotTracked = (state == EntityStates.Unchanged) || someItemNotTracked;
            });
            Assert.IsFalse(someItemNotTracked, "All items should have been tracked.");
        }
Esempio n. 21
0
        public void TrackEntityInstance <T>(T entityInstance)
            where T : class
        {
            DataServiceCollection <T> dataServiceCollection = new DataServiceCollection <T>(this);

            dataServiceCollection.Add(entityInstance);
        }
Esempio n. 22
0
        private static void DataServiceCollectionTrackingItems(
            DataServiceContextWrapper <DefaultContainer> contextWrapper)
        {
            var query = from p in contextWrapper.Context.Customer
                        where p.CustomerId > -100000
                        // try to get many for paging
                        select new Customer()
            {
                CustomerId = p.CustomerId,
                Name       = p.Name
            };
            DataServiceCollection <Customer> collection = new DataServiceCollection <Customer>(query);

            // the collection to track items
            int tmpCount = collection.Count;

            collection.Load(contextWrapper.Context.Execute(collection.Continuation));

            // for testing newly loaded item's tracking
            Assert.IsTrue(collection.Count > tmpCount, "Should have loaded another page.");
            bool someItemNotTracked = false;

            collection.ToList().ForEach(s =>
            {
                s.Name             = "value to test tracking";
                EntityStates state = contextWrapper.Context.GetEntityDescriptor(s).State;
                someItemNotTracked = (state == EntityStates.Unchanged) || someItemNotTracked;
            });
            Assert.IsFalse(someItemNotTracked, "All items should have been tracked.");
        }
Esempio n. 23
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            id = long.Parse(NavigationContext.QueryString["debtCalculationId"]);

            _container = ApiHelper.GetContainer();

            _calculations = new DataServiceCollection<DebtCalculation>(_container);

            // Cannot localize ApplicationBar unless it is created in code behind
            ApplicationBar = new ApplicationBar
            {
                BackgroundColor = Color.FromArgb(255, 0x86, 0xC4, 0x40), //"#86C440"
                Opacity = 1,
                ForegroundColor = Colors.White
            };

            ContentPanel.Children.Add(new ProgressBar { IsIndeterminate = true, Width = 300, Margin = new Thickness(0, 30, 0, 0) });

            var query = _container.DebtCalculations
                .Expand("Expenses/Payer")
                .Expand("Expenses/Debtors/User")
                .Expand("Participants/User")
                .Expand("Debts/Debtor")
                .Expand("Debts/Creditor")
                .Expand(dc => dc.Creator)
                .Where(dc => dc.Id == id);

            _calculations.LoadCompleted += ShowCalculation;
            _calculations.LoadAsync(query);
        }
Esempio n. 24
0
        private void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // Instantiate the DataServiceContext.
                context = new NorthwindEntities(svcUri);

                // Define a LINQ query that returns Orders and
                // Order_Details for a specific customer.
                var ordersQuery = from o in context.Orders.Expand("Order_Details")
                                  where o.Customers.CustomerID == customerId
                                  select o;

                // Create an DataServiceCollection<T> based on
                // execution of the LINQ query for Orders.
                DataServiceCollection <Orders> customerOrders = new
                                                                DataServiceCollection <Orders>(ordersQuery);

                // Make the DataServiceCollection<T> the binding source for the Grid.
                this.orderItemsGrid.DataContext = customerOrders;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public void UpdateComplexPropertyShouldOnlySerializeChangedProperties()
        {
            EntityType entity = new EntityType
            {
                ID      = 1,
                Complex = new ComplexType
                {
                    Name = "June",
                    Home = new Address("Dongchuan", 200)
                },
                StringCollection = new ObservableCollection <string>(new string[] { "first", "second" })
            };
            DataServiceCollection <EntityType> collection = new DataServiceCollection <EntityType>(context, null, TrackingMode.AutoChangeTracking, "EntitySet", null, null);

            collection.Add(entity);

            context.Entities.FirstOrDefault().State = EntityStates.Unchanged;
            entity.Complex = new ComplexType
            {
                Name = "July",
                Home = new Address("Jiaotong", 16)
            };
            Assert.AreEqual(EntityStates.Modified, context.Entities.FirstOrDefault().State);
            ValidateBodyContent(context, "{\"Complex\":{\"Name\":\"July\",\"Home\":{\"Code\":16,\"Street\":\"Jiaotong\"}}}");
        }
Esempio n. 26
0
        public void LoadSponsors()
        {
            Sponsors = new DataServiceCollection <Sponsor>(context);
            var query = from s in context.Sponsors.OrderBy(s => s.Name) select s;

            Sponsors.LoadAsync(query);
        }
Esempio n. 27
0
        public static Task <DataServiceCollection <T> > AsyncQuery <T>(
            this DataServiceCollection <T> data, IQueryable <T> query = null)
        {
            var       asyncr   = new SimpleAsyncResult();
            Exception exResult = null;

            data.LoadCompleted += delegate(object sender, LoadCompletedEventArgs e)
            {
                exResult = e.Error;
                asyncr.Finish();
            };

            if (query == null)
            {
                data.LoadAsync();
            }
            else
            {
                data.LoadAsync(query);
            }

            return(Task <DataServiceCollection <T> > .Factory.FromAsync(asyncr
                                                                        , r =>
            {
                if (exResult != null)
                {
                    throw new AggregateException("Async call problem", exResult);
                }
                return data;
            }
                                                                        ));
        }
Esempio n. 28
0
        private void LoadActivities()
        {
            Activities = new DataServiceCollection <Activity>(m_Context);
            var query = m_Context.Activities;

            Activities.Load(query);
        }
Esempio n. 29
0
        public void LoadTimeslots()
        {
            Timeslots = new DataServiceCollection <Timeslot>(context);
            var query = from ts in context.Timeslots select ts;

            Timeslots.LoadAsync(query);
        }
Esempio n. 30
0
        public void ClearListTest()
        {
            var ctxwrap = this.CreateWrappedContext <DefaultContainer>();
            var context = ctxwrap.Context;
            DataServiceCollection <Customer> DSC = new DataServiceCollection <Customer>(context);
            Customer c = new Customer {
                CustomerId = 1002
            };
            Customer c2 = new Customer {
                CustomerId = 1003
            };
            Customer c3 = new Customer {
                CustomerId = 1004
            };

            DSC.Add(c);
            DSC.Add(c2);
            DSC.Add(c3);
            Order o = new Order {
                OrderId = 2001, Customer = c, CustomerId = 1002
            };

            c.Orders.Add(o);
            VerifyCtxCount(context, 4, 1);
            DSC.Clear();
            VerifyCtxCount(context, 0, 0);

            this.EnqueueTestComplete();
        }
Esempio n. 31
0
        private void LoadQuestions()
        {
            Questions = new DataServiceCollection <Question>(m_Context);
            var query = m_Context.Questions;

            Questions.Load(query);
        }
Esempio n. 32
0
        public void LoadCollectionExceptionShouldNotRuinEntityTracking()
        {
            var ctxwrap = this.CreateWrappedContext <DefaultContainer>();
            var context = ctxwrap.Context;

            int[] customerIds = { /*existing*/ -9, /*non-existing*/ 0, /*existing*/ -10 };
            foreach (var customerId in customerIds)
            {
                Customer customer = null;

                try
                {
                    var query      = context.Customer.Where(c => c.CustomerId == customerId);
                    var collection = new DataServiceCollection <Customer>(query);
                    customer = collection.Single();
                }
                catch (DataServiceQueryException e)
                {
                    var inner = e.InnerException as DataServiceClientException;
                    if (inner != null && inner.StatusCode == (int)HttpStatusCode.NotFound)
                    {
                        continue;
                    }

                    throw;
                }

                context.SaveChanges();
            }
        }
Esempio n. 33
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // Initialize the context for the data service.
                context = new NorthwindEntities(new Uri(svcUri));

                //<snippetMasterDetailBinding>
                // Create a LINQ query that returns customers with related orders.
                var customerQuery = from cust in context.Customers.Expand("Orders")
                                    where cust.Country == customerCountry
                                    select cust;

                // Create a new collection for binding based on the LINQ query.
                trackedCustomers = new DataServiceCollection <Customer>(customerQuery);

                // Bind the root StackPanel element to the collection;
                // related object binding paths are defined in the XAML.
                LayoutRoot.DataContext = trackedCustomers;
                //</snippetMasterDetailBinding>
            }
            catch (DataServiceQueryException ex)
            {
                MessageBox.Show("The query could not be completed:\n" + ex.ToString());
            }
            catch (InvalidOperationException ex)
            {
                MessageBox.Show("The following error occurred:\n" + ex.ToString());
            }
        }
Esempio n. 34
0
        /// <summary>
        /// Asynchronously executes an <see cref="T:System.Linq.IQueryable`1"/> and loads results into the <see cref="T:System.Data.Services.Client.DataServiceCollection`1"/>.
        /// </summary>
        /// <typeparam name="T">Entity type of the <see cref="T:System.Data.Services.Client.DataServiceCollection`1"/> instance.</typeparam>
        /// <param name="bindingCollection">The <see cref="T:System.Data.Services.Client.DataServiceCollection`1"/> instance on which this extension method is enabled.</param>
        /// <param name="query">Query that when executed loads entities into the collection.</param>
        /// <returns>A <see cref="T:System.Threading.Tasks.Task`1"/> that, when completed, returns a <see cref="T:System.Data.Services.Client.LoadCompletedEventArgs"/>.</returns>
        public static async Task <LoadCompletedEventArgs> LoadAsync <T>(this DataServiceCollection <T> bindingCollection, IQueryable <T> query)
        {
            var tcs = new TaskCompletionSource <LoadCompletedEventArgs>();

            EventHandler <LoadCompletedEventArgs> handler =
                delegate(object o, LoadCompletedEventArgs e)
            {
                if (e.Error != null)
                {
                    tcs.TrySetException(e.Error);
                }
                else if (e.Cancelled)
                {
                    tcs.TrySetCanceled();
                }
                else
                {
                    tcs.TrySetResult(e);
                }
            };

            bindingCollection.LoadCompleted += handler;
            bindingCollection.LoadAsync(query);

            LoadCompletedEventArgs eventArgs = await tcs.Task;

            bindingCollection.LoadCompleted -= handler;

            return(eventArgs);
        }
Esempio n. 35
0
        private void LoadAddresses()
        {
            Addresses = new DataServiceCollection <Address>(m_Context);
            var query = m_Context.Addresses.Expand(i => i.Buildings);

            Addresses.Load(query);
        }
Esempio n. 36
0
        public void AddRemoveNullEntity()
        {
            var ctxwrap = this.CreateWrappedContext <DefaultContainer>();
            var context = ctxwrap.Context;
            DataServiceCollection <Customer> dsc = new DataServiceCollection <Customer>(context);

            try
            {
                dsc.Add(null);
                Assert.True(false, "Expected error not thrown");
            }
            catch (InvalidOperationException e)
            {
                Assert.NotNull(e);
            }

            try
            {
                dsc.Remove(null);
                Assert.True(false, "Expected error not thrown");
            }
            catch (InvalidOperationException e)
            {
                Assert.NotNull(e);
            }

            this.EnqueueTestComplete();
        }
Esempio n. 37
0
 private void LoadAvailableProjects()
 {
     var uri = new Uri(_settings.ServiceUrl+"/Projects");
     var context = IoC.Get<TFSDataServiceContext>();
     _collection = new DataServiceCollection<Project>(context);
     _collection.LoadCompleted += this.ItemsLoadCompleted;
     _collection.LoadAsync(uri);
 }
 public void LoadData()
 {
     var uri = new Uri(App.AWSERVICE);
     entities = new AdventureWorksLT2008R2Entities(uri);
     DSProducts = new DataServiceCollection<Product>(entities);
     var query = entities.Products;
     DSProducts.LoadAsync(query);
 }
Esempio n. 39
0
        public async Task SaveChangesTest()
        {
            var context = this.CreateWrappedContext<DefaultContainer>().Context;
            context.MergeOption = MergeOption.OverwriteChanges;
            int expectedPropertyCount = 1;
            Action<WritingEntryArgs> onEntryEnding = args =>
            {
                Assert.Equal(expectedPropertyCount, args.Entry.Properties.Count());
            };
            context.Configurations.RequestPipeline.OnEntryEnding(onEntryEnding);
            DataServiceCollection<Customer> customers = new DataServiceCollection<Customer>(context, "Customer", null, null);
            Customer c1 = new Customer();
            customers.Add(c1);
            c1.CustomerId = 1;
            c1.Name = "testName";

            //Partial Post an Entity
            expectedPropertyCount = 2;
            var response = await context.SaveChangesAsync(SaveChangesOptions.PostOnlySetProperties);
            Assert.True((response.First() as ChangeOperationResponse).StatusCode == 201, "StatusCode == 201");

            Order o1 = new Order { OrderId = 1000, CustomerId = 1, Concurrency = new ConcurrencyInfo() { Token = "token1" } };
            context.AddToOrder(o1);
            context.AddLink(c1, "Orders", o1);

            //Post with batch
            expectedPropertyCount = 3;
            await context.SaveChangesAsync(SaveChangesOptions.BatchWithSingleChangeset);

            List<Order> orders = new List<Order>();
            for (int i = 1; i <= 9; i++)
            {
                Order order = new Order { OrderId = 1000 + i };
                context.AddToOrder(order);
                orders.Add(order);
            }

            //Post with batch
            await context.SaveChangesAsync(SaveChangesOptions.BatchWithIndependentOperations);

            //Post $ref
            foreach (var order in orders)
            {
                context.AddLink(c1, "Orders", order);
            }
            await context.SaveChangesAsync();

            //Load property
            await context.LoadPropertyAsync(c1, "Orders");

            //Partial Update an Entity
            expectedPropertyCount = 1;
            c1.Orders[0].Concurrency.Token = "UpdatedToken";
            await context.SaveChangesAsync(SaveChangesOptions.None);

            this.EnqueueTestComplete();
        }
Esempio n. 40
0
        private void FetchAll()
        {
            var all = from p in context.People select p;

            DataServiceCollection<Person> peopleCollection = new DataServiceCollection<Person>(all);

            //var allPeople=context.People.ToList();
            LstOfPeople.DataContext = peopleCollection;
        }
Esempio n. 41
0
        private void BahadurPeopleButton_Click(object sender, RoutedEventArgs e)
        {
            var bahadurPeople = from p in context.People where p.LastName.Equals("Bahadur", StringComparison.OrdinalIgnoreCase) select p;

            DataServiceCollection<Person> peopleCollection = new DataServiceCollection<Person>(bahadurPeople);

            //var allPeople=context.People.ToList();
            LstOfPeople.DataContext = peopleCollection;
        }
        public BingSynonymsData()
        {
            serviceUri = new Uri(ROOT_SERVICE_URL);
            context = new BingSynonymsContainer(serviceUri);
            context.IgnoreMissingProperties = true;
            context.Credentials = new NetworkCredential(USER_ID, SECURE_ACCOUNT_ID);
            dataCollection = new DataServiceCollection<GetSynonymsEntitySet>(context);

            SynonymsList = new ObservableCollection<string>();
            dataCollection.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(dataCollection_LoadCompleted);
        }
Esempio n. 43
0
        public IList<BlogClass> GetBlogs()
        {
            List<BlogClass> blogs = new List<BlogClass>();
            using (var db = new LocalBlogContext(ConnectionString))
            {
                var query = from e in db.Blogs
                            select e;
                blogs = query.ToList();
            }

            return blogs;
        }
 public MainViewModel()
 {
     MessengerInstance.Register<RefreshEventListMessage>(this, (message) => RunQuery());
     if (IsInDesignMode)
     {
         // Code runs in Blend --> create design time data.
     }
     else
     {
         Events = new DataServiceCollection<ApprovedEvents>(context);
         RunQuery();
     }
 }
        public void ClientSerializeGeographyTest_BindingUpdateChangeShouldBeDetected()
        {
            DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost"));
            DataServiceCollection<SpatialEntityType> dsc = new DataServiceCollection<SpatialEntityType>(ctx, null, TrackingMode.AutoChangeTracking, "Entities", null, null);
            dsc.Add(testEntity);
            Assert.AreEqual(1, ctx.Entities.Count);

            ctx.Entities.FirstOrDefault().State = EntityStates.Unchanged;
            testEntity.Prop1 = testEntity.Prop1;
            Assert.AreEqual(EntityStates.Modified, ctx.Entities.FirstOrDefault().State);

            ClientSerializeGeographyTest_ValidateUpdate(ctx);
        }
Esempio n. 46
0
 private static void SelectFunctionItems(RoleDTO role, DataServiceCollection<FunctionItemDTO> functionItems)
 {
     for (int i = functionItems.Count - 1; i >= 0; i--)
     {
         var temp = functionItems[i];
         if (role.RoleFunctions.All(p => p.FunctionItemId != temp.Id))
         {
             functionItems.Remove(temp);
             continue;
         }
         SelectFunctionItems(role, temp.SubFunctionItems);
     }
 }
Esempio n. 47
0
        public void AddDeleteEntitySave()
        {
            var ctxwrap = this.CreateWrappedContext<DefaultContainer>();
            var context = ctxwrap.Context;
            DataServiceCollection<Customer> dsc = new DataServiceCollection<Customer>(context);
            Customer c = new Customer { CustomerId = 1002 };
            dsc.Add(c);
            dsc.Remove(c);
            Assert.True(VerifyCtxCount(context, 0, 0));
            this.SaveChanges(context);
            Assert.True(VerifyCtxCount(context, 0, 0));

            this.EnqueueTestComplete();
        }
Esempio n. 48
0
        public MainPage()
        {
            InitializeComponent();

            Uri uri = new Uri("/BlogService.svc", UriKind.Relative);
            svc = new BlogContext(uri);

            blogs = new DataServiceCollection<Blogs>(svc);
            this.LayoutRoot.DataContext = blogs;

            blogs.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(blogs_LoadCompleted);
            var q = svc.Blogs;
            blogs.LoadAsync(q);
        }
Esempio n. 49
0
        public void LoadData(DataServiceCollection<Blogs> blogs = null)
        {
            //var rows = from e in GetBlogs()
            //           select "id: " + e.Id + " name: " + e.Name + " owner: " + e.Owner;
            //lstBlogs.ItemsSource = rows;

            if (blogs == null)
                blogs = new DataServiceCollection<Blogs>();

            var source = GetBlogs();
            foreach (var b in blogs)
            {
                source.Add(new BlogClass(b));
            }

            lstBlogs.ItemsSource = source;
        }
Esempio n. 50
0
        public void GetSessions(Action<DataServiceCollection<Session>> onSuccess, Action<bool> onBusyStateChanged, Action<Exception> onError)
        {
            var sessions = new DataServiceCollection<Session>(null, TrackingMode.None);

            sessions.LoadCompleted += (s, e) =>
                                         {
                                             DispatchBusyStateChanged(onBusyStateChanged, false);
                                             if (e.Cancelled) return;
                                             if (e.Error != null)
                                                 DispatchError(e.Error, onError);
                                             else
                                                 onSuccess(sessions);
                                         };

            DispatchBusyStateChanged(onBusyStateChanged, true);
            sessions.LoadAsync(Context.Sessions);
        }
Esempio n. 51
0
        private void btnFindCommodity_Click(object sender, RoutedEventArgs e)
        {
            // Initialize the context and the binding collection 
            context = new TopCarrotEntities(topCarrotDataUri);
            context.SendingRequest += new EventHandler<SendingRequestEventArgs>(context_SendingRequest);
            commodityPluCodes = new DataServiceCollection<CommodityPluCode>(context);
            //Show the progress bar
            pageIndicators.ShowProgress(this);  


            if (UserInputUtilities.IsPluCode(txtCommodityToFind.Text))
            {
                txtblkInstructions.Text = "By PLU code entered";
                SearchQuery = from CommodityPluCode PluData in context.CommodityPluCodes
                            where PluData.PLU == txtCommodityToFind.Text.ToString()
                            select PluData;
            }
            if (UserInputUtilities.IsCropNumber(txtCommodityToFind.Text))
            {
                txtblkInstructions.Text = "By crop ID entered";
                SearchQuery = from CommodityPluCode PluData in context.CommodityPluCodes
                              where PluData.Commodity == txtCommodityToFind.Text.ToUpper()
                              select PluData;
            }
            else
            {
                txtblkInstructions.Text = "By commondity name entered";
                SearchQuery = from CommodityPluCode PluData in context.CommodityPluCodes
                            where PluData.Commodity == txtCommodityToFind.Text.ToUpper()
                            select PluData;
            }

            // Register for the LoadCompleted event.
            commodityPluCodes.LoadCompleted
               += new EventHandler<LoadCompletedEventArgs>(commodityPluCodes_LoadCompleted);


            // Load the customers feed by executing the LINQ query.
            commodityPluCodes.LoadAsync(SearchQuery);

        }
Esempio n. 52
0
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            DataServiceCollection<SampleData> sampleDataCollection;
            var context = CloudStorageContext.Current.Resolver.CreateTableServiceContext();

            sampleDataCollection = new DataServiceCollection<SampleData>(context);
            sampleDataCollection.LoadCompleted += (s2, e2) =>
            {
                List<SampleData> cloudNotes = sampleDataCollection.ToList();
                ListPics.ItemsSource = cloudNotes;
            };

            var tableUri = new Uri(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}/{1}()",
                        context.BaseUri,
                        "pics"),
                UriKind.Absolute);

            sampleDataCollection.Clear();
            sampleDataCollection.LoadAsync(tableUri);
        }
		/// <summary>
		/// Downloads a radio map for the building with the specified id. 
		/// </summary>
		/// <param name="buildingId"></param>
		public static void DownloadRadioMap(int buildingId)
		{
			radiomapContext = new radiomapEntities(radiomapUri);
			buildings = new DataServiceCollection<Building>(radiomapContext);
            
            String expandOptions = "Building_Floors,Vertices,Vertices/AbsoluteLocations,Vertices/SymbolicLocations,Vertices/Edges,Edges,Edges/Vertices,Edges/Vertices/AbsoluteLocations";
			var query = from b in radiomapContext.Buildings.Expand(expandOptions)
						where b.ID == buildingId 
						select b;

			// Register for the LoadCompleted event.
			buildings.LoadCompleted
				+= new EventHandler<LoadCompletedEventArgs>(buildings_LoadCompleted);
			buildings.LoadAsync(query);
		}
Esempio n. 54
0
 public void Load()
 {
     announcements = App.MainViewModel.Announcements;
     RaisePropertyChanged(() => Announcements);
 }
Esempio n. 55
0
 public void Load()
 {
     speakers = App.MainViewModel.Speakers;
     RaisePropertyChanged(() => Speakers);
 }
Esempio n. 56
0
        public void OnCloneComposition(object obj)
        {
            Repository.DataService.Composition sourceComposition = CompositionManager.Composition;

            SetDimensions(sourceComposition);

            var verses = new DataServiceCollection<Repository.DataService.Verse>(null, TrackingMode.None);
            var staffgroups = new DataServiceCollection<Repository.DataService.Staffgroup>(null, TrackingMode.None);
            var arcs = new DataServiceCollection<Repository.DataService.Arc>(null, TrackingMode.None);

            var composition = CompositionManager.Create();
            Cache.Clear();

            foreach (var sourceStaffgroup in sourceComposition.Staffgroups)
            {
                var staffgroup = StaffgroupManager.Clone(composition.Id, sourceStaffgroup);

                var staffs = new DataServiceCollection<Repository.DataService.Staff>(null, TrackingMode.None);
                foreach (var sourceStaff in sourceStaffgroup.Staffs)
                {
                    var staff = StaffManager.Clone(staffgroup.Id, sourceStaff);
                    var measures = new DataServiceCollection<Repository.DataService.Measure>(null, TrackingMode.None);
                    foreach (var sourceMeasure in sourceStaff.Measures)
                    {
                        var measure = MeasureManager.Clone(staff.Id, sourceMeasure);
                        var chords = new DataServiceCollection<Repository.DataService.Chord>(null, TrackingMode.None);
                        foreach (var sourceChord in sourceMeasure.Chords)
                        {
                            ChordManager.Measure = measure;
                            var chord = ChordManager.Clone(measure, sourceChord);
                            var notes = new DataServiceCollection<Repository.DataService.Note>(null, TrackingMode.None);
                            foreach (var sourceNote in sourceChord.Notes)
                            {
                                var note = NoteController.Clone(chord.Id, sourceChord, measure, sourceNote.Location_X, sourceNote.Location_Y, sourceNote);
                                if (note != null)
                                {
                                    _repository.Context.AddLink(chord, "Notes", note);
                                    notes.Add(note);
                                }
                            }
                            chord.Notes = notes;
                            _repository.Context.AddLink(measure, "Chords", chord);
                            chords.Add(chord);
                        }
                        measure.Chords = chords;
                        _repository.Context.AddLink(staff, "Measures", measure);
                        measures.Add(measure);
                    }
                    staff.Measures = measures;
                    _repository.Context.AddLink(staffgroup, "Staffs", staff);
                    staffs.Add(staff);
                }
                staffgroup.Staffs = staffs;
                _repository.Context.AddLink(composition, "Staffgroups", staffgroup);
                staffgroups.Add(staffgroup);
            }
            int s;
            for (s = 0; s < sourceComposition.Arcs.Count; s++)
            {
                var arc = ArcManager.Clone(sourceComposition.Arcs[s]);
                _repository.Context.AddLink(composition, "Arcs", arc);
                arcs.Add(arc);
            }

            for (s = 0; s < sourceComposition.Verses.Count; s++)
            {
                var verse = VerseManager.Clone(composition.Id, sourceComposition.Verses[s]);
                Cache.Verses.Add(verse);
                _repository.Context.AddLink(composition, "Verses", verse);
                verses.Add(verse);
            }
            composition.Instrument_Id = sourceComposition.Instrument_Id;
            composition.Key_Id = sourceComposition.Key_Id;
            composition.Provenance = sourceComposition.Provenance;
            composition.Arcs = arcs;
            composition.Verses = verses;
            composition.Staffgroups = staffgroups;

            _ea.GetEvent<NewComposition>().Publish(composition);
        }
Esempio n. 57
0
        public static void OnCreateNewComposition(object obj)
        {
            var payload = (Tuple<string, List<string>, _Enum.StaffConfiguration, List<short>>)obj;
            _repository = ServiceLocator.Current.GetInstance<DataServiceRepository<Repository.DataService.Composition>>();

            var verses = new DataServiceCollection<Repository.DataService.Verse>(null, TrackingMode.None);
            var staffgroups = new DataServiceCollection<Staffgroup>(null, TrackingMode.None);
            var collaborations = new DataServiceCollection<Repository.DataService.Collaboration>(null, TrackingMode.None);

            var composition = Create();
            composition.Provenance.TitleLine = payload.Item1;
            composition.StaffConfiguration = (short)payload.Item3;
            ClefIds = payload.Item4;
            for (int sgIndex = 0; sgIndex < Infrastructure.Support.Densities.StaffgroupDensity; sgIndex++)
            {
                var staffgroup = StaffgroupManager.Create(composition.Id, _staffgroupSequence);
                _staffgroupSequence += Defaults.SequenceIncrement;
                var staffs = new DataServiceCollection<Staff>(null, TrackingMode.None);
                _staffSequence = 0;
                for (int sIndex = 0; sIndex < Infrastructure.Support.Densities.StaffDensity; sIndex++)
                {
                    var staff = StaffManager.Create(staffgroup.Id, _staffSequence);

                    //clefIds was populated in NewCompositionPanel. it's a list of selected staff clef Ids top to bottom.
                    //if Dimensions.StaffDensity > then in multi instrument staffconfiguration - each staff clef is the
                    //same as the first staff clef. otherwise the staff clefs are whatever was specified in the newcompositionpanel
                    staff.Clef_Id = (Infrastructure.Support.Densities.StaffDensity > 2) ? ClefIds[0] : ClefIds[sIndex % 2];

                    _staffSequence += Defaults.SequenceIncrement;
                    var measures = new DataServiceCollection<Repository.DataService.Measure>(null, TrackingMode.None);
                    _measureSequence = 0;
                    for (int mIndex = 0; mIndex < Infrastructure.Support.Densities.MeasureDensity; mIndex++)
                    {
                        var measure = MeasureManager.Create(staff.Id, _measureSequence);

                        _measureSequence += Defaults.SequenceIncrement;
                        measure.Index = _measureIndex;
                        _measureIndex++;
                        _repository.Context.AddLink(staff, "Measures", measure);
                        //if this is the last measure on the last staff then measure.bar is the EndBar.
                        if (mIndex == Infrastructure.Support.Densities.MeasureDensity - 1)
                        {
                            if (sgIndex == Infrastructure.Support.Densities.StaffgroupDensity - 1)
                            {
                                if (sIndex == Infrastructure.Support.Densities.StaffDensity - 1)
                                {
                                    measure.Bar_Id = 1;
                                }
                            }
                        }
                        measures.Add(measure);
                    }
                    staff.Measures = measures;
                    _repository.Context.AddLink(staffgroup, "Staffs", staff);
                    staffs.Add(staff);
                }
                staffgroup.Staffs = staffs;
                _repository.Context.AddLink(composition, "Staffgroups", staffgroup);
                staffgroups.Add(staffgroup);
            }

            composition.Staffgroups = staffgroups;
            Repository.DataService.Collaboration collaboration = CollaborationManager.Create(composition, 0);
            _repository.Context.AddLink(composition, "Collaborations", collaboration);
            collaborations.Add(collaboration);
            composition.Collaborations = collaborations;
            composition.Verses = verses;
            Ea.GetEvent<NewComposition>().Publish(composition);
        }
Esempio n. 58
0
        /// <summary>
        /// Reloads notes from server
        /// </summary>
        private void LoadData()
        {
            this.IsDataLoaded = false;
            this.IsUiEnabled = false;

            // preparing a data context
            this._context = new NotesDataContext(new Uri(NotesDataServiceUri));

            // passing the authentication token obtained from Microsoft Account via the Authorization header
            this._context.SendingRequest += (sender, args) =>
            {
                // let our header look a bit custom
                args.RequestHeaders["Authorization"] = Constants.AuthorizationHeaderPrefix + this._authenticationToken;
            };

            var notes = new DataServiceCollection<Note>(this._context);
            notes.LoadCompleted += (sender, args) =>
            {
                if (this.Notes.Continuation != null)
                {
                    this.Notes.LoadNextPartialSetAsync();
                    return;
                }

                if (args.Error == null)
                {
                    this.IsDataLoaded = true;
                }
                else
                {
                    this.OnError.FireSafely(args.Error);
                }

                this.IsUiEnabled = true;
            };

            // Defining a query
            var query =
                from note in this._context.Notes
                orderby note.TimeCreated descending
                select note;

            // Demonstrating LINQ query dynamic generation.
            notes.LoadAsync
            (
                this._showTodaysNotesOnly
                ?
                // This will be translated into DynamoDb Query on the server, like this:
                // DynamoDb  index query: SELECT * FROM Note WHERE TimeCreated GreaterThan <some DateTime> AND UserId Equal <some userId> ORDER BY TimeCreated DESC. Index name: TimeCreatedIndex
                query.Where(note => note.TimeCreated > DateTime.Today)
                :
                query
            );

            this.Notes = notes;
            this.NotifyPropertyChanged(() => this.Notes);
        }
        private void fetchData(string filter, Action<List<Post>> callback)
        {
            StackOverflow.StackOverflow context = new StackOverflow.StackOverflow(new System.Uri("https://odata.sqlazurelabs.com/OData.svc/v0.1/rp1uiewita/StackOverflow"));

            var query = from t in context.Posts
                        where t.Tags.Contains("Silverlight") && t.Score > 5
                        select t;

            if (!String.IsNullOrWhiteSpace(filter))
                query = query.Where(t => t.Body.Contains(filter) || t.Title.Contains(filter));

            DataServiceCollection<Post> posts = new DataServiceCollection<Post>();
            posts.LoadCompleted += (s, e) =>
            {
                if (e.Error != null)
                    throw e.Error;

                callback(posts.ToList());
            };
            posts.LoadAsync(query.OrderByDescending(t => t.CreationDate).Take(30));
        }
        private static void DataServiceCollectionTrackingItems(
            DataServiceContextWrapper<DefaultContainer> contextWrapper)
        {
            var query = from p in contextWrapper.Context.Customer
                where p.CustomerId > -100000
                // try to get many for paging
                select new Customer()
                {
                    CustomerId = p.CustomerId,
                    Name = p.Name
                };
            DataServiceCollection<Customer> collection = new DataServiceCollection<Customer>(query);

            // the collection to track items
            int tmpCount = collection.Count;
            collection.Load(contextWrapper.Context.Execute(collection.Continuation));

            // for testing newly loaded item's tracking
            Assert.IsTrue(collection.Count > tmpCount, "Should have loaded another page.");
            bool someItemNotTracked = false;
            collection.ToList().ForEach(s =>
            {
                s.Name = "value to test tracking";
                EntityStates state = contextWrapper.Context.GetEntityDescriptor(s).State;
                someItemNotTracked = (state == EntityStates.Unchanged) || someItemNotTracked;
            });
            Assert.IsFalse(someItemNotTracked, "All items should have been tracked.");
        }