public void Properties() { string name = "category1"; CategoryData c = new CategoryData(); c.Name = name; Assert.AreEqual(name, c.Name); DestinationData dest1 = new DestinationData(); dest1.Name = "dest1"; dest1.Sink = "sink1"; DestinationData dest2 = new DestinationData(); dest2.Name = "dest2"; dest2.Sink = "sink2"; // DestinationDataCollection destinations = new DestinationDataCollection(); // destinations.Add(dest1); // destinations.Add(dest2); c.DestinationDataCollection.Add(dest1); c.DestinationDataCollection.Add(dest2); Assert.AreEqual(2, c.DestinationDataCollection.Count); Assert.AreEqual("dest1", c.DestinationDataCollection["dest1"].Name); Assert.AreEqual("dest2", c.DestinationDataCollection["dest2"].Name); }
/// <summary> /// Initializes a new instance of the <see cref="Category"/> class. /// </summary> /// <param name="client"><see cref="T:TcmCoreService.Client" /></param> /// <param name="folderData"><see cref="T:Tridion.ContentManager.CoreService.Client.CategoryData" /></param> protected Category(Client client, CategoryData categoryData) : base(client, categoryData) { if (categoryData == null) throw new ArgumentNullException("categoryData"); mCategoryData = categoryData; }
/// <summary> /// sets the depth for a 3d graph category /// </summary> /// <param name="category"></param> /// <param name="depth"></param> public void Set3DCategoryDepth(string category, double depth) { if (mData.ContainsKey(category) == false) { Debug.LogWarning("Invalid category name. Make sure the category is present in the chart"); return; } if (depth < 0) { depth = 0f; } CategoryData data = (CategoryData)mData[category]; data.Depth = depth; RaiseDataChanged(); }
public void CategoriesDataTest() { CategoryDataCollection data = new CategoryDataCollection(); CategoryData categoryData = new CategoryData(); categoryData.Name = "Test"; data.Add(categoryData); CategoryCollectionNode node = new CategoryCollectionNode(data); GeneratedApplicationNode.Nodes.Add(node); CategoryDataCollection nodeData = node.CategoryDataCollection; Assert.AreEqual(1, nodeData.Count); Assert.AreEqual(categoryData.Name, nodeData[categoryData.Name].Name); }
public async Task <IActionResult> Add([FromBody] CategoryData categoryData) { if (ModelState.IsValid) { Category category = categoryData.Category; category.CreatedAt = DateTime.Now; category.UpdateAt = DateTime.Now; _catgoryRepo.AddCatagory(category); await _catgoryRepo.SaveAll(); return(Ok(category)); } return(BadRequest(ModelState)); }
public IActionResult Edit(int?id) { List <CategoryLanguage> categoryLanguages = _baselDb.Categories .SelectMany(x => x.CategoryLanguages) .Include(x => x.Category) .Where(x => x.CategoryId == id) .ToList(); CategoryData categoryData = new CategoryData() { CategoryLanguages = categoryLanguages, CategoryModel = new CategoryModel() }; return(View(categoryData)); }
private static Boolean IsParentInChildren(CategoryData catData, int parentItemId) { foreach (var ch in catData.GetDirectChildren()) { if (ch.ItemID == parentItemId) { return(true); } var catChildData = CategoryUtils.GetCategoryData(ch.ItemID, StoreSettings.Current.EditLanguage); if (IsParentInChildren(catChildData, parentItemId)) { return(true); } } return(false); }
protected virtual void OnButton1Clicked(object sender, System.EventArgs e) { // Create a new CategoryData node CategoryData cat = new CategoryData (); // set the label (only label for now) cat.Label = this.categoryName.Text; // set any other data requried cat.provider = providerNode.provider; // Add the child and trigger the updates providerNode.AddChild (cat); this.Destroy (); }
internal BlackboardSectionController(GraphData graphData, BlackboardSectionViewModel sectionViewModel, GraphDataStore dataStore) : base(graphData, sectionViewModel, dataStore) { m_BlackboardSectionView = new SGBlackboardSection(sectionViewModel); blackboard = sectionViewModel.parentView as SGBlackboard; if (blackboard == null) { return; } blackboard.Add(m_BlackboardSectionView); // These make sure that the drag indicators are disabled whenever a drag action is cancelled without completing a drop blackboard.RegisterCallback <MouseUpEvent>(evt => { m_BlackboardSectionView.OnDragActionCanceled(); }); blackboard.hideDragIndicatorAction += m_BlackboardSectionView.OnDragActionCanceled; // Go through categories in Data Store foreach (var categoryData in graphData.categories) { // If category can be found with matching guid for this section // And that category contains this input if (categoryData.categoryGuid == ViewModel.associatedCategoryGuid) { m_CategoryDataReference = categoryData; break; } } foreach (var shaderInput in graphData.properties) { if (IsInputInSection(shaderInput)) { InsertBlackboardRow(shaderInput); } } foreach (var shaderInput in graphData.keywords) { if (IsInputInSection(shaderInput)) { InsertBlackboardRow(shaderInput); } } }
public int AddCategory(CategoryData data) { try { category p = new category(); p.categoryname = data.categoryname; p.editdate = DateTime.Now; p.description = data.description; p.editor = "admin"; _repository.Insert(p); return(p.id); } catch (Exception) { return(-1); } }
private void categoryCursor() { for (int i = 0; i < MyCategories.Length; i++) { CategoryData cs = MyCategories[i]; var Title = cs.category_name; var id = cs.category_id; var er = ""; items.Add(new CategoryData() { category_name = Title, category_id = id, error = er }); } listData.Adapter = MyAdapter = new CategoryAdapter(this, items); }
public ActionResult Index(string searchString, int page = 1, int pageSize = 2) { var cate = new CategoryData().ListAll(); int i = 0; foreach (var item in cate) { item.DisplayOrder = i; new CategoryData().UpdateOrder(item); i++; } var data = new CategoryData(); var model = data.ListAllCategory(searchString, page, pageSize); ViewBag.SearchString = searchString; return(View(model)); }
/// <summary> /// Get a random available skin in _subCategoryDataSkin. (null if there is none) /// </summary> /// <param name="_skin"></param> /// <returns></returns> public SubCategorySkinData GetSubCategoryDataSkin(Skin _skin) { for (int i = 0; i < shopData.categories.Count; i++) { CategoryData category = shopData.categories[i]; for (int j = 0; j < category.subCategories.Count; j++) { SubCategoryData subCategory = category.subCategories[j]; if (subCategory is SubCategorySkinData subCategoryDataSkin && subCategoryDataSkin.skins.Contains(_skin)) { return(subCategoryDataSkin); } } } return(null); }
/// <summary> /// Distribute a new log message to one or more destination sinks. /// Routing is based on the category. /// </summary> /// <param name="log">Log message.</param> public void ProcessLog(LogEntry log) { try { CategoryData category = GetCategory(log); if (category == null) { return; } DistributeLogEntry(log, category); } catch (Exception ex) { this.events.LogProcessLogException(log, ex); throw; } }
private async Task <ResponseNestedCategory> ReverseCategoryListRecursive(CategoryData mainCategoryData) { var subCategory = await _categoryRepository.GetNestedByParentId(mainCategoryData.Id); int productCount = await _productRepository.GetCountByCategoryId(mainCategoryData.Id); var subCategoryList = subCategory.Select(cat => ReverseCategoryListRecursive(cat).Result).ToList(); return(new ResponseNestedCategory { Id = mainCategoryData.Id, Name = mainCategoryData.Name, Href = mainCategoryData.Url, ProductsCount = productCount.ToString(), SubCategories = subCategoryList }); }
public void Init(CategoryData data) { notFoundTransform.gameObject.SetActive(false); existingTransform.gameObject.SetActive(false); _isEmpty = data.IsEmpty; numberOfPlace = data.NumberOfPlace; if (!_isEmpty) { category.text = data.Name; sum.text = GetSumByCategory(category.text).ToString(); existingTransform.gameObject.SetActive(true); } else { notFoundTransform.gameObject.SetActive(true); } }
public async Task <IActionResult> OnPostAsync(int?id) { if (id == null) { return(NotFound()); } CategoryData = await _context.CategoryData.FindAsync(id); if (CategoryData != null) { _context.CategoryData.Remove(CategoryData); await _context.SaveChangesAsync(); } return(RedirectToPage("./Index")); }
public CategoryData SelectCategoryById(int Id) { string query = "SELECT * FROM Categories where id = @p1"; komanda = new SqlCommand(query, savienojums); komanda.Parameters.Add("@p1", SqlDbType.Int).Value = Id; SqlDataReader reader = komanda.ExecuteReader(); reader.Read(); CategoryData category = new CategoryData(); category.Id = Convert.ToInt32(reader["Id"]); category.Title = Convert.ToString(reader["Title"]); reader.Close(); return(category); }
protected void CopyButton_Click(object obj, EventArgs args) { if (CurrentProject != null) { int selectedProjectId = Convert.ToInt32(ProjectList.SelectedValue); List <Category> newCategories = Category.GetCategoriesByProjectId(selectedProjectId); foreach (Category cat in newCategories) { Category newCat = new Category(cat.Abbreviation, cat.EstimateDuration, cat.Name, CurrentProject.Id); newCat.Save(); } CategoryData.DataBind(); ListAllCategories.DataBind(); } }
public async Task RemoveByIdTest() { var id = Guid.NewGuid(); var category = CategoryData.CreateCategory(id); await CommitCreateAsync(category); var existing = await CategoryRepository.GetAsync(id); Assert.That(existing, Is.Not.Null); await CommitRemoveByIdAsync(id); var notExisting = await CategoryRepository.GetAsync(id); Assert.That(notExisting, Is.Null); }
/// <summary> /// rename a category. throws and exception on error /// </summary> /// <param name="prevName"></param> /// <param name="newName"></param> public void RenameCategory(string prevName, string newName) { if (prevName == newName) { return; } if (mData.ContainsKey(newName)) { throw new ArgumentException(String.Format("A category named {0} already exists", newName)); } CategoryData cat = (CategoryData)mData[prevName]; mData.Remove(prevName); cat.Name = newName; mData.Add(newName, cat); RaiseDataChanged(); }
public HttpResponseMessage Post([FromBody] CategoryModel Category) { HttpResponseMessage response; CategoryData data = new CategoryData(); if (ModelState.IsValid) { data.SaveCategory(Category.Category); response = Request.CreateResponse(HttpStatusCode.Created); } else { response = Request.CreateResponse(HttpStatusCode.NotFound, new { Message = "Model is invalid.", ModelValidation = "Category name must be between 2 - 64 signs. Cannot be null or empty." }); } return(response); }
public string RemoveCategoryImage(HttpContext context, string editLangCurrent) { EditLangCurrent = editLangCurrent; //get uploaded params var ajaxInfo = NBrightBuyUtils.GetAjaxFields(context); var catitemid = ajaxInfo.GetXmlPropertyInt("genxml/hidden/selectedcatid"); var catData = new CategoryData(catitemid, EditLangCurrent); if (catData.Exists) { catData.DataRecord.SetXmlProperty("genxml/hidden/imageurl", ""); catData.DataRecord.SetXmlProperty("genxml/hidden/imagepath", ""); catData.Save(); } return(CategoryAdminDetail(context, 0, EditLangCurrent)); }
/// <summary> /// Checks if there are any more of the given categorys. Only returns true if it is found higher than the CategoryData offset /// </summary> /// <param CategoryData="CatData"></param> /// <returns></returns> public bool IsAnyMoreOfCat(CategoryData CatData) { int InnerCount = 0; for (int i = 0; i < ItemStack.Count; i++) { if (ItemStack[i].Name == CatData.Name) { if (InnerCount >= CatData.Offset) { return(true); } InnerCount++; } } return(false); }
public async Task ChangeTest() { var id = Guid.NewGuid(); var category = CategoryData.CreateCategory(id); var description = "Orange"; await CommitCreateAsync(category); category.ChangeDescription(description); await CommitChangeAsync(category); var expected = category; var actual = await CategoryRepository.GetAsync(id); Assert.AreEqual(expected, actual); }
/// <summary> /// Create and initialize the shop view based on _shopData. /// This method is called automatically in the Initialize method of the Shop. /// </summary> /// <param name="_shopData"></param> public void CreateVisualShop(ShopData _shopData) { categories = new List <CategoryVisual>(); chestRoomText = chestRoomArea.GetComponentInChildren <TextMeshProUGUI>(true); comingSoonText = comingSoonArea.GetComponentInChildren <TextMeshProUGUI>(true); titleText = header.GetComponentInChildren <TextMeshProUGUI>(true); canvas = GetComponentInParent <Canvas>(); canvasGroup = GetComponent <CanvasGroup>(); camera = canvas.GetComponentInChildren <Camera>(true); shop = Shop.Instance; if (_shopData == null) { return; } if (rvButton != null) { rvButton.UpdateValue(_shopData.RVBonusCurrency, _shopData.RVBonusValue); } if (paymentPicker != null) { paymentPicker.buttonPicker.onClick.AddListener(RequestPurchase); } if (scrollRect != null) { // List<CategoryDataServer> categoryDataServers = RemoteConfigManager.Instance.List<CategoryDataServer>(); for (var i = 0; i < _shopData.categories.Count; i++) { CategoryData categoryData = _shopData.categories[i]; // CategoryDataServer categoryDataServer = categoryDataServers.Find(x => x.id == categoryData.id); // if (categoryDataServer != null) // categoryData.Initialize(categoryDataServer); CategoryVisual categoryVisual = categoryData.AddShopCategory(scrollRect, subCategoryDotZoneParent); categories.Add(categoryVisual); } } StartCoroutine(ResizeSubCategories(_shopData)); }
public async Task UpdateCategory_NewTagWithSameNameAsAutogenerated_DeletesAutogeneratedTag() { var activeTags = new List <TagData> { new TagData { Id = 1, Name = "Netflix", IsAutoGenerated = true }, new TagData { Id = 1, Name = "Disney+" } }; var existingCategory = new CategoryData { Id = 1, UserId = 1, Name = "Bills", Tags = new List <TagData> { new TagData { Id = 1, Name = "Disney+" } } }; var categoryService = CreateServiceForCategoryUpdate( out var fakeCategoryRepository, out var fakeTagRepository, existingCategory, activeTags); var newTags = new List <Tag> { new Tag { Name = "Disney+" }, new Tag { Name = "Netflix" } }; await categoryService.UpdateCategory(existingCategory.Id, existingCategory.Name, newTags); Assert.NotNull(activeTags[0].DeletedAt); }
public override void OnAfterDeserialize() { if (mSerializedData == null) { return; } mData.Clear(); mSuspendEvents = true; for (int i = 0; i < mSerializedData.Length; i++) { SerializedCategory cat = mSerializedData[i]; if (cat.Depth < 0) { cat.Depth = 0f; } string name = cat.Name; AddInnerCategoryGraph(name, cat.LinePrefab, cat.Material, cat.LineThickness, cat.LineTiling, cat.FillPrefab, cat.InnerFill, cat.StetchFill, cat.DotPrefab, cat.PointMaterial, cat.PointSize, cat.Depth, cat.IsBezierCurve, cat.SegmentsPerCurve, cat.InitialData); Set2DCategoryPrefabs(name, cat.LineHoverPrefab, cat.PointHoverPrefab); CategoryData data = (CategoryData)mData[name]; data.AllowNonFunctions = cat.AllowNonFunctionsBeta; data.ViewOrder = i; if (data.Data == null) { data.Data = new List <DoubleVector3>(); } else { data.Data.Clear(); } if (cat.InitialData != null) { SetInitialData(name, cat.InitialData, cat.IsBezierCurve); } // if (cat.data != null) // data.Data.AddRange(cat.data); data.MaxX = cat.MaxX; data.MaxY = cat.MaxY; data.MinX = cat.MinX; data.MinY = cat.MinY; data.MaxRadius = cat.MaxRadius; } mSuspendEvents = false; }
/// <summary> /// Adds a new category to the graph chart. each category corrosponds to a graph line. /// </summary> /// <param name="category"></param> /// <param name="material"></param> /// <param name="innerFill"></param> public void AddCategory(string category, Material lineMaterial, double lineThickness, MaterialTiling lineTiling, Material innerFill, bool strechFill, Material pointMaterial, double pointSize) { if (mData.ContainsKey(category)) throw new ArgumentException(String.Format("A category named {0} already exists", category)); CategoryData data = new CategoryData(); mData.Add(category, data); data.Name = category; data.LineMaterial = lineMaterial; data.LineHoverPrefab = null; data.PointHoverPrefab = null; data.FillMaterial = innerFill; data.LineThickness = lineThickness; data.LineTiling = lineTiling; data.StetchFill = strechFill; data.PointMaterial = pointMaterial; data.PointSize = pointSize; RaiseDataChanged(); }
public void SetCategoryHover(string category, ChartItemEffect lineHover, ChartItemEffect pointHover) { try { CategoryData data = mDataSource.Columns[category].UserData as CategoryData; if (data == null) { throw new Exception("category not set"); // should never happen } data.LineHover = lineHover; data.PointHover = pointHover; RaiseDataChanged(); } catch { Debug.LogWarning("Invalid category name. Make sure the category is present in the graph"); } }
public void SetCategoryInfo(string category, string title, string text, Sprite image) { if (title == null) { title = ""; } if (text == null) { text = ""; } var col = mDataSource.Columns[category]; CategoryData data = col.UserData as CategoryData; data.Text = text; data.Title = title; data.Image = image; RaisePropertyUpdated(); }
public void Set3DCategoryOrientation(string category, float seperation, float curve) { try { CategoryData data = mDataSource.Columns[category].UserData as CategoryData; if (data == null) { throw new Exception("category not set"); // should never happen } data.Seperation = seperation; data.Curve = curve; RaiseDataChanged(); } catch { Debug.LogWarning("Invalid category name. Make sure the category is present in the graph"); } }
public void DeleteCategory(object item) { if (CanDeleteCategory(null)) { bool result = false; result = CategoriesClient.DeleteCategory(SelectedCategory.ProductCategoryID); if (result) { CategoryData categoryJustDeleted = CategoryList.First(c => c.ProductCategoryID == SelectedCategory.ProductCategoryID); CategoryList.Remove(categoryJustDeleted); MessageBox.Show("Delete successful"); } else { MessageBox.Show("Delete failed"); } } }
public List<CategoryData> GetCategories() { var ctx = new ApplicationEntities(ConfigurationManager.ConnectionStrings["ApplicationConnection"].ToString()); var result = new List<CategoryData>(); var categories = ctx.Categories .Where(category => category.IsActive) .OrderBy(category => category.Name) .AsQueryable(); foreach (var category in categories) { var categoryData = new CategoryData(category); result.Add(categoryData); } ctx.Dispose(); return result; }
public void EnumeratorCurrentTest() { CategoryData catA = new CategoryData(); catA.Name = "MyName"; cats.Add(catA); CategoryData catB = new CategoryData(); catB.Name = "MyName2"; cats.Add(catB); int count = 0; foreach (CategoryData cat1 in cats) { Assert.IsNotNull(cat1); count++; foreach (CategoryData cat2 in cats) { Assert.IsNotNull(cat2); count++; } } Assert.AreEqual(6, count); }
internal unsafe SharedPerformanceCounter(string catName, string counterName, string instanceName, PerformanceCounterInstanceLifetime lifetime) { this.InitialOffset = 4; this.thisInstanceOffset = -1; this.categoryName = catName; this.categoryNameHashCode = GetWstrHashCode(this.categoryName); this.categoryData = this.GetCategoryData(); if (this.categoryData.UseUniqueSharedMemory) { if ((instanceName != null) && (instanceName.Length > 0x7f)) { throw new InvalidOperationException(SR.GetString("InstanceNameTooLong")); } } else if (lifetime != PerformanceCounterInstanceLifetime.Global) { throw new InvalidOperationException(SR.GetString("ProcessLifetimeNotValidInGlobal")); } if (((counterName != null) && (instanceName != null)) && this.categoryData.CounterNames.Contains(counterName)) { this.counterEntryPointer = this.GetCounter(counterName, instanceName, this.categoryData.EnableReuse, lifetime); } }
public static CategoryResult From(CategoryData item, ISessionAwareCoreService client, string currentUserId) { var result = new CategoryResult { Description = TextEntry.From(item.Description, Resources.LabelDescription), XmlName = TextEntry.From(item.XmlName, Resources.LabelXmlName) }; if (item.UseForNavigation == false) { result.Publishable = TextEntry.From(Resources.CannotBePublished, Resources.LabelPublishable); } if (item.UseForIdentification == true) { result.UseForIdentification = TextEntry.From(Resources.Yes, Resources.LabelUseForIdentification); } result.LinkedSchema = LinkEntry.From(item.KeywordMetadataSchema, Resources.LabelLinkedSchema, currentUserId); AddCommonProperties(item, result); AddPropertiesForRepositoryLocalObject(item, result, currentUserId); return result; }
private unsafe CategoryData GetCategoryData() { CategoryData data = (CategoryData) categoryDataTable[this.categoryName]; if (data == null) { lock (categoryDataTable) { data = (CategoryData) categoryDataTable[this.categoryName]; if (data == null) { data = new CategoryData { FileMappingName = "netfxcustomperfcounters.1.0", MutexName = this.categoryName }; new RegistryPermission(PermissionState.Unrestricted).Assert(); RegistryKey key = null; try { int fileMappingSizeFromConfig; key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\" + this.categoryName + @"\Performance"); object obj2 = key.GetValue("CategoryOptions"); if (obj2 != null) { int num = (int) obj2; data.EnableReuse = (num & 1) != 0; if ((num & 2) != 0) { data.UseUniqueSharedMemory = true; this.InitialOffset = 8; data.FileMappingName = "netfxcustomperfcounters.1.0" + this.categoryName; } } object obj3 = key.GetValue("FileMappingSize"); if ((obj3 != null) && data.UseUniqueSharedMemory) { fileMappingSizeFromConfig = (int) obj3; if (fileMappingSizeFromConfig < 0x8000) { fileMappingSizeFromConfig = 0x8000; } if (fileMappingSizeFromConfig > 0x2000000) { fileMappingSizeFromConfig = 0x2000000; } } else { fileMappingSizeFromConfig = GetFileMappingSizeFromConfig(); if (data.UseUniqueSharedMemory) { fileMappingSizeFromConfig = fileMappingSizeFromConfig >> 2; } } object obj4 = key.GetValue("Counter Names"); byte[] buffer = obj4 as byte[]; if (buffer != null) { ArrayList list = new ArrayList(); try { fixed (byte* numRef = buffer) { int startIndex = 0; for (int i = 0; i < (buffer.Length - 1); i += 2) { if (((buffer[i] == 0) && (buffer[i + 1] == 0)) && (startIndex != i)) { list.Add(new string((sbyte*) numRef, startIndex, i - startIndex, Encoding.Unicode).ToLowerInvariant()); startIndex = i + 2; } } } } finally { numRef = null; } data.CounterNames = list; } else { string[] c = (string[]) obj4; for (int j = 0; j < c.Length; j++) { c[j] = c[j].ToLowerInvariant(); } data.CounterNames = new ArrayList(c); } if (SharedUtils.CurrentEnvironment == 1) { data.FileMappingName = @"Global\" + data.FileMappingName; data.MutexName = @"Global\" + this.categoryName; } data.FileMapping = new FileMapping(data.FileMappingName, fileMappingSizeFromConfig, this.InitialOffset); categoryDataTable[this.categoryName] = data; } finally { if (key != null) { key.Close(); } CodeAccessPermission.RevertAssert(); } } } } this.baseAddress = (long) data.FileMapping.FileViewAddress; if (data.UseUniqueSharedMemory) { this.InitialOffset = 8; } return data; }
/// <summary> /// Reload the <see cref="Category" /> with the specified <see cref="T:Tridion.ContentManager.CoreService.Client.CategoryData" /> /// </summary> /// <param name="categoryData"><see cref="T:Tridion.ContentManager.CoreService.Client.CategoryData" /></param> protected void Reload(CategoryData categoryData) { if (categoryData == null) throw new ArgumentNullException("categoryData"); mCategoryData = categoryData; base.Reload(categoryData); mAllowedParentCategories = null; mKeywordMetadataSchema = null; }
private unsafe CategoryData GetCategoryData() { CategoryData data = (CategoryData) categoryDataTable[categoryName]; if (data == null) { lock(categoryDataTable) { data = (CategoryData) categoryDataTable[categoryName]; if (data == null) { data = new CategoryData(); data.FileMappingName = DefaultFileMappingName; data.MutexName = categoryName; RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted); registryPermission.Assert(); RegistryKey categoryKey = null; try { categoryKey = Registry.LocalMachine.OpenSubKey(PerformanceCounterLib.ServicePath + "\\" + categoryName + "\\Performance"); // first read the options Object optionsObject = categoryKey.GetValue("CategoryOptions"); if (optionsObject != null) { int options = (int) optionsObject; data.EnableReuse = (((PerformanceCounterCategoryOptions) options & PerformanceCounterCategoryOptions.EnableReuse) != 0); if (((PerformanceCounterCategoryOptions) options & PerformanceCounterCategoryOptions.UseUniqueSharedMemory) != 0) { data.UseUniqueSharedMemory = true; InitialOffset = 8; data.FileMappingName = DefaultFileMappingName + categoryName; } } int fileMappingSize; object fileMappingSizeObject = categoryKey.GetValue("FileMappingSize"); if (fileMappingSizeObject != null && data.UseUniqueSharedMemory) { // we only use this reg value in the unique shared memory case. fileMappingSize = (int) fileMappingSizeObject; if (fileMappingSize < MinCountersFileMappingSize) fileMappingSize = MinCountersFileMappingSize; if (fileMappingSize > MaxCountersFileMappingSize) fileMappingSize = MaxCountersFileMappingSize; } else { fileMappingSize = GetFileMappingSizeFromConfig(); if (data.UseUniqueSharedMemory) fileMappingSize = fileMappingSize >> 2; // if we have a custom filemapping, only make it 25% as large. } // now read the counter names object counterNamesObject = categoryKey.GetValue("Counter Names"); byte[] counterNamesBytes = counterNamesObject as byte[]; if (counterNamesBytes != null) { ArrayList names = new ArrayList(); fixed (byte* counterNamesPtr = counterNamesBytes) { int start = 0; for (int i=0; i<counterNamesBytes.Length-1; i+=2) { if (counterNamesBytes[i] == 0 && counterNamesBytes[i+1] == 0 && start != i) { string counter = new String((sbyte*)counterNamesPtr, start, i-start, Encoding.Unicode); names.Add(counter.ToLowerInvariant()); start = i+2; } } } data.CounterNames = names; } else { string[] counterNames = (string[]) counterNamesObject; for (int i=0; i<counterNames.Length; i++) counterNames[i] = counterNames[i].ToLowerInvariant(); data.CounterNames = new ArrayList(counterNames); } // figure out the shared memory name if (SharedUtils.CurrentEnvironment == SharedUtils.W2kEnvironment) { data.FileMappingName = "Global\\" + data.FileMappingName; data.MutexName = "Global\\" + categoryName; } data.FileMapping = new FileMapping(data.FileMappingName, fileMappingSize, InitialOffset); categoryDataTable[categoryName] = data; } finally { if (categoryKey != null) categoryKey.Close(); RegistryPermission.RevertAssert(); } } } } baseAddress = (long) data.FileMapping.FileViewAddress; if (data.UseUniqueSharedMemory) InitialOffset = 8; return data; }
internal unsafe SharedPerformanceCounter(string catName, string counterName, string instanceName, PerformanceCounterInstanceLifetime lifetime) { this.categoryName = catName; this.categoryNameHashCode = GetWstrHashCode(categoryName); categoryData = GetCategoryData(); // Check that the instance name isn't too long if we're using the new shared memory. // We allocate InstanceNameSlotSize bytes in the shared memory if (categoryData.UseUniqueSharedMemory) { if (instanceName != null && instanceName.Length > InstanceNameMaxLength) throw new InvalidOperationException(SR.GetString(SR.InstanceNameTooLong)); } else { if (lifetime != PerformanceCounterInstanceLifetime.Global) throw new InvalidOperationException(SR.GetString(SR.ProcessLifetimeNotValidInGlobal)); } if (counterName != null && instanceName != null) { if (!categoryData.CounterNames.Contains(counterName)) Debug.Assert(false, "Counter " + counterName + " does not exist in category " + catName); else this.counterEntryPointer = GetCounter(counterName, instanceName, categoryData.EnableReuse, lifetime); } }