/// <summary>
        /// Respond to the triggering of the X button (and related key).
        /// </summary>
        protected override void ButtonXPressed(ContentEntry <Gear> entry)
        {
            // check the parameter
            if ((entry == null) || (entry.Content == null))
            {
                return;
            }

            // check whether the gear could be dropped
            if (!entry.Content.IsDroppable)
            {
                return;
            }

            // add a message box confirming the drop
            MessageBoxScreen dropEquipmentConfirmationScreen =
                new MessageBoxScreen("Are you sure you want to drop the " +
                                     entry.Content.Name + "?");

            dropEquipmentConfirmationScreen.Accepted +=
                new EventHandler <EventArgs>(delegate(object sender, EventArgs args)
            {
                Session.Party.RemoveFromInventory(entry.Content, 1);
            });
            ScreenManager.AddScreen(dropEquipmentConfirmationScreen);
        }
示例#2
0
        /// <summary>
        /// Add the given gear, in the given quantity, to the party's inventory.
        /// </summary>
        public void AddToInventory(Gear gear, int count)
        {
            // check the parameters
            if ((gear == null) || (count <= 0))
            {
                return;
            }

            // search for an existing entry
            ContentEntry <Gear> existingEntry = inventory.Find(
                delegate(ContentEntry <Gear> entry)
            {
                return(entry.Content == gear);
            });

            // increment the existing entry, if any
            if (existingEntry != null)
            {
                existingEntry.Count += count;
                return;
            }

            // no existing entry - create a new entry
            ContentEntry <Gear> newEntry = new ContentEntry <Gear>();

            newEntry.Content     = gear;
            newEntry.Count       = count;
            newEntry.ContentName = gear.AssetName;
            if (newEntry.ContentName.StartsWith(@"Gear\"))
            {
                newEntry.ContentName = newEntry.ContentName.Substring(5);
            }
            inventory.Add(newEntry);
        }
示例#3
0
    private void Start()
    {
        DialogueDBAdmin.DeleteDatabase("F****r.db");
        DialogueDBAdmin.CreateUniDialogueDB("F****r.db");
        //SQLiteConnection _connection = new SQLiteConnection("Assets/StreamingAssets/F****r.db", SQLiteOpenFlags.ReadWrite);
        DialogueDBConnection _connection = new DialogueDBConnection("F****r.db", SQLiteOpenFlags.ReadWrite);
        DialogueDBManager    _dbManager  = new DialogueDBManager(_connection);

        ConversationEntry con1 = new ConversationEntry("asd1", -1);
        ConversationEntry con2 = new ConversationEntry("asd2", -1);
        ConversationEntry con3 = new ConversationEntry("asd3", -1);
        ConversationEntry con4 = new ConversationEntry("asd4", -1);
        ConversationEntry con5 = new ConversationEntry("asd5", -1);

        ContentEntry coe1 = new ContentEntry("fff1", "ccc1", -1);
        ContentEntry coe2 = new ContentEntry("fff2", "ccc2", -1);
        ContentEntry coe3 = new ContentEntry("fff3", "ccc3", -1);
        ContentEntry coe4 = new ContentEntry("fff4", "ccc4", -1);
        ContentEntry coe5 = new ContentEntry("fff5", "ccc5", -1);

        ExecutionEntry exe1 = new ExecutionEntry("eee1", -1);
        ExecutionEntry exe2 = new ExecutionEntry("eee2", -1);
        ExecutionEntry exe3 = new ExecutionEntry("eee3", -1);
        ExecutionEntry exe4 = new ExecutionEntry("eee4", -1);
        ExecutionEntry exe5 = new ExecutionEntry("eee5", -1);

        ConditionEntry cod1 = new ConditionEntry("ddd1", -1, -1);
        ConditionEntry cod2 = new ConditionEntry("ddd2", -1, -1);
        ConditionEntry cod3 = new ConditionEntry("ddd3", -1, -1);
        ConditionEntry cod4 = new ConditionEntry("ddd4", -1, -1);
        ConditionEntry cod5 = new ConditionEntry("ddd5", -1, -1);

        _dbManager.InsertEntry(con1);
        _dbManager.InsertEntry(con2);
        _dbManager.InsertEntry(con3);
        _dbManager.InsertEntry(con4);
        _dbManager.InsertEntry(con5);
        _dbManager.InsertEntry(coe1);
        _dbManager.InsertEntry(coe2);
        _dbManager.InsertEntry(coe3);
        _dbManager.InsertEntry(coe4);
        _dbManager.InsertEntry(coe5);
        _dbManager.InsertEntry(exe1);
        _dbManager.InsertEntry(exe2);
        _dbManager.InsertEntry(exe3);
        _dbManager.InsertEntry(exe4);
        _dbManager.InsertEntry(exe5);
        _dbManager.InsertEntry(cod1);
        _dbManager.InsertEntry(cod2);
        _dbManager.InsertEntry(cod3);
        _dbManager.InsertEntry(cod4);
        _dbManager.InsertEntry(cod5);

        List <ExecutionEntry> list = _connection.Query <ExecutionEntry>("SELECT *, MAX(ID) FROM ExecutionEntry;");

        foreach (ExecutionEntry ee in list)
        {
            Debug.Log(ee.ExecutionCode);
        }
    }
 public bool Create(CategoryViewModel vm, Category e)
 {
     using (var DbTransaction = _unitOfWork.BeginTransaction())
     {
         try
         {
             var contentDefinition = new ContentDefinition
             {
                 Name = Contanst.TableName.Category
             };
             e.ContentDefinition = contentDefinition;
             foreach (var item in vm.LanguageVms)
             {
                 var contentEntry = new ContentEntry
                 {
                     LanguageId          = item.LanguageId,
                     Token               = item.Token,
                     Value               = item.Value ?? string.Empty,
                     ContentDefinitionId = contentDefinition.ContentDefinitionId
                 };
                 e.ContentDefinition.ContentEntries.Add(contentEntry);
             }
             _categoryRepository.Insert(e);
             _unitOfWork.Complete();
             DbTransaction.Commit();
             return(true);
         }
         catch (Exception exception)
         {
             Console.WriteLine(exception);
             return(false);
         }
     }
 }
        private async void AddTask()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ContentEntry.Text))
                {
                    await App.Current.MainPage.DisplayAlert("할 일 추가", "할 일을 입력해주세요.", "확인");

                    ContentEntry.Focus();
                    return;
                }

                if (string.IsNullOrWhiteSpace(CurrentIconPath))
                {
                    CurrentIconPath = "Resources/task.png";
                }

                OnClosed?.Invoke(this, new AddTaskResult {
                    Task = new TaskModel {
                        IconPath = CurrentIconPath, Content = ContentEntry.Text.Trim(), Status = false
                    }
                });
                await PopupNavigation.Instance.RemovePageAsync(this);
            }
            catch (Exception ex)
            {
                App.DisplayEx(ex);
            }
        }
示例#6
0
        private static async Task prepareImage(CommonDbContext dbContext, ContentEntry chapterContent, Stream imgStream, string imgName)
        {
            var mediaImg = chapterContent.MediaResource?.FirstOrDefault(x => x.Name == imgName);

            if (mediaImg == null)
            {
                if (chapterContent.MediaResource == null)
                {
                    chapterContent.MediaResource = new List <FileEntry>();
                }
                //图片判重
                if (chapterContent.MediaResource.Any(x => x.Name == imgName))
                {
                    return;
                }
                imgStream.Position = 0;
                QiniuTool.UploadImage(imgStream, imgName).Wait();
                chapterContent.MediaResource.Add(new FileEntry
                {
                    ActualPath = "https://mioto.milbit.com/" + imgName,
                    Name       = imgName,
                    CreateTime = DateTime.Now,
                    Id         = Guid.NewGuid()
                });
                await dbContext.SaveChangesAsync();
            }
        }
示例#7
0
 public async Task <ApiMessage> CreateContent(ContentEntry content)
 {
     return(await ApiMessage.Wrap(async() =>
     {
         content.CreateTime = DateTime.Now;
         await ContentAccessor.AddOrUpdate(content);
     }));
 }
示例#8
0
        public async Task <IActionResult> AddOrUpdate(ContentEntry contentEntry)
        {
            ViewData["DataType"]     = typeof(ContentEntry);
            ViewData["DataCategory"] = await contentBusiness.GetCategoryFormByP(KnowledgeBusiness.PublishKey);

            await contentBusiness.CreateContentWithTag(contentEntry, KnowledgeBusiness.PublishKey);

            return(RedirectToAction("Index"));
        }
示例#9
0
        public async Task <IActionResult> CreateKLArticle(ContentEntry contentEntry)
        {
            var apiMsg = await ApiMessage.Wrap(async() =>
            {
                await knowledgeBusiness.CreateKnowledgeArticle(contentEntry);
            });

            return(Json(apiMsg));
        }
示例#10
0
        public static ContentEntry ToContentEntry(this object source, string sourceIdentifierPath = null)
        {
            var res = new ContentEntry();

            var dynamicModel = source as dynamic;

            res.Id       = dynamicModel.SelectToken(sourceIdentifierPath ?? "place.@xml:id").ToString();
            res.Contents = dynamicModel;
            return(res);
        }
示例#11
0
        /// <summary>
        /// Draw the description of the selected item.
        /// </summary>
        protected override void DrawSelectedDescription(ContentEntry <Gear> entry)
        {
            // check the parameter
            if (entry == null)
            {
                throw new ArgumentNullException("entry");
            }
            Gear gear = entry.Content as Gear;

            if (gear == null)
            {
                return;
            }

            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
            Vector2     position    = descriptionTextPosition;

            // draw the description
            // -- it's up to the content owner to fit the description
            string text = gear.Description;

            if (!String.IsNullOrEmpty(text))
            {
                spriteBatch.DrawString(Fonts.DescriptionFont, text, position,
                                       Fonts.DescriptionColor);


                position.X += Fonts.DescriptionFont.MeasureString(text).X + 5;
            }

            // draw additional information for equipment
            Equipment equipment = entry.Content as Equipment;

            if (equipment != null)
            {
                // draw the modifiers
                text = equipment.OwnerBuffStatistics.GetModifierString();
                if (!String.IsNullOrEmpty(text))
                {
                    spriteBatch.DrawString(Fonts.DescriptionFont, text, position,
                                           Fonts.DescriptionColor);
                    position.X += Fonts.DescriptionFont.MeasureString(text).X + 5;
                }
            }

            // draw the restrictions
            text = entry.Content.GetRestrictionsText();
            if (!String.IsNullOrEmpty(text))
            {
                spriteBatch.DrawString(Fonts.DescriptionFont, text, position,
                                       Fonts.DescriptionColor);
                position.X += Fonts.DescriptionFont.MeasureString(text).X + 5;
            }
        }
示例#12
0
        /// <summary>
        /// 处理资讯详情
        /// </summary>
        /// <param name="spiderLog"></param>
        /// <param name="webElement"></param>
        /// <returns></returns>
        static async Task SetNewsDetailTask(SpiderLog spiderLog, IWebDriver driver)
        {
            IWebElement webElement = driver.FindElement(By.TagName("html"));
            var         title      = webElement.FindElement(By.CssSelector(".content .article-title")).GetAttribute("innerText");
            var         time       = webElement.FindElement(By.CssSelector(".content .article-info .time")).GetAttribute("innerText");
            var         content    = webElement.FindElement(By.CssSelector(".content .article-content")).GetAttribute("innerHTML");
            var         img        = webElement.FindElement(By.CssSelector(".content .article-content")).FindElement(By.TagName("img"))?.GetAttribute("src");
            var         dbCtx      = GetDbContext();
            var         dateTime   = DateTime.Parse(time);

            Console.WriteLine("process : :" + title);
            var cateNews = GetTopCategory(dbCtx, "资讯");

            var hasContent = dbCtx.ContentEntry.Any(x => x.Title == title);

            if (!hasContent)
            {
                var contentEntry = new ContentEntry
                {
                    Title      = title,
                    CreateTime = dateTime,
                    Id         = Guid.NewGuid(),
                    Content    = content,
                    Category   = cateNews,
                    Tags       = new List <Tags>
                    {
                        new Tags
                        {
                            Id   = Guid.NewGuid(),
                            Name = "资讯"
                        },
                        new Tags
                        {
                            Id   = Guid.NewGuid(),
                            Name = "梦域动漫"
                        }
                    }
                };
                if (img != null)
                {
                    contentEntry.MediaResource = new List <FileEntry> {
                        new FileEntry {
                            ActualPath = img,
                            CreateTime = dateTime,
                            Id         = Guid.NewGuid(),
                            Name       = "tmppath"
                        }
                    };
                }
                await dbCtx.ContentEntry.AddAsync(contentEntry);

                await dbCtx.SaveChangesAsync();
            }
        }
        public async Task <IActionResult> AddOrUpdate(ContentEntry contentEtnry)
        {
            var apiMsg = await ApiMessage.Wrap(async() =>
            {
                ViewData["DataType"]  = typeof(FileEntry);
                var _contentEntry     = await contentBusiness.CreateContent(contentEtnry);
                ViewData["DataModel"] = _contentEntry;
            });

            return(Json(apiMsg));
        }
示例#14
0
        private static void processChapter(string categoryTitle, TaskSpider contentTaskSpider)
        {
            TaskExutor exuctor    = TaskExutor.Instance;
            var        taskSpider = contentTaskSpider;

            Task.Run(() => exuctor.SetTask(taskSpider, (contentWebElement, state) =>
            {
                var chapterList  = contentWebElement.FindElement(By.TagName("body")).FindElements(By.CssSelector(".chapterList .item"));
                var contentIndex = 0;
                //章节列表
                foreach (var chapterItem in chapterList)
                {
                    var chapterTitle    = chapterItem.GetAttribute("innerText");
                    var chatpterItemUrl = chapterItem.FindElement(By.TagName("a")).GetAttribute("href");
                    var curState        = new Dictionary <string, string>();
                    foreach (var item in state)
                    {
                        curState.Add(item.Key, item.Value);
                    }
                    curState.Add("chapterTitle", chapterTitle);
                    //保存content entry
                    //判断是否存在content
                    ContentEntry contentEntry;
                    var chapterDbContext  = GetDbContext();
                    var hasCurrentContent = chapterDbContext.ContentEntry.AnyAsync(x => x.Category.Name == categoryTitle && x.Title == chapterTitle).Result;
                    if (!hasCurrentContent)
                    {
                        var currentCategory = chapterDbContext.Categories.FirstOrDefaultAsync(x => x.Name == categoryTitle).Result;
                        contentEntry        = new ContentEntry
                        {
                            Id         = Guid.NewGuid(),
                            Category   = currentCategory,
                            Title      = chapterTitle,
                            CreateTime = DateTime.Now,
                            Order      = contentIndex
                        };
                        chapterDbContext.ContentEntry.Add(contentEntry);
                        chapterDbContext.SaveChanges();
                    }
                    else
                    {
                        contentEntry = chapterDbContext.ContentEntry.FirstOrDefaultAsync(x => x.Title == chapterTitle && x.Category.Name == categoryTitle).Result;
                    }

                    //Console.WriteLine(chapterTitle);
                    var chapterTaskSpider = new TaskSpider(chatpterItemUrl, curState);
                    chapterTaskSpider.SetCookie(_cookie);
                    var chapterExcutor = TaskExutor.Instance;
                    processContent(categoryTitle, chapterTitle, contentIndex, chatpterItemUrl, contentEntry.Id, chapterTaskSpider);
                    contentIndex++;
                }
            }));
        }
            public EntryWrapper(ContentEntry entry, bool isNew)
            {
                Entry        = entry;
                InstallEntry = true;
                IsNew        = isNew;

                if (isNew)
                {
                    return;
                }
                _updateOptionsList = entry.Type.GetUpdateOptions().ToArray();
                SelectedOption     = _updateOptionsList[0];
            }
        public AddTaskPopup(string currentTaskList)
        {
            InitializeComponent();

            CurrentTaskList = currentTaskList;

            if (App.UseDarkMode)
            {
                MainFrame.BackgroundColor = Color.FromHex("333333");
            }

            ContentEntry.Focus();
        }
示例#17
0
        /// <summary>
        /// Draw the gear's content entry at the given position in the list.
        /// </summary>
        /// <param name="contentEntry">The content entry to draw.</param>
        /// <param name="position">The position to draw the entry at.</param>
        /// <param name="isSelected">If true, this item is selected.</param>
        protected override void DrawEntry(ContentEntry <Gear> entry, Vector2 position,
                                          bool isSelected)
        {
            // check the parameter
            if (entry == null)
            {
                throw new ArgumentNullException("entry");
            }
            Gear gear = entry.Content as Gear;

            if (gear == null)
            {
                return;
            }

            SpriteBatch spriteBatch  = ScreenManager.SpriteBatch;
            Vector2     drawPosition = position;

            // draw the icon
            spriteBatch.Draw(gear.IconTexture, drawPosition + iconOffset, null, Color.White, 0f,
                             Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);

            // draw the name
            Color color = isSelected ? Fonts.HighlightColor : Fonts.DisplayColor;

            drawPosition.Y += listLineSpacing / 4;
            drawPosition.X += nameColumnInterval;
            spriteBatch.DrawString(Fonts.GearInfoFont, gear.Name, drawPosition, color);

            // draw the power
            drawPosition.X += powerColumnInterval;
            string  powerText     = gear.GetPowerText();
            Vector2 powerTextSize = Fonts.GearInfoFont.MeasureString(powerText);
            Vector2 powerPosition = drawPosition;

            powerPosition.Y -= (float)Math.Ceiling((powerTextSize.Y - 30f) * ScaledVector2.ScaleFactor / 2);
            spriteBatch.DrawString(Fonts.GearInfoFont, powerText,
                                   powerPosition, color);

            // draw the quantity
            drawPosition.X += quantityColumnInterval;
            spriteBatch.DrawString(Fonts.GearInfoFont, entry.Count.ToString(),
                                   drawPosition, color);

            // turn on or off the select and drop buttons
            if (isSelected)
            {
                selectButtonText = "Select";
                xButtonText      = entry.Content.IsDroppable ? "Drop" : String.Empty;
            }
        }
        public void Documentation_GetDocumentationFor_ContentEntry()
        {
            documentation.Load();
            TableOfContents toc = documentation.GetTableOfContents();

            // find a key to search for
            ContentEntry toFind = toc.GetEntryFor("T:DocumentationTest.AllOutputTypesClass");

            // test find
            string found = documentation.GetDocumentationFor(toFind);

            Assert.IsNotNull(found);
            Assert.AreEqual(toFind.Key.ToString(), this.getKey(found));
        }
示例#19
0
        private void OutputParents()
        {
            Log("\nOutput parents using GetParents method\n");
            List <ContentEntry> parents;
            TableOfContents     contents = this.docs.GetTableOfContents();
            ContentEntry        entry    = contents.GetEntryFor("M:TheBoxSoftware.Reflection.AssemblyDef.#ctor");

            parents = entry.GetParents();

            foreach (ContentEntry current in parents)
            {
                Log(string.Format(" {0}\n", current.DisplayName));
            }
        }
示例#20
0
 public async Task <string> GetPrevContentId(ContentEntry cEntry)
 {
     if (cEntry.Order == 0)
     {
         return(null);
     }
     else
     {
         return(await ApiMessage.WrapData(async() =>
         {
             var prevEntry = await ContentAccessor.OneAsync <ContentEntry>(x => x.Order == cEntry.Order - 1 && x.Category == cEntry.Category);
             return prevEntry.Id.ToString();
         }));
     }
 }
示例#21
0
        /// <summary>
        /// Respond to the triggering of the Select action.
        /// </summary>
        protected override void SelectTriggered(ContentEntry <Gear> entry)
        {
            // if the quantity is zero, don't bother
            if (selectedQuantity <= 0)
            {
                return;
            }

            // check to see if gold is selected
            if (IsGoldSelected)
            {
                // play the "pick up gold" cue
                AudioManager.PlayCue("Money");
                // add the gold to the party
                Session.Party.PartyGold += selectedQuantity;
                chestEntry.Content.Gold -= selectedQuantity;
                if (chestEntry.Content.Gold > 0)
                {
                    selectedQuantity =
                        Math.Min(selectedQuantity, chestEntry.Content.Gold);
                }
                else
                {
                    ResetSelectedQuantity();
                }
            }
            else
            {
                // remove the selected quantity of gear from the chest
                int quantity = selectedQuantity;
                if ((entry.Content != null) && (quantity > 0))
                {
                    Session.Party.AddToInventory(entry.Content, quantity);
                    entry.Count -= quantity;
                }
                if (entry.Count > 0)
                {
                    selectedQuantity = Math.Min(entry.Count, selectedQuantity);
                }
                else
                {
                    // if the entry is now empty, remove it from the chest
                    chestEntry.Content.Entries.RemoveAt(SelectedGearIndex);
                    ResetSelectedQuantity();
                }
            }
        }
示例#22
0
        //public Task CreateContentWithTag(ContentEntry contentEntry, string v1, string v2)
        //{
        //    throw new NotImplementedException();
        //}
        public async Task <ApiMessage> CreateContentWithTag(ContentEntry content, string tagName)
        {
            return(await ApiMessage.Wrap(async() =>
            {
                //var categoryEntity = await CategoryAccessor.OneAsync<Categories>(x => x.Name == tagName);
                //if (categoryEntity == null)
                //{
                //    categoryEntity = new Categories
                //    {
                //        Name = tagName,
                //        CreateTime = DateTime.Now,
                //        Id = Guid.NewGuid()
                //    };
                //    await CategoryAccessor.Add(categoryEntity);
                //}

                var contentEntry = await ContentAccessor.OneAsync <ContentEntry>(x => x.Id == content.Id);
                if (contentEntry == null)
                {
                    contentEntry = new ContentEntry
                    {
                        Id = Guid.NewGuid(),
                        CategoryId = content.CategoryId,
                        Content = content.Content,
                        CreateTime = DateTime.Now,
                        IsFaq = content.IsFaq,
                        IsTop = content.IsTop,
                        Title = content.Title,
                        Tags = new List <Tags> {
                            new Tags {
                                Name = tagName
                            }
                        }
                    };
                    await ContentAccessor.Add(contentEntry);
                }
                else
                {
                    contentEntry.CategoryId = content.CategoryId;
                    contentEntry.Content = content.Content;
                    contentEntry.IsFaq = content.IsFaq;
                    contentEntry.IsTop = content.IsTop;
                    contentEntry.Title = content.Title;
                    await ContentAccessor.Update(contentEntry);
                }
            }));
        }
示例#23
0
        public async Task <string> GetNextContentId(ContentEntry cEntry)
        {
            var contentCountOfCategory = cEntry.Category.ContentList.Count;

            if (cEntry.Order + 1 == contentCountOfCategory)
            {
                return(null);
            }
            else
            {
                return(await ApiMessage.WrapData(async() =>
                {
                    var nextEntry = await ContentAccessor.OneAsync <ContentEntry>(x => x.Order == cEntry.Order + 1 && x.Category == cEntry.Category);
                    return nextEntry.Id.ToString();
                }));
            }
        }
示例#24
0
        /// <summary>
        /// 当前页为detail
        /// </summary>
        /// <param name="spiderLog"></param>
        /// <param name="webElement"></param>
        /// <returns></returns>
        static async Task SetDetailTask(SpiderLog spiderLog, IWebDriver driver)
        {
            var         mainDbContext = GetDbContext();
            IWebElement webElement    = driver.FindElement(By.TagName("html"));
            var         imgList       = webElement.FindElements(By.CssSelector(".r_img img"));
            var         detailTitle   = webElement.FindElement(By.CssSelector(".fl.r_tab_l span")).GetAttribute("innerText");

            var category = await mainDbContext.Categories.FirstOrDefaultAsync(x => x.Name == spiderLog.ParentName);

            var exitedContent = await mainDbContext.ContentEntry.AnyAsync(x => x.Title == detailTitle && x.Category.Id == category.Id);

            if (!exitedContent)
            {
                var medieaResources = new List <FileEntry>();
                for (int imgIndex = 0; imgIndex < imgList.Count; imgIndex++)
                {
                    var imgItem = imgList[imgIndex];
                    var imgSrc  = imgItem.GetAttribute("src");
                    medieaResources.Add(new FileEntry
                    {
                        ActualPath = imgSrc,
                        CreateTime = DateTime.Now,
                        Id         = Guid.NewGuid(),
                        Name       = "tmpname",
                        Order      = imgIndex
                    });
                }

                var content = new ContentEntry
                {
                    Id            = Guid.NewGuid(),
                    CreateTime    = DateTime.Now,
                    Category      = category,
                    MediaResource = medieaResources,
                    Title         = detailTitle,
                    Order         = spiderLog.Order
                };

                await mainDbContext.AddAsync(content);

                await mainDbContext.SaveChangesAsync();
            }


            Console.WriteLine("Process : " + spiderLog.ParentName + " - " + detailTitle);
        }
示例#25
0
        private static void ProcessChapterPage(IWebElement webElement, Dictionary <string, string> state)
        {
            var dbCtx        = GetDbContext();
            var cateTitle    = state["cateTitle"];
            var categoryData = dbCtx.Categories.FirstOrDefault(x => x.Name == cateTitle);

            var chapterList  = webElement.FindElement(By.TagName("body")).FindElements(By.CssSelector(".chapterList .item"));
            var contentIndex = 0;

            foreach (var chapterItem in chapterList)
            {
                var chapterTitle    = chapterItem.GetAttribute("innerText").Trim();
                var chatpterItemUrl = chapterItem.FindElement(By.TagName("a")).GetAttribute("href");
                var curState        = ExtensionState(state);
                curState.Add("chapterTitle", chapterTitle);
                var currentContent = dbCtx.ContentEntry.FirstOrDefaultAsync(x => x.Category.Name == cateTitle && x.Title == chapterTitle).Result;
                if (currentContent == null)
                {
                    var currentCategory = dbCtx.Categories.FirstOrDefaultAsync(x => x.Name == cateTitle).Result;
                    var contentEntry    = new ContentEntry
                    {
                        Id         = Guid.NewGuid(),
                        Category   = currentCategory,
                        Title      = chapterTitle,
                        CreateTime = DateTime.Now,
                        Order      = contentIndex,
                        Content    = "<url:" + chatpterItemUrl + ">"
                    };
                    dbCtx.ContentEntry.Add(contentEntry);
                }
                else
                {
                    currentContent.Content = "<url:" + chatpterItemUrl + ">";
                }
                dbCtx.SaveChanges();
                var chapterDetailSpiderTask = new TaskSpider(chatpterItemUrl, curState);
                if (currentContent.MediaResource == null || currentContent.MediaResource.Count() == 0)
                {
                    Task.Run(() => TaskExutor.Instance.SetTask(chapterDetailSpiderTask, ProcessChapterDetailPage)).Wait();
                }
                contentIndex++;
            }
        }
        /// <summary>
        /// Respond to the triggering of the Select action (and related key).
        /// </summary>
        protected override void SelectTriggered(ContentEntry <Gear> entry)
        {
            // check the parameter
            if ((entry == null) || (entry.Content == null))
            {
                return;
            }

            // if the event is valid, fire it and exit this screen
            if (GearSelected != null)
            {
                GearSelected(entry.Content);
                ExitScreen();
                return;
            }

            // otherwise, open the selection screen over this screen
            ScreenManager.AddScreen(new PlayerSelectionScreen(entry.Content));
        }
示例#27
0
        public async Task <ApiMessage> CreateContentWithCategory(ContentEntry content, string categoryName)
        {
            return(await ApiMessage.Wrap(async() =>
            {
                var categoryEntity = await CategoryAccessor.OneAsync <Categories>(x => x.Name == categoryName);
                if (categoryEntity == null)
                {
                    categoryEntity = new Categories
                    {
                        Name = categoryName,
                        CreateTime = DateTime.Now,
                        Id = Guid.NewGuid()
                    };
                    await CategoryAccessor.Add(categoryEntity);
                }

                var contentEntry = await ContentAccessor.OneAsync <ContentEntry>(x => x.Id == content.Id);
                if (contentEntry == null)
                {
                    contentEntry = new ContentEntry
                    {
                        Id = Guid.NewGuid(),
                        Category = categoryEntity,
                        Content = content.Content,
                        CreateTime = DateTime.Now,
                        IsFaq = content.IsFaq,
                        IsTop = content.IsTop,
                        Title = content.Title
                    };
                    await ContentAccessor.Add(contentEntry);
                }
                else
                {
                    contentEntry.Category = categoryEntity;
                    contentEntry.Content = content.Content;
                    contentEntry.IsFaq = content.IsFaq;
                    contentEntry.IsTop = content.IsTop;
                    contentEntry.Title = content.Title;
                    await ContentAccessor.Update(contentEntry);
                }
            }));
        }
示例#28
0
        /// <summary>
        /// Adds a new object and its serializer to the contents of
        /// this SmartCard.
        /// </summary>
        /// <param name="theObject">The object to the contents.</param>
        /// <param name="theSerializer">The serializer for the object.</param>
        /// <returns>The index of the object in the contents.</returns>
        /// <exception cref="InvalidSmartCardPropertyException">
        /// If either theObject or theSerializer is null.
        /// </exception>
        public int Add(object theObject, ISerializer theSerializer)
        {
            ContentEntry newEntry;

            // Check for invalid arguments
            if ((theObject == null) || (theSerializer == null))
            {
                throw new InvalidSmartCardPropertyException("Contents");
            }

            // Create the new entry.
            newEntry            = new ContentEntry();
            newEntry.Content    = theObject;
            newEntry.Serializer = theSerializer;

            _contents.Add(newEntry);

            // Return the index of the addition.
            return(_contents.Count - 1);
        }
示例#29
0
        /// <summary>
        /// Respond to the triggering of the Select action.
        /// </summary>
        protected override void SelectTriggered(ContentEntry <Gear> entry)
        {
            // check the parameter
            if ((entry == null) || (entry.Content == null))
            {
                return;
            }

            // make sure the selected quantity is valid
            selectedQuantity = Math.Min(selectedQuantity, entry.Count);

            // add the gold to the party's inventory
            Session.Party.PartyGold += selectedQuantity *
                                       (int)Math.Ceiling(entry.Content.GoldValue * store.SellMultiplier);

            // remove the items from the party's inventory
            Session.Party.RemoveFromInventory(entry.Content, selectedQuantity);

            // reset the quantities - either gold has gone down or the total was bad
            ResetQuantities();
        }
示例#30
0
        /// <summary>
        /// Respond to the triggering of the Y button (and related key).
        /// </summary>
        protected override void ButtonYPressed(ContentEntry <Gear> entry)
        {
            // add the entire amount of gold
            if (chestEntry.Content.Gold > 0)
            {
                AudioManager.PlayCue("Money");
                Session.Party.PartyGold += chestEntry.Content.Gold;
                chestEntry.Content.Gold  = 0;
            }
            // add all items at full quantity
            // -- there is no limit to the party's inventory
            ReadOnlyCollection <ContentEntry <Gear> > entries = GetDataList();

            foreach (ContentEntry <Gear> gearEntry in entries)
            {
                Session.Party.AddToInventory(gearEntry.Content, gearEntry.Count);
            }
            // clear the entries, as they're all gone now
            chestEntry.Content.Entries.Clear();
            selectedQuantity = 0;
        }
示例#31
0
        public string Backup(string[] sources)
        {
            BackupStatistics bs = new BackupStatistics(XervBackupOperationMode.Backup);
            SetupCommonOptions(bs);

            BackendWrapper backend = null;
            VerificationFile verification = null;

            if (m_options.DontReadManifests)
                throw new Exception(Strings.Interface.ManifestsMustBeReadOnBackups);
            if (m_options.SkipFileHashChecks)
                throw new Exception(Strings.Interface.CannotSkipHashChecksOnBackup);

            if (sources == null || sources.Length == 0)
                throw new Exception(Strings.Interface.NoSourceFoldersError);

            //Make sure they all have the same format and exist
            for (int i = 0; i < sources.Length; i++)
            {
                sources[i] = Utility.Utility.AppendDirSeparator(System.IO.Path.GetFullPath(sources[i]));

                if (!System.IO.Directory.Exists(sources[i]))
                    throw new System.IO.IOException(String.Format(Strings.Interface.SourceFolderIsMissingError, sources[i]));
            }

            //Sanity check for duplicate folders and multiple inclusions of the same folder
            for (int i = 0; i < sources.Length - 1; i++)
            {
                for (int j = i + 1; j < sources.Length; j++)
                    if (sources[i].Equals(sources[j], Utility.Utility.IsFSCaseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase))
                        throw new Exception(string.Format(Strings.Interface.SourceDirIsIncludedMultipleTimesError, sources[i]));
                    else if (sources[i].StartsWith(sources[j], Utility.Utility.IsFSCaseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase))
                        throw new Exception(string.Format(Strings.Interface.SourceDirsAreRelatedError, sources[i], sources[j]));
            }

            if (m_options.AsynchronousUpload)
            {
                m_asyncReserved = ASYNC_RESERVED;
                m_allowUploadProgress = false;
            }

            //Unused, but triggers errors in the encryption setup here
            Library.Interface.IEncryption encryptionModule = m_options.NoEncryption ? null : DynamicLoader.EncryptionLoader.GetModule(m_options.EncryptionModule, m_options.Passphrase, m_options.RawOptions);

            using (new Logging.Timer("Backup from " + string.Join(";", sources) + " to " + m_backend))
            {
                try
                {
                    if (OperationStarted != null)
                        OperationStarted(this, XervBackupOperation.Backup, bs.OperationMode, -1, -1, Strings.Interface.StatusLoadingFilelist, "");
                    OperationProgress(this, XervBackupOperation.Backup, bs.OperationMode, -1, -1, Strings.Interface.StatusLoadingFilelist, "");

                    CheckLiveControl();

                    bool full = m_options.Full;
                    if (full)
                        bs.SetTypeReason(string.Format(Strings.Interface.FullBecauseFlagWasSet, "full"));

                    backend = new BackendWrapper(bs, m_backend, m_options);
                    backend.ProgressEvent += new XervBackup.Library.Main.RSync.RSyncDir.ProgressEventDelegate(BackupTransfer_ProgressEvent);
                    backend.AsyncItemProcessedEvent += new EventHandler(backend_AsyncItemProcessedEvent);

                    m_progress = 0.0;

                    OperationProgress(this, XervBackupOperation.Backup, bs.OperationMode, (int)(m_progress * 100), -1, Strings.Interface.StatusReadingIncrementals, "");

                    CheckLiveControl();

                    List<ManifestEntry> backupsets;

                    if (full)
                    {
                        //This will create the target folder
                        backend.List(false);
                        backupsets = new List<ManifestEntry>();
                    }
                    else
                    {
                        //This will list all files on the backend and create the target folder
                        backupsets = backend.GetBackupSets();
                    }

                    if (backupsets.Count == 0)
                    {
                        if (!full)
                            bs.SetTypeReason(Strings.Interface.FullBecauseBackendIsEmpty);
                        full = true;
                    }
                    else
                    {
                        //A prioir backup exists, extract the compression and encryption modules used in the most recent entry
                        string compression = null;
                        string encryption = null;
                        for (int i = backupsets.Count - 1; compression == null && i >= 0; i--)
                        {
                            for (int j = backupsets[i].Incrementals.Count - 1; compression == null && j >= 0; j--)
                                for (int k = backupsets[i].Incrementals[j].Volumes.Count - 1; compression == null && k >= 0; k--)
                                {
                                    compression = backupsets[i].Incrementals[j].Volumes[k].Key.Compression;
                                    encryption = backupsets[i].Incrementals[j].Volumes[k].Key.EncryptionMode;

                                    if (compression != null)
                                        break;
                                }

                            for (int k = backupsets[i].Volumes.Count - 1; compression == null && k >= 0; k--)
                            {
                                compression = backupsets[i].Volumes[k].Key.Compression;
                                encryption = backupsets[i].Volumes[k].Key.EncryptionMode;

                                if (compression != null)
                                    break;
                            }
                        }

                        if (compression != null)
                        {
                            m_options.SetEncryptionModuleDefault(encryption);
                            m_options.SetCompressionModuleDefault(compression);
                        }
                    }

                    string fullCriteria1 = null;
                    string fullCriteria2 = null;
                    if (!full)
                    {
                        full = DateTime.Now > m_options.FullIfOlderThan(backupsets[backupsets.Count - 1].Time);
                        if (full)
                            bs.SetTypeReason(string.Format(Strings.Interface.FullBecauseLastFullIsFrom, backupsets[backupsets.Count - 1].Time, m_options.FullIfOlderThanValue));
                        else if (!string.IsNullOrEmpty(m_options.FullIfOlderThanValue))
                            fullCriteria1 = string.Format(Strings.Interface.IncrementalBecauseLastFullIsFrom, backupsets[backupsets.Count - 1].Time, m_options.FullIfOlderThanValue);
                    }

                    if (!full && m_options.FullIfMoreThanNIncrementals > 0)
                    {
                        full = backupsets[backupsets.Count - 1].Incrementals.Count >= m_options.FullIfMoreThanNIncrementals;
                        if (full)
                            bs.SetTypeReason(string.Format(Strings.Interface.FullBecauseThereAreNIncrementals, backupsets[backupsets.Count - 1].Incrementals.Count, m_options.FullIfMoreThanNIncrementals));
                        else
                            fullCriteria2 = string.Format(Strings.Interface.IncrementalBecauseThereAreNIncrementals, backupsets[backupsets.Count - 1].Incrementals.Count, m_options.FullIfMoreThanNIncrementals);

                    }
                    bs.Full = full;
                    if (!full)
                    {
                        if (fullCriteria1 == null && fullCriteria2 == null)
                            bs.SetTypeReason(Strings.Interface.IncrementalBecauseNoFlagsWereSet);
                        else if (fullCriteria2 == null)
                            bs.SetTypeReason(fullCriteria1);
                        else if (fullCriteria1 == null)
                            bs.SetTypeReason(fullCriteria2);
                        else
                            bs.SetTypeReason(fullCriteria1 + ". " + fullCriteria2);

                    }

                    List<string> controlfiles = new List<string>();
                    if (!string.IsNullOrEmpty(m_options.SignatureControlFiles))
                        controlfiles.AddRange(m_options.SignatureControlFiles.Split(System.IO.Path.PathSeparator));

                    int vol = 0;
                    long totalsize = 0;
                    Manifestfile manifest = new Manifestfile();

                    using (Utility.TempFolder tempfolder = new XervBackup.Library.Utility.TempFolder())
                    {
                        List<KeyValuePair<ManifestEntry, Library.Interface.ICompression>> patches = new List<KeyValuePair<ManifestEntry, XervBackup.Library.Interface.ICompression>>();
                        if (!full)
                        {
                            m_incrementalFraction = INCREMENAL_COST;
                            List<ManifestEntry> entries = new List<ManifestEntry>();
                            entries.Add(backupsets[backupsets.Count - 1]);
                            entries.AddRange(backupsets[backupsets.Count - 1].Incrementals);

                            //Check before we start the download
                            CheckLiveControl();

                            VerifyBackupChainWithFiles(backend, entries[entries.Count - 1]);
                            if (m_options.CreateVerificationFile)
                                verification = new VerificationFile(entries, backend.FilenameStrategy);

                            OperationProgress(this, XervBackupOperation.Backup, bs.OperationMode, (int)(m_progress * 100), -1, Strings.Interface.StatusReadingIncrementals, "");

                            patches = FindPatches(backend, entries, tempfolder, false, bs);

                            //Check before we start the download
                            CheckLiveControl();
                            Manifestfile latest = GetManifest(backend, backupsets[backupsets.Count - 1]);

                            //Manifest version 1 does not support multiple folders
                            if (latest.Version == 1)
                                latest.SourceDirs = new string[] { sources[0] };

                            if (latest.SourceDirs.Length != sources.Length)
                            {
                                if (m_options.FullIfSourceFolderChanged)
                                {
                                    Logging.Log.WriteMessage("Source folder count changed, issuing full backup", XervBackup.Library.Logging.LogMessageType.Information);
                                    if (!full)
                                        bs.SetTypeReason(Strings.Interface.FullBecauseSourceFoldersChanged);
                                    full = true;
                                }
                                else
                                    throw new Exception(string.Format(Strings.Interface.NumberOfSourceFoldersHasChangedError, latest.SourceDirs.Length, sources.Length));
                            }
                            else
                            {

                                if (!m_options.AllowSourceFolderChange)
                                {
                                    foreach (string s1 in latest.SourceDirs)
                                    {
                                        bool found = false;
                                        foreach (string s2 in sources)
                                            if (s1.Equals(s2, Utility.Utility.IsFSCaseSensitive ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase))
                                            {
                                                found = true;
                                                break;
                                            }

                                        if (!found)
                                        {
                                            if (m_options.FullIfSourceFolderChanged)
                                            {
                                                Logging.Log.WriteMessage("Source folders changed, issuing full backup", XervBackup.Library.Logging.LogMessageType.Information);
                                                if (!full)
                                                    bs.SetTypeReason(Strings.Interface.FullBecauseSourceFoldersChanged);
                                                full = true;
                                                break; //Exit the folder loop
                                            }
                                            else
                                                throw new Exception(string.Format(Strings.Interface.SourceFoldersHasChangedError, s1));
                                        }
                                    }

                                    manifest.SourceDirs = latest.SourceDirs;
                                }
                                else
                                {
                                    manifest.SourceDirs = sources;
                                }
                            }

                        }

                        DateTime backuptime = DateTime.Now;
                        DateTime backupchaintime;

                        if (full)
                        {
                            patches.Clear();
                            m_incrementalFraction = 0.0;
                            manifest.SourceDirs = sources;
                            if (m_options.CreateVerificationFile)
                                verification = new VerificationFile(new ManifestEntry[0], backend.FilenameStrategy);
                            backupchaintime = backuptime;
                        }
                        else
                        {
                            backupchaintime = patches[0].Key.Time;
                            manifest.PreviousManifestFilename = patches[patches.Count - 1].Key.Filename;
                            manifest.PreviousManifestHash = patches[patches.Count - 1].Key.RemoteHash;
                        }

                        OperationProgress(this, XervBackupOperation.Backup, bs.OperationMode, -1, -1, Strings.Interface.StatusBuildingFilelist, "");

                        bool completedWithoutChanges;

                        using (RSync.RSyncDir dir = new XervBackup.Library.Main.RSync.RSyncDir(manifest.SourceDirs, bs, m_options.Filter, patches))
                        {
                            CheckLiveControl();

                            dir.ProgressEvent += new XervBackup.Library.Main.RSync.RSyncDir.ProgressEventDelegate(BackupRSyncDir_ProgressEvent);

                            dir.DisableFiletimeCheck = m_options.DisableFiletimeCheck;
                            dir.MaxFileSize = m_options.SkipFilesLargerThan;
                            using (new Logging.Timer("Initiating multipass"))
                                dir.InitiateMultiPassDiff(full, m_options);

                            string tempVolumeFolder = m_options.AsynchronousUpload ? m_options.AsynchronousUploadFolder : m_options.TempDir;

                            bool done = false;
                            while (!done && totalsize < m_options.MaxSize)
                            {
                                using (new Logging.Timer("Multipass " + (vol + 1).ToString()))
                                using (Utility.TempFile signaturefile = new XervBackup.Library.Utility.TempFile(System.IO.Path.Combine(tempVolumeFolder, Guid.NewGuid().ToString())))
                                using (Utility.TempFile contentfile = new XervBackup.Library.Utility.TempFile(System.IO.Path.Combine(tempVolumeFolder, Guid.NewGuid().ToString())))
                                {
                                    OperationProgress(this, XervBackupOperation.Backup, bs.OperationMode, (int)(m_progress * 100), -1, string.Format(Strings.Interface.StatusCreatingVolume, vol + 1), "");

                                    CheckLiveControl();

                                    using (Library.Interface.ICompression signaturearchive = DynamicLoader.CompressionLoader.GetModule(m_options.CompressionModule, signaturefile, m_options.RawOptions))
                                    using (Library.Interface.ICompression contentarchive = DynamicLoader.CompressionLoader.GetModule(m_options.CompressionModule, contentfile, m_options.RawOptions))
                                    {
                                        //If we are all out, stop now, this may cause incomplete partial files
                                        if (m_options.MaxSize - totalsize < (contentarchive.FlushBufferSize + backend.FileSizeOverhead))
                                            break;

                                        //Add signature files to archive
                                        foreach (string s in controlfiles)
                                            if (!string.IsNullOrEmpty(s))
                                                using (System.IO.Stream cs = signaturearchive.CreateFile(System.IO.Path.Combine(RSync.RSyncDir.CONTROL_ROOT, System.IO.Path.GetFileName(s))))
                                                using (System.IO.FileStream fs = System.IO.File.OpenRead(s))
                                                    Utility.Utility.CopyStream(fs, cs);

                                        //Only add control files to the very first volume
                                        controlfiles.Clear();

                                        done = dir.MakeMultiPassDiff(signaturearchive, contentarchive, (Math.Min(m_options.VolumeSize, m_options.MaxSize - totalsize)) - backend.FileSizeOverhead);

                                        //TODO: This is not the correct size, we need to account for file size overhead as well
                                        totalsize += signaturearchive.Size;
                                        totalsize += contentarchive.Size;

                                        //TODO: This is not the best way to determine this
                                        if (totalsize >= m_options.MaxSize)
                                            dir.FinalizeMultiPass(signaturearchive, contentarchive, long.MaxValue);

                                    }

                                    completedWithoutChanges = done && !dir.AnyChangesFound;

                                    if (m_options.UploadUnchangedBackups || full)
                                        completedWithoutChanges = false;

                                    if (!completedWithoutChanges)
                                    {

                                        if (m_options.AsynchronousUpload)
                                        {
                                            m_lastProgressMessage = Strings.Interface.StatusWaitingForUpload;
                                            m_allowUploadProgress = true;
                                            m_allowUploadProgressAfter = DateTime.Now.AddSeconds(1);
                                        }
                                        else
                                            OperationProgress(this, XervBackupOperation.Backup, bs.OperationMode, (int)(m_progress * 100), -1, string.Format(Strings.Interface.StatusUploadingContentVolume, vol + 1), "");

                                        //Last check before we upload, we do not interrupt transfers
                                        CheckLiveControl();

                                        //The backendwrapper will remove these
                                        signaturefile.Protected = true;
                                        contentfile.Protected = true;

                                        ContentEntry ce = new ContentEntry(backuptime, full, vol + 1);
                                        SignatureEntry se = new SignatureEntry(backuptime, full, vol + 1);

                                        using (new Logging.Timer("Writing delta file " + (vol + 1).ToString()))
                                            backend.Put(ce, contentfile);

                                        if (!m_options.AsynchronousUpload)
                                            OperationProgress(this, XervBackupOperation.Backup, bs.OperationMode, (int)(m_progress * 100), -1, string.Format(Strings.Interface.StatusUploadingSignatureVolume, vol + 1), "");

                                        using (new Logging.Timer("Writing remote signatures"))
                                            backend.Put(se, signaturefile);

                                        manifest.AddEntries(ce, se);

                                        if (verification != null)
                                        {
                                            verification.AddFile(ce);
                                            verification.AddFile(se);
                                        }
                                    }
                                }

                                if (!completedWithoutChanges)
                                {
                                    //The backend wrapper will remove these
                                    Utility.TempFile mf = new XervBackup.Library.Utility.TempFile();

                                    using (new Logging.Timer("Writing manifest " + backuptime.ToUniversalTime().ToString("yyyyMMddTHHmmssK")))
                                    {
                                        //Alternate primary/secondary
                                        ManifestEntry mfe = new ManifestEntry(backuptime, full, manifest.SignatureHashes.Count % 2 != 0);
                                        manifest.SelfFilename = backend.GenerateFilename(mfe);
                                        manifest.Save(mf);

                                        if (!m_options.AsynchronousUpload)
                                            OperationProgress(this, XervBackupOperation.Backup, bs.OperationMode, (int)(m_progress * 100), -1, string.Format(Strings.Interface.StatusUploadingManifestVolume, vol + 1), "");

                                        //Write the file
                                        mf.Protected = true;
                                        backend.Put(mfe, mf);

                                        if (verification != null)
                                            verification.UpdateManifest(mfe);
                                    }

                                    if (verification != null)
                                    {
                                        using (new Logging.Timer("Writing verification " + backuptime.ToUniversalTime().ToString("yyyyMMddTHHmmssK")))
                                        {
                                            Utility.TempFile vt = new XervBackup.Library.Utility.TempFile();

                                            verification.Save(vt);

                                            if (!m_options.AsynchronousUpload)
                                                OperationProgress(this, XervBackupOperation.Backup, bs.OperationMode, (int)(m_progress * 100), -1, Strings.Interface.StatusUploadingVerificationVolume, "");

                                            vt.Protected = true;
                                            backend.Put(new VerificationEntry(backupchaintime), vt);
                                        }
                                    }

                                    if (m_options.AsynchronousUpload)
                                        m_allowUploadProgress = false;

                                    //The file volume counter
                                    vol++;
                                }
                            }
                        }

                        //If we are running asynchronous, we now enter the end-game
                        if (m_options.AsynchronousUpload)
                        {
                            m_lastProgressMessage = Strings.Interface.StatusWaitingForUpload;
                            m_allowUploadProgress = true;
                            m_allowUploadProgressAfter = DateTime.Now;

                            //Before we clear the temp folder, we need to ensure that all volumes are uploaded.
                            //To allow the UI to show some progress while uploading, we perform the remaining
                            // uploads synchronous
                            List<KeyValuePair<BackupEntryBase, string>> pendingUploads = backend.ExtractPendingUploads();

                            //Figure out what volume number we are at
                            foreach (KeyValuePair<BackupEntryBase, string> p in pendingUploads)
                                if (p.Key is ManifestEntry)
                                    vol--;

                            double unitcost = m_asyncReserved / pendingUploads.Count;

                            //The upload each remaining volume in order
                            foreach (KeyValuePair<BackupEntryBase, string> p in pendingUploads)
                            {
                                string msg;
                                if (p.Key is ManifestEntry)
                                {
                                    vol++;
                                    msg = string.Format(Strings.Interface.StatusUploadingManifestVolume, vol);
                                }
                                else if (p.Key is SignatureEntry)
                                    msg = string.Format(Strings.Interface.StatusUploadingSignatureVolume, ((SignatureEntry)p.Key).Volumenumber);
                                else if (p.Key is ContentEntry)
                                {
                                    msg = string.Format(Strings.Interface.StatusUploadingContentVolume, ((ContentEntry)p.Key).Volumenumber);

                                    //We allow a stop or pause request here
                                    CheckLiveControl();
                                }
                                else if (p.Key is VerificationEntry)
                                    msg = Strings.Interface.StatusUploadingVerificationVolume;
                                else
                                    throw new InvalidOperationException();

                                OperationProgress(this, XervBackupOperation.Backup, bs.OperationMode, (int)(m_progress * 100), -1, msg, "");
                                backend.Put(p.Key, p.Value);
                                m_asyncReserved -= unitcost;
                                m_progress += unitcost;
                            }
                        }
                    }
                }
                catch(Exception ex)
                {
                        //If this is a controlled user-requested stop, wait for the current upload to complete
                    if (backend != null && ex is LiveControl.ExecutionStoppedException)
                    {
                        try
                        {
                            if (m_options.AsynchronousUpload)
                            {
                                m_lastProgressMessage = Strings.Interface.StatusWaitingForUpload;
                                m_allowUploadProgress = true;
                                m_allowUploadProgressAfter = DateTime.Now;

                                //Wait for the current upload to complete and then delete all remaining temporary files
                                foreach (KeyValuePair<BackupEntryBase, string> p in backend.ExtractPendingUploads())
                                    try
                                    {
                                        if (System.IO.File.Exists(p.Value))
                                            System.IO.File.Delete(p.Value);
                                    }
                                    catch { } //Better to delete as many as possible rather than choke on a single file
                            }

                        }
                        catch { } //We already have an exception, just go with that
                    }

                    if (backend == null || backend.ManifestUploads == 0)
                    {
                        Logging.Log.WriteMessage(string.Format(Strings.Interface.ErrorRunningBackup, ex.Message), Logging.LogMessageType.Error);
                        throw; //This also activates "finally", unlike in other languages...
                    }

                    Logging.Log.WriteMessage(string.Format(Strings.Interface.PartialUploadMessage, backend.ManifestUploads, ex.Message), Logging.LogMessageType.Warning);
                    bs.LogError(string.Format(Strings.Interface.PartialUploadMessage, backend.ManifestUploads, ex.Message), ex);
                }
                finally
                {
                    m_progress = 100.0;
                    if (backend != null)
                        try { backend.Dispose(); }
                        catch { }

                    if (OperationCompleted != null)
                        OperationCompleted(this, XervBackupOperation.Backup, bs.OperationMode, 100, -1, Strings.Interface.StatusCompleted, "");

                    OperationProgress(this, XervBackupOperation.Backup, bs.OperationMode, 100, -1, Strings.Interface.StatusCompleted, "");
                }
            }

            bs.EndTime = DateTime.Now;

            return bs.ToString();
        }
示例#32
0
        /// <summary>
        /// Respond to the triggering of the Select action.
        /// </summary>
        protected override void SelectTriggered(ContentEntry<Gear> entry)
        {
            // if the quantity is zero, don't bother
            if (selectedQuantity <= 0)
            {
                return;
            }

            // check to see if gold is selected
            if (IsGoldSelected)
            {
                // play the "pick up gold" cue
                AudioManager.PlayCue("Money");
                // add the gold to the party
                Session.Party.PartyGold += selectedQuantity;
                chestEntry.Content.Gold -= selectedQuantity;
                if (chestEntry.Content.Gold > 0)
                {
                    selectedQuantity =
                        Math.Min(selectedQuantity, chestEntry.Content.Gold);
                }
                else
                {
                    ResetSelectedQuantity();
                }
            }
            else
            {
                // remove the selected quantity of gear from the chest
                int quantity = selectedQuantity;
                if ((entry.Content != null) && (quantity > 0))
                {
                    Session.Party.AddToInventory(entry.Content, quantity);
                    entry.Count -= quantity;
                }
                if (entry.Count > 0)
                {
                    selectedQuantity = Math.Min(entry.Count, selectedQuantity);
                }
                else
                {
                    // if the entry is now empty, remove it from the chest
                    chestEntry.Content.Entries.RemoveAt(SelectedGearIndex);
                    ResetSelectedQuantity();
                }
            }
        }
示例#33
0
        /// <summary>
        /// Draw the gear's content entry at the given position in the list.
        /// </summary>
        /// <param name="contentEntry">The content entry to draw.</param>
        /// <param name="position">The position to draw the entry at.</param>
        /// <param name="isSelected">If true, this item is selected.</param>
        protected override void DrawEntry(ContentEntry<Gear> entry, Vector2 position,
            bool isSelected)
        {
            // check the parameter
            if (entry == null)
            {
                throw new ArgumentNullException("entry");
            }
            Gear gear = entry.Content as Gear;
            if (gear == null)
            {
                return;
            }

            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
            Vector2 drawPosition = position;

            // draw the icon
            spriteBatch.Draw(gear.IconTexture, drawPosition + iconOffset, Color.White);

            // draw the name
            Color color = isSelected ? Fonts.HighlightColor : Fonts.DisplayColor;
            drawPosition.Y += listLineSpacing / 4;
            drawPosition.X += nameColumnInterval;
            spriteBatch.DrawString(Fonts.GearInfoFont, gear.Name, drawPosition, color);

            // draw the power
            drawPosition.X += powerColumnInterval;
            string powerText = gear.GetPowerText();
            Vector2 powerTextSize = Fonts.GearInfoFont.MeasureString(powerText);
            Vector2 powerPosition = drawPosition;
            powerPosition.Y -= (float)Math.Ceiling((powerTextSize.Y - 30f) / 2);
            spriteBatch.DrawString(Fonts.GearInfoFont, powerText,
                powerPosition, color);

            // draw the quantity
            drawPosition.X += quantityColumnInterval;
            if (isSelected)
            {
                // draw the left selection arrow
                drawPosition.X -= leftQuantityArrow.Width;
                spriteBatch.Draw(leftQuantityArrow,
                    new Vector2(drawPosition.X, drawPosition.Y - 4), Color.White);
                drawPosition.X += leftQuantityArrow.Width;
                // draw the selected quantity ratio
                string quantityText = selectedQuantity.ToString() + "/" +
                    entry.Count.ToString();
                spriteBatch.DrawString(Fonts.GearInfoFont, quantityText,
                    drawPosition, color);
                drawPosition.X += Fonts.GearInfoFont.MeasureString(quantityText).X;
                // draw the right selection arrow
                spriteBatch.Draw(rightQuantityArrow,
                    new Vector2(drawPosition.X, drawPosition.Y - 4), Color.White);
                drawPosition.X += rightQuantityArrow.Width;
            }
            else
            {
                // draw the remaining quantity
                spriteBatch.DrawString(Fonts.GearInfoFont, entry.Count.ToString(),
                    drawPosition, color);
            }
        }
示例#34
0
 /// <summary>
 /// Respond to the triggering of the Y button (and related key).
 /// </summary>
 protected override void ButtonYPressed(ContentEntry<Gear> entry)
 {
     // add the entire amount of gold
     if (chestEntry.Content.Gold > 0)
     {
         AudioManager.PlayCue("Money");
         Session.Party.PartyGold += chestEntry.Content.Gold;
         chestEntry.Content.Gold = 0;
     }
     // add all items at full quantity
     // -- there is no limit to the party's inventory
     ReadOnlyCollection<ContentEntry<Gear>> entries = GetDataList();
     foreach (ContentEntry<Gear> gearEntry in entries)
     {
         Session.Party.AddToInventory(gearEntry.Content, gearEntry.Count);
     }
     // clear the entries, as they're all gone now
     chestEntry.Content.Entries.Clear();
     selectedQuantity = 0;
 }
示例#35
0
 /// <summary>
 /// Adds a content and signature hash to the manifest
 /// </summary>
 /// <param name="contenthash">The content hash</param>
 /// <param name="signaturehash">The signature hash</param>
 public void AddEntries(ContentEntry contenthash, SignatureEntry signaturehash)
 {
     SignatureHashes.Add(new HashEntry(signaturehash));
     ContentHashes.Add(new HashEntry(contenthash));
 }
示例#36
0
        /// <summary>
        /// Add the given gear, in the given quantity, to the party's inventory.
        /// </summary>
        public void AddToInventory(Gear gear, int count)
        {
            // check the parameters
            if ((gear == null) || (count <= 0))
            {
                return;
            }

            // search for an existing entry
            ContentEntry<Gear> existingEntry = inventory.Find(
                delegate(ContentEntry<Gear> entry)
                {
                    return (entry.Content == gear);
                });
            // increment the existing entry, if any
            if (existingEntry != null)
            {
                existingEntry.Count += count;
                return;
            }

            // no existing entry - create a new entry
            ContentEntry<Gear> newEntry = new ContentEntry<Gear>();
            newEntry.Content = gear;
            newEntry.Count = count;
            newEntry.ContentName = gear.AssetName;
            if (newEntry.ContentName.StartsWith(@"Gear\"))
            {
                newEntry.ContentName = newEntry.ContentName.Substring(5);
            }
            inventory.Add(newEntry);
        }
示例#37
0
        /// <summary>
        /// Respond to the triggering of the Select action.
        /// </summary>
        protected override void SelectTriggered(ContentEntry<Gear> entry) 
        {
            // check the parameter
            if ((entry == null) || (entry.Content == null))
            {
                return;
            }

            // make sure the selected quantity is valid
            selectedQuantity = Math.Min(selectedQuantity, entry.Count);

            // add the gold to the party's inventory
            Session.Party.PartyGold += selectedQuantity *
                (int)Math.Ceiling(entry.Content.GoldValue * store.SellMultiplier);

            // remove the items from the party's inventory
            Session.Party.RemoveFromInventory(entry.Content, selectedQuantity);

            // reset the quantities - either gold has gone down or the total was bad
            ResetQuantities();
        }
示例#38
0
        /// <summary>
        /// Draw the entry at the given position in the list.
        /// </summary>
        /// <param name="contentEntry">The entry to draw.</param>
        /// <param name="position">The position to draw the entry at.</param>
        /// <param name="isSelected">If true, this item is selected.</param>
        protected override void DrawEntry(ContentEntry<Gear> entry, Vector2 position,
            bool isSelected)
        {
            // check the parameter
            if ((entry == null) || (entry.Content == null))
            {
                throw new ArgumentNullException("entry");
            }

            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
            Vector2 drawPosition = position;

            // draw the icon
            spriteBatch.Draw(entry.Content.IconTexture, drawPosition + iconOffset, 
                Color.White);

            // draw the name
            Color color = isSelected ? Fonts.HighlightColor : Fonts.DisplayColor;
            drawPosition.Y += listLineSpacing / 4;
            drawPosition.X += nameColumnInterval;
            spriteBatch.DrawString(Fonts.GearInfoFont, entry.Content.Name, 
                drawPosition, color);

            // draw the power
            drawPosition.X += powerColumnInterval;
            string powerText = entry.Content.GetPowerText();
            Vector2 powerTextSize = Fonts.GearInfoFont.MeasureString(powerText);
            Vector2 powerPosition = drawPosition;
            powerPosition.Y -= (float)Math.Ceiling((powerTextSize.Y - 30f) / 2);
            spriteBatch.DrawString(Fonts.GearInfoFont, powerText,
                powerPosition, color);

            // draw the quantity
            drawPosition.X += quantityColumnInterval;
            if (isSelected)
            {
                Vector2 quantityPosition = drawPosition;
                // draw the left selection arrow
                quantityPosition.X -= leftQuantityArrow.Width;
                spriteBatch.Draw(leftQuantityArrow,
                    new Vector2(quantityPosition.X, quantityPosition.Y - 4),
                    Color.White);
                quantityPosition.X += leftQuantityArrow.Width;
                // draw the selected quantity ratio
                string quantityText = selectedQuantity.ToString() + "/" +
                    entry.Count.ToString();
                spriteBatch.DrawString(Fonts.GearInfoFont, quantityText,
                    quantityPosition, color);
                quantityPosition.X +=
                    Fonts.GearInfoFont.MeasureString(quantityText).X;
                // draw the right selection arrow
                spriteBatch.Draw(rightQuantityArrow,
                    new Vector2(quantityPosition.X, quantityPosition.Y - 4),
                    Color.White);
                quantityPosition.X += rightQuantityArrow.Width;
                // draw the purchase button
                selectButtonText = "Sell";
            }
            else
            {
                spriteBatch.DrawString(Fonts.GearInfoFont, entry.Count.ToString(),
                    drawPosition, color);
            }

            // draw the price
            drawPosition.X += priceColumnInterval;
            string priceText = String.Empty;
            if (isSelected)
            {
                int totalPrice = selectedQuantity *
                    (int)Math.Ceiling(entry.Content.GoldValue * store.SellMultiplier);
                priceText = totalPrice.ToString();
            }
            else
            {
                priceText = ((int)Math.Ceiling(entry.Content.GoldValue * 
                    store.SellMultiplier)).ToString();
            }
            spriteBatch.DrawString(Fonts.GearInfoFont, priceText,
                drawPosition, color);
        }
示例#39
0
        /// <summary>
        /// Draw the description of the selected item.
        /// </summary>
        protected override void DrawSelectedDescription(ContentEntry<Gear> entry)
        {
            // check the parameter
            if ((entry == null) || (entry.Content == null))
            {
                throw new ArgumentNullException("entry");
            }

            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
            Vector2 position = descriptionTextPosition;

            // draw the description
            // -- it's up to the content owner to fit the description
            string text = entry.Content.Description;
            if (!String.IsNullOrEmpty(text))
            {
                spriteBatch.DrawString(Fonts.DescriptionFont, text, position,
                    Fonts.DescriptionColor);
                position.Y += Fonts.DescriptionFont.LineSpacing;
            }

            // draw the modifiers
            Equipment equipment = entry.Content as Equipment;
            if (equipment != null)
            {
                text = equipment.OwnerBuffStatistics.GetModifierString();
                if (!String.IsNullOrEmpty(text))
                {
                    spriteBatch.DrawString(Fonts.DescriptionFont, text, position,
                        Fonts.DescriptionColor);
                    position.Y += Fonts.DescriptionFont.LineSpacing;
                }
            }

            // draw the restrictions
            text = entry.Content.GetRestrictionsText();
            if (!String.IsNullOrEmpty(text))
            {
                spriteBatch.DrawString(Fonts.DescriptionFont, text, position,
                    Fonts.DescriptionColor);
                position.Y += Fonts.DescriptionFont.LineSpacing;
            }
        }