Exemplo n.º 1
0
        /// <summary>
        /// Gets a list of valid variants based on partial attribute selection
        /// </summary>
        /// <param name="productKey">The product key</param>
        /// <param name="attributeKeys">The selected option choices</param>
        /// <returns>A collection of <see cref="ProductVariantDisplay"/></returns>
        /// <remarks>
        /// Intended to assist in product variant selection 
        /// </remarks>
        public IEnumerable<ProductVariantDisplay> GetValidProductVariants(Guid productKey, Guid[] attributeKeys)
        {
            var product = Product(productKey);
            if(product == null) throw new InvalidOperationException("Product is null");
            if (!attributeKeys.Any()) return product.ProductVariants;

            var variants = product.ProductVariants.Where(x => attributeKeys.All(key => x.Attributes.FirstOrDefault(att => att.Key == key) != null));

            return variants;
        }
Exemplo n.º 2
0
        public static List<TestPerson> StructuredDataTypes(Guid[] guids)
        {
            List<TestPerson> list = null;

            DataProvider.ExecuteCmd(GetConnection, "dbo.TestTable_Structured"
               , inputParamMapper: delegate(SqlParameterCollection paramCollection)
               {
                   SqlParameter p = new SqlParameter("@ParamName", System.Data.SqlDbType.Structured);

                   if (guids != null && guids.Any())
                   {
                       p.Value = new Sabio.Data.UniqueIdTable(guids);
                   }

                   paramCollection.Add(p);

               }, map: delegate(IDataReader reader, short set)
               {
                   TestPerson p = new TestPerson();
                   int startingIndex = 0; //startingOrdinal

                   p.Name = reader.GetSafeString(startingIndex++);
                   p.Last = reader.GetSafeString(startingIndex++);

                   p.Age = reader.GetSafeInt32(startingIndex++);

                   if (list == null)
                   {
                       list = new List<TestPerson>();
                   }

                   list.Add(p);
               }
               );

            return list;
        }
Exemplo n.º 3
0
        public List<OrderDto> GetAll(string sortBy, string sortDirection, Guid[] statusId, DateTime? from, DateTime? to, int pageIndex, int pageSize, out int pageTotal)
        {
            var pagingCriteria = new PagingCriteria();

            pagingCriteria.PageNumber = pageIndex;
            pagingCriteria.PageSize = pageSize;
            pagingCriteria.SortBy = !string.IsNullOrEmpty(sortBy) ? sortBy : "CreatedDate";
            pagingCriteria.SortDirection = !string.IsNullOrEmpty(sortDirection) ? sortDirection : "DESC";

            Expression<Func<Order, bool>> where = x => statusId.Any(y => y == x.OrderStatusId)
                                                   && (!from.HasValue || x.CreatedDate >= from)
                                                   && (!to.HasValue || x.CreatedDate <= to);

            var results = Uow.Orders.GetAll(pagingCriteria, where,
                x => x.Client,
                x => x.Truck,
                x => x.Driver,
                x => x.OrderStatus,
                x => x.Deposit);

            pageTotal = results.PagedMetadata.TotalItemCount;

            return results.Entities.AsEnumerable().Select(Mapper.Map<Order, OrderDto>).ToList();
        }
        public void AttachPermissionToRoles(Guid permissionId, Guid[] roleIds, string handler)
        {
            // Remove all roles that include the permission.
            var spec = Specification<ActionRole>.Eval(a => a.ActionsId == permissionId);
            var rolesOfPms = this._actionRoleRepository.FindAll(spec);
            if (rolesOfPms != null)
            {
                foreach (var item in rolesOfPms)
                    this._actionRoleRepository.Remove(item);
            }

            if (roleIds == null || !roleIds.Any())
                return;

            // attach to role
            var actionRoles = (from roleId in roleIds
                select new ActionRole(permissionId, roleId, handler));
            foreach (var actionRole in actionRoles)
                this._actionRoleRepository.Add(actionRole);
        }
        public void AttachMenuToRoles(Guid menuId, Guid[] roleIds, string handler)
        {
            // Remove all roles that include the menu.
            var spec = Specification<MenuRole>.Eval(a => a.MenuId == menuId);
            var rolesOfmeun = this._menuRoleRepository.FindAll(spec);
            if (rolesOfmeun != null)
            {
                foreach (var item in rolesOfmeun)
                    this._menuRoleRepository.Remove(item);
            }

            if (roleIds == null || !roleIds.Any())
                return;

            // attach to role
            var menuRoles = (from roleId in roleIds
                select new MenuRole(menuId, roleId, handler));
            foreach (var menuRole in menuRoles)
                this._menuRoleRepository.Add(menuRole);
        }
Exemplo n.º 6
0
        public MenuResult UpdateMenu(AuthIdentity identity, Guid? menuId, Guid[] recipesAdd, Guid[] recipesRemove, MenuMove[] recipesMove, bool clear, string newName = null)
        {
            var ret = new MenuResult();
             ret.MenuUpdated = true; // TODO: Verify actual changes were made before setting MenuUpdated to true

             using (var session = GetSession())
             {
            using (var transaction = session.BeginTransaction())
            {
               Models.Menus dbMenu = null;
               IList<Favorites> dbRecipes = null;
               if (menuId.HasValue)
               {
                  dbMenu = session.QueryOver<Models.Menus>()
                     .Fetch(prop => prop.Recipes).Eager
                     .Where(p => p.MenuId == menuId)
                     .SingleOrDefault();

                  if (dbMenu == null)
                     throw new MenuNotFoundException();

                  if (dbMenu.UserId != identity.UserId) // User does not have access to modify this menu
                     throw new UserDoesNotOwnMenuException();

                  if (!String.IsNullOrWhiteSpace(newName) && dbMenu != null) // Rename menu
                     dbMenu.Title = newName.Trim();

                  dbRecipes = dbMenu.Recipes;
               }
               else
               {
                  dbRecipes = session.QueryOver<Favorites>()
                     .Where(p => p.UserId == identity.UserId)
                     .Where(p => p.Menu == null)
                     .List();
               }

               if (recipesAdd.Any()) // Add recipes to menu
               {
                  var existing = (from r in dbRecipes select r.Recipe.RecipeId);
                  recipesAdd = recipesAdd.Except(existing).ToArray(); //Remove dupes

                  foreach (var rid in recipesAdd)
                  {
                     var fav = new Favorites
                     {
                        UserId = identity.UserId,
                        Recipe = new Models.Recipes() {RecipeId = rid},
                        Menu = dbMenu
                     };

                     session.Save(fav);
                  }
               }

               if (recipesRemove.Any()) // Remove recipes from menu
               {
                  var toDelete = (from r in dbRecipes where recipesRemove.Contains(r.Recipe.RecipeId) select r);
                  toDelete.ForEach(session.Delete);
               }

               if (clear) // Remove every recipe from menu
               {
                  dbRecipes.ForEach(session.Delete);
               }

               if (recipesMove.Any()) // Move items to another menu
               {
                  foreach (var moveAction in recipesMove)
                  {
                     Models.Menus dbTarget = null;
                     if (moveAction.TargetMenu.HasValue)
                     {
                        dbTarget = session.QueryOver<Models.Menus>()
                           .Where(p => p.MenuId == moveAction.TargetMenu.Value)
                           .Where(p => p.UserId == identity.UserId)
                           .SingleOrDefault();

                        if (dbTarget == null)
                           throw new MenuNotFoundException(moveAction.TargetMenu.Value);
                     }

                     var rToMove = (moveAction.MoveAll
                        ? dbRecipes
                        : dbRecipes.Where(r => moveAction.RecipesToMove.Contains(r.Recipe.RecipeId)));

                     rToMove.ForEach(a => a.Menu = dbTarget);
                  }
               }

               transaction.Commit();
            }
             }

             return ret;
        }
Exemplo n.º 7
0
        public ShoppingListResult UpdateShoppingList(AuthIdentity identity, Guid? listId, Guid[] toRemove, ShoppingListModification[] toModify, IShoppingListSource[] toAdd, string newName = null)
        {
            using (var session = GetSession())
             {
            using (var transaction = session.BeginTransaction())
            {
               // Deletes
               if (toRemove.Any())
               {
                  var dbDeletes = session.QueryOver<ShoppingListItems>()
                     .Where(p => p.UserId == identity.UserId)
                     .Where(listId.HasValue
                        ? Expression.Eq("ShoppingList", listId.Value)
                        : Expression.IsNull("ShoppingList")
                     ).AndRestrictionOn(p => p.ItemId).IsInG(toRemove)
                     .List();

                  dbDeletes.ForEach(session.Delete);
               }

               // Updates
               Models.ShoppingLists dbList = null;
               IList<ShoppingListItems> dbItems = null;
               if (listId.HasValue)
               {
                  dbList = session.QueryOver<Models.ShoppingLists>()
                     .Fetch(prop => prop.Items).Eager
                     .Where(p => p.UserId == identity.UserId)
                     .Where(p => p.ShoppingListId == listId.Value)
                     .SingleOrDefault();

                  if (dbList == null)
                     throw new ShoppingListNotFoundException();

                  if (!String.IsNullOrWhiteSpace(newName))
                     dbList.Title = newName;

                  dbItems = dbList.Items;
               }
               else
               {
                  dbItems = session.QueryOver<ShoppingListItems>()
                     .Where(p => p.UserId == identity.UserId)
                     .Where(p => p.ShoppingList == null)
                     .List();
               }

               toModify.ForEach(item =>
               {
                  var dbItem = dbItems.FirstOrDefault(i => i.ItemId == item.ModifiedItemId);
                  if (dbItem == null) return;

                  if (item.CrossOut.HasValue) dbItem.CrossedOut = item.CrossOut.Value;
                  if (item.NewAmount != null) dbItem.Amount = item.NewAmount;
               });

               toAdd.ForEach(item =>
               {
                  var source = item.GetItem();

                  if (source.Ingredient == null && !String.IsNullOrWhiteSpace(source.Raw)) // Raw shopping list item
                  {
                     if (!dbItems.Any(i => source.Raw.Equals(i.Raw, StringComparison.OrdinalIgnoreCase))) // Add it
                     {
                        var newItem = new ShoppingListItems
                        {
                           ShoppingList = dbList,
                           UserId = identity.UserId,
                           Raw = source.Raw
                        };

                        session.Save(newItem);
                        dbItems.Add(newItem);
                     }

                     return;
                  }

                  if (source.Ingredient != null && source.Amount == null) // Raw ingredient without any amount
                  {
                     var existingItem = dbItems.FirstOrDefault(i => i.Ingredient != null && i.Ingredient.IngredientId == source.Ingredient.Id);

                     if (existingItem == null) // Add it
                     {
                        var newItem = new ShoppingListItems
                        {
                           ShoppingList = dbList,
                           UserId = identity.UserId,
                           Ingredient = Models.Ingredients.FromId(source.Ingredient.Id)
                        };

                        session.Save(newItem);
                        dbItems.Add(newItem);
                     }
                     else // Clear out existing amount
                     {
                        existingItem.Amount = null;
                     }
                  }

                  if (source.Ingredient != null && source.Amount != null) // Ingredient with amount, aggregate if necessary
                  {
                     var existingItem = dbItems.FirstOrDefault(i => i.Ingredient != null && i.Ingredient.IngredientId == source.Ingredient.Id);

                     if (existingItem == null) // Add it
                     {
                        var newItem = new ShoppingListItems
                        {
                           ShoppingList = dbList,
                           UserId = identity.UserId,
                           Ingredient = Models.Ingredients.FromId(source.Ingredient.Id),
                           Amount = source.Amount
                        };

                        session.Save(newItem);
                        dbItems.Add(newItem);
                     }
                     else if (existingItem.Amount != null) // Add to total
                     {
                        existingItem.Amount += source.Amount;
                     }
                  }
               });

               transaction.Commit();

               return new ShoppingListResult
               {
                  List = new ShoppingList(
                     dbList != null ? (Guid?) dbList.ShoppingListId : null,
                     dbList != null ? dbList.Title : null,
                     dbItems.Select(i => i.AsShoppingListItem()))
               };
            }
             }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Updates a specified menu owned by the current user.
        /// </summary>
        /// <param name="menuId">The Menu ID to update, or null to update the Favorites menu.</param>
        /// <param name="recipesAdd">A list of recipe IDs to add to the menu.  Duplicates will be ignored.</param>
        /// <param name="recipesRemove">A list of recipe IDs to remove from the menu.</param>
        /// <param name="recipesMove">A list of items to move from this menu to another menu.</param>
        /// <param name="clear">If true, all recipes will be removed from this menu.</param>
        /// <param name="newName">An optional new name for this menu.  Note, the favorites menu cannot be renamed.</param>
        /// <returns></returns>
        public MenuResult UpdateMenu(Guid? menuId, Guid[] recipesAdd, Guid[] recipesRemove, MenuMove[] recipesMove, bool clear, string newName = null)
        {
            var ret = new MenuResult();
             ret.IsMenuUpdated = true; // TODO: Verify actual changes were made before setting MenuUpdated to true

             Menus dbMenu = null;
             if (menuId.HasValue)
             {
            dbMenu = store.Menus.SingleOrDefault(p => p.MenuId == menuId);
            if (dbMenu == null)
               throw new MenuNotFoundException();

            if (dbMenu.UserId != Identity.UserId) // User does not have access to modify this menu
               throw new UserDoesNotOwnMenuException();
             }

             var dbFavorites = store.Favorites
            .Where(p => p.MenuId == menuId)
            .ToList();

             if (!string.IsNullOrWhiteSpace(newName) && dbMenu != null) // Rename menu
            dbMenu.Title = newName.Trim();

             if (recipesAdd.Any()) // Add recipes to menu
             {
            var existing = dbFavorites.Select(f => f.RecipeId);
            recipesAdd = recipesAdd.Except(existing).ToArray(); //Remove dupes

            foreach (var rid in recipesAdd)
            {
               var fav = new Favorites
               {
                  FavoriteId = Guid.NewGuid(),
                  UserId = Identity.UserId,
                  RecipeId = rid,
                  MenuId = menuId
               };

               store.Favorites.Add(fav);
            }
             }

             if (recipesRemove.Any()) // Remove recipes from menu
             {
            var toDelete = (from r in dbFavorites where recipesRemove.Contains(r.RecipeId) select r);
            toDelete.ForEach(r => store.Favorites.Remove(r));
             }

             if (clear) // Remove every recipe from menu
             {
            store.Favorites.RemoveAll(dbFavorites.Contains);
             }

             if (recipesMove.Any()) // Move items to another menu
             {
            foreach (var moveAction in recipesMove)
            {
               Menus dbTarget = null;
               if (moveAction.TargetMenu.HasValue)
               {
                  dbTarget = store.Menus
                     .Where(p => p.UserId == Identity.UserId)
                     .SingleOrDefault(p => p.MenuId == moveAction.TargetMenu);

                  if (dbTarget == null)
                     throw new MenuNotFoundException(moveAction.TargetMenu.Value);
               }

               var rToMove = (moveAction.AllMoved
                  ? dbFavorites
                  : dbFavorites.Where(r => moveAction.RecipesToMove.Contains(r.RecipeId)));

               rToMove.ForEach(a => a.MenuId = dbTarget != null ? (Guid?) dbTarget.MenuId : null);
            }
             }

             return ret;
        }
Exemplo n.º 9
0
        ShoppingListResult UpdateShoppingList(Guid? listId, Guid[] toRemove, IEnumerable<ShoppingListModification> toModify, IEnumerable<IShoppingListSource> toAdd, string newName = null)
        {
            // Deletes
             if (toRemove.Any())
             {
            var dbDeletes = store.ShoppingListItems
               .Where(p => p.UserId == Identity.UserId)
               .Where(p => p.ShoppingListId == listId)
               .Where(p => toRemove.Contains(p.ItemId));

            store.ShoppingListItems.RemoveAll(dbDeletes.Contains);
             }

             // Updates
             Guid? shoppingListId = null;
             ShoppingLists dbList = null;
             List<ShoppingListItems> dbItems = null;
             if (listId.HasValue)
             {
            dbList = store.ShoppingLists
               .Where(p => p.UserId == Identity.UserId)
               .SingleOrDefault(p => p.ShoppingListId == listId);

            if (dbList == null)
               throw new ShoppingListNotFoundException();

            dbItems = store.ShoppingListItems
               .Where(p => p.UserId == Identity.UserId)
               .Where(p => p.ShoppingListId.Equals(dbList.ShoppingListId))
               .ToList();

            if (!string.IsNullOrWhiteSpace(newName))
               dbList.Title = newName;

            shoppingListId = dbList.ShoppingListId;
             }
             else
             {
            dbItems = store.ShoppingListItems
               .Where(p => p.UserId == Identity.UserId)
               .Where(p => p.ShoppingListId == null)
               .ToList();
             }

             toModify.ForEach(item =>
             {
            var dbItem = store.ShoppingListItems.SingleOrDefault(p => p.ItemId == item.ModifiedItemId);
            if (dbItem == null) return;

            if (item.CrossOut.HasValue) dbItem.CrossedOut = item.CrossOut.Value;
            if (item.NewAmount != null)
            {
               dbItem.Qty = item.NewAmount.SizeHigh;
               dbItem.Unit = item.NewAmount.Unit;
            }
             });

             toAdd.ForEach(item =>
             {
            var source = item.GetItem();

            if (source.Ingredient == null && !string.IsNullOrWhiteSpace(source.Raw)) // Raw shopping list item
            {
               if (!dbItems.Any(i => source.Raw.Equals(i.Raw, StringComparison.OrdinalIgnoreCase))) // Add it
               {
                  store.ShoppingListItems.Add(new ShoppingListItems
                  {
                     ItemId = Guid.NewGuid(),
                     ShoppingListId = shoppingListId,
                     UserId = Identity.UserId,
                     Raw = source.Raw
                  });
               }

               return;
            }

            if (source.Ingredient != null && source.Amount == null) // Raw ingredient without any amount
            {
               var existingItem = dbItems.FirstOrDefault(i => i.IngredientId.HasValue && i.IngredientId.Value == source.Ingredient.Id);

               if (existingItem == null) // Add it
               {
                  store.ShoppingListItems.Add(new ShoppingListItems
                  {
                     ItemId = Guid.NewGuid(),
                     ShoppingListId = shoppingListId,
                     UserId = Identity.UserId,
                     IngredientId = source.Ingredient.Id
                  });
               }
               else // Clear out existing amount
               {
                  existingItem.Qty = null;
                  existingItem.Unit = null;
               }
            }

            if (source.Ingredient != null && source.Amount != null) // Ingredient with amount, aggregate if necessary
            {
               var existingItem = dbItems.FirstOrDefault(i => i.IngredientId.HasValue && i.IngredientId.Value == source.Ingredient.Id);

               if (existingItem == null) // Add it
               {
                  store.ShoppingListItems.Add(new ShoppingListItems
                  {
                     ItemId = Guid.NewGuid(),
                     ShoppingListId = shoppingListId,
                     UserId = Identity.UserId,
                     IngredientId = source.Ingredient.Id,
                     Qty = source.Amount != null ? (float?) source.Amount.SizeHigh : null,
                     Unit = source.Amount != null ? (Units?) source.Amount.Unit : null
                  });
               }
               else if (existingItem.Qty.HasValue) // Add to total
               {
                  existingItem.Qty += source.Amount.SizeHigh;
               }
            }
             });

             // Load full list to return
             var indexIngredients = store.GetIndexedIngredients();
             var indexRecipes = store.GetIndexedRecipes();

             var items = store.ShoppingListItems
            .Where(p => p.UserId == Identity.UserId)
            .Where(l => l.ShoppingListId == shoppingListId).Select(item =>
               new ShoppingListItem(item.ItemId)
               {
                  Raw = item.Raw,
                  Ingredient = item.IngredientId.HasValue ? Data.DTO.Ingredients.ToIngredient(indexIngredients[item.IngredientId.Value]) : null,
                  Recipe = item.RecipeId.HasValue ? Data.DTO.Recipes.ToRecipeBrief(indexRecipes[item.RecipeId.Value]) : null,
                  CrossedOut = item.CrossedOut,
                  Amount = (item.Qty.HasValue && item.Unit.HasValue) ? new Amount(item.Qty.Value, item.Unit.Value) : null
               });

             return new ShoppingListResult
             {
            List = new ShoppingList(shoppingListId, dbList != null ? dbList.Title : "", items)
             };
        }
        public ShoppingListResult UpdateShoppingList(
            AuthorIdentity identity, 
            Guid? listId, 
            Guid[] toRemove, 
            ShoppingListModification[] toModify, 
            IShoppingListSource[] toAdd, 
            string newName = null)
        {
            using (var session = this.GetSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    if (toRemove.Any())
                    {
                        DeleteItems(identity, listId, toRemove, session);
                    }

                    // Updates
                    ShoppingLists databaseList = null;
                    IList<ShoppingListItems> databaseItems = null;
                    if (listId.HasValue)
                    {
                        databaseList =
                            session.QueryOver<ShoppingLists>()
                                .Fetch(prop => prop.Items)
                                .Eager.Where(p => p.UserId == identity.UserId)
                                .Where(p => p.ShoppingListId == listId.Value)
                                .SingleOrDefault();

                        if (databaseList == null)
                        {
                            throw new ShoppingListNotFoundException();
                        }

                        if (!string.IsNullOrWhiteSpace(newName))
                        {
                            databaseList.Title = newName;
                        }

                        databaseItems = databaseList.Items;
                    }
                    else
                    {
                        databaseItems =
                            session.QueryOver<ShoppingListItems>()
                                .Where(p => p.UserId == identity.UserId)
                                .Where(p => p.ShoppingList == null)
                                .List();
                    }

                    ModifyShopingListItems(toModify, databaseItems);

                    return AddShopingListItems(identity, toAdd, databaseItems, databaseList, session, transaction);
                }
            }
        }
        public MenuResult UpdateMenu(
            AuthorIdentity identity, 
            Guid? menuId, 
            Guid[] recipesAdd, 
            Guid[] recipesRemove, 
            MenuMove[] recipesMove, 
            bool clear, 
            string newName = null)
        {
            var menu = new MenuResult();

            using (var session = this.GetSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    Menus databaseMenu = null;
                    IList<Favorites> databaseRecipes = null;
                    if (menuId.HasValue)
                    {
                        databaseMenu =
                            session.QueryOver<Menus>()
                                .Fetch(prop => prop.Recipes)
                                .Eager.Where(p => p.MenuId == menuId)
                                .SingleOrDefault();

                        if (databaseMenu == null)
                        {
                            throw new MenuNotFoundException();
                        }

                        CheckForUserAccess(identity, databaseMenu);

                        RenameMenu(newName, databaseMenu);

                        databaseRecipes = databaseMenu.Recipes;
                    }
                    else
                    {
                        databaseRecipes =
                            session.QueryOver<Favorites>()
                                .Where(p => p.UserId == identity.UserId)
                                .Where(p => p.Menu == null)
                                .List();
                    }

                    if (recipesAdd.Any())
                    {
                        AddRecipesToMenu(identity, recipesAdd, databaseRecipes, databaseMenu, session);
                        menu.MenuUpdated = true;
                    }

                    if (recipesRemove.Any())
                    {
                        RemoveRecipesFromMenu(recipesRemove, databaseRecipes, session);
                        menu.MenuUpdated = true;
                    }

                    if (clear)
                    {
                        RemoveAllRecipesFromMenu(databaseRecipes, session);
                        menu.MenuUpdated = true;
                    }

                    if (recipesMove.Any())
                    {
                        MoveRecipesToAnotherMenu(identity, recipesMove, session, databaseRecipes);
                        menu.MenuUpdated = true;
                    }

                    transaction.Commit();
                }
            }

            return menu;
        }
Exemplo n.º 12
0
        public async void StartScanningForDevices(Guid[] serviceUuids)
        {
            if (_isScanning)
            {
                Mvx.Trace("Adapter: Already scanning!");
                return;
            }

            _isScanning = true;

            // in ScanTimeout seconds, stop the scan
            _cancellationTokenSource = new CancellationTokenSource();

            try
            {
                // Wait for the PoweredOn state
                await WaitForState(CBCentralManagerState.PoweredOn, _cancellationTokenSource.Token).ConfigureAwait(false);

                Mvx.Trace("Adapter: Starting a scan for devices.");

                CBUUID[] serviceCbuuids = null;
                if (serviceUuids != null && serviceUuids.Any())
                {
                    serviceCbuuids = serviceUuids.Select(u => CBUUID.FromString(u.ToString())).ToArray();
                    Mvx.Trace("Adapter: Scanning for " + serviceCbuuids.First());
                }

                // clear out the list
                _discoveredDevices = new List<IDevice>();

                // start scanning
                _central.ScanForPeripherals(serviceCbuuids);

                await Task.Delay(ScanTimeout, _cancellationTokenSource.Token);

                Mvx.Trace("Adapter: Scan timeout has elapsed.");

                StopScan();

                TryDisposeToken();
                _isScanning = false;

                //important for this to be caled after _isScanning = false so don't move to finally block
                ScanTimeoutElapsed(this, new EventArgs());
            }
            catch (TaskCanceledException)
            {
                Mvx.Trace("Adapter: Scan was cancelled.");
                StopScan();

                TryDisposeToken();
                _isScanning = false;
            }
        }
Exemplo n.º 13
0
        protected override async Task StartScanningForDevicesNativeAsync(Guid[] serviceUuids, bool allowDuplicatesKey, CancellationToken scanCancellationToken)
        {
            // Wait for the PoweredOn state
            await WaitForState(CBCentralManagerState.PoweredOn, scanCancellationToken).ConfigureAwait(false);

            if (scanCancellationToken.IsCancellationRequested)
                throw new TaskCanceledException("StartScanningForDevicesNativeAsync cancelled");

            Trace.Message("Adapter: Starting a scan for devices.");

            CBUUID[] serviceCbuuids = null;
            if (serviceUuids != null && serviceUuids.Any())
            {
                serviceCbuuids = serviceUuids.Select(u => CBUUID.FromString(u.ToString())).ToArray();
                Trace.Message("Adapter: Scanning for " + serviceCbuuids.First());
            }

            DiscoveredDevices.Clear();
            _centralManager.ScanForPeripherals(serviceCbuuids, new PeripheralScanningOptions { AllowDuplicatesKey = allowDuplicatesKey });
        }
Exemplo n.º 14
0
        private async void StartLeScan(Guid[] serviceUuids)
        {
            if (_isScanning)
            {
                Mvx.Trace("Adapter: Already scanning.");
                return;
            }

            _isScanning = true;

            // clear out the list
            _discoveredDevices = new List<IDevice>();

            if (serviceUuids == null || !serviceUuids.Any())
            {
                if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
                {
                    Mvx.Trace("Adapter < 21: Starting a scan for devices.");
                    //without filter
                    _adapter.StartLeScan(this);
                }
                else
                {
                    Mvx.Trace("Adapter >= 21: Starting a scan for devices.");
                    if (_adapter.BluetoothLeScanner != null)
                    {
                        _adapter.BluetoothLeScanner.StartScan(_api21ScanCallback);
                    }
                    else
                    {
                        Mvx.Trace("Adapter >= 21: Scan failed. Bluetooth is probably off");
                    }
                }

            }
            else
            {
                if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
                {
                    var uuids = serviceUuids.Select(u => UUID.FromString(u.ToString())).ToArray();
                    Mvx.Trace("Adapter < 21: Starting a scan for devices.");
                    _adapter.StartLeScan(uuids, this);
                }
                else
                {

                    Mvx.Trace("Adapter >=21: Starting a scan for devices with service ID {0}.", serviceUuids.First());

                    var scanFilters = new List<ScanFilter>();
                    foreach (var serviceUuid in serviceUuids)
                    {
                        var sfb = new ScanFilter.Builder();
                        sfb.SetServiceUuid(ParcelUuid.FromString(serviceUuid.ToString()));
                        scanFilters.Add(sfb.Build());
                    }

                    var ssb = new ScanSettings.Builder();
                    //ssb.SetCallbackType(ScanCallbackType.AllMatches);

                    if (_adapter.BluetoothLeScanner != null)
                    {
                        _adapter.BluetoothLeScanner.StartScan(scanFilters, ssb.Build(), _api21ScanCallback);
                    }
                    else
                    {
                        Mvx.Trace("Adapter >= 21: Scan failed. Bluetooth is probably off");
                    }
                }

            }

            // in ScanTimeout seconds, stop the scan
            _cancellationTokenSource = new CancellationTokenSource();

            try
            {
                await Task.Delay(ScanTimeout, _cancellationTokenSource.Token);

                Mvx.Trace("Adapter: Scan timeout has elapsed.");

                StopScan();

                TryDisposeToken();
                _isScanning = false;

                //important for this to be caled after _isScanning = false;
                ScanTimeoutElapsed(this, new EventArgs());
            }
            catch (TaskCanceledException)
            {
                Mvx.Trace("Adapter: Scan was cancelled.");
                StopScan();

                TryDisposeToken();
                _isScanning = false;
            }
        }