?
Solved

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

Posted on 2014-11-15
3
Medium Priority
?
174 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 2000 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: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Suggested Courses
Course of the Month7 days, 21 hours left to enroll

765 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