private static void ProcessItem(SPListItem item, bool fIncludeFolderItems, ItemProcessor itemProcessor, ItemProcessorErrorCallout errorCallout) { if (item == null) { throw new ArgumentNullException("item"); } if (itemProcessor == null) { throw new ArgumentNullException("itemProcessor"); } if (fIncludeFolderItems || (item.FileSystemObjectType != SPFileSystemObjectType.Folder)) { try { itemProcessor(item); } catch (System.Exception exception) { if ((errorCallout == null) || errorCallout(item, exception)) { throw; } } } }
public void VerifyBrieHasChanged() { var items = new List <Item> { new Item { Name = Constants.ProductNames.AgedBrie, Quality = 0, SellIn = 2 } }; var initialQuality = items[0].Quality; var initialSellIn = items[0].SellIn; var itemProcessor = new ItemProcessor(items); itemProcessor.UpdateQuality(); var updateItems = itemProcessor.GetItems(); var item = updateItems.FirstOrDefault(i => i.Name.Contains(Constants.ProductNames.AgedBrie)); item.ShouldNotBe(null); item.Quality.ShouldBe(initialQuality + 1); item.SellIn.ShouldBe(initialSellIn - 1); }
private async Task PinRecord(PinRecord Record) { BookItem Book = await ItemProcessor.GetBookFromId(Record.Id); if (Book == null) { return; } TaskCompletionSource <bool> TCS = new TaskCompletionSource <bool>(); BookLoader BL = new BookLoader(async(b) => { if (b != null) { string TileId = await PageProcessor.PinToStart(Book); if (!string.IsNullOrEmpty(TileId)) { PM.RegPin(b, TileId, false); } } TCS.SetResult(true); }); BL.Load(Book); await TCS.Task; }
public override async Task <IList <IEvent> > ProcessAction() { ItemProcessor.InputData = InputData; var itemId = GetValue <string>("Id"); var result = ItemProcessor.DeleteItem(itemId); if (result.Success == false) { return(new List <IEvent>() { new ShowMessage(result.Message) }); } var message = "Item deleted successfully"; if (!String.IsNullOrWhiteSpace(result.Message)) { message = result.Message; } var events = new List <IEvent>(); events.Add(new CancelInputDialog()); if (ViewToShowAfterModify != null) { events.Add(new ExecuteAction(ViewToShowAfterModify, ParametersToPassToViewAfterModify)); } events.Add(new ShowMessage(message)); return(events); }
public void Should_ScanFourItems_AndApplyOffersOnThree_AndUpdatePrice() { Mock <IQueryOffers> mockQueryOffers = new Mock <IQueryOffers>(); Offer offer = new Offer("A99", 3, 1.30M); mockQueryOffers.Setup(_ => _.GetOffersBySku("A99", 3)).Returns(offer); ItemProcessor itemProcessor = new ItemProcessor(mockQueryOffers.Object); Checkout checkout = new Checkout(itemProcessor); Item item = new Item("A99", 0.50M); // scan three items to qualify for theoffer checkout.Scan(item); checkout.Scan(item); checkout.Scan(item); decimal offersPrice = checkout.TotalPriceIncludingOffers(); Assert.AreEqual(offersPrice, offer.OfferPrice); Offer nullOffer = null; // scan an extra item that isn't applicable to another offer mockQueryOffers.Setup(_ => _.GetOffersBySku("A99", 4)).Returns(nullOffer); checkout.Scan(item); offersPrice = checkout.TotalPriceIncludingOffers(); // the total price should now be 1.30 + 0.50 Assert.AreEqual(offersPrice, offer.OfferPrice + item.UnitPrice); }
public async void ProcessItem(IGRRow DataContext) { if (DataContext is GRRow <IBookProcess> Row) { await ItemProcessor.ProcessLocal(( LocalBook )Row.Source); } }
private async Task <bool> _RowAction(IGRRow _Row) { GRRow <BookDisplay> Row = (GRRow <BookDisplay>)_Row; BookInstruction Payload = ( BookInstruction )Row.Source.Payload; if (Payload != null) { // Save the book here Payload.SaveInfo(); // Reload the BookDisplay as Entry might changed from SaveInfo Row.Source = new BookDisplay(Payload.Entry); } SpiderBook Item = await SpiderBook.CreateSAsync(Row.Source.Entry.ZoneId, Row.Source.Entry.ZItemId, Payload?.BookSpiderDef); Item.PropertyChanged += Item_PropertyChanged; XParameter Metadata = Item.PSettings.Parameter("METADATA") ?? new XParameter("METADATA"); Metadata.SetValue(new XKey("payload", Row.Source.Entry.Meta[AppKeys.GLOBAL_SSID])); Item.PSettings.SetParameter(Metadata); if (!Item.ProcessSuccess && Item.CanProcess) { await ItemProcessor.ProcessLocal(Item); } Item.PropertyChanged -= Item_PropertyChanged; (( BookDisplayPageExt )Extension).OpenItem(_Row); return(true); }
private static void ItemProcessingTask_Simple_Core() { var proc = new ItemProcessor(); var task = new ItemProcessingTask(proc); Assert.AreEqual(2, task.Priority); Assert.IsFalse(task.IsRunnable); task.RecalculatePriority(); Assert.IsFalse(task.IsRunnable); proc.Add(); Assert.IsTrue(task.IsRunnable); using var s = PhysicalScheduler.Create(); using var l = new LogicalScheduler(s); l.Schedule(task); proc.Events[0].WaitOne(); proc.Add(); l.RecalculatePriority(); proc.Events[1].WaitOne(); }
private async void MessageBus_OnDelivery(Message Mesg) { // Handles secondary tile launch on App opened switch (Mesg.Content) { case AppKeys.SYS_2ND_TILE_LAUNCH: case AppKeys.SYS_FILE_LAUNCH: if (Navigating) { ActionBlocked(); return; } BookItem Book = null; if (Mesg.Payload is string) { Book = await ItemProcessor.GetBookFromTileCmd(( string )Mesg.Payload); } else if (ItemProcessor.RequestOpenXRBK(Mesg.Payload, out var ISF)) { Book = await _BgTaskContext.RunAsync(ItemProcessor.OpenXRBK, ISF); } if (Book != null) { NavigateTo(PageId.MONO_REDIRECTOR, () => new MonoRedirector(), P => (( MonoRedirector )P).InfoView(Book)); } break; } }
public async void OpenItem(object DataContext) { if (DataContext is GRRow <FTSResult> RsRow) { Chapter Ch = Shared.BooksDb.Chapters.Find(RsRow.Source.ChapterId); if (Ch == null) { StringResources stx = StringResources.Load("Message"); await Popups.ShowDialog(UIAliases.CreateDialog(string.Format(stx.Str("FTSNeedsRebuild")))); return; } Ch.Book = Shared.BooksDb.QueryBook(x => x.Id == Ch.BookId).FirstOrDefault(); // Chapter is hard-linked to Volume. So we can load it confidently await Shared.BooksDb.LoadCollectionAsync(Ch.Book, x => x.Volumes, x => x.Index); foreach (Volume V in Ch.Book.Volumes) { await Shared.BooksDb.LoadCollectionAsync(V, x => x.Chapters, x => x.Index); } BookItem BkItem = ItemProcessor.GetBookItem(Ch.Book); PageProcessor.NavigateToReader(BkItem, Ch); } }
public override async Task <IList <IEvent> > ProcessAction() { var id = GetValue <string>("Id"); var confirmed = GetValue <bool>("Confirmation"); var parentId = String.Empty; var menu = ItemProcessor.RetrieveItem(id); parentId = menu.ParentMenu == null ? String.Empty : menu.ParentMenu.Id; var isParentMenu = MenuService.IsParentMenu(id); if (isParentMenu && !confirmed) { var tmpData = new Dictionary <string, object>(InputData); tmpData.Add("Confirmation", true); return(new List <IEvent>() { new UserConfirmation("Menu has sub-menus.\nThey will be deleted as well?") { OnConfirmationUIAction = EventNumber.DeleteMenu, CancelButtonText = "Cancel", ConfirmationButtonText = "Ok", Data = tmpData } }); } ParentId = parentId; return(await base.ProcessAction()); }
public override async Task <IList <IEvent> > ProcessAction(int actionNumber) { ItemProcessor.InputData = InputData; if (actionNumber == 1) { return(new List <IEvent>() { new CancelInputDialog(), new ExecuteAction(ViewToShowAfterModify, ParametersToPassToViewAfterModify) }); } else if (actionNumber == 0) { var itemId = GetValue("Id"); var existingItem = ItemProcessor.RetrieveExistingItem(); if ((IsNew && existingItem != null) || (!IsNew && existingItem != null && existingItem.Id != itemId)) { return(new List <IEvent>() { new ShowMessage("{0} already exists", ItemNameForDisplay) }); } var validationError = await ValidateInputs(); if (validationError != null && validationError.Success == false) { return(new List <IEvent>() { new ShowMessage(validationError.Message) }); } var result = await ItemProcessor.SaveOrUpdate(itemId); if (result.Success == false) { return(new List <IEvent>() { new ShowMessage(result.Message) }); } var message = String.Format("{0} {1} successfully.", ItemNameForDisplay, IsNew ? "created" : "modified"); if (!String.IsNullOrWhiteSpace(result.Message)) { message = result.Message; } return(new List <IEvent>() { new ExecuteAction(ViewToShowAfterModify, ParametersToPassToViewAfterModify), new CancelInputDialog(), new ShowMessage(message), }); } return(null); }
public ProcessorTestContainer(Mock <IFileLoader> loaderMock, Mock <IUriMapper> urlMapperMock, Mock <IItemWriter> writerMock, ItemProcessor processor) { LoaderMock = loaderMock; UrlMapperMock = urlMapperMock; WriterMock = writerMock; Processor = processor; }
/// <summary> /// Process ListItem one by one /// </summary> /// <param name="listName">ListName</param> /// <param name="camlQuery">CamlQuery</param> /// <param name="itemProcessor">itemprocessor delegate</param> /// <param name="errorCallout">error delegate</param> public void ProcessListItem(string listName, CamlQuery camlQuery, ItemProcessor itemProcessor, ItemProcessorErrorCallout errorCallout) { List list = _context.Web.Lists.GetByTitle(listName); CamlQuery query = camlQuery; ListItemCollectionPosition position = null; query.ListItemCollectionPosition = position; while (true) { ListItemCollection listItems = list.GetItems(query); _context.Load(listItems, items => items.ListItemCollectionPosition); _context.ExecuteQuery(); for (int i = 0; i < listItems.Count; i++) { try { itemProcessor(listItems[i]); } catch (System.Exception ex) { if (errorCallout == null || errorCallout(listItems[i], ex)) { throw; } } } if (listItems.ListItemCollectionPosition == null) { return; } else { /*if query contains lookup column filter last batch returns null * by removing the lookup column in paginginfo query will return next records */ string pagingInfo = listItems.ListItemCollectionPosition.PagingInfo; string[] parameters = pagingInfo.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); List <string> requiredParameters = new List <string>(); foreach (string str in parameters) { if (str.Contains("Paged=") || str.Contains("p_ID=")) { requiredParameters.Add(str); } } pagingInfo = string.Join("&", requiredParameters.ToArray()); listItems.ListItemCollectionPosition.PagingInfo = pagingInfo; query.ListItemCollectionPosition = listItems.ListItemCollectionPosition; } } }
/// <summary> /// Compares the initial and desired sets of items, forwarding items to the appropriate /// callback and returning the aggregate set of results. /// </summary> /// <remarks> /// Items that appear in <paramref name="desired"/> but not in <paramref name="initial"/> /// are passed to <paramref name="addProcessor"/>. /// Items that appear in <paramref name="initial"/> but not in <paramref name="desired"/> /// are passed to <paramref name="dropProcessor"/>. /// Items that appear in both sets are passed to <paramref name="compareProcessor"/> for /// comparison. /// Results of all callbacks are aggregated and returned. /// </remarks> private static IEnumerable <RelationalModelChange> CompareSets <T>(IEnumerable <T> initial, IEnumerable <T> desired, ItemProcessor <T> addProcessor, ItemProcessor <T> dropProcessor, CompareItemProcessor <T> compareProcessor) where T : ElementInfo { var changes = new List <RelationalModelChange>(); // partition desired set into those items that are contained in the initial set (true) and // those that are not (false) var a = CollectionUtils.GroupBy(desired, x => CollectionUtils.Contains(initial, y => Equals(x, y))); // partition initial set into those items that are contained in the desired set (true) and // those that are not (false) var b = CollectionUtils.GroupBy(initial, x => CollectionUtils.Contains(desired, y => Equals(x, y))); // these items need to be added List <T> adds; if (a.TryGetValue(false, out adds)) { foreach (var add in adds) { changes.AddRange(addProcessor(add)); } } // these items need to be dropped List <T> drops; if (b.TryGetValue(false, out drops)) { foreach (var drop in drops) { changes.AddRange(dropProcessor(drop)); } } // these items exist in both sets, so they need to be compared one by one // these keys should either both exist, or both not exist var desiredCommon = a.ContainsKey(true) ? a[true] : new List <T>(); var initialCommon = b.ContainsKey(true) ? b[true] : new List <T>(); // sort these vectors by identity, so that they are aligned desiredCommon.Sort((x, y) => x.Identity.CompareTo(y.Identity)); initialCommon.Sort((x, y) => x.Identity.CompareTo(y.Identity)); // compare each of the common items for (var i = 0; i < initialCommon.Count; i++) { changes.AddRange(compareProcessor(initialCommon[i], desiredCommon[i])); } return(changes); }
/// <summary> /// Process item. /// </summary> /// <param name="item"></param> /// <returns></returns> /// <exception cref="System.Exception"></exception> protected TOut DoProcess(TIn item) { if (ItemProcessor == null) { object result = item; return((TOut)result); } object resultProcess = ItemProcessor.Process(item); return((TOut)resultProcess); }
private async void ExportXRBK(object DataContext) { if (TryGetBookItem(DataContext, out BookItem BkItem)) { IStorageFile ISF = await AppStorage.SaveFileAsync("GR Book ( XRBK )", new string[] { ".xrbk" }, BkItem.Title); if (ISF != null) { await ItemProcessor.WriteXRBK(BkItem, ISF); } } }
public static void Main(string[] args) { var itemProcessor = new ItemProcessor(GetDefaultItems()); System.Console.WriteLine("Updating item quality..."); itemProcessor.UpdateQuality(); System.Console.WriteLine("Displaying items..."); itemProcessor.ListItems(); System.Console.ReadKey(); }
public void Given_2_Processors_Process_Called_Once_For_Each_Processor() { var fakeProcessor1 = new Mock<IItemProcessor>(MockBehavior.Loose); var fakeProcessor2 = new Mock<IItemProcessor>(MockBehavior.Loose); var itemProcessor = new ItemProcessor(fakeProcessor1.Object, fakeProcessor2.Object); itemProcessor.Process(new Item()); fakeProcessor1.Verify(p => p.Process(It.IsAny<Item>()), Times.Once()); fakeProcessor2.Verify(p => p.Process(It.IsAny<Item>()), Times.Once()); }
public static async Task <ProcessingResult> ProcessAsync(Configuration configuration, CancellationToken token) { using var fileLoader = new FileLoader(token); var mapper = new UriMapper(configuration); var parser = new ItemParser(mapper, configuration.Mode); var writer = new ItemWriter(mapper); var processor = new ItemProcessor(fileLoader, parser, writer, configuration, token); await processor.RunAsync().ConfigureAwait(false); return(new ProcessingResult(fileLoader.FailedUris)); }
public void Given_2_Processors_Process_Called_Once_For_Each_Processor() { var fakeProcessor1 = new Mock <IItemProcessor>(MockBehavior.Loose); var fakeProcessor2 = new Mock <IItemProcessor>(MockBehavior.Loose); var itemProcessor = new ItemProcessor(fakeProcessor1.Object, fakeProcessor2.Object); itemProcessor.Process(new Item()); fakeProcessor1.Verify(p => p.Process(It.IsAny <Item>()), Times.Once()); fakeProcessor2.Verify(p => p.Process(It.IsAny <Item>()), Times.Once()); }
public void Success_HandlesNullItem() { // Setup var qualityFactory = new Mock <IQualityPipelineFactory>(); var shelfLifeFactory = new Mock <IShelfLifeAlgorithmFactory>(); var factory = new ItemProcessor(qualityFactory.Object, shelfLifeFactory.Object); // Execution var result = factory.Process(null); // Assert Assert.IsNull(result); }
private bool TryGetBookItem(object DataContext, out BookItem BkItem) { BkItem = null; if (DataContext is GRRow <BookDisplay> BkRow) { BkItem = ItemProcessor.GetBookItem(BkRow.Source.Entry); } else if (DataContext is BookItem) { BkItem = ( BookItem )DataContext; } return(BkItem != null); }
public async void Blow() { if (LB.CanProcess) { await ItemProcessor.ProcessLocal(LB); } if (LB.ProcessSuccess) { ControlFrame.Instance.NavigateTo( PageId.BOOK_INFO_VIEW , () => new BookInfoView(ItemProcessor.GetBookEx(LB.ZItemId)) ); } }
public async void SetHomePage(string Id, Func <Page> FPage, Action <Page> PageAct = null) { // Handles secondary tile launch when App closed if (LaunchArgs is string TileQStr && !string.IsNullOrEmpty(TileQStr)) { Id = PageId.BOOK_INFO_VIEW; BookItem Book = await ItemProcessor.GetBookFromTileCmd(TileQStr); if (Book != null) { FPage = () => new BookInfoView(Book); } LaunchArgs = null; }
public void ProcessItem_RawData_MarksItemAsProcessed() { string data = "my test data"; var rawItem = new FullItem() { File = new UTF8Encoding().GetBytes(data), FileName = "test.txt", Received = DateTime.Now.ToUniversalTime(), ResourceId = Guid.NewGuid() }; var processor = new ItemProcessor(); var finishedItem = processor.ProcessItem(rawItem); Assert.IsTrue(finishedItem.IsProcessed); }
static void Main(string[] args) { var jsonData = File.ReadAllText("Data.json"); var data = JsonSerializer.Deserialize <List <Item> >(jsonData); var itemProcessor = new ItemProcessor(data); itemProcessor.ProcessItems(); foreach (var item in data) { System.Console.WriteLine($"{item.Name} {item.SellIn} {item.Quality}"); } System.Console.ReadKey(); }
public void ProcessItem_LowerCaseData_IsUpperCased() { string data = "my test data"; var rawItem = new FullItem() { File = new UTF8Encoding().GetBytes(data), FileName = "test.txt", Received = DateTime.Now.ToUniversalTime(), ResourceId = Guid.NewGuid() }; var processor = new ItemProcessor(); var finishedItem = processor.ProcessItem(rawItem); string result = new UTF8Encoding().GetString(finishedItem.File); Assert.AreEqual(data.ToUpper(), result); }
public override async Task <InitializeResult> Initialize(string data) { var json = JsonHelper.Parse(data); if (IsNew) { DataItem = Activator.CreateInstance <TBaseClass>(); } else { var id = json.GetValue("Id"); DataItem = ItemProcessor.RetrieveItem(id); } return(new InitializeResult(true)); }
public async void ProcessItem(IGRRow DataContext) { if (DataContext is GRRow <IBookProcess> Row) { SpiderBook BkProc = ( SpiderBook )Row.Source; if (!BkProc.Processing) { await ItemProcessor.ProcessLocal(BkProc); if (BkProc.GetBook().Packed == true) { new VolumeLoader((x) => { }).Load(BkProc.GetBook()); } } } }
private async void SHUploadComplete(string Id, string AccessToken) { await ControlFrame.Instance.CloseSubView(); HubScriptItem HSI = await PageProcessor.GetScriptFromHub(Id, AccessToken); if (ThisBook.ZItemId != Id) { ThisBook.Update(await ItemProcessor.GetBookFromId(Id)); } if (HSI != null) { OpenHSComment(HSI); } }
private async void Edit_Click(object sender, RoutedEventArgs e) { object DataContext = (( FrameworkElement )sender).DataContext; if (DataContext is GRRow <BookDisplay> BkRow) { BookItem BkItem = ItemProcessor.GetBookItem(BkRow.Source.Entry); SpiderBook SBk = await SpiderBook.CreateSAsync(BkItem.ZoneId, BkItem.ZItemId, null); if (SBk.CanProcess) { ControlFrame.Instance.NavigateTo(PageId.PROC_PANEL, () => new ProcPanelWrapper(SBk.MetaLocation)); } } }
public object Convert(object value, Type targetType, object parameter, string language) { if (value is BookDisplay BkDisplay) { BookItem BItem = ItemProcessor.GetBookItem(BkDisplay.Entry); if (!BItem.CoverExist) { BookLoader Loader = new BookLoader(); Loader.LoadCover(BItem, true); } return(BItem); } return(null); }
/// <summary> /// Process ListItem one by one /// </summary> /// <param name="listName">ListName</param> /// <param name="camlQuery">CamlQuery</param> /// <param name="itemProcessor">itemprocessor delegate</param> /// <param name="errorCallout">error delegate</param> public void ProcessListItem(string listName, CamlQuery camlQuery, ItemProcessor itemProcessor,ref List<PeoplePickerListOutput> lstPeoplepickeroutput, ItemProcessorErrorCallout errorCallout) { List list = _context.Web.Lists.GetByTitle(listName); CamlQuery query = camlQuery; //EventReceiverDefinitionCollection erCollection = list.EventReceivers; //foreach(EventReceiverDefinition erDefinition in erCollection) //{ // erDefinition. //} ListItemCollectionPosition position = null; query.ListItemCollectionPosition = position; while (true) { ListItemCollection listItems = list.GetItems(query); _context.Load(listItems, items => items.ListItemCollectionPosition); _context.ExecuteQuery(); for (int i = 0; i < listItems.Count; i++) { try { itemProcessor(listItems[i], _context, ref lstPeoplepickeroutput); } catch (System.Exception ex) { if (errorCallout == null || errorCallout(listItems[i], ex)) { throw; } } } if (listItems.ListItemCollectionPosition == null) { return; } else { /*if query contains lookup column filter last batch returns null by removing the lookup column in paginginfo query will return next records */ string pagingInfo = listItems.ListItemCollectionPosition.PagingInfo; string[] parameters = pagingInfo.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); List<string> requiredParameters = new List<string>(); foreach (string str in parameters) { if (str.Contains("Paged=") || str.Contains("p_ID=")) requiredParameters.Add(str); } pagingInfo = string.Join("&", requiredParameters.ToArray()); listItems.ListItemCollectionPosition.PagingInfo = pagingInfo; query.ListItemCollectionPosition = listItems.ListItemCollectionPosition; } } }