Solved

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

Posted on 2014-11-15
3
158 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 34

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 34

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: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
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!
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

726 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