Beispiel #1
0
        public IActionResult SaveList(string NewListName, List <string[]> NewListCategories)
        {
            // Execute stored procedure to create new list
            _context.Database.ExecuteSqlRaw("EXECUTE Packd.CreateNewList_StoredProcedure {0}", NewListName);

            foreach (var item in NewListCategories)
            {
                var CategoryToSave = item[0];

                // Save Category to Category table in the database (if not already there)
                if (!CommonQueries.CategoryExists(_context, CategoryToSave))
                {
                    _context.Database.ExecuteSqlRaw("EXECUTE Packd.CreateNewCategory_StoredProcedure {0}", CategoryToSave);
                }

                var CategoryId = CommonQueries.GetCategoryId(_context, CategoryToSave);
                var ListId     = CommonQueries.GetListId(_context, NewListName);

                for (var i = 1; i < item.Length; i++)
                {
                    // Save Item to Items table in the database (if not already there)
                    if (!CommonQueries.ItemExistsInCategory(_context, item[i], CategoryId))
                    {
                        _context.Database.ExecuteSqlRaw("EXECUTE Packd.CreateNewItem_StoredProcedure {0}, {1}", item[i], CategoryId);
                    }

                    var ItemId = CommonQueries.GetItemId(_context, CategoryId, item[i]);

                    // Save Item to ListContent table in the database
                    _context.Database.ExecuteSqlRaw("EXECUTE Packd.CreateNewListContent_StoredProcedure {0}, {1}, {2}", ListId, CategoryId, ItemId);
                }
            }

            return(RedirectToAction("MyLists"));
        }
        public static async Task Handler(
            [ServiceBusTrigger("agroqueue", Connection = "ServiceBusConnectionString", IsSessionsEnabled = true)] Message message,
            [SignalR(HubName = "AsyncConnection")] IAsyncCollector <SignalRMessage> signalRMessages,
            ILogger log)
        {
            var opInstance  = ServiceBus.Deserialize(message.Body);
            var ObjectIdAAD = opInstance.Value <string>("ObjectIdAAD");
            var queries     = new CommonQueries(ConfigManager.GetDbArguments);
            var userId      = await queries.GetUserIdFromAAD(ObjectIdAAD);

            var EntityName = opInstance.Value <string>("EntityName");
            var agro       = await ContainerMethods.AgroManager(ObjectIdAAD, false);

            var     entityType = opInstance["EntityType"].ToObject <Type>();
            var     repo       = agro.GetOperationByInputType(entityType);
            dynamic element    = opInstance["Element"].ToObject(entityType);

            element.Id = opInstance.Value <string>("Id");
            try {
                var saveReturn = await repo.SaveInput(element, false);

                await agro.UserActivity.SaveInput(new UserActivityInput {
                    Action     = opInstance.Value <string>("HttpMethod").Equals("post") ? UserActivityAction.CREATE : UserActivityAction.MODIFY,
                    Date       = DateTime.Now,
                    EntityName = EntityName,
                    EntityId   = saveReturn.IdRelated
                }, false);

                await signalRMessages.AddAsync(new SignalRMessage { Target = "Success", UserId = userId, Arguments = new object[] { EntityName } });
            }
            catch (Exception ex) {
                log.LogError(ex, ex.Message);
                await signalRMessages.AddAsync(new SignalRMessage { Target = "Error", UserId = userId, Arguments = new object[] { ex is Validation_Exception ? ((Validation_Exception)ex).ErrorMessages : (object)new string[] { $"{ex.Message}" } } });
            }
        }
Beispiel #3
0
        private async Task DoSwipeDownload(BookData bookData)
        {
            var bookcard = GetBookCardFromBookData(bookData);

            var bookdb = BookDataContext.Get();
            var nd     = CommonQueries.BookNavigationDataEnsure(bookdb, bookData);

            nd.NSwipeRight++;
            nd.NSpecificSelection++;
            CommonQueries.BookSaveChanges(bookdb);

            // Before I can download, make sure that the download file list is set up.
            SetupDownloadsIfNeeded(bookData);

            // But wait! If the book is already downloaded, then just display it
            var fileStatus = bookData.DownloadData == null ? DownloadData.FileStatus.Unknown : bookData.DownloadData.CurrFileStatus;

            switch (fileStatus)
            {
            case DownloadData.FileStatus.Downloaded:
                var nav = Navigator.Get();
                nav.DisplayBook(ControlId, bookData);
                break;

            default:
                await bookcard.DoDownloadAsync();

                break;
            }
        }
 private void ShowAllBooksNotes_Click(object sender, RoutedEventArgs e)
 {
     if ((e.OriginalSource as AppBarToggleButton).IsChecked.Value)
     {
         // All books, please
         var list      = CommonQueries.BookNotesGetAll();
         var titleList = new List <UserNoteWithTitle>();
         foreach (var bn in list)
         {
             foreach (var note in bn.Notes)
             {
                 titleList.Add(new UserNoteWithTitle(note, true));
             }
         }
         var sortedList = titleList.OrderBy(item => item.Title).ThenBy(item => item.BaseNote.LocationNumericValue);
         Notes.Clear();
         foreach (var note in sortedList)
         {
             Notes.Add(note);
         }
     }
     else
     {
         // Just the one book
         SetNotes(CurrBookData);
     }
 }
        private void DeleteNotes_Click(object sender, RoutedEventArgs e)
        {
            var bookdb = BookDataContext.Get();

            UserNoteWithTitle[] list = new UserNoteWithTitle[uiList.SelectedItems.Count];
            int i = 0;

            foreach (var item in uiList.SelectedItems)
            {
                list[i++] = item as UserNoteWithTitle;
            }
            foreach (var note in list)
            {
                Notes.Remove(note);
                var bookId = note.BookId;
                var bn     = CommonQueries.BookNotesFind(bookdb, bookId);
                if (bn == null)
                {
                    ;
                }
                else if (bn.Notes != null)
                {
                    bn.Notes.Remove(note.BaseNote);
                }
            }
            CommonQueries.BookSaveChanges(bookdb);
        }
Beispiel #6
0
        /// <summary>
        /// Will do an absolute save position. This is almost never needed; instead use the
        /// SavePositionEZ which will save in a CPU and disk friendlier way.
        /// </summary>
        private async Task SavePositionNow()
        {
            if (BookData == null)
            {
                return;
            }
            var bookdb = BookDataContext.Get();

            var currPosition = GetCurrBookLocation().ToJson();

            if (currPosition == lastSavedPosition)
            {
                return;
            }
            var nd = EnsureBookNavigationData(bookdb);

            if (nd == null)
            {
                return;
            }
            nd.CurrSpot       = currPosition;
            lastSavedPosition = currPosition;
            CommonQueries.BookSaveChanges(bookdb);

            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

            localSettings.Values[CURR_READING_BOOK_ID]  = BookData.BookId;
            localSettings.Values[CURR_READING_BOOK_POS] = currPosition;

            // Update the bookmark file, too.
            await BookMarkFile.SmartSaveAsync(BookMarkFile.BookMarkFileType.RecentOnly);
        }
        private void SetNotes(BookData bookData)
        {
            var bookdb = BookDataContext.Get();

            if (bookData == null)
            {
                // Do a refresh as needed
                bookData = CurrBookData;
                if (bookData == null)
                {
                    return; // very uncommon -- perhaps race conditions and startup?
                }
            }
            CurrBookData = bookData;
            Notes.Clear();
            var bookId = CurrBookData.BookId;
            var bn     = CommonQueries.BookNotesFind(bookdb, bookId);

            if (bn == null)
            {
                ;
            }
            else if (bn.Notes != null)
            {
                var sorted = bn.Notes.OrderBy(note => note.LocationNumericValue).ToList();
                foreach (var note in sorted)
                {
                    Notes.Add(new UserNoteWithTitle(note, false));
                }
            }
        }
Beispiel #8
0
        public IActionResult NewList()
        {
            ListContentData DefaultListContent = CommonQueries.GetListContentData(_context);

            ViewBag.DefaultListContent = DefaultListContent;

            return(View());
        }
        public void EnsureCommonQueriesDisposesRouter()
        {
            var router = _kernel.GetMock <IBrokerRouter>();
            var common = new CommonQueries(router.Object);

            using (common) { }
            router.Verify(x => x.Dispose(), Times.Once());
        }
        public void EmptyTopicMetadataShouldThrowException()
        {
            var routerProxy = new BrokerRouterProxy(_kernel);
            var router      = routerProxy.Create();
            var common      = new CommonQueries(router);

            common.GetTopic("MissingTopic");
        }
Beispiel #11
0
        public IActionResult DisplayList(int Id)
        {
            ListContentData DisplayListContent = CommonQueries.GetListContentData(_context, Id);

            ViewBag.DisplayListContent = DisplayListContent;

            return(View());
        }
        public void GetTopicShouldReturnTopic()
        {
            var routerProxy = new BrokerRouterProxy(_kernel);
            var router      = routerProxy.Create();
            var common      = new CommonQueries(router);

            var result = common.GetTopic(BrokerRouterProxy.TestTopic);

            Assert.That(result.Name, Is.EqualTo(BrokerRouterProxy.TestTopic));
        }
Beispiel #13
0
 public AgroManager(AgroDbArguments arguments, IEmail email, IUploadImage uploadImage, IWeatherApi weatherApi, IAgroSearch searchServiceInstance, string ObjectIdAAD, bool _isBatch)
 {
     Arguments              = arguments;
     _email                 = email;
     _uploadImage           = uploadImage;
     _weatherApi            = weatherApi;
     _searchServiceInstance = searchServiceInstance;
     UserId                 = CommonQueries.GetUserIdFromAAD(ObjectIdAAD).Result;
     isBatch                = _isBatch;
 }
Beispiel #14
0
        private void OnStarRatingChanged(RatingControl sender, object args)
        {
            var value = sender.Value;

            EnsureReview();
            BookData.Review.NStars = value;
            var bookdb = BookDataContext.Get();

            CommonQueries.BookSaveChanges(bookdb);
        }
Beispiel #15
0
        public static void ReloadAllNotes()
        {
            AllNotes = new Dictionary <string, BookNotes>();
            var bn = CommonQueries.BookNotesGetAll();

            foreach (var note in bn)
            {
                AllNotes[note.BookId] = note;
            }
        }
        public void GetTopicOffsetShouldQueryEachBroker()
        {
            var routerProxy = new BrokerRouterProxy(_kernel);
            var router      = routerProxy.Create();
            var common      = new CommonQueries(router);

            var result = common.GetTopicOffsetAsync(BrokerRouterProxy.TestTopic).Result;

            Assert.That(routerProxy.BrokerConn0.OffsetRequestCallCount, Is.EqualTo(1));
            Assert.That(routerProxy.BrokerConn1.OffsetRequestCallCount, Is.EqualTo(1));
        }
Beispiel #17
0
        public static IEnumerable <EveItem> Completions(string input)
        {
            var completions = CommonQueries.GetTypesWithNamesLike(input + "%").ToList();

            if (completions.Count < 100)
            {
                completions.AddRange(CommonQueries.GetTypesWithNamesLike("%" + input + "%").Where(item => !completions.Contains(item)));
            }

            return(completions.Select(res => new EveItem(res.Item1, res.Item2)));
        }
Beispiel #18
0
        private async void OnCreateDatabase(object sender, RoutedEventArgs e)
        {
            BookDataContext.ResetSingleton("InitialBookData.Db");
            var bookdb = BookDataContext.Get();

            CommonQueries.BookDoMigrate(bookdb); // might not exist at all; Migrate is the way to force creation of tables.

            var iftg = new InitializeFilesToGet();
            await iftg.CreateDatabaseAsync(bookdb);

            BookDataContext.ResetSingleton(null); // reset database
        }
Beispiel #19
0
 public AgroManager(IDbAgroConnect dbConnect, IEmail email, IUploadImage uploadImage, IWeatherApi weatherApi, IAgroSearch <T> searchServiceInstance, string ObjectIdAAD)
 {
     this.dbConnect = dbConnect;
     _email         = email;
     _uploadImage   = uploadImage;
     _weatherApi    = weatherApi;
     Search         = searchServiceInstance;
     if (!string.IsNullOrWhiteSpace(ObjectIdAAD))
     {
         UserId = CommonQueries.GetUserIdFromAAD(ObjectIdAAD).Result;
     }
 }
Beispiel #20
0
        private void MarkBookUserCurrStatus(BookNavigationData.UserStatus status)
        {
            var bookdb = BookDataContext.Get();
            var nd     = EnsureBookNavigationData(bookdb);

            if (nd == null)
            {
                return;
            }
            nd.TimeMarkedDone = DateTimeOffset.Now;
            nd.CurrStatus     = status; // e.g. Abandoned, Read, Reading, NoStatus
            CommonQueries.BookSaveChanges(bookdb);
        }
        public void GetTopicOffsetShouldThrowAnyException()
        {
            var routerProxy = new BrokerRouterProxy(_kernel);

            routerProxy.BrokerConn0.OffsetResponseFunction = () => { throw new ApplicationException("test 99"); };
            var router = routerProxy.Create();
            var common = new CommonQueries(router);

            common.GetTopicOffsetAsync(BrokerRouterProxy.TestTopic).ContinueWith(t =>
            {
                Assert.That(t.IsFaulted, Is.True);
                Assert.That(t.Exception.Flatten().ToString(), Is.StringContaining("test 99"));
            }).Wait();
        }
Beispiel #22
0
        private void SetReviewSymbol()
        {
            var bookdb  = BookDataContext.Get();
            var review  = CommonQueries.UserReviewFind(bookdb, BookData.BookId);
            var button  = uiReviewMenuButton;
            var symbol  = Symbol.Favorite; // filled favorite
            var outline = Symbol.OutlineStar;

            if (review == null || review.IsNotSet)
            {
                symbol = outline;
            }
            button.Icon = new SymbolIcon(symbol);
        }
Beispiel #23
0
        public static async Task <IActionResult> NegotiatBindingAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "negotiate")] HttpRequest req,
            IBinder binder,
            ILogger log)
        {
            string AUTH_HEADER_NAME = "Authorization";
            string BEARER_PREFIX    = "Bearer ";

            if (req.Headers.ContainsKey(AUTH_HEADER_NAME) && req.Headers[AUTH_HEADER_NAME].ToString().StartsWith(BEARER_PREFIX))
            {
                var token = req.Headers[AUTH_HEADER_NAME].ToString().Substring(BEARER_PREFIX.Length);

                if (token.Equals("cloud-app"))
                {
                    var conn = binder.Bind <SignalRConnectionInfo>(new SignalRConnectionInfoAttribute {
                        HubName = "agro", UserId = "cloud-app"
                    });

                    return(new OkObjectResult(conn));
                }

                log.LogInformation("with binding " + token);
                IAuthentication auth = new Authentication(
                    Environment.GetEnvironmentVariable("clientID", EnvironmentVariableTarget.Process),
                    Environment.GetEnvironmentVariable("tenant", EnvironmentVariableTarget.Process),
                    Environment.GetEnvironmentVariable("tenantID", EnvironmentVariableTarget.Process),
                    Environment.GetEnvironmentVariable("validAudiences", EnvironmentVariableTarget.Process).Split(";")
                    );
                var claims = await auth.ValidateAccessToken(token);

                string ObjectIdAAD = claims.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                var    queries     = new CommonQueries(ConfigManager.GetDbArguments);
                // extract userId from token
                var userId = await queries.GetUserIdFromAAD(ObjectIdAAD);

                var connectionInfo = binder.Bind <SignalRConnectionInfo>(new SignalRConnectionInfoAttribute {
                    HubName = "agro", UserId = userId
                });
                log.LogInformation("negotiated " + connectionInfo);
                //https://gist.github.com/ErikAndreas/72c94a0c8a9e6e632f44522c41be8ee7
                // connectionInfo contains an access key token with a name identifier claim set to the authenticated user
                return(new OkObjectResult(connectionInfo));
            }
            else
            {
                // temporal, para conectar winform sin autenticación
                return(new UnauthorizedResult());
            }
        }
Beispiel #24
0
        public void SaveData()
        {
            var bookdb = BookDataContext.Get();

            if (BookData != null)
            {
                EnsureReview();
                BookData.Review.Review = uiReview.TextValue;
                BookData.Review.Tags   = uiTags.Text;
                CommonQueries.BookSaveChanges(bookdb);
            }

            // // // TODO: actually save note.... uiNotes.SaveNote(); //
            uiNoteEditor.SaveNoteIfNeeded(Navigator.NavigateControlId.MainReader, bookdb);
        }
Beispiel #25
0
        public IActionResult Edit(int ListId)
        {
            // Don't edit if default list
            if (ListId == 1)
            {
                return(RedirectToAction("MyLists"));
            }

            ListContentData DefaultListContent    = CommonQueries.GetListContentData(_context);
            ListContentData ListToEditListContent = CommonQueries.GetListContentData(_context, ListId);

            ViewBag.DefaultListContent    = DefaultListContent;
            ViewBag.ListToEditListContent = ListToEditListContent;

            return(View());
        }
Beispiel #26
0
        public void ResetDownloadPanel()
        {
            var book = DataContext as BookData;

            // Set up the uiDownload combo box
            uiDownloadList.Items.Clear();
            // Get a subset of the offered items -- we don't need to see multiple
            // text files with different character sets when we already have just
            // the one we need.
            var list = FilenameAndFormatData.GetProcessedFileList(book.Files.ToList());

            foreach (var file in list)
            {
                var cbi = new ComboBoxItem()
                {
                    Content = file.FileTypeAsString(),
                    Tag     = file
                };
                uiDownloadList.Items.Add(cbi);
            }
            if (uiDownloadList.Items.Count > 0)
            {
                uiDownloadList.SelectedIndex = 0;
            }

            var bookdb     = BookDataContext.Get();
            var dd         = CommonQueries.DownloadedBookFind(bookdb, book.BookId);
            var fileStatus = dd?.CurrFileStatus ?? DownloadData.FileStatus.Unknown;

            switch (fileStatus)
            {
            case DownloadData.FileStatus.Unknown:
            case DownloadData.FileStatus.Deleted:
                AllowEnableDownloadPanel = true;
                break;

            case DownloadData.FileStatus.Downloaded:
                AllowEnableDownloadPanel = false;
                break;
            }
            uiDownloadButton.Visibility        = Visibility.Visible;
            uiCancelDownloadButton.Visibility  = Visibility.Collapsed;
            uiDownloadProgress.IsIndeterminate = false;
            uiDownloadProgress.Value           = 0;

            uiDownloadFinished.Visibility = Visibility.Collapsed;
        }
Beispiel #27
0
        static async Task Main(string[] args)
        {
            var queriesToDB = new CommonQueries(new CosmosDbArguments {
                EndPointUrl = "https://agro-cosmodb.documents.azure.com:443/", NameDb = "agro-cosmodb", PrimaryKey = "kaPYpzhFCcG1bk3aC69aX1T2amavVi8TfHmrIMNJuhpYXtIz67PMhwBKctunNzclFBcxypZvcjPUW846YZuvjA=="
            });
            var searchServiceInstance = new AgroSearch <GeographyPoint>("https://fenix-search.search.windows.net/", "EFF07EE3D5A0C74C2363EC4DDB9710D7", new ImplementsSearch(), new HashEntityAgroSearch());

            var entityTypes = new List <Type> {
                typeof(ApplicationOrder),
                typeof(ApplicationTarget),
                typeof(Barrack),
                typeof(Brand),
                typeof(BusinessName),
                typeof(CertifiedEntity),
                typeof(Comment),
                typeof(CostCenter),
                typeof(Dose),
                typeof(ExecutionOrder),
                typeof(ExecutionOrderStatus),
                typeof(Ingredient),
                typeof(IngredientCategory),
                typeof(Job),
                typeof(Nebulizer),
                typeof(NotificationEvent),
                typeof(PhenologicalEvent),
                typeof(PlotLand),
                typeof(PreOrder),
                typeof(Product),
                typeof(OrderFolder),
                typeof(Role),
                typeof(Season),
                typeof(Sector),
                typeof(Specie),
                typeof(Tractor),
                typeof(Rootstock),
                typeof(UserApplicator),
                typeof(Variety),
                typeof(Warehouse),
                typeof(WarehouseDocument)
            };

            foreach (var entityType in entityTypes)
            {
                await InvokeGenericMethodDynamically <Task>(typeof(Program), "RegenerateIndexFromDB", entityType, null, new object[] { queriesToDB, searchServiceInstance });
            }
        }
        public void SaveNoteIfNeeded(NavigateControlId controlId, BookDataContext bookdb)
        {
            var note = DataContext as UserNote;

            if (note == null)
            {
                return;
            }

            bool changed = SaveToContext();

            if (changed)
            {
                CommonQueries.BookNoteSave(bookdb, note);
                Navigator.Get().UpdatedNotes(controlId);
            }
        }
Beispiel #29
0
        /// <summary>
        /// NavigateTo means navigate to a spot in the book. Will also do a navigation with User...
        /// </summary>
        /// <param name="sourceId"></param>
        /// <param name="location"></param>
        public void NavigateTo(NavigateControlId sourceId, BookLocation location)
        {
            var bookdb = BookDataContext.Get();

            if (Logger.LogExtraTiming)
            {
                Logger.Log($"MainEpubReader: Navigation: to {location}");
            }
            // Save the fact that we navigated to here. Only the main reader saves this information
            var navigationData = CommonQueries.BookNavigationDataFind(bookdb, BookData.BookId);

            if (navigationData == null)
            {
                navigationData = new BookNavigationData()
                {
                    BookId = BookData.BookId, CurrStatus = BookNavigationData.UserStatus.Reading
                };
                CommonQueries.BookNavigationDataAdd(bookdb, navigationData, CommonQueries.ExistHandling.IfNotExists);
            }
            navigationData.CurrSpot   = location.Location;
            navigationData.CurrStatus = BookNavigationData.UserStatus.Reading; // If I'm navigating then I'm reading?


            // And now actually navigate. There are two types of navigation: navigation
            // via tags and navigation by percent.
            // Both need to be handled.
            var percent = location.HtmlPercent;

            if (percent >= 0.0)
            {
                if (Logger.LogExtraTiming)
                {
                    Logger.Log($"MainEpubReader: Navigation: to percent");
                }
                NavigateToPercent(location);
            }
            else
            {
                if (Logger.LogExtraTiming)
                {
                    Logger.Log($"MainEpubReader: Navigation: via location, not percent ({location})");
                }
                NavigateToLocation(location);
            }
        }
Beispiel #30
0
        private void OnSwipeRemove(SwipeItem sender, SwipeItemInvokedEventArgs args)
        {
            var bookdb   = BookDataContext.Get();
            var bookcard = GetBookCardFromSwipe(args);

            if (bookcard == null)
            {
                return;
            }

            var bookData = bookcard.GetBookData();
            var nd       = CommonQueries.BookNavigationDataEnsure(bookdb, bookData);

            nd.NSwipeLeft++;
            CommonQueries.BookSaveChanges(bookdb);

            bookData = args.SwipeControl.DataContext as BookData;
            Books.Remove(bookData);
        }