Solved

Store meta data from .dbml table in a dictionary variable.

Posted on 2014-11-15
3
140 Views
Last Modified: 2014-12-09
In the attached .dbml file I have one table.

Question: How can I store the field names in a dictionary<string, bool> variable to store filed name, false (default)?
dbml file
0
Comment
Question by:Mike Eghtebas
  • 2
3 Comments
 
LVL 33

Expert Comment

by:it_saige
ID: 40445204
Okay so, I am going to introduce a couple of concepts to you.  The first is Reflection, the second is Polymorphism and the third is Extension methods.
Reflection provides objects (of type Type) that describe assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them.

Source

So how does reflection help us?

Simple -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace EE_Q28562832
{
	class Searcher
	{
		public string First_Name { get; set; }
		public string Last_Name { get; set; }
		public string Address { get; set; }
		public string City { get; set; }
		public string Zip_Code { get; set; }
		public string Phone { get; set; }
		public string Email { get; set; }
		public string Order_Date { get; set; }
		public string Title { get; set; }
		public string UnitPrice { get; set; }
		public string Quantity { get; set; }

		public static Dictionary<string, bool> ToDictionary()
		{
			return (from PropertyInfo prop in typeof(Searcher).GetProperties() select new KeyValuePair<string, bool>(prop.Name, false)).ToDictionary(x => x.Key, y => y.Value, StringComparer.OrdinalIgnoreCase);
		}
	}

	class Program
	{

		static void Main(string[] args)
		{
			Dictionary<string, bool> dict = Searcher.ToDictionary();
			foreach (KeyValuePair<string, bool> property in dict)
				Console.WriteLine(string.Format("Property: Key = {0}; Value = {1}", property.Key, property.Value));

			Console.ReadLine();
		}
	}
}

Open in new window


Produces the following output -Capture.JPG
But we can make it better by adding in polymorphism and extension methods.  What is polymorphism?
Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance. Polymorphism is a Greek word that means "many-shaped" and it has two distinct aspects:
      •  At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.
      •  Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.

Source

More specifically Interface-Based Polymorphism

Using interface-based polymorphism, we can create an interface that will be used to identify *any* class that you want to retrieve the properties of and place them into a dictionary.

Why is this important to us?  Because extension methods (like any other method, class, etc.) allow for us to constrain the type that can call it.  This is important because maybe we don't want to be able to make all classes into dictionaries, it also allows for us to group the classes that we do wish to get dictionaries for together.  So how do we do this, like such -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace EE_Q28562832
{
	class Searcher : IDynamicDictionary
	{
		public string First_Name { get; set; }
		public string Last_Name { get; set; }
		public string Address { get; set; }
		public string City { get; set; }
		public string Zip_Code { get; set; }
		public string Phone { get; set; }
		public string Email { get; set; }
		public string Order_Date { get; set; }
		public string Title { get; set; }
		public string UnitPrice { get; set; }
		public string Quantity { get; set; }
	}

	class Program
	{

		static void Main(string[] args)
		{
			var dict = new Searcher().ToDynamicDictionary();
			foreach (KeyValuePair<string, bool> property in dict)
				Console.WriteLine(string.Format("Property: Key = {0}; Value = {1}", property.Key, property.Value));

			Console.ReadLine();
		}
	}

	interface IDynamicDictionary { }

	static class Extensions
	{
		public static Dictionary<string, bool> ToDynamicDictionary<T>(this T data) where T : IDynamicDictionary
		{
			return (from PropertyInfo prop in typeof(T).GetProperties() select new KeyValuePair<string, bool>(prop.Name, false)).ToDictionary(x => x.Key, y => y.Value, StringComparer.OrdinalIgnoreCase);
		}
	}
}

Open in new window


Produces the following output -Capture.JPG
-saige-
0
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 40445209
But wait there is more.  If you have a property that you do not wish to place in your dictionary, you only need to add the attribute [Browsable(false)] to it and then we can modify the extension method to look for instances that the property IsBrowsable -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace EE_Q28562832
{
	class Searcher : IDynamicDictionary
	{
		public string First_Name { get; set; }
		public string Last_Name { get; set; }
		[Browsable(false)]
		public string Address { get; set; }
		[Browsable(false)]
		public string City { get; set; }
		[Browsable(false)]
		public string Zip_Code { get; set; }
		[Browsable(false)]
		public string Phone { get; set; }
		public string Email { get; set; }
		public string Order_Date { get; set; }
		public string Title { get; set; }
		public string UnitPrice { get; set; }
		public string Quantity { get; set; }
	}

	class Program
	{

		static void Main(string[] args)
		{
			var dict = new Searcher().ToDynamicDictionary();
			foreach (KeyValuePair<string, bool> property in dict)
				Console.WriteLine(string.Format("Property: Key = {0}; Value = {1}", property.Key, property.Value));

			Console.ReadLine();
		}
	}

	interface IDynamicDictionary { }

	static class Extensions
	{
		public static Dictionary<string, bool> ToDynamicDictionary<T>(this T data) where T : IDynamicDictionary
		{
			return (from PropertyInfo prop in typeof(T).GetProperties() 
				   where prop.IsBrowsable()
				   select new KeyValuePair<string, bool>(prop.Name, false)).ToDictionary(x => x.Key, y => y.Value, StringComparer.OrdinalIgnoreCase);
		}

		private static bool IsBrowsable(this PropertyInfo property)
		{
			bool res = true;
			foreach (object att_loopVariable in property.GetCustomAttributes(true))
			{
				if (att_loopVariable is BrowsableAttribute)
					if (!((BrowsableAttribute)att_loopVariable as BrowsableAttribute).Browsable)
						res = false;
			}
			return res;
		}
	}
}

Open in new window


Now produces the following output -Capture.JPG
-saige-
0
 
LVL 34

Author Comment

by:Mike Eghtebas
ID: 40445219
Hi Saige,

I just got back from gym, after 10 hours of work/study today. Here I found lots of gifts from you that will take me some time to digest.

I kindly appreciate the help.

Mike
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SqlDataBase 7 54
Graphics 2 32
Moving code from one TFS branch to another 3 33
how to double quote a string for an inline sql statement. 8 73
Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question