Пример #1
0
        // This is dependent on the Proxy class
        //
        // Apparently, 'T' and 'entityName' param can be of different names (e.g. Pais and Paises)
        public ObservableCollection <T> GetEntities <T>(string entityName, IDictionary <string, object> filters) where T : class
        {
            IEnumerable <T> result = null;

            if (string.IsNullOrEmpty(entityName))
            {
                return(null);
            }

            if (!this.isConnected)
            {
                return(null);
            }
            try
            {
                //  Paises.OrderBy(x => x.nombre).ToList();
                //var list = this.container.CreateQuery<T>(entityName).ToList();
                DataServiceQuery <T> query = this.container.CreateQuery <T>(entityName);

                // Country?$filter=Name eq 'USA'

                if (filters == null)
                {
                    result = query.Execute();
                }
                else
                {
                    // Test this ...
                    foreach (string filter in filters.Keys)
                    {
                        object filterValue = filters[filter];
                        if (filterValue != null)
                        {
                            // Immutability here ?
                            query = query.AddQueryOption(filter, filterValue);
                        }
                    }

                    result = query.Execute();
                }

                // Synchronous operation ???
                var list = result.ToList();

                return(new ObservableCollection <T>(list));
            }
            catch (Exception ex)  // will this work for all types of errors?
            {
                this.errors.Add(ex);
            }

            return(null);
        }
        public static T CreateEntity <T>(DataServiceContext ctx, string entitySetName, EntityStates state, DataServiceQuery <T> query) where T : class, new()
        {
            T entity = null;

            try
            {
                switch (state)
                {
                case EntityStates.Added:
                    entity = new T();
                    ctx.AddObject(entitySetName, entity);
                    break;

                case EntityStates.Deleted:
                    entity = CreateEntity(ctx, entitySetName, EntityStates.Unchanged, query);
                    ctx.DeleteObject(entity);
                    break;

                case EntityStates.Detached:
                    entity = query.Execute().Single();
                    Assert.AreEqual(MergeOption.NoTracking != ctx.MergeOption, ctx.Detach(entity));
                    break;

                case EntityStates.Unchanged:
                    entity = query.Execute().Single();
                    if (MergeOption.NoTracking == ctx.MergeOption)
                    {
                        ctx.AttachTo(entitySetName, entity);
                    }

                    break;

                case EntityStates.Modified:
                    entity = CreateEntity(ctx, entitySetName, EntityStates.Unchanged, query);
                    ctx.UpdateObject(entity);
                    break;

                default:
                    Assert.Fail(String.Format("unexpected state encountered: {0}", state));
                    break;
                }
            }
            catch (Exception ex)
            {
                Assert.Fail("{0}", ex);
            }

            return(entity);
        }
Пример #3
0
        public static Collection <PartialMatche> Search(string strSearch)
        {
            if (string.IsNullOrWhiteSpace(strSearch))
            {
                return(null);
            }

            BingSearchContainer objService = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/"));

            objService.Credentials = new NetworkCredential(AppId, AppId);
            DataServiceQuery <ImageResult> imagequery = objService.Image(strSearch, "DisableLocationDetection",
                                                                         CultureInfo.CurrentCulture.Name, "Off", null, null, null);

            IEnumerable <ImageResult> imagesList = imagequery.Execute();

            if (imagesList != null)
            {
                List <ImageResult> images = imagesList.ToList();
                return(CreatePartialMatch(images));
            }
            else
            {
                return(null);
            }
        }
Пример #4
0
            public void QueryHeadersViaExecuteMethod()
            {
                Uri baseUri = ctx.BaseUri;

                // Accessing headers via DataServiceContext.Execute<> method
                Uri requestUri = new Uri(baseUri.OriginalString + "/Customers('QUICK')");
                var results    = (QueryOperationResponse <northwindClient.Customers>)ctx.Execute <northwindClient.Customers>(requestUri);

                Utils.IsSuccessResponse(results, HttpStatusCode.OK);
                // assert that there is exactly one object
                results.Single <northwindClient.Customers>();

                // Accessing headers via DataServiceContext.BeginExecute/EndExecute method
                IAsyncResult asyncResult = ctx.BeginExecute <northwindClient.Customers>(requestUri, null, null);

                results = (QueryOperationResponse <northwindClient.Customers>)ctx.EndExecute <northwindClient.Customers>(asyncResult);
                Utils.IsSuccessResponse(results, HttpStatusCode.OK);
                // assert that there is exactly one object
                results.Single <northwindClient.Customers>();

                // Accessing headers via DataServiceQuery<>.Execute method
                DataServiceQuery <northwindClient.Customers> query = ctx.CreateQuery <northwindClient.Customers>("Customers");

                results = (QueryOperationResponse <northwindClient.Customers>)query.Execute();
                Utils.IsSuccessResponse(results, HttpStatusCode.OK);
                Assert.IsTrue(results.Count <northwindClient.Customers>() > 0, "expecting atleast one object");

                // Accessing headers via DataServiceQuery<>.BeginExecute/EndExecute method
                asyncResult = query.BeginExecute(null, null);
                results     = (QueryOperationResponse <northwindClient.Customers>)query.EndExecute(asyncResult);
                Utils.IsSuccessResponse(results, HttpStatusCode.OK);
                Assert.IsTrue(results.Count <northwindClient.Customers>() > 0, "expecting atleast one object");
            }
        /// <summary>
        /// Executes the specified query.
        /// </summary>
        /// <typeparam name="T">The type.</typeparam>
        /// <param name="query">The query.</param>
        /// <returns>A collection</returns>
        public static IEnumerable <T> Execute <T>(DataServiceQuery <T> query)
        {
            var watch = new Stopwatch();

            watch.Start();

            try
            {
                var result = query.Execute();
                watch.Stop();
                LogInfo($"     <.><.> Execute<T>: {query.RequestUri}: {watch.ElapsedMilliseconds}ms");

                return(result);
            }
            catch (DataServiceQueryException ex)
            {
                LogError($"Exception {ex.InnerException.Message} on Execute:{query.RequestUri}", typeof(Proxy));
                throw;
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    LogError($"Exception {e.GetType()}: {e.Message} on Execute:{query.RequestUri}", typeof(Proxy));
                }

                throw;
            }
            catch (Exception ex)
            {
                LogError($"Exception {ex.GetType()}: {ex.Message} Execute:{query.RequestUri}", typeof(Proxy));
                throw;
            }
        }
        public IEnumerable <T> ExecuteQueryWithContinutation <T>(DataServiceQuery <T> query)
        {
            query = AddContinutationToQuery(query);

            var response = (QueryOperationResponse)query.Execute();

            this.RetreiveContinuationFromResponse(response);

            return((IEnumerable <T>)response);
        }
Пример #7
0
        public void RemapRequestUri()
        {
            var context = this.CreateWrappedContext <DefaultContainer>();
            DataServiceQuery customQuery = context.CreateQuery <Customer>("RemapPath");
            //Path should remap to the customers set

            var retrievedCustomers = (IEnumerable <Customer>)customQuery.Execute();

            Assert.IsNotNull(retrievedCustomers);
        }
Пример #8
0
 /// <summary>
 /// Extension method to perform sync/async version of DataServiceQuery.Execute dynamically
 /// </summary>
 /// <typeparam name="TElement">The element type of the results</typeparam>
 /// <param name="query">The query to execute</param>
 /// <param name="continuation">The asynchronous continuation</param>
 /// <param name="async">A value indicating whether or not to use async API</param>
 /// <param name="onCompletion">A callback for when the call completes</param>
 public static void Execute <TElement>(this DataServiceQuery <TElement> query, IAsyncContinuation continuation, bool async, Action <IEnumerable <TElement> > onCompletion)
 {
     ExceptionUtilities.CheckArgumentNotNull(query, "query");
     AsyncHelpers.InvokeSyncOrAsyncMethodCall <IEnumerable <TElement> >(
         continuation,
         async,
         () => query.Execute(),
         c => query.BeginExecute(c, null),
         r => query.EndExecute(r),
         onCompletion);
 }
Пример #9
0
        public List <Item> GetItems(string ModifiedDate)
        {
            string serviceODataURL = ConfigurationManager.AppSettings["NAVODATAUrl"];
            string WS_User         = ConfigurationManager.AppSettings["NAV_User"];
            string WS_Pwd          = ConfigurationManager.AppSettings["NAV_Pwd"];
            string WS_Domain       = ConfigurationManager.AppSettings["NAV_Domain"];
            string Company         = ConfigurationManager.AppSettings["Company"];

            string serviceUri = string.Format(serviceODataURL + "/Company('{0}')", Company);

            List <Item> itemListB2B = new List <Item>();

            try
            {
                DataServiceContext context = new DataServiceContext(new Uri(serviceUri));

                NAV_ODATA.NAV theNav = new NAV_ODATA.NAV(new Uri(serviceUri));
                theNav.Credentials = new System.Net.NetworkCredential(WS_User, WS_Pwd, WS_Domain);

                DataServiceQuery <NAV_ODATA.B2BArticoliWeb> q = theNav.CreateQuery <NAV_ODATA.B2BArticoliWeb>("B2BArticoliWeb");

                if (ModifiedDate.Length > 0)
                {
                    //OData Filter Expression ge = greater than or equal to
                    string FilterValue = string.Format("Last_Date_Modified ge datetime'{0}' or Last_Movement_Date ge datetime'{0}'", ModifiedDate);
                    q = q.AddQueryOption("$filter", FilterValue);
                }

                List <NAV_ODATA.B2BArticoliWeb> itemList = q.Execute().ToList();

                foreach (NAV_ODATA.B2BArticoliWeb item in itemList)
                {
                    Item a = new Item();
                    a.No               = item.No;
                    a.Description1     = item.Description;
                    a.Description2     = item.Description_2;
                    a.Inventory        = item.Inventory;
                    a.Lot              = item.Quantità_Lotto;
                    a.UnitOfMeasure    = item.Base_Unit_of_Measure;
                    a.ItemType         = item.Linea;
                    a.ItemBrand        = item.Dimension_Value_Code;
                    a.BrandDescription = item.Name;
                    itemListB2B.Add(a);
                }
            }
            catch (Exception ex)
            {
                string exmsg = ex.Message;
            }

            return(itemListB2B);
        }
Пример #10
0
        public static IEnumerable <Customers> Select()
        {
            NorthwindEntities _entities = new NorthwindEntities(serviceUri);

            _entities.SendingRequest += new EventHandler <SendingRequestEventArgs>(_entities_SendingRequest);
            List <Customers> _collection = new List <Customers>();
            // Query the first 10 records to test. You can do paging by Skip and Take but for the
            // simplicity purpose it's not shown here
            DataServiceQuery <Customers> query = (DataServiceQuery <Customers>)(
                from c in _entities.Customers
                select c).Skip(0).Take(10);
            var result = query.Execute();

            return(result);
        }
Пример #11
0
        /// <summary>
        /// Get translated text from Bing Translator service.
        /// </summary>
        /// <param name="textToTranslate">Text to translate.</param>
        /// <param name="fromLang">Language to translate from.</param>
        /// <param name="toLang">Language to translate to.</param>
        /// <returns>Translated text.</returns>
        List <string> ITranslator.GetTranslatedText(string textToTranslate,
                                                    string fromLang,
                                                    string toLang,
                                                    ILoginCredentials login)
        {
            if (login == null)
            {
                return(null);
            }

            // the TranslatorContainer gives us access to the Microsoft Translator services
            MSTranslate.Service.TranslatorContainer tc = new MSTranslate.Service.TranslatorContainer(login.TranslationServiceUri);

            // Give the TranslatorContainer access to your subscription
            tc.Credentials = new NetworkCredential(SecureStringExtensionMethod.ConvertToUnsecureString(login.User),
                                                   login.Password);

            try
            {
                // Generate the query
                DataServiceQuery <Translation> translationQuery = tc.Translate(textToTranslate, toLang, fromLang);

                // Call the query and get the results as a List
                var translationResults = translationQuery.Execute().ToList();

                // Verify there was a result
                if (translationResults.Count() <= 0)
                {
                    return(new List <string>());
                }

                // In case there were multiple results, pick the first one
                var translationResult = translationResults.First();

                List <string> ret = new List <string>();

                for (int i = 0; i < translationResults.Count(); i++)
                {
                    ret.Add(translationResult.Text);
                }

                return(ret);
            }
            catch (Exception exc)
            {
                throw new Exception(string.Format("Translation text:'{0}', toLang: '{1}', fromLang '{2}'", textToTranslate, toLang, fromLang), exc);
            }
        }
Пример #12
0
        public void RemapBaseAndPathSeparately()
        {
            var context = this.CreateWrappedContext <DefaultContainer>();
            DataServiceQuery customQuery = context.CreateQuery <Customer>("RemapBaseAndPathSeparately");
            //Path should remap to the customers set
            var retrievedPersons = (IEnumerable <Customer>)customQuery.Execute();

            Assert.IsNotNull(retrievedPersons);
            EntityDescriptor descriptor = null;

            foreach (var element in retrievedPersons)
            {
                descriptor = context.GetEntityDescriptor(element);
                Assert.IsTrue(descriptor.EditLink.AbsoluteUri.StartsWith("http://potato"));
            }
        }
        static void Main(string[] args)
        {
            NAV nav = new NAV(new Uri("http://localhost:7048/DynamicsNAV90/OData"));

            nav.Credentials = CredentialCache.DefaultCredentials;

            DataServiceQuery <PurchasePrice> query  = nav.CreateQuery <PurchasePrice>("PurchasePrice");
            List <PurchasePrice>             prices = query.Execute().ToList <PurchasePrice>();

            foreach (PurchasePrice price in prices)
            {
                Console.WriteLine("Item: {0}, Unit cost: {1}", price.Item_No, price.Direct_Unit_Cost);
            }

            Console.ReadLine();
        }
Пример #14
0
        public List <SalesShipment> GetNAVShipments(string NAVInstanceName, string shipmentDateFilter)
        {
            try
            {
                string URL       = Properties.Settings.Default[NAVInstanceName].ToString();
                string WS_User   = Properties.Settings.Default[NAVInstanceName + "_User"].ToString();
                string WS_Pwd    = Properties.Settings.Default[NAVInstanceName + "_Pwd"].ToString();
                string WS_Domain = Properties.Settings.Default[NAVInstanceName + "_Domain"].ToString();

                DataServiceContext context = new DataServiceContext(new Uri(URL));

                NAVODATAWS.NAV NAV = new NAVODATAWS.NAV(new Uri(URL));
                NAV.Credentials = new System.Net.NetworkCredential(WS_User, WS_Pwd, WS_Domain);

                DataServiceQuery <NAVODATAWS.ItemShipments> q = NAV.CreateQuery <NAVODATAWS.ItemShipments>("ItemShipments");

                if (shipmentDateFilter != null)
                {
                    string FilterValue = string.Format("Shipment_Date ge datetime'{0}'", shipmentDateFilter);
                    q = q.AddQueryOption("$filter", FilterValue);
                }

                List <NAVODATAWS.ItemShipments> list = q.Execute().ToList();

                List <SalesShipment> sslist = new List <SalesShipment>();

                foreach (NAVODATAWS.ItemShipments shpt in list)
                {
                    SalesShipment ss = new SalesShipment();
                    ss.No           = shpt.No;
                    ss.CustomerNo   = shpt.Sell_to_Customer_No;
                    ss.ItemNo       = shpt.ItemNo;
                    ss.Description  = shpt.Description;
                    ss.Description2 = shpt.Description_2;
                    ss.UoM          = shpt.Unit_of_Measure;
                    ss.Quantity     = shpt.Quantity;
                    ss.ShipmentDate = shpt.Shipment_Date;
                    sslist.Add(ss);
                }

                return(sslist);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #15
0
        public List <Customer> GetCustomers()
        {
            string serviceODataURL = ConfigurationManager.AppSettings["NAVODATAUrl"];
            string WS_User         = ConfigurationManager.AppSettings["NAV_User"];
            string WS_Pwd          = ConfigurationManager.AppSettings["NAV_Pwd"];
            string WS_Domain       = ConfigurationManager.AppSettings["NAV_Domain"];
            string Company         = ConfigurationManager.AppSettings["Company"];
            //OData URI creation
            string serviceUri = string.Format(serviceODataURL + "/Company('{0}')", Company);

            List <Customer> custListB2B = new List <Customer>();

            try
            {
                DataServiceContext context = new DataServiceContext(new Uri(serviceUri));
                //Web service initialization
                NAV_ODATA.NAV theNav = new NAV_ODATA.NAV(new Uri(serviceUri));
                //User impersonation
                theNav.Credentials = new System.Net.NetworkCredential(WS_User, WS_Pwd, WS_Domain);
                //Calls the OData WS (NAV Query)
                DataServiceQuery <NAV_ODATA.B2BClientiWeb> q = theNav.CreateQuery <NAV_ODATA.B2BClientiWeb>("B2BClientiWeb");

                List <NAV_ODATA.B2BClientiWeb> custList = q.Execute().ToList();

                foreach (NAV_ODATA.B2BClientiWeb cust in custList)
                {
                    Customer c = new Customer();
                    c.No             = cust.No;
                    c.Name           = cust.Name;
                    c.Address        = cust.Address;
                    c.City           = cust.City;
                    c.CAP            = cust.Post_Code;
                    c.Country        = cust.Country_Region_Code;
                    c.County         = cust.County;
                    c.FiscalCode     = cust.Fiscal_Code;
                    c.VATNo          = cust.VAT_Registration_No;
                    c.EmailEcommerce = cust.Email_Ecommerce;
                    c.Active         = cust.ActivadoWeb;
                    custListB2B.Add(c);
                }
            }
            catch (Exception)
            {
            }

            return(custListB2B);
        }
        public static int Count(this DataServiceQuery source)
        {
            var result = source.Execute();
            int count  = 0;

            if (result == null)
            {
                return(count);
            }
            var enumerator = result.GetEnumerator();

            while (enumerator.MoveNext())
            {
                count++;
            }
            return(count);
        }
Пример #17
0
        public IEnumerable <SearchResultType> Search <SearchResultType>(string searchTerm, int maxNumResults = 10)
        {
            // Create a Bing container.

            string rootUri = "https://api.datamarket.azure.com/Bing/Search";

            var bingContainer = new BingSearchContainer(new Uri(rootUri));

            // Replace this value with your account key.

            var accountKey = "iSQBkXDEeiJ2/tgd7OYgrtN1XbHiLCRUmzPzU9wW0MI";

            // Configure bingContainer to use your credentials.

            bingContainer.Credentials = new NetworkCredential(accountKey, accountKey);

            DataServiceQuery <SearchResultType> query = null;

            if (typeof(SearchResultType) == new ImageResult().GetType())
            {
                query = bingContainer.Image(searchTerm, null, null, null, null, null, null) as DataServiceQuery <SearchResultType>;
            }

            if (typeof(SearchResultType) == new NewsResult().GetType())
            {
                query = bingContainer.News(searchTerm, null, "en-US", "Moderate", null, null, null, "rt_Sports", "Date") as DataServiceQuery <SearchResultType>;
            }

            if (typeof(SearchResultType) == new WebResult().GetType())
            {
                query = bingContainer.Web(searchTerm, null, null, "en-US", "Moderate", null, null, null) as DataServiceQuery <SearchResultType>;
            }

            if (typeof(SearchResultType) == new VideoResult().GetType())
            {
                query = bingContainer.Video(searchTerm, null, "en-US", "Moderate", null, null, null, "Date") as DataServiceQuery <SearchResultType>;
            }

            if (query == null)
            {
                return(null);
            }


            return(query.Execute());
        }
Пример #18
0
        public static Hashtable SearchPortrait(string strSearch, bool usePartialMatche)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(strSearch))
                {
                    return(null);
                }

                Task.Factory.StartNew(() => Util.NotifyEvent("Provider: Bing Portrait : " + strSearch));

                BingSearchContainer objService = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/"));
                objService.Credentials = new NetworkCredential(AppId, AppId);
                DataServiceQuery <ImageResult> imagequery = objService.Image(strSearch, "DisableLocationDetection",
                                                                             null, "Off", null, null, @"Style:Photo+Face:Face+Aspect:Tall");

                if (imagequery != null)
                {
                    List <ImageResult> images = imagequery.Execute().ToList();

                    if (usePartialMatche == true)
                    {
                        return(ShowPartialMatch(images));
                    }
                    else if (images.Any())
                    {
                        Hashtable objResults = new Hashtable();
                        objResults.Add("Image", images[0].MediaUrl);
                        return(objResults);
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                Util.LogException(ex, strSearch);
                return(null);
            }
        }
        /// <summary>
        /// Gets available Windows Azure offers from the Marketplace.
        /// </summary>
        /// <param name="countryCode">The country two character code. Uses 'US' by default </param>
        /// <returns>The list of offers</returns>
        public virtual List <WindowsAzureOffer> GetAvailableWindowsAzureOffers(string countryCode)
        {
            countryCode = string.IsNullOrEmpty(countryCode) ? "US" : countryCode;
            List <WindowsAzureOffer>             result             = new List <WindowsAzureOffer>();
            List <Offer>                         windowsAzureOffers = new List <Offer>();
            CatalogServiceReadOnlyDbContext      context            = new CatalogServiceReadOnlyDbContext(new Uri(Resources.MarketplaceEndpoint));
            DataServiceQueryContinuation <Offer> nextOfferLink      = null;

            do
            {
                DataServiceQuery <Offer> query = context.Offers
                                                 .AddQueryOption("$filter", "IsAvailableInAzureStores")
                                                 .Expand("Plans, Categories");
                QueryOperationResponse <Offer> offerResponse = query.Execute() as QueryOperationResponse <Offer>;
                foreach (Offer offer in offerResponse)
                {
                    List <Plan> allPlans = new List <Plan>(offer.Plans);
                    DataServiceQueryContinuation <Plan> nextPlanLink = null;

                    do
                    {
                        QueryOperationResponse <Plan> planResponse = context.LoadProperty(
                            offer,
                            "Plans",
                            nextPlanLink) as QueryOperationResponse <Plan>;
                        nextPlanLink = planResponse.GetContinuation();
                        allPlans.AddRange(offer.Plans);
                    } while (nextPlanLink != null);

                    IEnumerable <Plan>   validPlans     = offer.Plans.Where <Plan>(p => p.CountryCode == countryCode);
                    IEnumerable <string> offerLocations = offer.Categories.Select <Category, string>(c => c.Name)
                                                          .Intersect <string>(SubscriptionLocations);
                    if (validPlans.Count() > 0)
                    {
                        result.Add(new WindowsAzureOffer(
                                       offer,
                                       validPlans,
                                       offerLocations.Count() == 0 ? SubscriptionLocations : offerLocations));
                    }
                }

                nextOfferLink = offerResponse.GetContinuation();
            } while (nextOfferLink != null);

            return(result);
        }
Пример #20
0
        //UDP udgaven:

        /*
         * private static void StartTcpServer()
         * {
         *  LoadRadioMap();
         *
         *  //Start listening for sniffer measurements
         *  UdpClient udpc = new UdpClient(5555);
         *  Console.WriteLine("Server started, servicing on port 2055");
         *  IPEndPoint ep = null;
         *  while (true)
         *  {
         *      byte[] rawData = udpc.Receive(ref ep);
         *      string strData = Encoding.ASCII.GetString(rawData);
         *      string[] msgParts = strData.Split(' ');
         *
         *      try
         *      {
         *          string snifferMac = msgParts[0];
         *          string hms = msgParts[1]; //e.g.: 10:01:21.185194
         *          DateTime time = getTime(hms);
         *          string strRssi = msgParts[2];
         *          int rssi = int.Parse(strRssi);
         *          string clientMac = msgParts[3];
         *
         *          if (isCurrentlyMeasuring(clientMac))
         *          {
         *              addToMeasurement(snifferMac, clientMac, rssi, time);
         *          }
         *          Console.WriteLine("Sniffer mac = {0}; time = {1}; RSSI = {2}; clientMac = {3}", snifferMac, time, strRssi, clientMac);
         *      }
         *      catch (Exception ex)
         *      {
         *          Console.WriteLine(ex.Message);
         *      }
         *  }
         * }
         */

        private static void LoadRadioMap()
        {
            if (!IsDownloadingRadioMap)
            {
                IsDownloadingRadioMap = true;

                context = new radiomapEntities(radiomapUri);
                //Load LoadedBuildings
                String expandOptions = "Building_MacInfos,Building_Floors,Edges,Vertices,Vertices/AbsoluteLocations,Vertices/SymbolicLocations,Vertices/SnifferWifiMeasurements,Vertices/SnifferWifiMeasurements/SnifferHistograms";
                DataServiceQuery <Building> query = context.Buildings.Expand(expandOptions);

                //NOTE: Maybe surround with try-catch and try again
                LoadedBuildings = query.Execute().ToList();

                IsDownloadingRadioMap = false;
                checkBuildings();
            }
        }
Пример #21
0
        public List <ShipmentAddress> GetShipmentAddresses()
        {
            string serviceODataURL = ConfigurationManager.AppSettings["NAVODATAUrl"];
            string WS_User         = ConfigurationManager.AppSettings["NAV_User"];
            string WS_Pwd          = ConfigurationManager.AppSettings["NAV_Pwd"];
            string WS_Domain       = ConfigurationManager.AppSettings["NAV_Domain"];
            string Company         = ConfigurationManager.AppSettings["Company"];

            string serviceUri = string.Format(serviceODataURL + "/Company('{0}')", Company);

            List <ShipmentAddress> indListB2B = new List <ShipmentAddress>();

            try
            {
                DataServiceContext context = new DataServiceContext(new Uri(serviceUri));

                NAV_ODATA.NAV theNav = new NAV_ODATA.NAV(new Uri(serviceUri));
                theNav.Credentials = new System.Net.NetworkCredential(WS_User, WS_Pwd, WS_Domain);

                DataServiceQuery <NAV_ODATA.B2BShipAddress> q = theNav.CreateQuery <NAV_ODATA.B2BShipAddress>("B2BShipAddress");

                List <NAV_ODATA.B2BShipAddress> addrList = q.Execute().ToList();

                foreach (NAV_ODATA.B2BShipAddress addr in addrList)
                {
                    ShipmentAddress ind = new ShipmentAddress();
                    ind.CustomerNo = addr.Customer_No;
                    ind.Code       = addr.Code;
                    ind.Name       = addr.Name;
                    ind.Address    = addr.Address;
                    ind.City       = addr.City;
                    ind.County     = addr.County;
                    ind.Country    = addr.Country_Region_Code;
                    ind.Default    = addr.Default_Shipment;

                    indListB2B.Add(ind);
                }
            }
            catch (Exception)
            {
            }

            return(indListB2B);
        }
Пример #22
0
        /// <summary>
        /// Executes the <see cref="DataGetRequest{TEntity}" />.
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public override Message Execute(DataRequestParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (Query == null)
            {
                throw new ArgumentException("Could not execute request because no query has been set.");
            }

            DataServiceContext         serviceContext   = Resolve(parameters);
            DataServiceQuery <TEntity> query            = serviceContext.CreateQuery <TEntity>(parameters.EntitySet);
            IEnumerable <TEntity>      result           = Query(query);
            DataServiceQuery <TEntity> dataServiceQuery = result as DataServiceQuery <TEntity>;
            IEnumerable <TEntity>      entities         = dataServiceQuery != null?dataServiceQuery.Execute() : result;

            return(new DataResponse <IEnumerable <TEntity> > {
                Result = entities
            });
        }
 private void entityToShow_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (entityToShow.SelectedIndex < 0)
     {
         return;
     }
     if (string.IsNullOrEmpty(authCookie))
     {
         return;
     }
     try {
         context.SaveChanges();
         DataServiceQuery queue = entities[entityToShow.SelectedItem.ToString()];
         List <object>    ds    = new List <object>();
         ds.AddRange((IEnumerable <object>)queue.Execute());
         ListObjects = ds;
         if (ListObjects[0] is Categories)
         {
             categoryInteceptor.Enabled = true;
             gvlODataV3Service_FocusedRowChanged(null, null);
         }
         else
         {
             categoryInteceptor.Enabled = false;
             pictureBox.Image           = null;
         }
         if (ListObjects[0] is Products)
         {
             checkRemove.Enabled = true;
         }
         else
         {
             checkRemove.Enabled = false;
         }
     } catch (Exception ex) {
         MessageBox.Show(ex.ToString());
     }
 }
Пример #24
0
        public void BasesDontMatchFail()
        {
            var context = this.CreateWrappedContext <DefaultContainer>();

            DataServiceQuery customQuery = context.CreateQuery <Customer>("BasesDontMatchFail");
            //Path should remap to the customers set
            var expectedServiceUrl = "http://potato:9090/FailMeService/";
            var expectedRequestUrl = "http://potato:9090/DontFailMeService/Customer";

            try
            {
                customQuery.Execute();
                Assert.Fail("Different service bases between service uri and request uri should fail");
            }
            catch (DataServiceQueryException ex)
            {
                Assert.IsNotNull(ex.InnerException, "No inner exception found");
                Assert.IsInstanceOfType(ex.InnerException, typeof(DataServiceClientException), "Unexpected inner exception type");

                StringResourceUtil.VerifyODataLibString(ClientExceptionUtil.ExtractServerErrorMessage(ex),
                                                        "UriQueryPathParser_RequestUriDoesNotHaveTheCorrectBaseUri", true, expectedRequestUrl, expectedServiceUrl);
            }
        }
Пример #25
0
        /// <summary>
        /// Populate this collection with another collection of items
        /// </summary>
        /// <param name="items">The items to populate this collection with</param>
        private void InternalLoadCollection(IEnumerable <T> items)
        {
            Debug.Assert(items != null, "items != null");
#if !PORTABLELIB
            // For SDP, we must execute the Query implicitly
            DataServiceQuery <T> query = items as DataServiceQuery <T>;
            if (query != null)
            {
                items = query.Execute() as QueryOperationResponse <T>;
            }
#else
            Debug.Assert(!(items is DataServiceQuery), "SL Client using DSQ as items...should have been caught by ValidateIteratorParameter.");
#endif

            foreach (T item in items)
            {
                // if this is too slow, consider hashing the set
                // or just use LoadProperties
                if (!this.Contains(item))
                {
                    this.Add(item);
                }
            }

            QueryOperationResponse <T> response = items as QueryOperationResponse <T>;
            if (response != null)
            {
                // this should never be throwing (since we've enumerated already)!
                // Note: Inner collection's nextPartLinkUri is set by the materializer
                this.continuation = response.GetContinuation();
            }
            else
            {
                this.continuation = null;
            }
        }
Пример #26
0
            public void QueryRowCountInlineAndValue()
            {
                DataServiceQuery <northwindClient.Customers> q = (DataServiceQuery <northwindClient.Customers>)(from c in ctx.CreateQuery <northwindClient.Customers>("Customers").IncludeCount()
                                                                                                                select c);

                QueryOperationResponse <northwindClient.Customers> r = (QueryOperationResponse <northwindClient.Customers>)q.Execute();
                long sc1 = r.Count;

                q = (DataServiceQuery <northwindClient.Customers>)(from c in ctx.CreateQuery <northwindClient.Customers>("Customers")
                                                                   select c);
                long sc2 = q.LongCount();

                Assert.AreEqual(sc1, sc2);
            }
Пример #27
0
        //Constructor
        public DM_DBConnection()
        {
            aList = CL_List.Instance;
            _carRentalEntities = new Fi12_peterson_infrastrukturDBEntities(
                new Uri("http://localhost:5202/WcfCarRentalSchoolDataService.svc"));

            DataServiceQuery <Adresse> queryAddress = _carRentalEntities.Adresse;

            addressListEnumerable = queryAddress.Execute();

            DataServiceQuery <Kontakt> queryContact = _carRentalEntities.Kontakt;

            contactListEnumerable = queryContact.Execute();

            DataServiceQuery <Anmeldung> queryLogin = _carRentalEntities.Anmeldung;

            loginListEnumerable = queryLogin.Execute();

            DataServiceQuery <Benutzerart> queryUserType = _carRentalEntities.Benutzerart;

            userTypeListEnumerable = queryUserType.Execute();

            DataServiceQuery <Benutzer> queryUser = _carRentalEntities.Benutzer;

            userListEnumerable = queryUser.Execute();

            DataServiceQuery <Fahrzeugtyp> queryVehicleType = _carRentalEntities.Fahrzeugtyp;

            vehicleTypeListEnumerable = queryVehicleType.Execute();

            DataServiceQuery <Versicherungspaket> queryInsurancePackage = _carRentalEntities.Versicherungspaket;

            insurancePackageListEnumerable = queryInsurancePackage.Execute();

            DataServiceQuery <Fahrzeug> queryVehicle = _carRentalEntities.Fahrzeug;

            vehicleListEnumerable = queryVehicle.Execute();

            DataServiceQuery <Kunde> queryCustomer = _carRentalEntities.Kunde;

            customerListEnumerable = queryCustomer.Execute();

            DataServiceQuery <Auftrag> queryOrder = _carRentalEntities.Auftrag;

            orderListEnumerable = queryOrder.Execute();

            aList.AddressList           = new ObservableCollection <Adresse>(addressListEnumerable.ToList());
            aList.AddressComparisonList = new ObservableCollection <Adresse>(aList.AddressList.ToList());

            aList.ContactList           = new ObservableCollection <Kontakt>(contactListEnumerable.ToList());
            aList.ContactComparisonList = new ObservableCollection <Kontakt>(aList.ContactList.ToList());

            aList.LoginList           = new ObservableCollection <Anmeldung>(loginListEnumerable.ToList());
            aList.LoginComparisonList = new ObservableCollection <Anmeldung>(aList.LoginList.ToList());

            aList.UserTypeList = new ObservableCollection <Benutzerart>(userTypeListEnumerable.ToList());

            aList.UserList           = new ObservableCollection <Benutzer>(userListEnumerable.ToList());
            aList.UserComparisonList = new ObservableCollection <Benutzer>(aList.UserList.ToList());

            aList.VehicleTypeList      = new ObservableCollection <Fahrzeugtyp>(vehicleTypeListEnumerable.ToList());
            aList.InsurancePackageList = new ObservableCollection <Versicherungspaket>(insurancePackageListEnumerable.ToList());

            aList.VehicleList = new ObservableCollection <Fahrzeug>(vehicleListEnumerable.ToList());
            foreach (Fahrzeug aVehicle in aList.VehicleList)
            {
                foreach (Fahrzeugtyp aVehicleType in aList.VehicleTypeList)
                {
                    if (aVehicle.FahrzeugtypID == aVehicleType.FahrzeugtypID)
                    {
                        aVehicle.Fahrzeugtyp = aVehicleType;
                    }
                }

                foreach (Versicherungspaket aInsurancePackage in aList.InsurancePackageList)
                {
                    if (aVehicle.VersicherungspaketID == aInsurancePackage.VersicherungspaketID)
                    {
                        aVehicle.Versicherungspaket = aInsurancePackage;
                    }
                }
            }
            aList.VehicleComparisonList = new ObservableCollection <Fahrzeug>(aList.VehicleList.ToList());

            aList.CustomerList = new ObservableCollection <Kunde>(customerListEnumerable.ToList());
            foreach (Kunde aCustomer in aList.CustomerList)
            {
                foreach (Adresse aAddress in aList.AddressList)
                {
                    if (aCustomer.AdresseID == aAddress.AdresseID)
                    {
                        aCustomer.Adresse = aAddress;
                    }
                }

                foreach (Kontakt aContact in aList.ContactList)
                {
                    if (aCustomer.KontaktID == aContact.KontaktID)
                    {
                        aCustomer.Kontakt = aContact;
                    }
                }
            }
            aList.CustomerComparisonList = new ObservableCollection <Kunde>(aList.CustomerList.ToList());

            aList.OrderList = new ObservableCollection <Auftrag>(orderListEnumerable.ToList());
            foreach (Auftrag aOrder in aList.OrderList)
            {
                foreach (Kunde aCustomer in aList.CustomerList)
                {
                    if (aOrder.KundeID == aCustomer.KundeID)
                    {
                        aOrder.Kunde = aCustomer;
                    }
                }

                foreach (Fahrzeug aVehicle in aList.VehicleList)
                {
                    if (aOrder.FahrzeugID == aVehicle.FahrzeugID)
                    {
                        aOrder.Fahrzeug = aVehicle;
                    }
                }
            }
            aList.OrderComparisonList       = new ObservableCollection <Auftrag>(aList.OrderList.ToList());
            aList.VehicleSortedByTypeList   = new ObservableCollection <Fahrzeug>();
            aList.OrderSortedByCustomerList = new ObservableCollection <Auftrag>();
        }
Пример #28
0
        /// <summary>
        /// Select a colleciton of items from the data source
        /// </summary>
        /// <returns>Collection of Item</returns>
        public IEnumerable <TQuery> ExecuteQuery <TQuery>(IQueryable <TQuery> query)
        {
            DataServiceQuery <TQuery> service = query as DataServiceQuery <TQuery>;

            return(service.Execute());
        }
        public void NamedStreams_NestedQuery_2()
        {
            // projecting out collection of collection properties - both narrow type and anonymous type
            {
                // Querying url of the nested type - doing this makes the entity non-tracking, but populated the link property
                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                context.EnableAtom = true;
                context.Format.UseAtom();
                DataServiceQuery <EntityWithNamedStreams1> q = (DataServiceQuery <EntityWithNamedStreams1>) from s in context.CreateQuery <EntityWithNamedStreams1>("MySet1")
                                                               select new EntityWithNamedStreams1
                {
                    ID         = s.ID,
                    Stream1    = s.Stream1,
                    Collection = (from c in s.Collection
                                  select new EntityWithNamedStreams2()
                    {
                        ID = c.ID,
                        ColStream = c.ColStream,
                        Collection1 = (from c1 in c.Collection1
                                       select new EntityWithNamedStreams1()
                        {
                            ID = c1.ID,
                            RefStream1 = c1.RefStream1
                        }).ToList()
                    }).ToList()
                };

                Assert.AreEqual(request.ServiceRoot.AbsoluteUri + "/MySet1?$expand=Collection($select=ID),Collection($select=ColStream),Collection($expand=Collection1($select=ID)),Collection($expand=Collection1($select=RefStream1))&$select=ID,Stream1", q.ToString(), "make sure the right uri is produced by the linq translator");

                var response = (QueryOperationResponse <EntityWithNamedStreams1>)q.Execute();
                DataServiceQueryContinuation <EntityWithNamedStreams2> continuation = null;
                foreach (var o in response)
                {
                    Assert.IsNotNull(o.Stream1.EditLink, "Stream1 should not be null");
                    Assert.AreEqual(o.Stream1.EditLink, context.GetReadStreamUri(o, "Stream1"), "the stream url for Stream1 must be populated correctly");
                    foreach (var c in o.Collection)
                    {
                        Assert.IsNotNull(c.ColStream.EditLink, "ColStream should not be null");
                        Assert.AreEqual(c.ColStream.EditLink, context.GetReadStreamUri(c, "ColStream"), "the url for the nested collection entity should match - Level 0");
                        foreach (var c1 in c.Collection1)
                        {
                            Assert.IsNotNull(c1.RefStream1.EditLink, "RefStream1 should not be null");
                            Assert.AreEqual(c1.RefStream1.EditLink, context.GetReadStreamUri(c1, "RefStream1"), "the url for the nested collection entity should match - Level 1");
                        }
                    }

                    // Make sure you get the continuation token for the collection and try and get the next page
                    continuation = response.GetContinuation(o.Collection);
                }

                Assert.AreEqual(context.Entities.Count, 3, "there should be 3 entities tracked by the context");
                Assert.AreEqual(context.Entities[0].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet1(1)", "top level entity must be tracked");
                Assert.AreEqual(context.Entities[1].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet3('ABCDE')", "top level entity must be tracked");
                Assert.AreEqual(context.Entities[2].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet2(3)", "the nested entity must be tracked");
                Assert.IsNotNull(continuation, "since SDP is turned on, we should get the continuation token");

                // Get the next page and make sure we get the right entity and the link is populated.
                foreach (var entity in context.Execute(continuation))
                {
                    Assert.IsNotNull(entity.ColStream.EditLink, "ColStream should not be null");
                    Assert.AreEqual(entity.ColStream.EditLink, context.GetReadStreamUri(entity, "ColStream"), "the url for the nested collection entity should match - Level 1");
                    foreach (var c1 in entity.Collection1)
                    {
                        Assert.IsNotNull(c1.RefStream1.EditLink, "RefStream1 should not be null");
                        Assert.AreEqual(c1.RefStream1.EditLink, context.GetReadStreamUri(c1, "RefStream1"), "the url for the nested collection entity should match - Level 1");
                    }
                }

                Assert.AreEqual(context.Entities.Count, 4, "there should be 4 entities tracked by the context");
            }

            {
                // Querying url of the nested type - doing this makes the entity non-tracking, but populated the link property
                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                context.EnableAtom = true;
                context.Format.UseAtom();
                var q = from s in context.CreateQuery <EntityWithNamedStreams1>("MySet1")
                        select new
                {
                    ID         = s.ID,
                    Stream1Url = s.Stream1,
                    Collection = (from c in s.Collection
                                  select new
                    {
                        Name = c.Name,
                        Stream1Url = c.ColStream,
                        Collection1 = (from c1 in c.Collection1
                                       select new
                        {
                            ID = c1.ID,
                            Stream1Url = c1.RefStream1
                        })
                    })
                };

                Assert.AreEqual(request.ServiceRoot.AbsoluteUri + "/MySet1?$expand=Collection($select=Name),Collection($select=ColStream),Collection($expand=Collection1($select=ID)),Collection($expand=Collection1($select=RefStream1))&$select=ID,Stream1", q.ToString(), "make sure the right uri is produced by the linq translator");

                foreach (var o in q)
                {
                    Assert.AreEqual(o.Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet1(1)/Stream1", "the stream url for Stream1 must be populated correctly");
                    Assert.AreEqual(o.Collection.First().Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet3('ABCDE')/ColStream", "the stream url of the collection stream must be populated correctly - index 0");
                    Assert.AreEqual(o.Collection.First().Collection1.Single().Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet2(3)/RefStream1", "the stream url of the collection stream must be populated correctly - index 0 - index 0");
                }

                Assert.AreEqual(context.Entities.Count, 0, "there should be no entities tracked by the context");
            }
        }
Пример #30
0
            public void QueryRowCountInlineAndValueWithKeyPredicate()
            {
                DataServiceQuery <northwindClient.Customers> q =
                    ((DataServiceQuery <northwindClient.Customers>)
                         (from c in ctx.CreateQuery <northwindClient.Customers>("Customers").Where(cc => cc.CustomerID == "ALFKI")
                         select c)).IncludeTotalCount();

                QueryOperationResponse <northwindClient.Customers> r = (QueryOperationResponse <northwindClient.Customers>)q.Execute();
                long sc1 = r.TotalCount;

                q = (DataServiceQuery <northwindClient.Customers>)
                        (from c in ctx.CreateQuery <northwindClient.Customers>("Customers").Where(cc => cc.CustomerID == "ALFKI")
                        select c);
                long sc2 = q.LongCount();

                Assert.AreEqual(sc1, sc2);
            }