protected override void InternalInitialize() { DataSourceAttribute dataSourceAttr = Info.GetCustomAttribute <DataSourceAttribute>(); Type dataSourceType = dataSourceAttr?.Type; if (dataSourceType != null) { // Используя сервис локатор, запросим у Prism ObjectListViewModel<>, которая // реализует IObjectsEnumerable предоставляя доступ к коллекции объектов ObjectViewModelBase<>. IObjectsEnumerable dataSource = ServiceLocator.Current.GetService(dataSourceType) as IObjectsEnumerable; // Получим неизменяемую коллекцию элементов IRealKeyViewModel. comboBox.ItemsSource = dataSource.Items.Cast <IRealKeyViewModel>().ToArray(); // Используя PropertyInfo получим значения свойства. // Так как это произвольный класс, он должен быть наследником ObjectViewModelBase<>, // который реализует IRealKeyViewModel. Используя данный интерфейс получим ключ доменного объекта. long realKey = ((IRealKeyViewModel)Info.GetValue(viewModel)).RealKey; // По ключу доменного объекта найдем оборачивающую его модель представления. IRealKeyViewModel obj = comboBox.ItemsSource.Cast <IRealKeyViewModel>().SingleOrDefault(v => v.RealKey == realKey); // Если это не создание нового. if (obj != null) { comboBox.SelectedItem = obj; } } }
private void AddDataSourceImage(Type type) { DataSourceAttribute attribute = (DataSourceAttribute)Attribute.GetCustomAttribute(type, typeof(DataSourceAttribute)); if (attribute?.IconResourceName != null && !connectionImageList.Images.ContainsKey(type.FullName)) { connectionImageList.Images.Add(type.FullName, attribute.GetIcon(type.Assembly)); } }
public void GetConstructorArguments_Null_ReturnsEmptyParameters() { var attr = new DataSourceAttribute(); var args = attr.GetConstructorArguments(); Assert.That(args, Is.Not.Null); Assert.That(args.Any(), Is.False); }
public void Add(DataSourceAttribute dataSource) { try { _testRows.AddRange(dataSource.DataRows); } catch (Exception ex) { _errorReason = ex.ToString(); } }
public void GetConstructorArguments_WhenCalled_NamedParametersAreCreated() { var attr = new DataSourceAttribute(); attr.ConstructorArugments = new object[] { "a", 1, "b", "2" }; var args = attr.GetConstructorArguments(); Assert.That(args.GetParameter <int>("a"), Is.EqualTo(1)); Assert.That(args["b"], Is.EqualTo("2")); }
public void JustTheAttribute() { var dsa = new DataSourceAttribute("System.Data.SqlClient", string.Format("Data Source=.\\SQLEXPRESS;" + @"AttachDBFilename=|DataDirectory|\csUnitTestData.mdf;" + "Integrated Security=True;Connect Timeout=30;User Instance=True"), "DivisionTests"); var rows = dsa.DataRows; Assert.Contains(new DataRow(4, 2, 2), rows, "Note: SQL Server (Express) database needed to pass"); Assert.Contains(new DataRow(10, 5, 2), rows); Assert.Contains(new DataRow(9, 3, 3), rows); Assert.Equals(3, rows.GetLength(0)); }
public Microsoft.VisualStudio.TestTools.UnitTesting.DataSourceAttribute GetTestDataSource(string dataSourceSettingName) { Microsoft.VisualStudio.TestTools.UnitTesting.DataSourceElement element = null; DataSourceAttribute dataSourceAttribute = null; TestConfigurationSection configurationSection = GetTestConfigurationSection(); element = configurationSection.DataSources[dataSourceSettingName]; if (element != null) { System.Configuration.ConnectionStringSettings connectionString = GetConnectionString(element.ConnectionString); dataSourceAttribute = new DataSourceAttribute(connectionString.ProviderName, connectionString.ConnectionString, element.DataTableName, (DataAccessMethod)Enum.Parse(typeof(DataAccessMethod), element.DataAccessMethod)); } return(dataSourceAttribute); }
private CustomDataSourceReference( Type type, CustomDataSourceAttribute metadata, DataSourceAttribute dataSource) : base(type) { Debug.Assert(metadata != null); Debug.Assert(dataSource != null); Debug.Assert(metadata.Equals(type.GetCustomAttribute <CustomDataSourceAttribute>())); Debug.Assert(dataSource.Equals(type.GetCustomAttribute <DataSourceAttribute>())); this.Guid = metadata.Guid; this.Name = metadata.Name; this.Description = metadata.Description; this.DataSource = dataSource; this.CommandLineOptions = this.Instance.CommandLineOptions.ToList().AsReadOnly(); }
private void ConnectionContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) { try { BindableTreeNode connectionNode = ClientUtility.GetContextMenuTreeviewNode(dataSourceTreeView, sender); Type connectionType = connectionNode.DataSource.GetType(); ConnectionAttribute connectionAttribute = (ConnectionAttribute)Attribute.GetCustomAttribute(connectionType, typeof(ConnectionAttribute)); IConnection connection = (IConnection)connectionNode.DataSource; testConnectionToolStripMenuItem.Visible = connection is IAvailableProvider; openConnectionInBrowserToolStripMenuItem.Visible = connection is IUrlAddressable; openConnectionInBrowserToolStripMenuItem.Enabled = connection is IUrlAddressable && ((IUrlAddressable)connection).Url != default(Uri); testOpenToolStripSeparator.Visible = connection is IAvailableProvider || connection is IUrlAddressable; ConnectionCache cache = new ConnectionCache((IConnection)connectionNode.DataSource); clearCacheToolStripMenuItem.Enabled = cache.Count > 0; addDataSourceToolStripMenuItem.DropDownItems.Clear(); List <Type> dataSourceTypes = CoreUtility.GetInterfaceImplementorsWithAttribute(typeof(IDataSource), typeof(DataSourceAttribute)); foreach (Type dataSourceType in dataSourceTypes) { DataSourceAttribute dataSourceAttribute = (DataSourceAttribute)Attribute.GetCustomAttribute(dataSourceType, typeof(DataSourceAttribute)); if (connectionType == dataSourceAttribute.ConnectionType || connectionType.IsSubclassOf(dataSourceAttribute.ConnectionType)) { ToolStripMenuItem dataSourceToolStripMenuItem = new ToolStripMenuItem() { ImageScaling = ToolStripItemImageScaling.None, Tag = dataSourceType }; dataSourceToolStripMenuItem.Click += AddDataSourceToolStripMenuItem_Click; dataSourceToolStripMenuItem.Text = dataSourceAttribute.DisplayName; dataSourceToolStripMenuItem.ToolTipText = dataSourceAttribute.Description; dataSourceToolStripMenuItem.Image = dataSourceAttribute.GetIcon(dataSourceType.Assembly); addDataSourceToolStripMenuItem.DropDownItems.Add(dataSourceToolStripMenuItem); } } addDataSourceToolStripMenuItem.Enabled = addDataSourceToolStripMenuItem.DropDownItems.Count > 0; } catch (Exception ex) { ApplicationState.Default.RaiseNotification(new NotificationEventArgs(NotificationType.Error, ex.Message, ex)); } }
public static IEfRepositoryFactory GetEfRepositoryFactory(Type entityType) { string dataSourceName = _dataAccessList.GetOrAdd(entityType.AssemblyQualifiedName, (key) => { DataSourceAttribute da = entityType.GetCustomAttribute <DataSourceAttribute>(); string name = null; if (da != null && !string.IsNullOrEmpty(da.Name)) { name = da.Name; } if (name == null) { throw new DataAccessException("该接口未标识为数据访问类型"); } return(name); }); return(GetEfRepositoryFactory(dataSourceName)); }
static void Main(string[] args) { XmlDocument doc = new XmlDocument(); XmlElement projectElement = doc.CreateElement("ProjectSchemaDefinitions", xmlns); List <string> categories = new List <string>(); doc.AppendChild(projectElement); // These attributes are probably common to all property schemas in Visual Studio. projectElement.SetAttribute("xmlns", "clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework"); projectElement.SetAttribute("xmlns:x", "http://schemas.microsoft.com/winfx/2006/xaml"); projectElement.SetAttribute("xmlns:sys", "clr-namespace:System;assembly=mscorlib"); projectElement.SetAttribute("xmlns:transformCallback", "Microsoft.Cpp.Dev10.ConvertPropertyCallback"); XmlElement ruleElement = (XmlElement)projectElement.AppendChild(doc.CreateElement("Rule", xmlns)); ruleElement.AppendChild(doc.CreateComment("This file is generated! Modify with caution!")); RuleAttribute ruleAttr = (RuleAttribute)Attribute.GetCustomAttribute(typeof(Clang), typeof(RuleAttribute)); if (ruleAttr == null) { throw new InvalidOperationException("Class requires Rule attribute!"); } PropsToXmlAttr(doc, ruleAttr, ruleElement); DataSourceAttribute dataAttr = (DataSourceAttribute)Attribute.GetCustomAttribute(typeof(Clang), typeof(DataSourceAttribute)); if (dataAttr == null) { throw new InvalidOperationException("Class requires DataSource attribute!"); } AttrToSubElem(doc, dataAttr, ruleElement, "DataSource"); XmlElement catsElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("Rule.Categories", xmlns)); PropertyCategoryAttribute[] allAttributes = (PropertyCategoryAttribute[])Attribute.GetCustomAttributes(typeof(Clang), typeof(PropertyCategoryAttribute)); allAttributes = allAttributes.OrderBy(x => x.Order).ToArray(); Dictionary <string, PropertyCategoryAttribute> categoryMap = allAttributes.ToDictionary(x => x.Name); MemberInfo[] members = typeof(Clang).GetMembers(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance); foreach (PropertyCategoryAttribute catAttr in allAttributes) { XmlElement catElement = (XmlElement)catsElement.AppendChild(doc.CreateElement("Category", xmlns)); PropsToXmlAttr(doc, catAttr, catElement); } foreach (MemberInfo member in members) { PropertyPageAttribute[] attrs = (PropertyPageAttribute[])Attribute.GetCustomAttributes(member, typeof(PropertyPageAttribute)); foreach (PropertyPageAttribute attr in attrs) { Console.WriteLine("Member name: {0}", member.Name); if (attr.Category != null && attr.Category != "") { PropertyCategoryAttribute req; if (!categoryMap.TryGetValue(attr.Category, out req)) { Console.WriteLine("Category not found: {0}", attr.Category); } } } XmlElement curElement = null; switch (member.MemberType) { case MemberTypes.Property: PropertyInfo pInfo = (PropertyInfo)member; PropertyPageAttribute propAttr = (PropertyPageAttribute)Attribute.GetCustomAttribute(member, typeof(PropertyPageAttribute)); // Untracked parameter. if (propAttr == null) { continue; } if (pInfo.PropertyType.IsSubclassOf(typeof(Enum))) { Console.WriteLine("Warning: Enumerations are invalid types because VisualStudio isn't that smart. You'll have to make it a string and back it with an enum."); continue; } else if (pInfo.PropertyType.IsAssignableFrom(typeof(ITaskItem[]))) { curElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("StringListProperty", xmlns)); PropsToXmlAttr(doc, propAttr, curElement).SetAttribute("Name", member.Name); } else if (pInfo.PropertyType.IsAssignableFrom(typeof(String))) { EnumeratedValueAttribute enumAttr = (EnumeratedValueAttribute)Attribute.GetCustomAttribute(member, typeof(EnumeratedValueAttribute)); if (enumAttr != null) { curElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("EnumProperty", xmlns)); PropsToXmlAttr(doc, propAttr, curElement).SetAttribute("Name", member.Name); int foundAttr = 0; FieldInfo[] fields = enumAttr.Enumeration.GetFields(BindingFlags.Public | BindingFlags.Static); foreach (FieldInfo field in fields) { FieldAttribute attr = (FieldAttribute)field.GetCustomAttribute(typeof(FieldAttribute)); if (attr != null) { foundAttr++; PropsToXmlAttr(doc, attr, (XmlElement)curElement.AppendChild(doc.CreateElement("EnumValue", xmlns))).SetAttribute("Name", field.Name); } } if (foundAttr > 0 && foundAttr != fields.Length) { Console.WriteLine("Not all fields in {0} have attributes", pInfo.Name); } } else { curElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("StringProperty", xmlns)); PropsToXmlAttr(doc, propAttr, curElement).SetAttribute("Name", member.Name); } } else if (pInfo.PropertyType.IsAssignableFrom(typeof(String[]))) { curElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("StringListProperty", xmlns)); PropsToXmlAttr(doc, propAttr, curElement).SetAttribute("Name", member.Name); } else if (pInfo.PropertyType.IsAssignableFrom(typeof(Boolean))) { curElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("BoolProperty", xmlns)); PropsToXmlAttr(doc, propAttr, curElement).SetAttribute("Name", member.Name); } else if (pInfo.PropertyType.IsAssignableFrom(typeof(int))) { curElement = (XmlElement)ruleElement.AppendChild(doc.CreateElement("IntProperty", xmlns)); PropsToXmlAttr(doc, propAttr, curElement).SetAttribute("Name", member.Name); } break; // Fields are not exposed, only property accessors. case MemberTypes.Field: break; default: break; } if (curElement != null) { DataSourceAttribute dataSrcAttr = (DataSourceAttribute)Attribute.GetCustomAttribute(member, typeof(DataSourceAttribute)); if (dataSrcAttr != null) { AttrToSubElem(doc, dataSrcAttr, curElement, "DataSource"); } } } IEnumerable <Attribute> additionalAttrs = Attribute.GetCustomAttributes(typeof(Clang), typeof(ItemTypeAttribute)); additionalAttrs = additionalAttrs.Concat(Attribute.GetCustomAttributes(typeof(Clang), typeof(FileExtensionAttribute))); additionalAttrs = additionalAttrs.Concat(Attribute.GetCustomAttributes(typeof(Clang), typeof(ContentTypeAttribute))); foreach (Attribute additionalAttr in additionalAttrs) { string attrName = additionalAttr.GetType().Name; attrName = attrName.Substring(0, attrName.Length - "Attribute".Length); // So lollers. C# is great. PropsToXmlAttr(doc, additionalAttr, (XmlElement)projectElement.AppendChild(doc.CreateElement(attrName, xmlns))); } FileStream fs = new FileStream(@"..\..\sbclang.xml", FileMode.Create); XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.NewLineOnAttributes = true; xmlSettings.Indent = true; xmlSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates; XmlWriter writer = XmlWriter.Create(fs, xmlSettings); doc.Save(writer); Console.WriteLine("All done! Press any key to exit."); Console.ReadKey(); }
public void XmlDataSourceWithNullValue() { var attr = new DataSourceAttribute((string)null); Assert.Equals(new DataRow[] { }, attr.DataRows); }