Solved

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

Posted on 2014-11-15
3
113 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 32

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 32

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 33

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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

707 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now