// ISelectionPathInterpreter Members public DependencyObject ResolveSelectionPath(CategoryList root, SelectionPath path, out bool pendingGeneration) { pendingGeneration = false; if (path == null || !string.Equals(PathTypeId, path.PathTypeId)) { Debug.Fail("Invalid SelectionPath specified."); return null; } if (root == null) { Debug.Fail("No CategoryList specified."); return null; } string editorTypeName = path.Path; if (string.IsNullOrEmpty(editorTypeName)) { Debug.Fail("Invalid SelectionPath specified."); return null; } ModelCategoryEntry category; CategoryEditor editor = root.FindCategoryEditor(editorTypeName, out category); if (editor == null || category == null) { return null; } return root.FindCategoryEditorVisual(editor, category, out pendingGeneration); }
public static CategoryList InitializeCategories() { var user = new User { UserId = 2 }; var result = new CategoryList { new Category(user){Name="Other",CategoryId=1 }}; return result; }
void rpCategory_Populate() { //make category list CategoryList catList = new CategoryList(); //get all categories catList = catList.GetAll(); //bind the list to the repeater rptCategories.DataSource = catList.List; rptCategories.DataBind(); }
public StaticServiceData() { CategoryList = new CategoryList(); TypeTransactionList = new TypeTransactionList(); TypeTransactionReasonList = new TypeTransactionReasonList(); NotificationList = new NotificationList(); TypeFrequencyList = new TypeFrequencyList(); IntervalList = new TypeIntervalList(); RecurrenceRuleList = new RecurrenceRuleList(); }
// <summary> // Basic ctor // </summary> // <param name="owner">Contained CategoryList</param> public CategoryListAutomationPeer(CategoryList owner) : base(owner) { if (owner == null) { throw FxTrace.Exception.ArgumentNull("owner"); } _control = owner; _children = new List<AutomationPeer>(); }
protected void ddlCategory_Populate() { CategoryList catList = new CategoryList(); //Get all categories catList = catList.GetAll(); //Bind the types of Categories to ddlCategory ddlCategory.DataSource = catList.List; ddlCategory.DataTextField = "Type"; ddlCategory.DataValueField = "ID"; ddlCategory.DataBind(); //call findCategory FindCategory(); }
public DlgEditPerson(Gtk.Window super, CategoryList cats, Person p) { this.person = p; this.categories = cats; this.TransientFor = super; this.Modal = true; this.Title = super.Title; this.Icon = super.Icon; this.Build(); this.ShowAll(); this.SetPosition( Gtk.WindowPosition.CenterOnParent ); this.Resizable = false; }
// <summary> // Attempt to resolve the given SelectionPath into the corresponding visual in the // specified CategoryList control. // </summary> // <param name="root">CategoryList control instance to look in</param> // <param name="path">SelectionPath to resolve</param> // <returns>Corresponding visual, if found, null otherwise</returns> public static DependencyObject ResolveSelectionPath(CategoryList root, SelectionPath path, out bool pendingGeneration) { pendingGeneration = false; if (root == null || path == null) { return null; } ISelectionPathInterpreter interpreter; if (!_interpreters.TryGetValue(path.PathTypeId, out interpreter)) { return null; } return interpreter.ResolveSelectionPath(root, path, out pendingGeneration); }
// ISelectionPathInterpreter Members public DependencyObject ResolveSelectionPath(CategoryList root, SelectionPath path, out bool pendingGeneration) { pendingGeneration = false; if (path == null || !string.Equals(PathTypeId, path.PathTypeId)) { Debug.Fail("Invalid SelectionPath specified."); return null; } if (root == null) { Debug.Fail("No CategoryList specified."); return null; } string[] pathValues = path.Path.Split(','); string categoryName = PersistedStateUtilities.Unescape(pathValues[0]); bool isAdvanced = pathValues.Length == 2; CategoryEntry category = root.FindCategory(categoryName); if (category == null) { return null; } DependencyObject categoryVisual = root.FindCategoryEntryVisual(category); if (categoryVisual == null) { return null; } DependencyObject searchStart; // For basic section, start at the root. // For advanced section, start at the advanced expander. // The next SelectionStop in both cases will be the section header SelectionStop. if (!isAdvanced) { searchStart = categoryVisual; } else { searchStart = VisualTreeUtils.GetNamedChild<FrameworkElement>(categoryVisual, "PART_AdvancedExpander"); } return PropertySelection.FindNeighborSelectionStop<DependencyObject>(searchStart, SearchDirection.Next); }
/// <summary> /// Adds the provider. /// </summary> /// <param name="root">The root.</param> /// <param name="entryPoint">The entry point.</param> /// <param name="providerName">Name of the provider.</param> /// <param name="categoryList">The category list.</param> /// <returns> /// <c>true</c> if [the provider has been attached]; otherwise, <c>false</c>. /// </returns> /// <exception cref="System.InvalidOperationException">Content provider for this node already attached. /// or /// Content provider with same name already attached.</exception> public static bool AddProvider(int root, int entryPoint, string providerName, CategoryList categoryList) { string name = string.Format(CultureInfo.InvariantCulture, "{0}-ClonedContent-{1}-{2}", providerName, root, entryPoint); IQueryable<ClonedContentProviderSettings> providerCollection = SettingsRepository.Instance.GetAll().AsQueryable(); if (providerCollection.Count(pc => pc.EntryPoint.Equals(entryPoint)) > 0) { // A provider is already attached to this node. throw new InvalidOperationException("Content provider for this node already attached."); } if (providerCollection.Count(pc => pc.Name.Equals(name)) > 0) { // A provider with the same name already exists. throw new InvalidOperationException("Content provider with same name already attached."); } CategoryList categories = categoryList ?? new CategoryList(); ClonedContentProvider provider = new ClonedContentProvider( name, new PageReference(root), new PageReference(entryPoint), categories); IContentProviderManager providerManager = ServiceLocator.Current.GetInstance<IContentProviderManager>(); ClonedContentProviderSettings contentProviderSettings = new ClonedContentProviderSettings { Name = name, EntryPoint = entryPoint, Root = root, CategoryList = string.Join( ",", categories) }; providerManager.ProviderMap.AddProvider(provider); SettingsRepository.Instance.SaveSettings(contentProviderSettings); CacheManager.Clear(); return true; }
// IPropertyViewManager Members // <summary> // Add a property into the correct category within the specified CategoryList. // </summary> // <param name="propertySet">Specified property (passed in as a set for multi-select scenarios)</param> // <param name="propertyName">Name of the current property (perf optimization)</param> // <param name="categoryList">CategoryList instance to populate</param> // <returns>Wrapped ModelPropertyEntry for the specified propertySet</returns> public ModelPropertyEntry AddProperty(IEnumerable<ModelProperty> propertySet, string propertyName, CategoryList categoryList) { string categoryName = GetCategoryName(propertySet); ModelCategoryEntry category = categoryList.FindCategory(categoryName) as ModelCategoryEntry; bool reuseEntries = ExtensibilityAccessor.IsEditorReusable(propertySet); if (reuseEntries && category != null) { ModelPropertyEntry foundProperty; if ((foundProperty = (ModelPropertyEntry)category[propertyName]) != null) { if (foundProperty.PropertyType != null && foundProperty.PropertyType.Equals(System.Activities.Presentation.Internal.PropertyEditing.Model.ModelUtilities.GetPropertyType(propertySet))) { // Found a match for the property, so reuse it bool oldIsBrowsable = foundProperty.IsBrowsable; bool oldIsAdvanced = foundProperty.IsAdvanced; foundProperty.SetUnderlyingModelProperty(propertySet); // If the IsBrowsable or IsAdvanced value of the property changed, // refresh the property within the category, because how and whether // this property should be rendered may have changed. // Note that refreshing a selected property also nullifies its stickiness // (ie. it resets CategoryList.PropertySelectionMode) if (oldIsAdvanced != foundProperty.IsAdvanced || oldIsBrowsable != foundProperty.IsBrowsable) { category.Refresh(foundProperty, category.GetBucket(foundProperty), this.PropertyComparer); } return foundProperty; } } } if (category == null) { category = new ModelCategoryEntry(categoryName); categoryList.InsertAlphabetically(category); } ModelPropertyEntry property = new ModelPropertyEntry(propertySet, null); category.Add(property, category.GetBucket(property), this.PropertyComparer); return property; }
/// <summary> /// Removes any page not matching any of the specified categories /// </summary> /// <param name="pages">The page collection to filter</param> /// <param name="categories">Categories used for filtering, pages not matching at least one category will be filtered out</param> public static void FilterByCategories(this PageDataCollection pages, CategoryList categories) { if (categories == null || !categories.Any()) { return; } for (var i = pages.Count - 1; i >= 0; i--) { var atLeastOneCategoryMatches = categories.Any(c => pages[i].Category.Contains(c)); if (!atLeastOneCategoryMatches) { pages.RemoveAt(i); } } }
public CategoryList GetLocalizations() { var xml = LoadXml(); var languages = GetEnabledLanguages(); var categories = new CategoryList(); foreach (var localization in GetLocalizationDefinitions()) { var translation = categories.AddTranslation( localization.Key, localization.Description, localization.Category, localization.DefaultValue); foreach (var lang in languages) { var value = XmlLanguageFileHelper.FindExistingTranslation(xml, lang, translation.Key); translation.AddTranslation(lang, value ?? string.Empty); } } return categories; }
public void Pass_Delete() { // Arrange CategoryList expectedCategoryList = new CategoryList(); expectedCategoryList.GetAll(); target.IsNew = true; target.Type = "TestAction"; // Act target.Save(); target.Deleted = true; target.IsNew = false; target.IsDirty = true; target.Save(); CategoryList actualCategoryList = new CategoryList(); actualCategoryList.GetAll(); // Assert Assert.AreEqual(expectedCategoryList.List.Count, actualCategoryList.List.Count, "It deleted! yay!"); }
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot, CategoryList categoryFilter) { if (cloneRoot.CompareToIgnoreWorkID(entryRoot)) { throw new NotSupportedException("Entry root and clone root cannot be set to the same content reference"); } if (DataFactory.Instance.GetChildren<IContent>(entryRoot).Any()) { throw new NotSupportedException("Unable to create ClonedContentProvider, the EntryRoot property must point to leaf content (without children)"); } CloneRoot = cloneRoot; EntryRoot = entryRoot; Category = categoryFilter; // Set the entry point parameter Parameters.Add(Configuration.PageProvider.EntryPointString, EntryRoot.ID.ToString(CultureInfo.InvariantCulture)); // Configure content store used to retrieve pages ContentStore = ServiceLocator.Current.GetInstance<ContentStore>(); }
public List<CategoryItem> GetCategories() { //return new List<Category>(); var context = new SitecoreContext(); List<CategoryItem> categories = new List<CategoryItem>(); categoryList = context.GetItem<CategoryList>(CATEGORY_ROOT_GUID); var categoryBucket = categoryList.Children.Select(a => new Category() { CategoryId = a.CategoryId, Title = a.Title, Description = a.Description, SmallImage = a.SmallImage }).ToList<Category>().Where(x => x.Title != null); foreach (var v in categoryBucket) { categories.Add(new CategoryItem() { CategoryId=v.CategoryId, Title=v.Title, Description=v.Description, SmallImage=v.SmallImage }); } return categories; }
public void LoadLiveCategories(Action<Exception> callback) { var retVal = new CategoryList(); var client = new StaticClient(); try { latestState = Guid.NewGuid().ToString(); client.GetAllCategoriesAsync(App.Instance.User.UserId); client.GetAllCategoriesCompleted += async (o, e) => { if (e.Error == null) { await StorageUtility.DeleteAllItems(STATIC_CATEGORY_FOLDER, App.Instance.User.UserName); await SetupTypeCategoryData(e.Result, true); } callback(e.Error); }; } catch (Exception) { throw; } }
private async void KeywordsCategoryControl_SubmitClick(object sender, ItemClickEventArgs e) { try { KeywordsCategoryControl.ActiveProgressRing(); #region 除多余类目 var length = KeywordsCategoryControl.deleteIds?.Count; for (int i = 0; i < length; i++) { var DeleteObject = await LinqHelper.DeleteData("BlockQueryCategory", KeywordsCategoryControl.deleteIds[i]); var result = JsonConvert.DeserializeObject <JsonChangedTemplate>(DeleteObject); // string DeleteResultCode = DeleteObject.GetNamedValue("ResultCode").ToString(); if (result.ResultCode != (int)ResultCodeType.操作成功) { throw (new Exception("KeywordsCategory 删除失败" + result.Message)); } } #endregion #region Update the CategoryList exist before var updateList = KeywordsCategoryControl.CategoryList.Where(x => !String.IsNullOrEmpty(x.Id)).ToList(); for (int i = 0; i < updateList.Count; i++) { var item = updateList[i]; if (!String.IsNullOrEmpty(item.Id)) { var updateResult = await LinqHelper.UpdateData("BlockQueryCategory", item); var result = JsonConvert.DeserializeObject <JsonChangedTemplate>(updateResult); if (result.ResultCode != (int)ResultCodeType.操作成功) { throw (new Exception("KeywordsCategory 更新" + result.Message)); } } } #endregion #region 批量上传 新增类目 var newlist = KeywordsCategoryControl.CategoryList.Where(x => String.IsNullOrEmpty(x.Id)); if (newlist != null && newlist.Count() > 0) { var jsonArray = JsonConvert.SerializeObject(newlist); var jsonResult = await LinqHelper.SaveBatchData(jsonArray, "BlockQueryCategory"); var result = JsonConvert.DeserializeObject <JsonChangedTemplate>(jsonResult); await MainPage.ShowMessage(result.ResultCode); } #endregion CategoryList.Clear(); InitCategory(); KeywordsCategoryControl.Dispose(); } catch (Exception ex) { await MainPage.ShowErrorMessage(ex.Message); } finally { KeywordsCategoryControl.InActiveProgressRing(); } }
/// <summary> /// Загрузить категории /// </summary> /// <returns></returns> public CategoryList LoadCategories() { var list = new CategoryList(); if (server == null) return null; try { using (var documentStore = server.OpenClient()) { var categories = documentStore.Query<Category>(); //foreach (Category category in categories) // documentStore.Delete(category); //documentStore.Commit(); if (categories.Count() > 0) { foreach (var category in categories) if (category!=null) list.Add(category); } else { var c = new Category { Name = "Default" }; list.Add(c); documentStore.Store(c); documentStore.Commit(); } foreach (var category in list) category.SetOwner(list); list.Reorder(); } } catch (Exception ex) { MessageBox.Show("Ошибка выборки категорий из БД." + ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } return list; }
public LocalizationEditorViewModel() { Categories = new CategoryList(); }
/// <summary> /// Загрузить категории /// </summary> /// <returns></returns> public CategoryList LoadCategories() { if (ds != null) ds.Dispose(); ds = new DataSet(); CategoryList list = null; using (SQLiteCommand mycommand = new SQLiteCommand(conn)) { mycommand.CommandText = "select * from categories"; da = new SQLiteDataAdapter(); da.SelectCommand = mycommand; System.Data.SQLite.SQLiteCommandBuilder cb = new System.Data.SQLite.SQLiteCommandBuilder(da); da.Fill(ds, "categories"); foreach (DataRow row in ds.Tables["categories"].Rows) { string categories_xml = row["categories_xml"].ToString(); if (!string.IsNullOrEmpty(categories_xml)) { try { var reader = new StringReader(categories_xml); var sr = new XmlSerializer(typeof(CategoryList)); list = (CategoryList)sr.Deserialize(reader); foreach (Category category in list) category.SetOwner(list); list.Reorder(); return list;//(CategoryList)sr.Deserialize(reader); } catch { } break; } } } if (list == null) { list = new CategoryList(); list.Add(new Category() { Name = "Default" }); } foreach (Category category in list) category.SetOwner(list); list.Reorder(); return list; }
public AgendaSystem() { this.personsList = new PersonsList(); this.categoryList = new CategoryList(); }
// <summary> // Scans the list of categories in the specified CategoryList and returns a set of // CategoryEditor types that should be present in the list based on the properties // in it. // </summary> // <param name="ownerType">Type of the currently displayed item</param> // <param name="categoryList">CategoryList to examine</param> // <returns>Set of expected CategoryEditor types</returns> public Dictionary<Type, object> GetCategoryEditors(Type ownerType, CategoryList categoryList) { // No category editors in alpha-view return new Dictionary<Type, object>(); }
public void Can_project_using_let_and_have_nested_query_with_let_that_refers_to_the_outer_let() { using (var store = GetDocumentStore()) using (var session = store.OpenSession()) { const string categoryListId = "reference/categoryList"; const string departmentListId = "reference/departmentList"; var categories = new CategoryList { Categories = new Dictionary <string, Category> { { "1", new Category { Name = "Tables" } }, { "2", new Category { Name = "Electrical" } } } }; session.Store(categories, categoryListId); var departments = new DepartmentList { Departments = new Dictionary <string, Department> { { "1", new Department { Name = "Operations" } }, { "2", new Department { Name = "Engineering" } } } }; session.Store(departments, departmentListId); var order = new Order { Items = new List <OrderItem> { new OrderItem { Name = "Table", CategoryId = "1", DepartmentId = "1" }, new OrderItem { Name = "20 Amp Service", CategoryId = "2", DepartmentId = "2" } } }; session.Store(order); session.SaveChanges(); var query = from o in session.Query <Order>() let categoryList = RavenQuery.Load <CategoryList>(categoryListId) let departmentList = RavenQuery.Load <DepartmentList>(departmentListId) select new { o.Id, Items = from i in order.Items let category = categoryList.Categories[i.CategoryId] let department = departmentList.Departments[i.DepartmentId] select new { i.Name, CategoryName = category.Name, DepartmentName = department.Name } }; var result = query.First(); Assert.All(result.Items, item => { Assert.NotNull(item.CategoryName); Assert.NotNull(item.DepartmentName); }); } }
public ICategoryList ClassifyText(string text, int maxResults) { long startTime = DateTime.Now.Ticks; ListDictionary results = new ListDictionary(); Dictionary <string, double> scores = new Dictionary <string, double>(); TokenTable tblTest = new TokenTable(text); double maxScore = 0; double threshold = 0; List <TokenVoter> charsetVoters = new List <TokenVoter>(); // collect stats based on charset (first filter) foreach (string category in this.Keys) { ITokenTable catTable = this[category]; if (!catTable.Enabled) { continue; } double score = catTable.CharsetTable.CharsetComparisonScore(tblTest.CharsetTable, threshold); if (score > maxScore) { maxScore = score; threshold = (maxScore * this.m_Threshold); } if (score > threshold) { charsetVoters.Add(new TokenVoter(category, score)); } } // chinese does not have a "Charset"... so to be sure.... if ((charsetVoters.Count < 3) && (this.Keys.Contains("zh"))) { charsetVoters.Add(new TokenVoter("zh")); } charsetVoters.Sort(); for (int i = charsetVoters.Count - 1; i > -1; i--) { if (charsetVoters[i].Score < threshold) { charsetVoters.RemoveAt(i); } } maxScore = 0;; // collect scores for each table int maxWordHits = 0; threshold = 0; foreach (TokenVoter charVoter in charsetVoters) { ITokenTable catTable = this[charVoter.Category]; if (!catTable.Enabled) { continue; } int hits = 0; double score = catTable.WordComparisonScore(tblTest, threshold, ref hits); if (hits > maxWordHits) { maxWordHits = hits; } if (score > maxScore) { maxScore = score; threshold = (maxScore * this.m_Threshold); } if (score > threshold) { scores.Add(charVoter.Category, score); } } double sumScore = 0; List <TokenVoter> voters = new List <TokenVoter>(); if (scores.Count == 0) { maxScore = charsetVoters[0].Score;; // take the voters from the closed charsert foreach (TokenVoter v in charsetVoters) { scores.Add(v.Category, v.Score); } } threshold = (maxScore * m_Threshold); // copy the scores to a sorted voters list foreach (string key in scores.Keys) { /* if ((long)scores[key] < threshold) * continue; */ // calc sum score double score = scores[key]; /* * if (maxWordHits < 1) * { * score = 0; // score > 0 ? 1 : 0; * } * else*/ if (score > threshold) { score /= maxScore; if (maxWordHits > 0) { score /= maxWordHits; } score *= 100; sumScore += score; voters.Add(new TokenVoter(key, score)); } } if (voters.Count > 1) { if (sumScore > 0) { voters.Sort(); // cleanup voters and rebalance if more than 3 voters... if (voters.Count > m_MaxVoters) { sumScore = 0; for (int i = 0; i < m_MaxVoters; i++) { ((TokenVoter)voters[i]).Score -= ((TokenVoter)voters[m_MaxVoters]).Score; sumScore += ((TokenVoter)voters[i]).Score; } voters.RemoveRange(m_MaxVoters, voters.Count - m_MaxVoters); } } } // now normalize results.. // the results are not an absolute confidence // but relative if (voters.Count == 1) { // only one voter, so it we are 100% sure that's the one! ScoreHolder newScore = new ScoreHolder(100); results.Add(((TokenVoter)voters[0]).Category, newScore); } else { for (int i = 0; i < voters.Count; i++) { TokenVoter stats = voters[i] as TokenVoter; double percScore = sumScore > 0 ? (stats.Score / sumScore) * 100 : 0; results.Add(stats.Category, new ScoreHolder(percScore)); } // if we have more than one possible result // we will try to disambiguate it by checking for // very common words if ((results.Count == 0) || (results.Count > 1)) { scores.Clear(); maxScore = 0; threshold = 0; // collect scores for each table foreach (string category in results.Keys) { ITokenTable catTable = (ITokenTable)this[category]; // threshold = tblTest.WordTable. Ranks*catTable.WordTable.Count; double score = catTable.ComparisonScore(tblTest, threshold); if (score > 0) { maxScore = System.Math.Max(maxScore, score); scores.Add(category, score); } } // got results? if (scores.Count > 0) { sumScore = 0; // copy the scores to a sorted voters list voters.Clear(); foreach (string key in scores.Keys) { // calc sum score sumScore += scores[key]; voters.Add(new TokenVoter(key, scores[key])); } voters.Sort(); // now normalize results.. // the results are not an absolute confidence // but relative if (voters.Count == 1) { // only one voter, so all other results are only 3/4 value foreach (string category in results.Keys) { if (category != ((TokenVoter)voters[0]).Category) { ((ScoreHolder)results[category]).DevideScore(0.75); } } } else { for (int i = 0; i < voters.Count; i++) { TokenVoter stats = voters[i] as TokenVoter; double percScore = (stats.Score / sumScore) * 200; ((ScoreHolder)results[stats.Category]).AddScore(percScore); } foreach (string category in results.Keys) { ((ScoreHolder)results[category]).DevideScore(0.75); } } } } } // now build a proper result.. voters.Clear(); foreach (string key in results.Keys) { voters.Add(new TokenVoter(key, ((ScoreHolder)results[key]).Score)); } voters.Sort(); /* * // Do a distance to next boos * for (int i = 0; i < voters.Count-1; i++) * { * voters[i].Score += voters[i].Score - voters[i + 1].Score; * } */ // reduce to maximum results if (voters.Count > maxResults) { voters.RemoveRange(maxResults, voters.Count - maxResults); } // re-weight... double dSumScore = 0; foreach (TokenVoter voter in voters) { dSumScore += voter.Score; } results.Clear(); foreach (TokenVoter voter in voters) { results.Add(voter.Category, new ScoreHolder((voter.Score / dSumScore) * 100)); } // ArrayList resultList = new ArrayList(results.Values); // resultList.Sort CategoryList result = new CategoryList(); foreach (string category in results.Keys) { result.Add(new Category(category, ((ScoreHolder)results[category]).Score)); } result.Sort(); #if DIALOGUEMASTER if (UseCounters) { m_Counters.Classifications.Increment(); m_Counters.ClassificationsPerSecond.Increment(); m_Counters.ComparisonTime.IncrementBy(DateTime.Now.Ticks - startTime); m_Counters.ComparisonTimeBase.Increment(); } #endif tblTest.Clear(); return(result); }
public EmoteCategoryAttribute(params uint[] emoteCategorys) { CategoryList.AddRange(emoteCategorys.ToList().Cast <EmoteCategory>()); }
public EmoteCategoryAttribute(params EmoteCategory[] emoteCategorys) { CategoryList.AddRange(emoteCategorys); }
public EmoteCategoryAttribute(EmoteCategory emoteCategory) { CategoryList.Add(emoteCategory); }
// IPropertyViewManager Members // <summary> // Add a property into the correct category within the specified CategoryList. // </summary> // <param name="propertySet">Specified property (passed in as a set for multi-select scenarios)</param> // <param name="propertyName">Name of the current property (perf optimization)</param> // <param name="categoryList">CategoryList instance to populate</param> // <returns>Wrapped ModelPropertyEntry for the specified propertySet</returns> public ModelPropertyEntry AddProperty(IEnumerable <ModelProperty> propertySet, string propertyName, CategoryList categoryList) { string categoryName = GetCategoryName(propertySet); ModelCategoryEntry category = categoryList.FindCategory(categoryName) as ModelCategoryEntry; bool reuseEntries = ExtensibilityAccessor.IsEditorReusable(propertySet); if (reuseEntries && category != null) { ModelPropertyEntry foundProperty; if ((foundProperty = (ModelPropertyEntry)category[propertyName]) != null) { if (foundProperty.PropertyType != null && foundProperty.PropertyType.Equals(System.Activities.Presentation.Internal.PropertyEditing.Model.ModelUtilities.GetPropertyType(propertySet))) { // Found a match for the property, so reuse it bool oldIsBrowsable = foundProperty.IsBrowsable; bool oldIsAdvanced = foundProperty.IsAdvanced; foundProperty.SetUnderlyingModelProperty(propertySet); // If the IsBrowsable or IsAdvanced value of the property changed, // refresh the property within the category, because how and whether // this property should be rendered may have changed. // Note that refreshing a selected property also nullifies its stickiness // (ie. it resets CategoryList.PropertySelectionMode) if (oldIsAdvanced != foundProperty.IsAdvanced || oldIsBrowsable != foundProperty.IsBrowsable) { category.Refresh(foundProperty, category.GetBucket(foundProperty), this.PropertyComparer); } return(foundProperty); } } } if (category == null) { category = new ModelCategoryEntry(categoryName); categoryList.InsertAlphabetically(category); } ModelPropertyEntry property = new ModelPropertyEntry(propertySet, null); category.Add(property, category.GetBucket(property), this.PropertyComparer); return(property); }
public void LoadTModels( ) { FindTModel ft = new FindTModel(); ft.CategoryBag.Add(CommonCanonical.UddiOrgTypes, "categorization", "Categorization (taxonomy)"); TModelList list = null; try { list = ft.Send(_connection); } catch (Exception e) { MessageBox.Show(this, e.Message, @"Error loading Category Tree", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (null == list) { MessageBox.Show(this, @"An unknown error occurred while loading the Category Tree.", @"Error loading Category Tree", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } GetRelatedCategories grc = new GetRelatedCategories(); Category c = new Category(); c.RelationshipQualifiers.Add(RelationshipQualifier.root); foreach (TModelInfo info in list.TModelInfos) { bool categorization = false; c.TModelKey = info.TModelKey; grc.Categories.Add(c); CategoryList cl = null; try { cl = grc.Send(_connection); categorization = true; } catch (InvalidKeyPassedException) { // // tModel doesn't represent a categorization. So, don't show // it in the tree. // } catch (Exception e) { // // if anything else happened, re-throw & let the app deal with it. // throw e; } if (categorization) { // // Create a new node and wrap the tModelInfo into a // CategoryInfo object. // CategoryTreeNode catnode = new CategoryTreeNode(new CategoryInfo(info.TModelKey)); catnode.Nodes.Clear(); // // Set the Text of the node to the text of the tModel. // catnode.Text = info.Name.Text; CategoryValueCollection values = cl.CategoryInfos[0].Roots; foreach (CategoryValue val in values) { CategoryTreeNode subnode = new CategoryTreeNode(val); subnode.CategoryValue.TModelKey = catnode.CategoryValue.TModelKey; catnode.Nodes.Add(subnode); } catnode.HasDownloadedChildren = true; // // Add the node to the root. // Nodes.Add(catnode); } } }
// GET: Categories public ActionResult Index() { CategoryList list = this.categoryService.CategoryList(db.Categories.ToList()); return(View(list.Categories)); }
public void ShouldSimplifyTransparentIdentifierParameters() { using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { var categories = Enumerable.Range(0, 10) .Select(x => { var category = new Category { Name = $"Category {x}" }; session.Store(category); return(category); }) .ToList(); var categoryList = new CategoryList { Categories = categories }; session.Store(categoryList); var orderItems = categories .Select(x => new OrderItem { CategoryId = x.Id }) .ToList(); var order = new Order { CategoryListId = categoryList.Id, OrderItems = orderItems }; session.Store(order); session.SaveChanges(); } using (var session = store.OpenSession()) { var queryable = from o in session.Query <Order>() let categoryList = RavenQuery.Load <CategoryList>(o.CategoryListId) select new OrderProjection { Id = o.Id, Items = from i in o.OrderItems let cat = categoryList.Categories let id = i.CategoryId let first = cat.FirstOrDefault(x => x.Id == id) let name = first.Name select new OrderItemProjection { CategoryName = name } }; Assert.Equal("from 'Orders' as o load o.CategoryListId as categoryList " + "select { Id : id(o), Items : o.OrderItems" + ".map(function(i){return {i:i,cat:categoryList.Categories};})" + ".map(function(__rvn0){return {__rvn0:__rvn0,id:__rvn0.i.CategoryId};})" + ".map(function(__rvn1){return {__rvn1:__rvn1,first:__rvn1.__rvn0.cat.find(function(x){return id(x)===__rvn1.id;})};})" + ".map(function(__rvn2){return {__rvn2:__rvn2,name:__rvn2.first.Name};})" + ".map(function(__rvn3){return {CategoryName:__rvn3.name};}) }" , queryable.ToString()); var result = queryable.ToList(); Assert.NotNull(result); var items = result[0].Items.ToList(); Assert.Equal(10, items.Count); for (var i = 0; i < 10; i++) { Assert.Equal($"Category {i}", items[i].CategoryName); } } } }
private void UnhookEvents(CategoryList categoryList) { if (categoryList == null) { Debug.Fail("This method shouldn't be called when there is no CategoryList instance to process."); return; } categoryList.ContainerGenerated -= new ContainerGeneratedHandler(OnCategoryContainerGenerated); }
public ClonedContentProvider(PageReference cloneRoot, PageReference entryRoot, CategoryList categoryFilter) { if (cloneRoot.CompareToIgnoreWorkID(entryRoot)) { throw new NotSupportedException("Entry root and clone root cannot be set to the same content reference"); } if (ServiceLocator.Current.GetInstance <IContentLoader>().GetChildren <IContent>(entryRoot).Any()) { throw new NotSupportedException("Unable to create ClonedContentProvider, the EntryRoot property must point to leaf content (without children)"); } CloneRoot = cloneRoot; EntryRoot = entryRoot; Category = categoryFilter; // Set the entry point parameter Parameters.Add(ContentProviderElement.EntryPointString, EntryRoot.ID.ToString(CultureInfo.InvariantCulture)); }
public IEnumerable <CategoryItem> Get(int page) { return(CategoryList.Items(this.db, GetProfile().Id)); }
/// <summary> /// Send a CategorySelectedMessage /// </summary> /// <param name="selectedCategory"></param> private void SelectCategory(string selectedCategory) { SelectedCategory = CategoryList.FirstOrDefault(x => x == selectedCategory); Messenger.Default.Send(new CategorySelectedMessage(this, SelectedCategory)); }
/// <summary> /// Сохранить категории /// </summary> public void SaveCategories(CategoryList categories) { long timeStamp = DateTime.Now.ToUniversalTime().ToBinary(); var xs = new XmlSerializer(typeof(CategoryList)); var sb = new StringBuilder(); var w = new StringWriter(sb, CultureInfo.InvariantCulture); xs.Serialize(w, categories, new XmlSerializerNamespaces(new[] { new XmlQualifiedName(string.Empty) })); string categories_xml = sb.ToString(); if (!string.IsNullOrEmpty(categories_xml)) { lock (_locker) { using (SQLiteCommand cmd = new SQLiteCommand("", conn)) { try { if (ds != null) ds.Dispose(); ds = new DataSet(); da = new SQLiteDataAdapter(); string sql = string.Format("select * from categories"); cmd.CommandText = sql; da.SelectCommand = cmd; var cb = new System.Data.SQLite.SQLiteCommandBuilder(da); da.Fill(ds, "categories"); // исправляем свой косяк, надо было изначально ID сделать, иначе SQLite без праймари ки ругается на датасет // это чтобы не перегенерировать БД if (!ds.Tables["categories"].Columns.Contains("id")) { // убьем таблицу категорий cmd.CommandText = "DROP TABLE categories"; cmd.ExecuteNonQuery(); // создаем таблицу категорий. Данных там мало и чтобы не мудохаться все храним в одной записи-строке sql = "create table categories(" + "id varchar PRIMARY KEY ,categories_xml text, stamp bigint)"; cmd.CommandText = sql; cmd.ExecuteNonQuery(); // формируем датасет и дальше уже пишем данные ds = new DataSet(); da = new SQLiteDataAdapter(); sql = string.Format("select * from categories"); cmd.CommandText = sql; da.SelectCommand = cmd; cb = new System.Data.SQLite.SQLiteCommandBuilder(da); da.Fill(ds, "categories"); MainWindow.MainForm.GetLogger().Add( "Перегенерировали таблицу категорий (исправление некорректности)."); } if (ds.Tables["categories"].Rows.Count == 0) { DataRow dr = ds.Tables["categories"].NewRow(); dr["id"] = 1; dr["categories_xml"] = categories_xml; dr["stamp"] = timeStamp; ds.Tables["categories"].Rows.Add(dr); } else { ds.Tables["categories"].Rows[0]["categories_xml"] = categories_xml; ds.Tables["categories"].Rows[0]["stamp"] = timeStamp; } da.Update(ds.Tables["categories"]); } catch (Exception ex) { MainWindow.MainForm.GetLogger().Add("Ошибка записи категорий в БД: " + ex.Message); } } } } }
private async Task OnTextChangedCommand() { if (!string.IsNullOrEmpty(SearchText)) { Pins.Clear(); var Text = SearchText.ToLower(); var PinModels = (await _pinService.GetPinsAsync(App.CurrentUserId)) .Where(x => x.IsFavorite == true && (x.Name.ToLower().Contains(Text) || x.Description.ToLower().Contains(Text) || x.Latitude.ToString().Contains(Text) || x.Longtitude.ToString().Contains(Text))); if (PinModels != null) { var Filter = CategoryList.Where(x => x.IsSelected == true); var categoryFilter = new List <int>(); foreach (var category in Filter) { categoryFilter.Add(category.ID); } if (categoryFilter.Count != 0) { var pins = PinModels.Where(x => categoryFilter.Contains(x.CategoryID)); foreach (PinModel model in pins) { Pins.Add(model.ToPin()); } } else { foreach (PinModel model in PinModels) { Pins.Add(model.ToPin()); } } } } else { Pins.Clear(); var PinModels = await _pinService.GetPinsAsync(App.CurrentUserId); if (PinModels != null) { var Filter = CategoryList.Where(x => x.IsSelected == true); var categoryFilter = new List <int>(); foreach (var category in Filter) { categoryFilter.Add(category.ID); } if (categoryFilter.Count != 0) { var pinModels = PinModels.Where(x => categoryFilter.Contains(x.CategoryID)); foreach (PinModel model in pinModels) { Pins.Add(model.ToPin()); } } else { await LoadPinsFromDataBase(); } } } }
public BlogServer(BlogServerOptions options) { if (options == null) { throw new System.ArgumentNullException("options"); } this.Options = options; CreateFolderSafe(this.Options.OutputFolder); // Initialize the log string logfilename = GetLogFilename(); Console.WriteLine("Log at: {0}", logfilename); if (this.Options.OverwriteLog) { LogStream = System.IO.File.CreateText(logfilename); } else { LogStream = System.IO.File.AppendText(logfilename); } LogStream.AutoFlush = true; this.WriteLog("----------------------------------------"); this.WriteLog("Start New Server Session "); this.WriteLog("----------------------------------------"); this.HostName = Environment.MachineName.ToLower(); // The Primary url is what will normally be used // However the server supports using localhost as well this.ServerUrlPrimary = string.Format("http://{0}:{1}/", HostName, this.Options.Port); this.ServerUrlSecondary = string.Format("http://{0}:{1}/", "localhost", this.Options.Port); this.WriteLog("Primary Url: {0}", this.ServerUrlPrimary); this.WriteLog("Secondary Url: {0}", this.ServerUrlSecondary); // The title of the blog will be based on the class name this.BlogTitle = "Untitled Blog"; // This server will contain a single user var adminuser = new BlogUser { Name = "admin", Password = "******" }; // Setup Collections this.BlogList = new List<UserBlogInfo>(); this.BlogUsers = new List<BlogUser>(); this.PostList = new PostList(); this.MediaObjectList = new MediaObjectList(); this.CategoryList = new CategoryList(); this.BlogUsers.Add(adminuser); // This server will contain a single blog this.BlogList.Add(new UserBlogInfo(adminuser.Name, this.ServerUrlPrimary, this.BlogTitle)); // Add Placeholder Content if (this.Options.CreateSampleContent && this.PostList.Count < 1) { if (this.CategoryList.Count < 1) { this.CategoryList.Add("0", "sports"); this.CategoryList.Add("0", "biology"); this.CategoryList.Add("0", "office supplies"); this.CategoryList.Add("0", "food"); this.CategoryList.Add("0", "tech"); } var cats1 = new[] {"sports","biology", "office supplies"}; var cats2 = new[] {"food"}; var cats3 = new[] {"food" }; var cats4 = new[] {"biology"}; string lipsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; this.PostList.Add(new System.DateTime(2012, 12, 2), "1000 Amazing Uses for Staples", lipsum, cats1, true); this.PostList.Add(new System.DateTime(2012, 1, 15), "Why Pizza is Great", lipsum, cats2, true); this.PostList.Add(new System.DateTime(2013, 4, 10), "Sandwiches I have loved", lipsum, cats3, true); this.PostList.Add(new System.DateTime(2013, 3, 31), "Useful Things You Can Do With a Giraffe", lipsum, cats4, true); } this.HttpListener = new System.Net.HttpListener(); }
public bool ContainsCategory(String category) { return(CategoryList.Contains(category)); }
/// <summary> /// Сохранить категории /// </summary> public void SaveCategories(CategoryList categories) { if (server == null) return; try { using (IObjectContainer documentStore = server.OpenClient()) { foreach (var category in categories) { if (category == null) continue; var _category = documentStore.Query<Category>(x => x!=null && x.Name == category.Name).FirstOrDefault(); if (_category != null) { _category.Name = category.Name; documentStore.Delete(_category); documentStore.Store(_category); } else documentStore.Store(category); } documentStore.Commit(); } } catch (Exception ex) { MessageBox.Show("Ошибка записи категорий в БД." + ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } }
public void AddCategory(String category) { CategoryObjList[category] = new Category(category); CategoryList.Add(category); Sort(); }
/// <summary> /// Not used in Designer. Check to make changes manually and that unparameterized controls match /// </summary> private void InitializeComponent(CategoryList categories) { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.PriceTB = new System.Windows.Forms.TextBox(); this.DescTB = new System.Windows.Forms.TextBox(); this.CatePicker = new System.Windows.Forms.ComboBox(); this.DateTimePicker = new System.Windows.Forms.DateTimePicker(); this.CreateButt = new System.Windows.Forms.Button(); this.cbRevenue = new System.Windows.Forms.CheckBox(); this.cbExpense = new System.Windows.Forms.CheckBox(); this.lblError = new System.Windows.Forms.Label(); this.AutoCheck = new System.Windows.Forms.CheckBox(); this.FrequencyLb = new System.Windows.Forms.Label(); this.FreqCB = new System.Windows.Forms.ComboBox(); this.AutomaticError = new System.Windows.Forms.Label(); this.DateErr = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(25, 13); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(46, 19); this.label1.TabIndex = 0; this.label1.Text = "Price"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(192, 12); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(93, 19); this.label2.TabIndex = 1; this.label2.Text = "Description"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(28, 78); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(79, 19); this.label3.TabIndex = 2; this.label3.Text = "Category"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(192, 78); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(116, 19); this.label4.TabIndex = 3; this.label4.Text = "Time and Date"; // // PriceTB // this.PriceTB.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.PriceTB.Location = new System.Drawing.Point(28, 47); this.PriceTB.Name = "PriceTB"; this.PriceTB.Size = new System.Drawing.Size(100, 26); this.PriceTB.TabIndex = 4; // // DescTB // this.DescTB.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.DescTB.Location = new System.Drawing.Point(195, 47); this.DescTB.Name = "DescTB"; this.DescTB.Size = new System.Drawing.Size(294, 26); this.DescTB.TabIndex = 5; // // CatePicker // this.CatePicker.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.CatePicker.FormattingEnabled = true; this.CatePicker.Location = new System.Drawing.Point(28, 111); this.CatePicker.Name = "CatePicker"; this.CatePicker.Size = new System.Drawing.Size(148, 27); this.CatePicker.TabIndex = 6; // // DateTimePicker // this.DateTimePicker.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.DateTimePicker.Location = new System.Drawing.Point(195, 111); this.DateTimePicker.Name = "DateTimePicker"; this.DateTimePicker.Size = new System.Drawing.Size(294, 26); this.DateTimePicker.TabIndex = 7; // // CreateButt // this.CreateButt.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.CreateButt.Location = new System.Drawing.Point(83, 212); this.CreateButt.Name = "CreateButt"; this.CreateButt.Size = new System.Drawing.Size(169, 55); this.CreateButt.TabIndex = 8; this.CreateButt.Text = "Create!"; this.CreateButt.UseVisualStyleBackColor = true; this.CreateButt.Click += new System.EventHandler(this.CreateButt_Click_1); // // cbRevenue // this.cbRevenue.AutoSize = true; this.cbRevenue.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cbRevenue.Location = new System.Drawing.Point(28, 180); this.cbRevenue.Name = "cbRevenue"; this.cbRevenue.Size = new System.Drawing.Size(92, 23); this.cbRevenue.TabIndex = 9; this.cbRevenue.Text = "Revenue"; this.cbRevenue.UseVisualStyleBackColor = true; // // cbExpense // this.cbExpense.AutoSize = true; this.cbExpense.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cbExpense.Location = new System.Drawing.Point(28, 157); this.cbExpense.Name = "cbExpense"; this.cbExpense.Size = new System.Drawing.Size(91, 23); this.cbExpense.TabIndex = 10; this.cbExpense.Text = "Expense"; this.cbExpense.UseVisualStyleBackColor = true; // // lblError // this.lblError.AutoSize = true; this.lblError.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblError.ForeColor = System.Drawing.Color.Red; this.lblError.Location = new System.Drawing.Point(79, 270); this.lblError.Name = "lblError"; this.lblError.Size = new System.Drawing.Size(253, 19); this.lblError.TabIndex = 11; this.lblError.Text = "Check either expense or addition"; this.lblError.Visible = false; // // AutoCheck // this.AutoCheck.AutoSize = true; this.AutoCheck.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.AutoCheck.Location = new System.Drawing.Point(310, 161); this.AutoCheck.Name = "AutoCheck"; this.AutoCheck.Size = new System.Drawing.Size(95, 23); this.AutoCheck.TabIndex = 12; this.AutoCheck.Text = "Repeats?"; this.AutoCheck.UseVisualStyleBackColor = true; this.AutoCheck.CheckedChanged += new System.EventHandler(this.AutoCheck_CheckedChanged); // // FrequencyLb // this.FrequencyLb.AutoSize = true; this.FrequencyLb.Enabled = false; this.FrequencyLb.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FrequencyLb.Location = new System.Drawing.Point(307, 187); this.FrequencyLb.Name = "FrequencyLb"; this.FrequencyLb.Size = new System.Drawing.Size(88, 19); this.FrequencyLb.TabIndex = 13; this.FrequencyLb.Text = "Frequency"; // // FreqCB // this.FreqCB.Enabled = false; this.FreqCB.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FreqCB.FormattingEnabled = true; this.FreqCB.Items.AddRange(new object[] { "1 - Everyday", "2 - Every Other day", "3 - Every Week", "4 - Every two weeks", "5 - Every Month", "6 - Every 6 Months", "7 - Every Year" }); this.FreqCB.Location = new System.Drawing.Point(310, 209); this.FreqCB.Name = "FreqCB"; this.FreqCB.Size = new System.Drawing.Size(179, 27); this.FreqCB.TabIndex = 14; // // AutomaticError // this.AutomaticError.AutoSize = true; this.AutomaticError.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.AutomaticError.ForeColor = System.Drawing.Color.Red; this.AutomaticError.Location = new System.Drawing.Point(79, 289); this.AutomaticError.Name = "AutomaticError"; this.AutomaticError.Size = new System.Drawing.Size(194, 19); this.AutomaticError.TabIndex = 15; this.AutomaticError.Text = "Please select a frequency"; this.AutomaticError.Visible = false; // // DateErr // this.DateErr.AutoSize = true; this.DateErr.Font = new System.Drawing.Font("Rockwell", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.DateErr.ForeColor = System.Drawing.Color.Red; this.DateErr.Location = new System.Drawing.Point(79, 308); this.DateErr.Name = "DateErr"; this.DateErr.Size = new System.Drawing.Size(225, 19); this.DateErr.TabIndex = 16; this.DateErr.Text = "The date cannot before today"; this.DateErr.Visible = false; // // TransactionForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.GradientActiveCaption; this.ClientSize = new System.Drawing.Size(619, 339); this.Controls.Add(this.lblError); this.Controls.Add(this.cbExpense); this.Controls.Add(this.cbRevenue); this.Controls.Add(this.CreateButt); this.Controls.Add(this.DateTimePicker); this.Controls.Add(this.CatePicker); this.Controls.Add(this.DescTB); this.Controls.Add(this.PriceTB); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.AutoCheck); this.Controls.Add(this.FrequencyLb); this.Controls.Add(this.FreqCB); this.Controls.Add(this.DateErr); this.Controls.Add(this.AutomaticError); this.MinimumSize = new System.Drawing.Size(635, 378); this.Name = "TransactionForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "New Transaction"; this.ResumeLayout(false); this.PerformLayout(); }
public void Sort() { CategoryList.Sort(); }
private async void LoadCachedCategories(Action<CategoryList, Exception> callback) { var retVal = new CategoryList(); try { foreach (var item in await StorageUtility.ListItems(STATIC_CATEGORY_FOLDER, App.Instance.User.UserName)) { var staticType = await StorageUtility.RestoreItem<Category>(STATIC_CATEGORY_FOLDER, item, App.Instance.User.UserName); CategoryList.Add(staticType); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); //callback(null, ex); } //SetupTypeCategoryData(retVal, false); //CategoryList = retVal; callback(CategoryList, null); }
protected void Page_Load(object sender, EventArgs e) { LiHyperLink.SetNameToCompare(Context, "UserManagement"); string role = DecodeFromQS("role"); if (!Page.IsPostBack) { SetupTogglePermissionsScript(read, edit, publish, read, "read"); SetupTogglePermissionsScript(read, edit, publish, edit, "edit"); SetupTogglePermissionsScript(read, edit, publish, publish, "publish"); SetupTogglePermissionsScript(readRolePermission, editRolePermission, publishRolePermission, readRolePermission, "read"); SetupTogglePermissionsScript(readRolePermission, editRolePermission, publishRolePermission, editRolePermission, "edit"); SetupTogglePermissionsScript(readRolePermission, editRolePermission, publishRolePermission, publishRolePermission, "publish"); if (!String.IsNullOrEmpty(role)) { RolePermissionsCollection rpc = RolePermissionManager.GetRolePermissions(); RolePermissions rp = rpc.Find( delegate(RolePermissions rper) { return(rper.RoleName.ToLower() == role.ToLower()); }); if (rp != null) { readRolePermission.Checked = rp.HasRead; editRolePermission.Checked = rp.HasEdit; publishRolePermission.Checked = rp.HasPublish; } } } if (role != null) { string encodedRoleName = HttpUtility.HtmlEncode(role); if (!IsPostBack) { if (Request.QueryString["new"] != null) { Message.Text = string.Format("The role <strong>{0}</strong> was created.", encodedRoleName); Message.Type = StatusType.Success; } litExistingRoleName.Text = encodedRoleName; PageText.Text = "Update " + encodedRoleName; CategoryList.DataSource = new CategoryController().GetAllCachedCategories(); CategoryList.DataBind(); } new_role_container.Visible = false; Role_List.Visible = false; role_edit_form.Visible = true; } else { if (!Page.IsPostBack) { RolePermissionsCollection rps = RolePermissionManager.GetRolePermissions(); rps.Sort( delegate(RolePermissions rp1, RolePermissions rp2) { return(Comparer <string> .Default.Compare(rp1.RoleName, rp2.RoleName)); }); // move everyone to the top RolePermissionsCollection rpss = new RolePermissionsCollection(); foreach (RolePermissions rp in rps) { if (rp.RoleName == GraffitiUsers.EveryoneRole) { rpss.Insert(0, rp); } } foreach (RolePermissions rp in rps) { if (rp.RoleName != GraffitiUsers.EveryoneRole) { rpss.Add(rp); } } Role_List.DataSource = rpss; Role_List.DataBind(); if (Request.QueryString["roleSaved"] != null) { string roleSaved = HttpUtility.UrlDecode(Request.QueryString["roleSaved"]); Message.Text = string.Format("The role <strong>{0}</strong> was updated.", roleSaved); Message.Type = StatusType.Success; } } new_role_container.Visible = true; role_edit_form.Visible = false; Role_List.Visible = true; } }
public void RemoveCategory(Category cat) { CategoryList.Remove(cat); }
private void OnCategoryCreated(object obj) { CategoryList.Add(client.AddCategory(NewCategoryName)); NewCategoryName = string.Empty; NotifyPropertyChanged("NewCategoryName"); }
// ISelectionPathInterpreter Members public DependencyObject ResolveSelectionPath(CategoryList root, SelectionPath path, out bool pendingGeneration) { pendingGeneration = false; if (path == null || !string.Equals(PathTypeId, path.PathTypeId)) { Debug.Fail("Invalid SelectionPath specified."); return null; } if (root == null) { Debug.Fail("No CategoryList specified."); return null; } string[] pathValues = path.Path.Split(','); if (pathValues.Length < 1) { Debug.Fail("Invalid SelectionPath specified."); return null; } // // Note: By the time this method gets called, all the visuals should have been expanded // and rendered. Hence, if we can't find a visual in the visual tree, it doesn't exist // and we shouldn't worry about trying to expand some parent visual and waiting for it // to render. // ModelCategoryEntry parentCategory; PropertyEntry currentProperty = root.FindPropertyEntry(PersistedStateUtilities.Unescape(pathValues[0]), out parentCategory); PropertyContainer currentContainer = root.FindPropertyEntryVisual(currentProperty, parentCategory, out pendingGeneration); DependencyObject lastFoundContainer = currentContainer; int pathIndex = 1; while (currentContainer != null && pathIndex < pathValues.Length) { SubPropertyEditor subPropertyEditor = VisualTreeUtils.GetTemplateChild<SubPropertyEditor>(currentContainer); if (subPropertyEditor == null) { break; } // If the subpropertyEditor is not expanded and is expandable, we won't be able to get the target property's visual // element, Expand it, set pendingGeneration to True, and return null. Expect the caller to call again. if (subPropertyEditor.IsExpandable && !subPropertyEditor.IsExpanded) { subPropertyEditor.IsExpanded = true; pendingGeneration = true; return null; } PropertyEntry property = subPropertyEditor.FindSubPropertyEntry(PersistedStateUtilities.Unescape(pathValues[pathIndex])); if (property == null) { break; } currentContainer = subPropertyEditor.FindSubPropertyEntryVisual(property); lastFoundContainer = currentContainer ?? lastFoundContainer; pathIndex++; } if (lastFoundContainer == null) { return null; } return lastFoundContainer; }
/// <summary> /// Parse a bukget plugin from the json result /// </summary> /// <param name="jsonCode"></param> /// <returns></returns> public BukgetPlugin(string jsonCode) { InitFields(); if (string.IsNullOrEmpty(jsonCode)) { throw new FormatException("Invalid JSON supplied: string is empty"); } if (Equals(jsonCode, "[]")) { throw new FormatException("Invalid JSON supplied: array is empty"); } // Load the string into a json object JsonObject json; // In case of an array, load the first entry try { if (jsonCode.StartsWith("[")) { json = (JsonObject)JsonConvert.Import <JsonArray>(jsonCode)[0]; } else { json = JsonConvert.Import <JsonObject>(jsonCode); } } catch (Exception exception) { throw new FormatException("Invalid JSON supplied: " + exception); } if (json["main"] != null) { Main = (string)json["main"]; } if (json["plugin_name"] != null) { Name = (string)json["plugin_name"]; } // If no name or mainspace, return if (string.IsNullOrEmpty(Main) || string.IsNullOrEmpty(Name)) { return; } Logger.Log(LogLevel.Info, "BukGetAPI", "parsing plugin:" + Name, Main); // Slug if (json["slug"] != null) { Slug = (String)json["slug"]; } // Description if (json["description"] != null) { Description = (String)json["description"]; } // BukkitDev link if (json["dbo_page"] != null) { BukkitDevLink = (String)json["dbo_page"]; } // Website if (json["link"] != null) { Website = (String)json["link"]; } // Stage if (json["stage"] != null) { try { Status = (PluginStatus)Enum.Parse(typeof(PluginStatus), json["stage"].ToString()); } catch (Exception e) { Logger.Log(LogLevel.Warning, "BukgetV3", "Couldn't parse plugin status", e.Message); } } // Authors AuthorsList = JsonParser.ParseJsonStringList(json["authors"]); // Categories // load strings List <String> categories = JsonParser.ParseJsonStringList(json["categories"]); // convert to enum values foreach (string category in categories) { CategoryList.Add((PluginCategory)Enum.Parse(typeof(PluginCategory), category)); } // Versions IEnumerable <JsonObject> versions = JsonParser.ParseJsonObjectList(json["versions"]); foreach (JsonObject jsonObject in versions) { BukgetPluginVersion v = new BukgetPluginVersion(this, jsonObject.ToString()); if (v.VersionNumber != null) { VersionsList.Add(v); } } LastParsedPlugin = this; }
// ISelectionPathInterpreter Members public DependencyObject ResolveSelectionPath(CategoryList root, SelectionPath path, out bool pendingGeneration) { pendingGeneration = false; if (path == null || !string.Equals(PathTypeId, path.PathTypeId)) { Debug.Fail("Invalid SelectionPath specified."); return(null); } if (root == null) { Debug.Fail("No CategoryList specified."); return(null); } string[] pathValues = path.Path.Split(','); if (pathValues.Length < 1) { Debug.Fail("Invalid SelectionPath specified."); return(null); } // // Note: By the time this method gets called, all the visuals should have been expanded // and rendered. Hence, if we can't find a visual in the visual tree, it doesn't exist // and we shouldn't worry about trying to expand some parent visual and waiting for it // to render. // ModelCategoryEntry parentCategory; PropertyEntry currentProperty = root.FindPropertyEntry(PersistedStateUtilities.Unescape(pathValues[0]), out parentCategory); PropertyContainer currentContainer = root.FindPropertyEntryVisual(currentProperty, parentCategory, out pendingGeneration); DependencyObject lastFoundContainer = currentContainer; int pathIndex = 1; while (currentContainer != null && pathIndex < pathValues.Length) { SubPropertyEditor subPropertyEditor = VisualTreeUtils.GetTemplateChild <SubPropertyEditor>(currentContainer); if (subPropertyEditor == null) { break; } // If the subpropertyEditor is not expanded and is expandable, we won't be able to get the target property's visual // element, Expand it, set pendingGeneration to True, and return null. Expect the caller to call again. if (subPropertyEditor.IsExpandable && !subPropertyEditor.IsExpanded) { subPropertyEditor.IsExpanded = true; pendingGeneration = true; return(null); } PropertyEntry property = subPropertyEditor.FindSubPropertyEntry(PersistedStateUtilities.Unescape(pathValues[pathIndex])); if (property == null) { break; } currentContainer = subPropertyEditor.FindSubPropertyEntryVisual(property); lastFoundContainer = currentContainer ?? lastFoundContainer; pathIndex++; } if (lastFoundContainer == null) { return(null); } return(lastFoundContainer); }
/// <summary> /// Adds the provider. /// </summary> /// <param name="root">The root.</param> /// <param name="entryPoint">The entry point.</param> /// <param name="providerName">Name of the provider.</param> /// <param name="categoryList">The category list.</param> /// <returns> /// <c>true</c> if [the provider has been attached]; otherwise, <c>false</c>. /// </returns> /// <exception cref="System.InvalidOperationException">Content provider for this node already attached. /// or /// Content provider with same name already attached.</exception> public static bool AddProvider(int root, int entryPoint, string providerName, CategoryList categoryList) { string name = string.Format(CultureInfo.InvariantCulture, "{0}-ClonedContent-{1}-{2}", providerName, root, entryPoint); IQueryable <ClonedContentProviderSettings> providerCollection = SettingsRepository.Instance.GetAll().AsQueryable(); if (providerCollection.Count(pc => pc.EntryPoint.Equals(entryPoint)) > 0) { // A provider is already attached to this node. throw new InvalidOperationException("Content provider for this node already attached."); } if (providerCollection.Count(pc => pc.Name.Equals(name)) > 0) { // A provider with the same name already exists. throw new InvalidOperationException("Content provider with same name already attached."); } CategoryList categories = categoryList ?? new CategoryList(); ClonedContentProvider provider = new ClonedContentProvider( name, new PageReference(root), new PageReference(entryPoint), categories); IContentProviderManager providerManager = ServiceLocator.Current.GetInstance <IContentProviderManager>(); ClonedContentProviderSettings contentProviderSettings = new ClonedContentProviderSettings { Name = name, EntryPoint = entryPoint, Root = root, CategoryList = string.Join( ",", categories) }; providerManager.ProviderMap.AddProvider(provider); SettingsRepository.Instance.SaveSettings(contentProviderSettings); CacheManager.Clear(); return(true); }
// <summary> // Returns a SelectionPath pointing to the first visible property // in the list or null if no such property exists. // </summary> // <param name="categoryList">CategoryList for reference</param> // <returns>SelectionPath pointing to the first visible property // in the list or null if no such property exists.</returns> public SelectionPath GetDefaultSelectionPath(CategoryList categoryList) { if (categoryList.Count > 0) { CategoryEntry firstCategory = categoryList[0]; if (firstCategory != null) { foreach (ModelPropertyEntry firstProperty in firstCategory.Properties) { if (firstProperty != null && firstProperty.IsBrowsable && firstProperty.MatchesFilter) { return PropertySelectionPathInterpreter.Instance.ConstructSelectionPath(firstProperty); } } } } return null; }
private void button8_Click(object sender, EventArgs e) { CategoryList cl = new CategoryList(); cl.ShowDialog(); }
/// <summary> /// Loads the provider. /// </summary> /// <returns> /// [true] if the provider has been loaded. /// </returns> private static bool LoadProviders() { IContentProviderManager providerManager = ServiceLocator.Current.GetInstance<IContentProviderManager>(); Collection<ClonedContentProviderSettings> providerCollection = SettingsRepository.Instance.GetAll(); foreach (ClonedContentProviderSettings providerSettings in providerCollection) { try { ContentProvider contentProvider = providerManager.GetProvider(providerSettings.Name); if (contentProvider != null) { continue; } CategoryList categoryList = new CategoryList( providerSettings.CategoryList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray()); ClonedContentProvider provider = new ClonedContentProvider( providerSettings.Name, new PageReference(providerSettings.Root), new PageReference(providerSettings.EntryPoint), categoryList); providerManager.ProviderMap.AddProvider(provider); } catch (ArgumentNullException) { return false; } catch (ArgumentException) { return false; } catch (NotSupportedException) { return false; } } return true; }
/// <summary> /// returns the first category in a CategoryList /// </summary> /// <param name="categoryList"></param> /// <returns></returns> public static Category GetFirst(this CategoryList categoryList) { return(categoryList.GetCategories().FirstOrDefault()); }
public static EmailSignature GetSignature(string responsePath, ref bool isHTML) { Pointel.Logger.Core.ILog _logger = Pointel.Logger.Core.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "AID"); //string responseContent = string.Empty; EmailSignature emailSignature = new EmailSignature(); try { if (responsePath.StartsWith("response")) { responsePath = responsePath.Substring(("response:").Length); List <string> path = responsePath.Split('\\').ToList <string>(); OutputValues outputMsg = Pointel.Interactions.Contact.Core.Request.RequestGetAllResponse.GetResponseContent(ConfigContainer.Instance().TenantDbId); if (outputMsg.IContactMessage != null) { CategoryList categoryList = null; EventGetAllCategories eventGetAllCategories = (EventGetAllCategories)outputMsg.IContactMessage; _logger.Info("AllCatageories " + eventGetAllCategories.SRLContent.ToString()); categoryList = eventGetAllCategories.SRLContent; if (categoryList != null) { StandardResponse response = GetResponseCategories(categoryList, path); if (response == null) { return(null); } //responseContent = string.Empty; // responseContent = !string.IsNullOrEmpty(response.StructuredBody) ? response.StructuredBody : !string.IsNullOrEmpty(response.Body) ? response.Body : string.Empty; emailSignature.EmailBody = !string.IsNullOrEmpty(response.StructuredBody) ? response.StructuredBody : !string.IsNullOrEmpty(response.Body) ? response.Body : string.Empty; isHTML = !string.IsNullOrEmpty(response.StructuredBody); emailSignature.Subject = string.IsNullOrEmpty(response.Subject) ? null : response.Subject; if (response.Attachments != null) { emailSignature.AttachmentList = response.Attachments; } } //LoadResponses(categoryList); } } else if (responsePath.StartsWith("file")) { responsePath = responsePath.Substring(("file:").Length); if (File.Exists(responsePath)) { try { using (StreamReader sr = new StreamReader(responsePath)) { //responseContent = sr.ReadToEnd(); emailSignature.EmailBody = sr.ReadToEnd(); } } catch (Exception ex) { //responseContent = string.Empty; emailSignature.EmailBody = string.Empty; } } else { //responseContent = string.Empty; emailSignature.EmailBody = string.Empty; } } } catch (Exception ex) { _logger.Error("Error occurred as " + ex.Message); } finally { _logger = null; } //return responseContent.Trim(); return(emailSignature); }
private void CategorySave_Button_Click(object sender, RoutedEventArgs e) { try { if (creating == false) { var str2 = Formats_TextBox.Text.Split('.'); CategoryList[indexIn].Formats.Clear(); foreach (string s in str2) { if (s != "") { if (s.EndsWith("; ")) { CategoryList[indexIn].Formats.Add(s.Remove(s.Length - 2).Insert(0, ".")); } else if (s.EndsWith(";")) { CategoryList[indexIn].Formats.Add(s.Remove(s.Length - 1).Insert(0, ".")); } else { CategoryList[indexIn].Formats.Add(s.Insert(0, ".")); } } } } else { CategoryClass newCategory = new CategoryClass(Name_TextBox.Text, new ObservableCollection <string>()); var str2 = Formats_TextBox.Text.Split('.'); foreach (string s in str2) { if (s != "") { if (s.EndsWith("; ")) { newCategory.Formats.Add(s.Remove(s.Length - 2).Insert(0, ".")); } else if (s.EndsWith(";")) { newCategory.Formats.Add(s.Remove(s.Length - 1).Insert(0, ".")); } else { newCategory.Formats.Add(s.Insert(0, ".")); } } } CategoryList.Add(newCategory); } JSP.Categories = CategoryList; JSP.FileExceptions = FileException; JsonSerializer serializer = new JsonSerializer(); using (StreamWriter sw = new StreamWriter($@"{Environment.CurrentDirectory}\Settings.json")) using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Formatting = Formatting.Indented; serializer.Serialize(writer, JSP); } this.Close(); } catch (Exception ex) { Clipboard.SetText(ex.ToString()); } }
protected void Clear_Click(object sender, EventArgs e) { CategoryList.ClearSelection(); CategoryProductList.DataSource = null; CategoryProductList.DataBind(); }
private void SelectedComboBox() { CategoryItem = CategoryList.FirstOrDefault(v => v.Id == MemoItem.CategoryId); }